@substrat-run/control-plane-api 0.200.0 → 0.202.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,4 +1,4 @@
1
- import { sourceBuildRequest } from '@substrat-run/contracts';
1
+ import { addDecimal, sourceBuildRequest } from '@substrat-run/contracts';
2
2
  import { SourceBuildInterrupted } from './source-builds.js';
3
3
  import { PREVIEW_CONNECTIONS_REFUSAL } from './connection-relay.js';
4
4
  import { bindingChangeRefusal, bindingOptionsRefusal, connectionBindingOptions, refusesBindingChange } from './connection-binding-options.js';
@@ -6,15 +6,17 @@ import { resolveObservabilityWindow } from './observability-window.js';
6
6
  import { Hono } from 'hono';
7
7
  import { permissionKey, parseHostname, withLabel, RESERVED_LABEL_SEPARATOR, adminAction, lakeEventsInput, ownerTransferInput, memberInviteInput, memberRoleInput, ASSET_PART_PREFIX, assetHash, STORE_DRIVERS, storeDriverErasesSubjects, storeDriverServesVertical, storeCatalogOperation, storeDriverBasisAdmits, 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, connectionSendTest, connectionSendTestResult, connectionSenders, createTenantInput, entitlementGrantInput, hostname as hostnameSchema, hostnameRegion, hostnameStatus, identityLink, errorCode, issueStatus, issueStatusInput, FINDINGS_LIMIT_DEFAULT, FINDINGS_LIMIT_MAX, findingCursorOf, findingKind, findingRuleInput, findingStatus, findingStatusInput, listPageQuery, matchesOutboundHost, pageOf, platformRequestFilter, principalId as principalIdSchema, impersonationStamp, promotionAcknowledgement, bindAcknowledgement, rebindAcknowledgement, provisionableJurisdiction, publishVersionInput, queryScopeInput, readScopeTableInput, entityHistoryInput, eventFacetInput, eventCauseInput, eventEffectsInput, invocationEventsInput, deadLettersInput, lifecycleFlowInput, operationSeriesCount, operationSeriesInput, delegatedReadParams, createOrgInput, roleKey as roleKeySchema, peerSwitch, verticalSlug, scopeText, systemSwitch, DEFAULT_DENIAL_LIMIT, DENIAL_LIMIT_MAX, denialGroupBy, registerVerticalInput, platformScriptCollision, platformScriptRefusal, PLATFORM_SCRIPT_NAMES, serviceDimensions, sweepRunKind, sweepRunOutcome, scopeDump, mergeDumpPages, dataSubjectId as dataSubjectIdSchema, scopeId as scopeIdSchema, scopeStatus, requestRollupReading, meterDaysReading, verticalOwnersReading, utcDay, storageShape, surfaceName, modelUsageLine, tenantId as tenantIdSchema, tenantStatus, versionOrigin, z, PROBLEM_CONTENT_TYPE, toProblem, validationIssuesFrom, redrainEventsInput, importCursorMove, importCursorAcknowledgementMissing, REDRAIN_BATCH, migrationsOnTop, substratError, errorCodeOf, envVarSpec, capabilityFilterQuery, capabilityId as capabilityIdSchema, PLATFORM_FEATURES_HEADER, PLATFORM_FEATURE_SCOPE_SWEEPER, PLATFORM_FEATURE_SOURCE_BUILDS, SOCIAL_RELAY_VERTICALS, isVerticalConnectorProvider, previewTag, buildPreviewTagPrefix, } from '@substrat-run/contracts';
8
8
  import { upstreamHandleIn, upstreamReferenceOf, withUpstreamReference } from '@substrat-run/contracts';
9
+ import { mailInAddressAct, mailInStanding } from '@substrat-run/contracts';
9
10
  import { ENGINE_ENTITLEMENT_KEYS, bareSlug, declarableEntitlementKey, entitlementNamespaceRefusal, grantableEntitlements } from '@substrat-run/contracts';
10
11
  import { SCOPE_COPY_LEASE_MS, copyRestoreFence, publishedMigrationDigest, replayStoreErasures, storesFencedRefusal } from '@substrat-run/kernel';
11
12
  import { attributeFailure } from './failure-attribution.js';
12
13
  import { auditedChange, withAuditedOutcomes } from './audited-change.js';
13
- import { BIND_EXPORT_BREAK_REFUSAL, CARRIED_AWAY_KEY, bindExportBreakRefusal, carriedAwayDump, dumpMetaValue, metaValueIn, crossVerticalHealth, exportBreakRefusal, isBindExportBreakRefusal, isExportBreakRefusal, listedPromoteRefusal, isExportBreakUnjudged, isPrimaryScope, promoteReviewDigest, rebindReviewDigest, assertRebindReviewCurrent, migrationProgress, ulid, auditWarningOf, REQUEST_ROLLUP_LIMIT_DEFAULT, REQUEST_ROLLUP_LIMIT_MAX, STORAGE_HISTORY_LIMIT_MAX, STORAGE_GAUGE_RETENTION_MONTHS, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, BILLING_ROLLUP_RETENTION_MONTHS, METER_DAYS_LIMIT_DEFAULT, METER_DAYS_LIMIT_MAX, releaseRolesAskScopes, releaseRoleSetRefusal, withheldOpsFailure, } from '@substrat-run/kernel';
14
+ import { BIND_EXPORT_BREAK_REFUSAL, CARRIED_AWAY_KEY, bindExportBreakRefusal, dumpMetaValue, metaValueIn, crossVerticalHealth, exportBreakRefusal, isBindExportBreakRefusal, isExportBreakRefusal, listedPromoteRefusal, isExportBreakUnjudged, isPrimaryScope, promoteReviewDigest, rebindReviewDigest, assertRebindReviewCurrent, migrationProgress, ulid, auditWarningOf, REQUEST_ROLLUP_LIMIT_DEFAULT, REQUEST_ROLLUP_LIMIT_MAX, STORAGE_HISTORY_LIMIT_MAX, STORAGE_GAUGE_RETENTION_MONTHS, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, BILLING_ROLLUP_RETENTION_MONTHS, METER_DAYS_LIMIT_DEFAULT, METER_DAYS_LIMIT_MAX, releaseRolesAskScopes, releaseRoleSetRefusal, withheldOpsFailure, foldModelUsage, } from '@substrat-run/kernel';
14
15
  import { TENANT_HEADER, confinedTenant } from './auth.js';
15
16
  import { mintTenantToken } from './tenant-token.js';
16
17
  import { issuerOnlyConfigKeyOf } from './issuer-config.js';
17
18
  import { COPY_MAX_BYTES, abandonCopy, beginTransfer, connectionGrantsForScope, transferScope, isScopeNotHeld, notHeldIsBenign } from './vertical-client.js';
19
+ import { ManagedSignInIncomplete, removeManagedSignIn, unlistManagedTenant } from './managed-sign-in.js';
18
20
  import { COPY_JOB_MAX_MS, copyJobAt, copyJobHeld, copyJobId, copyJobLive, copyTagId, versionIdOfOrder, versionOrderOf, } from './copy-job.js';
19
21
  import { exportStoreDumps, runningVersionOf, runningVersionStoresOf, scopeStoreReachOf, scopeStoresOf, unrouteScope } from './platform-scope-stores.js';
20
22
  import { liveApprovalOf } from './store-script.js';
@@ -742,6 +744,11 @@ const modelUsageSummaryQuery = z.object({
742
744
  until: z.string().optional(),
743
745
  });
744
746
  export const DEFAULT_MODEL_MARGIN_PERCENT = 20;
747
+ /**
748
+ * The most review lines one tenant's metered-usage read folds. A tenant's reviews are capped far
749
+ * below it at intake (50 kept in 30 days), so reaching it marks the figure a lower bound.
750
+ */
751
+ export const REVIEW_USAGE_READ_MAX = 500;
745
752
  const TENANT_ROUTES = [
746
753
  { method: 'GET', re: /\/verticals\/[^/]+\/email-sender$/, pin: 'owner' },
747
754
  { method: 'POST', re: /\/verticals\/[^/]+\/email-sender$/, pin: 'owner' },
@@ -772,6 +779,9 @@ const TENANT_ROUTES = [
772
779
  // #2343: a mail connection's test send. The dashboard sends it only to the signed-in person.
773
780
  { method: 'POST', re: /\/tenants\/[^/]+\/connections\/[^/]+\/send-test$/, pin: 'path' },
774
781
  { method: 'GET', re: /\/tenants\/[^/]+\/connections\/[^/]+\/senders$/, pin: 'path' },
782
+ // #2611: one app's mail-in address — read it, and request, rotate or revoke it.
783
+ { method: 'GET', re: /\/tenants\/[^/]+\/scopes\/[^/]+\/mail-in$/, pin: 'path' },
784
+ { method: 'POST', re: /\/tenants\/[^/]+\/scopes\/[^/]+\/mail-in$/, pin: 'path' },
775
785
  // A vertical's mailed connect links (connections.md §3.5.4): the consent landing's liveness
776
786
  // read, the callback's spend and its undo, and the integrations card's list and revoke.
777
787
  { method: 'GET', re: /\/tenants\/[^/]+\/connect-links$/, pin: 'path' },
@@ -1770,6 +1780,21 @@ export function createControlPlaneApi(options) {
1770
1780
  // under the tenant. The blast radius is the console's to show; the audit row
1771
1781
  // is this layer's to guarantee.
1772
1782
  await c.var.admin.setTenantStatus(c.get('actor'), tenantId, status);
1783
+ // #3261, D-72: a managed tenant entering `deleting` is taken off its manager's auth-servers'
1784
+ // account pages, so nobody's list shows a business being deleted. After the transition, so
1785
+ // the containment never waits on an auth-server; a failure is answered rather than hidden,
1786
+ // and the reap removes the place again.
1787
+ if (status === 'deleting') {
1788
+ try {
1789
+ await unlistManagedTenant(managedSignInDeps(c), tenantId);
1790
+ }
1791
+ catch (e) {
1792
+ if (!(e instanceof ManagedSignInIncomplete))
1793
+ throw e;
1794
+ return refuseStatus(c, 502, `tenant ${tenantId} is deleting, but its place may still be listed at its manager's auth-server — ` +
1795
+ 'repeat this request to retry; reaping the tenant removes it too', { reason: e.message });
1796
+ }
1797
+ }
1773
1798
  return c.json(await c.var.admin.getTenant(c.get('actor'), tenantId));
1774
1799
  });
1775
1800
  // Reap a DELETING tenant now (control-plane.md §4.8) — the staff "reap now" that skips
@@ -1791,6 +1816,8 @@ export function createControlPlaneApi(options) {
1791
1816
  if (tenant.status !== 'deleting') {
1792
1817
  return refuse(c, 'conflict', `tenant ${tenantId} is ${tenant.status}, not deleting — only a deleting tenant may be reaped`);
1793
1818
  }
1819
+ // #3261, D-72: a managed tenant's client and place at its manager's auth-servers go BEFORE
1820
+ // anything is wiped, so a failure leaves the tenant whole and the reap is simply retried.
1794
1821
  try {
1795
1822
  for (const scope of await c.var.admin.listScopes(actor, { tenantId })) {
1796
1823
  if (scope.status === 'reaped')
@@ -1811,7 +1838,12 @@ export function createControlPlaneApi(options) {
1811
1838
  const vertical = await verticalForScope(c, scope);
1812
1839
  // Archived above, so the router no longer serves it (`READ_ROUTE_SQL` wants an active scope of
1813
1840
  // an active tenant), and reapScope below releases its names.
1814
- await (await platformStoresFence(c, scope, { outlives: true, whileTenantDeleting: true }))();
1841
+ const fenceStores = await platformStoresFence(c, scope, { outlives: true, whileTenantDeleting: true });
1842
+ // #3261, D-72: past the backup and the stores' preflight, which touch nothing, and before
1843
+ // the fence and the wipe, so an auth-server that cannot be reached stops the reap here.
1844
+ // The mark commits the reap first, so no un-delete can land while the client is deleted.
1845
+ await removeManagedSignIn(managedSignInDeps(c), tenantId, scope.id, () => c.var.admin.markScopeStoresFenced(actor, tenantId, scope.id, { whileTenantDeleting: true }));
1846
+ await fenceStores();
1815
1847
  if (vertical)
1816
1848
  await vertical.deleteScope({ tenantId, scopeId: scope.id });
1817
1849
  // Tenant teardown reaps every scope and releases every name by design — force past
@@ -1825,6 +1857,8 @@ export function createControlPlaneApi(options) {
1825
1857
  return c.json(await c.var.admin.getTenant(actor, tenantId));
1826
1858
  }
1827
1859
  catch (e) {
1860
+ if (e instanceof ManagedSignInIncomplete)
1861
+ return refuseStatus(c, 502, ...notReapedForSignIn(e));
1828
1862
  if (e instanceof ControlPlaneError) {
1829
1863
  return relayRefusal(c, e);
1830
1864
  }
@@ -2002,6 +2036,43 @@ export function createControlPlaneApi(options) {
2002
2036
  if (rows.length < STORAGE_HISTORY_LIMIT_MAX)
2003
2037
  storageDays = { rows };
2004
2038
  }
2039
+ // The tenant's code reviews, priced (#2365): the one figure on this read with a price, because
2040
+ // a review is metered to the tenant and the tenant sees what it would cost before it is
2041
+ // charged. The lines are the tenant's own in the review scope, folded as the ledger bills.
2042
+ let reviews;
2043
+ if (options.reviewUsage) {
2044
+ const window = { since: `${since}T00:00:00Z`, until: `${until}T00:00:00Z` };
2045
+ const zeroRated = options.reviewUsage.zeroRated;
2046
+ reviews = { state: 'unavailable', calls: null, reportedCalls: 0, inputTokens: null, outputTokens: null, unpriced: 0, wouldCostUsd: null, chargedUsd: null, zeroRated, lowerBound: false, ...window };
2047
+ if (usageNow() < deadline) {
2048
+ // The ledger compares `at` as text, and a line's `at` carries milliseconds, so the bounds do
2049
+ // too: `T00:00:00Z` sorts after `T00:00:00.500Z` and would drop the first second of the window.
2050
+ const lines = await admin.listModelUsage(actor, {
2051
+ tenantId, scopeId: options.reviewUsage.scope, since: `${since}T00:00:00.000Z`, until: `${until}T00:00:00.000Z`,
2052
+ limit: REVIEW_USAGE_READ_MAX + 1, order: 'asc',
2053
+ });
2054
+ const kept = lines.slice(0, REVIEW_USAGE_READ_MAX);
2055
+ const clipped = lines.length > REVIEW_USAGE_READ_MAX;
2056
+ const folded = foldModelUsage(kept, {
2057
+ readAt, ...window, marginPercent: options.modelMarginPercent ?? DEFAULT_MODEL_MARGIN_PERCENT,
2058
+ ...(zeroRated ? { zeroRatedScopes: [options.reviewUsage.scope] } : {}),
2059
+ }).totals;
2060
+ const reported = kept.filter((line) => line.reported);
2061
+ reviews = {
2062
+ ...reviews,
2063
+ state: kept.length === 0 ? 'empty' : clipped ? 'truncated' : 'complete',
2064
+ calls: kept.length > 0 ? kept.length : null,
2065
+ reportedCalls: reported.length,
2066
+ inputTokens: reported.length > 0 ? folded.inputTokens : null,
2067
+ outputTokens: reported.length > 0 ? folded.outputTokens : null,
2068
+ unpriced: folded.unpriced,
2069
+ // What they would cost at the platform's rate, and what of that is charged: nothing while zero-rated.
2070
+ wouldCostUsd: kept.length > 0 ? addDecimal(folded.billedUsd, folded.zeroRatedUsd) : null,
2071
+ chargedUsd: kept.length > 0 ? folded.billedUsd : null,
2072
+ lowerBound: clipped,
2073
+ };
2074
+ }
2075
+ }
2005
2076
  const hasModelLedger = typeof admin.listTenantModelUsageMeter === 'function' && !modelSkipped;
2006
2077
  let builds = { state: 'unavailable', builds: null, ms: null, lowerBound: false, since: `${since}T00:00:00Z`, until: `${until}T00:00:00Z`, byVertical: [], breakdownTruncated: false };
2007
2078
  if (usageNow() < deadline) {
@@ -2025,6 +2096,7 @@ export function createControlPlaneApi(options) {
2025
2096
  requests,
2026
2097
  models,
2027
2098
  builds,
2099
+ ...(reviews ? { reviews } : {}),
2028
2100
  days: usageDays(utcDaysBetween(since, through), {
2029
2101
  requests: requestDays,
2030
2102
  models: hasModelLedger ? { rows: modelDayRows, truncated } : null,
@@ -2857,6 +2929,66 @@ export function createControlPlaneApi(options) {
2857
2929
  }));
2858
2930
  }
2859
2931
  });
2932
+ /**
2933
+ * **One app's mail-in address** (#2611): its standing, and the three acts on it. The caller has
2934
+ * already made its own in-scope check (the dashboard's `dashboard/begin-connection`) and names
2935
+ * the principal it was for as `createdBy`; the tenant is the path's. Not an admin-log mutation
2936
+ * of its own: the address's connection is created, granted and revoked through `HostAdmin`,
2937
+ * which logs each. Who asked is on the request record, beside the connection's `createdBy`.
2938
+ */
2939
+ const mailInScope = (c) => ({
2940
+ tenantId: tenantIdSchema.parse(c.req.param('tenantId')),
2941
+ scopeId: scopeIdSchema.parse(c.req.param('scopeId')),
2942
+ });
2943
+ const mailInRefusal = (c, e) => {
2944
+ const status = e?.status;
2945
+ if (typeof status !== 'number' || status >= 500 || !(e instanceof Error))
2946
+ return undefined;
2947
+ const code = e.code;
2948
+ return code ? refuse(c, code, e.message) : refuseStatus(c, status, e.message);
2949
+ };
2950
+ app.get('/tenants/:tenantId/scopes/:scopeId/mail-in', async (c) => {
2951
+ const door = options.mailIn;
2952
+ if (!door)
2953
+ return refuseStatus(c, 501, 'inbound mail is not wired on this deployment');
2954
+ try {
2955
+ return c.json(mailInStanding.parse(await door.standing(c.var.host, mailInScope(c))));
2956
+ }
2957
+ catch (e) {
2958
+ const refused = mailInRefusal(c, e);
2959
+ if (refused)
2960
+ return refused;
2961
+ throw e;
2962
+ }
2963
+ });
2964
+ app.post('/tenants/:tenantId/scopes/:scopeId/mail-in', async (c) => {
2965
+ const door = options.mailIn;
2966
+ if (!door)
2967
+ return refuseStatus(c, 501, 'inbound mail is not wired on this deployment');
2968
+ const body = mailInAddressAct.safeParse(await c.req.json().catch(() => null));
2969
+ if (!body.success) {
2970
+ const first = body.error.issues[0];
2971
+ return refuse(c, 'validation_failed', `invalid mail-in act: ${first ? `${first.path.join('.') || '(root)'} — ${first.message}` : 'malformed body'}`);
2972
+ }
2973
+ const scope = mailInScope(c);
2974
+ const principal = c.get('principal');
2975
+ console.log('mail-in.address', {
2976
+ tenantId: scope.tenantId,
2977
+ scopeId: scope.scopeId,
2978
+ action: body.data.action,
2979
+ actor: c.get('actor'),
2980
+ onBehalfOf: principal.kind === 'tenant' ? (principal.onBehalfOf?.principal ?? null) : null,
2981
+ });
2982
+ try {
2983
+ return c.json({ address: await door.act(c.var.host, scope, body.data) });
2984
+ }
2985
+ catch (e) {
2986
+ const refused = mailInRefusal(c, e);
2987
+ if (refused)
2988
+ return refused;
2989
+ throw e;
2990
+ }
2991
+ });
2860
2992
  /**
2861
2993
  * **What the connection has done** (#605) — the connector's dispatch ledger, projected.
2862
2994
  *
@@ -3035,6 +3167,14 @@ export function createControlPlaneApi(options) {
3035
3167
  open: (items) => c.var.admin.openSubjectPayloads(c.get('actor'), tenantId, scopeId, items),
3036
3168
  });
3037
3169
  const verticalForScope = async (c, scope) => (await deploymentForScope(c, scope))?.client;
3170
+ /** What `managed-sign-in.ts` needs, for this request (#3261). */
3171
+ const managedSignInDeps = (c) => ({
3172
+ admin: c.var.admin,
3173
+ actor: c.get('actor'),
3174
+ resolveVerticalForScope: (scope) => verticalForScope(c, scope),
3175
+ });
3176
+ /** The refusal of a reap whose managed sign-in could not be removed (#3261): nothing was wiped. */
3177
+ const notReapedForSignIn = (e) => ["not reaped — the managed tenant's sign-in could not be removed at its manager's auth-server, and nothing more was wiped; retry", { reason: e.message }];
3038
3178
  /**
3039
3179
  * Reconcile one install's client at the social relay (#1544). Skips — never throws for — an
3040
3180
  * install the relay is not for: not configured here, not an Auth Server, or no deployment to
@@ -3916,20 +4056,23 @@ export function createControlPlaneApi(options) {
3916
4056
  }
3917
4057
  };
3918
4058
  /**
3919
- * Wipe one copy of a scope that no route reaches (#1722), without reaping it. Fenced where the
3920
- * deployment can fence it: the wipe runs only if nothing was loaded into that DO since
3921
- * `expectLoadStamp`, compared inside the wipe's own transaction, and `false` means something
3922
- * was (a rollback restored there), so the copy stays. A deployment built before the fence
3923
- * answers `'unfenced'`, and the wipe is then an unconditional load of the tombstone through
3924
- * the restore verb every deployment has. The caller re-reads the route first; that re-read is
3925
- * all that guards an unfenced wipe.
4059
+ * Wipe one copy of a scope that no route reaches (#1722), without reaping it. Fenced: the wipe
4060
+ * runs only if nothing was loaded into that DO since `expectLoadStamp`, compared inside the
4061
+ * wipe's own transaction; `'refused'` means something was (a rollback restored there), so the
4062
+ * copy stays.
4063
+ *
4064
+ * A deployment built before the fence answers `'unfenced'`, and then nothing is wiped: the caller
4065
+ * leaves the copy `retained`, reached by reap and erasure, as the sweep and crash recovery
4066
+ * already do (#3230). A wipe there could only be an unconditional load of the tombstone, and a
4067
+ * rollback can make that script live again between the route read that decides the wipe and
4068
+ * the load landing. That is how a push and a rollback across a pre-fence script lost both copies.
3926
4069
  */
3927
4070
  const wipeCarriedCopy = async (holder, scope, expect, carriedTo,
3928
4071
  /** The scope was read routing elsewhere: a copy changed in any way since is kept (#1722 r8). */
3929
4072
  protectIfChanged = false) => {
3930
4073
  const at = new Date().toISOString();
3931
4074
  // #2005 (Codex #2008 r10): the directory's word that the scope is not primary goes with the
3932
- // wipe, on both paths, so a copy made before the marker leaves it marked — tombstoned or kept.
4075
+ // wipe, so a copy made before the marker leaves it marked — tombstoned or kept.
3933
4076
  const markCopy = copyLineageOf(scope);
3934
4077
  const fenced = await retryTransient(() => holder.wipeCarriedCopy({
3935
4078
  scopeId: scope.id,
@@ -3940,15 +4083,9 @@ export function createControlPlaneApi(options) {
3940
4083
  at,
3941
4084
  ...(markCopy ? { markCopy } : {}),
3942
4085
  }));
3943
- if (fenced !== 'unfenced')
3944
- return fenced.wiped;
3945
- await retryTransient(() => holder.restoreScope(scope.tenantId, scope.id, carriedAwayDump({ to: carriedTo, at }), {
3946
- sourceScopeId: scope.id,
3947
- exact: true,
3948
- // #2005: as every restore onto a non-primary scope, so the wiped copy stays a copy.
3949
- ...(markCopy ? { markCopy } : {}),
3950
- }));
3951
- return true;
4086
+ if (fenced === 'unfenced')
4087
+ return 'unfenced';
4088
+ return fenced.wiped ? 'wiped' : 'refused';
3952
4089
  };
3953
4090
  /**
3954
4091
  * Where the scope routes now, read again after a carry's bind (null for a scope gone from the
@@ -4093,17 +4230,26 @@ export function createControlPlaneApi(options) {
4093
4230
  /**
4094
4231
  * The copy a carry restored for a bind that did not land, wiped unless the scope routes to
4095
4232
  * that script now. Best effort: it never throws, and a failure is recorded.
4233
+ *
4234
+ * `bound`: the bind DID land, and the route has moved off this carry's destination since (#3230).
4235
+ * That store was live, so whatever moved the route away from it carried out of it, and wipes it
4236
+ * under its own fence once its destination is known to hold the data. This carry leaves it alone:
4237
+ * its own wipe, fenced only on its own load stamp (an export is a read and moves no stamp), would
4238
+ * pass while that mover is still reading the store, a tombstone re-carry included.
4096
4239
  */
4097
- const dropUnboundCopy = async (c, scope, versionId, carried) => {
4240
+ const dropUnboundCopy = async (c, scope, versionId, carried, opts = {}) => {
4098
4241
  let route = null;
4099
4242
  try {
4100
4243
  route = await currentRoute(c, scope, versionId, carried);
4101
- if (route === carried.to) {
4244
+ if (route === carried.to || opts.bound) {
4245
+ // The bind settled this entry `done` already; a destination the route reached is the
4246
+ // concern of the move that left it, which names it as its own source.
4102
4247
  await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, 'done');
4103
4248
  return;
4104
4249
  }
4105
4250
  const wiped = await wipeCarriedCopy(carried.dest, scope, { loadStamp: carried.restoredStamp }, route ?? carried.from);
4106
- await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, wiped ? 'done' : 'retained');
4251
+ // Refused (a load since) or pre-fence (#3230): the copy stays, named for reap and erasure.
4252
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.to, carried.moveId, wiped === 'wiped' ? 'done' : 'retained');
4107
4253
  }
4108
4254
  catch (e) {
4109
4255
  recordCarryCleanup(c, scope, versionId, 'unbound-copy', e);
@@ -4193,10 +4339,17 @@ export function createControlPlaneApi(options) {
4193
4339
  // The caller read the route elsewhere, so a copy that changed in any way since the export (a
4194
4340
  // load as much as a write: a staff restore-forward into it racing this carry, Codex #2008 r8)
4195
4341
  // is kept in the store rather than left an unmarked orphan.
4196
- if (await wipeCarriedCopy(carried.source, scope, expect, carried.to, true)) {
4342
+ const wiped = await wipeCarriedCopy(carried.source, scope, expect, carried.to, true);
4343
+ if (wiped === 'wiped') {
4197
4344
  await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, 'done', expect);
4198
4345
  return;
4199
4346
  }
4347
+ if (wiped === 'unfenced') {
4348
+ // A script built before the fence is never wiped (#3230): its copy stays, reached by reap
4349
+ // and erasure, so a rollback onto it can never meet a wipe that this carry decided earlier.
4350
+ await c.var.admin.settleScopeScriptCopy(c.get('actor'), scope.tenantId, scope.id, carried.from, carried.moveId, 'retained', expect);
4351
+ return;
4352
+ }
4200
4353
  // A rollback that restored into it since made it the live store again: it is no kept copy, and
4201
4354
  // a marker this refusal set while the rollback had not yet bound comes off.
4202
4355
  const route = await currentRoute(c, scope, versionId, carried);
@@ -4216,15 +4369,15 @@ export function createControlPlaneApi(options) {
4216
4369
  * Wipe the copy a landed carry left in its source script (#1722), once nothing routes there.
4217
4370
  *
4218
4371
  * The route is read again first. A scope that routes to the source again was bound back to it
4219
- * (a rollback that has landed), and its copy stays. A scope that routes to this carry's
4220
- * destination has its store checked for the `carried_away` tombstone first: an unfenced wipe
4221
- * from an earlier carry out of this script can overtake this carry's restore when this carry
4222
- * IS the rollback, and then the source, which nothing has wiped yet, is carried again before
4223
- * it goes. The fenced wipe in a deployment that has it makes the overtaking impossible.
4372
+ * (a rollback that has landed), and its copy stays. A scope that routes elsewhere leaves this
4373
+ * carry's destination to the move that took the route off it (`dropUnboundCopy`, `bound`).
4224
4374
  *
4225
- * Left open, for a script built before the fence only: an unfenced wipe whose request reaches
4226
- * the old script after a rollback's bind and this check, both, still destroys the rollback's
4227
- * restore. Narrow, and recorded here rather than claimed closed.
4375
+ * Every wipe is fenced (#3230): a script built before the fence is never wiped, its copy stays
4376
+ * `retained`. A fenced wipe compares the store's load stamp inside its own transaction, so it
4377
+ * cannot overtake a later restore, and a rollback can never find its destination wiped after it
4378
+ * restored there. The `carried_away` check below is kept for a tombstone that lands anyway: an
4379
+ * unconditional wipe sent by a control plane that predates #3230, during a deploy's overlap. The
4380
+ * source, which nothing has wiped yet, is then carried again before it goes.
4228
4381
  */
4229
4382
  const settleCarriedSource = async (c, scope, versionId, carried) => {
4230
4383
  const actor = c.get('actor');
@@ -4233,13 +4386,13 @@ export function createControlPlaneApi(options) {
4233
4386
  await c.var.admin.settleScopeScriptCopy(actor, scope.tenantId, scope.id, carried.to, carried.moveId, 'done');
4234
4387
  }
4235
4388
  else {
4236
- await dropUnboundCopy(c, scope, versionId, carried);
4389
+ await dropUnboundCopy(c, scope, versionId, carried, { bound: true });
4237
4390
  }
4238
4391
  };
4239
4392
  try {
4240
4393
  const route = await currentRoute(c, scope, versionId, carried);
4241
4394
  if (route !== carried.to) {
4242
- await dropUnboundCopy(c, scope, versionId, carried);
4395
+ await dropUnboundCopy(c, scope, versionId, carried, { bound: true });
4243
4396
  return;
4244
4397
  }
4245
4398
  // The store this carry landed in is live; a kept marker another carry set while racing it
@@ -4249,7 +4402,8 @@ export function createControlPlaneApi(options) {
4249
4402
  if (await isCarriedAway(carried.dest, scope)) {
4250
4403
  // No size gate (#2450): the bind has landed on this store, so refusing the re-carry would
4251
4404
  // leave the scope serving a wiped copy. Its destination predates the fenced wipe (#1722),
4252
- // and so the stage too: it takes the pages merged, the version-skew fallback.
4405
+ // and so the stage too: it takes the pages merged, the version-skew fallback. Its source
4406
+ // is not wiped under it: the carry the rollback overtook leaves that store alone (#3230).
4253
4407
  const { dump, loadStamp: stamp, revision, meta } = await transferScope(carried.source, carried.dest, { from: scope.id }, { retry: retryTransient });
4254
4408
  if (dumpMetaValue(meta, CARRIED_AWAY_KEY) !== null) {
4255
4409
  throw new ControlPlaneError(500, `both copies of scope ${scope.id} hold the carried_away tombstone; nothing was wiped`);
@@ -5480,7 +5634,9 @@ export function createControlPlaneApi(options) {
5480
5634
  * it was before the ledger. Without per-script resolution there is only that deployment, and
5481
5635
  * a ledgered copy the platform cannot reach refuses the reap.
5482
5636
  */
5483
- const reapScopeStorage = async (c, scope, row = { outlives: false }) => {
5637
+ const reapScopeStorage = async (c, scope, row = { outlives: false },
5638
+ /** #3261: also remove a managed tenant's sign-in at its manager's auth-servers (throws `ManagedSignInIncomplete`). */
5639
+ signIn = {}) => {
5484
5640
  const actor = c.get('actor');
5485
5641
  const dispatch = options.resolveVerticalRef;
5486
5642
  // #2285: every refusal that can be decided up front comes before anything is destroyed, the
@@ -5490,6 +5646,13 @@ export function createControlPlaneApi(options) {
5490
5646
  else
5491
5647
  await assertNoUnreachableScopeCopies(c.var.admin, actor, scope.tenantId, scope.id);
5492
5648
  const fenceStores = await platformStoresFence(c, scope, row);
5649
+ // #3261, D-72: past every refusal above, which touch nothing, and before the unroute and the
5650
+ // wipe, so an auth-server that cannot be reached stops the reap with the scope whole, and a
5651
+ // refused reap keeps the client the scope still signs in with.
5652
+ // The mark commits the reap first, so no unarchive can land while the client is deleted.
5653
+ if (signIn.managed) {
5654
+ await removeManagedSignIn(managedSignInDeps(c), scope.tenantId, scope.id, () => c.var.admin.markScopeStoresFenced(actor, scope.tenantId, scope.id));
5655
+ }
5493
5656
  // Stop routing first: that is the fast path, which ends new requests. A call already past the
5494
5657
  // router, or signed and still on its way, is what the fence below is for (D-71). It would
5495
5658
  // otherwise recreate the store object after the wipe, and nothing left could reach it.
@@ -6306,10 +6469,12 @@ export function createControlPlaneApi(options) {
6306
6469
  'retry, or reap with backup=false to accept an unrecoverable wipe', { detail: e instanceof Error ? e.message : String(e) });
6307
6470
  }
6308
6471
  }
6472
+ // #3261, D-72: a managed tenant's scope takes its client and place at its manager's
6473
+ // auth-servers with it, before its bytes go, so a failure leaves the scope as it was.
6309
6474
  try {
6310
6475
  // By this point the backup contract has resolved (a copy landed, or the caller
6311
6476
  // explicitly declined one), so stranding is a bookkeeping fact, not data loss.
6312
- const storageStranded = await reapScopeStorage(c, scope, { outlives: true });
6477
+ const storageStranded = await reapScopeStorage(c, scope, { outlives: true }, { managed: true });
6313
6478
  await c.var.admin.reapScope(actor, tenantId, scopeId, {
6314
6479
  ...(backup ? { backupRef: backupRefOf(backup) } : {}),
6315
6480
  });
@@ -6317,6 +6482,8 @@ export function createControlPlaneApi(options) {
6317
6482
  return c.json({ ...reaped, backup, ...(storageStranded ? { storageStranded: true } : {}) });
6318
6483
  }
6319
6484
  catch (e) {
6485
+ if (e instanceof ManagedSignInIncomplete)
6486
+ return refuseStatus(c, 502, ...notReapedForSignIn(e));
6320
6487
  if (e instanceof ControlPlaneError) {
6321
6488
  return relayRefusal(c, e);
6322
6489
  }
@@ -11930,7 +12097,7 @@ export function createControlPlaneApi(options) {
11930
12097
  const now = new Date();
11931
12098
  const since = q.since ?? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
11932
12099
  const until = q.until ?? now.toISOString();
11933
- const summary = await c.var.admin.summarizeModelUsage(c.get('actor'), { ...(q.tenantId ? { tenantId: q.tenantId } : {}), since, until }, options.modelMarginPercent ?? DEFAULT_MODEL_MARGIN_PERCENT);
12100
+ const summary = await c.var.admin.summarizeModelUsage(c.get('actor'), { ...(q.tenantId ? { tenantId: q.tenantId } : {}), since, until }, options.modelMarginPercent ?? DEFAULT_MODEL_MARGIN_PERCENT, options.reviewUsage?.zeroRated ? { zeroRatedScopes: [options.reviewUsage.scope] } : {});
11934
12101
  return c.json(summary);
11935
12102
  });
11936
12103
  // -- store-driver releases (D-63, #2300) ----------------------------------------