@substrat-run/control-plane-api 0.140.0 → 0.141.0

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.
package/dist/api.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { resolveObservabilityWindow } from './observability-window.js';
2
2
  import { Hono } from 'hono';
3
3
  import { parseHostname, withLabel, RESERVED_LABEL_SEPARATOR, adminAction, ownerTransferInput, memberInviteInput, memberRoleInput, ASSET_PART_PREFIX, assetHash, channelName, connectLinkId, connectionActivity, connectionActivitySource, connectionCredential, connectionCertificate, connectionFilter, connectionHealthState, connectionProvider, connectorDispatchKind, PROVISION_SIBLING_KIND, ARCHIVE_SCOPE_KIND, PROVISION_TENANT_KIND, SET_ENTITLEMENTS_KIND, MODEL_USAGE_KIND, SWEEP_RUNS_KIND, toConnectionHealthEntry, CONNECTION_EXPIRY_WARNING_DAYS, CONNECTION_STALE_DAYS, connectionProbe, createTenantInput, entitlementGrantInput, hostname as hostnameSchema, hostnameRegion, hostnameStatus, identityLink, errorCode, issueStatus, issueStatusInput, findingKind, findingRuleInput, findingStatus, findingStatusInput, listPageQuery, matchesOutboundHost, pageOf, platformRequestFilter, principalId as principalIdSchema, impersonationStamp, promotionAcknowledgement, bindAcknowledgement, provisionableJurisdiction, publishVersionInput, queryScopeInput, readScopeTableInput, entityHistoryInput, eventFacetInput, eventCauseInput, eventEffectsInput, invocationEventsInput, deadLettersInput, lifecycleFlowInput, operationSeriesCount, operationSeriesInput, delegatedReadParams, createOrgInput, roleKey as roleKeySchema, peerSwitch, verticalSlug, systemSwitch, DEFAULT_DENIAL_LIMIT, DENIAL_LIMIT_MAX, denialGroupBy, registerVerticalInput, platformScriptCollision, platformScriptRefusal, PLATFORM_SCRIPT_NAMES, serviceDimensions, sweepRunKind, sweepRunOutcome, scopeDump, dataSubjectId as dataSubjectIdSchema, scopeId as scopeIdSchema, scopeStatus, storageShape, surfaceName, tenantId as tenantIdSchema, tenantStatus, versionOrigin, z, PROBLEM_CONTENT_TYPE, toProblem, redrainEventsInput, importCursorMove, importCursorAcknowledgementMissing, REDRAIN_BATCH, migrationsOnTop, errorCodeOf, capabilityFilterQuery, PLATFORM_FEATURES_HEADER, PLATFORM_FEATURE_SCOPE_SWEEPER, } from '@substrat-run/contracts';
4
+ import { SCOPE_COPY_LEASE_MS, copyRestoreFence } from '@substrat-run/kernel';
4
5
  import { attributeFailure } from './failure-attribution.js';
5
6
  import { auditedChange, withAuditedOutcomes } from './audited-change.js';
6
7
  import { BIND_EXPORT_BREAK_REFUSAL, CARRIED_AWAY_KEY, bindExportBreakRefusal, carriedAwayDump, dumpMetaValue, metaValueIn, crossVerticalHealth, exportBreakRefusal, isBindExportBreakRefusal, isExportBreakRefusal, isPrimaryScope, migrationProgress, ulid, auditWarningOf, } from '@substrat-run/kernel';
7
8
  import { TENANT_HEADER, confinedTenant } from './auth.js';
8
9
  import { mintTenantToken } from './tenant-token.js';
9
10
  import { connectionGrantsForScope } from './vertical-client.js';
11
+ import { assertNoUnreachableScopeCopies, listAllScopeScriptCopies, reapScopeScriptCopies, recordStrandedStorage } from './scope-copy-cleanup.js';
10
12
  import { oidcCallbackUrl, retireClientsOfReapedScope, wirePreviewAuth } from './preview-auth.js';
11
13
  import { versionReachedAt } from './scope-deployment.js';
12
14
  import { reconcileConnectionGrants } from './connection-grants.js';
@@ -696,6 +698,7 @@ const TENANT_ROUTES = [
696
698
  { method: 'GET', re: /\/observability\/tenant-metrics$/, pin: 'query' },
697
699
  { method: 'GET', re: /\/observability\/tenant-metrics-series$/, pin: 'query' },
698
700
  { method: 'GET', re: /\/observability\/tenant-logs$/, pin: 'query' },
701
+ { method: 'GET', re: /\/observability\/tenant-field-coverage$/, pin: 'query' },
699
702
  // #1746: the request record's histogram, facets and list — same grain, same forced tenant.
700
703
  { method: 'GET', re: /\/observability\/tenant-request-volume$/, pin: 'query' },
701
704
  { method: 'GET', re: /\/observability\/tenant-request-facets$/, pin: 'query' },
@@ -798,6 +801,7 @@ const namedTenants = (c) => {
798
801
  */
799
802
  export function createControlPlaneApi(options) {
800
803
  const { host, authenticate, authenticateBuilder, authenticateTenantService } = options;
804
+ const copyLeaseMs = options.copyLeaseMs ?? SCOPE_COPY_LEASE_MS;
801
805
  const app = new Hono();
802
806
  // The CLI version advisory (#971), stamped on EVERY response — including the 401 the
803
807
  // auth middleware below answers with, since a CLI too old to authenticate is exactly
@@ -959,6 +963,7 @@ export function createControlPlaneApi(options) {
959
963
  { method: 'GET', re: /\/observability\/tenant-metrics$/ },
960
964
  { method: 'GET', re: /\/observability\/tenant-metrics-series$/ },
961
965
  { method: 'GET', re: /\/observability\/tenant-logs$/ },
966
+ { method: 'GET', re: /\/observability\/tenant-field-coverage$/ },
962
967
  // #1746: the same lines, counted and listed. Tenant-keyed, so no fleet-wide fallback.
963
968
  { method: 'GET', re: /\/observability\/tenant-request-volume$/ },
964
969
  { method: 'GET', re: /\/observability\/tenant-request-facets$/ },
@@ -2064,6 +2069,7 @@ export function createControlPlaneApi(options) {
2064
2069
  exact: source.exact,
2065
2070
  loadStamp: source.loadStamp,
2066
2071
  expect: source.expect,
2072
+ ...(source.fence ? { fence: source.fence } : {}),
2067
2073
  ...(markCopy ? { markCopy } : {}),
2068
2074
  }));
2069
2075
  };
@@ -2101,13 +2107,9 @@ export function createControlPlaneApi(options) {
2101
2107
  if (!source || !dest) {
2102
2108
  throw new ControlPlaneError(501, 'adopt-serving needs dispatch resolution for both ends');
2103
2109
  }
2104
- const dump = await source.exportScope(scopeId);
2105
2110
  // #1742: the recorded OFF positions ride the restore, applied in the replay's own event.
2106
- const restored = await restoreCarryingSwitches(actor, dest, tenantId, scopeId, dump, { scopeId, exact: true });
2107
- // Data landed — only now flip routing and move the version pointer.
2108
- await c.var.admin
2109
- .setScopeServingRef(actor, tenantId, scopeId, serving.ref, { acknowledge: opts.acknowledge })
2110
- .catch(relayHostRefusal);
2111
+ // Data landed — only then does routing flip and the version pointer move.
2112
+ const restored = await moveOntoServing(c, scope, source, dest, serving.ref, { acknowledge: opts.acknowledge });
2111
2113
  await c.var.admin
2112
2114
  .bindScopeVersion(actor, tenantId, scopeId, serving.versionId, { acknowledge: opts.acknowledge })
2113
2115
  .catch(relayHostRefusal);
@@ -2187,8 +2189,9 @@ export function createControlPlaneApi(options) {
2187
2189
  * independent, and the scope's DO carries the SOURCE lineage's applied-migration
2188
2190
  * journal. The digest gate refuses the crossing unless the scope's bound version and
2189
2191
  * the target's serving version carry the same migration digest — or the operator
2190
- * acknowledges having read both surfaces (`ackMigrations`). The source script's copy
2191
- * is never deleted — flipping `servingRef` + version back is the backout.
2192
+ * acknowledges having read both surfaces (`ackMigrations`). Once the move is confirmed the
2193
+ * source script's copy is wiped by the sweep (#1722, `moveOntoServing`), so it is no backout:
2194
+ * rollback is an explicit snapshot or backup taken before the rebind.
2192
2195
  */
2193
2196
  const rebindScopeOntoVertical = async (c, tenantId, scopeId, target, opts) => {
2194
2197
  const actor = c.get('actor');
@@ -2220,10 +2223,25 @@ export function createControlPlaneApi(options) {
2220
2223
  const move = { acknowledge: opts.acknowledge };
2221
2224
  if (opts.abandonData) {
2222
2225
  // Directory-only crossing: no bytes move, so the frontier gate has nothing to
2223
- // protect — the target provisions its own schema from scratch. The source
2224
- // script's copy is untouched and remains the backout, same as a carried rebind.
2225
- // The scope serves nothing until `/verticals/:slug/instances` re-provisions it.
2226
- await c.var.admin.setScopeServingRef(actor, tenantId, scopeId, serving.ref, move).catch(relayHostRefusal);
2226
+ // protect — the target provisions its own schema from scratch. The source script's
2227
+ // copy is the only copy of the scope's data, and its deployment predates the export a
2228
+ // fenced wipe needs, so it is kept (`retained`), never swept, and reap and erasure still
2229
+ // reach it. The scope serves nothing until `/verticals/:slug/instances` re-provisions it.
2230
+ const sourceRef = await routeOf(c, scope);
2231
+ const moveId = sourceRef && sourceRef !== serving.ref ? ulid() : null;
2232
+ if (moveId && sourceRef) {
2233
+ await c.var.admin.recordScopeScriptCopy(actor, tenantId, scopeId, sourceRef, moveId, { role: 'source' });
2234
+ }
2235
+ try {
2236
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, tenantId, scopeId);
2237
+ await c.var.admin.setScopeServingRef(actor, tenantId, scopeId, serving.ref, {
2238
+ ...move, expectedErasureEpoch: erasureEpoch, ...(moveId ? { confirmMove: { moveId, source: 'retained' } } : {}),
2239
+ }).catch(relayHostRefusal);
2240
+ }
2241
+ finally {
2242
+ if (moveId)
2243
+ await c.var.admin.settleScopeScriptCopy(actor, tenantId, scopeId, sourceRef, moveId, 'retained');
2244
+ }
2227
2245
  await c.var.admin.bindScopeVersion(actor, tenantId, scopeId, serving.versionId, move).catch(relayHostRefusal);
2228
2246
  return { servingRef: serving.ref, versionId: serving.versionId, dataAbandoned: true };
2229
2247
  }
@@ -2246,18 +2264,68 @@ export function createControlPlaneApi(options) {
2246
2264
  if (!source || !dest) {
2247
2265
  throw new ControlPlaneError(501, 'rebind-vertical needs dispatch resolution for both ends');
2248
2266
  }
2249
- const dump = await source.exportScope(scopeId);
2250
- const restored = await restoreCarryingSwitches(actor, dest, tenantId, scopeId, dump, { scopeId, exact: true }); // #1742, as adopt
2251
- // Data landed on the target script — only now flip routing and cross the pointer.
2252
- // `bindScopeVersion` rewrites `scopes.vertical` from the version row, audited. No
2253
- // extra snapshot here (adopt-serving's precedent): the source script's copy is the
2254
- // pre-migration state, and it is never deleted — that copy is the backout.
2255
- await c.var.admin.setScopeServingRef(actor, tenantId, scopeId, serving.ref, move).catch(relayHostRefusal);
2267
+ // #1742, as adopt. Data landed on the target script — only then do routing flip and the
2268
+ // pointer cross. `bindScopeVersion` rewrites `scopes.vertical` from the version row, audited.
2269
+ // No snapshot is taken here: the old copy is swept once the move is confirmed, so an
2270
+ // operator who wants a way back takes a snapshot or backup first.
2271
+ const restored = await moveOntoServing(c, scope, source, dest, serving.ref, move);
2256
2272
  await c.var.admin.bindScopeVersion(actor, tenantId, scopeId, serving.versionId, move).catch(relayHostRefusal);
2257
2273
  // #1674: re-assert the recorded OFF positions in the store the scope now routes to.
2258
2274
  await c.var.admin.reassertSystemSwitches(actor, { tenantId, scopeId }, { appliedInUnit: restored.switchedOff });
2259
2275
  return { servingRef: serving.ref, versionId: serving.versionId, tables: restored.tables };
2260
2276
  };
2277
+ /**
2278
+ * The copy move under adopt-serving and rebind-vertical (#1722): export from the script the
2279
+ * scope routes to, restore onto the serving script, then flip the route. Both ends are in the
2280
+ * ledger, leased to this move, before any bytes move, and the destination's entry names the
2281
+ * stamp its restore leaves, so a crash-recovery sweep can wipe an unbound restore if this
2282
+ * request dies. The route flips only while that lease is live and unclaimed, and the same
2283
+ * write settles the destination `done`.
2284
+ *
2285
+ * The old source is then `eligible`, as a carry's is: the scheduled sweep wipes it, fenced on
2286
+ * the stamp and revision this export read, so a copy that took a write since is kept for staff
2287
+ * rather than deleted. The old copy is not a backout; rollback is an explicit snapshot or
2288
+ * backup taken before the move (the decided policy). A source whose deployment predates the
2289
+ * stamped export cannot be wiped under a fence, and stays `retained`. A move that fails or is
2290
+ * never confirmed keeps its source too: the catch below settles both ends `retained`.
2291
+ */
2292
+ const moveOntoServing = async (c, scope, source, dest, servingRef, routeOpts) => {
2293
+ const actor = c.get('actor');
2294
+ const { tenantId, id: scopeId } = scope;
2295
+ const sourceRef = await routeOf(c, scope);
2296
+ const moveId = sourceRef !== servingRef ? ulid() : null;
2297
+ const restoredStamp = ulid();
2298
+ const recordedAt = Date.now();
2299
+ if (moveId && sourceRef) {
2300
+ await c.var.admin.recordScopeScriptCopy(actor, tenantId, scopeId, sourceRef, moveId, { role: 'source', leaseMs: copyLeaseMs });
2301
+ }
2302
+ try {
2303
+ if (moveId) {
2304
+ await c.var.admin.recordScopeScriptCopy(actor, tenantId, scopeId, servingRef, moveId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
2305
+ }
2306
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, tenantId, scopeId);
2307
+ const { tables: dump, loadStamp: sourceStamp, revision: sourceRevision } = await retryTransient(() => source.exportScopeStamped(scopeId));
2308
+ const restored = await restoreCarryingSwitches(actor, dest, tenantId, scopeId, dump, {
2309
+ scopeId, exact: true, loadStamp: restoredStamp,
2310
+ ...(moveId ? { fence: copyRestoreFence(moveId, recordedAt, copyLeaseMs, erasureEpoch) } : {}),
2311
+ });
2312
+ await c.var.admin.setScopeServingRef(actor, tenantId, scopeId, servingRef, {
2313
+ ...routeOpts, expectedErasureEpoch: erasureEpoch,
2314
+ ...(moveId ? { confirmMove: sourceStamp
2315
+ ? { moveId, source: 'eligible', sourceMarker: { loadStamp: sourceStamp, revision: sourceRevision } }
2316
+ : { moveId, source: 'retained' } } : {}),
2317
+ }).catch(relayHostRefusal);
2318
+ return restored;
2319
+ }
2320
+ catch (error) {
2321
+ if (moveId)
2322
+ await Promise.allSettled([
2323
+ ...(sourceRef ? [c.var.admin.settleScopeScriptCopy(actor, tenantId, scopeId, sourceRef, moveId, 'retained')] : []),
2324
+ c.var.admin.settleScopeScriptCopy(actor, tenantId, scopeId, servingRef, moveId, 'retained'),
2325
+ ]);
2326
+ throw error;
2327
+ }
2328
+ };
2261
2329
  /** The script a scope's requests reach: its serving pin, else its bound version's own script. */
2262
2330
  const routeOf = async (c, scope) => {
2263
2331
  if (scope.servingRef)
@@ -2351,43 +2419,74 @@ export function createControlPlaneApi(options) {
2351
2419
  throw new ControlPlaneError(502, `cannot move scope ${scope.id} from '${from}' to '${to}': ${missing} could not be reached, ` +
2352
2420
  `so the version was not bound (#1710)`);
2353
2421
  }
2354
- const { tables: dump, loadStamp: sourceStamp, revision: sourceRevision } = await retryTransient(() => source.exportScopeStamped(scope.id));
2355
- // What the destination holds now, read before the binding is checked again. The restore
2356
- // sends it back and is refused if the store moved since: another carry into the same script
2357
- // loaded it, or it went live under another carry's bind and took a write. That is a CI retry
2358
- // of the same version, held before its restore while the first run bound and served.
2359
- const destMarker = await retryTransient(() => dest.loadMarker(scope.id));
2360
- const now = await c.var.admin.getScopeRecord(actor, scope.tenantId, scope.id);
2361
- if (!now ||
2362
- (now.verticalVersionId ?? null) !== (scope.verticalVersionId ?? null) ||
2363
- (now.servingRef ?? null) !== (scope.servingRef ?? null)) {
2364
- throw new ControlPlaneError(412, `scope ${scope.id} was re-pointed while its data was being copied out of '${from}', so nothing was ` +
2365
- `moved or bound (#1722). Reload the scope and retry.`);
2366
- }
2367
- if (dumpMetaValue(dump, CARRIED_AWAY_KEY) !== null) {
2368
- throw new ControlPlaneError(412, `the copy of scope ${scope.id} in '${from}' was already carried to another script and wiped, so nothing ` +
2369
- `was moved or bound (#1722). Reload the scope and retry.`);
2370
- }
2422
+ // Before exporting or restoring anything, retain the script identity in the directory, so a
2423
+ // failed carry stays named for reap and erasure. Both entries are leased to this move: if this
2424
+ // request dies, a sweep settles them once the lease runs out, and the move can then no longer
2425
+ // confirm its bind.
2426
+ const moveId = ulid();
2371
2427
  // #1742: the recorded OFF positions ride the restore, as on adopt and rebind. #1722: so does
2372
- // a stamp of this carry's own, which a refused bind's wipe of the copy expects.
2428
+ // a stamp of this carry's own, which a refused bind's wipe of the copy expects, and which the
2429
+ // destination's entry names before the restore so a crash-recovery sweep can fence on it.
2373
2430
  const restoredStamp = ulid();
2374
- const restored = await restoreCarryingSwitches(actor, dest, scope.tenantId, scope.id, dump, {
2375
- scopeId: scope.id,
2376
- exact: true,
2377
- loadStamp: restoredStamp,
2378
- ...(destMarker === 'unfenced' ? {} : { expect: destMarker }),
2379
- });
2380
- return {
2381
- from,
2382
- to,
2383
- tables: restored.tables,
2384
- switchedOff: restored.switchedOff,
2385
- source,
2386
- dest,
2387
- sourceStamp,
2388
- sourceRevision,
2389
- restoredStamp,
2390
- };
2431
+ const recordedAt = Date.now();
2432
+ await c.var.admin.recordScopeScriptCopy(actor, scope.tenantId, scope.id, from, moveId, { role: 'source', leaseMs: copyLeaseMs });
2433
+ try {
2434
+ // The unbound destination can also survive a refused bind or a failed best-effort
2435
+ // cleanup. Name it before any bytes are restored so reap and erasure can find it.
2436
+ await c.var.admin.recordScopeScriptCopy(actor, scope.tenantId, scope.id, to, moveId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
2437
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, scope.tenantId, scope.id);
2438
+ const { tables: dump, loadStamp: sourceStamp, revision: sourceRevision } = await retryTransient(() => source.exportScopeStamped(scope.id));
2439
+ // What the destination holds now, read before the binding is checked again. The restore
2440
+ // sends it back and is refused if the store moved since: another carry into the same script
2441
+ // loaded it, or it went live under another carry's bind and took a write. That is a CI retry
2442
+ // of the same version, held before its restore while the first run bound and served.
2443
+ const destMarker = await retryTransient(() => dest.loadMarker(scope.id));
2444
+ const now = await c.var.admin.getScopeRecord(actor, scope.tenantId, scope.id);
2445
+ if (!now ||
2446
+ (now.verticalVersionId ?? null) !== (scope.verticalVersionId ?? null) ||
2447
+ (now.servingRef ?? null) !== (scope.servingRef ?? null)) {
2448
+ throw new ControlPlaneError(412, `scope ${scope.id} was re-pointed while its data was being copied out of '${from}', so nothing was ` +
2449
+ `moved or bound (#1722). Reload the scope and retry.`);
2450
+ }
2451
+ if (dumpMetaValue(dump, CARRIED_AWAY_KEY) !== null) {
2452
+ throw new ControlPlaneError(412, `the copy of scope ${scope.id} in '${from}' was already carried to another script and wiped, so nothing ` +
2453
+ `was moved or bound (#1722). Reload the scope and retry.`);
2454
+ }
2455
+ const restored = await restoreCarryingSwitches(actor, dest, scope.tenantId, scope.id, dump, {
2456
+ scopeId: scope.id,
2457
+ exact: true,
2458
+ loadStamp: restoredStamp,
2459
+ ...(destMarker === 'unfenced' ? {} : { expect: destMarker }),
2460
+ // The store refuses this load once the move's lease can have run out (#1722).
2461
+ fence: copyRestoreFence(moveId, recordedAt, copyLeaseMs, erasureEpoch),
2462
+ });
2463
+ return {
2464
+ moveId,
2465
+ erasureEpoch,
2466
+ from,
2467
+ to,
2468
+ tables: restored.tables,
2469
+ switchedOff: restored.switchedOff,
2470
+ source,
2471
+ dest,
2472
+ sourceStamp,
2473
+ sourceRevision,
2474
+ restoredStamp,
2475
+ };
2476
+ }
2477
+ catch (error) {
2478
+ // Neither script can be discarded based on this unconfirmed move. A retry or reap
2479
+ // can still reach both. A crash leaves them pending and blocks key finalization.
2480
+ const settled = await Promise.allSettled([
2481
+ c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, from, moveId, 'retained'),
2482
+ c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, to, moveId, 'retained'),
2483
+ ]);
2484
+ for (const result of settled) {
2485
+ if (result.status === 'rejected')
2486
+ recordCarryCleanup(c, scope, versionId, 'copy-ledger', result.reason);
2487
+ }
2488
+ throw error;
2489
+ }
2391
2490
  };
2392
2491
  /**
2393
2492
  * Wipe one copy of a scope that no route reaches (#1722), without reaping it. Fenced where the
@@ -2505,14 +2604,29 @@ export function createControlPlaneApi(options) {
2505
2604
  await dropUnboundCopy(c, scope, versionId, stale);
2506
2605
  throw new CarrySourceChanged(scope.id, stale.from, stale.to, attempt);
2507
2606
  }
2607
+ // The fresh carry restored over the stale one's copy in the same script and holds its own
2608
+ // entries for both ends, so the stale move leaves nothing of its own behind (#1722).
2609
+ await supersedeMove(c, scope, versionId, stale);
2508
2610
  carried = next;
2509
2611
  }
2612
+ // #1722: the write that moves the route confirms the move, while its lease is live. That is the
2613
+ // bind itself, unless a pin still routes the scope to the source until it is cleared below.
2614
+ // The source is confirmed `retained`, not `eligible`: `settleCarriedSource` may still have to
2615
+ // carry it again (an overtaken destination), and promotes it only once that is ruled out, so
2616
+ // no sweep can wipe it first. A request that dies in between leaves it kept, not swept.
2617
+ const unpins = Boolean(opts.clearServingRef && scope.servingRef);
2618
+ const confirmMove = carried
2619
+ ? { confirmMove: { moveId: carried.moveId, source: 'retained',
2620
+ sourceMarker: { loadStamp: carried.sourceStamp, revision: carried.sourceRevision } } }
2621
+ : {};
2510
2622
  try {
2511
2623
  await c.var.admin
2512
2624
  .bindScopeVersion(actor, scope.tenantId, scope.id, versionId, {
2513
2625
  acknowledge: opts.acknowledge,
2514
2626
  ...(opts.snapshot ? { snapshot: true } : {}),
2515
2627
  expectedVersionId: scope.verticalVersionId ?? null,
2628
+ ...(carried ? { expectedErasureEpoch: carried.erasureEpoch } : {}),
2629
+ ...(unpins ? {} : confirmMove),
2516
2630
  })
2517
2631
  .catch(relayHostRefusal);
2518
2632
  }
@@ -2521,8 +2635,15 @@ export function createControlPlaneApi(options) {
2521
2635
  await dropUnboundCopy(c, scope, versionId, carried);
2522
2636
  throw e;
2523
2637
  }
2524
- if (opts.clearServingRef && scope.servingRef) {
2525
- await c.var.admin.setScopeServingRef(actor, scope.tenantId, scope.id, null).catch(relayHostRefusal);
2638
+ if (unpins) {
2639
+ try {
2640
+ await c.var.admin.setScopeServingRef(actor, scope.tenantId, scope.id, null, carried ? { expectedErasureEpoch: carried.erasureEpoch, ...confirmMove } : undefined).catch(relayHostRefusal);
2641
+ }
2642
+ catch (e) {
2643
+ if (carried)
2644
+ await dropUnboundCopy(c, scope, versionId, carried);
2645
+ throw e;
2646
+ }
2526
2647
  }
2527
2648
  try {
2528
2649
  await c.var.admin.reassertSystemSwitches(actor, { tenantId: scope.tenantId, scopeId: scope.id }, { appliedInUnit: carried?.switchedOff });
@@ -2534,19 +2655,36 @@ export function createControlPlaneApi(options) {
2534
2655
  await settleCarriedSource(c, scope, versionId, carried);
2535
2656
  }
2536
2657
  };
2658
+ /** Settle a carry that a fresh carry into the same script replaced. Best effort, recorded. */
2659
+ const supersedeMove = async (c, scope, versionId, stale) => {
2660
+ const settled = await Promise.allSettled([stale.from, stale.to].map((ref) => c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, ref, stale.moveId, 'done')));
2661
+ for (const result of settled) {
2662
+ if (result.status === 'rejected')
2663
+ recordCarryCleanup(c, scope, versionId, 'copy-ledger', result.reason);
2664
+ }
2665
+ };
2537
2666
  /**
2538
2667
  * The copy a carry restored for a bind that did not land, wiped unless the scope routes to
2539
2668
  * that script now. Best effort: it never throws, and a failure is recorded.
2540
2669
  */
2541
2670
  const dropUnboundCopy = async (c, scope, versionId, carried) => {
2671
+ let route = null;
2542
2672
  try {
2543
- const route = await currentRoute(c, scope, versionId, carried);
2544
- if (route === carried.to)
2673
+ route = await currentRoute(c, scope, versionId, carried);
2674
+ if (route === carried.to) {
2675
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, 'done');
2545
2676
  return;
2546
- await wipeCarriedCopy(carried.dest, scope, { loadStamp: carried.restoredStamp }, route ?? carried.from);
2677
+ }
2678
+ const wiped = await wipeCarriedCopy(carried.dest, scope, { loadStamp: carried.restoredStamp }, route ?? carried.from);
2679
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, wiped ? 'done' : 'retained');
2547
2680
  }
2548
2681
  catch (e) {
2549
2682
  recordCarryCleanup(c, scope, versionId, 'unbound-copy', e);
2683
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, 'retained').catch((err) => recordCarryCleanup(c, scope, versionId, 'unbound-copy-ledger', err));
2684
+ }
2685
+ finally {
2686
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, route === carried.from ? 'done' : 'retained')
2687
+ .catch((err) => recordCarryCleanup(c, scope, versionId, 'source-copy-ledger', err));
2550
2688
  }
2551
2689
  };
2552
2690
  /**
@@ -2628,8 +2766,10 @@ export function createControlPlaneApi(options) {
2628
2766
  // The caller read the route elsewhere, so a copy that changed in any way since the export (a
2629
2767
  // load as much as a write: a staff restore-forward into it racing this carry, Codex #2008 r8)
2630
2768
  // is kept in the store rather than left an unmarked orphan.
2631
- if (await wipeCarriedCopy(carried.source, scope, expect, carried.to, true))
2769
+ if (await wipeCarriedCopy(carried.source, scope, expect, carried.to, true)) {
2770
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, 'done', expect);
2632
2771
  return;
2772
+ }
2633
2773
  // A rollback that restored into it since made it the live store again: it is no kept copy, and
2634
2774
  // a marker this refusal set while the rollback had not yet bound comes off.
2635
2775
  const route = await currentRoute(c, scope, versionId, carried);
@@ -2637,8 +2777,11 @@ export function createControlPlaneApi(options) {
2637
2777
  await releaseIfLive(c, scope, versionId, carried, carried.source, carried.from);
2638
2778
  return;
2639
2779
  }
2640
- if (route === carried.to && (await bringClearForward(c, scope, versionId, carried)))
2780
+ if (route === carried.to && (await bringClearForward(c, scope, versionId, carried))) {
2781
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, 'done', expect);
2641
2782
  return;
2783
+ }
2784
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, 'kept', expect);
2642
2785
  recordCarryCleanup(c, scope, versionId, 'source-copy-kept', new ControlPlaneError(409, `scope ${scope.id}'s copy in '${carried.from}' changed after it was carried to '${carried.to}', so it was ` +
2643
2786
  `kept: it holds what reached it in between, which the carry did not copy (#1722)`));
2644
2787
  };
@@ -2658,35 +2801,68 @@ export function createControlPlaneApi(options) {
2658
2801
  */
2659
2802
  const settleCarriedSource = async (c, scope, versionId, carried) => {
2660
2803
  const actor = c.get('actor');
2804
+ const finishDestination = async () => {
2805
+ if ((await currentRoute(c, scope, versionId, carried)) === carried.to) {
2806
+ await c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, carried.to, carried.moveId, 'done');
2807
+ }
2808
+ else {
2809
+ await dropUnboundCopy(c, scope, versionId, carried);
2810
+ }
2811
+ };
2661
2812
  try {
2662
2813
  const route = await currentRoute(c, scope, versionId, carried);
2663
- if (route === carried.from)
2814
+ if (route !== carried.to) {
2815
+ await dropUnboundCopy(c, scope, versionId, carried);
2664
2816
  return;
2817
+ }
2665
2818
  // The store this carry landed in is live; a kept marker another carry set while racing it
2666
2819
  // does not belong on it (#1722 r8).
2667
- if (route === carried.to)
2668
- await releaseIfLive(c, scope, versionId, carried, carried.dest, carried.to);
2669
- if (route === carried.to && (await isCarriedAway(carried.dest, scope))) {
2820
+ await releaseIfLive(c, scope, versionId, carried, carried.dest, carried.to);
2821
+ let sourceMarker = { loadStamp: carried.sourceStamp, revision: carried.sourceRevision };
2822
+ if (await isCarriedAway(carried.dest, scope)) {
2670
2823
  const { tables: dump, loadStamp: stamp, revision } = await retryTransient(() => carried.source.exportScopeStamped(scope.id));
2671
2824
  if (dumpMetaValue(dump, CARRIED_AWAY_KEY) !== null) {
2672
2825
  throw new ControlPlaneError(500, `both copies of scope ${scope.id} hold the carried_away tombstone; nothing was wiped`);
2673
2826
  }
2674
- await restoreCarryingSwitches(actor, carried.dest, scope.tenantId, scope.id, dump, {
2675
- scopeId: scope.id,
2676
- exact: true,
2677
- loadStamp: ulid(),
2678
- });
2827
+ // The re-carry is a copy move of its own (#1722): in the ledger and leased before it
2828
+ // writes, and fenced, so it cannot land after a reap or an erasure has settled the scope.
2829
+ const recarryId = ulid();
2830
+ const restoredStamp = ulid();
2831
+ const recordedAt = Date.now();
2832
+ await c.var.admin.recordScopeScriptCopy(actor, scope.tenantId, scope.id, carried.to, recarryId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
2833
+ try {
2834
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, scope.tenantId, scope.id);
2835
+ await restoreCarryingSwitches(actor, carried.dest, scope.tenantId, scope.id, dump, {
2836
+ scopeId: scope.id,
2837
+ exact: true,
2838
+ loadStamp: restoredStamp,
2839
+ fence: copyRestoreFence(recarryId, recordedAt, copyLeaseMs, erasureEpoch),
2840
+ });
2841
+ }
2842
+ finally {
2843
+ // The scope routes to this store, so the route reaches whatever landed in it.
2844
+ await c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, carried.to, recarryId, 'done');
2845
+ }
2679
2846
  if (await isCarriedAway(carried.dest, scope)) {
2680
2847
  throw new ControlPlaneError(500, `scope ${scope.id}'s store in '${carried.to}' was wiped again; its source copy stays`);
2681
2848
  }
2682
2849
  // Re-carried, so the fence expects what the re-export read.
2683
- await keepOrWipeSource(c, scope, versionId, carried, { loadStamp: stamp, revision });
2850
+ sourceMarker = { loadStamp: stamp, revision };
2851
+ }
2852
+ // Only now may the sweep wipe the source: the destination holds the data.
2853
+ const eligible = await c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, carried.from, carried.moveId, 'eligible', sourceMarker);
2854
+ if (!eligible) {
2855
+ await finishDestination(); // a later move through this script superseded this carry
2684
2856
  return;
2685
2857
  }
2686
- await keepOrWipeSource(c, scope, versionId, carried, { loadStamp: carried.sourceStamp, revision: carried.sourceRevision });
2858
+ await keepOrWipeSource(c, scope, versionId, carried, sourceMarker);
2859
+ await finishDestination();
2687
2860
  }
2688
2861
  catch (e) {
2689
2862
  recordCarryCleanup(c, scope, versionId, 'source-copy', e);
2863
+ // This call can no longer restore another destination copy. Clear its pending
2864
+ // move if it is still serving, even when the source wipe needs a sweep retry.
2865
+ await finishDestination().catch((err) => recordCarryCleanup(c, scope, versionId, 'destination-copy-ledger', err));
2690
2866
  }
2691
2867
  };
2692
2868
  app.get('/tenants/:tenantId/scopes/:scopeId/tables', async (c) => {
@@ -3592,12 +3768,53 @@ export function createControlPlaneApi(options) {
3592
3768
  // on); the DIRECTORY half — provenance row, activation, version bind — runs here.
3593
3769
  // With no vertical client resolved (co-located host, tests, self-host) the host's
3594
3770
  // in-process snapshotScope does both halves against its own SCOPE namespace.
3771
+ /**
3772
+ * The script a slug-resolved scope lives in, by the hosted resolver's rule: the vertical's
3773
+ * stable serving script, else its prod channel's version script (control-plane worker
3774
+ * `resolveVerticalFor`). Null unless the platform can also reach that script by ref.
3775
+ */
3776
+ const slugRefOf = async (c, slug) => {
3777
+ const actor = c.get('actor');
3778
+ const serving = await c.var.admin.verticalServing(actor, slug).catch(() => null);
3779
+ let ref = serving?.ref ?? null;
3780
+ if (!ref) {
3781
+ const prod = (await c.var.admin.listChannels(actor, slug).catch(() => [])).find((ch) => ch.channel === 'prod');
3782
+ ref = prod ? ((await c.var.admin.getVersion(actor, prod.versionId, slug))?.deploymentRef ?? null) : null;
3783
+ }
3784
+ return ref && (await options.resolveVerticalRef?.(ref)) ? ref : null;
3785
+ };
3595
3786
  const orchestratedSnapshot = async (c, tenantId, scope, opts) => {
3596
3787
  const actor = c.get('actor');
3597
- const vertical = await verticalForScope(c, scope);
3788
+ const deployment = await deploymentForScope(c, scope);
3789
+ const vertical = deployment?.client;
3598
3790
  if (!vertical)
3599
3791
  return c.var.host.snapshotScope(actor, tenantId, scope.id, opts);
3600
3792
  const snapId = scopeIdSchema.parse(ulid());
3793
+ // #1722: the script the copy lands in (the source's own), named in the ledger before the
3794
+ // copy, so a bind that fails, or a request that dies, leaves a fork reap and erasure reach.
3795
+ // A pinned or bound source names it with the same value its client was resolved from. A
3796
+ // source resolved by slug is resolved once, here (`slugRefOf`), and copied through THAT
3797
+ // ref's client, so a serving move or a promote between two reads cannot put the bytes in
3798
+ // one script and the ledger entry on another. Without a ref (no per-script resolution, or
3799
+ // a slug script the platform cannot reach by ref) the fork has no entry, and reap and
3800
+ // erasure reach it through the slug resolution instead.
3801
+ let ref = null;
3802
+ let copier = vertical;
3803
+ if (options.resolveVerticalRef) {
3804
+ if (deployment.via === 'serving-script')
3805
+ ref = scope.servingRef ?? null;
3806
+ else if (deployment.via === 'bound-version' && scope.vertical && scope.verticalVersionId) {
3807
+ ref = (await c.var.admin.getVersion(actor, scope.verticalVersionId, scope.vertical))?.deploymentRef ?? null;
3808
+ }
3809
+ else if (deployment.via === 'slug' && scope.vertical) {
3810
+ ref = await slugRefOf(c, scope.vertical);
3811
+ const byRef = ref ? await options.resolveVerticalRef(ref) : undefined;
3812
+ if (byRef)
3813
+ copier = byRef;
3814
+ else
3815
+ ref = null;
3816
+ }
3817
+ }
3601
3818
  // Directory row FIRST, as `provisioning` (K-31's two-phase shape, used as
3602
3819
  // intended): a crash between the row and the data copy leaves an inert
3603
3820
  // provisioning row — which, carrying provenance and an expiry, the GC sweep
@@ -3612,12 +3829,34 @@ export function createControlPlaneApi(options) {
3612
3829
  forkedAt: new Date().toISOString(),
3613
3830
  expiresAt: opts.expiresAt,
3614
3831
  });
3615
- await retryTransient(() => vertical.snapshotScope({ sourceScopeId: scope.id, newScopeId: snapId, tenantId }));
3616
- await c.var.admin.activateScope(actor, tenantId, snapId);
3617
- // Bound to the SOURCE's current version: source and fork share a deployment, so
3618
- // the fork resolves to the DO namespace its bytes actually live in.
3619
- if (scope.verticalVersionId) {
3620
- await c.var.admin.bindScopeVersion(actor, tenantId, snapId, scope.verticalVersionId);
3832
+ const moveId = ref ? ulid() : null;
3833
+ try {
3834
+ if (moveId && ref) {
3835
+ // No load stamp: the vertical's in-script copy leaves none, so a crash-recovery sweep keeps
3836
+ // this copy (`retained`) rather than wiping it, and reap and erasure still reach it.
3837
+ await c.var.admin.recordScopeScriptCopy(actor, tenantId, snapId, ref, moveId, { role: 'destination', leaseMs: copyLeaseMs });
3838
+ }
3839
+ await retryTransient(() => copier.snapshotScope({ sourceScopeId: scope.id, newScopeId: snapId, tenantId }));
3840
+ await c.var.admin.activateScope(actor, tenantId, snapId);
3841
+ // Bound to the SOURCE's current version: source and fork share a deployment, so
3842
+ // the fork resolves to the DO namespace its bytes actually live in.
3843
+ if (scope.verticalVersionId) {
3844
+ await c.var.admin.bindScopeVersion(actor, tenantId, snapId, scope.verticalVersionId);
3845
+ }
3846
+ // The fork's route is the script its bytes were copied into, never the serving pointer
3847
+ // `provisionScope` stamped (which may have moved since), and the write that sets it confirms
3848
+ // the move. A fork of a bound source routes by its bound version, whose script is `ref`: its
3849
+ // stamped pin is cleared, so a later bind of the fork carries its data like any other scope's.
3850
+ // A fork of a pinned or slug-resolved source is pinned to `ref`, the script it lives in.
3851
+ if (moveId && ref) {
3852
+ await c.var.admin.setScopeServingRef(actor, tenantId, snapId, deployment.via === 'bound-version' ? null : ref, { confirmMove: { moveId, source: 'retained' } });
3853
+ }
3854
+ }
3855
+ catch (e) {
3856
+ if (moveId && ref) {
3857
+ await c.var.admin.settleScopeScriptCopy(actor, tenantId, snapId, ref, moveId, 'retained').catch(() => undefined);
3858
+ }
3859
+ throw e;
3621
3860
  }
3622
3861
  return snapId;
3623
3862
  };
@@ -3677,6 +3916,37 @@ export function createControlPlaneApi(options) {
3677
3916
  throw e;
3678
3917
  }
3679
3918
  };
3919
+ /**
3920
+ * Delete a scope's storage in every script that may hold it, before the directory forgets it.
3921
+ * Answers whether some of it is stranded (a script that predates `/internal/delete-scope`).
3922
+ *
3923
+ * #1722: with per-script resolution, the ledger names every copy a move or a fork wrote, and
3924
+ * the route names the live store; `reapScopeScriptCopies` reaches both, under the reap claim.
3925
+ * A scope nothing routes (no pin, no bound version) may still keep its store where its vertical
3926
+ * resolves by slug, which is where it was provisioned, so that deployment is reached too, as
3927
+ * it was before the ledger. Without per-script resolution there is only that deployment, and
3928
+ * a ledgered copy the platform cannot reach refuses the reap.
3929
+ */
3930
+ const reapScopeStorage = async (c, scope) => {
3931
+ const actor = c.get('actor');
3932
+ // The deployment the scope's vertical resolves to, deleted through; a 501 there is recorded
3933
+ // as stranded storage, as `reapScopeScriptCopies` records its own.
3934
+ const viaDeployment = async () => {
3935
+ const stranded = await deleteScopeStorageOrStrand(await verticalForScope(c, scope), scope.tenantId, scope.id);
3936
+ if (stranded) {
3937
+ await recordStrandedStorage(c.var.admin, actor, scope.tenantId, scope.id, `the deployment its vertical '${scope.vertical}' resolves to`);
3938
+ }
3939
+ return stranded;
3940
+ };
3941
+ if (!options.resolveVerticalRef) {
3942
+ await assertNoUnreachableScopeCopies(c.var.admin, actor, scope.tenantId, scope.id);
3943
+ return viaDeployment();
3944
+ }
3945
+ const unrouted = (await routeOf(c, scope)) === null;
3946
+ const { storageStranded } = await reapScopeScriptCopies({ admin: c.var.admin, actor, resolveRef: options.resolveVerticalRef }, scope.tenantId, scope.id);
3947
+ const bySlug = unrouted ? await viaDeployment() : false;
3948
+ return storageStranded || bySlug;
3949
+ };
3680
3950
  app.delete('/tenants/:tenantId/scopes/:scopeId', async (c) => {
3681
3951
  const tenantId = tenantIdSchema.parse(c.req.param('tenantId'));
3682
3952
  const scopeId = scopeIdSchema.parse(c.req.param('scopeId'));
@@ -3692,8 +3962,7 @@ export function createControlPlaneApi(options) {
3692
3962
  // local/placeholder wipe, hostnames + directory row, audit) — the same
3693
3963
  // storage-before-row ordering deleteSnapshot itself keeps, so a crash
3694
3964
  // between the two converges on retry.
3695
- const vertical = await verticalForScope(c, scope);
3696
- const storageStranded = await deleteScopeStorageOrStrand(vertical, tenantId, scopeId);
3965
+ const storageStranded = await reapScopeStorage(c, scope);
3697
3966
  await c.var.host.deleteSnapshot(actor, tenantId, scopeId);
3698
3967
  return c.json({ deleted: scopeId, ...(storageStranded ? { storageStranded: true } : {}) });
3699
3968
  }
@@ -3819,7 +4088,42 @@ export function createControlPlaneApi(options) {
3819
4088
  const scope = await c.var.admin.getScopeRecord(c.get('actor'), tenantId, scopeId);
3820
4089
  if (!scope)
3821
4090
  return c.json({ error: `unknown scope for tenant: (${tenantId}, ${scopeId})` }, 404);
3822
- return c.json(await c.var.admin.shredSubject(c.get('actor'), tenantId, scopeId, subjectId));
4091
+ const copies = await listAllScopeScriptCopies(c.var.admin, c.get('actor'), tenantId, scopeId);
4092
+ // A move in flight can still restore a copy no inventory read now would name. Its entries
4093
+ // settle when it confirms or fails, or, if it died, when the sweep finds its lease run out.
4094
+ if (copies.some((copy) => copy.state === 'pending')) {
4095
+ throw new ControlPlaneError(412, `scope ${scopeId} has a copy move in flight; retry the erasure after it settles`);
4096
+ }
4097
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(c.get('actor'), tenantId, scopeId);
4098
+ const currentRef = await routeOf(c, scope);
4099
+ if (!options.resolveVerticalRef) {
4100
+ if (currentRef || copies.some((copy) => copy.state !== 'done')) {
4101
+ throw new ControlPlaneError(502, `scope ${scopeId} has script copies, but this control plane cannot reach their deployments`);
4102
+ }
4103
+ return c.json(await c.var.admin.shredSubject(c.get('actor'), tenantId, scopeId, subjectId));
4104
+ }
4105
+ // A scope nothing routes may still keep its store where its vertical resolves by slug (where
4106
+ // it was provisioned), so erasure reaches that deployment too, as reap does (`reapScopeStorage`).
4107
+ const bySlug = currentRef ? undefined : await verticalForScope(c, scope);
4108
+ if (!currentRef && !bySlug && copies.every((copy) => copy.state === 'done')) {
4109
+ return c.json(await c.var.admin.shredSubject(c.get('actor'), tenantId, scopeId, subjectId));
4110
+ }
4111
+ const refs = new Set(copies.filter((copy) => copy.state !== 'done').map((copy) => copy.scriptRef));
4112
+ if (currentRef)
4113
+ refs.add(currentRef);
4114
+ const redactions = [];
4115
+ for (const ref of refs) {
4116
+ const script = await options.resolveVerticalRef(ref);
4117
+ if (!script)
4118
+ throw new ControlPlaneError(502, `scope ${scopeId}'s copy in '${ref}' cannot be reached for erasure`);
4119
+ redactions.push(await script.redactSubject(scopeId, subjectId));
4120
+ }
4121
+ if (bySlug)
4122
+ redactions.push(await bySlug.redactSubject(scopeId, subjectId));
4123
+ return c.json(await c.var.admin.finalizeSubjectShred(c.get('actor'), tenantId, scopeId, subjectId, redactions, {
4124
+ versionId: scope.verticalVersionId, servingRef: scope.servingRef ?? null, epoch: erasureEpoch,
4125
+ copyCount: copies.length,
4126
+ }).catch(relayHostRefusal));
3823
4127
  });
3824
4128
  // -- directory backups (#40) -----------------------------------------------
3825
4129
  // The platform's own disaster recovery, on the same store posture as the scope
@@ -4266,10 +4570,9 @@ export function createControlPlaneApi(options) {
4266
4570
  }
4267
4571
  }
4268
4572
  try {
4269
- const vertical = await verticalForScope(c, scope);
4270
4573
  // By this point the backup contract has resolved (a copy landed, or the caller
4271
4574
  // explicitly declined one), so stranding is a bookkeeping fact, not data loss.
4272
- const storageStranded = await deleteScopeStorageOrStrand(vertical, tenantId, scopeId);
4575
+ const storageStranded = await reapScopeStorage(c, scope);
4273
4576
  await c.var.admin.reapScope(actor, tenantId, scopeId, {
4274
4577
  ...(backup ? { backupRef: backupRefOf(backup) } : {}),
4275
4578
  });
@@ -6622,6 +6925,45 @@ export function createControlPlaneApi(options) {
6622
6925
  const services = await appServices(c.get('actor'), input.tenantId, input.scopeId, input.vertical);
6623
6926
  return c.json(await options.observability.tenantLogs({ ...input, services }));
6624
6927
  });
6928
+ // #1331: one app's sampled field reports, joined to the router's own request lines.
6929
+ app.get('/observability/tenant-field-coverage', async (c) => {
6930
+ if (!options.observability?.fieldCoverage) {
6931
+ return c.json({ error: 'field coverage is not configured on this control plane' }, 501);
6932
+ }
6933
+ const tenantId = confinedTenant(c.get('principal')) ?? c.req.query('tenantId');
6934
+ if (!tenantId)
6935
+ throw new ControlPlaneError(400, 'tenantId is required');
6936
+ const input = z.object({
6937
+ tenantId: tenantIdSchema,
6938
+ scopeId: z.string().min(1).max(64),
6939
+ versionId: z.string().min(1).max(64),
6940
+ hours: z.coerce.number().int().min(1).max(72).default(24),
6941
+ since: z.string().datetime({ offset: true }).optional(),
6942
+ until: z.string().datetime({ offset: true }).optional(),
6943
+ }).parse({ tenantId, scopeId: c.req.query('scopeId'), versionId: c.req.query('versionId'),
6944
+ hours: c.req.query('hours'), since: c.req.query('since') || undefined, until: c.req.query('until') || undefined });
6945
+ try {
6946
+ resolveObservabilityWindow(input);
6947
+ }
6948
+ catch (e) {
6949
+ throw new ControlPlaneError(400, e.message);
6950
+ }
6951
+ const scopes = await host.admin.listScopes(c.get('actor'), { tenantId: input.tenantId });
6952
+ const installed = scopes.find((s) => s.id === input.scopeId);
6953
+ if (!installed?.vertical)
6954
+ return c.json({ error: 'app not found' }, 404);
6955
+ const services = scriptFamiliesOfScopes(scopes, { scopeId: input.scopeId });
6956
+ const json = await c.var.admin.versionManifest(c.get('actor'), installed.vertical, input.versionId);
6957
+ if (!json)
6958
+ return c.json({ error: 'version not found' }, 404);
6959
+ const outputSurface = storedDeployManifest.parse(JSON.parse(json)).outputSurface ?? [];
6960
+ const declared = Object.fromEntries(outputSurface.map((op) => [op.operationId, op.fields]));
6961
+ return c.json(await options.observability.fieldCoverage({
6962
+ tenantId: input.tenantId, vertical: installed.vertical, scopeId: input.scopeId, services, declared,
6963
+ versionId: input.versionId, hours: input.hours,
6964
+ ...(input.since ? { since: input.since, until: input.until } : {}),
6965
+ }));
6966
+ });
6625
6967
  // #1746: the per-request record, read at the tenant grain. The three routes take ONE
6626
6968
  // query — tenant, window, facet filters (`tenant-request-query.ts`) — so the histogram,
6627
6969
  // the facet counts and the list beside them always describe the same set of requests.
@@ -7067,15 +7409,29 @@ export function createControlPlaneApi(options) {
7067
7409
  * its hostnames. Storage-before-row, the same ordering the DELETE route uses — a crash
7068
7410
  * between the two converges on retry. Shared by that route and by the create path, which
7069
7411
  * reaps a HALF-BUILT leftover before re-forking (see `orchestratedPreview`). */
7412
+ /** Answers whether some of the preview's storage was stranded (and recorded as such). */
7070
7413
  const reapPreview = async (c, preview) => {
7071
7414
  // A fork's own sign-in clients go FIRST (#1704): a failure here leaves the preview in
7072
7415
  // place, so the retry a PR-close job makes still finds it — after the row is gone, nothing
7073
7416
  // would name those clients again. A clean room never had one.
7074
7417
  await retireClientsOfReapedScope(previewAuthDeps(c), preview);
7075
- const vertical = await verticalForScope(c, preview);
7076
- if (vertical)
7077
- await vertical.deleteScope({ tenantId: preview.tenantId, scopeId: preview.id });
7418
+ let storageStranded = false;
7419
+ if (options.resolveVerticalRef) {
7420
+ ({ storageStranded } = await reapScopeScriptCopies({
7421
+ admin: c.var.admin,
7422
+ actor: c.get('actor'),
7423
+ resolveRef: options.resolveVerticalRef,
7424
+ }, preview.tenantId, preview.id));
7425
+ }
7426
+ else {
7427
+ await assertNoUnreachableScopeCopies(c.var.admin, c.get('actor'), preview.tenantId, preview.id);
7428
+ const vertical = await verticalForScope(c, preview);
7429
+ if (vertical)
7430
+ await vertical.deleteScope({ tenantId: preview.tenantId, scopeId: preview.id });
7431
+ }
7432
+ // Co-located hosts have no script ref; their storage is wiped by deleteSnapshot.
7078
7433
  await c.var.host.deleteSnapshot(c.get('actor'), preview.tenantId, preview.id);
7434
+ return { storageStranded };
7079
7435
  };
7080
7436
  /** The preview-login seam (#1704, `preview-auth.ts`): the directory, and each issuer's deployment. */
7081
7437
  const previewAuthDeps = (c) => ({
@@ -7372,6 +7728,7 @@ export function createControlPlaneApi(options) {
7372
7728
  }
7373
7729
  };
7374
7730
  let row;
7731
+ /** `fenced`: the ledger stamp and lease of this fork's restore (#1722), when it has one. */
7375
7732
  let restore;
7376
7733
  /** #2009: the directory's classification of the row below, which every restore of it carries. */
7377
7734
  const markCopyOfRow = () => {
@@ -7410,7 +7767,7 @@ export function createControlPlaneApi(options) {
7410
7767
  // pushes a fresh version per try) — #559 (2).
7411
7768
  // #2009: a load classifies nothing by itself, so the restore carries the directory's
7412
7769
  // classification of the row below, as every restore onto a non-primary scope does.
7413
- restore = () => target.restoreScope(tenantId, previewId, tables, { sourceScopeId: source.id, exact: true, ...markCopyOfRow() });
7770
+ restore = (fenced) => target.restoreScope(tenantId, previewId, tables, { sourceScopeId: source.id, exact: true, ...markCopyOfRow(), ...fenced });
7414
7771
  }
7415
7772
  else {
7416
7773
  // A clean-room preview (#509 (b)): an EMPTY scope, no source to export. No `forkedFrom`
@@ -7429,19 +7786,49 @@ export function createControlPlaneApi(options) {
7429
7786
  expiresAt: expiresAt ?? undefined,
7430
7787
  };
7431
7788
  // #2009: marked a copy on the directory's word, as the fork above.
7432
- restore = target ? () => target.restoreScope(tenantId, previewId, [], markCopyOfRow()) : null;
7789
+ restore = target ? (fenced) => target.restoreScope(tenantId, previewId, [], { ...markCopyOfRow(), ...fenced }) : null;
7433
7790
  }
7791
+ // #1722: the PR version's script, named in the ledger before the restore writes into it.
7792
+ // Nothing routes the new row there until the bind, so without the entry a failure between
7793
+ // the two leaves a fork of the source's data that reap and erasure never reach.
7794
+ const targetRef = restore && options.resolveVerticalRef
7795
+ ? ((await c.var.admin.getVersion(actor, opts.versionId, slug))?.deploymentRef ?? null)
7796
+ : null;
7797
+ let fork = null;
7434
7798
  try {
7435
7799
  // Inside the try: a host writes the directory row FIRST and then migrates, projects and
7436
7800
  // seats, so a provision that throws can leave a `provisioning` row too. A provision
7437
7801
  // that never wrote one (the tag's slug taken by a racing create) marks nothing: the
7438
7802
  // write below targets this create's own id, which does not exist, and is swallowed.
7439
7803
  await c.var.host.provisionScope(actor, row);
7440
- if (restore)
7441
- await restoreOrRecord(restore);
7804
+ if (restore) {
7805
+ let fenced = {};
7806
+ if (targetRef) {
7807
+ const moveId = ulid();
7808
+ const restoredStamp = ulid();
7809
+ const recordedAt = Date.now();
7810
+ await c.var.admin.recordScopeScriptCopy(actor, tenantId, previewId, targetRef, moveId, { role: 'destination', loadStamp: restoredStamp, leaseMs: copyLeaseMs });
7811
+ fork = { moveId };
7812
+ const erasureEpoch = await c.var.admin.scopeErasureEpoch(actor, tenantId, previewId);
7813
+ fenced = { loadStamp: restoredStamp, fence: copyRestoreFence(moveId, recordedAt, copyLeaseMs, erasureEpoch) };
7814
+ }
7815
+ const load = restore;
7816
+ await restoreOrRecord(() => load(fenced));
7817
+ }
7442
7818
  await c.var.admin.activateScope(actor, tenantId, previewId);
7819
+ // Bind the PR version. A private vertical's push self-admitted, so this is accepted; a
7820
+ // preview scope also admits a pending version (#513), which is what a clean-room rehearsal
7821
+ // of not-yet-admitted code needs. It routes the row onto the fork, so it confirms the move.
7822
+ await c.var.admin.bindScopeVersion(actor, tenantId, previewId, opts.versionId, fork ? { confirmMove: { moveId: fork.moveId, source: 'retained' } } : undefined);
7443
7823
  }
7444
7824
  catch (e) {
7825
+ // The fork stays named for reap and erasure; if this request had died instead, the sweep
7826
+ // would settle the entry once its lease ran out.
7827
+ const unbound = fork;
7828
+ if (unbound && targetRef) {
7829
+ await c.var.admin.settleScopeScriptCopy(actor, tenantId, previewId, targetRef, unbound.moveId, 'retained')
7830
+ .catch(() => undefined);
7831
+ }
7445
7832
  // Expire the row this create left behind, so the next create reaps it at once rather
7446
7833
  // than refusing it as in flight for the whole bound (#1920) — that next create is the
7447
7834
  // CLI's retry after a known-dead attempt (#1918). The row stays until then, or until
@@ -7452,10 +7839,6 @@ export function createControlPlaneApi(options) {
7452
7839
  .catch(() => undefined);
7453
7840
  throw e;
7454
7841
  }
7455
- // Bind the PR version. A private vertical's push self-admitted, so this is accepted; a
7456
- // preview scope also admits a pending version (#513), which is what a clean-room rehearsal
7457
- // of not-yet-admitted code needs.
7458
- await c.var.admin.bindScopeVersion(actor, tenantId, previewId, opts.versionId);
7459
7842
  const hostname = await bindPreviewHostname(c.var.admin, actor, baseHostname, tenantId, previewId, opts.tag, surface);
7460
7843
  await assertServesBoundVersion(previewId);
7461
7844
  const auth = await wireLogin(previewId, hostname, source);
@@ -7571,8 +7954,8 @@ export function createControlPlaneApi(options) {
7571
7954
  // Storage-before-row, the same ordering as the fork hard-delete: wipe the DO in the
7572
7955
  // PR version's deployment, then deleteSnapshot (fork-only re-check, hostnames + row,
7573
7956
  // audit). A crash between the two converges on retry.
7574
- await reapPreview(c, preview);
7575
- return c.json({ deleted: preview.id });
7957
+ const { storageStranded } = await reapPreview(c, preview);
7958
+ return c.json({ deleted: preview.id, ...(storageStranded ? { storageStranded: true } : {}) });
7576
7959
  }
7577
7960
  catch (e) {
7578
7961
  if (e instanceof ControlPlaneError)