@substrat-run/adapter-cloudflare 0.221.0 → 0.223.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.
Files changed (86) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +251 -67
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +666 -247
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +7 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +12 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/executor-route.d.ts +13 -0
  57. package/dist/executor-route.d.ts.map +1 -0
  58. package/dist/executor-route.js +12 -0
  59. package/dist/executor-route.js.map +1 -0
  60. package/dist/host.d.ts +76 -2
  61. package/dist/host.d.ts.map +1 -1
  62. package/dist/host.js +386 -67
  63. package/dist/host.js.map +1 -1
  64. package/dist/index.d.ts +2 -1
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +1 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/platform-sweeper-do.d.ts +1 -1
  69. package/dist/platform-sweeper-do.js +1 -1
  70. package/dist/scope-do.d.ts +11 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +206 -58
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +22 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +74 -54
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/tenant-due-work-do.d.ts +99 -0
  83. package/dist/tenant-due-work-do.d.ts.map +1 -0
  84. package/dist/tenant-due-work-do.js +149 -0
  85. package/dist/tenant-due-work-do.js.map +1 -0
  86. package/package.json +10 -10
package/dist/scope-do.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { REWIND_REFUSED } from './rewind-refusal.js';
2
+ import { EXECUTOR_ROUTE_NOT_DUE } from './executor-route.js';
2
3
  import { SYSTEM_DOOR_MOVED } from './system-door.js';
3
4
  import { DurableObject } from 'cloudflare:workers';
4
- import { ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CAPTURE_REFUSALS, attachmentRecord, domainEvent, domainEventInput, eventId, instant, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, toWireFailure, grantRefFromProof, principalId, principalBecomeCapabilityInput, principalBindLinkInput, scopeId as scopeIdOf, tenantId as tenantIdOf, platformRequestInput, platformRequestId, MAX_PENDING_PLATFORM_REQUESTS, MAX_PENDING_SWEEP_RUNS, SWEEP_RUNS_KIND, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, listLimitOf, pageOf, countedPageOf, requestFingerprint, substratError, errorCodeOf, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsOf, isRuntimeTable, replayDumpObjects, dumpObjectsAudit, REDRAIN_BATCH, storeOperationKeyOf, } from '@substrat-run/contracts';
5
+ import { PRODUCTION_ENVIRONMENT, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CAPTURE_REFUSALS, attachmentRecord, domainEvent, domainEventInput, eventId, instant, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, toWireFailure, grantRefFromProof, principalId, principalBecomeCapabilityInput, principalBindLinkInput, scopeId as scopeIdOf, tenantId as tenantIdOf, platformRequestInput, platformRequestId, MAX_PENDING_PLATFORM_REQUESTS, MAX_PENDING_SWEEP_RUNS, SWEEP_RUNS_KIND, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, listLimitOf, pageOf, countedPageOf, requestFingerprint, substratError, errorCodeOf, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsOf, isRuntimeTable, replayDumpObjects, dumpObjectsAudit, REDRAIN_BATCH, storeOperationKeyOf, SCOPE_DUE_HOST_KEY, } from '@substrat-run/contracts';
5
6
  import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, ConnectionSealingKeyUnavailableError, noSealingKeyMessage, sealTo, assertReadOnlyQuery, refuseEntitlement, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleErasurePlan, redactSubjectScopeText, assertRowLimit, assertRowOffset, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_LEASE_EXPIRED_NOTE, JOB_STEP_RECORD_SQL, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, grantEntityShapeOnceIn, topUpEntityGrantShapes, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, SCOPE_SEATED_ROLES_SQL, inUnitRoleRefusal, loadedRoleSetRefusedRole, reservedRoleSetRefusedRole, reservedGrantRefusal, reservedRoleRefusal, reservedShapeRefusal, effectiveRoleGrantQuery, switchRecordedOff, switchSystemSchedules, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, PermissionDenied, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, impersonationStampOf, createAtomic, NotSearchable, isSearchIndexTable, countDumpRows, planDumpSample, sampleFilters, sampleGraph, rowCountTable, searchIndexPlans, NotListable, listIndexPlans, moduleMigrations, REGISTERED_MIGRATIONS, registeredMigrationsOf, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations,
6
7
  // #2993 part 3: the scope's type, recorded here and read at wake, decides which modules it runs.
7
- HOME_SCOPE_TYPE, SCOPE_TYPE_META_KEY, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRoleRefusal, scopeTypeRuns, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
8
+ HOME_SCOPE_TYPE, SCOPE_TYPE_META_KEY,
9
+ // #2995: and its parent, recorded here beside it, which the doors of a CP-less host read.
10
+ PARENT_SCOPE_META_KEY, provisionedParent, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRoleRefusal, scopeTypeRuns, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
8
11
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
9
12
  import { replyOf } from './do-reply.js';
10
13
  import { OperationQueue } from './serialization.js';
@@ -24,7 +27,7 @@ import { DELIVERY_HANDOFF_KEY, DELIVERY_MODE_KEY, HANDOFF_ROUNDS, deliveryModeAf
24
27
  import { registerPlatformDeliveryBroker } from './delivery-broker-platform.js';
25
28
  import { advanceMarks, brokerName, handoffQueries, messagesOf, senderDeliveryOf } from '@substrat-run/kernel';
26
29
  import { DELIVERY_HANDOFF_ENV, intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
27
- import { SCOPE_SWEEPER_NAME } from './scope-sweeper-do.js';
30
+ import { SCOPE_SWEEPER_NAME, kickPlatformDrain, runScopeDueWork } from './scope-sweeper-do.js';
28
31
  import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
29
32
  import { CARRIED_AWAY_KEY, COPY_MARK_CLEARED_KEY, KEPT_COPY_REFUSAL, KEPT_DIVERGENT_KEY, LOAD_STAMP_KEY, STORE_LOCAL_META_KEYS, WRITE_REVISION_KEY, carriedAwayDump, isCopyMarkInsert, isWriteStatement, assertSpineTablesBuilt, clearCopyMarker, dumpRowsInsert, isSpineTable, markCopyOrigin, repointScopeGrants, settleCopiedWork, emittedHere, IS_COPY_SQL, CLEAN_ROOM_COPY_SQL, isCopyLoad, isLifecycleWrite, readLifecycle, settleLifecycleAfterLoad, writeLifecycle, spineColumnAdditions } from '@substrat-run/kernel';
30
33
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
@@ -1040,6 +1043,8 @@ options = {}) {
1040
1043
  * fix and a load are the only writers, and both set it here). Undefined until first read.
1041
1044
  */
1042
1045
  scopeTypeHeld;
1046
+ /** #2995: this scope's parent as its store holds it (`null`: none), read once; a load clears it. */
1047
+ scopeParentHeld;
1043
1048
  /**
1044
1049
  * #2430: what a registered module, or a module the class's declared `permissions` lists, declares
1045
1050
  * `holder: 'system'` — the role and grant doors' refusals read it.
@@ -1763,7 +1768,12 @@ options = {}) {
1763
1768
  * `servesTenant`.
1764
1769
  */
1765
1770
  admission(tenantId) {
1766
- return { verdict: this.tenantVerdict(tenantId).verdict, lifecycle: readLifecycle(this.switchSql()) };
1771
+ return {
1772
+ verdict: this.tenantVerdict(tenantId).verdict,
1773
+ lifecycle: readLifecycle(this.switchSql()),
1774
+ type: this.scopeType(),
1775
+ parent: this.scopeParent(),
1776
+ };
1767
1777
  }
1768
1778
  /**
1769
1779
  * #1738 / #2016: this scope's tenant against `tenantId` — the one reading behind the served-here
@@ -3116,21 +3126,27 @@ options = {}) {
3116
3126
  * `takesSchedules` is a pass saying its sweeper can take `runScopeDue` (`ScheduleTick.alarmRunsDue`);
3117
3127
  * it is remembered, and only from then on does the alarm cover the `due: 'event'` schedules, so a
3118
3128
  * scope whose sweeper predates that call never arms for work it would not run.
3129
+ *
3130
+ * `fromPass` is a pass leaving the work to the alarm (`deferrable`), remembered as `passDefers`:
3131
+ * from then on the alarm may run it itself rather than ask the sweeper.
3119
3132
  */
3120
- async armPurgeAlarm(tenantId, scopeId, takesSchedules = false) {
3133
+ async armPurgeAlarm(tenantId, scopeId, takesSchedules = false, fromPass = false) {
3121
3134
  if (!this.dueAlarmApplies() || this.isCopyRead())
3122
3135
  return false;
3123
3136
  const held = (await this.ctx.storage.get(PURGE_ALARM_KEY)) ?? null;
3124
3137
  const schedules = takesSchedules || held?.schedules === true;
3138
+ const samePair = held?.tenantId === tenantId && held.scopeId === scopeId;
3139
+ const defers = fromPass || (samePair && held?.passDefers === true);
3125
3140
  const at = this.dueAtNow(Date.now(), schedules);
3126
3141
  if (at === null && !(takesSchedules && !held?.schedules))
3127
3142
  return false;
3128
- if (!held || held.tenantId !== tenantId || held.scopeId !== scopeId || (schedules && !held.schedules)) {
3143
+ if (!held || !samePair || (schedules && !held.schedules) || (defers && !held.passDefers)) {
3129
3144
  await this.ctx.storage.put(PURGE_ALARM_KEY, {
3130
3145
  tenantId,
3131
3146
  scopeId,
3132
- ...(held?.notBefore !== undefined && held.tenantId === tenantId && held.scopeId === scopeId ? { notBefore: held.notBefore } : {}),
3147
+ ...(held?.notBefore !== undefined && samePair ? { notBefore: held.notBefore } : {}),
3133
3148
  ...(schedules ? { schedules: true } : {}),
3149
+ ...(defers ? { passDefers: true } : {}),
3134
3150
  });
3135
3151
  }
3136
3152
  if (at === null)
@@ -3154,18 +3170,41 @@ options = {}) {
3154
3170
  }
3155
3171
  }
3156
3172
  /**
3157
- * #3540: the due alarm's half of `alarm()`. When something is due by event, the scope asks its
3158
- * sweeper to run it for this scope alone — `runScopeDue` (its purges and its `due: 'event'`
3159
- * schedules) once a pass has said the sweeper takes that call, `runScopePurges` until then — which
3160
- * runs it through the coordinator's door, with every gate a pass applies. Then it re-arms from
3161
- * what its rows say now:
3173
+ * #3540: the vertical's own scope host, to run this scope's due work with: the one its
3174
+ * `mountPlatformSurface` builds its routes with and registers under `SCOPE_DUE_HOST_KEY`, built
3175
+ * from this object's env, which is the script's. Its door holds the tenant pair, the lifecycle,
3176
+ * the kill switch and the rewind hold, and its calls into this scope are calls like any other.
3177
+ * Null when the bundle registers none (a vertical-host older than the key, a self-host wiring its
3178
+ * own) or building it throws: the alarm then asks the sweeper, so the work is never stranded.
3179
+ */
3180
+ dueRunHost() {
3181
+ const hostFor = globalThis[Symbol.for(SCOPE_DUE_HOST_KEY)];
3182
+ if (typeof hostFor !== 'function')
3183
+ return null;
3184
+ try {
3185
+ return hostFor(this.env);
3186
+ }
3187
+ catch (err) {
3188
+ console.error('substrat: the due alarm could not build its host; asking the sweeper instead', err);
3189
+ return null;
3190
+ }
3191
+ }
3192
+ /**
3193
+ * #3540: the due alarm's half of `alarm()`. When something is due by event, the scope runs it for
3194
+ * itself alone — its purges, and its `due: 'event'` schedules once a pass has said its sweeper
3195
+ * takes `runScopeDue` — through the host's door, with every gate a pass applies
3196
+ * (`runScopeDueWork`). Once a pass has said it leaves that work to the alarm (`passDefers`), the
3197
+ * scope runs it with the vertical's own host (`dueRunHost`), and no sweeper is asked; until then,
3198
+ * or when the bundle gives it no host, it asks its sweeper to (`runScopeDue`, or `runScopePurges`
3199
+ * before that call), which runs the same work after its roster check. Then it re-arms from what
3200
+ * its rows say now:
3162
3201
  *
3163
3202
  * - nothing left due (a restore cancelled it, or the run did it): nothing armed;
3164
3203
  * - a purge lap left open by a run that answered: due again at once, since that run made progress;
3165
3204
  * - otherwise never sooner than `PURGE_ALARM_MIN_GAP_MS`, or the shortest cadence when the
3166
3205
  * sweeper could not be asked, so a run that cannot progress cannot spin the alarm;
3167
- * - a run the sweeper held (a lifecycle, a switch, a scope off its roster): not re-armed, and no
3168
- * commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
3206
+ * - a run that was held (a lifecycle, a switch, a scope off the sweeper's roster): not re-armed, and
3207
+ * no commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
3169
3208
  *
3170
3209
  * Never throws: a thrown alarm is retried by the runtime.
3171
3210
  */
@@ -3186,6 +3225,7 @@ options = {}) {
3186
3225
  scopeId: state.scopeId,
3187
3226
  ...(notBefore !== undefined ? { notBefore } : {}),
3188
3227
  ...(schedules ? { schedules: true } : {}),
3228
+ ...(state.passDefers ? { passDefers: true } : {}),
3189
3229
  });
3190
3230
  // Nothing due: only a record that says the sweeper takes `runScopeDue` is worth keeping.
3191
3231
  const settle = async () => {
@@ -3209,10 +3249,22 @@ options = {}) {
3209
3249
  let answer;
3210
3250
  this.#purgeAlarmRunning = true;
3211
3251
  try {
3212
- const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3213
- answer = schedules
3214
- ? await stub.runScopeDue(state.tenantId, state.scopeId)
3215
- : await stub.runScopePurges(state.tenantId, state.scopeId);
3252
+ // Its own run once a pass has said it leaves the work here, so nothing else runs it; the
3253
+ // sweeper's call otherwise, and whenever this bundle gives the scope no host to run it with.
3254
+ const host = state.passDefers === true || schedules ? this.dueRunHost() : null;
3255
+ if (host) {
3256
+ const { tenantId, scopeId } = state;
3257
+ answer = await runScopeDueWork(host, tenantId, scopeId, schedules, {
3258
+ versionId: this.env.SUBSTRAT_VERSION_ID ?? null,
3259
+ kickPlatformDrain: () => this.ctx.waitUntil(kickPlatformDrain(this.env, tenantId, scopeId).catch(() => { })),
3260
+ });
3261
+ }
3262
+ else {
3263
+ const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3264
+ answer = schedules
3265
+ ? await stub.runScopeDue(state.tenantId, state.scopeId)
3266
+ : await stub.runScopePurges(state.tenantId, state.scopeId);
3267
+ }
3216
3268
  }
3217
3269
  catch (err) {
3218
3270
  answer = { error: err instanceof Error ? err.message : String(err) };
@@ -3311,14 +3363,17 @@ options = {}) {
3311
3363
  return;
3312
3364
  }
3313
3365
  let answered;
3366
+ let answeredEnvironment;
3314
3367
  const ran = await runWake(state, Date.now(), () => this.wakeWork(), async (body) => {
3315
3368
  const answer = await kickControlPlane(transport, body);
3316
3369
  answered = answer?.broker;
3370
+ answeredEnvironment = answer?.brokerEnvironment;
3317
3371
  return answer;
3318
3372
  });
3319
- // A5: the delivery mode the control plane holds for this tenant, on the same answer.
3373
+ // A5: the delivery mode the control plane holds for this tenant, on the same answer, and
3374
+ // (#3639) the named environment whose broker it hands off to.
3320
3375
  if (answered)
3321
- await this.applyDeliveryMode(state.tenantId, state.scopeId, answered);
3376
+ await this.applyDeliveryMode(state.tenantId, state.scopeId, answered, answeredEnvironment);
3322
3377
  // The object took other calls while the kick was out: keep what a commit stored meanwhile.
3323
3378
  const next = keepRegisteredMeanwhile(state, ran, (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null);
3324
3379
  if (!next) {
@@ -3334,13 +3389,28 @@ options = {}) {
3334
3389
  console.error('substrat: scope wake failed; the pass is the backstop', err);
3335
3390
  }
3336
3391
  }
3337
- /** K-74: this scope's broker, or null when the script binds none (the broker is off). */
3338
- deliveryBroker(tenantId) {
3392
+ /**
3393
+ * K-74: this scope's broker, or null when the script binds none (the broker is off). #3639
3394
+ * (D-83): its environment's, named by `environment`; production's (`<tenant>/<app>`, as before)
3395
+ * when it names none.
3396
+ */
3397
+ deliveryBroker(tenantId, environment) {
3339
3398
  const ns = this.env.SUBSTRAT_DELIVERY_BROKER;
3340
3399
  if (!ns)
3341
3400
  return null;
3342
3401
  const app = this.env.SUBSTRAT_VERTICAL ?? 'vertical';
3343
- return ns.get(ns.idFromName(brokerName(tenantId, app)));
3402
+ return ns.get(ns.idFromName(brokerName(tenantId, app, environment)));
3403
+ }
3404
+ /**
3405
+ * #3639: the named environment whose broker this scope hands off to, or undefined for
3406
+ * production's: what the control plane last told it (`DELIVERY_MODE_KEY`), else what its last
3407
+ * handoff stored, which outlives the mode going off.
3408
+ */
3409
+ async handoffEnvironment() {
3410
+ const mode = (await this.ctx.storage.get(DELIVERY_MODE_KEY)) ?? null;
3411
+ if (mode)
3412
+ return mode.environment;
3413
+ return ((await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null)?.environment;
3344
3414
  }
3345
3415
  /**
3346
3416
  * K-74: hand off what the scope's commits left, past its marks, and keep the marks the broker
@@ -3356,14 +3426,17 @@ options = {}) {
3356
3426
  async handOffCommitted(tenantId, scopeId,
3357
3427
  /** #3474: the invocation whose commit this follows, and its trace: its own rows carry the trace. */
3358
3428
  commit) {
3359
- const broker = this.deliveryBroker(tenantId);
3360
- if (!broker)
3429
+ if (!this.env.SUBSTRAT_DELIVERY_BROKER)
3361
3430
  return;
3362
3431
  // A5 (#3471): only while the tenant is in shadow or live, and under that mode.
3363
3432
  const options = await this.handoffOptions(tenantId, scopeId);
3364
3433
  if (options === null)
3365
3434
  return;
3435
+ // #3639: to the broker of the scope's environment, which every state this writes keeps.
3436
+ const environment = await this.handoffEnvironment();
3437
+ const broker = this.deliveryBroker(tenantId, environment);
3366
3438
  const ids = { tenantId, scopeId };
3439
+ const kept = { tenantId, scopeId, ...(environment ? { environment } : {}) };
3367
3440
  const stored = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
3368
3441
  let marks = stored?.marks;
3369
3442
  /** #3474: the round now with the broker, so a throw reports what it tried. */
@@ -3388,7 +3461,7 @@ options = {}) {
3388
3461
  break;
3389
3462
  }
3390
3463
  if (!retry) {
3391
- retry = handoffPending(stored, marks, Date.now(), ids);
3464
+ retry = handoffPending(stored, marks, Date.now(), kept);
3392
3465
  await this.keepHandoff(retry);
3393
3466
  await this.armAlarmBy(retry.due);
3394
3467
  }
@@ -3399,7 +3472,7 @@ options = {}) {
3399
3472
  delete options.start;
3400
3473
  }
3401
3474
  const next = advanceMarks(marks, sent, answer);
3402
- this.reportHandoffRound(tenantId, scopeId, inFlight, handoffOutcome(sent, answer));
3475
+ this.reportHandoffRound(tenantId, scopeId, inFlight, handoffOutcome(sent, answer), environment);
3403
3476
  inFlight = null;
3404
3477
  // An answer that acknowledges nothing new: stop, and leave the retry armed.
3405
3478
  if (sameMarks(next, marks))
@@ -3408,19 +3481,19 @@ options = {}) {
3408
3481
  await this.keepHandoff({ ...retry, marks });
3409
3482
  }
3410
3483
  if (drained) {
3411
- await this.keepHandoff({ tenantId, scopeId, marks });
3484
+ await this.keepHandoff({ ...kept, marks });
3412
3485
  return;
3413
3486
  }
3414
3487
  // The round limit, with work left: continue on the first step of the back-off.
3415
- const more = handoffPending(null, marks, Date.now(), ids);
3488
+ const more = handoffPending(null, marks, Date.now(), kept);
3416
3489
  await this.keepHandoff(more);
3417
3490
  await this.armAlarmBy(more.due);
3418
3491
  }
3419
3492
  catch (err) {
3420
3493
  if (inFlight)
3421
- this.reportHandoffRound(tenantId, scopeId, inFlight, 'failed');
3494
+ this.reportHandoffRound(tenantId, scopeId, inFlight, 'failed', environment);
3422
3495
  console.error('substrat: delivery handoff failed; the scope alarm retries it', err);
3423
- const next = handoffAfterFailure(stored, marks, Date.now(), ids);
3496
+ const next = handoffAfterFailure(stored, marks, Date.now(), kept);
3424
3497
  await this.keepHandoff(next);
3425
3498
  await this.armAlarmBy(next.due);
3426
3499
  }
@@ -3463,10 +3536,12 @@ options = {}) {
3463
3536
  * Public for the platform and the suites; a caller in the script can only change which receivers
3464
3537
  * its own next messages are owed, never what the control plane lets the broker drive.
3465
3538
  */
3466
- async applyDeliveryMode(tenantId, scopeId, mode) {
3539
+ async applyDeliveryMode(tenantId, scopeId, mode, environment) {
3467
3540
  await this.ensureMigrations();
3541
+ // #3639: production is named by no environment, whichever way an answer spells it.
3542
+ const named = environment && environment !== PRODUCTION_ENVIRONMENT ? environment : undefined;
3468
3543
  const prior = (await this.ctx.storage.get(DELIVERY_MODE_KEY)) ?? null;
3469
- const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed());
3544
+ const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed(), named);
3470
3545
  if (next === prior)
3471
3546
  return;
3472
3547
  if (!next) {
@@ -3474,7 +3549,7 @@ options = {}) {
3474
3549
  return;
3475
3550
  }
3476
3551
  if (seeded)
3477
- await this.keepHandoff({ tenantId, scopeId, marks: seeded });
3552
+ await this.keepHandoff({ tenantId, scopeId, ...(named ? { environment: named } : {}), marks: seeded });
3478
3553
  await this.ctx.storage.put(DELIVERY_MODE_KEY, next);
3479
3554
  // The window's start reaches the broker with the next handoff; one now, so a quiet scope has one too.
3480
3555
  if (seeded)
@@ -3495,14 +3570,16 @@ options = {}) {
3495
3570
  return intentStateOf(this.sql.exec(q.sql, ...q.params).toArray());
3496
3571
  }
3497
3572
  /** #3474: one point per handoff round, when the script binds `SUBSTRAT_BROKER_TELEMETRY`. */
3498
- reportHandoffRound(tenantId, scopeId, round, outcome) {
3573
+ reportHandoffRound(tenantId, scopeId, round, outcome,
3574
+ /** #3639: the named environment whose broker the round went to; undefined for production's. */
3575
+ environment) {
3499
3576
  if (this.brokerSink === undefined) {
3500
3577
  const dataset = brokerTelemetryDataset(this.env);
3501
3578
  this.brokerSink = dataset ? analyticsBrokerSink(dataset) : null;
3502
3579
  }
3503
3580
  if (!this.brokerSink)
3504
3581
  return;
3505
- reportHandoff(this.brokerSink, { tenantId, app: this.env.SUBSTRAT_VERTICAL ?? 'vertical', scopeId }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
3582
+ reportHandoff(this.brokerSink, { tenantId, app: this.env.SUBSTRAT_VERTICAL ?? 'vertical', ...(environment ? { environment } : {}), scopeId }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
3506
3583
  }
3507
3584
  brokerSink;
3508
3585
  /**
@@ -5410,7 +5487,7 @@ options = {}) {
5410
5487
  // here, so a purge is never run by both. It arms the alarm instead, which is also how a bin
5411
5488
  // filled before the switch was turned on, or an alarm that was lost, comes to be armed.
5412
5489
  if (mode === 'deferrable' && this.purgeDueByEvent()) {
5413
- await this.armPurgeAlarm(tenantId, scopeId);
5490
+ await this.armPurgeAlarm(tenantId, scopeId, false, true);
5414
5491
  return { purged: 0, skipped: 0, errors: [], more: false, lapFailed: 0, byAlarm: true };
5415
5492
  }
5416
5493
  const due = purgeDueOf(doSpineSql(this.sql), this.statePlans, this.operationTarget, operation, schedule.entityType, new Date().toISOString(), PURGE_BATCH);
@@ -5464,7 +5541,7 @@ options = {}) {
5464
5541
  const row = readScheduleDue(doSpineSql(this.sql), due);
5465
5542
  if (mode === 'deferrable' && this.dueByEventSwitched() && !this.isCopyRead()) {
5466
5543
  // The pair is the host's, which has already held it to this scope's record.
5467
- await this.armPurgeAlarm(tenantId, scopeId, true);
5544
+ await this.armPurgeAlarm(tenantId, scopeId, true, true);
5468
5545
  if (row.established)
5469
5546
  return { ...row, byAlarm: true };
5470
5547
  }
@@ -5937,6 +6014,34 @@ options = {}) {
5937
6014
  return type;
5938
6015
  }));
5939
6016
  }
6017
+ /** #2995: this scope's parent, `null` when it has none. Read once; never written but by `fixScopeParentReply`. */
6018
+ scopeParent() {
6019
+ if (this.scopeParentHeld === undefined)
6020
+ this.scopeParentHeld = this.metaValue(PARENT_SCOPE_META_KEY);
6021
+ return this.scopeParentHeld;
6022
+ }
6023
+ /**
6024
+ * #2995 (K-64): fix this scope's parent, at its provision as a child — the hosted half of the pure
6025
+ * host's `scopes.parent_scope_id`, kept in the scope's own `_substrat_meta` beside its type, so a
6026
+ * CP-less host's doors can judge a child with no directory to ask. Fixed once, by the kernel's
6027
+ * `provisionedParent`: a provision restating the link, or naming none, keeps it; one naming another
6028
+ * parent, or a parent for a store already provisioned without one, is `conflict` and writes nothing.
6029
+ * Called after `fixScopeTypeReply` and before anything migrates. Answers the parent held.
6030
+ */
6031
+ async fixScopeParentReply(requested, scopeId) {
6032
+ return replyOf(() => this.queue.enqueue(() => {
6033
+ const held = this.metaValue(PARENT_SCOPE_META_KEY);
6034
+ const recorded = held !== null ? held : this.provisionedFor() !== null || this.holdsData() ? null : undefined;
6035
+ const parent = provisionedParent(requested, recorded, scopeId);
6036
+ if (held === null && parent !== null) {
6037
+ this.revision.transactionSync(() => {
6038
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, PARENT_SCOPE_META_KEY, parent);
6039
+ });
6040
+ }
6041
+ this.scopeParentHeld = parent;
6042
+ return parent;
6043
+ }));
6044
+ }
5940
6045
  /** #2993 part 3: this scope's type, for a host that seats or probes by it. Reads; writes nothing. */
5941
6046
  async scopeTypeHere() {
5942
6047
  return this.scopeType();
@@ -6391,6 +6496,18 @@ options = {}) {
6391
6496
  * is counted over the routed deliveries alone (`MAX_PENDING_CONNECTOR_DISPATCHES`): module
6392
6497
  * intents and `sweep-runs` reports no longer take a delivery's slot, nor it theirs.
6393
6498
  *
6499
+ * #3676: routed once per logical delivery. `pendingExecutorDeliveries` is a read, and more than
6500
+ * one pass can act on the same read — the inline drain after a commit, the router's kick, the
6501
+ * scope's alarm, `routeDueDeliveries`. Each used to insert an intent and bump the journal, so
6502
+ * one event became as many intents as passes reached it, with as many attempts on its journal
6503
+ * row, and a comparison by intent id could not see it. So the decision is made here, in the
6504
+ * transaction that writes: a delivery this scope's journal no longer holds due (routed,
6505
+ * dead-lettered, or waiting out a backoff) answers `'not-due'` and writes nothing. Due is the
6506
+ * read's own predicate — no row, or a next attempt that has come — so a dead letter a person
6507
+ * re-drives (`retryExecutorDelivery`) routes again, and a different `deliveryId` for the same
6508
+ * event routes its own. The due check comes before the room check: a delivery already routed
6509
+ * is not one waiting for room, and must not stop the caller's pass.
6510
+ *
6394
6511
  * `invocationId` is LAST, and defaulted, for the RPC-skew reason `recordExecutorAttempt`
6395
6512
  * states at length.
6396
6513
  */
@@ -6402,31 +6519,52 @@ options = {}) {
6402
6519
  * so leaving it null would make the column read "no call" for the common case.
6403
6520
  */
6404
6521
  invocationId = null) {
6405
- if (this.pendingConnectorDispatches() >= MAX_PENDING_CONNECTOR_DISPATCHES)
6406
- return null;
6407
- const id = platformRequestId.parse(this.mintIntentId());
6408
- // K-42: the intent inherits the SOURCE EVENT's stamp rather than being written
6409
- // unstamped. Nobody is impersonating at this moment — the drain runs long after
6410
- // the session's invoke returned — but the intent exists BECAUSE of an event that
6411
- // was raised under one, and the platform drain is where an operator asks who
6412
- // caused an outbound effect. Read here rather than passed over the RPC: the DO
6413
- // owns the outbox, so a coordinator cannot claim a stamp or drop one.
6414
- const source = this.sql
6415
- .exec('SELECT impersonation, tenant_id, scope_id FROM _substrat_outbox WHERE id = ?', eventId)
6416
- .toArray()[0];
6417
- this.sql.exec(`INSERT INTO _substrat_platform_requests
6418
- (id, kind, payload, requested_by, impersonation, status, attempts, requested_at)
6419
- VALUES (?, ?, ?, ?, ?, 'pending', 0, ?)`, id, kind, payload, requestedBy, source?.impersonation ?? null, instant.parse(new Date().toISOString()));
6420
- this.recordExecutorAttempt(eventId, deliveryId, null, null, invocationId);
6522
+ const now = new Date().toISOString();
6523
+ const routed = this.revision.transactionSync(() => {
6524
+ if (!this.executorDeliveryDue(eventId, deliveryId, now))
6525
+ return EXECUTOR_ROUTE_NOT_DUE;
6526
+ if (this.pendingConnectorDispatches() >= MAX_PENDING_CONNECTOR_DISPATCHES)
6527
+ return null;
6528
+ const id = platformRequestId.parse(this.mintIntentId());
6529
+ // K-42: the intent inherits the SOURCE EVENT's stamp rather than being written
6530
+ // unstamped. Nobody is impersonating at this moment — the drain runs long after
6531
+ // the session's invoke returned — but the intent exists BECAUSE of an event that
6532
+ // was raised under one, and the platform drain is where an operator asks who
6533
+ // caused an outbound effect. Read here rather than passed over the RPC: the DO
6534
+ // owns the outbox, so a coordinator cannot claim a stamp or drop one.
6535
+ const source = this.sql
6536
+ .exec('SELECT impersonation, tenant_id, scope_id FROM _substrat_outbox WHERE id = ?', eventId)
6537
+ .toArray()[0];
6538
+ this.sql.exec(`INSERT INTO _substrat_platform_requests
6539
+ (id, kind, payload, requested_by, impersonation, status, attempts, requested_at)
6540
+ VALUES (?, ?, ?, ?, ?, 'pending', 0, ?)`, id, kind, payload, requestedBy, source?.impersonation ?? null, instant.parse(now));
6541
+ this.recordExecutorAttempt(eventId, deliveryId, null, null, invocationId);
6542
+ return { id, source };
6543
+ });
6544
+ if (routed === null || routed === EXECUTOR_ROUTE_NOT_DUE)
6545
+ return routed;
6546
+ const { id, source } = routed;
6421
6547
  // K-69: this intent is enqueued by the coordinator after the commit's own wake was armed, so
6422
- // it arms one too, under the ids its source event carries. Both writes above are made before
6423
- // this await, as one unit.
6548
+ // it arms one too, under the ids its source event carries. Both writes above committed in
6549
+ // one transaction, before this await.
6424
6550
  if (source) {
6425
6551
  await this.noteScopeWake(tenantIdOf.parse(source.tenant_id), scopeIdOf.parse(source.scope_id));
6426
6552
  await this.handOffCommitted(tenantIdOf.parse(source.tenant_id), scopeIdOf.parse(source.scope_id));
6427
6553
  }
6428
6554
  return id;
6429
6555
  }
6556
+ /**
6557
+ * #3676: whether this executor delivery is still due — `pendingExecutorDeliveries`'s journal
6558
+ * predicate for one row: never attempted, or retrying with its next attempt come. A routed or
6559
+ * delivered row, a dead letter, and a retry still backing off are not.
6560
+ */
6561
+ executorDeliveryDue(eventId, deliveryId, now) {
6562
+ return (this.sql
6563
+ .exec(`SELECT 1 FROM _substrat_deliveries
6564
+ WHERE event_id = ? AND consumer_module = ?
6565
+ AND (next_attempt_at IS NULL OR next_attempt_at > ?)`, eventId, deliveryId, now)
6566
+ .toArray().length === 0);
6567
+ }
6430
6568
  /** #3365: the routed connector deliveries this scope holds pending — their own room. */
6431
6569
  pendingConnectorDispatches() {
6432
6570
  return Number(this.sql
@@ -7389,6 +7527,8 @@ options = {}) {
7389
7527
  const receiptBefore = this.provisionedFor();
7390
7528
  // #2993 part 3: the type this store's own provision fixed, which a load never changes.
7391
7529
  const typeBefore = this.metaValue(SCOPE_TYPE_META_KEY);
7530
+ // #2995: and the parent it fixed, which a load never changes either: a copy carries none.
7531
+ const parentBefore = this.metaValue(PARENT_SCOPE_META_KEY);
7392
7532
  // #2555: this store's own permission flags, read before the drops take them.
7393
7533
  const flagsBefore = keepPermissionFlags ? PERMISSION_FLAG_KEYS.map((key) => [key, this.metaValue(key)]) : [];
7394
7534
  if (provisionedFor !== undefined && receiptBefore !== null && receiptBefore !== provisionedFor) {
@@ -7502,8 +7642,13 @@ options = {}) {
7502
7642
  if (typeBefore !== null) {
7503
7643
  this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, SCOPE_TYPE_META_KEY, typeBefore);
7504
7644
  }
7645
+ this.sql.exec(`DELETE FROM _substrat_meta WHERE key = ?`, PARENT_SCOPE_META_KEY);
7646
+ if (parentBefore !== null) {
7647
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, PARENT_SCOPE_META_KEY, parentBefore);
7648
+ }
7505
7649
  // Read again from what the load left, as a wake would: the store is the type's only record.
7506
7650
  this.scopeTypeHeld = undefined;
7651
+ this.scopeParentHeld = undefined;
7507
7652
  // #1722: whatever stamp an export read here no longer describes this store, so every load
7508
7653
  // replaces it: with the carry's own, or with none. And the write revision moves on from
7509
7654
  // where it stood before the drops, so it never goes back.
@@ -8216,7 +8361,9 @@ options = {}) {
8216
8361
  * one: whatever a handoff switch says, since a broker keeps what it took while it was on.
8217
8362
  *
8218
8363
  * The broker and the ids its messages are kept under are named first from the handoff state:
8219
- * the (tenant, scope) every handoff of this scope used, written before its first broker call. A
8364
+ * the (tenant, scope) every handoff of this scope used, written before its first broker call, and
8365
+ * (#3639) the environment whose broker those handoffs reached, so a named environment's messages
8366
+ * are erased where they went, never looked for in production's broker. A
8220
8367
  * scope whose state is gone (a restore) falls back to its own identity, its `provisioned_for`
8221
8368
  * receipt and its object name, as `wakeForReconcileAsk` reads them. So `redactSubject` takes no
8222
8369
  * new argument, and a coordinator of any version reaches the broker. A scope that can name it by
@@ -8231,7 +8378,8 @@ options = {}) {
8231
8378
  if (!tenant.success || !scope.success) {
8232
8379
  throw substratError('unavailable', 'subject erasure: this scope cannot name its delivery broker, so its copies were not erased');
8233
8380
  }
8234
- await this.deliveryBroker(tenant.data).eraseSubject({ tenantId: tenant.data, scopeId: scope.data, subjectId, at });
8381
+ // #3639: the broker of the scope's environment, which the handoff state keeps after the mode went off.
8382
+ await this.deliveryBroker(tenant.data, await this.handoffEnvironment()).eraseSubject({ tenantId: tenant.data, scopeId: scope.data, subjectId, at });
8235
8383
  }
8236
8384
  /**
8237
8385
  * One page of what this scope holds about one data subject (GDPR Art. 15, D-74): the kernel's