@bastani/atomic 0.9.20-alpha.8 → 0.9.20

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 (309) hide show
  1. package/CHANGELOG.md +288 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +25 -0
  3. package/dist/builtin/intercom/package.json +3 -5
  4. package/dist/builtin/mcp/CHANGELOG.md +13 -0
  5. package/dist/builtin/mcp/package.json +3 -3
  6. package/dist/builtin/subagents/CHANGELOG.md +56 -0
  7. package/dist/builtin/subagents/package.json +3 -3
  8. package/dist/builtin/subagents/skills/tdd/SKILL.md +10 -2
  9. package/dist/builtin/subagents/skills/tdd/mocking.md +4 -0
  10. package/dist/builtin/subagents/skills/tdd/test-audit.md +105 -0
  11. package/dist/builtin/subagents/skills/tdd/tests.md +3 -1
  12. package/dist/builtin/subagents/src/extension/index.bundle.mjs +13 -3
  13. package/dist/builtin/web-access/CHANGELOG.md +13 -0
  14. package/dist/builtin/web-access/package.json +1 -1
  15. package/dist/builtin/workflows/CHANGELOG.md +169 -0
  16. package/dist/builtin/workflows/README.md +1 -1
  17. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  18. package/dist/builtin/workflows/builtin/{chunk-njmf5ze7.js → chunk-0nrgfbag.js} +1 -1
  19. package/dist/builtin/workflows/builtin/{chunk-hmt5w62g.js → chunk-2hak3b7g.js} +1 -1
  20. package/dist/builtin/workflows/builtin/{chunk-2hzrv5y8.js → chunk-73c5tayt.js} +1020 -200
  21. package/dist/builtin/workflows/builtin/{chunk-ffdrv23t.js → chunk-bzdvx2xr.js} +1 -1
  22. package/dist/builtin/workflows/builtin/{chunk-5724b0cf.js → chunk-crw7q5g1.js} +1 -1
  23. package/dist/builtin/workflows/builtin/{chunk-7n51c5gh.js → chunk-cw86srkf.js} +1 -1
  24. package/dist/builtin/workflows/builtin/{chunk-dxjxtgmp.js → chunk-jaj27rqc.js} +1 -1
  25. package/dist/builtin/workflows/builtin/{chunk-3tx8ry44.js → chunk-kspvwc24.js} +3 -2
  26. package/dist/builtin/workflows/builtin/{chunk-7bzcersz.js → chunk-maqv731g.js} +3 -3
  27. package/dist/builtin/workflows/builtin/{chunk-9z3ztr2a.js → chunk-vkmpdat4.js} +1 -1
  28. package/dist/builtin/workflows/builtin/{chunk-vn0wb31x.js → chunk-w18kbz63.js} +1 -1
  29. package/dist/builtin/workflows/builtin/{chunk-jngsbbpm.js → chunk-wh19f5ee.js} +3 -3
  30. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  31. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  32. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  33. package/dist/builtin/workflows/builtin/goal.js +4 -4
  34. package/dist/builtin/workflows/builtin/index.js +12 -12
  35. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  36. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  37. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  38. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  39. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  40. package/dist/builtin/workflows/package.json +4 -4
  41. package/dist/builtin/workflows/src/authoring.d.ts +6 -3
  42. package/dist/builtin/workflows/src/extension/index.bundle.mjs +12164 -11365
  43. package/dist/builtin/workflows/src/index.js +41685 -12907
  44. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +13 -0
  45. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  46. package/dist/core/agent-session-boundaries.js +9 -4
  47. package/dist/core/agent-session-boundaries.js.map +1 -1
  48. package/dist/core/agent-session-events.d.ts.map +1 -1
  49. package/dist/core/agent-session-events.js +4 -0
  50. package/dist/core/agent-session-events.js.map +1 -1
  51. package/dist/core/agent-session-methods.d.ts +3 -0
  52. package/dist/core/agent-session-methods.d.ts.map +1 -1
  53. package/dist/core/agent-session-methods.js.map +1 -1
  54. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  55. package/dist/core/agent-session-queue-pause.js +2 -1
  56. package/dist/core/agent-session-queue-pause.js.map +1 -1
  57. package/dist/core/agent-session-tasks.js +4 -4
  58. package/dist/core/agent-session-tasks.js.map +1 -1
  59. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  60. package/dist/core/agent-session-tool-registry.js +4 -3
  61. package/dist/core/agent-session-tool-registry.js.map +1 -1
  62. package/dist/core/agent-session.d.ts +3 -0
  63. package/dist/core/agent-session.d.ts.map +1 -1
  64. package/dist/core/agent-session.js +3 -0
  65. package/dist/core/agent-session.js.map +1 -1
  66. package/dist/core/cache-stats.d.ts +7 -1
  67. package/dist/core/cache-stats.d.ts.map +1 -1
  68. package/dist/core/cache-stats.js +24 -5
  69. package/dist/core/cache-stats.js.map +1 -1
  70. package/dist/core/context-tool-pairing.d.ts +10 -14
  71. package/dist/core/context-tool-pairing.d.ts.map +1 -1
  72. package/dist/core/context-tool-pairing.js +99 -28
  73. package/dist/core/context-tool-pairing.js.map +1 -1
  74. package/dist/core/execution-model-router.d.ts +1 -1
  75. package/dist/core/execution-model-router.d.ts.map +1 -1
  76. package/dist/core/execution-model-router.js +23 -14
  77. package/dist/core/execution-model-router.js.map +1 -1
  78. package/dist/core/extensions/agent-events.d.ts +9 -1
  79. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  80. package/dist/core/extensions/agent-events.js.map +1 -1
  81. package/dist/core/extensions/api-types.d.ts +2 -1
  82. package/dist/core/extensions/api-types.d.ts.map +1 -1
  83. package/dist/core/extensions/api-types.js.map +1 -1
  84. package/dist/core/extensions/event-types.d.ts +2 -2
  85. package/dist/core/extensions/event-types.d.ts.map +1 -1
  86. package/dist/core/extensions/event-types.js.map +1 -1
  87. package/dist/core/extensions/index.d.ts +1 -1
  88. package/dist/core/extensions/index.d.ts.map +1 -1
  89. package/dist/core/extensions/index.js.map +1 -1
  90. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  91. package/dist/core/extensions/loader-core.js +1 -0
  92. package/dist/core/extensions/loader-core.js.map +1 -1
  93. package/dist/core/extensions/provider-types.d.ts +34 -16
  94. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  95. package/dist/core/extensions/provider-types.js.map +1 -1
  96. package/dist/core/extensions/runtime-types.d.ts +4 -0
  97. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  98. package/dist/core/extensions/runtime-types.js.map +1 -1
  99. package/dist/core/extensions/tool-types.d.ts +9 -0
  100. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  101. package/dist/core/extensions/tool-types.js.map +1 -1
  102. package/dist/core/fast-model-routing.d.ts.map +1 -1
  103. package/dist/core/fast-model-routing.js +1 -0
  104. package/dist/core/fast-model-routing.js.map +1 -1
  105. package/dist/core/messages.d.ts.map +1 -1
  106. package/dist/core/messages.js +2 -1
  107. package/dist/core/messages.js.map +1 -1
  108. package/dist/core/model-registry.d.ts +3 -1
  109. package/dist/core/model-registry.d.ts.map +1 -1
  110. package/dist/core/model-registry.js +6 -0
  111. package/dist/core/model-registry.js.map +1 -1
  112. package/dist/core/model-runtime-auth.d.ts +2 -2
  113. package/dist/core/model-runtime-auth.d.ts.map +1 -1
  114. package/dist/core/model-runtime-auth.js.map +1 -1
  115. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  116. package/dist/core/model-runtime-streaming.js +2 -1
  117. package/dist/core/model-runtime-streaming.js.map +1 -1
  118. package/dist/core/model-runtime.d.ts +11 -3
  119. package/dist/core/model-runtime.d.ts.map +1 -1
  120. package/dist/core/model-runtime.js +41 -6
  121. package/dist/core/model-runtime.js.map +1 -1
  122. package/dist/core/package-manager-npm.d.ts.map +1 -1
  123. package/dist/core/package-manager-npm.js +32 -8
  124. package/dist/core/package-manager-npm.js.map +1 -1
  125. package/dist/core/package-manager-resolver.js +3 -1
  126. package/dist/core/package-manager-resolver.js.map +1 -1
  127. package/dist/core/package-manager-types.d.ts +1 -0
  128. package/dist/core/package-manager-types.d.ts.map +1 -1
  129. package/dist/core/package-manager-types.js.map +1 -1
  130. package/dist/core/provider-composer-internal.d.ts +40 -21
  131. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  132. package/dist/core/provider-composer-internal.js +22 -20
  133. package/dist/core/provider-composer-internal.js.map +1 -1
  134. package/dist/core/provider-composer.d.ts +3 -3
  135. package/dist/core/provider-composer.d.ts.map +1 -1
  136. package/dist/core/provider-composer.js +54 -10
  137. package/dist/core/provider-composer.js.map +1 -1
  138. package/dist/core/remote-catalog-provider.d.ts +8 -1
  139. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  140. package/dist/core/remote-catalog-provider.js +46 -4
  141. package/dist/core/remote-catalog-provider.js.map +1 -1
  142. package/dist/core/resource-loader-core.d.ts.map +1 -1
  143. package/dist/core/resource-loader-core.js +7 -3
  144. package/dist/core/resource-loader-core.js.map +1 -1
  145. package/dist/core/resource-loader-extension-warnings.d.ts +9 -0
  146. package/dist/core/resource-loader-extension-warnings.d.ts.map +1 -0
  147. package/dist/core/resource-loader-extension-warnings.js +54 -0
  148. package/dist/core/resource-loader-extension-warnings.js.map +1 -0
  149. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  150. package/dist/core/resource-loader-extensions.js +1 -0
  151. package/dist/core/resource-loader-extensions.js.map +1 -1
  152. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  153. package/dist/core/resource-loader-reload.js +6 -0
  154. package/dist/core/resource-loader-reload.js.map +1 -1
  155. package/dist/core/runtime-credentials.d.ts.map +1 -1
  156. package/dist/core/runtime-credentials.js +3 -1
  157. package/dist/core/runtime-credentials.js.map +1 -1
  158. package/dist/core/sdk.js +16 -6
  159. package/dist/core/sdk.js.map +1 -1
  160. package/dist/core/settings-manager-basic-accessors.js +4 -4
  161. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  162. package/dist/core/structured-output/choice-schema.d.ts +8 -0
  163. package/dist/core/structured-output/choice-schema.d.ts.map +1 -0
  164. package/dist/core/structured-output/choice-schema.js +79 -0
  165. package/dist/core/structured-output/choice-schema.js.map +1 -0
  166. package/dist/core/structured-output/index.d.ts +3 -5
  167. package/dist/core/structured-output/index.d.ts.map +1 -1
  168. package/dist/core/structured-output/index.js +218 -41
  169. package/dist/core/structured-output/index.js.map +1 -1
  170. package/dist/core/structured-output/resolver.d.ts +0 -46
  171. package/dist/core/structured-output/resolver.d.ts.map +1 -1
  172. package/dist/core/structured-output/resolver.js +15 -93
  173. package/dist/core/structured-output/resolver.js.map +1 -1
  174. package/dist/core/structured-output/types.d.ts +27 -21
  175. package/dist/core/structured-output/types.d.ts.map +1 -1
  176. package/dist/core/structured-output/types.js.map +1 -1
  177. package/dist/core/system-prompt.d.ts.map +1 -1
  178. package/dist/core/system-prompt.js +9 -1
  179. package/dist/core/system-prompt.js.map +1 -1
  180. package/dist/core/tasks/owner-store.d.ts +6 -0
  181. package/dist/core/tasks/owner-store.d.ts.map +1 -1
  182. package/dist/core/tasks/owner-store.js +16 -3
  183. package/dist/core/tasks/owner-store.js.map +1 -1
  184. package/dist/core/tasks/pause.js +1 -1
  185. package/dist/core/tasks/pause.js.map +1 -1
  186. package/dist/core/tasks/supervisor.d.ts +4 -2
  187. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  188. package/dist/core/tasks/supervisor.js +9 -3
  189. package/dist/core/tasks/supervisor.js.map +1 -1
  190. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  191. package/dist/core/tools/ask-user-question/ask-user-question.js +1 -0
  192. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  193. package/dist/core/tools/bash.d.ts.map +1 -1
  194. package/dist/core/tools/bash.js +1 -0
  195. package/dist/core/tools/bash.js.map +1 -1
  196. package/dist/core/tools/edit.d.ts.map +1 -1
  197. package/dist/core/tools/edit.js +1 -0
  198. package/dist/core/tools/edit.js.map +1 -1
  199. package/dist/core/tools/file-mutation-coordinator.d.ts +4 -3
  200. package/dist/core/tools/file-mutation-coordinator.d.ts.map +1 -1
  201. package/dist/core/tools/file-mutation-coordinator.js +45 -38
  202. package/dist/core/tools/file-mutation-coordinator.js.map +1 -1
  203. package/dist/core/tools/powershell.d.ts +16 -0
  204. package/dist/core/tools/powershell.d.ts.map +1 -1
  205. package/dist/core/tools/structured-output.d.ts +9 -6
  206. package/dist/core/tools/structured-output.d.ts.map +1 -1
  207. package/dist/core/tools/structured-output.js +36 -8
  208. package/dist/core/tools/structured-output.js.map +1 -1
  209. package/dist/core/tools/todos.d.ts.map +1 -1
  210. package/dist/core/tools/todos.js +1 -0
  211. package/dist/core/tools/todos.js.map +1 -1
  212. package/dist/core/tools/tool-concurrency.d.ts +23 -0
  213. package/dist/core/tools/tool-concurrency.d.ts.map +1 -0
  214. package/dist/core/tools/tool-concurrency.js +58 -0
  215. package/dist/core/tools/tool-concurrency.js.map +1 -0
  216. package/dist/core/tools/tool-definition-wrapper.d.ts +4 -1
  217. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  218. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  219. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  220. package/dist/core/tools/write.d.ts.map +1 -1
  221. package/dist/core/tools/write.js +1 -0
  222. package/dist/core/tools/write.js.map +1 -1
  223. package/dist/index-extensions.d.ts +1 -1
  224. package/dist/index-extensions.d.ts.map +1 -1
  225. package/dist/index-extensions.js.map +1 -1
  226. package/dist/index.d.ts +1 -1
  227. package/dist/index.d.ts.map +1 -1
  228. package/dist/index.js +1 -1
  229. package/dist/index.js.map +1 -1
  230. package/dist/main.d.ts.map +1 -1
  231. package/dist/main.js +4 -0
  232. package/dist/main.js.map +1 -1
  233. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  234. package/dist/modes/interactive/components/settings-selector-items.js +11 -9
  235. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  236. package/dist/modes/interactive/components/settings-selector-types.d.ts +2 -1
  237. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  238. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  239. package/dist/modes/interactive/components/task-inspector.d.ts +1 -0
  240. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  241. package/dist/modes/interactive/components/task-inspector.js +11 -11
  242. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  243. package/dist/modes/interactive/components/task-list.d.ts +9 -3
  244. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  245. package/dist/modes/interactive/components/task-list.js +26 -2
  246. package/dist/modes/interactive/components/task-list.js.map +1 -1
  247. package/dist/modes/interactive/interactive-agent-events.js +3 -9
  248. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  249. package/dist/modes/interactive/interactive-auth-login.js +1 -1
  250. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  251. package/dist/modes/interactive/interactive-render-chat.js +3 -9
  252. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  253. package/dist/modes/interactive/interactive-resource-rendering.js +6 -9
  254. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  255. package/dist/modes/interactive/interactive-selectors.js +1 -0
  256. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  257. package/dist/modes/interactive/interactive-slash-commands.js +2 -4
  258. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  259. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -0
  260. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  261. package/dist/modes/interactive-engine/isolated-runtime.js +5 -0
  262. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  263. package/dist/utils/clipboard-image.d.ts.map +1 -1
  264. package/dist/utils/clipboard-image.js +14 -17
  265. package/dist/utils/clipboard-image.js.map +1 -1
  266. package/docs/background-tasks.md +1 -0
  267. package/docs/computer-use.md +33 -9
  268. package/docs/custom-provider/registration.md +1 -1
  269. package/docs/custom-provider.md +43 -1
  270. package/docs/extensions/authoring.md +22 -3
  271. package/docs/extensions/events.md +18 -0
  272. package/docs/extensions/examples.md +1 -0
  273. package/docs/getting-started/first-session.md +1 -1
  274. package/docs/models/evals.md +31 -79
  275. package/docs/models/model-selection.md +5 -1
  276. package/docs/packages/authoring.md +3 -1
  277. package/docs/providers.md +7 -11
  278. package/docs/sdk/reference.md +18 -42
  279. package/docs/sdk/structured-decisions.md +44 -89
  280. package/docs/sdk.md +1 -1
  281. package/docs/settings.md +6 -6
  282. package/docs/skills.md +2 -2
  283. package/docs/subagents/reference.md +7 -8
  284. package/docs/usage.md +13 -0
  285. package/docs/workflows/api-reference.md +38 -35
  286. package/docs/workflows/authoring.md +113 -1
  287. package/docs/workflows/builtins.md +1 -1
  288. package/docs/workflows/operations.md +53 -29
  289. package/docs/workflows/reliable-design.md +1 -1
  290. package/docs/workflows/verification.md +38 -7
  291. package/docs/workflows.md +1 -1
  292. package/examples/extensions/README.md +1 -0
  293. package/examples/extensions/debug-provider.ts +90 -0
  294. package/examples/extensions/structured-output.ts +6 -0
  295. package/npm-shrinkwrap.json +32 -32
  296. package/package.json +3 -3
  297. package/dist/builtin/workflows/src/durable/dependency-doctor-types.d.ts +0 -42
  298. package/dist/core/decision-provider.d.ts +0 -4
  299. package/dist/core/decision-provider.d.ts.map +0 -1
  300. package/dist/core/decision-provider.js +0 -12
  301. package/dist/core/decision-provider.js.map +0 -1
  302. package/dist/core/structured-output/jev-client.d.ts +0 -25
  303. package/dist/core/structured-output/jev-client.d.ts.map +0 -1
  304. package/dist/core/structured-output/jev-client.js +0 -174
  305. package/dist/core/structured-output/jev-client.js.map +0 -1
  306. package/dist/core/structured-output/jev.d.ts +0 -5
  307. package/dist/core/structured-output/jev.d.ts.map +0 -1
  308. package/dist/core/structured-output/jev.js +0 -249
  309. package/dist/core/structured-output/jev.js.map +0 -1
@@ -4955,7 +4955,7 @@ var require_lib2 = __commonJS(function(exports, module) {
4955
4955
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
4956
4956
  import { randomUUID as randomUUID3 } from "node:crypto";
4957
4957
  import { mkdir as mkdir2, readdir as readdir2, rm as rm2, stat } from "node:fs/promises";
4958
- import { dirname as dirname3, join as join5 } from "node:path";
4958
+ import { dirname as dirname4, join as join5 } from "node:path";
4959
4959
  import { getAgentDir, getEnvValue } from "@bastani/atomic";
4960
4960
  // dist/builtin/workflows/src/durable/backend-process-owner.ts
4961
4961
  var DURABLE_BACKEND_PROCESS_OWNER_KEY = Symbol.for("atomic-workflows/durable-backend-process-owner@1");
@@ -5125,6 +5125,18 @@ function getDbosProcessOwner() {
5125
5125
  // dist/builtin/workflows/src/durable/dbos-sdk-handle.ts
5126
5126
  var ATOMIC_EXECUTOR_ID = `atomic-${process.pid.toString(36)}-${crypto.randomUUID().slice(0, 8)}`;
5127
5127
 
5128
+ // dist/builtin/workflows/src/durable/dbos-system-database-url.ts
5129
+ function nonEmptyTrimmed(value) {
5130
+ const trimmed = value?.trim();
5131
+ return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;
5132
+ }
5133
+ function environmentSystemDatabaseUrl() {
5134
+ return nonEmptyTrimmed(process.env.DBOS_SYSTEM_DATABASE_URL);
5135
+ }
5136
+ function explicitDbosSystemDatabaseUrl() {
5137
+ return environmentSystemDatabaseUrl() ?? nonEmptyTrimmed(getDbosProcessOwner().systemDatabaseUrl);
5138
+ }
5139
+
5128
5140
  // ../../node_modules/pg/esm/index.mjs
5129
5141
  var import_lib = __toESM(require_lib2(), 1);
5130
5142
  var Client = import_lib.default.Client;
@@ -5159,13 +5171,17 @@ function defaultPostgresUrl(database, host = process.env.PGHOST || "localhost",
5159
5171
  import {
5160
5172
  chmodSync,
5161
5173
  chownSync,
5174
+ closeSync,
5162
5175
  copyFileSync,
5163
5176
  existsSync as existsSync3,
5177
+ fstatSync,
5164
5178
  lstatSync as lstatSync3,
5165
5179
  mkdirSync as mkdirSync2,
5180
+ openSync,
5166
5181
  readdirSync as readdirSync2,
5167
5182
  readFileSync as readFileSync3,
5168
5183
  readlinkSync,
5184
+ readSync,
5169
5185
  realpathSync as realpathSync3,
5170
5186
  renameSync as renameSync2,
5171
5187
  rmdirSync,
@@ -5174,9 +5190,9 @@ import {
5174
5190
  symlinkSync,
5175
5191
  writeFileSync as writeFileSync2
5176
5192
  } from "node:fs";
5177
- import { createRequire as createRequire2 } from "node:module";
5193
+ import { createRequire as createRequire3 } from "node:module";
5178
5194
  import { tmpdir, uptime } from "node:os";
5179
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2 } from "node:path";
5195
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute3, join as join4, relative as relative2, sep as sep2 } from "node:path";
5180
5196
 
5181
5197
  // dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts
5182
5198
  import { createHash } from "node:crypto";
@@ -5188,14 +5204,15 @@ import {
5188
5204
  mkdir,
5189
5205
  open,
5190
5206
  readdir,
5207
+ readFile,
5191
5208
  readlink,
5192
5209
  realpath,
5193
5210
  rename,
5194
5211
  rm,
5195
5212
  writeFile
5196
5213
  } from "node:fs/promises";
5197
- import { homedir } from "node:os";
5198
- import { dirname, isAbsolute, join, relative, sep } from "node:path";
5214
+ import { homedir, userInfo } from "node:os";
5215
+ import { basename, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
5199
5216
 
5200
5217
  // dist/builtin/workflows/src/durable/local-command.ts
5201
5218
  import { spawn } from "node:child_process";
@@ -5368,30 +5385,43 @@ function parseIdentityGroups(result) {
5368
5385
  }
5369
5386
  var STAGE_OWNER_FILE = ".atomic-stage-owner";
5370
5387
  var STAGE_PAYLOAD_DIR = "runtime";
5388
+ var RUNTIME_MARKER = ".atomic-runtime-complete.json";
5389
+ var MAX_RUNTIME_REPAIR_GENERATIONS = 8;
5371
5390
  var TRAVERSAL_OPERATIONS_PER_YIELD = 16;
5372
5391
  var HASH_CHUNK_BYTES = 64 * 1024;
5392
+ var sourceMemo = new Map;
5393
+ var legacyMemo = new Map;
5394
+ var validatedMemo = new Map;
5395
+ var corruptGenerationMemo = new Map;
5396
+ function runtimeGenerationIdentity(rootStat, markerStat) {
5397
+ const identity = (stat) => stat === undefined ? null : [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeMs, stat.ctimeMs, stat.birthtimeMs];
5398
+ return JSON.stringify([identity(rootStat), identity(markerStat)]);
5399
+ }
5400
+ async function candidateIdentity(candidate, rootStat) {
5401
+ return runtimeGenerationIdentity(rootStat, await lstatOrUndefined(join(candidate, RUNTIME_MARKER)));
5402
+ }
5373
5403
  async function prepareBinariesForOwner(binaries, context, runner = runLocalCommand, options = {}) {
5374
- const owner = context.owner;
5375
- if (owner === undefined)
5376
- return binaries;
5377
- const probe = await context.runAsOwner(binaries.initdb, ["--version"]).catch(() => {
5378
- return;
5379
- });
5380
- if (probe !== undefined && probe.exitCode === 0)
5381
- return binaries;
5382
5404
  const sourceNativeDir = dirname(dirname(binaries.initdb));
5383
- const copiedRuntimeDir = join(context.baseDir, "pg-runtime");
5405
+ const override = process.env.ATOMIC_POSTGRES_RUNTIME_CACHE_DIR;
5406
+ if (override !== undefined && !isAbsolute(override))
5407
+ throw new Error(`Embedded Postgres runtime cache override must be absolute: ${override}`);
5408
+ const copiedRuntimeDir = override === undefined ? join(context.baseDir, "pg-runtime") : normalize(override);
5384
5409
  const publisher = publisherIdentity();
5385
5410
  const progress = runtimeProgress(options);
5386
- const sourceSnapshot = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
5411
+ await ensureRuntimeCacheDirectory(copiedRuntimeDir, publisher, context.owner !== undefined, context.owner);
5412
+ const sourceSnapshot = await memoizedSourceSnapshot(sourceNativeDir, copiedRuntimeDir, publisher, progress, options);
5387
5413
  await options.afterInitialSourceSnapshot?.();
5388
- const copiedNativeDir = await findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options);
5414
+ const copiedNativeDir = await findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options, context.owner !== undefined);
5389
5415
  return {
5390
- pg_ctl: join(copiedNativeDir, "bin", "pg_ctl"),
5391
- initdb: join(copiedNativeDir, "bin", "initdb"),
5392
- postgres: join(copiedNativeDir, "bin", "postgres")
5416
+ pg_ctl: join(copiedNativeDir, "bin", basename(binaries.pg_ctl)),
5417
+ initdb: join(copiedNativeDir, "bin", basename(binaries.initdb)),
5418
+ postgres: join(copiedNativeDir, "bin", basename(binaries.postgres)),
5419
+ sealedIdentity: sourceSnapshot.sealedIdentity
5393
5420
  };
5394
5421
  }
5422
+ async function fingerprintPreparedRuntime(binaries, options = {}) {
5423
+ return validatePreparedRuntime(dirname(dirname(binaries.postgres)), binaries, runtimeProgress(options), undefined, options);
5424
+ }
5395
5425
  async function cleanupAbandonedRuntimeStages(baseDir, abandonedOwnerTokens = new Set) {
5396
5426
  if (abandonedOwnerTokens.size === 0)
5397
5427
  return;
@@ -5419,30 +5449,65 @@ async function cleanupAbandonedRuntimeStages(baseDir, abandonedOwnerTokens = new
5419
5449
  await rm(stage, { recursive: true, force: true });
5420
5450
  }
5421
5451
  }
5422
- async function findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options) {
5423
- await mkdir(copiedRuntimeDir, { recursive: true, mode: 493 });
5424
- const runtimeStat = await lstat(copiedRuntimeDir);
5425
- if (!runtimeStat.isDirectory() || runtimeStat.isSymbolicLink()) {
5426
- throw new Error(`Embedded Postgres runtime parent must be a real directory: ${copiedRuntimeDir}`);
5452
+ async function findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options, needsPrivilegeDrop) {
5453
+ await ensureRuntimeCacheDirectory(copiedRuntimeDir, publisher, needsPrivilegeDrop);
5454
+ const canonical = join(copiedRuntimeDir, `native-${sourceSnapshot.sourceIdentity}`);
5455
+ if (options.repairCorruptGeneration && !options.publicationLease?.refresh()) {
5456
+ throw new RuntimePublicationLeaseLostError("Embedded Postgres runtime repair requires its setup lease.");
5427
5457
  }
5428
- await chown(copiedRuntimeDir, publisher.uid, publisher.gid);
5429
- await chmod(copiedRuntimeDir, 493);
5430
- const generationNativeDir = join(copiedRuntimeDir, `native-${sourceSnapshot.sourceIdentity}`);
5431
- const existing = await lstatOrUndefined(generationNativeDir);
5432
- if (existing !== undefined) {
5458
+ let generationNativeDir;
5459
+ for (let repair = 0;repair <= MAX_RUNTIME_REPAIR_GENERATIONS; repair++) {
5460
+ const candidate = repair === 0 ? canonical : `${canonical}-repair-${repair}`;
5461
+ let candidateFingerprint;
5433
5462
  try {
5434
- if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5435
- throw new Error("sealed identity mismatch");
5463
+ const existing = await lstatOrUndefined(candidate);
5464
+ if (existing === undefined) {
5465
+ if (candidate === options.reservedGeneration)
5466
+ continue;
5467
+ generationNativeDir ??= candidate;
5468
+ if (!options.repairCorruptGeneration)
5469
+ break;
5470
+ continue;
5436
5471
  }
5437
- await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while selecting an existing generation.");
5438
- return generationNativeDir;
5472
+ candidateFingerprint = await candidateIdentity(candidate, existing);
5473
+ const knownCorrupt = corruptGenerationMemo.get(candidate);
5474
+ if (knownCorrupt?.identity === candidateFingerprint)
5475
+ throw new CorruptRuntimeGenerationError(knownCorrupt.reason);
5476
+ const identity = await validatePreparedRuntime(candidate, {
5477
+ pg_ctl: join(candidate, "bin", basename(binaries.pg_ctl)),
5478
+ initdb: join(candidate, "bin", basename(binaries.initdb)),
5479
+ postgres: join(candidate, "bin", basename(binaries.postgres))
5480
+ }, progress, sourceSnapshot.sealedIdentity, options);
5481
+ if (identity !== sourceSnapshot.sealedIdentity)
5482
+ throw new CorruptRuntimeGenerationError("sealed identity mismatch");
5439
5483
  } catch (error) {
5440
- if (error instanceof SourceRuntimeChangedError)
5484
+ if (error instanceof RuntimePublicationLeaseLostError)
5441
5485
  throw error;
5442
- const detail = error instanceof Error ? error.message : String(error);
5443
- throw new Error(`Embedded Postgres runtime generation is corrupt and cannot be replaced while it may be in use (${generationNativeDir}): ${detail}`);
5486
+ if (!isCorruptRuntimeGeneration(error, candidate))
5487
+ throw error;
5488
+ if (candidateFingerprint !== undefined) {
5489
+ const current = await lstatOrUndefined(candidate);
5490
+ if (current && await candidateIdentity(candidate, current) === candidateFingerprint)
5491
+ corruptGenerationMemo.set(candidate, {
5492
+ identity: candidateFingerprint,
5493
+ reason: error instanceof Error ? error.message : String(error)
5494
+ });
5495
+ }
5496
+ if (!options.repairCorruptGeneration) {
5497
+ const detail = error instanceof Error ? error.message : String(error);
5498
+ throw new Error(`Embedded Postgres runtime generation is corrupt and cannot be replaced while it may be in use (${candidate}): ${detail}`);
5499
+ }
5500
+ if (!options.publicationLease?.refresh())
5501
+ throw new RuntimePublicationLeaseLostError("Embedded Postgres runtime repair lost its setup lease.");
5502
+ continue;
5444
5503
  }
5504
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while selecting an existing generation.");
5505
+ return candidate;
5445
5506
  }
5507
+ if (generationNativeDir === undefined)
5508
+ throw new Error("Embedded Postgres runtime repair slots are exhausted; preserve the existing generations.");
5509
+ if (options.reuseOnly)
5510
+ throw new RuntimeGenerationMissingError;
5446
5511
  const stageOwner = options.publicationLease?.ownerToken ?? `unmanaged-${process.pid}-${crypto.randomUUID()}`;
5447
5512
  const stagedRoot = join(copiedRuntimeDir, `.native-staged-${process.pid}-${crypto.randomUUID()}`);
5448
5513
  const stagedNativeDir = join(stagedRoot, STAGE_PAYLOAD_DIR);
@@ -5451,25 +5516,50 @@ async function findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, co
5451
5516
  try {
5452
5517
  await progress();
5453
5518
  await cp(sourceNativeDir, stagedNativeDir, { recursive: true, verbatimSymlinks: true });
5454
- const copiedSnapshot = await snapshotSourceRuntime(stagedNativeDir, publisher, progress);
5455
- if (copiedSnapshot.sourceIdentity !== sourceSnapshot.sourceIdentity) {
5456
- throw new Error("Copied embedded Postgres runtime did not match its source package.");
5457
- }
5458
- await sealRuntimeForPublisher(stagedNativeDir, publisher, runner, progress);
5459
- if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5460
- throw new Error("Sealed embedded Postgres runtime did not match its source package.");
5461
- }
5519
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while preparing a generation.");
5520
+ await sealRuntimeForPublisher(stagedNativeDir, publisher, runner, progress, needsPrivilegeDrop);
5462
5521
  await options.beforePublish?.(stagedNativeDir);
5463
- if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5522
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while preparing a generation.");
5523
+ const manifest = await snapshotSealedManifest(stagedNativeDir, progress);
5524
+ if (manifest.sealedIdentity !== sourceSnapshot.sealedIdentity)
5464
5525
  throw new Error("Embedded Postgres runtime changed after sealed validation and before publication.");
5465
- }
5526
+ await writeFile(join(stagedNativeDir, RUNTIME_MARKER), JSON.stringify(manifest), { mode: 292, flag: "wx" });
5527
+ await chmod(join(stagedNativeDir, RUNTIME_MARKER), 292);
5466
5528
  await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while preparing a generation.");
5467
- assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
5468
5529
  await progress();
5469
- await rename(stagedNativeDir, generationNativeDir);
5530
+ assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
5531
+ try {
5532
+ await (options.renameStage ?? rename)(stagedNativeDir, generationNativeDir);
5533
+ assertPublicationLease(options, "Embedded Postgres runtime lost its setup lease after publication.");
5534
+ legacyMemo.delete(generationNativeDir);
5535
+ corruptGenerationMemo.delete(generationNativeDir);
5536
+ } catch (error) {
5537
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
5538
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "EACCES"].includes(String(code)) || !await lstatOrUndefined(generationNativeDir))
5539
+ throw error;
5540
+ if (await validatePreparedRuntime(generationNativeDir, {
5541
+ pg_ctl: join(generationNativeDir, "bin", basename(binaries.pg_ctl)),
5542
+ initdb: join(generationNativeDir, "bin", basename(binaries.initdb)),
5543
+ postgres: join(generationNativeDir, "bin", basename(binaries.postgres))
5544
+ }, progress, sourceSnapshot.sealedIdentity) !== sourceSnapshot.sealedIdentity)
5545
+ throw new CorruptRuntimeGenerationError("Concurrent runtime publication disagrees with its source.");
5546
+ assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
5547
+ return generationNativeDir;
5548
+ }
5470
5549
  await options.afterPublish?.(generationNativeDir);
5471
- if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5472
- throw new Error("Embedded Postgres published runtime changed during publication.");
5550
+ try {
5551
+ if (await validatePreparedRuntime(generationNativeDir, {
5552
+ pg_ctl: join(generationNativeDir, "bin", basename(binaries.pg_ctl)),
5553
+ initdb: join(generationNativeDir, "bin", basename(binaries.initdb)),
5554
+ postgres: join(generationNativeDir, "bin", basename(binaries.postgres))
5555
+ }, progress, sourceSnapshot.sealedIdentity) !== sourceSnapshot.sealedIdentity)
5556
+ throw new CorruptRuntimeGenerationError("sealed identity mismatch");
5557
+ } catch (error) {
5558
+ if (error instanceof CorruptRuntimeGenerationError)
5559
+ throw new Error(`Embedded Postgres published runtime changed during publication: ${error.message}`, {
5560
+ cause: error
5561
+ });
5562
+ throw error;
5473
5563
  }
5474
5564
  await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed during publication.");
5475
5565
  await options.afterPublishValidation?.(generationNativeDir);
@@ -5480,36 +5570,109 @@ async function findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, co
5480
5570
  await rm(stagedRoot, { recursive: true, force: true });
5481
5571
  }
5482
5572
  }
5573
+ var SYSTEM_ACCOUNT_FILES = { group: "/etc/group", passwd: "/etc/passwd" };
5574
+ async function readAccountRecords(path, gidField) {
5575
+ try {
5576
+ return (await readFile(path, "utf8")).split(/\r?\n/u).map((line) => line.split(":")).filter((fields) => fields.length > gidField && /^\d+$/u.test(fields[gidField]));
5577
+ } catch {
5578
+ return;
5579
+ }
5580
+ }
5581
+ async function isUserPrivateGroup(gid, account, files = SYSTEM_ACCOUNT_FILES) {
5582
+ const groups = await readAccountRecords(files.group, 2);
5583
+ const users = await readAccountRecords(files.passwd, 3);
5584
+ if (groups === undefined || users === undefined)
5585
+ return false;
5586
+ const entries = groups.filter((fields) => Number(fields[2]) === gid);
5587
+ if (entries.length === 0)
5588
+ return false;
5589
+ const primaryMembers = users.filter((fields) => Number(fields[3]) === gid);
5590
+ if (primaryMembers.some((fields) => !/^\d+$/u.test(fields[2]) || Number(fields[2]) !== account.uid))
5591
+ return false;
5592
+ const supplementaryMembers = entries.flatMap((fields) => (fields[3] ?? "").split(",").map((member) => member.trim()).filter((member) => member !== ""));
5593
+ if (supplementaryMembers.some((member) => member !== account.username))
5594
+ return false;
5595
+ return primaryMembers.length + supplementaryMembers.length > 0;
5596
+ }
5597
+ function publisherAccount(publisher) {
5598
+ return {
5599
+ uid: publisher.uid,
5600
+ username: process.getuid?.() === publisher.uid ? userInfo().username : undefined
5601
+ };
5602
+ }
5603
+ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat, privateGroup = (gid) => isUserPrivateGroup(gid, publisherAccount(publisher))) {
5604
+ if (!isAbsolute(path))
5605
+ throw new Error(`Embedded Postgres runtime cache override must be absolute: ${path}`);
5606
+ await mkdir(path, { recursive: true, mode: 493 });
5607
+ const stat = await inspect(path);
5608
+ if (!stat.isDirectory() || stat.isSymbolicLink() || process.getuid !== undefined && stat.uid !== publisher.uid)
5609
+ throw new Error(`Untrusted embedded Postgres runtime cache directory: ${path}`);
5610
+ let ancestor = await realpath(path);
5611
+ while (true) {
5612
+ const info = await inspect(ancestor);
5613
+ const sticky = (info.mode & 512) !== 0;
5614
+ const writableByOthers = !sticky && (info.mode & 2) !== 0;
5615
+ const writableByGroup = !sticky && (info.mode & 16) !== 0;
5616
+ if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || writableByOthers || writableByGroup && (info.gid !== publisher.gid || !await privateGroup(info.gid))))
5617
+ throw new Error(`Untrusted embedded Postgres runtime cache directory ancestor: ${ancestor}`);
5618
+ if (needsPrivilegeDrop && owner && publisher.uid === 0 && process.platform !== "win32") {
5619
+ const execute = info.uid === owner.uid ? 64 : info.gid === owner.gid ? 8 : 1;
5620
+ if ((info.mode & execute) === 0)
5621
+ throw new Error(`Embedded Postgres dropped owner cannot traverse runtime cache directory: ${ancestor}`);
5622
+ }
5623
+ const parent = dirname(ancestor);
5624
+ if (parent === ancestor)
5625
+ break;
5626
+ ancestor = parent;
5627
+ }
5628
+ if (needsPrivilegeDrop)
5629
+ await chown(path, publisher.uid, publisher.gid);
5630
+ await chmod(path, 493);
5631
+ }
5483
5632
 
5484
5633
  class SourceRuntimeChangedError extends Error {
5485
5634
  }
5635
+
5636
+ class RuntimePublicationLeaseLostError extends Error {
5637
+ }
5638
+
5639
+ class CorruptRuntimeGenerationError extends Error {
5640
+ }
5641
+
5642
+ class RuntimeGenerationMissingError extends Error {
5643
+ }
5644
+ function isCorruptRuntimeGeneration(error, candidate) {
5645
+ if (error instanceof CorruptRuntimeGenerationError)
5646
+ return true;
5647
+ if (!(error instanceof Error))
5648
+ return false;
5649
+ const code = "code" in error ? error.code : undefined;
5650
+ const path = "path" in error ? error.path : undefined;
5651
+ return (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP" || code === "EACCES") && typeof path === "string" && (path === candidate || path.startsWith(`${candidate}${sep}`));
5652
+ }
5486
5653
  async function assertSourceSnapshotUnchanged(sourceNativeDir, expected, publisher, progress, message) {
5487
- const current = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
5654
+ const current = await memoizedSourceSnapshot(sourceNativeDir, process.env.ATOMIC_POSTGRES_RUNTIME_CACHE_DIR ?? "", publisher, progress);
5488
5655
  if (current.sourceIdentity !== expected.sourceIdentity || current.sealedIdentity !== expected.sealedIdentity) {
5489
5656
  throw new SourceRuntimeChangedError(message);
5490
5657
  }
5491
5658
  }
5492
5659
  function assertPublicationLease(options, message) {
5493
5660
  if (options.publicationLease !== undefined && !options.publicationLease.refresh())
5494
- throw new Error(message);
5661
+ throw new RuntimePublicationLeaseLostError(message);
5495
5662
  }
5496
5663
  function runtimeProgress(options) {
5497
5664
  let operations = 0;
5498
5665
  const yieldToEventLoop = options.yieldToEventLoop ?? (() => new Promise((resolve) => setImmediate(resolve)));
5499
- return async () => {
5500
- if (operations % TRAVERSAL_OPERATIONS_PER_YIELD === 0) {
5501
- if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
5502
- throw new Error("Embedded Postgres runtime publication lost its setup lease.");
5503
- }
5504
- if (operations > 0) {
5505
- await yieldToEventLoop();
5506
- if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
5507
- throw new Error("Embedded Postgres runtime publication lost its setup lease.");
5508
- }
5509
- }
5666
+ return Object.assign(async () => {
5667
+ if (options.publicationLease?.isLost?.())
5668
+ throw new RuntimePublicationLeaseLostError("Embedded Postgres runtime publication lost its setup lease.");
5669
+ if (operations > 0 && operations % TRAVERSAL_OPERATIONS_PER_YIELD === 0) {
5670
+ await yieldToEventLoop();
5671
+ if (options.publicationLease?.isLost?.())
5672
+ throw new RuntimePublicationLeaseLostError("Embedded Postgres runtime publication lost its setup lease.");
5510
5673
  }
5511
5674
  operations += 1;
5512
- };
5675
+ }, { onContentRead: options.onContentRead });
5513
5676
  }
5514
5677
  async function snapshotSourceRuntime(root, publisher, progress) {
5515
5678
  const rootStat = await lstat(root);
@@ -5543,46 +5706,300 @@ async function hashSourceEntry(sourceHash, sealedHash, path, relativePath, rootR
5543
5706
  await hashFileInto([sourceHash, sealedHash], path, progress);
5544
5707
  return;
5545
5708
  }
5546
- throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5709
+ throw new CorruptRuntimeGenerationError(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5710
+ }
5711
+ async function memoizedSourceSnapshot(root, cacheDir, publisher, progress, options = {}) {
5712
+ const realRoot = await realpath(root);
5713
+ const key = `${publisher.uid}:${publisher.gid}:${realRoot}`;
5714
+ const packageSignature = await installedPackageSignature(realRoot);
5715
+ const indexPath = cacheDir ? join(cacheDir, ".atomic-source-index.json") : undefined;
5716
+ const cached = sourceMemo.get(key);
5717
+ const refreshSource = options.refreshSourceSnapshot ?? options.repairCorruptGeneration === true;
5718
+ if (!refreshSource && packageSignature !== undefined && cached !== undefined && (cached.packageSignature ?? cached.signature) === packageSignature)
5719
+ return cached.snapshot;
5720
+ let index = {};
5721
+ if (indexPath) {
5722
+ try {
5723
+ const stat = await lstat(indexPath);
5724
+ if (!stat.isFile() || stat.isSymbolicLink() || process.getuid !== undefined && stat.uid !== publisher.uid || process.platform !== "win32" && (stat.mode & 18) !== 0)
5725
+ throw new Error("Untrusted source index");
5726
+ index = JSON.parse(await readFile(indexPath, "utf8"));
5727
+ if (!index || typeof index !== "object" || Array.isArray(index))
5728
+ throw new Error("Invalid source index");
5729
+ const entry = index[key];
5730
+ if (!refreshSource && packageSignature !== undefined && (entry?.packageSignature ?? entry?.signature) === packageSignature && /^[a-f0-9]{64}$/.test(entry.snapshot?.sourceIdentity) && /^[a-f0-9]{64}$/.test(entry.snapshot?.sealedIdentity)) {
5731
+ sourceMemo.set(key, entry);
5732
+ return entry.snapshot;
5733
+ }
5734
+ } catch {
5735
+ index = {};
5736
+ }
5737
+ }
5738
+ options.onSourceStatPass?.();
5739
+ const entries = await statRuntimeEntries(root, progress, true);
5740
+ const signature = JSON.stringify([realRoot, entries]);
5741
+ if (!refreshSource && cached?.signature === signature && (packageSignature === undefined || cached.packageSignature === packageSignature) && !sourceEntriesRacy(entries, cached.indexWrittenAt))
5742
+ return cached.snapshot;
5743
+ const entry = index[key];
5744
+ if (entry?.signature === signature && (packageSignature === undefined || entry.packageSignature === packageSignature) && !sourceEntriesRacy(entries, entry.indexWrittenAt) && /^[a-f0-9]{64}$/.test(entry.snapshot?.sourceIdentity) && /^[a-f0-9]{64}$/.test(entry.snapshot?.sealedIdentity)) {
5745
+ sourceMemo.set(key, entry);
5746
+ return entry.snapshot;
5747
+ }
5748
+ if (refreshSource)
5749
+ sourceMemo.delete(key);
5750
+ const snapshot = await snapshotSourceRuntime(root, publisher, progress);
5751
+ options.onSourceStatPass?.();
5752
+ if (signature !== JSON.stringify([await realpath(root), await statRuntimeEntries(root, progress, true)]))
5753
+ throw new SourceRuntimeChangedError("Embedded Postgres source package changed during snapshot.");
5754
+ const indexed = { snapshot, signature, packageSignature, indexWrittenAt: Date.now() };
5755
+ sourceMemo.set(key, indexed);
5756
+ if (indexPath) {
5757
+ await ensureRuntimeCacheDirectory(cacheDir, publisher);
5758
+ const temporary = `${indexPath}.${process.pid}-${crypto.randomUUID()}`;
5759
+ try {
5760
+ await writeFile(temporary, JSON.stringify({ ...index, [key]: indexed }), { mode: 384, flag: "wx" });
5761
+ await rename(temporary, indexPath);
5762
+ } catch {
5763
+ return snapshot;
5764
+ } finally {
5765
+ await rm(temporary, { force: true });
5766
+ }
5767
+ }
5768
+ return snapshot;
5769
+ }
5770
+ async function installedPackageSignature(realRoot) {
5771
+ if (process.env.ATOMIC_POSTGRES_RUNTIME_DIR !== undefined || !["native", "postgres-runtime"].includes(basename(realRoot)))
5772
+ return;
5773
+ const packageRoot = dirname(realRoot);
5774
+ const nodeModules = packageRoot.lastIndexOf(`${sep}node_modules${sep}`);
5775
+ if (nodeModules < 0)
5776
+ return;
5777
+ try {
5778
+ const manifest = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
5779
+ if (!manifest.name || !manifest.version)
5780
+ return;
5781
+ const lockRoot = packageRoot.slice(0, nodeModules + `${sep}node_modules`.length);
5782
+ let installed;
5783
+ try {
5784
+ const lock = JSON.parse(await readFile(join(lockRoot, ".package-lock.json"), "utf8"));
5785
+ const lockKey = `node_modules/${relative(lockRoot, packageRoot).split(sep).join("/")}`;
5786
+ installed = lock.packages?.[lockKey];
5787
+ } catch {
5788
+ installed = undefined;
5789
+ }
5790
+ if (installed?.version !== undefined && installed.version !== manifest.version)
5791
+ return;
5792
+ return JSON.stringify([
5793
+ await realpath(packageRoot),
5794
+ manifest.name,
5795
+ manifest.version,
5796
+ installed?.integrity,
5797
+ installed?.resolved
5798
+ ]);
5799
+ } catch {
5800
+ return;
5801
+ }
5802
+ }
5803
+ function sourceEntriesRacy(entries, indexWrittenAt) {
5804
+ if (!Number.isFinite(indexWrittenAt))
5805
+ return true;
5806
+ return entries.some((entry) => {
5807
+ const fields = entry[5]?.split(":");
5808
+ if (!fields || fields.length < 7)
5809
+ return true;
5810
+ return Number(fields.at(-5)) >= indexWrittenAt - 2000 || Number(fields.at(-4)) >= indexWrittenAt - 2000;
5811
+ });
5547
5812
  }
5548
- async function snapshotSealedRuntime(root, progress) {
5813
+ async function validatePreparedRuntime(root, binaries, progress, expected, options = {}) {
5814
+ const marker = join(root, RUNTIME_MARKER);
5815
+ await requiredRuntimeFiles(root, binaries);
5816
+ const markerStat = await lstatOrUndefined(marker);
5817
+ const markerIdentity = markerStat && `${markerStat.dev}:${markerStat.ino}:${markerStat.size}:${markerStat.mtimeMs}:${markerStat.ctimeMs}`;
5818
+ if (options.fullValidation)
5819
+ validatedMemo.delete(root);
5820
+ const cached = validatedMemo.get(root);
5821
+ if (options.quickValidation && markerStat?.isFile() && (markerStat.mode & 146) === 0) {
5822
+ let manifest;
5823
+ try {
5824
+ manifest = JSON.parse(await readFile(marker, "utf8"));
5825
+ } catch {
5826
+ throw new CorruptRuntimeGenerationError("invalid runtime completion marker");
5827
+ }
5828
+ if (manifest.version !== 1 || !Array.isArray(manifest.entries) || !/^[a-f0-9]{64}$/.test(manifest.sealedIdentity))
5829
+ throw new CorruptRuntimeGenerationError("invalid runtime completion marker");
5830
+ return manifest.sealedIdentity;
5831
+ }
5832
+ if (options.memoizedValidation && !options.fullValidation && markerIdentity && cached?.marker === markerIdentity && (expected === undefined || expected === cached.identity)) {
5833
+ return cached.identity;
5834
+ }
5835
+ let manifest;
5836
+ try {
5837
+ const markerStat = await lstat(marker);
5838
+ if (!markerStat.isFile() || (markerStat.mode & 146) !== 0)
5839
+ throw new CorruptRuntimeGenerationError("untrusted runtime completion marker");
5840
+ const text = await readFile(marker, "utf8");
5841
+ manifest = JSON.parse(text);
5842
+ if (manifest.version !== 1 || !Array.isArray(manifest.entries) || !/^[a-f0-9]{64}$/.test(manifest.sealedIdentity))
5843
+ throw new CorruptRuntimeGenerationError("invalid runtime completion marker");
5844
+ } catch (error) {
5845
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") {
5846
+ if (error instanceof CorruptRuntimeGenerationError)
5847
+ throw error;
5848
+ throw new CorruptRuntimeGenerationError("invalid runtime completion marker");
5849
+ }
5850
+ const cached = legacyMemo.get(root);
5851
+ if (cached !== undefined)
5852
+ manifest = cached;
5853
+ else {
5854
+ manifest = await snapshotSealedManifest(root, progress);
5855
+ if (expected !== undefined && manifest.sealedIdentity !== expected)
5856
+ throw new CorruptRuntimeGenerationError("legacy sealed identity mismatch");
5857
+ legacyMemo.set(root, manifest);
5858
+ }
5859
+ }
5860
+ options.onValidation?.();
5861
+ const entries = await statRuntimeEntries(root, progress, false);
5862
+ const metadataChanged = JSON.stringify(entries.map((entry) => entry[0] === "." ? entry.slice(0, 6) : entry)) !== JSON.stringify(manifest.entries.map((entry) => entry[0] === "." ? entry.slice(0, 6) : entry));
5863
+ if (metadataChanged) {
5864
+ if (JSON.stringify(entries.map((entry) => entry.slice(0, 6))) !== JSON.stringify(manifest.entries.map((entry) => entry.slice(0, 6))))
5865
+ throw new CorruptRuntimeGenerationError("runtime completion manifest mismatch");
5866
+ if ((await snapshotSealedManifest(root, progress)).sealedIdentity !== manifest.sealedIdentity)
5867
+ throw new CorruptRuntimeGenerationError("runtime completion manifest mismatch");
5868
+ }
5869
+ for (const binary of [binaries.pg_ctl, binaries.initdb, binaries.postgres]) {
5870
+ if (!entries.some(([name, kind]) => name === relative(root, binary) && kind === "file"))
5871
+ throw new CorruptRuntimeGenerationError("required Postgres executable missing");
5872
+ }
5873
+ const timezone = join("share", ...binaries.postgres.endsWith(".exe") ? [] : ["postgresql"], "timezonesets", "Default");
5874
+ if (entries.some(([name]) => name === "share") && !entries.some(([name, kind]) => name === timezone && kind === "file"))
5875
+ throw new CorruptRuntimeGenerationError("required Postgres timezone data missing");
5876
+ if (markerIdentity)
5877
+ validatedMemo.set(root, { marker: markerIdentity, identity: manifest.sealedIdentity });
5878
+ return manifest.sealedIdentity;
5879
+ }
5880
+ async function requiredRuntimeFiles(root, binaries) {
5881
+ for (const binary of [binaries.postgres, binaries.pg_ctl, binaries.initdb]) {
5882
+ if (!(await lstatOrUndefined(binary))?.isFile())
5883
+ throw new CorruptRuntimeGenerationError("required Postgres executable missing");
5884
+ }
5885
+ const share = join(root, "share");
5886
+ if (await lstatOrUndefined(share)) {
5887
+ const timezone = join(share, ...binaries.postgres.endsWith(".exe") ? [] : ["postgresql"], "timezonesets", "Default");
5888
+ if (!(await lstatOrUndefined(timezone))?.isFile())
5889
+ throw new CorruptRuntimeGenerationError("required Postgres timezone data missing");
5890
+ }
5891
+ }
5892
+ async function statRuntimeEntries(root, progress, source) {
5893
+ const entries = [];
5894
+ const rootStat = await lstat(root);
5895
+ assertRuntimeRoot(root, rootStat);
5896
+ const realRoot = await realpath(root);
5897
+ const visit = async (path, name) => {
5898
+ await progress();
5899
+ const info = await lstat(path);
5900
+ const suffix = source ? `${info.size}:${info.mode & 511}:${info.mtimeMs}:${info.ctimeMs}:${info.birthtimeMs}:${info.dev}:${info.ino}` : undefined;
5901
+ if (info.isSymbolicLink()) {
5902
+ const target = await validatedLinkTarget(path, name, realRoot);
5903
+ entries.push([
5904
+ name,
5905
+ "link",
5906
+ 0,
5907
+ info.uid,
5908
+ info.gid,
5909
+ source ? `${target}:${suffix}` : target,
5910
+ source ? undefined : [info.ctimeMs, info.ino, info.dev]
5911
+ ]);
5912
+ } else if (info.isDirectory()) {
5913
+ entries.push(source ? [name, "directory", info.mode & 511, info.uid, info.gid, suffix] : name === "." ? [name, "directory", info.mode & 511, info.uid, info.gid, undefined] : [
5914
+ name,
5915
+ "directory",
5916
+ info.mode & 511,
5917
+ info.uid,
5918
+ info.gid,
5919
+ undefined,
5920
+ [info.ctimeMs, info.ino, info.dev]
5921
+ ]);
5922
+ for (const child of (await readdir(path)).sort()) {
5923
+ if (!source && name === "." && child === RUNTIME_MARKER)
5924
+ continue;
5925
+ await visit(join(path, child), name === "." ? child : join(name, child));
5926
+ }
5927
+ } else if (info.isFile()) {
5928
+ entries.push([
5929
+ name,
5930
+ "file",
5931
+ info.mode & 511,
5932
+ info.uid,
5933
+ info.gid,
5934
+ source ? `${info.size}:${suffix}` : String(info.size),
5935
+ source ? undefined : [info.ctimeMs, info.ino, info.dev]
5936
+ ]);
5937
+ } else
5938
+ throw new CorruptRuntimeGenerationError(`Unsupported runtime entry: ${name}`);
5939
+ };
5940
+ await visit(root, ".");
5941
+ return entries;
5942
+ }
5943
+ async function snapshotSealedManifest(root, progress) {
5549
5944
  const rootStat = await lstat(root);
5550
5945
  assertRuntimeRoot(root, rootStat);
5551
5946
  const rootRealPath = await realpath(root);
5552
5947
  const hash = createHash("sha256");
5553
- await hashSealedEntry(hash, root, ".", rootRealPath, progress);
5554
- return hash.digest("hex");
5948
+ const entries = [];
5949
+ await hashSealedEntry(hash, root, ".", rootRealPath, progress, entries);
5950
+ return { version: 1, sealedIdentity: hash.digest("hex"), entries };
5555
5951
  }
5556
- async function hashSealedEntry(hash, path, relativePath, rootRealPath, progress) {
5952
+ async function hashSealedEntry(hash, path, relativePath, rootRealPath, progress, entries) {
5557
5953
  await progress();
5558
5954
  const stat = await lstat(path);
5559
5955
  if (stat.isSymbolicLink()) {
5560
5956
  const target = await validatedLinkTarget(path, relativePath, rootRealPath);
5957
+ entries.push([relativePath, "link", 0, stat.uid, stat.gid, target, [stat.ctimeMs, stat.ino, stat.dev]]);
5561
5958
  hashField(hash, "link", relativePath, String(stat.uid), String(stat.gid), target);
5562
5959
  return;
5563
5960
  }
5564
5961
  if (stat.isDirectory()) {
5565
5962
  hashField(hash, "directory", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid));
5963
+ entries.push(relativePath === "." ? [relativePath, "directory", stat.mode & 511, stat.uid, stat.gid, undefined] : [
5964
+ relativePath,
5965
+ "directory",
5966
+ stat.mode & 511,
5967
+ stat.uid,
5968
+ stat.gid,
5969
+ undefined,
5970
+ [stat.ctimeMs, stat.ino, stat.dev]
5971
+ ]);
5566
5972
  for (const entry of (await readdir(path)).sort()) {
5567
- await hashSealedEntry(hash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, progress);
5973
+ if (relativePath === "." && entry === RUNTIME_MARKER)
5974
+ continue;
5975
+ await hashSealedEntry(hash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, progress, entries);
5568
5976
  }
5569
5977
  return;
5570
5978
  }
5571
5979
  if (stat.isFile()) {
5980
+ entries.push([
5981
+ relativePath,
5982
+ "file",
5983
+ stat.mode & 511,
5984
+ stat.uid,
5985
+ stat.gid,
5986
+ String(stat.size),
5987
+ [stat.ctimeMs, stat.ino, stat.dev]
5988
+ ]);
5572
5989
  hashField(hash, "file", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid), String(stat.size));
5573
5990
  await hashFileInto([hash], path, progress);
5574
5991
  return;
5575
5992
  }
5576
- throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5993
+ throw new CorruptRuntimeGenerationError(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5577
5994
  }
5578
5995
  async function validatedLinkTarget(path, relativePath, rootRealPath) {
5579
5996
  const target = await readlink(path);
5580
5997
  if (isAbsolute(target))
5581
- throw new Error(`Embedded Postgres runtime contains an absolute link: ${relativePath}`);
5998
+ throw new CorruptRuntimeGenerationError(`Embedded Postgres runtime contains an absolute link: ${relativePath}`);
5582
5999
  const resolvedTarget = await realpath(path);
5583
6000
  const targetFromRoot = relative(rootRealPath, resolvedTarget);
5584
6001
  if (targetFromRoot === ".." || targetFromRoot.startsWith(`..${sep}`) || isAbsolute(targetFromRoot)) {
5585
- throw new Error(`Embedded Postgres runtime link escapes its tree: ${relativePath}`);
6002
+ throw new CorruptRuntimeGenerationError(`Embedded Postgres runtime link escapes its tree: ${relativePath}`);
5586
6003
  }
5587
6004
  return target;
5588
6005
  }
@@ -5595,6 +6012,7 @@ async function hashFileInto(hashes, path, progress) {
5595
6012
  if (bytesRead === 0)
5596
6013
  return;
5597
6014
  const chunk = buffer.subarray(0, bytesRead);
6015
+ progress.onContentRead?.(path);
5598
6016
  for (const hash of hashes)
5599
6017
  hash.update(chunk);
5600
6018
  await progress();
@@ -5603,10 +6021,12 @@ async function hashFileInto(hashes, path, progress) {
5603
6021
  await handle.close();
5604
6022
  }
5605
6023
  }
5606
- async function sealRuntimeForPublisher(runtimeDir, publisher, runner, progress) {
5607
- const result = await runner("chown", ["-R", `${publisher.uid}:${publisher.gid}`, runtimeDir]);
5608
- if (result.exitCode !== 0) {
5609
- throw new Error(`Could not seal the copied embedded Postgres runtime: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`);
6024
+ async function sealRuntimeForPublisher(runtimeDir, publisher, runner, progress, needsPrivilegeDrop) {
6025
+ if (needsPrivilegeDrop) {
6026
+ const result = await runner("chown", ["-R", `${publisher.uid}:${publisher.gid}`, runtimeDir]);
6027
+ if (result.exitCode !== 0) {
6028
+ throw new Error(`Could not seal the copied embedded Postgres runtime: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`);
6029
+ }
5610
6030
  }
5611
6031
  await sealRuntimeModes(runtimeDir, progress, true);
5612
6032
  }
@@ -5655,7 +6075,7 @@ function publisherIdentity() {
5655
6075
  }
5656
6076
  function assertRuntimeRoot(root, stat) {
5657
6077
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
5658
- throw new Error(`Embedded Postgres runtime must be a real directory: ${root}`);
6078
+ throw new CorruptRuntimeGenerationError(`Embedded Postgres runtime must be a real directory: ${root}`);
5659
6079
  }
5660
6080
  }
5661
6081
  async function lstatOrUndefined(path) {
@@ -5757,6 +6177,13 @@ function resolveEmbeddedPostgresTarget(host) {
5757
6177
  // dist/builtin/workflows/src/durable/dbos-postgres-health.ts
5758
6178
  var HEALTH_INTERVAL_MS = 5000;
5759
6179
  var RECOVERY_ATTEMPTS = 3;
6180
+ function isMonitoringConnectionFailure(error) {
6181
+ if (!(error instanceof Error))
6182
+ return false;
6183
+ if ("code" in error)
6184
+ return ["ECONNREFUSED", "ECONNRESET", "EPIPE", "ETIMEDOUT", "57P01", "57P02", "57P03"].includes(String(error.code));
6185
+ return error.message === "timeout expired" || error.message === "Connection terminated due to connection timeout";
6186
+ }
5760
6187
 
5761
6188
  class PostgresHealth {
5762
6189
  operations;
@@ -5765,6 +6192,7 @@ class PostgresHealth {
5765
6192
  stopped = false;
5766
6193
  available;
5767
6194
  attempts = 0;
6195
+ nextRecoveryAt = 0;
5768
6196
  failure;
5769
6197
  revision = 0;
5770
6198
  listeners = new Set;
@@ -5822,7 +6250,21 @@ class PostgresHealth {
5822
6250
  }
5823
6251
  async probe() {
5824
6252
  const revision = this.revision;
5825
- const identity = await this.operations.probe();
6253
+ let identity;
6254
+ try {
6255
+ identity = await this.operations.probe();
6256
+ } catch (error) {
6257
+ if (!isMonitoringConnectionFailure(error) || this.stopped)
6258
+ throw error;
6259
+ try {
6260
+ identity = await this.operations.probe();
6261
+ } catch (retryError) {
6262
+ if (!isMonitoringConnectionFailure(retryError))
6263
+ throw retryError;
6264
+ this.failure = retryError;
6265
+ return;
6266
+ }
6267
+ }
5826
6268
  if (revision !== this.revision)
5827
6269
  return;
5828
6270
  if (this.stopped)
@@ -5833,6 +6275,7 @@ class PostgresHealth {
5833
6275
  this.invalidate();
5834
6276
  this.available = identity;
5835
6277
  this.attempts = 0;
6278
+ this.nextRecoveryAt = 0;
5836
6279
  return identity.url;
5837
6280
  }
5838
6281
  async refresh() {
@@ -5849,6 +6292,8 @@ class PostgresHealth {
5849
6292
  if (this.attempts === 0)
5850
6293
  this.failure = new DbosDependencyError("Managed PostgreSQL failed its live health check.");
5851
6294
  this.invalidate();
6295
+ if ((this.operations.now ?? Date.now)() < this.nextRecoveryAt)
6296
+ throw new DbosDependencyError("Managed Postgres recovery is cooling down after bounded attempts.");
5852
6297
  while (!this.stopped && this.attempts < RECOVERY_ATTEMPTS) {
5853
6298
  const attempt = this.attempts++;
5854
6299
  if (attempt > 0)
@@ -5864,15 +6309,18 @@ class PostgresHealth {
5864
6309
  this.failure = error instanceof Error ? error : new Error(String(error));
5865
6310
  }
5866
6311
  }
6312
+ this.attempts = 0;
6313
+ this.nextRecoveryAt = (this.operations.now ?? Date.now)() + HEALTH_INTERVAL_MS;
5867
6314
  throw new DbosDependencyError("Managed Postgres is unavailable after bounded recovery. Preserve its data and ownership records.");
5868
6315
  }
5869
6316
  }
5870
6317
 
5871
6318
  // dist/builtin/workflows/src/durable/dbos-postgres-identity.ts
5872
6319
  import { existsSync as existsSync2, lstatSync as lstatSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
6320
+ import { createRequire as createRequire2 } from "node:module";
5873
6321
  import { createServer } from "node:net";
5874
6322
  import { endianness } from "node:os";
5875
- import { join as join3 } from "node:path";
6323
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
5876
6324
 
5877
6325
  // dist/builtin/workflows/src/durable/dbos-postgres-ownership.ts
5878
6326
  import { randomUUID } from "node:crypto";
@@ -6037,6 +6485,30 @@ function availablePostgresPort(preferred) {
6037
6485
  });
6038
6486
  });
6039
6487
  }
6488
+ function managedPostgresRuntimeHealthy(metadata, port = metadata.server?.port) {
6489
+ return postgresRuntimeFilesExist(managedPostgresLaunchExecutable(metadata, port));
6490
+ }
6491
+ function managedPostgresLaunchExecutable(metadata, port = metadata.server?.port) {
6492
+ const optsPath = join3(metadata.dataDir, "postmaster.opts");
6493
+ if (!lstatSync2(optsPath).isFile())
6494
+ throw new Error("Managed Postgres launch options are missing or untrusted.");
6495
+ const command = readFileSync2(optsPath, "utf8").trimEnd();
6496
+ const launch = /^(.*[\\/]postgres(?:\.exe)?) "-D" "([^"]+)" "-p" "(\d+)" "-c" "listen_addresses=127\.0\.0\.1"/.exec(command);
6497
+ const collector = ' "-c" "logging_collector=on" "-c" "log_directory=log" "-c" "log_filename=postgresql-%a.log" "-c" "log_truncate_on_rotation=on" "-c" "log_rotation_age=1d" "-c" "log_rotation_size=0"';
6498
+ const unsafe = ' "-c" "fsync=off" "-c" "synchronous_commit=off" "-c" "full_page_writes=off"';
6499
+ if (!launch || !isAbsolute2(launch[1]) || !isAbsolute2(launch[2]) || !["", collector, collector + unsafe].includes(command.slice(launch[0].length))) {
6500
+ throw new Error("Managed Postgres launch options do not identify Atomic's PostgreSQL runtime.");
6501
+ }
6502
+ if (realpathSync2(launch[2]) !== metadata.dataDir || port !== undefined && Number(launch[3]) !== port) {
6503
+ throw new Error("Managed Postgres launch options do not match its owned data directory and port.");
6504
+ }
6505
+ return launch[1];
6506
+ }
6507
+ function postgresRuntimeFilesExist(postgres) {
6508
+ const native = dirname2(dirname2(postgres));
6509
+ const timezoneSets = join3(native, "share", ...postgres.endsWith(".exe") ? [] : ["postgresql"], "timezonesets");
6510
+ return lstatSync2(postgres, { throwIfNoEntry: false })?.isFile() === true && lstatSync2(timezoneSets, { throwIfNoEntry: false })?.isDirectory() === true && lstatSync2(join3(timezoneSets, "Default"), { throwIfNoEntry: false })?.isFile() === true;
6511
+ }
6040
6512
  function managedPostmaster(metadata) {
6041
6513
  const systemIdentifier = managedSystemIdentifier(metadata);
6042
6514
  const path = join3(metadata.dataDir, "postmaster.pid");
@@ -6073,6 +6545,27 @@ var POSTGRES_IDENTITY_SQL = `SELECT current_setting('data_directory') AS data_di
6073
6545
  inet_server_port() AS port, host(inet_server_addr()) AS host,
6074
6546
  split_part(pg_read_file('postmaster.pid'), E'\\n', 3) AS started,
6075
6547
  system_identifier::text, current_setting('server_version') AS server_version FROM pg_control_system()`;
6548
+ var POSTGRES_TIMEZONE_SQL = "SELECT set_config('timezone_abbreviations', 'Default', true)";
6549
+ async function probePostgresTimezoneData(port) {
6550
+ const client = new Client({
6551
+ host: "127.0.0.1",
6552
+ port,
6553
+ user: "postgres",
6554
+ password: "atomic",
6555
+ database: "postgres",
6556
+ ssl: false,
6557
+ connectionTimeoutMillis: 1000,
6558
+ query_timeout: 1000,
6559
+ statement_timeout: 1000
6560
+ });
6561
+ client.on("error", () => {});
6562
+ try {
6563
+ await client.connect();
6564
+ await client.query(POSTGRES_TIMEZONE_SQL);
6565
+ } finally {
6566
+ await client.end();
6567
+ }
6568
+ }
6076
6569
  async function probePostgresIdentity(port) {
6077
6570
  const client = new Client({
6078
6571
  host: "127.0.0.1",
@@ -6099,6 +6592,27 @@ async function probePostgresIdentity(port) {
6099
6592
  await client.end();
6100
6593
  }
6101
6594
  }
6595
+ function verifyManagedPostmasterProcess(metadata, expected) {
6596
+ const pidPath = join3(metadata.dataDir, "postmaster.pid");
6597
+ const before = managedPostmaster(metadata);
6598
+ if (metadata.server?.pid !== expected.pid || metadata.server.started !== expected.started || metadata.server.port !== expected.port || metadata.server.systemIdentifier !== expected.systemIdentifier)
6599
+ throw new Error("Managed Postgres published process identity mismatch. Preserve the server and data directory.");
6600
+ if (!before)
6601
+ return { status: "absent" };
6602
+ const beforeFile = readFileSync2(pidPath, "utf8");
6603
+ if (before.pid !== expected.pid || before.started !== expected.started || before.port !== expected.port || before.systemIdentifier !== expected.systemIdentifier || before.pid === process.pid || before.pid === process.ppid || realpathSync2(beforeFile.split(/\r?\n/)[1]) !== metadata.dataDir)
6604
+ throw new Error("Managed Postgres process identity mismatch. Preserve the server and data directory.");
6605
+ const binding = createRequire2(import.meta.url)("@bastani/atomic-natives");
6606
+ const identity = binding.postgresProcessStartTime(before.pid);
6607
+ if (readFileSync2(pidPath, "utf8") !== beforeFile)
6608
+ throw new Error("Managed Postgres OS process start identity mismatch. Preserve the server and data directory.");
6609
+ if (!identity.found)
6610
+ return { status: "absent" };
6611
+ if (identity.startTime === undefined || !Number.isFinite(identity.startTime) || identity.startTime <= 0 || identity.startTime > before.started + 1) {
6612
+ throw new Error("Managed Postgres OS process start identity mismatch. Preserve the server and data directory.");
6613
+ }
6614
+ return { status: "live", server: before, observedCreateTime: identity.startTime };
6615
+ }
6102
6616
  async function verifyPostgresIdentity(metadata, port, expectedPid, probe = probePostgresIdentity) {
6103
6617
  const before = managedPostmaster(metadata);
6104
6618
  if (!before)
@@ -6157,25 +6671,14 @@ class EmbeddedPostgresCleanupPendingError extends AggregateError {
6157
6671
  var activeCluster;
6158
6672
  var ensureOperation = ensure;
6159
6673
  var retainedPostgresSpawnerOverride;
6674
+ var windowsPostgresGuardOverride;
6160
6675
  var ensured;
6161
6676
  var consumer;
6162
6677
  var initializing = false;
6163
6678
  var health;
6164
- var lastFailure;
6165
- function embeddedPostgresLastFailure() {
6166
- return health?.lastFailure ?? lastFailure;
6167
- }
6168
6679
  function embeddedPostgresHealth() {
6169
6680
  return health;
6170
6681
  }
6171
- async function recoverEmbeddedPostgres(context, metadata) {
6172
- if (activeCluster && !activeCluster.shared)
6173
- throw new EmbeddedPostgresCleanupPendingError([], "Managed Postgres cleanup is still pending.");
6174
- activeCluster?.lease.release();
6175
- activeCluster = undefined;
6176
- await ensureCluster({ context, recovery: metadata });
6177
- ensured ??= Promise.resolve();
6178
- }
6179
6682
  function ensureEmbeddedDbosPostgres() {
6180
6683
  if (ensured !== undefined && !initializing && health !== undefined)
6181
6684
  return health.check().then(() => {});
@@ -6186,7 +6689,6 @@ function ensureEmbeddedDbosPostgres() {
6186
6689
  initializing = true;
6187
6690
  ensured ??= ensureOperation().catch((error) => {
6188
6691
  ensured = undefined;
6189
- lastFailure = error instanceof Error ? error : new Error(String(error));
6190
6692
  throw error;
6191
6693
  }).finally(() => {
6192
6694
  initializing = false;
@@ -6215,8 +6717,9 @@ async function ensureCluster(options = {}) {
6215
6717
  chmodSync(root, 493);
6216
6718
  }
6217
6719
  let startedCluster;
6218
- try {
6219
- await withSetupLock(join4(root, `v${EMBEDDED_PG_MAJOR}.setup-lock`), async (setup) => {
6720
+ await withSetupLock(join4(root, `v${EMBEDDED_PG_MAJOR}.setup-lock`), async (setup) => {
6721
+ let adoptedRegistry;
6722
+ try {
6220
6723
  await cleanupAbandonedRuntimeStages(root, setup.abandonedRuntimeStageOwnerTokens);
6221
6724
  const preferredPort = preferredPostgresPort();
6222
6725
  const registered = existsSync3(postgresOwnershipDirectory(root, EMBEDDED_PG_MAJOR));
@@ -6229,10 +6732,13 @@ async function ensureCluster(options = {}) {
6229
6732
  if (!existsSync3(join4(dataDir, "PG_VERSION")) && registered) {
6230
6733
  throw new Error(`Managed Postgres data is missing PG_VERSION; preserve its ownership records: ${dataDir}`);
6231
6734
  }
6232
- if (!registered && existsSync3(dataDir) && readdirSync2(dataDir).length > 0) {
6735
+ const unregisteredData = !registered && existsSync3(dataDir) && readdirSync2(dataDir).length > 0;
6736
+ if (unregisteredData && (options.recovery || !launchedByPreOwnershipAtomic(dataDir))) {
6233
6737
  throw new Error(`Refusing to adopt unregistered Postgres data: ${dataDir}. Preserve it and configure DBOS_SYSTEM_DATABASE_URL explicitly.`);
6234
6738
  }
6235
- let metadata = registered ? managedPostgresMetadata(root, EMBEDDED_PG_MAJOR, false) : undefined;
6739
+ let metadata = registered || unregisteredData ? managedPostgresMetadata(root, EMBEDDED_PG_MAJOR, unregisteredData) : undefined;
6740
+ if (unregisteredData)
6741
+ adoptedRegistry = postgresOwnershipDirectory(root, EMBEDDED_PG_MAJOR);
6236
6742
  if (options.recovery && !metadata)
6237
6743
  throw new Error("Managed Postgres recovery requires existing ownership records.");
6238
6744
  if (options.recovery && (metadata?.clusterId !== options.recovery.clusterId || metadata.directoryIdentity !== options.recovery.directoryIdentity || metadata.server?.systemIdentifier !== options.recovery.server?.systemIdentifier)) {
@@ -6244,18 +6750,135 @@ async function ensureCluster(options = {}) {
6244
6750
  throw new Error("Managed Postgres published process identity mismatch. Preserve the cluster and ownership records.");
6245
6751
  }
6246
6752
  let verified;
6753
+ const existingServerProbe = () => options.probeIdentity ?? probePostgresIdentity;
6247
6754
  let prepared = options.prepared ? options.binaries : undefined;
6248
- if (existing) {
6755
+ let selectedIdentity = options.runtimeIdentity;
6756
+ let reservedLiveGeneration;
6757
+ const verifyReplacementSource = async (source) => {
6758
+ if (!postgresRuntimeFilesExist(source.postgres)) {
6759
+ throw new Error("Replacement managed Postgres source runtime is incomplete; preserving the running server.");
6760
+ }
6761
+ if (options.probeIdentity !== undefined)
6762
+ return;
6763
+ hydrateBinaryLibraryLinks(source.pg_ctl);
6764
+ for (const binary of [source.postgres, source.pg_ctl, source.initdb]) {
6765
+ const result = await runLocalCommand(binary, ["--version"]);
6766
+ const version = /\(PostgreSQL\)\s+(\d+)\b/.exec(result.stdout);
6767
+ if (result.exitCode !== 0 || Number(version?.[1]) !== EMBEDDED_PG_MAJOR)
6768
+ throw new Error(`incompatible PostgreSQL runtime: ${binary} --version expected major ${EMBEDDED_PG_MAJOR}: ${commandFailureDetail(result)}`);
6769
+ }
6770
+ };
6771
+ const prepareRetainedRuntime = async (source, reservedGeneration, quickValidation = false, fullValidation = false, refreshSourceSnapshot = false) => {
6772
+ const cacheDir = process.env.ATOMIC_POSTGRES_RUNTIME_CACHE_DIR;
6773
+ if (cacheDir === undefined)
6774
+ return prepareBinariesForOwner(source, context, undefined, {
6775
+ publicationLease: setup.runtimePublicationLease,
6776
+ repairCorruptGeneration: true,
6777
+ refreshSourceSnapshot,
6778
+ reservedGeneration,
6779
+ quickValidation,
6780
+ memoizedValidation: true,
6781
+ fullValidation
6782
+ });
6783
+ await ensureRuntimeCacheDirectory(cacheDir, undefined, context.owner !== undefined);
6784
+ try {
6785
+ return await prepareBinariesForOwner(source, context, undefined, {
6786
+ publicationLease: setup.runtimePublicationLease,
6787
+ repairCorruptGeneration: true,
6788
+ refreshSourceSnapshot,
6789
+ reservedGeneration,
6790
+ quickValidation,
6791
+ fullValidation,
6792
+ memoizedValidation: true,
6793
+ reuseOnly: true
6794
+ });
6795
+ } catch (error) {
6796
+ if (!(error instanceof RuntimeGenerationMissingError))
6797
+ throw error;
6798
+ }
6799
+ let result;
6800
+ await withSetupLock(join4(cacheDir, ".publication-lock"), async (cache) => {
6801
+ await cleanupAbandonedRuntimeStages(cacheDir, cache.abandonedRuntimeStageOwnerTokens);
6802
+ result = await prepareBinariesForOwner(source, context, undefined, {
6803
+ publicationLease: {
6804
+ ownerToken: cache.runtimePublicationLease.ownerToken,
6805
+ refresh: () => cache.runtimePublicationLease.refresh() && setup.runtimePublicationLease.refresh(),
6806
+ isLost: () => cache.runtimePublicationLease.isLost?.() === true || setup.runtimePublicationLease.isLost?.() === true
6807
+ },
6808
+ repairCorruptGeneration: true,
6809
+ refreshSourceSnapshot,
6810
+ reservedGeneration,
6811
+ quickValidation,
6812
+ fullValidation,
6813
+ memoizedValidation: true
6814
+ });
6815
+ }, { attempts: READY_ATTEMPTS * 4 });
6816
+ if (result === undefined)
6817
+ throw new Error("Embedded Postgres runtime publication did not complete.");
6818
+ return result;
6819
+ };
6820
+ const chooseRuntime = async (mode = "start") => {
6821
+ if (prepared !== undefined && selectedIdentity !== undefined) {
6822
+ let retainedValid = false;
6823
+ try {
6824
+ retainedValid = await fingerprintPreparedRuntime(prepared, {
6825
+ publicationLease: setup.runtimePublicationLease,
6826
+ quickValidation: mode === "attach",
6827
+ memoizedValidation: mode !== "damage",
6828
+ fullValidation: mode === "damage"
6829
+ }) === selectedIdentity;
6830
+ } catch (error) {
6831
+ if (!isCorruptRuntimeGeneration(error, dirname3(dirname3(prepared.postgres))))
6832
+ throw error;
6833
+ }
6834
+ if (retainedValid)
6835
+ return prepared;
6836
+ const source = await loadEmbeddedPostgresBinaries();
6837
+ await verifyReplacementSource(source);
6838
+ const reservedGeneration = reservedLiveGeneration ?? dirname3(dirname3(prepared.postgres));
6839
+ prepared = await prepareRetainedRuntime(source, reservedGeneration, mode === "attach", mode === "damage", true);
6840
+ selectedIdentity = prepared.sealedIdentity;
6841
+ } else {
6842
+ if (prepared === undefined) {
6843
+ const source = options.binaries ?? await loadEmbeddedPostgresBinaries();
6844
+ await verifyReplacementSource(source);
6845
+ prepared = await prepareRetainedRuntime(source, reservedLiveGeneration, mode === "attach", mode === "damage", mode === "damage");
6846
+ }
6847
+ }
6848
+ if (!postgresRuntimeFilesExist(prepared.postgres) || ![prepared.pg_ctl, prepared.initdb].every((binary) => lstatSync3(binary, { throwIfNoEntry: false })?.isFile()) || prepared.sealedIdentity !== undefined && await fingerprintPreparedRuntime(prepared, {
6849
+ publicationLease: setup.runtimePublicationLease,
6850
+ quickValidation: mode === "attach",
6851
+ memoizedValidation: true
6852
+ }) !== prepared.sealedIdentity) {
6853
+ throw new Error("Replacement managed Postgres runtime is incomplete or changed; preserving the running server.");
6854
+ }
6855
+ return prepared;
6856
+ };
6857
+ if (existing && !managedPostgresRuntimeHealthy(metadata, port)) {
6858
+ reservedLiveGeneration = dirname3(dirname3(managedPostgresLaunchExecutable(metadata, existing.port)));
6859
+ prepared = await chooseRuntime("damage");
6860
+ if (adoptedRegistry !== undefined) {
6861
+ if (verifyManagedPostmasterProcess({ ...metadata, server: existing }, existing).status === "live") {
6862
+ if (!setup.runtimePublicationLease.refresh())
6863
+ throw new Error("Postgres setup lease lost before legacy adoption.");
6864
+ publishPostgresServer(root, metadata, existing);
6865
+ }
6866
+ adoptedRegistry = undefined;
6867
+ }
6868
+ if (await stopBrokenManagedPostmaster(metadata, existing, prepared.pg_ctl, context, setup.runtimePublicationLease, options.shutdownWait)) {
6869
+ activeCluster?.lease.release();
6870
+ activeCluster = undefined;
6871
+ }
6872
+ } else if (existing) {
6249
6873
  await waitForClusterReadiness(logFile, undefined, async () => {
6250
- verified = await verifyPostgresIdentity(metadata, port, existing.pid, options.probeIdentity);
6874
+ verified = await verifyPostgresIdentity(metadata, port, existing.pid, existingServerProbe());
6251
6875
  return verified !== undefined || managedPostmaster(metadata) === undefined;
6252
- }, READY_ATTEMPTS, delay, port);
6876
+ }, READY_ATTEMPTS, delay, port, dataDir);
6253
6877
  }
6878
+ if (verified)
6879
+ reservedLiveGeneration = dirname3(dirname3(managedPostgresLaunchExecutable(metadata, verified.port)));
6254
6880
  if (!verified) {
6255
- const loaded = options.binaries ?? await loadEmbeddedPostgresBinaries();
6256
- const binaries = prepared ?? await prepareBinariesForOwner(loaded, context, undefined, {
6257
- publicationLease: setup.runtimePublicationLease
6258
- });
6881
+ const binaries = await chooseRuntime();
6259
6882
  prepared = binaries;
6260
6883
  if (!existsSync3(join4(dataDir, "PG_VERSION"))) {
6261
6884
  if (options.recovery)
@@ -6274,13 +6897,15 @@ async function ensureCluster(options = {}) {
6274
6897
  if (!setup.runtimePublicationLease.refresh())
6275
6898
  throw new Error("Postgres setup lease lost before start.");
6276
6899
  try {
6277
- const lease = await startCluster(binaries.postgres, dataDir, logFile, context, port);
6900
+ const lease = await startCluster(binaries.postgres, dataDir, logFile, context, port, {
6901
+ unsafeDurability: process.env.ATOMIC_POSTGRES_TEST_UNSAFE_DURABILITY === "1"
6902
+ });
6278
6903
  startedCluster = { lease };
6279
6904
  activeCluster = startedCluster;
6280
6905
  await waitForClusterReadiness(logFile, startedCluster, async () => {
6281
6906
  verified = await verifyPostgresIdentity(metadata, port, lease.pid, options.probeIdentity);
6282
6907
  return verified !== undefined;
6283
- }, READY_ATTEMPTS, delay, port);
6908
+ }, READY_ATTEMPTS, delay, port, dataDir);
6284
6909
  break;
6285
6910
  } catch (error) {
6286
6911
  if (activeCluster !== undefined || attempt === 2 || !(error instanceof Error) || !/exited early|address already in use|EADDRINUSE/i.test(error.message) || !await isReachable(EMBEDDED_HOST, port, 1000))
@@ -6291,20 +6916,36 @@ async function ensureCluster(options = {}) {
6291
6916
  }
6292
6917
  if (!metadata || !verified)
6293
6918
  throw new Error("Managed Postgres identity was not verified.");
6919
+ if (options.probeIdentity === undefined)
6920
+ await probePostgresTimezoneData(verified.port);
6921
+ let runtimeIdentity;
6294
6922
  if (health === undefined) {
6295
- prepared ??= await prepareBinariesForOwner(options.binaries ?? await loadEmbeddedPostgresBinaries(), context, undefined, { publicationLease: setup.runtimePublicationLease });
6923
+ prepared = await chooseRuntime(verified && startedCluster === undefined ? "attach" : "start");
6924
+ runtimeIdentity = prepared.sealedIdentity ?? await fingerprintPreparedRuntime(prepared, { publicationLease: setup.runtimePublicationLease });
6296
6925
  }
6297
6926
  if (!setup.runtimePublicationLease.refresh())
6298
6927
  throw new Error("Postgres setup lease lost before attach.");
6299
6928
  publishPostgresServer(root, metadata, verified);
6929
+ adoptedRegistry = undefined;
6300
6930
  actualPort = port;
6301
6931
  inspectPostgresConsumers(root, metadata);
6302
6932
  const nextConsumer = acquirePostgresConsumer(root, metadata, `${process.execPath} | ${import.meta.url}`);
6303
6933
  consumer?.release();
6304
6934
  consumer = nextConsumer;
6935
+ if (health !== undefined && options.recovery !== undefined && prepared?.sealedIdentity !== undefined) {
6936
+ options.binaries = prepared;
6937
+ options.runtimeIdentity = selectedIdentity ?? prepared.sealedIdentity;
6938
+ }
6305
6939
  if (health === undefined) {
6306
6940
  const pinned = { ...metadata, server: verified };
6307
- const recoveryOptions = { ...options, context, binaries: prepared, prepared: true, recovery: pinned };
6941
+ const recoveryOptions = {
6942
+ ...options,
6943
+ context,
6944
+ binaries: prepared,
6945
+ prepared: true,
6946
+ recovery: pinned,
6947
+ runtimeIdentity
6948
+ };
6308
6949
  const inspect = async (probe = options.probeIdentity) => {
6309
6950
  const current = managedPostgresMetadata(root, EMBEDDED_PG_MAJOR, false);
6310
6951
  if (current.clusterId !== pinned.clusterId || current.directoryIdentity !== pinned.directoryIdentity || current.server?.systemIdentifier !== pinned.server.systemIdentifier) {
@@ -6313,11 +6954,17 @@ async function ensureCluster(options = {}) {
6313
6954
  const server = current.server;
6314
6955
  if (!server)
6315
6956
  throw new Error("Managed Postgres published identity is missing.");
6316
- const live = await verifyPostgresIdentity(current, server.port, server.pid, probe);
6957
+ if (!managedPostgresRuntimeHealthy(current, server.port)) {
6958
+ verifyManagedPostmasterProcess(current, server);
6959
+ return;
6960
+ }
6961
+ const live = await verifyPostgresIdentity(current, server.port, server.pid, probe ?? existingServerProbe());
6317
6962
  if (!live)
6318
6963
  return;
6319
6964
  if (live.started !== server.started)
6320
6965
  throw new Error("Managed Postgres published start identity mismatch.");
6966
+ if (probe === undefined)
6967
+ await probePostgresTimezoneData(live.port);
6321
6968
  actualPort = live.port;
6322
6969
  return { url: embeddedDbosSystemDatabaseUrl(), identity: JSON.stringify(live) };
6323
6970
  };
@@ -6331,6 +6978,10 @@ async function ensureCluster(options = {}) {
6331
6978
  });
6332
6979
  if (!identity)
6333
6980
  throw new DbosDependencyError;
6981
+ if (options.probeIdentity === undefined) {
6982
+ const query = { text: POSTGRES_TIMEZONE_SQL, query_timeout: 1000 };
6983
+ await client.query(query);
6984
+ }
6334
6985
  },
6335
6986
  recover: async () => {
6336
6987
  if (activeCluster && !activeCluster.shared)
@@ -6341,12 +6992,95 @@ async function ensureCluster(options = {}) {
6341
6992
  }
6342
6993
  });
6343
6994
  }
6344
- });
6345
- } catch (startupError) {
6346
- if (startupError instanceof EmbeddedPostgresCleanupPendingError)
6347
- throw startupError;
6348
- await rollbackStartedCluster(startedCluster, startupError);
6995
+ } catch (startupError) {
6996
+ if (startupError instanceof EmbeddedPostgresCleanupPendingError)
6997
+ throw startupError;
6998
+ await rollbackStartedCluster(startedCluster, startupError).catch((error) => {
6999
+ if (adoptedRegistry !== undefined && !(error instanceof EmbeddedPostgresCleanupPendingError))
7000
+ rmSync2(adoptedRegistry, { recursive: true, force: true });
7001
+ throw error;
7002
+ });
7003
+ }
7004
+ });
7005
+ }
7006
+ async function stopBrokenManagedPostmaster(metadata, verified, pgCtl, context, lease, wait = delay, platform = process.platform) {
7007
+ const check = () => {
7008
+ const current = managedPostgresMetadata(context.baseDir, metadata.major, false);
7009
+ if (current.clusterId !== metadata.clusterId || current.directoryIdentity !== metadata.directoryIdentity) {
7010
+ throw new Error("Managed Postgres restart identity changed. Preserve the server and data directory.");
7011
+ }
7012
+ return { current, process: verifyManagedPostmasterProcess(current, verified) };
7013
+ };
7014
+ const { current, process: state } = check();
7015
+ if (state.status === "absent")
7016
+ return true;
7017
+ if (managedPostgresRuntimeHealthy(current, verified.port))
7018
+ return false;
7019
+ const binding = createRequire3(import.meta.url)("@bastani/atomic-natives");
7020
+ const released = async () => {
7021
+ const identity = binding.postgresProcessStartTime(verified.pid);
7022
+ if (identity.found || managedPostmaster(current) !== undefined)
7023
+ return false;
7024
+ if (activeCluster?.lease.pid === verified.pid)
7025
+ await activeCluster.lease.wait(0);
7026
+ return true;
7027
+ };
7028
+ const signal = (mode, observedCreateTime) => {
7029
+ if (!lease.refresh())
7030
+ throw new Error("Postgres setup lease lost before stopping the verified managed server.");
7031
+ const result = binding.signalVerifiedPostgres(verified.pid, observedCreateTime, mode);
7032
+ if (result === "mismatch")
7033
+ throw new Error("Managed Postgres OS process start identity mismatch. Preserve the server and data directory.");
7034
+ };
7035
+ const waitForExit = async (guard) => {
7036
+ for (let attempt = 0;attempt < READY_ATTEMPTS; attempt++) {
7037
+ if (guard?.exited() && await released())
7038
+ return true;
7039
+ if (guard === undefined && await released())
7040
+ return true;
7041
+ await wait(READY_DELAY_MS);
7042
+ }
7043
+ return (guard === undefined || guard.exited()) && released();
7044
+ };
7045
+ const stop = async (mode, observedCreateTime) => {
7046
+ if (platform !== "win32") {
7047
+ signal(mode, observedCreateTime);
7048
+ return waitForExit();
7049
+ }
7050
+ if (!lease.refresh())
7051
+ throw new Error("Postgres setup lease lost before stopping the verified managed server.");
7052
+ const guard = windowsPostgresGuardOverride?.(verified.pid, observedCreateTime) ?? binding.guardWindowsPostgresProcess(verified.pid, observedCreateTime);
7053
+ try {
7054
+ if (guard.status === "mismatch")
7055
+ throw new Error("Managed Postgres OS process start identity mismatch. Preserve the server and data directory.");
7056
+ if (guard.status === "absent") {
7057
+ if (await released())
7058
+ return true;
7059
+ throw new Error("Managed Postgres shutdown did not release its postmaster file.");
7060
+ }
7061
+ const killed = await context.runAsOwner(pgCtl, [
7062
+ "kill",
7063
+ mode === "fast" ? "INT" : "QUIT",
7064
+ String(verified.pid)
7065
+ ]);
7066
+ if (killed.exitCode !== 0)
7067
+ throw new Error(`Could not signal the verified managed Postgres server: ${commandFailureDetail(killed)}`);
7068
+ return await waitForExit(guard);
7069
+ } finally {
7070
+ guard.close();
7071
+ }
7072
+ };
7073
+ if (await stop("fast", state.observedCreateTime))
7074
+ return true;
7075
+ const fresh = check();
7076
+ if (fresh.process.status === "absent") {
7077
+ if (await released())
7078
+ return true;
7079
+ throw new Error("Managed Postgres shutdown did not release its postmaster file.");
6349
7080
  }
7081
+ if (await stop("immediate", fresh.process.observedCreateTime))
7082
+ return true;
7083
+ throw new Error("Could not stop the verified managed Postgres server within the shutdown budget.");
6350
7084
  }
6351
7085
  async function rollbackStartedCluster(cluster, startupError) {
6352
7086
  if (cluster !== undefined && activeCluster === cluster) {
@@ -6358,13 +7092,13 @@ async function rollbackStartedCluster(cluster, startupError) {
6358
7092
  }
6359
7093
  throw startupError;
6360
7094
  }
6361
- async function waitForClusterReadiness(logFile, rollbackCluster, isReachable = tcpReachable, attempts = READY_ATTEMPTS, wait = delay, port = EMBEDDED_PORT) {
7095
+ async function waitForClusterReadiness(logFile, rollbackCluster, isReachable = tcpReachable, attempts = READY_ATTEMPTS, wait = delay, port = EMBEDDED_PORT, dataDir = join4(dirname3(logFile), "v18")) {
6362
7096
  const deadline = performance.now() + READY_ATTEMPTS * READY_DELAY_MS;
6363
7097
  try {
6364
7098
  for (let attempt = 0;attempt < attempts && performance.now() < deadline; attempt += 1) {
6365
- await assertRetainedPostgresRunning(rollbackCluster, logFile, port);
7099
+ await assertRetainedPostgresRunning(rollbackCluster, logFile, port, dataDir);
6366
7100
  if (await isReachable(EMBEDDED_HOST, port)) {
6367
- await assertRetainedPostgresRunning(rollbackCluster, logFile, port);
7101
+ await assertRetainedPostgresRunning(rollbackCluster, logFile, port, dataDir);
6368
7102
  if (rollbackCluster !== undefined)
6369
7103
  rollbackCluster.shared = true;
6370
7104
  return;
@@ -6376,7 +7110,7 @@ async function waitForClusterReadiness(logFile, rollbackCluster, isReachable = t
6376
7110
  await rollbackStartedCluster(rollbackCluster, startupError);
6377
7111
  }
6378
7112
  }
6379
- async function assertRetainedPostgresRunning(cluster, logFile, port = EMBEDDED_PORT) {
7113
+ async function assertRetainedPostgresRunning(cluster, logFile, port = EMBEDDED_PORT, dataDir = join4(dirname3(logFile), "v18")) {
6380
7114
  if (cluster === undefined)
6381
7115
  return;
6382
7116
  const observed = await cluster.lease.wait(0).catch((error) => {
@@ -6386,7 +7120,7 @@ async function assertRetainedPostgresRunning(cluster, logFile, port = EMBEDDED_P
6386
7120
  throw error;
6387
7121
  });
6388
7122
  if (observed?.exited) {
6389
- throw new Error(`The embedded Postgres process exited early before accepting connections on ${EMBEDDED_HOST}:${port}; see ${logFile}.${logTail(logFile)}`);
7123
+ throw new Error(`The embedded Postgres process exited early before accepting connections on ${EMBEDDED_HOST}:${port}; see ${logFile}.${logTail(logFile, dataDir)}`);
6390
7124
  }
6391
7125
  }
6392
7126
  function shutdownEmbeddedDbosPostgres() {
@@ -6422,6 +7156,24 @@ async function stopActiveCluster(cluster) {
6422
7156
  throw error;
6423
7157
  }
6424
7158
  }
7159
+ function launchedByPreOwnershipAtomic(dataDir) {
7160
+ const versionFile = join4(dataDir, "PG_VERSION");
7161
+ const optsFile = join4(dataDir, "postmaster.opts");
7162
+ try {
7163
+ if (!lstatSync3(versionFile).isFile() || !lstatSync3(optsFile).isFile())
7164
+ return false;
7165
+ if (readFileSync3(versionFile, "utf8").trim() !== String(EMBEDDED_PG_MAJOR))
7166
+ return false;
7167
+ const launch = /^.+[\\/]postgres(?:\.exe)? "-D" "([^"]+)" "-p" "\d+" "-c" "listen_addresses=127\.0\.0\.1"\s*$/.exec(readFileSync3(optsFile, "utf8"));
7168
+ if (!launch || !isAbsolute3(launch[1]))
7169
+ return false;
7170
+ if (launch[1] === dataDir)
7171
+ return true;
7172
+ return realpathSync3(launch[1]) === realpathSync3(dataDir);
7173
+ } catch {
7174
+ return false;
7175
+ }
7176
+ }
6425
7177
  async function initializeCluster(initdb, dataDir, context) {
6426
7178
  if (context.owner !== undefined) {
6427
7179
  mkdirSync2(dataDir, { recursive: true, mode: 448 });
@@ -6453,28 +7205,69 @@ async function initializeCluster(initdb, dataDir, context) {
6453
7205
  rmSync2(passwordFile, { force: true });
6454
7206
  }
6455
7207
  }
6456
- async function startCluster(postgres, dataDir, logFile, context, port = EMBEDDED_PORT) {
7208
+ async function startCluster(postgres, dataDir, logFile, context, port = EMBEDDED_PORT, options = {}) {
6457
7209
  try {
7210
+ let unsafeDurability = false;
7211
+ if (options.unsafeDurability) {
7212
+ const canonical = (path) => {
7213
+ const resolved = realpathSync3.native(path);
7214
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
7215
+ };
7216
+ const canonicalManagedBase = (path) => {
7217
+ try {
7218
+ return canonical(path);
7219
+ } catch (error) {
7220
+ if (error.code !== "ENOENT")
7221
+ throw error;
7222
+ return join4(canonicalManagedBase(dirname3(path)), process.platform === "win32" ? basename2(path).toLowerCase() : basename2(path));
7223
+ }
7224
+ };
7225
+ const realDataDir = canonical(dataDir);
7226
+ const realTempDir = canonical(tmpdir());
7227
+ const withinTemp = relative2(realTempDir, realDataDir);
7228
+ const withinManagedHome = relative2(canonicalManagedBase(defaultEmbeddedBaseDir()), realDataDir);
7229
+ unsafeDurability = withinTemp !== "" && withinTemp !== ".." && !withinTemp.startsWith(`..${sep2}`) && !isAbsolute3(withinTemp) && (withinManagedHome === ".." || withinManagedHome.startsWith(`..${sep2}`) || isAbsolute3(withinManagedHome));
7230
+ }
6458
7231
  return retainedPostgresSpawner()({
6459
7232
  executable: postgres,
6460
- args: ["-D", dataDir, "-p", String(port), "-c", `listen_addresses=${EMBEDDED_HOST}`],
7233
+ args: [
7234
+ "-D",
7235
+ dataDir,
7236
+ "-p",
7237
+ String(port),
7238
+ "-c",
7239
+ `listen_addresses=${EMBEDDED_HOST}`,
7240
+ "-c",
7241
+ "logging_collector=on",
7242
+ "-c",
7243
+ "log_directory=log",
7244
+ "-c",
7245
+ "log_filename=postgresql-%a.log",
7246
+ "-c",
7247
+ "log_truncate_on_rotation=on",
7248
+ "-c",
7249
+ "log_rotation_age=1d",
7250
+ "-c",
7251
+ "log_rotation_size=0",
7252
+ ...unsafeDurability ? ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"] : []
7253
+ ],
6461
7254
  cwd: dataDir,
6462
7255
  logFile,
6463
7256
  ...context.owner === undefined ? {} : { uid: context.owner.uid, gid: context.owner.gid }
6464
7257
  });
6465
7258
  } catch (error) {
6466
7259
  const detail = error instanceof Error ? error.message : String(error);
6467
- throw new Error(`Could not start the embedded Postgres cluster: ${detail}${logTail(logFile)}`);
7260
+ throw new Error(`Could not start the embedded Postgres cluster: ${detail}${logTail(logFile, dataDir)}`);
6468
7261
  }
6469
7262
  }
6470
7263
  function retainedPostgresSpawner() {
6471
7264
  if (retainedPostgresSpawnerOverride !== undefined)
6472
7265
  return retainedPostgresSpawnerOverride;
6473
- const binding = createRequire2(import.meta.url)("@bastani/atomic-natives");
7266
+ const binding = createRequire3(import.meta.url)("@bastani/atomic-natives");
6474
7267
  return binding.spawnRetainedPostgres;
6475
7268
  }
6476
7269
  function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile = copyFileSync) {
6477
- let current = dirname2(pgCtlPath);
7270
+ let current = dirname3(pgCtlPath);
6478
7271
  let manifestPath;
6479
7272
  let manifestRoot;
6480
7273
  for (let depth = 0;depth < 5; depth += 1) {
@@ -6490,7 +7283,7 @@ function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile
6490
7283
  manifestRoot = current;
6491
7284
  break;
6492
7285
  }
6493
- current = dirname2(current);
7286
+ current = dirname3(current);
6494
7287
  }
6495
7288
  if (manifestPath === undefined || manifestRoot === undefined)
6496
7289
  return;
@@ -6504,8 +7297,8 @@ function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile
6504
7297
  throw new Error(`incomplete PostgreSQL runtime: invalid aliases in ${manifestPath}`);
6505
7298
  }
6506
7299
  const firstSource = manifest[0]?.source;
6507
- if (firstSource?.startsWith("native/") && !existsSync3(join4(manifestRoot, firstSource)) && existsSync3(join4(dirname2(manifestRoot), firstSource))) {
6508
- manifestRoot = dirname2(manifestRoot);
7300
+ if (firstSource?.startsWith("native/") && !existsSync3(join4(manifestRoot, firstSource)) && existsSync3(join4(dirname3(manifestRoot), firstSource))) {
7301
+ manifestRoot = dirname3(manifestRoot);
6509
7302
  }
6510
7303
  const canonicalRoot = realpathSync3(manifestRoot);
6511
7304
  const targets = new Map;
@@ -6515,9 +7308,9 @@ function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile
6515
7308
  const absoluteSource = lstatSync3(sourcePath, { throwIfNoEntry: false }) ? sourcePath : plannedSources.get(source) ?? sourcePath;
6516
7309
  const absoluteTarget = join4(manifestRoot, target);
6517
7310
  try {
6518
- for (const path of [absoluteSource, dirname2(absoluteTarget)]) {
7311
+ for (const path of [absoluteSource, dirname3(absoluteTarget)]) {
6519
7312
  const contained = relative2(canonicalRoot, realpathSync3(path));
6520
- if (isAbsolute2(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\"))
7313
+ if (isAbsolute3(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\"))
6521
7314
  throw new Error(`alias escapes runtime: ${target}`);
6522
7315
  }
6523
7316
  if (!statSync(absoluteSource).isFile())
@@ -6529,7 +7322,7 @@ function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile
6529
7322
  throw new Error(`dangling alias target: ${target}`);
6530
7323
  if (existsSync3(absoluteTarget)) {
6531
7324
  const contained = relative2(canonicalRoot, realpathSync3(absoluteTarget));
6532
- if (isAbsolute2(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\") || !statSync(absoluteTarget).isFile() || !readFileSync3(absoluteTarget).equals(readFileSync3(absoluteSource)))
7325
+ if (isAbsolute3(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\") || !statSync(absoluteTarget).isFile() || !readFileSync3(absoluteTarget).equals(readFileSync3(absoluteSource)))
6533
7326
  throw new Error(`invalid alias target: ${target}`);
6534
7327
  }
6535
7328
  } catch (cause) {
@@ -6541,12 +7334,12 @@ function hydrateBinaryLibraryLinks(pgCtlPath, createLink = symlinkSync, copyFile
6541
7334
  for (const { absoluteSource, absoluteTarget } of plans) {
6542
7335
  if (lstatSync3(absoluteTarget, { throwIfNoEntry: false })) {
6543
7336
  const contained = relative2(canonicalRoot, realpathSync3(absoluteTarget));
6544
- if (isAbsolute2(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\") || !statSync(absoluteTarget).isFile() || !readFileSync3(absoluteTarget).equals(readFileSync3(absoluteSource)))
7337
+ if (isAbsolute3(contained) || contained === ".." || contained.startsWith("../") || contained.startsWith("..\\") || !statSync(absoluteTarget).isFile() || !readFileSync3(absoluteTarget).equals(readFileSync3(absoluteSource)))
6545
7338
  throw new Error(`incomplete PostgreSQL runtime: invalid alias target: ${absoluteTarget}`);
6546
7339
  continue;
6547
7340
  }
6548
7341
  try {
6549
- createLink(relative2(dirname2(absoluteTarget), absoluteSource), absoluteTarget);
7342
+ createLink(relative2(dirname3(absoluteTarget), absoluteSource), absoluteTarget);
6550
7343
  } catch {
6551
7344
  try {
6552
7345
  copyFile(absoluteSource, absoluteTarget);
@@ -6594,7 +7387,7 @@ function resolvePackageManifest(packageName, resolvePackage) {
6594
7387
  }
6595
7388
  }
6596
7389
  function packagedRuntimeCandidate(packageName, resolution) {
6597
- return resolution.manifest === undefined ? `${packageName}/postgres-runtime (${resolution.error ?? "package is unavailable"})` : join4(dirname2(resolution.manifest), "postgres-runtime");
7390
+ return resolution.manifest === undefined ? `${packageName}/postgres-runtime (${resolution.error ?? "package is unavailable"})` : join4(dirname3(resolution.manifest), "postgres-runtime");
6598
7391
  }
6599
7392
  async function loadEmbeddedPostgresBinaries(options = {}) {
6600
7393
  const host = options.host ?? {
@@ -6605,21 +7398,21 @@ async function loadEmbeddedPostgresBinaries(options = {}) {
6605
7398
  const target = resolveEmbeddedPostgresTarget(host);
6606
7399
  const searched = [];
6607
7400
  const moduleUrl = options.moduleUrl ?? import.meta.url;
6608
- const resolvePackage = options.resolvePackage ?? createRequire2(moduleUrl).resolve;
7401
+ const resolvePackage = options.resolvePackage ?? createRequire3(moduleUrl).resolve;
6609
7402
  const rootPackage = resolvePackageManifest("@bastani/atomic-natives", resolvePackage);
6610
- const leafResolver = options.resolvePackage ?? (rootPackage.manifest === undefined ? resolvePackage : createRequire2(rootPackage.manifest).resolve);
7403
+ const leafResolver = options.resolvePackage ?? (rootPackage.manifest === undefined ? resolvePackage : createRequire3(rootPackage.manifest).resolve);
6611
7404
  const leafPackage = target.nativeLeafPackageName === undefined ? undefined : resolvePackageManifest(target.nativeLeafPackageName, leafResolver);
6612
7405
  const explicitRuntime = options.runtimeDirectory ?? process.env.ATOMIC_POSTGRES_RUNTIME_DIR;
6613
7406
  const candidates = [
6614
7407
  ...explicitRuntime === undefined ? [] : [{ path: explicitRuntime, label: explicitRuntime }],
6615
7408
  ...target.nativeLeafPackageName === undefined || leafPackage === undefined ? [] : [
6616
7409
  {
6617
- path: leafPackage.manifest === undefined ? undefined : join4(dirname2(leafPackage.manifest), "postgres-runtime"),
7410
+ path: leafPackage.manifest === undefined ? undefined : join4(dirname3(leafPackage.manifest), "postgres-runtime"),
6618
7411
  label: packagedRuntimeCandidate(target.nativeLeafPackageName, leafPackage)
6619
7412
  }
6620
7413
  ],
6621
7414
  {
6622
- path: rootPackage.manifest === undefined ? undefined : join4(dirname2(rootPackage.manifest), "postgres-runtime"),
7415
+ path: rootPackage.manifest === undefined ? undefined : join4(dirname3(rootPackage.manifest), "postgres-runtime"),
6623
7416
  label: packagedRuntimeCandidate("@bastani/atomic-natives", rootPackage),
6624
7417
  validateTarget: true
6625
7418
  }
@@ -6647,7 +7440,7 @@ async function loadEmbeddedPostgresBinaries(options = {}) {
6647
7440
  const legacy = resolvePackageManifest(target.npmPackageName, resolvePackage);
6648
7441
  if (legacy.manifest !== undefined) {
6649
7442
  try {
6650
- return binariesFromDirectory(join4(dirname2(legacy.manifest), "native"), host.platform, options.readOnly);
7443
+ return binariesFromDirectory(join4(dirname3(legacy.manifest), "native"), host.platform, options.readOnly);
6651
7444
  } catch {}
6652
7445
  }
6653
7446
  }
@@ -6657,7 +7450,7 @@ async function loadEmbeddedPostgresBinaries(options = {}) {
6657
7450
  if (typeof binaries.pg_ctl !== "string" || typeof binaries.initdb !== "string") {
6658
7451
  throw new Error("package did not export pg_ctl/initdb paths");
6659
7452
  }
6660
- const postgres = join4(dirname2(binaries.pg_ctl), host.platform === "win32" ? "postgres.exe" : "postgres");
7453
+ const postgres = join4(dirname3(binaries.pg_ctl), host.platform === "win32" ? "postgres.exe" : "postgres");
6661
7454
  if (!options.readOnly)
6662
7455
  for (const binary of [binaries.pg_ctl, binaries.initdb, postgres])
6663
7456
  ensureExecutable(binary);
@@ -6690,7 +7483,7 @@ async function withSetupLock(lockDir, fn, options = {}) {
6690
7483
  const isProcessAlive = options.isProcessAlive ?? processIsAlive2;
6691
7484
  let lease;
6692
7485
  for (let attempt = 0;attempt < attempts; attempt += 1) {
6693
- lease = acquireSetupLock(lockDir, clock(), staleMs, isProcessAlive, options.beforeOwnerMarkerWrite);
7486
+ lease = acquireSetupLock(lockDir, clock, staleMs, isProcessAlive, options.beforeOwnerMarkerWrite);
6694
7487
  if (lease !== undefined)
6695
7488
  break;
6696
7489
  if (attempt === attempts - 1) {
@@ -6700,11 +7493,18 @@ async function withSetupLock(lockDir, fn, options = {}) {
6700
7493
  }
6701
7494
  if (lease === undefined)
6702
7495
  throw new Error(`Could not acquire the embedded Postgres setup lock (${lockDir}).`);
6703
- const refresh = () => refreshSetupLockLease(lease, clock(), options.beforeHeartbeatReplace);
7496
+ let lost = false;
7497
+ const refresh = () => {
7498
+ if (lost)
7499
+ return false;
7500
+ if (!refreshSetupLockLease(lease, clock(), staleMs, options.beforeHeartbeatReplace))
7501
+ lost = true;
7502
+ return !lost;
7503
+ };
6704
7504
  const stopHeartbeat = scheduleHeartbeat(refresh, heartbeatMs);
6705
7505
  try {
6706
7506
  await fn({
6707
- runtimePublicationLease: { ownerToken: lease.token, refresh },
7507
+ runtimePublicationLease: { ownerToken: lease.token, refresh, isLost: () => lost },
6708
7508
  abandonedRuntimeStageOwnerTokens: lease.abandonedOwnerTokens
6709
7509
  });
6710
7510
  } finally {
@@ -6712,20 +7512,20 @@ async function withSetupLock(lockDir, fn, options = {}) {
6712
7512
  releaseSetupLock(lease);
6713
7513
  }
6714
7514
  }
6715
- function acquireSetupLock(lockDir, now, staleMs, isProcessAlive, beforeOwnerMarkerWrite) {
7515
+ function acquireSetupLock(lockDir, clock, staleMs, isProcessAlive, beforeOwnerMarkerWrite) {
6716
7516
  const abandonedOwnerTokens = new Set;
6717
7517
  for (let attempt = 0;attempt < 2; attempt += 1) {
6718
7518
  const token = `${process.pid}-${crypto.randomUUID()}`;
6719
7519
  if (createSetupLockDirectory(lockDir)) {
6720
7520
  beforeOwnerMarkerWrite?.(lockDir);
6721
- const lease = claimCreatedSetupLock(lockDir, token, now, abandonedOwnerTokens);
7521
+ const lease = claimCreatedSetupLock(lockDir, token, clock(), abandonedOwnerTokens);
6722
7522
  if (lease !== undefined)
6723
7523
  return lease;
6724
7524
  }
6725
7525
  const observation = observeSetupLock(lockDir);
6726
- if (observation === undefined || !setupLockIsStale(observation, now, staleMs, isProcessAlive))
7526
+ if (observation === undefined || !setupLockIsStale(observation, clock(), staleMs, isProcessAlive))
6727
7527
  return;
6728
- const abandoned = breakStaleSetupLock(lockDir, observation, now, staleMs, token, isProcessAlive);
7528
+ const abandoned = breakStaleSetupLock(lockDir, observation, clock, staleMs, token, isProcessAlive);
6729
7529
  if (abandoned === undefined)
6730
7530
  return;
6731
7531
  for (const abandonedToken of abandoned)
@@ -6779,8 +7579,9 @@ function createdSetupLockHoldsOnly(lockDir, markerName) {
6779
7579
  function errorCode(error) {
6780
7580
  return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
6781
7581
  }
6782
- function refreshSetupLockLease(lease, now, beforeReplace) {
6783
- if (!ownsSetupLock(lease))
7582
+ function refreshSetupLockLease(lease, now, staleMs, beforeReplace) {
7583
+ const deadline = performance.now() + Math.min(100, staleMs / 4);
7584
+ if (!ownsSetupLock(lease, deadline))
6784
7585
  return false;
6785
7586
  const record = { token: lease.token, pid: lease.ownerPid, heartbeatMonotonicMs: now.monotonicMs };
6786
7587
  const temporaryMarkerPath = join4(lease.lockDir, `.owner-${lease.token}.tmp-${crypto.randomUUID()}`);
@@ -6791,12 +7592,18 @@ function refreshSetupLockLease(lease, now, beforeReplace) {
6791
7592
  flush: true
6792
7593
  });
6793
7594
  beforeReplace?.(temporaryMarkerPath);
6794
- if (!ownsSetupLock(lease)) {
7595
+ if (!ownsSetupLock(lease, deadline)) {
6795
7596
  removeMarkerIfOwned(temporaryMarkerPath, record);
6796
7597
  return false;
6797
7598
  }
6798
- renameSync2(temporaryMarkerPath, lease.markerPath);
6799
- return ownsSetupLock(lease);
7599
+ return retrySetupLockSharingViolation(() => {
7600
+ if (!ownsSetupLock(lease, deadline)) {
7601
+ removeMarkerIfOwned(temporaryMarkerPath, record);
7602
+ return false;
7603
+ }
7604
+ renameSync2(temporaryMarkerPath, lease.markerPath);
7605
+ return ownsSetupLock(lease, deadline);
7606
+ }, deadline);
6800
7607
  } catch {
6801
7608
  removeMarkerIfOwned(temporaryMarkerPath, record);
6802
7609
  return false;
@@ -6812,10 +7619,26 @@ function removeMarkerIfOwned(path, expected) {
6812
7619
  }
6813
7620
  } catch {}
6814
7621
  }
6815
- function ownsSetupLock(lease) {
7622
+ function retrySetupLockSharingViolation(operation, deadline) {
7623
+ let backoffMs = 1;
7624
+ for (;; ) {
7625
+ try {
7626
+ return operation();
7627
+ } catch (error) {
7628
+ const remainingMs = deadline - performance.now();
7629
+ if (!["EPERM", "EACCES", "EBUSY"].includes(errorCode(error) ?? "") || remainingMs <= 0)
7630
+ throw error;
7631
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(backoffMs, remainingMs));
7632
+ backoffMs = Math.min(10, backoffMs * 2);
7633
+ }
7634
+ }
7635
+ }
7636
+ function ownsSetupLock(lease, deadline = performance.now()) {
6816
7637
  try {
6817
- const record = parseLockOwner(readFileSync3(lease.markerPath, "utf8"));
6818
- return record?.token === lease.token && record.pid === lease.ownerPid && lstatSync3(lease.markerPath).isFile();
7638
+ return retrySetupLockSharingViolation(() => {
7639
+ const record = parseLockOwner(readFileSync3(lease.markerPath, "utf8"));
7640
+ return record?.token === lease.token && record.pid === lease.ownerPid && lstatSync3(lease.markerPath).isFile();
7641
+ }, deadline);
6819
7642
  } catch {
6820
7643
  return false;
6821
7644
  }
@@ -6828,7 +7651,7 @@ function releaseSetupLock(lease) {
6828
7651
  rmdirSync(lease.lockDir);
6829
7652
  } catch {}
6830
7653
  }
6831
- function breakStaleSetupLock(lockDir, observed, now, staleMs, token, isProcessAlive) {
7654
+ function breakStaleSetupLock(lockDir, observed, clock, staleMs, token, isProcessAlive) {
6832
7655
  const breakPath = `${lockDir}.stale-${token}`;
6833
7656
  try {
6834
7657
  renameSync2(lockDir, breakPath);
@@ -6836,7 +7659,7 @@ function breakStaleSetupLock(lockDir, observed, now, staleMs, token, isProcessAl
6836
7659
  return;
6837
7660
  }
6838
7661
  const displaced = observeSetupLock(breakPath);
6839
- if (displaced === undefined || displaced.fingerprint !== observed.fingerprint || !setupLockIsStale(displaced, now, staleMs, isProcessAlive)) {
7662
+ if (displaced === undefined || displaced.fingerprint !== observed.fingerprint || !setupLockIsStale(displaced, clock(), staleMs, isProcessAlive)) {
6840
7663
  try {
6841
7664
  renameSync2(breakPath, lockDir);
6842
7665
  } catch {}
@@ -6951,17 +7774,45 @@ function scheduleSetupLockHeartbeat(heartbeat, intervalMs) {
6951
7774
  timer.unref();
6952
7775
  return () => clearInterval(timer);
6953
7776
  }
6954
- function logTail(logFile) {
7777
+ function readLogSuffix(file) {
7778
+ const fd = openSync(file, "r");
6955
7779
  try {
6956
- const lines = readFileSync3(logFile, "utf8").trimEnd().split(`
7780
+ const size = fstatSync(fd).size;
7781
+ const buffer = Buffer.alloc(Math.min(size, 65536));
7782
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, size - buffer.length);
7783
+ return buffer.toString("utf8", 0, bytesRead);
7784
+ } finally {
7785
+ closeSync(fd);
7786
+ }
7787
+ }
7788
+ function logTail(logFile, dataDir) {
7789
+ const tails = [];
7790
+ const appendTail = (file, label) => {
7791
+ try {
7792
+ const lines = readLogSuffix(file).trimEnd().split(`
6957
7793
  `);
6958
- return `
6959
- Postgres log tail:
7794
+ tails.push(`${label}:
6960
7795
  ${lines.slice(-5).join(`
6961
- `)}`;
6962
- } catch {
6963
- return "";
6964
- }
7796
+ `)}`);
7797
+ } catch {}
7798
+ };
7799
+ appendTail(logFile, "Postgres log tail");
7800
+ try {
7801
+ const current = readLogSuffix(join4(dataDir, "current_logfiles")).match(/^stderr\s+(.+)$/m)?.[1];
7802
+ if (current) {
7803
+ const logDir = join4(dataDir, "log");
7804
+ const realDataDir = realpathSync3(dataDir);
7805
+ const realLogDir = realpathSync3(logDir);
7806
+ const candidate = join4(dataDir, current.trim());
7807
+ const lexical = relative2(logDir, candidate);
7808
+ const resolved = relative2(realLogDir, realpathSync3(candidate));
7809
+ if (realLogDir === join4(realDataDir, "log") && [lexical, resolved].every((part) => part !== "" && part !== ".." && !part.startsWith(`..${sep2}`) && !isAbsolute3(part)))
7810
+ appendTail(candidate, "Postgres collector log tail");
7811
+ }
7812
+ } catch {}
7813
+ return tails.length ? `
7814
+ ${tails.join(`
7815
+ `)}` : "";
6965
7816
  }
6966
7817
 
6967
7818
  // dist/builtin/workflows/src/durable/dbos-local-postgres.ts
@@ -6991,44 +7842,13 @@ var owner = ownerBag3[ownerKey] ?? {
6991
7842
  resolve: resolveDbosSystemDatabaseUrl,
6992
7843
  provision: provisionResolvedLocalDbos,
6993
7844
  shutdown: shutdownResolvedLocalDbos,
6994
- health: resolvedPostgresHealth,
6995
- provider: resolvedPostgresProvider,
6996
- failure: postgresLastFailure,
6997
- recover: recoverManagedPostgres
7845
+ health: resolvedPostgresHealth
6998
7846
  };
6999
7847
  ownerBag3[ownerKey] = owner;
7000
- function resolvedPostgresProvider() {
7001
- if (owner.provider !== resolvedPostgresProvider)
7002
- return owner.provider?.() ?? "unresolved";
7003
- return resolvedProvider === embeddedProvider ? "embedded" : resolvedProvider === dockerProvider ? "docker" : "unresolved";
7004
- }
7005
- function postgresLastFailure() {
7006
- if (owner.failure !== postgresLastFailure)
7007
- return owner.failure?.();
7008
- return embeddedPostgresLastFailure();
7009
- }
7010
- async function recoverManagedPostgres(context, metadata) {
7011
- if (owner.recover !== recoverManagedPostgres) {
7012
- if (!owner.recover)
7013
- throw new Error("Reloaded PostgreSQL owner does not support explicit recovery. Restart Atomic without deleting data.");
7014
- return owner.recover(context, metadata);
7015
- }
7016
- if (process.env.DBOS_SYSTEM_DATABASE_URL?.trim() || resolvedProvider === dockerProvider)
7017
- throw new Error("Managed recovery is not allowed for the selected provider.");
7018
- resolvedPostgresHealth()?.invalidate();
7019
- try {
7020
- await recoverEmbeddedPostgres(context, metadata);
7021
- resolvedProvider = embeddedProvider;
7022
- } catch (error) {
7023
- if (error instanceof EmbeddedPostgresCleanupPendingError)
7024
- resolvedProvider = embeddedProvider;
7025
- throw error;
7026
- }
7027
- }
7028
7848
  function resolvedPostgresHealth(url) {
7029
7849
  if (owner.health !== resolvedPostgresHealth)
7030
7850
  return owner.health?.(url);
7031
- if (process.env.DBOS_SYSTEM_DATABASE_URL?.trim() || resolvedProvider !== embeddedProvider)
7851
+ if (explicitDbosSystemDatabaseUrl() || resolvedProvider !== embeddedProvider)
7032
7852
  return;
7033
7853
  if (url !== undefined && url !== embeddedDbosSystemDatabaseUrl())
7034
7854
  return;
@@ -7049,7 +7869,7 @@ function resolveDbosSystemDatabaseUrl() {
7049
7869
  async function provisionResolvedLocalDbos() {
7050
7870
  if (owner.provision !== provisionResolvedLocalDbos)
7051
7871
  return owner.provision();
7052
- if (process.env.DBOS_SYSTEM_DATABASE_URL?.trim())
7872
+ if (explicitDbosSystemDatabaseUrl())
7053
7873
  return;
7054
7874
  await (resolvedProvider ?? embeddedProvider)();
7055
7875
  }
@@ -7166,7 +7986,7 @@ async function dockerPostgresQueryReady(host, port) {
7166
7986
  }
7167
7987
  }
7168
7988
  async function resolve() {
7169
- const explicit = process.env.DBOS_SYSTEM_DATABASE_URL?.trim();
7989
+ const explicit = explicitDbosSystemDatabaseUrl();
7170
7990
  if (explicit)
7171
7991
  return;
7172
7992
  try {
@@ -9438,7 +10258,7 @@ function workflowArtifactRoot() {
9438
10258
  const override = getEnvValue(ENV_WORKFLOW_ARTIFACT_DIR);
9439
10259
  if (override !== undefined && override.length > 0)
9440
10260
  return override;
9441
- return join5(dirname3(getAgentDir()), "workflows");
10261
+ return join5(dirname4(getAgentDir()), "workflows");
9442
10262
  }
9443
10263
  function workflowArtifactRunsRoot() {
9444
10264
  return join5(workflowArtifactRoot(), "runs");