@bastani/atomic 0.9.15 → 0.9.16-alpha.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 (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/README.md +8 -8
  4. package/dist/builtin/intercom/contact-supervisor-tool.ts +68 -32
  5. package/dist/builtin/intercom/index-heavy.ts +1 -0
  6. package/dist/builtin/intercom/index.ts +21 -15
  7. package/dist/builtin/intercom/intercom-tool.ts +66 -10
  8. package/dist/builtin/intercom/package.json +1 -1
  9. package/dist/builtin/intercom/parent-ask-handoff.ts +72 -0
  10. package/dist/builtin/mcp/package.json +1 -1
  11. package/dist/builtin/subagents/CHANGELOG.md +13 -0
  12. package/dist/builtin/subagents/README.md +23 -12
  13. package/dist/builtin/subagents/agents/worker.md +2 -2
  14. package/dist/builtin/subagents/package.json +1 -1
  15. package/dist/builtin/subagents/skills/subagent/SKILL.md +10 -17
  16. package/dist/builtin/subagents/src/extension/index.ts +5 -30
  17. package/dist/builtin/subagents/src/extension/notification-content.ts +1 -1
  18. package/dist/builtin/subagents/src/extension/schemas.ts +2 -14
  19. package/dist/builtin/subagents/src/extension/tool-description.ts +1 -2
  20. package/dist/builtin/subagents/src/extension/tool-rendering.ts +53 -0
  21. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +1 -1
  22. package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
  23. package/dist/builtin/subagents/src/runs/foreground/execution-parent-ask-handoff.ts +78 -0
  24. package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +7 -5
  25. package/dist/builtin/subagents/src/runs/foreground/notify.ts +5 -6
  26. package/dist/builtin/subagents/src/runs/foreground/parent-ask-output.ts +48 -0
  27. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst-display.ts +46 -0
  28. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst.ts +403 -0
  29. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +48 -9
  30. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +3 -1
  31. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-live-update.ts +11 -0
  32. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +164 -93
  33. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +36 -29
  34. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parent-ask-projection.ts +11 -0
  35. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +42 -17
  36. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +3 -121
  37. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +7 -2
  38. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +30 -220
  39. package/dist/builtin/subagents/src/runs/inprocess/control-status.ts +0 -34
  40. package/dist/builtin/subagents/src/runs/inprocess/index.ts +0 -12
  41. package/dist/builtin/subagents/src/runs/inprocess/prompt-behavior.ts +1 -1
  42. package/dist/builtin/subagents/src/runs/inprocess/runner.ts +2 -141
  43. package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +8 -0
  44. package/dist/builtin/subagents/src/shared/status-format.ts +3 -3
  45. package/dist/builtin/subagents/src/shared/types-config.ts +41 -0
  46. package/dist/builtin/subagents/src/shared/types-foreground-state.ts +7 -15
  47. package/dist/builtin/subagents/src/shared/types-results.ts +3 -1
  48. package/dist/builtin/subagents/src/shared/types-runtime.ts +1 -11
  49. package/dist/builtin/subagents/src/tui/render-progress.ts +2 -2
  50. package/dist/builtin/subagents/src/tui/render-result-compact.ts +2 -2
  51. package/dist/builtin/subagents/src/tui/render-result.ts +38 -14
  52. package/dist/builtin/subagents/src/tui/render-status-progress.ts +1 -1
  53. package/dist/builtin/web-access/package.json +1 -1
  54. package/dist/builtin/workflows/CHANGELOG.md +10 -0
  55. package/dist/builtin/workflows/README.md +1 -1
  56. package/dist/builtin/workflows/package.json +1 -1
  57. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +548 -39
  58. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +529 -65
  59. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +30 -8
  60. package/dist/builtin/workflows/src/durable/dbos-local-postgres.ts +36 -3
  61. package/dist/builtin/workflows/src/durable/local-command.ts +68 -10
  62. package/dist/builtin/workflows/src/extension/dispatcher.ts +7 -1
  63. package/dist/builtin/workflows/src/extension/extension-factory.ts +2 -2
  64. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1094 -298
  65. package/dist/builtin/workflows/src/extension/public-types.ts +2 -2
  66. package/dist/builtin/workflows/src/extension/render-result.ts +16 -2
  67. package/dist/builtin/workflows/src/extension/runtime.ts +8 -1
  68. package/dist/builtin/workflows/src/extension/workflow-request-abort.ts +15 -0
  69. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +4 -3
  70. package/dist/builtin/workflows/src/extension/workflow-tool-registration.ts +107 -13
  71. package/dist/builtin/workflows/src/extension/workflow-tool.ts +22 -12
  72. package/dist/builtin/workflows/src/tui/widget.ts +25 -6
  73. package/dist/core/event-bus.d.ts.map +1 -1
  74. package/dist/core/event-bus.js +19 -3
  75. package/dist/core/event-bus.js.map +1 -1
  76. package/docs/intercom.md +28 -26
  77. package/docs/subagents.md +15 -11
  78. package/docs/workflows.md +27 -10
  79. package/npm-shrinkwrap.json +32 -32
  80. package/package.json +3 -3
  81. package/dist/builtin/subagents/src/runs/inprocess/attempt-handles.ts +0 -104
  82. /package/dist/builtin/subagents/src/runs/foreground/{subagent-executor-resume.ts → subagent-executor-cwd.ts} +0 -0
@@ -6,10 +6,11 @@
6
6
  * (`@embedded-postgres/<platform>-<arch>`, installed as an optional dependency
7
7
  * of `embedded-postgres`). No Docker daemon or system Postgres is required.
8
8
  *
9
- * The cluster lives under `~/.atomic/postgres/v<major>` on a dedicated port and
10
- * is started with `pg_ctl`, which daemonizes the server into its own session:
11
- * it survives Atomic exiting and is shared by every concurrent Atomic session.
12
- * Atomic never stops it.
9
+ * The cluster lives under `~/.atomic/postgres/v<major>` on a dedicated port.
10
+ * Atomic starts Postgres directly and retains an opaque native process lease;
11
+ * releasing that lease does not kill the server, so it survives abrupt exits
12
+ * and can be shared by concurrent sessions. Orderly shutdown signals and waits
13
+ * on that exact retained process instance; attached clusters are untouched.
13
14
  *
14
15
  * PostgreSQL refuses to run as UID 0, so a root Atomic process (containers,
15
16
  * CI sandboxes, eval harnesses) resolves an unprivileged system account, keeps
@@ -23,18 +24,27 @@ import {
23
24
  chownSync,
24
25
  copyFileSync,
25
26
  existsSync,
27
+ lstatSync,
26
28
  mkdirSync,
29
+ readdirSync,
27
30
  readFileSync,
31
+ readlinkSync,
32
+ renameSync,
33
+ rmdirSync,
28
34
  rmSync,
29
35
  statSync,
30
36
  symlinkSync,
31
37
  writeFileSync,
32
38
  } from "node:fs";
33
- import { tmpdir } from "node:os";
39
+ import { createRequire } from "node:module";
40
+ import { tmpdir, uptime } from "node:os";
34
41
  import { dirname, join, relative } from "node:path";
42
+ import type { RetainedPostgres, RetainedPostgresSpawnOptions } from "@bastani/atomic-natives";
35
43
  import {
44
+ cleanupAbandonedRuntimeStages,
36
45
  type EmbeddedPostgresRunContext,
37
46
  prepareBinariesForOwner,
47
+ type RuntimePublicationLease,
38
48
  resolveEmbeddedRunContext,
39
49
  } from "./dbos-embedded-postgres-root.js";
40
50
  import { commandFailureDetail, delay, tcpReachable } from "./local-command.js";
@@ -47,19 +57,51 @@ const EMBEDDED_PG_MAJOR = 18;
47
57
  const READY_ATTEMPTS = 120;
48
58
  const READY_DELAY_MS = 250;
49
59
  const SETUP_LOCK_STALE_MS = 120_000;
60
+ const SHUTDOWN_TIMEOUT_MS = 60_000;
50
61
 
51
62
  export const EMBEDDED_DBOS_SYSTEM_DATABASE_URL = `postgresql://${EMBEDDED_USER}:${EMBEDDED_PASSWORD}@${EMBEDDED_HOST}:${EMBEDDED_PORT}/atomic_workflows_dbos_sys?connect_timeout=10&sslmode=disable`;
52
63
 
53
64
  interface EmbeddedPostgresBinaries {
54
65
  readonly pg_ctl: string;
55
66
  readonly initdb: string;
67
+ readonly postgres: string;
56
68
  }
57
69
 
70
+ type RetainedPostgresSpawner = (options: RetainedPostgresSpawnOptions) => RetainedPostgres;
71
+
72
+ interface ActiveEmbeddedPostgres {
73
+ readonly lease: RetainedPostgres;
74
+ stopPromise?: Promise<void>;
75
+ }
76
+
77
+ type EnsureOperation = () => Promise<void>;
78
+ type ReachabilityProbe = (host: string, port: number, timeoutMs?: number) => Promise<boolean>;
79
+ type DelayOperation = (milliseconds: number) => Promise<void>;
80
+
81
+ export class EmbeddedPostgresCleanupPendingError extends AggregateError {
82
+ constructor(errors: readonly unknown[], message: string) {
83
+ super(errors, message);
84
+ this.name = "EmbeddedPostgresCleanupPendingError";
85
+ }
86
+ }
87
+
88
+ let activeCluster: ActiveEmbeddedPostgres | undefined;
89
+ let ensureOperation: EnsureOperation = ensure;
90
+ let retainedPostgresSpawnerOverride: RetainedPostgresSpawner | undefined;
91
+
58
92
  let ensured: Promise<void> | undefined;
59
93
 
60
94
  /** Start or attach to the shared embedded DBOS Postgres exactly once per process. */
61
95
  export function ensureEmbeddedDbosPostgres(): Promise<void> {
62
- ensured ??= ensure().catch((error: unknown) => {
96
+ if (ensured === undefined && activeCluster !== undefined) {
97
+ return Promise.reject(
98
+ new EmbeddedPostgresCleanupPendingError(
99
+ [],
100
+ "Embedded Postgres startup is blocked while retained Postgres cleanup is pending; retry shutdown first.",
101
+ ),
102
+ );
103
+ }
104
+ ensured ??= ensureOperation().catch((error: unknown) => {
63
105
  ensured = undefined;
64
106
  throw error;
65
107
  });
@@ -74,26 +116,97 @@ async function ensure(): Promise<void> {
74
116
  const root = context.baseDir;
75
117
  const dataDir = join(root, `v${EMBEDDED_PG_MAJOR}`);
76
118
  const logFile = join(root, `v${EMBEDDED_PG_MAJOR}.log`);
77
- mkdirSync(root, { recursive: true, mode: 0o700 });
78
- if (context.owner !== undefined) chownSync(root, context.owner.uid, context.owner.gid);
79
- const binaries = await prepareBinariesForOwner(loaded, context);
80
-
81
- await withSetupLock(join(root, `v${EMBEDDED_PG_MAJOR}.setup-lock`), async () => {
82
- if (await tcpReachable(EMBEDDED_HOST, EMBEDDED_PORT)) return;
83
- if (!existsSync(join(dataDir, "PG_VERSION"))) await initializeCluster(binaries.initdb, dataDir, context);
84
- await startCluster(binaries.pg_ctl, dataDir, logFile, context);
85
- });
119
+ mkdirSync(root, { recursive: true, mode: context.owner === undefined ? 0o700 : 0o755 });
120
+ if (context.owner !== undefined) {
121
+ // Keep every ancestor of published runtime generations root-owned. The
122
+ // data directory itself is handed to Postgres during initialization.
123
+ chownSync(root, 0, 0);
124
+ chmodSync(root, 0o755);
125
+ }
126
+ let startedCluster: ActiveEmbeddedPostgres | undefined;
127
+ try {
128
+ await withSetupLock(join(root, `v${EMBEDDED_PG_MAJOR}.setup-lock`), async (setup) => {
129
+ await cleanupAbandonedRuntimeStages(root, setup.abandonedRuntimeStageOwnerTokens);
130
+ if (await tcpReachable(EMBEDDED_HOST, EMBEDDED_PORT)) return;
131
+ const binaries = await prepareBinariesForOwner(loaded, context, undefined, {
132
+ publicationLease: setup.runtimePublicationLease,
133
+ });
134
+ if (!existsSync(join(dataDir, "PG_VERSION"))) await initializeCluster(binaries.initdb, dataDir, context);
135
+ const lease = await startCluster(binaries.postgres, dataDir, logFile, context);
136
+ if (lease !== undefined) {
137
+ startedCluster = { lease };
138
+ activeCluster = startedCluster;
139
+ }
140
+ });
141
+ } catch (startupError) {
142
+ await rollbackStartedCluster(startedCluster, startupError);
143
+ }
144
+ await waitForClusterReadiness(logFile, startedCluster);
145
+ }
86
146
 
87
- for (let attempt = 0; attempt < READY_ATTEMPTS; attempt += 1) {
88
- if (await tcpReachable(EMBEDDED_HOST, EMBEDDED_PORT)) return;
89
- await delay(READY_DELAY_MS);
147
+ async function rollbackStartedCluster(
148
+ cluster: ActiveEmbeddedPostgres | undefined,
149
+ startupError: unknown,
150
+ ): Promise<never> {
151
+ if (cluster !== undefined && activeCluster === cluster) {
152
+ try {
153
+ await shutdownEmbeddedDbosPostgres();
154
+ } catch (cleanupError) {
155
+ throw new EmbeddedPostgresCleanupPendingError(
156
+ [startupError, cleanupError],
157
+ "Embedded Postgres startup failed and its retained process could not be stopped.",
158
+ );
159
+ }
160
+ }
161
+ throw startupError;
162
+ }
163
+ async function waitForClusterReadiness(
164
+ logFile: string,
165
+ rollbackCluster: ActiveEmbeddedPostgres | undefined,
166
+ isReachable: ReachabilityProbe = tcpReachable,
167
+ attempts = READY_ATTEMPTS,
168
+ wait: DelayOperation = delay,
169
+ ): Promise<void> {
170
+ try {
171
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
172
+ if (await isReachable(EMBEDDED_HOST, EMBEDDED_PORT)) return;
173
+ await wait(READY_DELAY_MS);
174
+ }
175
+ throw new Error(
176
+ `Embedded Postgres started but never accepted connections on ${EMBEDDED_HOST}:${EMBEDDED_PORT}; see ${logFile}.`,
177
+ );
178
+ } catch (startupError) {
179
+ await rollbackStartedCluster(rollbackCluster, startupError);
180
+ }
181
+ }
182
+
183
+ /** Stop only the exact native process lease started by this Atomic process. */
184
+ export function shutdownEmbeddedDbosPostgres(): Promise<void> {
185
+ const cluster = activeCluster;
186
+ if (cluster === undefined) return Promise.resolve();
187
+ cluster.stopPromise ??= stopActiveCluster(cluster);
188
+ return cluster.stopPromise;
189
+ }
190
+
191
+ async function stopActiveCluster(cluster: ActiveEmbeddedPostgres): Promise<void> {
192
+ try {
193
+ await cluster.lease.interruptAndWait(SHUTDOWN_TIMEOUT_MS);
194
+ cluster.lease.release();
195
+ if (activeCluster === cluster) activeCluster = undefined;
196
+ } catch (error) {
197
+ // Timeout or signaling failure retains this exact native lease so a later
198
+ // orderly-shutdown attempt can retry without reconstructing ownership.
199
+ cluster.stopPromise = undefined;
200
+ throw error;
90
201
  }
91
- throw new Error(
92
- `Embedded Postgres started but never accepted connections on ${EMBEDDED_HOST}:${EMBEDDED_PORT}; see ${logFile}.`,
93
- );
94
202
  }
95
203
 
96
204
  async function initializeCluster(initdb: string, dataDir: string, context: EmbeddedPostgresRunContext): Promise<void> {
205
+ if (context.owner !== undefined) {
206
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
207
+ chownSync(dataDir, context.owner.uid, context.owner.gid);
208
+ chmodSync(dataDir, 0o700);
209
+ }
97
210
  const passwordFile = join(tmpdir(), `atomic-pg-pw-${process.pid}-${crypto.randomUUID().slice(0, 8)}`);
98
211
  writeFileSync(passwordFile, `${EMBEDDED_PASSWORD}\n`, { mode: 0o600 });
99
212
  try {
@@ -119,28 +232,35 @@ async function initializeCluster(initdb: string, dataDir: string, context: Embed
119
232
  }
120
233
 
121
234
  async function startCluster(
122
- pgCtl: string,
235
+ postgres: string,
123
236
  dataDir: string,
124
237
  logFile: string,
125
238
  context: EmbeddedPostgresRunContext,
126
- ): Promise<void> {
127
- const result = await context.runAsOwner(pgCtl, [
128
- "-D",
129
- dataDir,
130
- "-l",
131
- logFile,
132
- "-o",
133
- `-p ${EMBEDDED_PORT} -c listen_addresses=${EMBEDDED_HOST}`,
134
- "-w",
135
- "-t",
136
- "60",
137
- "start",
138
- ]);
139
- if (result.exitCode === 0) return;
140
- // A concurrent session may have won the start race; readiness polling in the
141
- // caller decides. Only fail here when nothing is coming up on the port.
142
- if (await tcpReachable(EMBEDDED_HOST, EMBEDDED_PORT, 3_000)) return;
143
- throw new Error(`Could not start the embedded Postgres cluster: ${commandFailureDetail(result)}${logTail(logFile)}`);
239
+ isReachable: ReachabilityProbe = tcpReachable,
240
+ ): Promise<RetainedPostgres | undefined> {
241
+ try {
242
+ return retainedPostgresSpawner()({
243
+ executable: postgres,
244
+ args: ["-D", dataDir, "-p", String(EMBEDDED_PORT), "-c", `listen_addresses=${EMBEDDED_HOST}`],
245
+ cwd: dataDir,
246
+ logFile,
247
+ ...(context.owner === undefined ? {} : { uid: context.owner.uid, gid: context.owner.gid }),
248
+ });
249
+ } catch (error) {
250
+ // Another process can win the port while the setup lock is held. Attach to
251
+ // it, but never manufacture an ownership lease from postmaster.pid.
252
+ if (await isReachable(EMBEDDED_HOST, EMBEDDED_PORT, 3_000)) return undefined;
253
+ const detail = error instanceof Error ? error.message : String(error);
254
+ throw new Error(`Could not start the embedded Postgres cluster: ${detail}${logTail(logFile)}`);
255
+ }
256
+ }
257
+
258
+ function retainedPostgresSpawner(): RetainedPostgresSpawner {
259
+ if (retainedPostgresSpawnerOverride !== undefined) return retainedPostgresSpawnerOverride;
260
+ const binding = createRequire(import.meta.url)("@bastani/atomic-natives") as {
261
+ readonly spawnRetainedPostgres: RetainedPostgresSpawner;
262
+ };
263
+ return binding.spawnRetainedPostgres;
144
264
  }
145
265
 
146
266
  /**
@@ -168,7 +288,7 @@ function hydrateBinaryLibraryLinks(pgCtlPath: string): void {
168
288
  try {
169
289
  copyFileSync(absoluteSource, absoluteTarget);
170
290
  } catch {
171
- // Missing optional libraries surface as an initdb/pg_ctl failure with detail.
291
+ // Missing optional libraries surface as an initdb/Postgres failure with detail.
172
292
  }
173
293
  }
174
294
  }
@@ -189,14 +309,9 @@ async function loadEmbeddedPostgresBinaries(): Promise<EmbeddedPostgresBinaries>
189
309
  if (typeof binaries.pg_ctl !== "string" || typeof binaries.initdb !== "string") {
190
310
  throw new Error(`Embedded Postgres package ${packageName} did not export pg_ctl/initdb paths.`);
191
311
  }
192
- for (const binary of [
193
- binaries.pg_ctl,
194
- binaries.initdb,
195
- join(dirname(binaries.pg_ctl), process.platform === "win32" ? "postgres.exe" : "postgres"),
196
- ]) {
197
- ensureExecutable(binary);
198
- }
199
- return { pg_ctl: binaries.pg_ctl, initdb: binaries.initdb };
312
+ const postgres = join(dirname(binaries.pg_ctl), process.platform === "win32" ? "postgres.exe" : "postgres");
313
+ for (const binary of [binaries.pg_ctl, binaries.initdb, postgres]) ensureExecutable(binary);
314
+ return { pg_ctl: binaries.pg_ctl, initdb: binaries.initdb, postgres };
200
315
  }
201
316
 
202
317
  /** npm can strip executable bits; restore them only when actually missing. */
@@ -209,36 +324,357 @@ function ensureExecutable(filePath: string): void {
209
324
  }
210
325
  }
211
326
 
212
- /** Serialize initdb/start across concurrent Atomic processes on this machine. */
213
- async function withSetupLock(lockDir: string, fn: () => Promise<void>): Promise<void> {
214
- for (let attempt = 0; attempt < READY_ATTEMPTS; attempt += 1) {
327
+ type SetupLockHeartbeatScheduler = (heartbeat: () => boolean, intervalMs: number) => () => void;
328
+
329
+ interface HostLeaseTime {
330
+ readonly monotonicMs: number;
331
+ readonly wallTimeMs: number;
332
+ }
333
+
334
+ interface SetupLockOptions {
335
+ /** Compatibility seam for existing focused tests; production uses `clock`. */
336
+ readonly now?: () => number;
337
+ readonly clock?: () => HostLeaseTime;
338
+ readonly wait?: DelayOperation;
339
+ readonly staleMs?: number;
340
+ readonly heartbeatMs?: number;
341
+ readonly attempts?: number;
342
+ readonly scheduleHeartbeat?: SetupLockHeartbeatScheduler;
343
+ readonly isProcessAlive?: (pid: number) => boolean;
344
+ /** Test seam after a complete heartbeat temp record is durable and before replacement. */
345
+ readonly beforeHeartbeatReplace?: (temporaryMarkerPath: string) => void;
346
+ }
347
+
348
+ interface SetupLockLease {
349
+ readonly lockDir: string;
350
+ readonly markerPath: string;
351
+ readonly token: string;
352
+ readonly ownerPid: number;
353
+ readonly abandonedOwnerTokens: ReadonlySet<string>;
354
+ }
355
+
356
+ interface SetupLockWorkContext {
357
+ readonly runtimePublicationLease: RuntimePublicationLease;
358
+ readonly abandonedRuntimeStageOwnerTokens: ReadonlySet<string>;
359
+ }
360
+
361
+ interface LockOwnerRecord {
362
+ readonly token: string;
363
+ readonly pid: number;
364
+ readonly heartbeatMonotonicMs: number;
365
+ }
366
+
367
+ interface LockObservation {
368
+ readonly fingerprint: string;
369
+ readonly latestMtimeMs: number;
370
+ readonly owners: readonly LockOwnerRecord[];
371
+ readonly hasUnexpectedState: boolean;
372
+ }
373
+
374
+ /** Serialize copied-runtime repair, initdb, and start across Atomic processes on this machine. */
375
+ async function withSetupLock(
376
+ lockDir: string,
377
+ fn: (setup: SetupLockWorkContext) => Promise<void>,
378
+ options: SetupLockOptions = {},
379
+ ): Promise<void> {
380
+ const compatibilityNow = options.now;
381
+ const clock =
382
+ options.clock ??
383
+ (compatibilityNow === undefined
384
+ ? hostLeaseTime
385
+ : () => {
386
+ const now = compatibilityNow();
387
+ return { monotonicMs: now, wallTimeMs: now };
388
+ });
389
+ const wait = options.wait ?? delay;
390
+ const staleMs = options.staleMs ?? SETUP_LOCK_STALE_MS;
391
+ const heartbeatMs = options.heartbeatMs ?? Math.max(1, Math.floor(staleMs / 4));
392
+ const attempts = options.attempts ?? READY_ATTEMPTS;
393
+ const scheduleHeartbeat = options.scheduleHeartbeat ?? scheduleSetupLockHeartbeat;
394
+ const isProcessAlive = options.isProcessAlive ?? processIsAlive;
395
+ let lease: SetupLockLease | undefined;
396
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
397
+ lease = acquireSetupLock(lockDir, clock(), staleMs, isProcessAlive);
398
+ if (lease !== undefined) break;
399
+ if (attempt === attempts - 1) {
400
+ throw new Error(`Timed out waiting for another Atomic process to finish Postgres setup (${lockDir}).`);
401
+ }
402
+ await wait(READY_DELAY_MS);
403
+ }
404
+ if (lease === undefined) throw new Error(`Could not acquire the embedded Postgres setup lock (${lockDir}).`);
405
+
406
+ const refresh = () => refreshSetupLockLease(lease, clock(), options.beforeHeartbeatReplace);
407
+ const stopHeartbeat = scheduleHeartbeat(refresh, heartbeatMs);
408
+ try {
409
+ await fn({
410
+ runtimePublicationLease: { ownerToken: lease.token, refresh },
411
+ abandonedRuntimeStageOwnerTokens: lease.abandonedOwnerTokens,
412
+ });
413
+ } finally {
414
+ stopHeartbeat();
415
+ releaseSetupLock(lease);
416
+ }
417
+ }
418
+
419
+ function acquireSetupLock(
420
+ lockDir: string,
421
+ now: HostLeaseTime,
422
+ staleMs: number,
423
+ isProcessAlive: (pid: number) => boolean,
424
+ ): SetupLockLease | undefined {
425
+ const abandonedOwnerTokens = new Set<string>();
426
+ for (let attempt = 0; attempt < 2; attempt += 1) {
427
+ const token = `${process.pid}-${crypto.randomUUID()}`;
428
+ const markerPath = join(lockDir, `.owner-${token}`);
215
429
  try {
216
430
  mkdirSync(lockDir);
217
- break;
218
- } catch {
219
- if (lockIsStale(lockDir)) {
220
- rmSync(lockDir, { recursive: true, force: true });
221
- continue;
431
+ try {
432
+ writeFileSync(
433
+ markerPath,
434
+ serializeLockOwner({ token, pid: process.pid, heartbeatMonotonicMs: now.monotonicMs }),
435
+ {
436
+ flag: "wx",
437
+ mode: 0o600,
438
+ },
439
+ );
440
+ return { lockDir, markerPath, token, ownerPid: process.pid, abandonedOwnerTokens };
441
+ } catch (error) {
442
+ try {
443
+ rmdirSync(lockDir);
444
+ } catch {
445
+ // Unexpected content means ownership was never established.
446
+ }
447
+ throw error;
222
448
  }
223
- await delay(READY_DELAY_MS);
224
- if (attempt === READY_ATTEMPTS - 1)
225
- throw new Error(`Timed out waiting for another Atomic process to finish Postgres setup (${lockDir}).`);
449
+ } catch (error) {
450
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
451
+ if (code !== "EEXIST") throw error;
226
452
  }
453
+
454
+ const observation = observeSetupLock(lockDir);
455
+ if (observation === undefined || !setupLockIsStale(observation, now, staleMs, isProcessAlive)) return undefined;
456
+ const abandoned = breakStaleSetupLock(lockDir, observation, now, staleMs, token, isProcessAlive);
457
+ if (abandoned === undefined) return undefined;
458
+ for (const abandonedToken of abandoned) abandonedOwnerTokens.add(abandonedToken);
227
459
  }
460
+ return undefined;
461
+ }
462
+ function refreshSetupLockLease(
463
+ lease: SetupLockLease,
464
+ now: HostLeaseTime,
465
+ beforeReplace?: (temporaryMarkerPath: string) => void,
466
+ ): boolean {
467
+ if (!ownsSetupLock(lease)) return false;
468
+ const record = { token: lease.token, pid: lease.ownerPid, heartbeatMonotonicMs: now.monotonicMs };
469
+ const temporaryMarkerPath = join(lease.lockDir, `.owner-${lease.token}.tmp-${crypto.randomUUID()}`);
228
470
  try {
229
- await fn();
230
- } finally {
231
- rmSync(lockDir, { recursive: true, force: true });
471
+ writeFileSync(temporaryMarkerPath, serializeLockOwner(record), {
472
+ flag: "wx",
473
+ mode: 0o600,
474
+ flush: true,
475
+ });
476
+ beforeReplace?.(temporaryMarkerPath);
477
+ if (!ownsSetupLock(lease)) {
478
+ removeMarkerIfOwned(temporaryMarkerPath, record);
479
+ return false;
480
+ }
481
+ // Same-directory rename is the record's atomic commit on every supported
482
+ // platform. Node's Windows implementation requests replace-existing; if a
483
+ // platform or scanner still rejects it, retain the intact old marker and
484
+ // fail ownership rather than falling back to an in-place write.
485
+ renameSync(temporaryMarkerPath, lease.markerPath);
486
+ return ownsSetupLock(lease);
487
+ } catch {
488
+ removeMarkerIfOwned(temporaryMarkerPath, record);
489
+ return false;
232
490
  }
233
491
  }
234
- function lockIsStale(lockDir: string): boolean {
492
+
493
+ function removeMarkerIfOwned(path: string, expected: LockOwnerRecord): void {
494
+ try {
495
+ if (!lstatSync(path).isFile()) return;
496
+ const record = parseLockOwner(readFileSync(path, "utf8"));
497
+ if (
498
+ record?.token === expected.token &&
499
+ record.pid === expected.pid &&
500
+ record.heartbeatMonotonicMs === expected.heartbeatMonotonicMs
501
+ ) {
502
+ rmSync(path, { force: true });
503
+ }
504
+ } catch {
505
+ // A displaced/replaced temp record is not ours to remove.
506
+ }
507
+ }
508
+
509
+ function ownsSetupLock(lease: SetupLockLease): boolean {
235
510
  try {
236
- return Date.now() - statSync(lockDir).mtimeMs > SETUP_LOCK_STALE_MS;
511
+ const record = parseLockOwner(readFileSync(lease.markerPath, "utf8"));
512
+ return record?.token === lease.token && record.pid === lease.ownerPid && lstatSync(lease.markerPath).isFile();
237
513
  } catch {
238
514
  return false;
239
515
  }
240
516
  }
241
517
 
518
+ function releaseSetupLock(lease: SetupLockLease): void {
519
+ if (!ownsSetupLock(lease)) return;
520
+ // The marker name is unique to this owner. If a stale takeover moved the old
521
+ // directory and installed a new one, this path cannot name the new marker;
522
+ // rmdir is also non-recursive and therefore cannot erase another owner.
523
+ rmSync(lease.markerPath, { force: true });
524
+ try {
525
+ rmdirSync(lease.lockDir);
526
+ } catch {
527
+ // Unexpected content is left for bounded stale recovery, never swept here.
528
+ }
529
+ }
530
+
531
+ function breakStaleSetupLock(
532
+ lockDir: string,
533
+ observed: LockObservation,
534
+ now: HostLeaseTime,
535
+ staleMs: number,
536
+ token: string,
537
+ isProcessAlive: (pid: number) => boolean,
538
+ ): readonly string[] | undefined {
539
+ const breakPath = `${lockDir}.stale-${token}`;
540
+ try {
541
+ renameSync(lockDir, breakPath);
542
+ } catch {
543
+ return undefined;
544
+ }
545
+ const displaced = observeSetupLock(breakPath);
546
+ if (
547
+ displaced === undefined ||
548
+ displaced.fingerprint !== observed.fingerprint ||
549
+ !setupLockIsStale(displaced, now, staleMs, isProcessAlive)
550
+ ) {
551
+ try {
552
+ renameSync(breakPath, lockDir);
553
+ } catch {
554
+ // A concurrent contender now owns the fixed path. The displaced owner
555
+ // will observe loss of its unique marker and cannot remove that lock.
556
+ }
557
+ return undefined;
558
+ }
559
+ const abandoned = displaced.owners.filter((owner) => !isProcessAlive(owner.pid)).map((owner) => owner.token);
560
+ rmSync(breakPath, { recursive: true, force: true });
561
+ return abandoned;
562
+ }
563
+
564
+ function observeSetupLock(path: string): LockObservation | undefined {
565
+ try {
566
+ const parts: string[] = [];
567
+ const owners: LockOwnerRecord[] = [];
568
+ let latestMtimeMs = Number.NEGATIVE_INFINITY;
569
+ let hasUnexpectedState = false;
570
+ const visit = (entryPath: string, name: string): void => {
571
+ const stat = lstatSync(entryPath);
572
+ latestMtimeMs = Math.max(latestMtimeMs, stat.mtimeMs);
573
+ let type = "other";
574
+ if (stat.isDirectory()) type = "directory";
575
+ else if (stat.isFile()) type = "file";
576
+ else if (stat.isSymbolicLink()) type = "link";
577
+ parts.push(`${name}:${type}:${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`);
578
+ if (stat.isDirectory()) {
579
+ for (const child of readdirSync(entryPath).sort()) visit(join(entryPath, child), `${name}/${child}`);
580
+ } else if (stat.isFile()) {
581
+ const contents = readFileSync(entryPath, "utf8");
582
+ parts.push(contents);
583
+ const owner = parseLockOwner(contents);
584
+ if (owner !== undefined && markerNameMatchesOwner(name, owner)) owners.push(owner);
585
+ else hasUnexpectedState = true;
586
+ } else if (stat.isSymbolicLink()) {
587
+ parts.push(readlinkSync(entryPath));
588
+ hasUnexpectedState = true;
589
+ } else {
590
+ hasUnexpectedState = true;
591
+ }
592
+ };
593
+ visit(path, ".");
594
+ return { fingerprint: parts.join("\0"), latestMtimeMs, owners, hasUnexpectedState };
595
+ } catch {
596
+ return undefined;
597
+ }
598
+ }
599
+
600
+ function markerNameMatchesOwner(name: string, owner: LockOwnerRecord): boolean {
601
+ const stableName = `./.owner-${owner.token}`;
602
+ return name === stableName || name.startsWith(`${stableName}.tmp-`);
603
+ }
604
+
605
+ function setupLockIsStale(
606
+ observation: LockObservation,
607
+ now: HostLeaseTime,
608
+ staleMs: number,
609
+ isProcessAlive: (pid: number) => boolean,
610
+ ): boolean {
611
+ for (const owner of observation.owners) {
612
+ // A dead recorded process is abandoned even when a reboot's new uptime has
613
+ // already crossed its old low uptime. PID reuse fails closed as live and
614
+ // falls back to the bounded monotonic age check.
615
+ if (!isProcessAlive(owner.pid)) continue;
616
+ // Uptime cannot move backward within one boot. A lower current value is
617
+ // therefore reboot/monotonic-reset evidence and the old lease is stale.
618
+ if (now.monotonicMs >= owner.heartbeatMonotonicMs && now.monotonicMs - owner.heartbeatMonotonicMs <= staleMs) {
619
+ return false;
620
+ }
621
+ }
622
+ if (!observation.hasUnexpectedState) return observation.owners.length > 0;
623
+ // Finite migration handling for malformed/legacy locks. A future mtime is
624
+ // rollback evidence rather than a lease that can stay fresh indefinitely.
625
+ return now.wallTimeMs < observation.latestMtimeMs || now.wallTimeMs - observation.latestMtimeMs > staleMs;
626
+ }
627
+ function serializeLockOwner(owner: LockOwnerRecord): string {
628
+ const serialized = JSON.stringify(owner);
629
+ if (serialized.length > 255) throw new Error("Embedded Postgres setup-lock owner record is unexpectedly large.");
630
+ return serialized.padEnd(256, "\n");
631
+ }
632
+
633
+ function parseLockOwner(value: string): LockOwnerRecord | undefined {
634
+ try {
635
+ const parsed = JSON.parse(value) as Partial<LockOwnerRecord>;
636
+ if (
637
+ typeof parsed.token !== "string" ||
638
+ parsed.token === "" ||
639
+ !Number.isInteger(parsed.pid) ||
640
+ (parsed.pid ?? 0) <= 0 ||
641
+ !Number.isFinite(parsed.heartbeatMonotonicMs) ||
642
+ (parsed.heartbeatMonotonicMs ?? -1) < 0
643
+ ) {
644
+ return undefined;
645
+ }
646
+ return {
647
+ token: parsed.token,
648
+ pid: parsed.pid,
649
+ heartbeatMonotonicMs: parsed.heartbeatMonotonicMs,
650
+ } as LockOwnerRecord;
651
+ } catch {
652
+ return undefined;
653
+ }
654
+ }
655
+
656
+ function hostLeaseTime(): HostLeaseTime {
657
+ return { monotonicMs: uptime() * 1000, wallTimeMs: Date.now() };
658
+ }
659
+
660
+ function processIsAlive(pid: number): boolean {
661
+ try {
662
+ process.kill(pid, 0);
663
+ return true;
664
+ } catch (error) {
665
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
666
+ return code !== "ESRCH";
667
+ }
668
+ }
669
+
670
+ function scheduleSetupLockHeartbeat(heartbeat: () => boolean, intervalMs: number): () => void {
671
+ const timer = setInterval(() => {
672
+ if (!heartbeat()) clearInterval(timer);
673
+ }, intervalMs);
674
+ timer.unref();
675
+ return () => clearInterval(timer);
676
+ }
677
+
242
678
  function logTail(logFile: string): string {
243
679
  try {
244
680
  const lines = readFileSync(logFile, "utf8").trimEnd().split("\n");
@@ -247,7 +683,35 @@ function logTail(logFile: string): string {
247
683
  return "";
248
684
  }
249
685
  }
686
+ function setActiveClusterForTests(lease: RetainedPostgres | undefined): ActiveEmbeddedPostgres | undefined {
687
+ activeCluster = lease === undefined ? undefined : { lease };
688
+ return activeCluster;
689
+ }
690
+
691
+ function setRetainedPostgresSpawnerForTests(spawner: RetainedPostgresSpawner | undefined): void {
692
+ retainedPostgresSpawnerOverride = spawner;
693
+ }
694
+
695
+ function setEnsureOperationForTests(operation: EnsureOperation | undefined): void {
696
+ ensured = undefined;
697
+ ensureOperation = operation ?? ensure;
698
+ }
699
+
700
+ /** Narrow seams for retained-process lifecycle tests. */
701
+ export const embeddedPostgresTestHooks = {
702
+ ensure: ensureEmbeddedDbosPostgres,
703
+ setActiveCluster: setActiveClusterForTests,
704
+ setEnsureOperation: setEnsureOperationForTests,
705
+ setRetainedPostgresSpawner: setRetainedPostgresSpawnerForTests,
706
+ startCluster,
707
+ waitForClusterReadiness,
708
+ withSetupLock,
709
+ };
250
710
 
251
711
  export function resetEmbeddedDbosPostgresForTests(): void {
252
712
  ensured = undefined;
713
+ activeCluster?.lease.release();
714
+ activeCluster = undefined;
715
+ ensureOperation = ensure;
716
+ retainedPostgresSpawnerOverride = undefined;
253
717
  }