@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
@@ -1,1165 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __param = (this && this.__param) || function (paramIndex, decorator) {
8
- return function (target, key) { decorator(target, key, paramIndex); }
9
- };
10
- import { parseSandboxExecutionRef } from "@capybara-hq/plugin-sdk";
11
- import { Inject, Injectable } from "@nestjs/common";
12
- import { sql } from "kysely";
13
- import { KernelDb } from "../infra/database/kernel-db.js";
14
- import { asPlatform } from "../infra/database/org-scope.js";
15
- import { TransactionHost } from "../infra/database/transaction-host.js";
16
- import { Transactional } from "../infra/database/transactional.decorator.js";
17
- import { PermissionAuthorityLock } from "./permission-authority-lock.js";
18
- import { LOCAL_RETIREMENT_PROVIDER, RETIREMENT_GENERATION } from "./providers.js";
19
- /**
20
- * Legacy retirement (permission runtime cutover phase 8.5): the durable legacy-launch freeze and
21
- * the physical no-reuse obligations of old instance incarnations (migration 0157).
22
- *
23
- * - **Freeze.** {@link freeze} writes the one freeze row under the platform authority writer (the
24
- * exclusive platform permission lock). An R1 (protocol 2) kernel admitted each legacy SID
25
- * launch under the shared platform lock immediately before its dispatch and refused once the
26
- * row existed, marking an admitted reservation `dispatched` with the incarnation it dispatched
27
- * into; this release launches no SID task, so it only reads those marks. A replica without the
28
- * fence must be stopped or drained before the freeze (the rows it writes still read `unknown`,
29
- * never "not dispatched", and the periodic re-scan picks them up).
30
- * - **Obligations.** {@link scan} enumerates, under the freeze, every legacy row whose processes
31
- * may still exist (running with a SID, a reservation that may have dispatched, a stop in flight,
32
- * `kill_pending` including terminal rows, a possibly dispatched launch that failed), and every
33
- * revoked managed background start whose recorded generation no longer runs (the 8.4 handoff).
34
- * Each becomes a member of the obligation of its device, provider and exact instance
35
- * generation. A SID, PID or output text is never turned into an execution reference: it only
36
- * names the row. Obligations live apart from the task rows, so output retention never removes
37
- * them, and task finish and event semantics stay with the task's own finisher.
38
- * - **Resolution** is the sandbox service's, under the device's exclusive lifecycle lease
39
- * (`SandboxService` gate), the same for every provider: an incarnation is destroyed whole by its
40
- * provider (confirmed destruction, the file system kept) or found destroyed by a recorded
41
- * confirmed destruction; a replaced one without recorded destruction and an unknown one are
42
- * quarantined. The owner can resolve exact local retirement through verified machine proof.
43
- * That path records its provenance and reopens when a newly discovered member needs checking.
44
- * Nothing here resolves on a new generation, a timeout or a process scan.
45
- */
46
- /** The freeze's single row id. */
47
- const FREEZE_ID = "platform";
48
- /** A generation as recorded: the decimal epoch millisecond, or `unknown`. */
49
- const GENERATION_RE = /^[0-9]{1,16}$/;
50
- /**
51
- * The cutover barrier is not in place: legacy admission is still open (no freeze), or the freeze
52
- * is published but its enumeration never completed. Nothing that depends on closed admission
53
- * (the cloud snapshot) may run.
54
- */
55
- export class CutoverBarrierError extends Error {
56
- constructor(message) {
57
- super(message);
58
- this.name = "CutoverBarrierError";
59
- }
60
- }
61
- /**
62
- * The freeze is published, but its enumeration kept finding new rows for every pass (legacy rows,
63
- * for example of a replica without the freeze code, or revoked managed starts). The freeze stays published (it
64
- * is never undone) and is not marked enumerated; stop that replica and run the freeze again.
65
- */
66
- export class LegacyFreezeUnsettledError extends Error {
67
- constructor(passes, added) {
68
- super(`The legacy-launch freeze is published, but its enumeration did not settle after ${passes} ` +
69
- `passes (${added} new members): new legacy or revoked rows kept appearing. Stop every ` +
70
- "old replica, then run the freeze again");
71
- this.name = "LegacyFreezeUnsettledError";
72
- }
73
- }
74
- /** The passes of the freeze's own enumeration before it is called unsettled. */
75
- const FREEZE_SCAN_PASSES = 5;
76
- /** What the report counts as a recent unmarked legacy row (database clock). */
77
- const RECENT = "15 minutes";
78
- /** The migration that added the legacy dispatch marker: rows after it without one are unfenced. */
79
- const MARKER_MIGRATION = "0157_legacy_retirement.sql";
80
- /**
81
- * The legacy rows whose processes may still exist: the partial index's predicate (0157) stated as
82
- * is, then the rows that may have dispatched or still owe a kill.
83
- */
84
- const MAY_STILL_RUN = sql `(t.status = 'running' OR t.kill_pending OR t.sid IS NULL)`;
85
- const MAY_HAVE_DISPATCHED = sql `(
86
- (t.status = 'running' AND (t.sid IS NOT NULL OR t.legacy_dispatch <> 'reserved'))
87
- OR t.kill_pending
88
- OR (t.sid IS NULL AND t.legacy_dispatch <> 'reserved')
89
- )`;
90
- /**
91
- * Whether `provider` names a provider (one whose whole-instance destroy is confirmed): any
92
- * recorded provider, the same for every one, never the `unknown` of an incarnation the kernel
93
- * cannot name.
94
- */
95
- export const isKnownProvider = (provider) => provider !== "unknown";
96
- /** The epoch millisecond of `d` as recorded generation text. */
97
- const generationOf = (d) => String(d.getTime());
98
- /**
99
- * The incarnation a legacy row's obligation is keyed by: the one it started in, else the one its
100
- * dispatch was admitted for; a historical reservation without either is `unknown`, never the
101
- * instance current now (I2). Its own provider: the admitted one, else the instance row's only
102
- * when it is that incarnation, else `unknown` (M6).
103
- */
104
- function legacyKey(r) {
105
- const generation = r.sandbox_created_at !== null
106
- ? generationOf(new Date(r.sandbox_created_at))
107
- : (r.legacy_dispatch_generation ?? "unknown");
108
- const current = r.instance_created_at !== null && generationOf(r.instance_created_at) === generation;
109
- const provider = r.legacy_dispatch_provider ??
110
- (current && r.instance_provider ? r.instance_provider : "unknown");
111
- return { provider, generation };
112
- }
113
- function localGenerationOf(refValue, deviceId, operationId) {
114
- try {
115
- const ref = parseSandboxExecutionRef(refValue);
116
- return ref.instanceId === deviceId &&
117
- ref.operationId === operationId &&
118
- RETIREMENT_GENERATION.test(ref.instanceGeneration)
119
- ? ref.instanceGeneration
120
- : undefined;
121
- }
122
- catch {
123
- return undefined;
124
- }
125
- }
126
- const toObligation = (r) => ({
127
- id: r.id,
128
- deviceId: r.device_id,
129
- orgId: r.org_id,
130
- provider: r.provider,
131
- instanceGeneration: r.instance_generation,
132
- state: r.state,
133
- reason: r.reason,
134
- attempts: r.attempts,
135
- createdAt: r.created_at,
136
- });
137
- let LegacyRetirementStore = class LegacyRetirementStore {
138
- db;
139
- txHost;
140
- locks;
141
- constructor(db, txHost, locks) {
142
- this.db = db;
143
- this.txHost = txHost;
144
- this.locks = locks;
145
- }
146
- /**
147
- * Publishes the legacy-launch freeze under the platform authority writer, then enumerates every
148
- * legacy row and revoked start until stable; idempotent. Returns when it was first published.
149
- * Never undone.
150
- */
151
- async freeze(by) {
152
- const frozenAt = await this.publishFreeze(by);
153
- // enumerated before the freeze returns: no use may run between it and the first scan (the
154
- // gate also scans each device it serves, so a worker that never runs bypasses nothing)
155
- const scan = await this.scanUntilStable(FREEZE_SCAN_PASSES);
156
- // A separate write after the scan (whose passes commit member by member): the mark only says
157
- // a whole enumeration completed stable; an unsettled run clears an earlier mark, so the
158
- // barrier never trusts an enumeration older than what this run found still moving.
159
- await this.db
160
- .updateTable("legacy_launch_freeze")
161
- .set({ enumerated_at: scan.stable ? sql `now()` : null })
162
- .where("id", "=", FREEZE_ID)
163
- .execute();
164
- if (!scan.stable)
165
- throw new LegacyFreezeUnsettledError(FREEZE_SCAN_PASSES, scan.added);
166
- return { frozenAt, added: scan.added, stable: true };
167
- }
168
- /** Whether the freeze is published and whether its enumeration completed. */
169
- async freezeState() {
170
- const row = await this.db
171
- .selectFrom("legacy_launch_freeze")
172
- .select(["frozen_at", "enumerated_at"])
173
- .where("id", "=", FREEZE_ID)
174
- .executeTakeFirst();
175
- return { frozenAt: row?.frozen_at ?? null, enumeratedAt: row?.enumerated_at ?? null };
176
- }
177
- /**
178
- * The cutover barrier (B-10): legacy admission is closed (the freeze is published), the
179
- * freeze's own enumeration completed, and no unmarked legacy row (only an old, unfenced replica
180
- * writes one) started after that enumeration. Throws {@link CutoverBarrierError} otherwise. The
181
- * freeze is never undone; a later legacy row is still enumerated by the gate before any use.
182
- */
183
- async assertCutoverBarrier() {
184
- const state = await this.freezeState();
185
- if (state.frozenAt === null)
186
- throw new CutoverBarrierError("Legacy admission is still open: publish the legacy-launch freeze first " +
187
- "(capybara permissions cutover freeze)");
188
- if (state.enumeratedAt === null)
189
- throw new CutoverBarrierError("The legacy-launch freeze is published but its enumeration never completed: " +
190
- "run capybara permissions cutover freeze again");
191
- const unfenced = await this.unfencedWriters(state);
192
- if (unfenced.afterEnumeration > 0)
193
- throw new CutoverBarrierError(`${unfenced.afterEnumeration} unmarked legacy row(s) started after the freeze's ` +
194
- "enumeration: an old, unfenced replica still runs. Stop it, then run capybara " +
195
- "permissions cutover freeze again");
196
- }
197
- async publishFreeze(by) {
198
- await this.locks.acquire({}, { kind: "write", level: "platform" });
199
- await this.db
200
- .insertInto("legacy_launch_freeze")
201
- .values({ id: FREEZE_ID, frozen_by: by.slice(0, 200) || "unknown" })
202
- .onConflict((oc) => oc.column("id").doNothing())
203
- .execute();
204
- const row = await this.db
205
- .selectFrom("legacy_launch_freeze")
206
- .select("frozen_at")
207
- .where("id", "=", FREEZE_ID)
208
- .executeTakeFirstOrThrow();
209
- return row.frozen_at;
210
- }
211
- /** When the freeze was published; null before. */
212
- async frozenAt() {
213
- const row = await this.db
214
- .selectFrom("legacy_launch_freeze")
215
- .select("frozen_at")
216
- .where("id", "=", FREEZE_ID)
217
- .executeTakeFirst();
218
- return row?.frozen_at ?? null;
219
- }
220
- /**
221
- * The worker's sweep of obligations whose device is gone (its row missing, `deleted_at` set, or
222
- * its org soft-deleted), at most `limit` per call:
223
- * - one waits while the device's instance row exists:
224
- * its destroy is still owed (the destroy job or the destruction sweep deletes the row when it
225
- * is done) and records the destruction then;
226
- * - one whose exact incarnation has a recorded confirmed destruction resolves
227
- * `provider-destroyed`, an already `abandoned` one too (provider evidence, not a
228
- * reopen);
229
- * - every other one becomes `abandoned`. Device ids are never reused, so no device can acquire
230
- * that incarnation again, but abandonment is no evidence that its processes ended (they may
231
- * still run on that computer); its members stay unsettled.
232
- * Returns the counts.
233
- */
234
- async abandonDeleted(limit) {
235
- return asPlatform("retirement of legacy launches across every org", async () => {
236
- let resolved = 0, abandoned = 0;
237
- // abandoned obligations that gained a matching recorded destruction
238
- const evidenced = await this.db
239
- .selectFrom("device_retirement_obligations as o")
240
- .innerJoin("device_instance_destructions as x", (j) => j
241
- .onRef("x.device_id", "=", "o.device_id")
242
- .onRef("x.provider", "=", "o.provider")
243
- .onRef("x.instance_generation", "=", "o.instance_generation"))
244
- .select("o.id")
245
- .where("o.state", "=", "abandoned")
246
- .limit(limit)
247
- .execute();
248
- for (const r of evidenced) {
249
- const u = await this.db
250
- .updateTable("device_retirement_obligations")
251
- .set({
252
- state: "resolved",
253
- resolution: "provider-destroyed",
254
- resolved_at: sql `now()`,
255
- abandoned_at: null,
256
- last_error: null,
257
- })
258
- .where("id", "=", r.id)
259
- .where("state", "=", "abandoned")
260
- .executeTakeFirst();
261
- resolved += Number(u.numUpdatedRows);
262
- }
263
- const rows = await this.db
264
- .selectFrom("device_retirement_obligations as o")
265
- .leftJoin("devices as d", "d.id", "o.device_id")
266
- .leftJoin("orgs as g", "g.id", "d.org_id")
267
- .select(["o.id", "o.device_id", "o.provider", "o.instance_generation"])
268
- .where("o.state", "in", ["open", "quarantined"])
269
- .where((eb) => eb.or([
270
- eb("d.id", "is", null),
271
- eb("d.deleted_at", "is not", null),
272
- eb("g.deleted_at", "is not", null),
273
- ]))
274
- // a destroy still owed keeps its instance row (R2-I2)
275
- .where((eb) => eb.not(eb.exists(eb
276
- .selectFrom("device_instances as i")
277
- .select("i.device_id")
278
- .whereRef("i.device_id", "=", "o.device_id"))))
279
- .orderBy("o.created_at")
280
- .limit(limit)
281
- .execute();
282
- for (const r of rows) {
283
- if (await this.destructionRecorded(r.device_id, r.provider, r.instance_generation)) {
284
- await this.resolveDestroyed(r.id);
285
- resolved++;
286
- continue;
287
- }
288
- const u = await this.db
289
- .updateTable("device_retirement_obligations")
290
- .set({ state: "abandoned", abandoned_at: sql `now()` })
291
- .where("id", "=", r.id)
292
- .where("state", "in", ["open", "quarantined"])
293
- .executeTakeFirst();
294
- abandoned += Number(u.numUpdatedRows);
295
- }
296
- return { resolved, abandoned };
297
- });
298
- }
299
- async frozen() {
300
- const row = await this.db
301
- .selectFrom("legacy_launch_freeze")
302
- .select("id")
303
- .where("id", "=", FREEZE_ID)
304
- .executeTakeFirst();
305
- return row !== undefined;
306
- }
307
- /**
308
- * One enumeration pass: every legacy row (only once the freeze is published) and every revoked
309
- * managed start that may still own processes on an incarnation that no longer runs, recorded as
310
- * members of their obligations. Idempotent; returns how many new members it recorded. The
311
- * worker repeats it every tick, so a row an old unfenced replica writes later is still found.
312
- */
313
- async scan(deviceId) {
314
- let added = await this.reopenLateMembers(deviceId);
315
- if (await this.frozen())
316
- added += await this.scanLegacyTasks(deviceId);
317
- added += await this.scanRevokedStarts(deviceId);
318
- return { added };
319
- }
320
- /** Repeats {@link scan} until a pass adds nothing (at most `maxPasses`). */
321
- async scanUntilStable(maxPasses = 5, deviceId) {
322
- let added = 0;
323
- for (let i = 0; i < maxPasses; i++) {
324
- const pass = await this.scan(deviceId);
325
- added += pass.added;
326
- if (pass.added === 0)
327
- return { added, stable: true };
328
- }
329
- return { added, stable: false };
330
- }
331
- /**
332
- * Legacy rows whose processes may still exist and that are not members yet (one device's, or
333
- * all). The `(status = 'running' OR kill_pending OR sid IS NULL)` conjunct is the partial index's
334
- * predicate (0157), stated as is so the planner can use it.
335
- */
336
- // org-filter: callers execute this fragment inside the platform sweep or add the owner check's
337
- // exact org to it before it runs
338
- legacyCandidates(deviceId) {
339
- let q = this.db
340
- .selectFrom("background_tasks as t")
341
- .leftJoin("devices as d", "d.id", "t.device_id")
342
- .leftJoin("device_instances as i", "i.device_id", "t.device_id")
343
- .select([
344
- "t.id",
345
- "t.org_id",
346
- "t.device_id",
347
- "t.sandbox_created_at",
348
- "t.legacy_dispatch_generation",
349
- "t.legacy_dispatch_provider",
350
- "i.provider as instance_provider",
351
- "i.created_at as instance_created_at",
352
- ])
353
- .where("t.launch_state", "=", "legacy")
354
- .where("t.device_id", "is not", null)
355
- .where(MAY_STILL_RUN)
356
- .where(MAY_HAVE_DISPATCHED)
357
- .where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_retirement_members as m")
358
- .select("m.ref_id")
359
- .where("m.kind", "=", "legacy-task")
360
- .whereRef("m.ref_id", "=", "t.id"))));
361
- if (deviceId !== undefined)
362
- q = q.where("t.device_id", "=", deviceId);
363
- return q;
364
- }
365
- async scanLegacyTasks(deviceId) {
366
- return asPlatform("retirement of legacy launches across every org", async () => {
367
- const rows = await this.legacyCandidates(deviceId)
368
- .orderBy("t.started_at", "asc")
369
- .orderBy("t.id", "asc")
370
- .execute();
371
- let added = 0;
372
- for (const r of rows) {
373
- const deviceId = r.device_id;
374
- const { provider, generation } = legacyKey(r);
375
- if (await this.addMember(deviceId, r.org_id, provider, generation, "legacy-task", r.id))
376
- added++;
377
- }
378
- return added;
379
- });
380
- }
381
- /** Revoked managed starts on an incarnation that no longer runs, not members yet. */
382
- // org-filter: a query fragment, not run here: its callers (the retirement sweep's methods)
383
- // execute it inside their asPlatform
384
- revokedCandidates(deviceId) {
385
- let q = this.db
386
- .selectFrom("sandbox_operation_intents as o")
387
- .select(["o.operation_id", "o.org_id", "o.device_id", "o.provider", "o.instance_generation"])
388
- .where("o.method", "=", "backgroundStart")
389
- .where("o.state", "=", "revoked")
390
- .where("o.revoke_acknowledged", "=", false)
391
- .where("o.execution_ref", "is not", null)
392
- // the recorded incarnation is no longer the one running (replaced, destroyed, suspended):
393
- // the revoke worker cannot reach it there
394
- .where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_instances as d")
395
- .select("d.device_id")
396
- .whereRef("d.device_id", "=", "o.device_id")
397
- .whereRef("d.provider", "=", "o.provider")
398
- .where("d.status", "=", "running")
399
- .where(sql `floor(extract(epoch from d.created_at) * 1000)::bigint::text = o.instance_generation`))))
400
- .where(({ not, exists, selectFrom }) => not(exists(selectFrom("device_retirement_members as m")
401
- .select("m.ref_id")
402
- .where("m.kind", "=", "revoked-start")
403
- .whereRef("m.ref_id", "=", "o.operation_id"))));
404
- if (deviceId !== undefined)
405
- q = q.where("o.device_id", "=", deviceId);
406
- return q;
407
- }
408
- async scanRevokedStarts(deviceId) {
409
- return asPlatform("retirement of legacy launches across every org", async () => {
410
- const rows = await this.revokedCandidates(deviceId).orderBy("o.operation_id").execute();
411
- let added = 0;
412
- for (const r of rows) {
413
- const generation = GENERATION_RE.test(r.instance_generation)
414
- ? r.instance_generation
415
- : "unknown";
416
- if (await this.addMember(r.device_id, r.org_id, r.provider, generation, "revoked-start", r.operation_id))
417
- added++;
418
- }
419
- return added;
420
- });
421
- }
422
- /** The obligation of the incarnation (created when missing), with the member added. */
423
- async addMember(deviceId, orgId, provider, generation, kind, refId) {
424
- return asPlatform("retirement of legacy launches across every org", async () => {
425
- await this.db
426
- .insertInto("device_retirement_obligations")
427
- .values({
428
- device_id: deviceId,
429
- org_id: orgId,
430
- provider,
431
- instance_generation: generation,
432
- })
433
- .onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
434
- .execute();
435
- const obligation = await this.db
436
- .selectFrom("device_retirement_obligations")
437
- .select(["id", "state", "resolution"])
438
- .where("device_id", "=", deviceId)
439
- .where("provider", "=", provider)
440
- .where("instance_generation", "=", generation)
441
- .forUpdate()
442
- .executeTakeFirstOrThrow();
443
- const r = await this.db
444
- .insertInto("device_retirement_members")
445
- .values({ obligation_id: obligation.id, kind, ref_id: refId })
446
- .onConflict((oc) => oc.columns(["kind", "ref_id", "obligation_id"]).doNothing())
447
- .returning("ref_id")
448
- .executeTakeFirst();
449
- // an exact cancel covers only the refs it stopped, and the incarnation lives on (B-22): a
450
- // member found later (a row of an old replica) reopens the obligation; so does one found on
451
- // an incarnation an old replica resolved by a restart of its computer
452
- if (r !== undefined &&
453
- obligation.state === "resolved" &&
454
- (obligation.resolution === "host-rebooted" || obligation.resolution === "exact-cancelled")) {
455
- await this.db
456
- .updateTable("device_retirement_obligations")
457
- .set({ state: "open", resolution: null, resolved_at: null })
458
- .where("id", "=", obligation.id)
459
- .execute();
460
- }
461
- return r !== undefined;
462
- });
463
- }
464
- /** The device's unresolved obligations (open and quarantined), oldest first. */
465
- async unresolved(deviceId) {
466
- return asPlatform("retirement of legacy launches across every org", async () => {
467
- const rows = await this.db
468
- .selectFrom("device_retirement_obligations")
469
- .select([
470
- "id",
471
- "device_id",
472
- "org_id",
473
- "provider",
474
- "instance_generation",
475
- "state",
476
- "reason",
477
- "attempts",
478
- "created_at",
479
- ])
480
- .where("device_id", "=", deviceId)
481
- .where("state", "in", ["open", "quarantined"])
482
- .orderBy("created_at", "asc")
483
- .orderBy("id", "asc")
484
- .execute();
485
- return rows.map(toObligation);
486
- });
487
- }
488
- /**
489
- * Whether the device has an unresolved obligation, or a candidate not enumerated yet (a legacy
490
- * row once frozen, a revoked start): the shared-path check. A candidate counts as unresolved, so
491
- * the device goes to the gate, which enumerates it under the exclusive lease (C1).
492
- */
493
- async hasUnresolved(deviceId) {
494
- return asPlatform("retirement of legacy launches across every org", async () => {
495
- const row = await this.db
496
- .selectFrom("device_retirement_obligations")
497
- .select("id")
498
- .where("device_id", "=", deviceId)
499
- .where("state", "in", ["open", "quarantined"])
500
- .limit(1)
501
- .executeTakeFirst();
502
- if (row !== undefined)
503
- return true;
504
- if ((await this.revokedCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined)
505
- return true;
506
- // an exact-cancelled obligation a member was added to after the cancel (a rolling upgrade)
507
- const late = await this.db
508
- .selectFrom("device_retirement_obligations as o")
509
- .select("o.id")
510
- .where("o.device_id", "=", deviceId)
511
- .where("o.state", "=", "resolved")
512
- .where("o.resolution", "=", "exact-cancelled")
513
- .where(({ exists }) => exists(this.lateMember()))
514
- .limit(1)
515
- .executeTakeFirst();
516
- if (late !== undefined)
517
- return true;
518
- return ((await this.frozen()) &&
519
- (await this.legacyCandidates(deviceId).limit(1).executeTakeFirst()) !== undefined);
520
- });
521
- }
522
- /**
523
- * No trusted way to establish termination: the obligation is quarantined (the device stays
524
- * unavailable). A resolved obligation is left as it is.
525
- */
526
- async quarantine(id, reason) {
527
- return asPlatform("retirement of legacy launches across every org", async () => {
528
- await this.db
529
- .updateTable("device_retirement_obligations")
530
- .set((eb) => ({
531
- state: "quarantined",
532
- reason: reason.slice(0, 1000),
533
- attempts: eb("attempts", "+", 1),
534
- last_attempt_at: sql `now()`,
535
- }))
536
- .where("id", "=", id)
537
- .where("state", "in", ["open", "quarantined"])
538
- .execute();
539
- });
540
- }
541
- /** A failed destroy or verification: the obligation stays as it is, the attempt is recorded. */
542
- async noteFailure(id, error) {
543
- return asPlatform("retirement of legacy launches across every org", async () => {
544
- const text = error instanceof Error ? error.message : String(error);
545
- await this.db
546
- .updateTable("device_retirement_obligations")
547
- .set((eb) => ({
548
- attempts: eb("attempts", "+", 1),
549
- last_attempt_at: sql `now()`,
550
- last_error: text.slice(0, 1000),
551
- }))
552
- .where("id", "=", id)
553
- .where("state", "in", ["open", "quarantined"])
554
- .execute();
555
- });
556
- }
557
- /** The provider confirmed the incarnation destroyed: the obligation resolves. */
558
- async resolveDestroyed(id) {
559
- return asPlatform("retirement of legacy launches across every org", async () => {
560
- await this.db
561
- .updateTable("device_retirement_obligations")
562
- .set({
563
- state: "resolved",
564
- resolution: "provider-destroyed",
565
- resolved_at: sql `now()`,
566
- last_error: null,
567
- })
568
- .where("id", "=", id)
569
- .where("state", "in", ["open", "quarantined"])
570
- .execute();
571
- });
572
- }
573
- /**
574
- * The provider confirmed the exact cancellation of the revoked managed starts `covered` on the
575
- * resumed incarnation (B-22): under the obligation's row lock (the lock {@link addMember} takes
576
- * before it adds a member), resolves it as `exact-cancelled` and acknowledges those
577
- * revocations, only while every member is one of them. False (nothing changed) when a member
578
- * outside `covered` exists, which was never stopped: the caller destroys the incarnation
579
- * instead. Acknowledging here is what tells a member added later apart ({@link scan}).
580
- */
581
- async resolveCancelled(id, covered) {
582
- return asPlatform("retirement of legacy launches across every org", async () => {
583
- const o = await this.db
584
- .selectFrom("device_retirement_obligations")
585
- .select(["state"])
586
- .where("id", "=", id)
587
- .forUpdate()
588
- .executeTakeFirst();
589
- if (o === undefined || (o.state !== "open" && o.state !== "quarantined"))
590
- return false;
591
- const members = await this.db
592
- .selectFrom("device_retirement_members")
593
- .select(["kind", "ref_id"])
594
- .where("obligation_id", "=", id)
595
- .execute();
596
- const set = new Set(covered);
597
- if (members.length === 0 ||
598
- members.some((m) => m.kind !== "revoked-start" || !set.has(m.ref_id)))
599
- return false;
600
- await this.db
601
- .updateTable("sandbox_operation_intents")
602
- .set({ revoke_acknowledged: true, updated_at: new Date() })
603
- .where("operation_id", "in", [...set])
604
- .where("state", "=", "revoked")
605
- .execute();
606
- await this.db
607
- .updateTable("device_retirement_obligations")
608
- .set({
609
- state: "resolved",
610
- resolution: "exact-cancelled",
611
- resolved_at: sql `now()`,
612
- last_error: null,
613
- })
614
- .where("id", "=", id)
615
- .execute();
616
- return true;
617
- });
618
- }
619
- /**
620
- * Reopens `exact-cancelled` obligations holding a member nobody stopped: a legacy row, or a
621
- * revoked start whose intent is not there acknowledged, a missing intent included (every
622
- * member the cancel covered was acknowledged with the resolution). A replica without the reopen in {@link addMember} (a
623
- * rolling upgrade) adds such members to a resolved obligation; the next scan of a new one
624
- * reopens it. Returns how many it reopened.
625
- */
626
- async reopenLateMembers(deviceId) {
627
- return asPlatform("retirement of legacy launches across every org", async () => {
628
- let q = this.db
629
- .updateTable("device_retirement_obligations as o")
630
- .set({ state: "open", resolution: null, resolved_at: null })
631
- .where("o.state", "=", "resolved")
632
- .where("o.resolution", "=", "exact-cancelled")
633
- .where(({ exists }) => exists(this.lateMember()));
634
- if (deviceId !== undefined)
635
- q = q.where("o.device_id", "=", deviceId);
636
- const r = await q.executeTakeFirst();
637
- return Number(r.numUpdatedRows);
638
- });
639
- }
640
- /**
641
- * A member of obligation `o` an exact cancel never covered (see {@link reopenLateMembers}),
642
- * correlated on `o.id`.
643
- */
644
- // org-filter: a correlated subquery fragment on o.id, run only inside the retirement sweep's
645
- // asPlatform
646
- lateMember() {
647
- // fail closed: a revoked start is covered only when its intent exists acknowledged (a missing
648
- // intent row proves nothing was stopped)
649
- return this.db
650
- .selectFrom("device_retirement_members as lm")
651
- .select("lm.ref_id")
652
- .where(sql `lm.obligation_id = o.id`)
653
- .where((eb) => eb.or([
654
- eb("lm.kind", "=", "legacy-task"),
655
- eb.not(eb.exists(eb
656
- .selectFrom("sandbox_operation_intents as li")
657
- .select("li.operation_id")
658
- .whereRef("li.operation_id", "=", "lm.ref_id")
659
- .where("li.revoke_acknowledged", "=", true))),
660
- ]));
661
- }
662
- /** The exact old obligations the owner may check, within their guarded org. */
663
- async quarantinedLocal(check) {
664
- const rows = await this.db
665
- .selectFrom("device_retirement_obligations")
666
- .selectAll()
667
- .where("org_id", "=", check.orgId)
668
- .where("device_id", "=", check.deviceId)
669
- .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
670
- .where("state", "=", "quarantined")
671
- .orderBy("id", "asc")
672
- .execute();
673
- return rows
674
- .map(toObligation)
675
- .filter((row) => RETIREMENT_GENERATION.test(row.instanceGeneration) &&
676
- BigInt(row.instanceGeneration) < BigInt(check.currentGeneration));
677
- }
678
- /** Correlate the kernel incarnation to a single exact generation of the local provider. */
679
- async localProviderGeneration(o) {
680
- if (o.provider !== LOCAL_RETIREMENT_PROVIDER ||
681
- !RETIREMENT_GENERATION.test(o.instanceGeneration))
682
- return undefined;
683
- const identity = await this.db
684
- .selectFrom("device_instance_retirement_identities")
685
- .select("provider_generation")
686
- .where("org_id", "=", o.orgId)
687
- .where("device_id", "=", o.deviceId)
688
- .where("provider", "=", o.provider)
689
- .where("instance_generation", "=", o.instanceGeneration)
690
- .executeTakeFirst();
691
- const members = await this.db
692
- .selectFrom("device_retirement_members as m")
693
- .leftJoin("sandbox_operation_intents as i", (join) => join.onRef("i.operation_id", "=", "m.ref_id").on("i.org_id", "=", o.orgId))
694
- .select([
695
- "m.kind",
696
- "m.ref_id",
697
- "i.device_id",
698
- "i.provider",
699
- "i.method",
700
- "i.state",
701
- "i.instance_generation",
702
- "i.execution_ref",
703
- ])
704
- .where("m.obligation_id", "=", o.id)
705
- .execute();
706
- if (members.some((member) => member.kind !== "revoked-start" ||
707
- member.device_id !== o.deviceId ||
708
- member.provider !== o.provider ||
709
- member.method !== "backgroundStart" ||
710
- member.state !== "revoked" ||
711
- member.instance_generation !== o.instanceGeneration))
712
- return undefined;
713
- // The scanner may not have attached an earlier launch yet. A relevant legacy launch or a
714
- // divergent retained managed ref defeats proof even before it becomes a member.
715
- const legacy = await this.legacyCandidates(o.deviceId)
716
- .where("t.org_id", "=", o.orgId)
717
- .execute();
718
- if (legacy.some((candidate) => {
719
- const origin = legacyKey(candidate);
720
- return (origin.generation === o.instanceGeneration &&
721
- (origin.provider === o.provider || origin.provider === "unknown"));
722
- }))
723
- return undefined;
724
- const references = this.db
725
- .selectFrom("sandbox_operation_intents")
726
- .select(["operation_id", "execution_ref"])
727
- .where("org_id", "=", o.orgId)
728
- .where("device_id", "=", o.deviceId)
729
- .where("provider", "=", o.provider)
730
- .where("method", "=", "backgroundStart")
731
- .where("execution_ref", "is not", null);
732
- const retained = await references
733
- .where("instance_generation", "=", o.instanceGeneration)
734
- .execute();
735
- let generation = identity?.provider_generation;
736
- for (const row of [
737
- ...members.map((member) => ({
738
- operation_id: member.ref_id,
739
- execution_ref: member.execution_ref,
740
- })),
741
- ...retained,
742
- ]) {
743
- const claimed = localGenerationOf(row.execution_ref, o.deviceId, row.operation_id);
744
- if (claimed === undefined || (generation !== undefined && generation !== claimed))
745
- return undefined;
746
- generation = claimed;
747
- }
748
- if (generation === undefined)
749
- return undefined;
750
- const reverse = await references
751
- .where("instance_generation", "!=", o.instanceGeneration)
752
- .where(sql `execution_ref ->> 'instanceGeneration'`, "=", generation)
753
- .execute();
754
- if (reverse.some((r) => localGenerationOf(r.execution_ref, o.deviceId, r.operation_id) !== undefined))
755
- return undefined;
756
- const conflicting = await this.db
757
- .selectFrom("device_instance_retirement_identities")
758
- .select("instance_generation")
759
- .where("org_id", "=", o.orgId)
760
- .where("device_id", "=", o.deviceId)
761
- .where("provider", "=", o.provider)
762
- .where("provider_generation", "=", generation)
763
- .where("instance_generation", "!=", o.instanceGeneration)
764
- .executeTakeFirst();
765
- return conflicting === undefined ? generation : undefined;
766
- }
767
- /** Commit exact evidence only while all identities seen by the owner check still hold. */
768
- async resolveLocalProof(check, o, providerGeneration, signal) {
769
- signal.throwIfAborted();
770
- if (o.orgId !== check.orgId ||
771
- o.deviceId !== check.deviceId ||
772
- o.provider !== LOCAL_RETIREMENT_PROVIDER ||
773
- !RETIREMENT_GENERATION.test(o.instanceGeneration) ||
774
- BigInt(o.instanceGeneration) >= BigInt(check.currentGeneration))
775
- return;
776
- const org = await this.db
777
- .selectFrom("orgs")
778
- .select("id")
779
- .where("id", "=", check.orgId)
780
- .where("deleted_at", "is", null)
781
- .forShare()
782
- .executeTakeFirst();
783
- const member = org &&
784
- (await this.db
785
- .selectFrom("memberships")
786
- .select("account_id")
787
- .where("org_id", "=", check.orgId)
788
- .where("account_id", "=", check.accountId)
789
- .forShare()
790
- .executeTakeFirst());
791
- if (!member)
792
- return;
793
- const owner = await this.db
794
- .selectFrom("devices")
795
- .select("id")
796
- .where("org_id", "=", check.orgId)
797
- .where("id", "=", check.deviceId)
798
- .where("owner_kind", "=", "personal")
799
- .where("owner_account_id", "=", check.accountId)
800
- .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
801
- .where("deleted_at", "is", null)
802
- .forNoKeyUpdate()
803
- .executeTakeFirst();
804
- if (!owner)
805
- return;
806
- const machine = await this.db
807
- .selectFrom("device_machines")
808
- .select("id")
809
- .where("org_id", "=", check.orgId)
810
- .where("device_id", "=", check.deviceId)
811
- .where("account_id", "=", check.accountId)
812
- .where("id", "=", check.machineId)
813
- .where("revoked_at", "is", null)
814
- .forShare()
815
- .executeTakeFirst();
816
- if (!machine)
817
- return;
818
- const instance = await this.db
819
- .selectFrom("device_instances")
820
- .select("created_at")
821
- .where("org_id", "=", check.orgId)
822
- .where("device_id", "=", check.deviceId)
823
- .where("provider", "=", LOCAL_RETIREMENT_PROVIDER)
824
- .where("generation", "=", check.fence)
825
- .where("status", "in", ["running", "suspended"])
826
- .where("handle", "is not", null)
827
- .where("had_instance", "=", true)
828
- .forUpdate()
829
- .executeTakeFirst();
830
- if (String(instance?.created_at.getTime()) !== check.currentGeneration)
831
- return;
832
- // Same row lock as addMember. A conflicting member that arrived during the RPC defeats proof.
833
- const obligation = await this.db
834
- .selectFrom("device_retirement_obligations")
835
- .select("id")
836
- .where("org_id", "=", check.orgId)
837
- .where("device_id", "=", check.deviceId)
838
- .where("provider", "=", o.provider)
839
- .where("instance_generation", "=", o.instanceGeneration)
840
- .where("id", "=", o.id)
841
- .where("state", "=", "quarantined")
842
- .forUpdate()
843
- .executeTakeFirst();
844
- if (!obligation)
845
- return;
846
- const recorded = await this.destructionRecorded(o.deviceId, o.provider, o.instanceGeneration);
847
- if (!recorded &&
848
- (providerGeneration === undefined ||
849
- (await this.localProviderGeneration(o)) !== providerGeneration))
850
- return;
851
- signal.throwIfAborted();
852
- if (!recorded && providerGeneration !== undefined)
853
- await this.db
854
- .insertInto("device_instance_retirement_identities")
855
- .values({
856
- org_id: o.orgId,
857
- device_id: o.deviceId,
858
- provider: o.provider,
859
- instance_generation: o.instanceGeneration,
860
- provider_generation: providerGeneration,
861
- attested_at: sql `now()`,
862
- })
863
- .onConflict((oc) => oc
864
- .columns(["org_id", "device_id", "provider", "instance_generation"])
865
- .doUpdateSet({ attested_at: sql `now()` }))
866
- .execute();
867
- // Unconditional destruction readers, including older replicas and operation reconciliation,
868
- // must never consume machine proof without checking the whole obligation's provenance.
869
- await this.db
870
- .updateTable("device_retirement_obligations")
871
- .set({
872
- state: "resolved",
873
- resolution: "provider-destroyed",
874
- resolved_at: sql `now()`,
875
- last_error: null,
876
- })
877
- .where("org_id", "=", check.orgId)
878
- .where("id", "=", o.id)
879
- .execute();
880
- signal.throwIfAborted();
881
- }
882
- /** The members of one obligation, oldest first. */
883
- async membersOf(obligationId) {
884
- const rows = await this.db
885
- .selectFrom("device_retirement_members")
886
- .select(["obligation_id", "kind", "ref_id"])
887
- .where("obligation_id", "=", obligationId)
888
- .orderBy("created_at", "asc")
889
- .orderBy("ref_id", "asc")
890
- .execute();
891
- return rows.map((r) => ({ obligationId: r.obligation_id, kind: r.kind, refId: r.ref_id }));
892
- }
893
- /**
894
- * Records the provider-confirmed destruction of an incarnation, the same for every provider (a
895
- * provider is trusted like every extension). An `unknown` provider names nothing and is refused.
896
- */
897
- async recordDestruction(deviceId, provider, generation) {
898
- if (!isKnownProvider(provider))
899
- throw new Error(`A ${provider} destroy is not evidence of destruction`);
900
- if (!GENERATION_RE.test(generation))
901
- throw new Error(`invalid generation ${generation}`);
902
- await this.db
903
- .insertInto("device_instance_destructions")
904
- .values({ device_id: deviceId, provider, instance_generation: generation })
905
- .onConflict((oc) => oc.columns(["device_id", "provider", "instance_generation"]).doNothing())
906
- .execute();
907
- }
908
- /** Whether a confirmed destruction of exactly that incarnation was recorded. */
909
- async destructionRecorded(deviceId, provider, generation) {
910
- if (!isKnownProvider(provider) || !GENERATION_RE.test(generation))
911
- return false;
912
- const row = await this.db
913
- .selectFrom("device_instance_destructions")
914
- .select("device_id")
915
- .where("device_id", "=", deviceId)
916
- .where("provider", "=", provider)
917
- .where("instance_generation", "=", generation)
918
- .executeTakeFirst();
919
- return row !== undefined;
920
- }
921
- /**
922
- * Devices with an unresolved obligation the worker should try now: never attempted, or last
923
- * attempted longer ago than the backoff (30 s doubling per attempt, at most an hour).
924
- */
925
- async due(limit) {
926
- return asPlatform("retirement of legacy launches across every org", async () => {
927
- const rows = await this.db
928
- .selectFrom("device_retirement_obligations")
929
- .select("device_id")
930
- .where("state", "in", ["open", "quarantined"])
931
- .where(sql `(last_attempt_at IS NULL OR last_attempt_at <
932
- now() - LEAST(3600, 30 * power(2, LEAST(attempts, 7))) * interval '1 second')`)
933
- .groupBy("device_id")
934
- .orderBy(sql `min(last_attempt_at) ASC NULLS FIRST`)
935
- .orderBy("device_id")
936
- .limit(limit)
937
- .execute();
938
- return rows.map((r) => r.device_id);
939
- });
940
- }
941
- /** Members of resolved obligations whose own records are not settled yet. */
942
- async unsettledMembers(limit) {
943
- const rows = await this.db
944
- .selectFrom("device_retirement_members as m")
945
- .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
946
- .select(["m.obligation_id", "m.kind", "m.ref_id"])
947
- .where("o.state", "=", "resolved")
948
- .where("m.settled", "=", false)
949
- // a member an exact cancel never covered is not settled (acknowledged unstopped): the next
950
- // scan reopens its obligation
951
- .where(({ eb, exists, selectFrom }) => eb.or([
952
- eb("o.resolution", "is", null),
953
- eb("o.resolution", "!=", "exact-cancelled"),
954
- exists(selectFrom("sandbox_operation_intents as ui")
955
- .select("ui.operation_id")
956
- .whereRef("ui.operation_id", "=", "m.ref_id")
957
- .where("ui.revoke_acknowledged", "=", true)),
958
- ]))
959
- .where(({ eb, and }) => eb.not(and([eb("o.resolution", "=", "exact-cancelled"), eb("m.kind", "=", "legacy-task")])))
960
- .orderBy("m.created_at", "asc")
961
- .limit(limit)
962
- .execute();
963
- return rows.map((r) => ({ obligationId: r.obligation_id, kind: r.kind, refId: r.ref_id }));
964
- }
965
- async markSettled(m) {
966
- await this.db
967
- .updateTable("device_retirement_members")
968
- .set({ settled: true })
969
- .where("obligation_id", "=", m.obligationId)
970
- .where("kind", "=", m.kind)
971
- .where("ref_id", "=", m.refId)
972
- .execute();
973
- }
974
- /**
975
- * Legacy rows without the dispatch marker started after the marker's migration was applied:
976
- * only a replica without the 8.5 code writes them (see {@link LegacyRetirementReport}).
977
- */
978
- async unfencedWriters(state) {
979
- return asPlatform("retirement of legacy launches across every org", async () => {
980
- // the migrator's own bookkeeping (schema `capybara`, `migrate()`): when 0157 was applied
981
- const applied = await sql `SELECT applied_at FROM capybara._migrations
982
- WHERE name = ${MARKER_MIGRATION}`.execute(this.db.db);
983
- const since = applied.rows[0]?.applied_at;
984
- if (since === undefined)
985
- return {
986
- sinceMigration: 0,
987
- afterFreeze: 0,
988
- afterEnumeration: 0,
989
- recent: 0,
990
- latestAt: null,
991
- };
992
- const after = (at) => sql `CASE WHEN started_at > ${at}::timestamptz THEN 1 END`;
993
- const row = await this.db
994
- .selectFrom("background_tasks")
995
- .select((eb) => [
996
- eb.fn.countAll().as("n"),
997
- eb.fn.count(after(state.frozenAt)).as("after"),
998
- eb.fn.count(after(state.enumeratedAt)).as("afterEnumeration"),
999
- // by the database clock, the one that stamped started_at
1000
- eb.fn
1001
- .count(sql `CASE WHEN started_at > now() - ${RECENT}::interval THEN 1 END`)
1002
- .as("recent"),
1003
- eb.fn.max("started_at").as("latest"),
1004
- ])
1005
- .where("launch_state", "=", "legacy")
1006
- .where("legacy_dispatch", "=", "unknown")
1007
- .where("started_at", ">", since)
1008
- .executeTakeFirstOrThrow();
1009
- return {
1010
- sinceMigration: Number(row.n),
1011
- afterFreeze: Number(row.after),
1012
- afterEnumeration: Number(row.afterEnumeration),
1013
- recent: Number(row.recent),
1014
- latestAt: row.latest ?? null,
1015
- };
1016
- });
1017
- }
1018
- /** The release gate's honest view (a quarantined device is unavailable, not retired). */
1019
- async report() {
1020
- return asPlatform("retirement of legacy launches across every org", async () => {
1021
- const freeze = await this.freezeState();
1022
- const frozen = freeze.frozenAt !== null;
1023
- const fenced = await this.db
1024
- .selectFrom("background_tasks")
1025
- .select((eb) => eb.fn.countAll().as("n"))
1026
- .where("launch_state", "=", "legacy")
1027
- .where("status", "=", "running")
1028
- .where("sid", "is", null)
1029
- .where("legacy_dispatch", "=", "reserved")
1030
- .executeTakeFirstOrThrow();
1031
- const unfenced = await this.unfencedWriters(freeze);
1032
- const counts = await this.db
1033
- .selectFrom("device_retirement_obligations")
1034
- .select(["state", (eb) => eb.fn.countAll().as("n")])
1035
- .groupBy("state")
1036
- .execute();
1037
- const n = (s) => Number(counts.find((c) => c.state === s)?.n ?? 0);
1038
- const unsettled = await this.db
1039
- .selectFrom("device_retirement_members as m")
1040
- .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
1041
- .select((eb) => eb.fn.countAll().as("n"))
1042
- .where("o.state", "=", "resolved")
1043
- .where("m.settled", "=", false)
1044
- .executeTakeFirstOrThrow();
1045
- const unresolved = await this.db
1046
- .selectFrom("device_retirement_obligations")
1047
- .select(["device_id", "provider", "instance_generation", "state", "reason"])
1048
- .where("state", "in", ["open", "quarantined"])
1049
- .orderBy("created_at", "asc")
1050
- .execute();
1051
- const abandonedRows = await this.db
1052
- .selectFrom("device_retirement_obligations")
1053
- .select(["device_id", "provider", "instance_generation", "abandoned_at"])
1054
- .where("state", "=", "abandoned")
1055
- .orderBy("abandoned_at", "asc")
1056
- .execute();
1057
- const abandonedMembers = await this.db
1058
- .selectFrom("device_retirement_members as m")
1059
- .innerJoin("device_retirement_obligations as o", "o.id", "m.obligation_id")
1060
- .select((eb) => eb.fn.countAll().as("n"))
1061
- .where("o.state", "=", "abandoned")
1062
- .executeTakeFirstOrThrow();
1063
- const cloudCandidates = await this.db
1064
- .selectFrom("background_tasks as t")
1065
- .innerJoin("devices as d", "d.id", "t.device_id")
1066
- .leftJoin("device_instances as i", "i.device_id", "t.device_id")
1067
- .select([
1068
- "t.device_id",
1069
- "t.sandbox_created_at",
1070
- "t.legacy_dispatch_generation",
1071
- "t.legacy_dispatch_provider",
1072
- "i.provider as instance_provider",
1073
- "i.created_at as instance_created_at",
1074
- "i.prev_handle",
1075
- "i.status as instance_status",
1076
- "i.handle as instance_handle",
1077
- "i.had_instance",
1078
- ])
1079
- .where("d.deleted_at", "is", null)
1080
- .where("t.launch_state", "=", "legacy")
1081
- .where(MAY_STILL_RUN)
1082
- .where(MAY_HAVE_DISPATCHED)
1083
- .orderBy("t.device_id")
1084
- .execute();
1085
- const cloudUnknown = new Map();
1086
- for (const r of cloudCandidates) {
1087
- const key = legacyKey(r);
1088
- if (key.generation !== "unknown" && key.provider !== "unknown")
1089
- continue;
1090
- if (cloudUnknown.has(r.device_id))
1091
- continue;
1092
- const live = r.instance_handle !== null &&
1093
- (r.instance_status === "running" ||
1094
- r.instance_status === "suspended" ||
1095
- r.instance_status === "creating");
1096
- const createdAt = r.instance_created_at;
1097
- const noInstance = createdAt === null || r.had_instance !== true;
1098
- const currentUnconfirmed = createdAt !== null &&
1099
- !noInstance &&
1100
- !live &&
1101
- !(r.instance_provider !== null &&
1102
- (await this.destructionRecorded(r.device_id, r.instance_provider, generationOf(createdAt))));
1103
- cloudUnknown.set(r.device_id, {
1104
- prevHandle: r.prev_handle !== null,
1105
- noInstance,
1106
- currentUnconfirmed,
1107
- });
1108
- }
1109
- const open = n("open"), quarantined = n("quarantined"), abandoned = n("abandoned"), unsettledMembers = Number(unsettled.n);
1110
- const retired = frozen && open === 0 && quarantined === 0 && unsettledMembers === 0;
1111
- return {
1112
- frozen,
1113
- frozenAt: freeze.frozenAt,
1114
- freezeEnumeratedAt: freeze.enumeratedAt,
1115
- fencedReservations: Number(fenced.n),
1116
- unfencedWriters: unfenced,
1117
- open,
1118
- quarantined,
1119
- resolved: n("resolved"),
1120
- unsettledMembers,
1121
- retired,
1122
- cleanRetirement: retired && abandoned === 0,
1123
- abandoned,
1124
- abandonedMembers: Number(abandonedMembers.n),
1125
- abandonedList: abandonedRows.map((r) => ({
1126
- deviceId: r.device_id,
1127
- provider: r.provider,
1128
- instanceGeneration: r.instance_generation,
1129
- abandonedAt: r.abandoned_at,
1130
- })),
1131
- cloudUnknown: [...cloudUnknown].map(([deviceId, flags]) => ({ deviceId, ...flags })),
1132
- unresolved: unresolved.map((r) => ({
1133
- deviceId: r.device_id,
1134
- provider: r.provider,
1135
- instanceGeneration: r.instance_generation,
1136
- state: r.state,
1137
- reason: r.reason,
1138
- })),
1139
- };
1140
- });
1141
- }
1142
- };
1143
- __decorate([
1144
- Transactional({ propagation: "requires_new" })
1145
- ], LegacyRetirementStore.prototype, "publishFreeze", null);
1146
- __decorate([
1147
- Transactional({ propagation: "requires_new" })
1148
- ], LegacyRetirementStore.prototype, "addMember", null);
1149
- __decorate([
1150
- Transactional({ propagation: "requires_new" })
1151
- ], LegacyRetirementStore.prototype, "resolveCancelled", null);
1152
- __decorate([
1153
- Transactional({ propagation: "requires_new" })
1154
- ], LegacyRetirementStore.prototype, "resolveLocalProof", null);
1155
- LegacyRetirementStore = __decorate([
1156
- Injectable()
1157
- // org-filter: deployment-wide retirement of legacy launches: the worker sweeps (retire-legacy-tasks
1158
- // job), the release-gate report and the cutover CLI span every org; the per-device and per-obligation
1159
- // calls come from SandboxService's retirement gate with kernel-held device and obligation ids
1160
- ,
1161
- __param(0, Inject(KernelDb)),
1162
- __param(1, Inject(TransactionHost)),
1163
- __param(2, Inject(PermissionAuthorityLock))
1164
- ], LegacyRetirementStore);
1165
- export { LegacyRetirementStore };