@capybara-hq/kernel 0.1.0-rc.121 → 0.1.0-rc.122

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 (229) hide show
  1. package/dist/background/finish.d.ts +5 -1
  2. package/dist/background/finish.js +29 -18
  3. package/dist/background/launch.d.ts +0 -5
  4. package/dist/background/launch.js +1 -6
  5. package/dist/background/managed.js +1 -4
  6. package/dist/background/poll.job.d.ts +3 -25
  7. package/dist/background/poll.job.js +20 -112
  8. package/dist/background/render.d.ts +2 -8
  9. package/dist/background/render.js +3 -17
  10. package/dist/background/stop.d.ts +15 -16
  11. package/dist/background/stop.js +39 -76
  12. package/dist/background/store.d.ts +17 -45
  13. package/dist/background/store.js +60 -94
  14. package/dist/background/tasks.service.d.ts +2 -5
  15. package/dist/background/tasks.service.js +9 -20
  16. package/dist/background/wake.js +3 -2
  17. package/dist/catalog/admin-catalog.controller.d.ts +2 -18
  18. package/dist/catalog/admin-catalog.controller.js +2 -28
  19. package/dist/catalog/catalog-content.d.ts +1 -5
  20. package/dist/catalog/catalog-items.d.ts +2 -6
  21. package/dist/catalog/catalog-items.js +5 -26
  22. package/dist/catalog/catalog-scope.service.d.ts +1 -121
  23. package/dist/catalog/catalog-scope.service.js +12 -552
  24. package/dist/catalog/catalog.service.d.ts +4 -15
  25. package/dist/catalog/catalog.service.js +7 -35
  26. package/dist/catalog/job-ids.d.ts +0 -18
  27. package/dist/catalog/job-ids.js +0 -20
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/org-catalog.service.js +6 -20
  30. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -19
  31. package/dist/catalog/org-plugin-uploads.controller.js +6 -34
  32. package/dist/catalog/org-plugin-uploads.d.ts +3 -10
  33. package/dist/catalog/org-plugin-uploads.js +4 -18
  34. package/dist/catalog/org-plugin-uploads.schemas.js +0 -1
  35. package/dist/catalog/owned-items.d.ts +6 -11
  36. package/dist/catalog/owned-items.js +10 -20
  37. package/dist/catalog/ownership.d.ts +3 -29
  38. package/dist/catalog/ownership.js +4 -54
  39. package/dist/catalog/platform-components.d.ts +5 -11
  40. package/dist/catalog/platform-components.js +8 -15
  41. package/dist/catalog/plugin-import.d.ts +3 -42
  42. package/dist/catalog/plugin-import.js +26 -195
  43. package/dist/catalog/plugin-install.js +1 -6
  44. package/dist/catalog/plugin-package.d.ts +1 -0
  45. package/dist/catalog/plugin-package.js +5 -0
  46. package/dist/catalog/plugin-upgrade.d.ts +3 -26
  47. package/dist/catalog/plugin-upgrade.js +20 -103
  48. package/dist/catalog/request-rules.js +4 -6
  49. package/dist/catalog/scope-sync.js +2 -4
  50. package/dist/catalog/scope.d.ts +2 -5
  51. package/dist/channels/jobs.d.ts +3 -3
  52. package/dist/channels/jobs.js +4 -3
  53. package/dist/channels/outbound.d.ts +1 -0
  54. package/dist/channels/outbound.js +32 -8
  55. package/dist/config/load.d.ts +0 -25
  56. package/dist/config/load.js +0 -57
  57. package/dist/config/schema.js +2 -3
  58. package/dist/conversations/attachments.service.js +3 -5
  59. package/dist/conversations/conversations.service.d.ts +3 -3
  60. package/dist/conversations/conversations.service.js +3 -3
  61. package/dist/conversations/job-org.d.ts +3 -0
  62. package/dist/conversations/job-org.js +11 -0
  63. package/dist/conversations/prompt-suggestions.d.ts +2 -7
  64. package/dist/conversations/prompt-suggestions.js +29 -27
  65. package/dist/conversations/titles.d.ts +3 -4
  66. package/dist/conversations/titles.js +19 -30
  67. package/dist/db/kernel-schema.d.ts +6 -16
  68. package/dist/db/pool.js +7 -2
  69. package/dist/devices/devices.controller.d.ts +0 -5
  70. package/dist/devices/devices.controller.js +2 -20
  71. package/dist/devices/devices.service.d.ts +1 -17
  72. package/dist/devices/devices.service.js +0 -22
  73. package/dist/errors.d.ts +1 -5
  74. package/dist/errors.js +1 -5
  75. package/dist/evals/judge.d.ts +3 -0
  76. package/dist/evals/judge.js +1 -1
  77. package/dist/evals/run-replay.d.ts +1 -1
  78. package/dist/evals/run-replay.js +26 -29
  79. package/dist/evals/step-replay.d.ts +3 -1
  80. package/dist/evals/step-replay.js +10 -1
  81. package/dist/evals/worker.d.ts +3 -1
  82. package/dist/evals/worker.js +53 -21
  83. package/dist/extensions/deployment-config-store.js +18 -14
  84. package/dist/extensions/effective-config.d.ts +1 -5
  85. package/dist/extensions/effective-config.js +1 -5
  86. package/dist/extensions/hooks.d.ts +3 -1
  87. package/dist/extensions/hooks.js +7 -2
  88. package/dist/extensions/installs.d.ts +2 -14
  89. package/dist/extensions/installs.js +10 -32
  90. package/dist/extensions/org-config.d.ts +3 -4
  91. package/dist/extensions/org-config.js +3 -4
  92. package/dist/extensions/plugin-guides.d.ts +0 -1
  93. package/dist/extensions/plugin-guides.js +0 -1
  94. package/dist/extensions/plugin-icons.d.ts +0 -1
  95. package/dist/extensions/plugin-icons.js +0 -3
  96. package/dist/files/blob-sweep.job.d.ts +2 -11
  97. package/dist/files/blob-sweep.job.js +7 -21
  98. package/dist/files/hash-job.d.ts +5 -15
  99. package/dist/files/hash-job.js +14 -33
  100. package/dist/files/library-jobs.module.d.ts +1 -6
  101. package/dist/files/library-jobs.module.js +3 -9
  102. package/dist/identity/api-tokens.js +54 -40
  103. package/dist/identity/auth.guard.js +2 -2
  104. package/dist/identity/sessions.js +7 -3
  105. package/dist/identity/settings.js +5 -21
  106. package/dist/inbox/inbox.service.d.ts +2 -3
  107. package/dist/inbox/org-notices.d.ts +0 -14
  108. package/dist/inbox/platform-inbox.service.d.ts +1 -8
  109. package/dist/inbox/platform-inbox.service.js +2 -6
  110. package/dist/inbox/platform-notices.d.ts +3 -3
  111. package/dist/index.d.ts +0 -4
  112. package/dist/index.js +0 -3
  113. package/dist/infra/database/database.module.js +2 -1
  114. package/dist/infra/database/org-scope.d.ts +5 -3
  115. package/dist/infra/database/org-scope.js +7 -1
  116. package/dist/infra/database/scoped-dialect.d.ts +3 -1
  117. package/dist/infra/database/scoped-dialect.js +17 -5
  118. package/dist/infra/events/kernel-events.d.ts +2 -0
  119. package/dist/infra/outbox/outbox.service.d.ts +2 -0
  120. package/dist/infra/outbox/outbox.service.js +10 -0
  121. package/dist/infra/outbox/registry.d.ts +0 -41
  122. package/dist/infra/outbox/registry.js +0 -37
  123. package/dist/models/embeddings.d.ts +0 -5
  124. package/dist/models/embeddings.js +28 -35
  125. package/dist/models/images.d.ts +3 -8
  126. package/dist/models/images.js +19 -37
  127. package/dist/models/purposes.d.ts +7 -2
  128. package/dist/models/purposes.js +16 -3
  129. package/dist/orgs/device-network-setting.d.ts +0 -44
  130. package/dist/orgs/device-network-setting.js +0 -83
  131. package/dist/orgs/invitations.service.js +34 -30
  132. package/dist/orgs/offboarding.d.ts +2 -2
  133. package/dist/orgs/offboarding.js +2 -2
  134. package/dist/orgs/orgs.service.d.ts +1 -1
  135. package/dist/orgs/orgs.service.js +19 -15
  136. package/dist/orgs/settings.service.d.ts +19 -14
  137. package/dist/orgs/settings.service.js +12 -37
  138. package/dist/platform/exclusions.js +0 -11
  139. package/dist/platform/ops/catalog-admin.ops.js +0 -8
  140. package/dist/platform/ops/devices.ops.js +0 -28
  141. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  142. package/dist/platform/ops/inbox.ops.js +5 -22
  143. package/dist/platform/ops/org-plugins.ops.d.ts +1 -3
  144. package/dist/platform/ops/org-plugins.ops.js +11 -67
  145. package/dist/roles/worker.module.js +0 -9
  146. package/dist/runtime/hook-calls.d.ts +13 -6
  147. package/dist/runtime/hook-calls.js +26 -4
  148. package/dist/runtime/maintenance.d.ts +3 -12
  149. package/dist/runtime/maintenance.js +25 -55
  150. package/dist/runtime/model-call.d.ts +4 -2
  151. package/dist/runtime/model-call.js +59 -58
  152. package/dist/runtime/providers.d.ts +27 -1
  153. package/dist/runtime/providers.js +57 -0
  154. package/dist/runtime/run-jobs.d.ts +1 -1
  155. package/dist/runtime/run-processors.d.ts +3 -9
  156. package/dist/runtime/run-worker.d.ts +2 -0
  157. package/dist/runtime/run-worker.js +23 -8
  158. package/dist/runtime/subagents/deliveries.js +6 -1
  159. package/dist/runtime/subagents/dispatch.d.ts +3 -3
  160. package/dist/runtime/write-base.service.d.ts +2 -3
  161. package/dist/runtime/write-base.service.js +3 -5
  162. package/dist/sandbox/device-sandbox-settings.d.ts +38 -92
  163. package/dist/sandbox/device-sandbox-settings.js +19 -325
  164. package/dist/sandbox/jobs.d.ts +3 -14
  165. package/dist/sandbox/jobs.js +2 -20
  166. package/dist/sandbox/modes.d.ts +5 -45
  167. package/dist/sandbox/modes.js +3 -60
  168. package/dist/sandbox/operation-authority.js +0 -11
  169. package/dist/sandbox/operation-intents.d.ts +32 -9
  170. package/dist/sandbox/operation-intents.js +241 -32
  171. package/dist/sandbox/operation-intents.module.js +2 -1
  172. package/dist/sandbox/operation-reconcile.job.d.ts +9 -11
  173. package/dist/sandbox/operation-reconcile.job.js +119 -33
  174. package/dist/sandbox/operation-revoke.d.ts +20 -0
  175. package/dist/sandbox/operation-revoke.js +3 -0
  176. package/dist/sandbox/permission-ceiling-writes.d.ts +1 -2
  177. package/dist/sandbox/permission-ceiling-writes.js +3 -6
  178. package/dist/sandbox/permission-config-publication.d.ts +1 -28
  179. package/dist/sandbox/permission-config-publication.js +14 -211
  180. package/dist/sandbox/permission-facts.d.ts +4 -15
  181. package/dist/sandbox/permission-facts.js +7 -29
  182. package/dist/sandbox/permission-instance-writes.d.ts +1 -4
  183. package/dist/sandbox/permission-instance-writes.js +1 -55
  184. package/dist/sandbox/providers.d.ts +1 -6
  185. package/dist/sandbox/providers.js +1 -15
  186. package/dist/sandbox/review/classifier.js +12 -13
  187. package/dist/sandbox/sandbox.module.js +3 -6
  188. package/dist/sandbox/sandbox.service.d.ts +17 -123
  189. package/dist/sandbox/sandbox.service.js +239 -998
  190. package/dist/shares/liveness.d.ts +1 -2
  191. package/dist/shares/liveness.js +1 -2
  192. package/dist/shares/shares.module.d.ts +1 -2
  193. package/dist/shares/shares.module.js +2 -5
  194. package/dist/shares/shares.service.js +1 -2
  195. package/dist/tools/builtins/image/generate.js +7 -15
  196. package/dist/tools/builtins/sandbox/common.d.ts +0 -2
  197. package/dist/tools/builtins/sandbox/common.js +1 -27
  198. package/dist/tools/builtins/sandbox/task-list.js +10 -10
  199. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -10
  200. package/dist/tools/builtins/sandbox/task-output.js +13 -83
  201. package/dist/tools/builtins/sandbox/task-stop.js +18 -22
  202. package/dist/tools/builtins/vision/read-image.js +9 -10
  203. package/dist/tools/builtins/web/extract.js +9 -10
  204. package/package.json +3 -3
  205. package/src/migrations/0206_retire_org_extension_uploads.sql +125 -0
  206. package/src/migrations/0207_confirm_device_instance_destruction.sql +25 -0
  207. package/src/migrations/0208_convert_stored_permission_settings.sql +189 -0
  208. package/dist/background/retire-legacy-tasks.job.d.ts +0 -57
  209. package/dist/background/retire-legacy-tasks.job.js +0 -149
  210. package/dist/catalog/owned-plugin-cleanup.d.ts +0 -47
  211. package/dist/catalog/owned-plugin-cleanup.js +0 -140
  212. package/dist/config/permission-migration.d.ts +0 -34
  213. package/dist/config/permission-migration.js +0 -115
  214. package/dist/devices/legacy-cleanup.job.d.ts +0 -34
  215. package/dist/devices/legacy-cleanup.job.js +0 -147
  216. package/dist/files/library-backfill.d.ts +0 -63
  217. package/dist/files/library-backfill.js +0 -143
  218. package/dist/infra/cli/permission-cutover.d.ts +0 -59
  219. package/dist/infra/cli/permission-cutover.js +0 -107
  220. package/dist/sandbox/cloud-permission-snapshot.d.ts +0 -159
  221. package/dist/sandbox/cloud-permission-snapshot.js +0 -430
  222. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +0 -8
  223. package/dist/sandbox/cloud-permission-snapshot.module.js +0 -34
  224. package/dist/sandbox/legacy-retirement.d.ts +0 -284
  225. package/dist/sandbox/legacy-retirement.js +0 -1165
  226. package/dist/sandbox/legacy-retirement.module.d.ts +0 -8
  227. package/dist/sandbox/legacy-retirement.module.js +0 -25
  228. package/dist/shares/share-objects.d.ts +0 -47
  229. package/dist/shares/share-objects.js +0 -93
@@ -67,18 +67,15 @@ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
67
67
  import { effectiveSandboxLimits, readOrgSettings } from "../orgs/settings.service.js";
68
68
  import { isStorageError } from "../runtime/permission-context-errors.js";
69
69
  import { canonicalJson } from "../tools/canonical-json.js";
70
- import { untilAborted } from "../until-aborted.js";
71
70
  import { attachmentsDir } from "./attachments-path.js";
72
- import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
73
71
  import { DeviceReports } from "./device-reports.js";
74
72
  import { isKernelReadMethod, KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
75
73
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
76
- import { isKnownProvider, LegacyRetirementStore, } from "./legacy-retirement.js";
77
74
  import { ManagedDeviceContextFailed } from "./managed-device-context.js";
78
- import { appliedLacksHost, appliedOf, appliedWider, installedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
75
+ import { appliedLacksHost, appliedOf, appliedWider, installedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, } from "./modes.js";
79
76
  import { PermissionFacts } from "./permission-facts.js";
80
77
  import { reportOwed, supportOf } from "./permission-runtime-reports.js";
81
- import { DeviceProviders, isInProcessName, LOCAL_RETIREMENT_PROVIDER, localRetirementGeneration, RETIREMENT_GENERATION, servesDialIn, } from "./providers.js";
78
+ import { DeviceProviders, isInProcessName, servesDialIn, } from "./providers.js";
82
79
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
83
80
  import { SandboxProviderUnreachableError } from "./unreachable.js";
84
81
  // Moved to leases.ts (phase C); re-exported for existing importers
@@ -89,14 +86,6 @@ const HOLDER_TTL_MARGIN_MS = 10 * 60_000;
89
86
  const PATH_LEASE_WAIT_MS = 30_000;
90
87
  /** Time limit of one provider call in maintenance (suspend, destroy). */
91
88
  const SWEEP_OP_TIMEOUT_MS = 120_000;
92
- const RETIREMENT_CHECK_TIMEOUT_MS = 15_000;
93
- /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
94
- const RECONCILE_RETRY_SECONDS = 600;
95
- /**
96
- * Where the reconcile sweep goes on from for one provider (the last device id it visited; B-12):
97
- * one cursor per provider, since each provider's rows are swept on their own.
98
- */
99
- const reconcileCursorKey = (plugin) => `capk:sandbox-reconcile-cursor:${plugin}`;
100
89
  /** The bound on one cloud `permissionSupport` read under a lifecycle lease (B-15). */
101
90
  const PERMISSION_SUPPORT_TIMEOUT_MS = 30_000;
102
91
  /** The bound on one `appliedNetwork` read under a lifecycle lease (issue #766). */
@@ -280,24 +269,6 @@ export const sandboxUnavailable = () => new ApiError("sandbox.unavailable", "No
280
269
  export const deviceNotRunning = () => new ApiError("device.not_running", "The device stopped before it could be read. Try again; it will be started first.");
281
270
  /** The holder name of {@link SandboxService.ensureRunningForOwner}: no conversation holds it. */
282
271
  const OWNER_START_HOLDER = "device-owner";
283
- /**
284
- * The device's old instance incarnation may still run legacy work that was never retired (503):
285
- * the device stays unavailable until the provider confirms that incarnation destroyed, or for
286
- * good when it is quarantined (permission runtime cutover 8.5). Never a retirement claim.
287
- */
288
- export class RetirementPendingError extends ApiError {
289
- name = "RetirementPendingError";
290
- }
291
- export const retirementPending = () => new RetirementPendingError("device.unavailable", "This device is unavailable: background work started by an earlier version may still run on its previous instance, and that instance has not been confirmed destroyed. A cloud device becomes usable once its provider confirms the old instance destroyed.");
292
- /**
293
- * A cloud device's earlier instance may still run legacy work and no evidence the kernel can get
294
- * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
295
- * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
296
- */
297
- export const recreateRequired = (local = false) => new RetirementPendingError("device.recreate_required", local
298
- ? "Earlier background work on the connected machine has not been confirmed stopped. If you own this device, open its device page and choose Check again."
299
- : "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.", local ? [{ reason: "local_retirement" }] : undefined);
300
- const isRetirementPending = (err) => err instanceof RetirementPendingError;
301
272
  const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
302
273
  function sleep(ms, signal) {
303
274
  return new Promise((resolve, reject) => {
@@ -348,8 +319,6 @@ let SandboxService = class SandboxService {
348
319
  operationIntents;
349
320
  authority;
350
321
  instanceWrites;
351
- retirement;
352
- snapshots;
353
322
  reports;
354
323
  relay;
355
324
  constructor(db,
@@ -359,10 +328,6 @@ let SandboxService = class SandboxService {
359
328
  providers,
360
329
  /** Whether a device's provider serves its org now (read at every use, never cached). */
361
330
  selection, config, log, facts, operationIntents, authority, instanceWrites,
362
- /** The retirement obligations every lifecycle acquisition is gated on (8.5). */
363
- retirement,
364
- /** The cloud snapshot writer's reconcile, for the lifecycle reconcile of marked devices (B-12). */
365
- snapshots,
366
331
  /** The stored device report, refreshed after a create or a resume (never fails the use). */
367
332
  reports,
368
333
  /**
@@ -381,8 +346,6 @@ let SandboxService = class SandboxService {
381
346
  this.operationIntents = operationIntents;
382
347
  this.authority = authority;
383
348
  this.instanceWrites = instanceWrites;
384
- this.retirement = retirement;
385
- this.snapshots = snapshots;
386
349
  this.reports = reports;
387
350
  this.relay = relay;
388
351
  }
@@ -710,20 +673,10 @@ let SandboxService = class SandboxService {
710
673
  * to `fn` aborts with `signal` or when the lease is lost. Errors of `fn` (`SandboxGoneError`
711
674
  * too) are thrown as they are.
712
675
  */
713
- async ifRunning(deviceId,
714
- /**
715
- * `exactRef`: an exact-ref managed drain (status, stop, the revoke worker), allowed on an
716
- * incarnation under a retirement obligation; every other caller (legacy SID polls, stops and
717
- * reads, staged browse) is refused there with a {@link RetirementPendingError} (8.5).
718
- */
719
- instance, fn, signal = new AbortController().signal) {
720
- return this.ifRunningAs(deviceId, instance, fn, signal, false);
676
+ async ifRunning(deviceId, instance, fn, signal = new AbortController().signal) {
677
+ return this.ifRunningAs(deviceId, instance, fn, signal);
721
678
  }
722
- /**
723
- * {@link ifRunning}; `use` (staged owner browse) also refuses a device carrying the B1
724
- * reconcile marker under the shared lease, before any provider call (B-11).
725
- */
726
- async ifRunningAs(deviceId, instance, fn, signal, use) {
679
+ async ifRunningAs(deviceId, instance, fn, signal) {
727
680
  const p = await this.loadedFor(deviceId);
728
681
  const env = deviceId;
729
682
  const deadline = Date.now() + this.config.get().sandbox.lockWaitSeconds * 1000;
@@ -745,16 +698,12 @@ let SandboxService = class SandboxService {
745
698
  }
746
699
  if (!this.usable(row, p, null))
747
700
  return { kind: "not_running", status: row.status };
748
- // an incarnation that may still run unretired legacy work: no SID signal, no new exec or
749
- // admission there; only exact-ref managed drains go on (I1)
750
- if (!instance.exactRef && (await this.retirement.hasUnresolved(env)))
751
- throw retirementPending();
752
701
  // the instance this check saw: its handle plus `created_at` (never `generation`, which
753
702
  // every lease bumps)
754
703
  const want = { handle: row.handle, createdAt: row.created_at.getTime() };
755
704
  const lease = await this.leases.tryShared(env, this.cap, token);
756
705
  if (lease) {
757
- const e = await this.asShared({ orgId: row.org_id, deviceId: env }, p, lease, (r) => this.usable(r, p, null) && isInstance(r, want), signal, !instance.exactRef, use ? "reconciled" : "none");
706
+ const e = await this.asShared({ orgId: row.org_id, deviceId: env }, p, lease, (r) => this.usable(r, p, null) && isInstance(r, want), signal);
758
707
  if (e) {
759
708
  try {
760
709
  const impl = tagged(p.impl, lease.token, undefined, () => this.register(env, lease.token));
@@ -971,7 +920,7 @@ let SandboxService = class SandboxService {
971
920
  list: (path, opts) => call("list", { path, limit: opts.limit }, opts.signal, (p, signal) => p.list(path, { limit: opts.limit, signal })),
972
921
  scan: (base, opts) => call("scan", { base }, opts.signal, (p, signal) => p.scan(base, { signal })),
973
922
  }, sig);
974
- }, signal, true);
923
+ }, signal);
975
924
  if (result.kind !== "ran")
976
925
  throw deviceNotRunning();
977
926
  return result.value;
@@ -980,8 +929,8 @@ let SandboxService = class SandboxService {
980
929
  * Makes the device's instance run for its owner (permission activation L2, Hook 3), before an
981
930
  * owner browse ({@link withBrowse}) of a device that may be stopped: the owner, membership and
982
931
  * browsing ceiling checks of the browse first (`resolveBrowse`), then the lifecycle `enter` a
983
- * use takes (the exclusive lease creates or resumes the instance through the retirement gate,
984
- * the B-11 reconcile marker, `maxRunningSandboxes` and fencing), and the lease
932
+ * use takes (the exclusive lease creates or resumes the instance with `maxRunningSandboxes` and
933
+ * fencing), and the lease
985
934
  * is left at once. No conversation holds it and nothing runs in it; what the start caused is
986
935
  * not marked seen, so each conversation's next use still learns of it. `narrow` is the browse's
987
936
  * own (see {@link withBrowse}), checked before the start, so a browse the narrowed scope refuses
@@ -1002,7 +951,7 @@ let SandboxService = class SandboxService {
1002
951
  /**
1003
952
  * Makes the device's instance run for a managed call before its permission review reads the
1004
953
  * device's facts: the lifecycle `enter` the call's own use takes (the exclusive lease creates
1005
- * or resumes the instance through the retirement gate, the binding, the limits and fencing, and
954
+ * or resumes the bound instance with the current limits and fencing, and
1006
955
  * records a cloud instance's permission evidence), then the lease is left at once. Nothing runs
1007
956
  * in it; what the start caused is kept for the holder's next use to tell (as a silent use).
1008
957
  */
@@ -1024,7 +973,7 @@ let SandboxService = class SandboxService {
1024
973
  * never creates, resumes or rebuilds an instance: without a running one (none, suspended, being
1025
974
  * created or destroyed, files lost) there is nothing to apply and the next use's resume applies
1026
975
  * the limits. Nothing is done when the limits already apply (no lease is taken, so open viewers
1027
- * stay), or while the device carries a retirement obligation (only a use's gate settles it).
976
+ * stay).
1028
977
  *
1029
978
  * The exclusive lease is taken with intent. Only the wait is bounded by `signal` and by
1030
979
  * `sandbox.lockWaitSeconds` (`sandbox.busy` after that: a tool call holding the device keeps
@@ -1045,16 +994,11 @@ let SandboxService = class SandboxService {
1045
994
  return "not_running";
1046
995
  if (!this.mustApply(before, p, await this.wantedLimits(use)))
1047
996
  return "unchanged";
1048
- if (await this.retirement.hasUnresolved(env))
1049
- return "unchanged";
1050
997
  const lease = await this.leases.acquireExclusive(env, signal, this.config.get().sandbox.lockWaitSeconds * 1000, { intent: true });
1051
998
  try {
1052
999
  // the apply's own budget: the caller's signal bounded only the wait (an abort mid-update
1053
1000
  // would quarantine the instance, one mid-recreate would leave it `creating`)
1054
1001
  const sig = AbortSignal.any([AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), lease.signal]);
1055
- // under the lease the B1 snapshot writer needs: no limits change on a device carrying the
1056
- // reconcile marker (B-11)
1057
- await this.facts.assertCloudReconciled(use.orgId, env);
1058
1002
  // under the lease, as `ensure` checks: a device deleted while this waited gets nothing
1059
1003
  // recreated on it
1060
1004
  const live = await this.db
@@ -1070,8 +1014,6 @@ let SandboxService = class SandboxService {
1070
1014
  const row = await this.readRow(use);
1071
1015
  if (!this.usable(row, p, null))
1072
1016
  return "not_running";
1073
- if (await this.retirement.hasUnresolved(env))
1074
- return "unchanged";
1075
1017
  const fence = { gen: row.generation };
1076
1018
  // every acquisition first does a fenced increment, so a holder whose lease ended unnoticed
1077
1019
  // fails its next write; the provider calls below carry this holder's token
@@ -1121,8 +1063,8 @@ let SandboxService = class SandboxService {
1121
1063
  }
1122
1064
  /**
1123
1065
  * A `write_base` kernel read ({@link withKernelRead}) on the instance the device runs now, under
1124
- * a shared lease taken the way {@link ifRunning} takes it (B1 reconcile marker and retirement
1125
- * gate included): a device with no running instance, or one that changes instance before the
1066
+ * a shared lease taken the way {@link ifRunning} takes it: a device with no running instance, or
1067
+ * one that changes instance before the
1126
1068
  * lease, throws {@link KernelReadInstanceNotRunning} with nothing made, woken or sent.
1127
1069
  *
1128
1070
  * Unlike a use's `enter`, this path neither applies changed limits (`mustApply`, which needs the
@@ -1140,7 +1082,7 @@ let SandboxService = class SandboxService {
1140
1082
  const row = await this.readRow(ctx);
1141
1083
  if (!this.usable(row, p, null))
1142
1084
  throw new KernelReadInstanceNotRunning();
1143
- const result = await this.ifRunningAs(ctx.deviceId, { createdAt: row.created_at }, (_tagged, h, sig, held) => fn(h, this.kernelReadProvider(held, ctx, p, read, sig), { fresh: false, restarted: false, roots: rootsOf(h) }, sig), signal, true);
1085
+ const result = await this.ifRunningAs(ctx.deviceId, { createdAt: row.created_at }, (_tagged, h, sig, held) => fn(h, this.kernelReadProvider(held, ctx, p, read, sig), { fresh: false, restarted: false, roots: rootsOf(h) }, sig), signal);
1144
1086
  if (result.kind !== "ran")
1145
1087
  throw new KernelReadInstanceNotRunning();
1146
1088
  return result.value;
@@ -1628,9 +1570,7 @@ let SandboxService = class SandboxService {
1628
1570
  const row = await this.readRow(ctx);
1629
1571
  // an instance whose mode or network must change goes through the exclusive lease
1630
1572
  const ready = (r) => this.usable(r, p, gone) && !this.mustApply(r, p, want);
1631
- // a device with an unresolved retirement obligation is only entered through the
1632
- // exclusive lease, whose gate retires the old incarnation or refuses (8.5)
1633
- if (!(await this.retirement.hasUnresolved(env)) && ready(row)) {
1573
+ if (ready(row)) {
1634
1574
  const lease = await this.leases.tryShared(env, this.cap, token);
1635
1575
  if (lease) {
1636
1576
  if (intent)
@@ -1647,8 +1587,7 @@ let SandboxService = class SandboxService {
1647
1587
  throw err;
1648
1588
  }
1649
1589
  }
1650
- // an obligation recorded while the shared lease was taken: null, back to the gate
1651
- const e = await this.asShared(ctx, p, lease, ready, signal, true, "use");
1590
+ const e = await this.asShared(ctx, p, lease, ready, signal);
1652
1591
  if (e) {
1653
1592
  // B-15: cloud evidence gone stale while the instance ran (a provider upgrade)
1654
1593
  await this.refreshCloudSupport(ctx, p, e, AbortSignal.any([signal, e.lease.signal]), false);
@@ -1813,27 +1752,14 @@ let SandboxService = class SandboxService {
1813
1752
  * Under a just-taken shared lease: confirms the row is still `accept`ed (else releases and
1814
1753
  * returns null), records the holder and revokes crashed holders' operations exactly.
1815
1754
  */
1816
- async asShared(ctx, p, lease, accept, signal,
1817
- /**
1818
- * Refused (null) while the device has an unresolved retirement obligation, checked under the
1819
- * lease and before anything is revoked or bumped; false only for exact-ref managed drains.
1820
- */
1821
- gated,
1822
- /**
1823
- * Checked under the lease (which the B1 snapshot writer's exclusive lease excludes) before
1824
- * anything is revoked or bumped: `reconciled` and `use` refuse a device carrying the
1825
- * reconcile marker (B-11). `none` for background polls, stops and drains.
1826
- */
1827
- check = "none") {
1755
+ async asShared(ctx, p, lease, accept, signal) {
1828
1756
  const env = ctx.deviceId;
1829
1757
  try {
1830
1758
  const row = await this.readRow(ctx);
1831
- if (!accept(row) || (gated && (await this.retirement.hasUnresolved(env)))) {
1759
+ if (!accept(row)) {
1832
1760
  await lease.release();
1833
1761
  return null;
1834
1762
  }
1835
- if (check !== "none")
1836
- await this.facts.assertCloudReconciled(ctx.orgId, env);
1837
1763
  // Bump the fence as every acquisition did before phase C: an exclusive holder whose lease
1838
1764
  // expired unnoticed (a stalled sweep) then fails its next write instead of suspending or
1839
1765
  // destroying the instance under this holder. Shared holders never compare it.
@@ -1872,9 +1798,6 @@ let SandboxService = class SandboxService {
1872
1798
  const env = ctx.deviceId;
1873
1799
  const sig = AbortSignal.any([signal, lease.signal]);
1874
1800
  try {
1875
- // under the lease the B1 snapshot writer needs: a device carrying the reconcile marker gets
1876
- // no create, resume, rebuild, limits change, retirement destroy or revocation (B-11)
1877
- await this.facts.assertCloudReconciled(ctx.orgId, env);
1878
1801
  const s = await this.ensure(ctx, p, lease, sig, gone);
1879
1802
  // the dead holders' records are forgotten only after their revocation is owed (on a fresh
1880
1803
  // instance too: their intents still name them); a resume delivers what `ensure` revoked
@@ -2040,7 +1963,9 @@ let SandboxService = class SandboxService {
2040
1963
  for (const o of owed) {
2041
1964
  try {
2042
1965
  await revoke(handle, { operationId: o.operationId, admitBeforeMs: o.deadline.getTime() }, AbortSignal.any([signal, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS)]));
2043
- await runOutsideTransaction(() => this.operationIntents.acknowledgeRevocation(o.operationId));
1966
+ // The worker settles a background task and its cancellation before acknowledging.
1967
+ if (o.method !== "backgroundStart")
1968
+ await runOutsideTransaction(() => this.operationIntents.acknowledgeRevocation(o.operationId));
2044
1969
  }
2045
1970
  catch (err) {
2046
1971
  if (signal.aborted || isSandboxGoneError(err))
@@ -2366,706 +2291,6 @@ let SandboxService = class SandboxService {
2366
2291
  await lease.release();
2367
2292
  }
2368
2293
  }
2369
- /** The owner's proof-only pass of the retirement gate, with no provider lifecycle mutation. */
2370
- async checkLocalRetirement(owner, requested) {
2371
- const { orgId, deviceId, accountId } = owner;
2372
- if (!(await this.ownerLocalProvider(owner)))
2373
- return "blocked";
2374
- const lease = await this.leases.tryExclusive(deviceId, { unlessStreams: true });
2375
- if (!lease)
2376
- return "busy";
2377
- const signal = AbortSignal.any([
2378
- requested,
2379
- lease.signal,
2380
- AbortSignal.timeout(RETIREMENT_CHECK_TIMEOUT_MS),
2381
- ]);
2382
- try {
2383
- const p = await this.ownerLocalProvider(owner);
2384
- const attest = p?.impl.retirement;
2385
- if (!p || !attest || signal.aborted)
2386
- return "blocked";
2387
- if (!(await this.retirement.hasUnresolved(deviceId)))
2388
- return "clear";
2389
- const row = await this.readRow(owner);
2390
- if (!row?.handle ||
2391
- row.handle.id !== deviceId ||
2392
- row.provider !== p.plugin ||
2393
- !row.had_instance ||
2394
- (row.status !== "running" && row.status !== "suspended"))
2395
- return "blocked";
2396
- const currentGeneration = String(row.created_at.getTime());
2397
- const currentProviderGeneration = localRetirementGeneration(p, row.handle, deviceId);
2398
- if (!RETIREMENT_GENERATION.test(currentGeneration) || currentProviderGeneration === undefined)
2399
- return "blocked";
2400
- const machine = await this.db
2401
- .selectFrom("device_machines")
2402
- .select("id")
2403
- .where("org_id", "=", orgId)
2404
- .where("device_id", "=", deviceId)
2405
- .where("account_id", "=", accountId)
2406
- .where("revoked_at", "is", null)
2407
- .executeTakeFirst();
2408
- if (!machine || signal.aborted)
2409
- return "blocked";
2410
- const fence = { gen: row.generation };
2411
- await this.fenced(lease, deviceId, fence, {});
2412
- const check = {
2413
- ...owner,
2414
- machineId: machine.id,
2415
- currentGeneration,
2416
- fence: fence.gen,
2417
- };
2418
- for (const o of await this.retirement.quarantinedLocal(check)) {
2419
- if (signal.aborted)
2420
- break;
2421
- const recorded = await this.retirement.destructionRecorded(deviceId, o.provider, o.instanceGeneration);
2422
- const providerGeneration = recorded
2423
- ? undefined
2424
- : await this.retirement.localProviderGeneration(o);
2425
- if (!recorded) {
2426
- if (providerGeneration === undefined ||
2427
- BigInt(providerGeneration) >= BigInt(currentProviderGeneration))
2428
- continue;
2429
- const confirmed = await untilAborted(Promise.resolve().then(() => attest.attestRetired(deviceId, providerGeneration, signal)), signal).catch(() => false);
2430
- if (confirmed !== true)
2431
- continue;
2432
- }
2433
- if (signal.aborted || !(await lease.renew()))
2434
- break;
2435
- if (!(await this.selection.isOnInOrg(orgId, p.plugin)))
2436
- break;
2437
- await this.retirement.resolveLocalProof(check, o, providerGeneration, signal);
2438
- }
2439
- return (await this.retirement.hasUnresolved(deviceId)) ? "blocked" : "clear";
2440
- }
2441
- catch (err) {
2442
- if (signal.aborted || err instanceof SandboxLockLostError)
2443
- return "blocked";
2444
- throw err;
2445
- }
2446
- finally {
2447
- await lease.release();
2448
- }
2449
- }
2450
- async ownerLocalProvider(owner) {
2451
- const row = await this.db
2452
- .selectFrom("devices")
2453
- .select("provider")
2454
- .where("org_id", "=", owner.orgId)
2455
- .where("id", "=", owner.deviceId)
2456
- .where("owner_kind", "=", "personal")
2457
- .where("owner_account_id", "=", owner.accountId)
2458
- .where("deleted_at", "is", null)
2459
- .executeTakeFirst();
2460
- if (!row)
2461
- throw deviceNotFound();
2462
- if (row.provider !== LOCAL_RETIREMENT_PROVIDER)
2463
- return undefined;
2464
- const p = this.providers.forDevice(row.provider);
2465
- return p && servesDialIn(p) && (await this.selection.isOnInOrg(owner.orgId, p.plugin))
2466
- ? p
2467
- : undefined;
2468
- }
2469
- /**
2470
- * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
2471
- * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder
2472
- * has the device (the inline gate runs on its next lifecycle acquisition anyway); `unavailable`:
2473
- * an obligation stays (quarantined, or a destroy that failed); `clear`: none left.
2474
- */
2475
- async retireLegacy(deviceId,
2476
- /** The worker's signal (its stop, a lost run lock): ends a destroy in flight. */
2477
- signal) {
2478
- const lease = await this.leases.tryExclusive(deviceId);
2479
- if (!lease)
2480
- return "busy";
2481
- try {
2482
- // org-filter: deviceId comes from the retire-legacy-tasks worker's due list (kernel-held,
2483
- // not caller input); the worker runs it in the platform scope
2484
- const row = await this.db
2485
- .selectFrom("device_instances")
2486
- .selectAll()
2487
- .where("device_id", "=", deviceId)
2488
- .executeTakeFirst();
2489
- const fence = row ? { gen: row.generation } : null;
2490
- if (row && fence)
2491
- await this.fenced(lease, deviceId, fence, {});
2492
- await this.retireIncarnations(deviceId, lease, row, fence, signal);
2493
- return "clear";
2494
- }
2495
- catch (err) {
2496
- if (isRetirementPending(err))
2497
- return "unavailable";
2498
- throw err;
2499
- }
2500
- finally {
2501
- await lease.release();
2502
- }
2503
- }
2504
- /**
2505
- * The lifecycle reconcile of a cloud device carrying `permission_reconcile_required` (B-12),
2506
- * under one try at its exclusive lifecycle lease (`busy`: a holder has it). The snapshot
2507
- * writer's reconcile runs first ({@link CloudPermissionSnapshots.reconcileHeld}: it narrows the
2508
- * authority to what the instance is known to run, and may clear the marker by itself). A device
2509
- * with an unresolved retirement obligation stops there: its incarnation is the retirement
2510
- * gate's alone (never resumed here). When the
2511
- * marker stays on a live instance whose provider can `update`, the provider applies the
2512
- * reconcile target, which is never wider than the instance in any dimension, so this only
2513
- * narrows; a suspended instance is resumed for it (its leftover operations revoked exactly,
2514
- * nobody else holds it) and suspended again, as its row still says. `updated` records the target as
2515
- * applied (fenced) and the reconcile runs again, which clears the marker. No `update`, a
2516
- * `recreate` answer, a gone instance or a failure leave the marker and its file reset action.
2517
- */
2518
- async reconcileLimits(deviceId, signal = AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)) {
2519
- const lease = await this.leases.tryExclusive(deviceId);
2520
- if (!lease)
2521
- return "busy";
2522
- try {
2523
- // org-filter: reads the device's own org; deviceId comes from the reconcile sweep
2524
- // (kernel-held, not caller input), which runs in the platform scope
2525
- const device = await this.db
2526
- .selectFrom("devices")
2527
- .select(["org_id", "provider"])
2528
- .where("id", "=", deviceId)
2529
- .executeTakeFirst();
2530
- if (!device)
2531
- return { state: "skipped" };
2532
- const orgId = device.org_id;
2533
- const row = await this.db
2534
- .selectFrom("device_instances")
2535
- .selectAll()
2536
- .where("device_id", "=", deviceId)
2537
- .where("org_id", "=", orgId)
2538
- .executeTakeFirst();
2539
- const fence = row ? { gen: row.generation } : null;
2540
- if (row && fence)
2541
- await this.fenced(lease, deviceId, fence, {});
2542
- const before = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
2543
- // an incarnation under a retirement obligation is never resumed or updated here: only the
2544
- // retirement gate may touch it (C1); the marker stays until the gate cleared it
2545
- if (before.state === "reconcile-required" && (await this.retirement.hasUnresolved(deviceId)))
2546
- return before;
2547
- const p = row ? this.rowProvider(row) : undefined;
2548
- const update = p?.impl.update?.bind(p.impl);
2549
- if (before.state !== "reconcile-required" ||
2550
- before.target === undefined ||
2551
- !row?.handle ||
2552
- !fence ||
2553
- !p ||
2554
- !update ||
2555
- row.provider !== p.plugin ||
2556
- device.provider !== p.plugin ||
2557
- row.fs_status !== "ready" ||
2558
- (row.status !== "running" && row.status !== "suspended"))
2559
- return before;
2560
- const handle = row.handle;
2561
- // the effective limits with their resources, read under the lease: exactly the target, or
2562
- // the authority moved since the reconcile (the next round sees it)
2563
- const want = await this.deviceLimits({ orgId, deviceId });
2564
- if (!sameAppliedExactly(appliedOf(want), before.target))
2565
- return before;
2566
- const sig = AbortSignal.any([signal, opSignal(lease)]);
2567
- const facts = { deviceId, provider: p.plugin, to: before.target };
2568
- const suspended = row.status === "suspended";
2569
- // the intent first (device update fencing design §7.2): an update this holder never hears
2570
- // back from is applied again by the next exclusive use
2571
- const rec = readInstanceLimits(row.instance_limits);
2572
- await this.fenced(lease, deviceId, fence, {
2573
- instance_limits: instanceLimitsJson(rec.applied, rec.unapplied ?? undefined, appliedOf(want)),
2574
- });
2575
- let answer;
2576
- // whether the provider answered without applying (nothing in flight): the intent goes again
2577
- let settled = false;
2578
- // a stale holder leaves the instance as it is (a newer holder may use it)
2579
- let stale = false;
2580
- try {
2581
- if (suspended && (await p.impl.resume(handle, sig)) === "gone")
2582
- answer = "gone";
2583
- else {
2584
- // what the pause brought back is revoked exactly before the update (the row still says
2585
- // suspended: a failure is revoked again on the next resume)
2586
- if (suspended)
2587
- await this.revokeIncarnation(deviceId, { provider: p.plugin, generation: String(row.created_at.getTime()) }, handle, p, sig, false);
2588
- answer = await update(handle, providerLimits(want), sig, { token: fence.gen });
2589
- }
2590
- settled = answer !== "updated";
2591
- }
2592
- catch (err) {
2593
- // a newer holder applied a higher token: this one is stale (never recorded, §7.1)
2594
- if (isStaleFenceError(err)) {
2595
- stale = true;
2596
- throw await this.staleHolder(lease, deviceId, p.plugin, fence, "update", err);
2597
- }
2598
- if (sig.aborted)
2599
- throw err;
2600
- this.log.warn("cannot apply the reconcile limits to the sandbox instance", {
2601
- ...facts,
2602
- err,
2603
- });
2604
- answer = "recreate";
2605
- }
2606
- finally {
2607
- if (suspended && !stale)
2608
- await this.bestEffort(deviceId, "suspend the instance again after a limits update", (s) => p.impl.suspend(handle, s));
2609
- }
2610
- if (answer !== "updated") {
2611
- // the provider answered and changed nothing: the record goes back to what it was; a
2612
- // failed update keeps the intent for the next use
2613
- if (settled && (await lease.renew()))
2614
- await this.fenced(lease, deviceId, fence, {
2615
- instance_limits: instanceLimitsJson(rec.applied, rec.unapplied ?? undefined, rec.pending ?? undefined),
2616
- });
2617
- return before;
2618
- }
2619
- if (!(await lease.renew()))
2620
- throw new SandboxLockLostError(deviceId);
2621
- await this.fenced(lease, deviceId, fence, {
2622
- instance_limits: instanceLimitsJson(appliedOf(want)),
2623
- });
2624
- this.log.info("sandbox instance limits reconciled by the provider's update", facts);
2625
- const after = await runOutsideTransaction(() => this.snapshots.reconcileHeld(orgId, deviceId));
2626
- // a running instance records its evidence for the new limits now; a suspended one on its
2627
- // next use's resume
2628
- if (!suspended)
2629
- await this.refreshCloudSupport({ orgId, deviceId }, p, { handle, createdAt: row.created_at.getTime() }, sig, false);
2630
- return after;
2631
- }
2632
- finally {
2633
- await lease.release();
2634
- }
2635
- }
2636
- /**
2637
- * The worker's sweep of {@link reconcileLimits} (`sandbox-reconcile-limits`): for each loaded
2638
- * provider that can `update`, up to `limit` live cloud devices of its own carrying the marker on
2639
- * a live instance, in id order from that provider's shared keyset cursor that wraps around (no
2640
- * starvation), each tried at most once per {@link RECONCILE_RETRY_SECONDS} across replicas (a
2641
- * Redis marker). Rows of a provider that is not loaded are never touched. Returns how many it
2642
- * reconciled.
2643
- */
2644
- async reconcileMarked(limit = 10) {
2645
- let n = 0;
2646
- for (const p of this.providers.loaded()) {
2647
- if (p.impl.update)
2648
- n += await this.reconcileMarkedOf(p, limit);
2649
- }
2650
- return n;
2651
- }
2652
- /** {@link reconcileMarked} for the devices of one provider. */
2653
- async reconcileMarkedOf(p, limit) {
2654
- const cursorKey = reconcileCursorKey(p.plugin);
2655
- // org-filter: deployment-wide reconcile sweep (worker) over every org's marked devices of
2656
- // this provider
2657
- const page = (after, n) => asPlatform("deployment-wide reconcile sweep", () => this.db
2658
- .selectFrom("devices as d")
2659
- .innerJoin("device_instances as i", "i.device_id", "d.id")
2660
- .select("d.id")
2661
- .where("d.deleted_at", "is", null)
2662
- .where("d.permission_reconcile_required", "=", true)
2663
- .where("d.provider", "=", p.plugin)
2664
- .where("i.provider", "=", p.plugin)
2665
- .where("i.handle", "is not", null)
2666
- .where("i.status", "in", ["running", "suspended"])
2667
- .where(sql `d.id COLLATE "C" > ${after}`)
2668
- .orderBy(sql `d.id COLLATE "C"`)
2669
- .limit(n)
2670
- .execute());
2671
- // a keyset cursor shared by the replicas (the cron runs once per tick): each tick goes on
2672
- // after the last device the previous one visited and wraps around, so devices that stay
2673
- // marked never starve the ones after them
2674
- const after = (await this.redis.get(cursorKey).catch(() => null)) ?? "";
2675
- const rows = await page(after, limit);
2676
- if (rows.length < limit && after !== "") {
2677
- const seen = new Set(rows.map((r) => r.id));
2678
- for (const r of await page("", limit - rows.length))
2679
- if (!seen.has(r.id) && r.id <= after)
2680
- rows.push(r);
2681
- }
2682
- const last = rows.at(-1)?.id;
2683
- await this.redis
2684
- .set(cursorKey, last ?? "", "EX", 86_400)
2685
- .catch((err) => this.log.warn("cannot record the reconcile cursor", { err }));
2686
- let n = 0;
2687
- for (const { id } of rows) {
2688
- // a retry window shared by the replicas, not a lock: a second try within it waits
2689
- const first = await this.redis
2690
- .set(`capk:cloud-reconcile-tried:${id}`, "1", "EX", RECONCILE_RETRY_SECONDS, "GET")
2691
- .then((prev) => prev === null)
2692
- .catch(() => false);
2693
- if (!first)
2694
- continue;
2695
- try {
2696
- const r = await this.reconcileLimits(id);
2697
- if (r !== "busy" && r.state === "bound")
2698
- n++;
2699
- }
2700
- catch (err) {
2701
- this.log.warn("cannot reconcile a cloud device's limits; will retry", {
2702
- deviceId: id,
2703
- err,
2704
- });
2705
- }
2706
- }
2707
- return n;
2708
- }
2709
- /**
2710
- * The retirement gate (permission runtime cutover 8.5), under the exclusive lifecycle lease and
2711
- * before the instance is used, resumed, rebuilt, switched to another provider, bound or
2712
- * downgraded to shared use: every unresolved obligation of the device is settled here or the
2713
- * device is unavailable ({@link retirementPending}).
2714
- * - The obligation names the **current** incarnation (provider and exact generation): it is
2715
- * destroyed whole by its provider, whatever the provider (never resumed, never `killAll`ed,
2716
- * the file system kept), the confirmed destruction is recorded and the row reads
2717
- * `destroyed`, so the use creates a fresh instance; a failed destroy keeps the obligation.
2718
- * - B-22: a **suspended** current incarnation whose members are all revoked managed starts
2719
- * is not destroyed whole (its other tasks would be lost): each revoked ref gets its exact stop
2720
- * (persisted while suspended), the instance is resumed, each stop is confirmed (`stopped` or
2721
- * `already-exited`), and the obligation resolves as `exact-cancelled`. Any failure is noted on
2722
- * the obligation and falls back to the whole-instance destroy above. `resumed` given (a use):
2723
- * the resumed instance is left running for it (`resumed.resumed` set); otherwise (the worker),
2724
- * or when the device stays refused, it is suspended again, as its row still says.
2725
- * - It names an incarnation that is **not current** (replaced, a reused handle with another
2726
- * generation, unknown): resolved only by a recorded provider-confirmed destruction of exactly
2727
- * it, else quarantined. A newer generation is never evidence.
2728
- * Returns the row as it is afterwards.
2729
- */
2730
- async retireIncarnations(id, held, row, fence, signal,
2731
- /** A use's holder: a gate that resumed the instance (B-22) leaves it running and says so. */
2732
- resumed) {
2733
- // the device's own candidates first: the gate never depends on the worker having scanned (C1)
2734
- await this.retirement.scanUntilStable(5, id);
2735
- const open = await this.retirement.unresolved(id);
2736
- let now = row;
2737
- // every obligation is tried (one that stays never hides another that can resolve); the
2738
- // device is refused at the end while any stays, with the answer that tells what would help:
2739
- // a failed or impossible destroy now → unavailable (a retry may succeed); an incarnation no
2740
- // evidence can ever cover → recreate the device
2741
- let pending = false;
2742
- let failed = false;
2743
- const isLive = (r) => r !== undefined &&
2744
- r.handle !== null &&
2745
- (r.status === "running" || r.status === "suspended" || r.status === "creating");
2746
- /** The instance this gate resumed for an exact cancel and still runs (B-22). */
2747
- let resumedHere = null;
2748
- const bounded = () => AbortSignal.any([
2749
- opSignal(held),
2750
- AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2751
- ...(signal ? [signal] : []),
2752
- ]);
2753
- /**
2754
- * B-22: on a suspended current cloud incarnation whose members are all revoked managed
2755
- * starts, cancels each by its exact ref and resumes the instance in between. `skip`: the
2756
- * shape does not apply (the destroy follows); `failed`: a cancel could not be confirmed (the
2757
- * reason is noted, the destroy follows).
2758
- */
2759
- const cancelOnResume = async (o, live) => {
2760
- if (live.status !== "suspended" || !isKnownProvider(o.provider))
2761
- return "skip";
2762
- const impl = this.providers.forDevice(o.provider)?.impl;
2763
- const background = impl?.background;
2764
- if (!impl || !background)
2765
- return "skip";
2766
- const members = await this.retirement.membersOf(o.id);
2767
- if (members.length === 0 || members.some((m) => m.kind !== "revoked-start"))
2768
- return "skip";
2769
- const owed = [];
2770
- for (const m of members) {
2771
- const intent = await this.db
2772
- .selectFrom("sandbox_operation_intents")
2773
- .select([
2774
- "method",
2775
- "state",
2776
- "revoke_acknowledged",
2777
- "provider",
2778
- "instance_generation",
2779
- "execution_ref",
2780
- ])
2781
- .where("operation_id", "=", m.refId)
2782
- .where("org_id", "=", o.orgId)
2783
- .where("device_id", "=", id)
2784
- .executeTakeFirst();
2785
- if (intent?.revoke_acknowledged === true)
2786
- continue;
2787
- if (intent === undefined ||
2788
- intent.method !== "backgroundStart" ||
2789
- intent.state !== "revoked" ||
2790
- intent.provider !== o.provider ||
2791
- intent.instance_generation !== o.instanceGeneration)
2792
- return { failed: `revoked start ${m.refId} cannot be named on this incarnation` };
2793
- let ref;
2794
- try {
2795
- ref = parseSandboxExecutionRef(intent.execution_ref);
2796
- }
2797
- catch {
2798
- return { failed: `revoked start ${m.refId} has no valid execution reference` };
2799
- }
2800
- // the intent named the incarnation above; the ref's generation is the provider's own
2801
- if (ref.operationId !== m.refId || ref.instanceId !== live.handle.id)
2802
- return { failed: `revoked start ${m.refId} names another instance` };
2803
- owed.push(ref);
2804
- }
2805
- try {
2806
- // persisted while suspended: the provider applies a pending cancel before any work of
2807
- // the instance runs again; the answer is confirmed after the resume
2808
- for (const ref of owed) {
2809
- const r = await background.stop(live.handle, ref, {
2810
- graceMs: MANAGED_STOP_GRACE_MS,
2811
- signal: bounded(),
2812
- });
2813
- // anything but a recorded (or already settled) cancel: never resume into the work
2814
- if (r.outcome !== "cancel-pending" &&
2815
- r.outcome !== "stopped" &&
2816
- r.outcome !== "already-exited")
2817
- return {
2818
- failed: `the exact stop of ${ref.operationId} answered ${r.outcome} while suspended`,
2819
- };
2820
- }
2821
- if ((await impl.resume(live.handle, bounded())) === "gone")
2822
- return { failed: "the instance is gone at the provider" };
2823
- resumedHere = { impl, handle: live.handle };
2824
- for (const ref of owed) {
2825
- const r = await background.stop(live.handle, ref, {
2826
- graceMs: MANAGED_STOP_GRACE_MS,
2827
- signal: bounded(),
2828
- });
2829
- if (r.outcome !== "stopped" && r.outcome !== "already-exited")
2830
- return { failed: `the exact stop of ${ref.operationId} answered ${r.outcome}` };
2831
- }
2832
- }
2833
- catch (err) {
2834
- if (held.signal.aborted || signal?.aborted)
2835
- throw err;
2836
- return { failed: err instanceof Error ? err.message : String(err) };
2837
- }
2838
- if (!(await held.renew()))
2839
- throw new SandboxLockLostError(id);
2840
- this.log.info("revoked starts cancelled exactly on a resumed instance", {
2841
- deviceId: id,
2842
- operations: owed.map((r) => r.operationId),
2843
- });
2844
- // every member read is covered (an acknowledged one needed no stop)
2845
- return { cancelled: members.map((m) => m.refId) };
2846
- };
2847
- /**
2848
- * Destroys the live incarnation of `now` whole with its own provider (never resumed or
2849
- * killAll'ed, files kept), records the confirmed destruction and marks the row destroyed.
2850
- */
2851
- const destroyLive = async (o, live) => {
2852
- const provider = live.provider ?? "unknown";
2853
- const impl = isKnownProvider(provider) ? this.providers.forDevice(provider)?.impl : undefined;
2854
- if (!impl) {
2855
- await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2856
- return false;
2857
- }
2858
- try {
2859
- // bounded (M5): a hung provider never holds the lease or the worker's tick
2860
- await impl.destroy(live.handle, AbortSignal.any([
2861
- opSignal(held),
2862
- AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2863
- ...(signal ? [signal] : []),
2864
- ]), tokenOf(fence));
2865
- }
2866
- catch (err) {
2867
- if (held.signal.aborted || signal?.aborted)
2868
- throw err;
2869
- if (isStaleFenceError(err) && fence)
2870
- throw await this.staleHolder(held, id, provider, fence, "destroy", err);
2871
- await this.retirement.noteFailure(o.id, err);
2872
- this.log.warn("cannot destroy an instance that may run legacy work; device unavailable", {
2873
- deviceId: id,
2874
- err,
2875
- });
2876
- return false;
2877
- }
2878
- if (!(await held.renew()))
2879
- throw new SandboxLockLostError(id);
2880
- resumedHere = null;
2881
- await this.retirement.recordDestruction(id, provider, String(live.created_at.getTime()));
2882
- if (fence)
2883
- await this.fenced(held, id, fence, {
2884
- status: "destroyed",
2885
- destroyed_at: sql `now()`,
2886
- running_since: null,
2887
- suspended_at: null,
2888
- sweep_failed_at: null,
2889
- });
2890
- this.log.info("instance that may run legacy work destroyed", { deviceId: id });
2891
- // org-filter: the device this retirement gate holds under its exclusive lease; the instance
2892
- // row is keyed by its device
2893
- now = await this.db
2894
- .selectFrom("device_instances")
2895
- .selectAll()
2896
- .where("device_id", "=", id)
2897
- .executeTakeFirst();
2898
- return true;
2899
- };
2900
- /**
2901
- * R2-I1: the row is not live (destroyed before 0157 without a record, or a create that left
2902
- * `creating` with no handle). With no `prev_handle`, the row's own cloud provider holds at
2903
- * most one instance of the device's name (device-provider@1 same-name replacement), so its destroy by
2904
- * that name confirms every incarnation there; it is recorded as the destruction of the row's
2905
- * incarnation. A provider not loaded or a failed destroy keeps the obligation open.
2906
- */
2907
- const destroyNamed = async (o, row) => {
2908
- const provider = row.provider ?? "unknown";
2909
- const impl = isKnownProvider(provider) ? this.providers.forDevice(provider)?.impl : undefined;
2910
- if (!impl) {
2911
- await this.retirement.noteFailure(o.id, `provider ${provider} is not loaded`);
2912
- return false;
2913
- }
2914
- try {
2915
- await impl.destroyByName(deviceResourceName(id), AbortSignal.any([
2916
- opSignal(held),
2917
- AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS),
2918
- ...(signal ? [signal] : []),
2919
- ]), tokenOf(fence));
2920
- }
2921
- catch (err) {
2922
- if (held.signal.aborted || signal?.aborted)
2923
- throw err;
2924
- if (isStaleFenceError(err) && fence)
2925
- throw await this.staleHolder(held, id, provider, fence, "destroy", err);
2926
- await this.retirement.noteFailure(o.id, err);
2927
- this.log.warn("cannot destroy by name an instance that may run legacy work", {
2928
- deviceId: id,
2929
- err,
2930
- });
2931
- return false;
2932
- }
2933
- if (!(await held.renew()))
2934
- throw new SandboxLockLostError(id);
2935
- await this.retirement.recordDestruction(id, provider, String(row.created_at.getTime()));
2936
- if (fence && row.status === "creating")
2937
- await this.fenced(held, id, fence, {
2938
- status: "destroyed",
2939
- destroyed_at: sql `now()`,
2940
- running_since: null,
2941
- suspended_at: null,
2942
- sweep_failed_at: null,
2943
- });
2944
- this.log.info("instance that may run legacy work destroyed by name", { deviceId: id });
2945
- // org-filter: the device this retirement gate holds under its exclusive lease; the instance
2946
- // row is keyed by its device
2947
- now = await this.db
2948
- .selectFrom("device_instances")
2949
- .selectAll()
2950
- .where("device_id", "=", id)
2951
- .executeTakeFirst();
2952
- return true;
2953
- };
2954
- try {
2955
- for (const o of open) {
2956
- const gen = o.instanceGeneration;
2957
- const current = isLive(now) && now.provider === o.provider && String(now.created_at.getTime()) === gen;
2958
- if (current && isLive(now)) {
2959
- let cancel = await cancelOnResume(o, now);
2960
- if (cancel !== "skip" && "cancelled" in cancel) {
2961
- // resolved only while no member outside the stopped refs exists (a concurrent scan's)
2962
- if (await this.retirement.resolveCancelled(o.id, cancel.cancelled))
2963
- continue;
2964
- cancel = { failed: "a revoked start was recorded while the cancel ran" };
2965
- }
2966
- if (cancel !== "skip") {
2967
- this.log.warn("cannot cancel revoked starts exactly; destroying the instance", {
2968
- deviceId: id,
2969
- reason: cancel.failed,
2970
- });
2971
- await this.retirement.noteFailure(o.id, cancel.failed);
2972
- }
2973
- if (await destroyLive(o, now))
2974
- await this.retirement.resolveDestroyed(o.id);
2975
- else {
2976
- pending = true;
2977
- failed = true;
2978
- }
2979
- continue;
2980
- }
2981
- // the existing whole-instance destroy left the row `destroyed` on exactly this incarnation
2982
- // with nothing kept for a later retry: the provider confirmed it
2983
- const destroyedHere = now !== undefined &&
2984
- now.status === "destroyed" &&
2985
- now.provider === o.provider &&
2986
- String(now.created_at.getTime()) === gen &&
2987
- now.prev_handle === null &&
2988
- isKnownProvider(o.provider);
2989
- if (destroyedHere || (await this.retirement.destructionRecorded(id, o.provider, gen))) {
2990
- await this.retirement.resolveDestroyed(o.id);
2991
- continue;
2992
- }
2993
- if (gen === "unknown" || o.provider === "unknown") {
2994
- // R1-I1 (b): an incarnation the kernel cannot name. Every incarnation the device had
2995
- // stopped being current through a kernel destroy, a provider `gone` or a kept
2996
- // `prev_handle`; so once the device's current incarnation is destroyed with
2997
- // confirmation, nothing earlier is kept (`prev_handle`) and the obligation was recorded
2998
- // under the freeze (no dispatch after it), no instance of the device can run legacy work.
2999
- // This rests on device-provider@1 same-name replacement: every rebuild on the same provider goes
3000
- // through `create`, which first removes the old `cap-device-<id>` instance (so a `gone`
3001
- // answer, E2B's token-failure `gone` included, and `applyLimits`' swallowed destroy
3002
- // failure leave nothing behind), and E2B's incarnations are one sandbox (destroying the
3003
- // current one ends the earlier processes). A provider or kernel path that rebuilds
3004
- // without same-name replacement breaks this barrier.
3005
- const frozenAt = await this.retirement.frozenAt();
3006
- const reason = frozenAt === null || o.createdAt < frozenAt
3007
- ? "an unknown cloud incarnation recorded before the freeze"
3008
- : now === undefined || !now.had_instance
3009
- ? // a row (re)inserted by this acquisition knows nothing of the earlier instances
3010
- "an unknown cloud incarnation and no instance record to destroy"
3011
- : now.prev_handle !== null
3012
- ? "an unknown cloud incarnation while an earlier provider's instance may still exist"
3013
- : null;
3014
- if (reason === null && now !== undefined) {
3015
- if (isLive(now)) {
3016
- if (await destroyLive(o, now))
3017
- await this.retirement.resolveDestroyed(o.id);
3018
- else {
3019
- pending = true;
3020
- failed = true;
3021
- }
3022
- continue;
3023
- }
3024
- if (now.status === "destroyed" &&
3025
- now.provider !== null &&
3026
- (await this.retirement.destructionRecorded(id, now.provider, String(now.created_at.getTime())))) {
3027
- await this.retirement.resolveDestroyed(o.id);
3028
- continue;
3029
- }
3030
- // not live and nothing recorded (R2-I1): confirm by name with the row's provider
3031
- if (await destroyNamed(o, now))
3032
- await this.retirement.resolveDestroyed(o.id);
3033
- else {
3034
- pending = true;
3035
- failed = true;
3036
- }
3037
- continue;
3038
- }
3039
- await this.retirement.quarantine(o.id, reason ??
3040
- "an unknown cloud incarnation and no confirmed destruction of the current one");
3041
- pending = true;
3042
- continue;
3043
- }
3044
- await this.retirement.quarantine(o.id, "the old instance was replaced without a recorded confirmed destruction");
3045
- pending = true;
3046
- }
3047
- }
3048
- catch (err) {
3049
- // a throw after a resume (a lost lease, an abort, a failed write): the row still says
3050
- // suspended, so the instance is suspended again (best effort) before the error goes on
3051
- const left = resumedHere;
3052
- if (left !== null)
3053
- await this.bestEffort(id, "suspend the instance again after a failed retirement", (s) => left.impl.suspend(left.handle, s));
3054
- throw err;
3055
- }
3056
- // a use runs on the instance this gate resumed; anything else leaves it as its row says
3057
- const still = resumedHere;
3058
- if (still !== null && (pending || resumed === undefined)) {
3059
- await this.bestEffort(id, "suspend the instance again after an exact cancel", (s) => still.impl.suspend(still.handle, s));
3060
- }
3061
- else if (still !== null && resumed !== undefined)
3062
- resumed.resumed = true;
3063
- if (pending)
3064
- throw failed
3065
- ? retirementPending()
3066
- : recreateRequired(now?.provider === LOCAL_RETIREMENT_PROVIDER);
3067
- return now;
3068
- }
3069
2294
  /**
3070
2295
  * A fenced write: only while the lease holds and the row's generation is still the one read
3071
2296
  * under it (and incremented); otherwise {@link SandboxLockLostError}.
@@ -3190,155 +2415,216 @@ let SandboxService = class SandboxService {
3190
2415
  throw deviceNotFound();
3191
2416
  // org-filter: reads org_id and throws foreign below (the device itself was just checked in
3192
2417
  // ctx.orgId)
3193
- const read = await this.db
2418
+ const row = await this.db
3194
2419
  .selectFrom("device_instances")
3195
2420
  .selectAll()
3196
2421
  .where("device_id", "=", id)
3197
2422
  .executeTakeFirst();
3198
- if (!read)
2423
+ if (!row)
3199
2424
  throw deviceNotFound();
3200
- if (read.org_id !== ctx.orgId)
2425
+ if (row.org_id !== ctx.orgId)
3201
2426
  throw this.foreign(ctx);
3202
- const fence = { gen: read.generation };
2427
+ const fence = { gen: row.generation };
3203
2428
  // Every acquisition first does a fenced increment: an old holder whose lease expired while it
3204
2429
  // kept running (a stalled sweep) then fails its next write.
3205
2430
  await this.fenced(held, id, fence, {});
3206
- // the retirement gate (8.5), before any use, resume, rebuild or bind: an
3207
- // old incarnation that may run legacy work is destroyed (cloud, confirmed) or refuses
3208
2431
  signal.throwIfAborted();
3209
- const gate = { resumed: false, running: false };
3210
- const row = (await this.retireIncarnations(id, held, read, fence, undefined, gate)) ?? read;
3211
- try {
3212
- if (row.fs_status === "lost")
3213
- throw deviceFilesLost();
3214
- // a device is bound to its provider for life: an instance row of another provider (never
3215
- // written by this kernel) is refused as it is, never taken over
3216
- if (row.provider !== null && row.provider !== p.plugin) {
3217
- throw deviceInstanceForeign(p.plugin, row.provider);
3218
- }
3219
- // read under the lease, after the fence moved: a value read before the wait may be stale
3220
- // (another replica may have changed the mode meanwhile)
3221
- const want = await this.wantedLimits(ctx);
3222
- const handle = row.handle;
3223
- const createdAt = row.created_at.getTime();
3224
- const fsResets = row.fs_resets;
3225
- if (handle && isInstance(row, gone) && row.status === "running") {
3226
- await this.destroyGone(id, p, held, row, handle, fence, signal);
3227
- const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
3228
- return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2432
+ if (row.fs_status === "lost")
2433
+ throw deviceFilesLost();
2434
+ // a device is bound to its provider for life: an instance row of another provider (never
2435
+ // written by this kernel) is refused as it is, never taken over
2436
+ if (row.provider !== null && row.provider !== p.plugin) {
2437
+ throw deviceInstanceForeign(p.plugin, row.provider);
2438
+ }
2439
+ // read under the lease, after the fence moved: a value read before the wait may be stale
2440
+ // (another replica may have changed the mode meanwhile)
2441
+ const want = await this.wantedLimits(ctx);
2442
+ const handle = row.handle;
2443
+ const createdAt = row.created_at.getTime();
2444
+ const fsResets = row.fs_resets;
2445
+ if (handle && isInstance(row, gone) && row.status === "running") {
2446
+ await this.destroyForReplacement(id, p, held, row, handle, fence, signal);
2447
+ const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
2448
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2449
+ }
2450
+ if (handle && row.status === "running") {
2451
+ const must = this.mustApply(row, p, want);
2452
+ const installed = !must && (await this.installedNetworkWider(id, p, row, handle, signal, want));
2453
+ // aborted while reading: the instance runs as it was (no quarantine of a healthy instance
2454
+ // for a cancel); the next exclusive step reads again
2455
+ if (installed && signal.aborted)
2456
+ throw abortReason(signal);
2457
+ if (must || installed) {
2458
+ const created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want, installed);
2459
+ if (created)
2460
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
3229
2461
  }
3230
- if (handle && row.status === "running") {
2462
+ return { handle, createdAt, fsResets, info: { fresh: false, restarted: false }, fence };
2463
+ }
2464
+ if (handle && row.status === "suspended") {
2465
+ const r = await this.lifecycleStep("resume", id, p, signal, async () => {
2466
+ try {
2467
+ const next = await runOutsideTransaction(() => this.cancelBeforeResume(row, handle, p, signal));
2468
+ if (next === "replace")
2469
+ return next;
2470
+ }
2471
+ catch (error) {
2472
+ if (isSandboxGoneError(error))
2473
+ return "gone";
2474
+ throw error;
2475
+ }
2476
+ return p.impl.resume(handle, signal);
2477
+ });
2478
+ if (r === "resumed") {
2479
+ const incarnation = { provider: p.plugin, generation: String(createdAt) };
2480
+ // the new limits first: the row says running only once the instance runs with them
2481
+ // (and again when the instance's installed network allows more than the record: #766)
3231
2482
  const must = this.mustApply(row, p, want);
3232
2483
  const installed = !must && (await this.installedNetworkWider(id, p, row, handle, signal, want));
3233
- // aborted while reading: the instance runs as it was (no quarantine of a healthy instance
3234
- // for a cancel); the next exclusive step reads again
3235
- if (installed && signal.aborted)
3236
- throw abortReason(signal);
3237
2484
  if (must || installed) {
3238
- const created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want, installed);
3239
- if (created)
3240
- return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
3241
- }
3242
- return { handle, createdAt, fsResets, info: { fresh: false, restarted: false }, fence };
3243
- }
3244
- if (handle && row.status === "suspended") {
3245
- // the retirement gate may have resumed it already, to cancel revoked starts exactly (B-22)
3246
- const r = gate.resumed
3247
- ? "resumed"
3248
- : await this.lifecycleStep("resume", id, p, signal, () => p.impl.resume(handle, signal));
3249
- if (r === "resumed") {
3250
- const incarnation = { provider: p.plugin, generation: String(createdAt) };
3251
- // the new limits first: the row says running only once the instance runs with them
3252
- // (and again when the instance's installed network allows more than the record: #766)
3253
- const must = this.mustApply(row, p, want);
3254
- const installed = !must && (await this.installedNetworkWider(id, p, row, handle, signal, want));
3255
- if (must || installed) {
3256
- let created;
3257
- try {
3258
- created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want, installed);
3259
- }
3260
- catch (err) {
3261
- // refused as stale: the provider changed nothing, and the instance (the same
3262
- // incarnation after an in-place update) may already run a newer holder's work
3263
- if (err instanceof SandboxLockLostError && err.reason === "generation")
3264
- throw err;
3265
- // the work a pause brought back is revoked exactly, never killed broadly; the row
3266
- // still says suspended, so the next use resumes and revokes again
3267
- await this.revokeIncarnation(id, incarnation, handle, p, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS), false).catch((e) => this.log.warn("cannot revoke the operations left after a failed limits change", {
3268
- deviceId: id,
3269
- err: e,
3270
- }));
3271
- throw err;
3272
- }
3273
- if (created) {
3274
- return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
3275
- }
3276
- }
3277
- // the work a pause brought back (every admitted, dispatching and started-or-unknown
3278
- // operation of this generation) is revoked before the row says running; the revokes are
3279
- // delivered before the downgrade. A failure fails the use closed: the instance is
3280
- // suspended again (best effort, its failure only warned), the row still says
3281
- // suspended, and the next use resumes and revokes again
2485
+ let created;
3282
2486
  try {
3283
- await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(id, incarnation));
2487
+ created = await this.applyLimits(ctx, p, held, row, handle, fence, signal, want, installed);
3284
2488
  }
3285
2489
  catch (err) {
3286
- await this.bestEffort(id, "suspend the instance again after a failed revocation", (s) => p.impl.suspend(handle, s));
2490
+ // refused as stale: the provider changed nothing, and the instance (the same
2491
+ // incarnation after an in-place update) may already run a newer holder's work
2492
+ if (err instanceof SandboxLockLostError && err.reason === "generation")
2493
+ throw err;
2494
+ // the work a pause brought back is revoked exactly, never killed broadly; the row
2495
+ // still says suspended, so the next use resumes and revokes again
2496
+ await this.revokeIncarnation(id, incarnation, handle, p, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS), false).catch((e) => this.log.warn("cannot revoke the operations left after a failed limits change", {
2497
+ deviceId: id,
2498
+ err: e,
2499
+ }));
3287
2500
  throw err;
3288
2501
  }
3289
- await this.fenced(held, id, fence, {
3290
- status: "running",
3291
- running_since: sql `now()`,
3292
- suspended_at: null,
3293
- sweep_failed_at: null,
3294
- });
3295
- gate.running = true;
3296
- return {
3297
- handle,
3298
- createdAt,
3299
- fsResets,
3300
- info: { fresh: false, restarted: false },
3301
- fence,
3302
- resumed: true,
3303
- };
2502
+ if (created) {
2503
+ return { ...created, fsResets, info: { fresh: true, restarted: true }, fence };
2504
+ }
3304
2505
  }
3305
- this.log.info("sandbox instance is gone at the provider; recreating", {
3306
- deviceId: id,
2506
+ // the work a pause brought back (every admitted, dispatching and started-or-unknown
2507
+ // operation of this generation) is revoked before the row says running; the revokes are
2508
+ // delivered before the downgrade. A failure fails the use closed: the instance is
2509
+ // suspended again (best effort, its failure only warned), the row still says
2510
+ // suspended, and the next use resumes and revokes again
2511
+ try {
2512
+ await runOutsideTransaction(() => this.operationIntents.revokeIncarnation(id, incarnation));
2513
+ }
2514
+ catch (err) {
2515
+ await this.bestEffort(id, "suspend the instance again after a failed revocation", (s) => p.impl.suspend(handle, s));
2516
+ throw err;
2517
+ }
2518
+ await this.fenced(held, id, fence, {
2519
+ status: "running",
2520
+ running_since: sql `now()`,
2521
+ suspended_at: null,
2522
+ sweep_failed_at: null,
3307
2523
  });
3308
- await this.destroyGone(id, p, held, row, handle, fence, signal);
2524
+ return {
2525
+ handle,
2526
+ createdAt,
2527
+ fsResets,
2528
+ info: { fresh: false, restarted: false },
2529
+ fence,
2530
+ resumed: true,
2531
+ };
3309
2532
  }
3310
- const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
3311
- // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
3312
- // makes this one a restart on the kept files
3313
- return {
3314
- ...created,
3315
- fsResets,
3316
- info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
3317
- fence,
3318
- };
2533
+ this.log.info("sandbox instance must be replaced before use", {
2534
+ deviceId: id,
2535
+ reason: r,
2536
+ });
2537
+ await this.destroyForReplacement(id, p, held, row, handle, fence, signal);
3319
2538
  }
3320
- catch (err) {
3321
- // the gate resumed the instance for an exact cancel (B-22) and this use failed before its
3322
- // row said running: suspended again (best effort), as the row still says
3323
- const resumedHandle = row.handle;
3324
- if (gate.resumed && !gate.running && resumedHandle)
3325
- await this.bestEffort(id, "suspend the instance again after a failed use", (s) => p.impl.suspend(resumedHandle, s));
3326
- throw err;
2539
+ const created = await this.createSettled(ctx, p, held, row, fence, signal, want);
2540
+ // had_instance only ever becomes true: any earlier instance (even if a rebuild failed since)
2541
+ // makes this one a restart on the kept files
2542
+ return {
2543
+ ...created,
2544
+ fsResets,
2545
+ info: { fresh: true, restarted: row.had_instance && row.fs_status === "ready" },
2546
+ fence,
2547
+ };
2548
+ }
2549
+ /** Persist exact cancellations on the suspended instance before its processes can run again. */
2550
+ async cancelBeforeResume(row, handle, p, signal) {
2551
+ const instance = {
2552
+ deviceId: row.device_id,
2553
+ provider: p.plugin,
2554
+ instanceGeneration: String(row.created_at.getTime()),
2555
+ };
2556
+ const owed = await this.db
2557
+ .selectFrom("sandbox_operation_intents as intent")
2558
+ .select(["intent.operation_id", "intent.execution_ref", "intent.deadline"])
2559
+ .where("intent.org_id", "=", row.org_id)
2560
+ .where("intent.device_id", "=", instance.deviceId)
2561
+ .where("intent.provider", "=", instance.provider)
2562
+ .where("intent.instance_generation", "=", instance.instanceGeneration)
2563
+ .where("intent.method", "=", "backgroundStart")
2564
+ .where((eb) => eb.or([
2565
+ eb.and([
2566
+ eb("intent.state", "=", "revoked"),
2567
+ eb("intent.revoke_acknowledged", "=", false),
2568
+ eb.or([
2569
+ eb("intent.execution_ref", "is not", null),
2570
+ eb("intent.outcome_unknown", "=", true),
2571
+ ]),
2572
+ ]),
2573
+ eb.and([
2574
+ eb("intent.state", "=", "background-running"),
2575
+ eb.exists(eb
2576
+ .selectFrom("background_tasks as task")
2577
+ .select("task.id")
2578
+ .whereRef("task.operation_id", "=", "intent.operation_id")
2579
+ .whereRef("task.org_id", "=", "intent.org_id")
2580
+ .whereRef("task.device_id", "=", "intent.device_id")
2581
+ .whereRef("task.instance_generation", "=", "intent.instance_generation")
2582
+ .where("task.status", "=", "running")
2583
+ .where("task.launch_state", "=", "cancel-pending")),
2584
+ ]),
2585
+ ]))
2586
+ .execute();
2587
+ for (const intent of owed) {
2588
+ const attempt = AbortSignal.any([signal, AbortSignal.timeout(MAINTENANCE_CALL_TIMEOUT_MS)]);
2589
+ if (intent.execution_ref === null) {
2590
+ if (!p.impl.revokeOperation)
2591
+ throw new SandboxOperationOutcomeUnknownError("Cannot revoke an unconfirmed background launch before resume");
2592
+ await p.impl.revokeOperation(handle, { operationId: intent.operation_id, admitBeforeMs: intent.deadline.getTime() }, attempt);
2593
+ await this.operationIntents.recordResumeProof(row.org_id, intent.operation_id, {
2594
+ ...instance,
2595
+ ref: null,
2596
+ result: { outcome: "tombstone" },
2597
+ });
2598
+ continue;
2599
+ }
2600
+ const ref = parseSandboxExecutionRef(intent.execution_ref);
2601
+ if (!p.impl.background ||
2602
+ ref.instanceId !== handle.id ||
2603
+ ref.operationId !== intent.operation_id)
2604
+ throw new SandboxOperationOutcomeUnknownError("Cannot cancel a background execution on its recorded instance before resume");
2605
+ // A pending stop is persisted by the provider before suspended work runs again.
2606
+ const stopped = await p.impl.background.stop(handle, ref, {
2607
+ graceMs: MANAGED_STOP_GRACE_MS,
2608
+ signal: attempt,
2609
+ });
2610
+ if (stopped.outcome === "cancel-pending")
2611
+ continue;
2612
+ if (stopped.outcome === "lost" && row.provider === p.plugin && !servesDialIn(p))
2613
+ return "replace";
2614
+ if (stopped.outcome !== "stopped" && stopped.outcome !== "already-exited")
2615
+ throw new SandboxOperationOutcomeUnknownError("The device could not confirm cancellation of a background execution before resume");
2616
+ // The final failed worker attempt may race this resume. Persist the proof while the
2617
+ // incarnation is still locked so the worker can settle the task even after retries end.
2618
+ await this.operationIntents.recordResumeProof(row.org_id, intent.operation_id, {
2619
+ ...instance,
2620
+ ref,
2621
+ result: stopped,
2622
+ });
3327
2623
  }
2624
+ return "resume";
3328
2625
  }
3329
- /**
3330
- * Under the exclusive lease, before the rebuild of an instance its provider answered gone
3331
- * (`SandboxGoneError` during a use, or `resume` answering `gone`): the row's incarnation is
3332
- * destroyed through its provider with this holder's fence token (a no-op where it is really
3333
- * gone; on a provider whose `gone` means "never served again", such as a local machine whose
3334
- * program restarted, it ends what the generation left) and that confirmed destruction is
3335
- * recorded (8.5 evidence) before anything new is created. Its revoked starts and owed revokes
3336
- * then settle against the record once a new incarnation runs, instead of quarantining the
3337
- * device for an incarnation replaced without a recorded destruction. A destroy that fails fails
3338
- * the use with nothing rebuilt: the row still names the gone incarnation, so the next use is
3339
- * told gone again and retries (unavailable for now, never `device.recreate_required`).
3340
- */
3341
- async destroyGone(id, p, held, row, handle, fence, signal) {
2626
+ /** Destroy the exact instance with the current fence before replacing it on the same files. */
2627
+ async destroyForReplacement(id, p, held, row, handle, fence, signal) {
3342
2628
  assertOwnRow(row, p);
3343
2629
  // still the holder (a fenced write), so the destroy's token is this holder's latest
3344
2630
  await this.fenced(held, id, fence, {});
@@ -3349,7 +2635,7 @@ let SandboxService = class SandboxService {
3349
2635
  if (isStaleFenceError(err))
3350
2636
  throw await this.staleHolder(held, id, p.plugin, fence, "destroy", err);
3351
2637
  if (!signal.aborted)
3352
- this.log.warn("cannot destroy the gone sandbox instance; it is rebuilt on a later use", {
2638
+ this.log.warn("cannot destroy the sandbox instance before replacement; a later use retries", {
3353
2639
  deviceId: id,
3354
2640
  err,
3355
2641
  });
@@ -3357,7 +2643,7 @@ let SandboxService = class SandboxService {
3357
2643
  }
3358
2644
  if (!(await held.renew()))
3359
2645
  throw new SandboxLockLostError(id);
3360
- await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
2646
+ await this.recordDestruction(row, p);
3361
2647
  }
3362
2648
  /**
3363
2649
  * {@link create} from {@link ensure}, then, for a provider whose limits are fixed at its file
@@ -3393,11 +2679,6 @@ let SandboxService = class SandboxService {
3393
2679
  // instance has none yet (NULL): its first commit is no roots change (no consent reset, no
3394
2680
  // revoke)
3395
2681
  const committedRoots = row.permission_roots ?? (row.handle ? rootsOf(row.handle) : null);
3396
- const previousGeneration = row.handle && row.had_instance && row.provider === p.plugin
3397
- ? localRetirementGeneration(p, row.handle, id)
3398
- : undefined;
3399
- if (previousGeneration !== undefined)
3400
- await runOutsideTransaction(() => this.instanceWrites.preserveRetirementIdentity(ctx.orgId, id, fence.gen, previousGeneration, held.signal));
3401
2682
  await this.fenced(held, id, fence, {
3402
2683
  org_id: ctx.orgId,
3403
2684
  provider: p.plugin,
@@ -3484,7 +2765,7 @@ let SandboxService = class SandboxService {
3484
2765
  running_since: sql `now()`,
3485
2766
  last_used_at: sql `now()`,
3486
2767
  ...(!atFileSystem && { instance_limits: record }),
3487
- }, held.signal, support, localRetirementGeneration(p, handle, id)));
2768
+ }, held.signal, support));
3488
2769
  fence.gen++;
3489
2770
  }
3490
2771
  catch (e) {
@@ -3592,37 +2873,7 @@ let SandboxService = class SandboxService {
3592
2873
  return null;
3593
2874
  }
3594
2875
  this.log.info("sandbox limits changed; recreating the instance on the kept files", facts);
3595
- // the provider answered gone: destroyed with confirmation and recorded before the rebuild
3596
- if (gone)
3597
- await this.destroyGone(id, p, held, row, handle, fence, signal);
3598
- else {
3599
- // still the holder (a fenced write), so a holder whose lease ended meanwhile never destroys
3600
- // what a newer one uses; the destroy's token is then this holder's latest
3601
- await this.fenced(held, id, fence, {});
3602
- let destroyed = false;
3603
- try {
3604
- await p.impl.destroy(handle, signal, { token: fence.gen });
3605
- destroyed = true;
3606
- }
3607
- catch (err) {
3608
- if (isStaleFenceError(err))
3609
- throw await this.staleHolder(held, id, p.plugin, fence, "destroy", err);
3610
- // `create` replaces an instance of the same name anyway
3611
- if (signal.aborted)
3612
- throw err;
3613
- this.log.warn("cannot destroy the sandbox instance before recreating it", {
3614
- deviceId: id,
3615
- err,
3616
- });
3617
- }
3618
- // the provider's destroy resolved: confirmed destruction of exactly this incarnation (8.5
3619
- // evidence, as in destroyRow), so its owed revokes settle once the new one runs
3620
- if (destroyed) {
3621
- if (!(await held.renew()))
3622
- throw new SandboxLockLostError(id);
3623
- await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
3624
- }
3625
- }
2876
+ await this.destroyForReplacement(id, p, held, row, handle, fence, signal);
3626
2877
  return await this.lifecycleStep("recreate", id, p, signal, () => this.create(ctx, p, held, row, fence, signal, want));
3627
2878
  }
3628
2879
  /**
@@ -3721,31 +2972,21 @@ let SandboxService = class SandboxService {
3721
2972
  }
3722
2973
  }
3723
2974
  /**
3724
- * Destroys an instance an earlier kernel recorded in `prev_*` (left by a provider replaced back
3725
- * then) with that provider: still loaded and destroyed → false; otherwise warns and returns true
3726
- * (the record must be kept).
2975
+ * Destroy the exact previous handle before its row can be cleared or deleted. An earlier
2976
+ * kernel recorded no generation for this handle, so its destruction cannot acknowledge an intent.
3727
2977
  */
3728
2978
  async retire(id, provider, handle, signal, fence) {
3729
2979
  const old = this.providers.forDevice(provider)?.impl;
3730
- if (old) {
3731
- try {
3732
- await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]), tokenOf(fence));
3733
- return false;
3734
- }
3735
- catch (err) {
3736
- // the previous provider's instance carries a higher token: this holder is stale
3737
- if (isStaleFenceError(err))
3738
- throw new SandboxLockLostError(id, "generation");
3739
- this.log.warn("cannot destroy a sandbox instance recorded from a previous provider", {
3740
- deviceId: id,
3741
- provider,
3742
- err,
3743
- });
3744
- return true;
3745
- }
2980
+ if (!old)
2981
+ throw new Error(`cannot destroy device ${id}'s previous instance: provider ${provider} is not loaded`);
2982
+ try {
2983
+ await old.destroy(handle, AbortSignal.any([signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]), tokenOf(fence));
2984
+ }
2985
+ catch (err) {
2986
+ if (isStaleFenceError(err))
2987
+ throw new SandboxLockLostError(id, "generation");
2988
+ throw err;
3746
2989
  }
3747
- this.log.warn("a sandbox instance recorded from a previous provider that is not loaded may leak", { deviceId: id, provider });
3748
- return true;
3749
2990
  }
3750
2991
  /**
3751
2992
  * Under the lease: destroys the row's instance with its own provider `p` (and an instance an
@@ -3755,10 +2996,12 @@ let SandboxService = class SandboxService {
3755
2996
  async destroyInstance(row, p, signal, held, fence) {
3756
2997
  const id = row.device_id;
3757
2998
  assertOwnRow(row, p);
3758
- let prev = {};
3759
2999
  try {
3760
3000
  if (row.handle) {
3761
3001
  await p.impl.destroy(row.handle, signal, tokenOf(fence));
3002
+ if (!(await held.renew()))
3003
+ throw new SandboxLockLostError(id);
3004
+ await this.recordDestruction(row, p);
3762
3005
  }
3763
3006
  else if (row.status === "creating") {
3764
3007
  // the provider may have built it already: only the name finds it
@@ -3771,11 +3014,19 @@ let SandboxService = class SandboxService {
3771
3014
  throw err;
3772
3015
  }
3773
3016
  if (row.prev_handle && row.prev_provider) {
3774
- if (!(await this.retire(id, row.prev_provider, row.prev_handle, signal, fence))) {
3775
- prev = { prev_provider: null, prev_handle: null };
3776
- }
3017
+ await this.retire(id, row.prev_provider, row.prev_handle, signal, fence);
3018
+ return { prev_provider: null, prev_handle: null };
3777
3019
  }
3778
- return prev;
3020
+ return {};
3021
+ }
3022
+ /** A dial-in destroy can return while the machine is offline or already on another generation. */
3023
+ async recordDestruction(row, p) {
3024
+ if (row.provider !== p.plugin || servesDialIn(p))
3025
+ return;
3026
+ await runOutsideTransaction(() => this.operationIntents.recordDestruction(row.org_id, row.device_id, {
3027
+ provider: p.plugin,
3028
+ generation: String(row.created_at.getTime()),
3029
+ }));
3779
3030
  }
3780
3031
  /**
3781
3032
  * Under the lease: destroys the row's file system with its own provider `p` (by name when no
@@ -3801,10 +3052,6 @@ let SandboxService = class SandboxService {
3801
3052
  await this.fenced(held, id, fence, {});
3802
3053
  const signal = opSignal(held);
3803
3054
  const prev = await this.destroyInstance(row, p, signal, held, fence);
3804
- // the provider's destroy resolved: confirmed destruction of exactly this incarnation (8.5
3805
- // evidence), the same for every provider
3806
- if (row.handle && isKnownProvider(p.plugin))
3807
- await this.retirement.recordDestruction(id, p.plugin, String(row.created_at.getTime()));
3808
3055
  if (mode === "device")
3809
3056
  await this.destroyFiles(row, p, signal);
3810
3057
  if (!(await held.renew()))
@@ -3841,10 +3088,6 @@ let SandboxService = class SandboxService {
3841
3088
  eb.or([eb("last_used_at", "<", idleBefore), eb("running_since", "<", runningBefore)]),
3842
3089
  ]);
3843
3090
  }
3844
- /** The loaded provider of an instance row (its own `provider`); undefined when not loaded. */
3845
- rowProvider(row) {
3846
- return this.providers.forDevice(row.provider);
3847
- }
3848
3091
  /** The device was deleted, or its org was: the instance and the files go. */
3849
3092
  deviceGone(eb) {
3850
3093
  // org-filter: a sweep condition fragment (a deleted device of any org, correlated to the
@@ -3885,10 +3128,8 @@ SandboxService = __decorate([
3885
3128
  __param(8, Inject(SandboxOperationIntents)),
3886
3129
  __param(9, Inject(SandboxOperationAuthority)),
3887
3130
  __param(10, Inject(PermissionInstanceWrites)),
3888
- __param(11, Inject(LegacyRetirementStore)),
3889
- __param(12, Inject(CloudPermissionSnapshots)),
3890
- __param(13, Inject(DeviceReports)),
3891
- __param(14, Optional()),
3892
- __param(14, Inject(DialInRelay))
3131
+ __param(11, Inject(DeviceReports)),
3132
+ __param(12, Optional()),
3133
+ __param(12, Inject(DialInRelay))
3893
3134
  ], SandboxService);
3894
3135
  export { SandboxService };