@substrat-run/adapter-cloudflare 0.219.0 → 0.221.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 (54) hide show
  1. package/dist/control-plane-do.d.ts +107 -5
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +207 -16
  4. package/dist/control-plane-do.js.map +1 -1
  5. package/dist/directory-mirror-backfill.d.ts +143 -0
  6. package/dist/directory-mirror-backfill.d.ts.map +1 -0
  7. package/dist/directory-mirror-backfill.js +467 -0
  8. package/dist/directory-mirror-backfill.js.map +1 -0
  9. package/dist/directory-mirror-verify.d.ts +166 -0
  10. package/dist/directory-mirror-verify.d.ts.map +1 -0
  11. package/dist/directory-mirror-verify.js +478 -0
  12. package/dist/directory-mirror-verify.js.map +1 -0
  13. package/dist/directory-mirror.d.ts +101 -3
  14. package/dist/directory-mirror.d.ts.map +1 -1
  15. package/dist/directory-mirror.js +143 -37
  16. package/dist/directory-mirror.js.map +1 -1
  17. package/dist/directory-objects.d.ts +14 -0
  18. package/dist/directory-objects.d.ts.map +1 -1
  19. package/dist/directory-objects.js +34 -0
  20. package/dist/directory-objects.js.map +1 -1
  21. package/dist/directory-placement.d.ts.map +1 -1
  22. package/dist/directory-placement.js +10 -2
  23. package/dist/directory-placement.js.map +1 -1
  24. package/dist/directory-split-inventory.d.ts +2 -1
  25. package/dist/directory-split-inventory.d.ts.map +1 -1
  26. package/dist/directory-split-inventory.js +4 -1
  27. package/dist/directory-split-inventory.js.map +1 -1
  28. package/dist/host.d.ts +71 -5
  29. package/dist/host.d.ts.map +1 -1
  30. package/dist/host.js +293 -37
  31. package/dist/host.js.map +1 -1
  32. package/dist/peer-call-target.d.ts.map +1 -1
  33. package/dist/peer-call-target.js +3 -2
  34. package/dist/peer-call-target.js.map +1 -1
  35. package/dist/route-read-model-publisher.d.ts +42 -1
  36. package/dist/route-read-model-publisher.d.ts.map +1 -1
  37. package/dist/route-read-model-publisher.js +176 -55
  38. package/dist/route-read-model-publisher.js.map +1 -1
  39. package/dist/route-read-model.d.ts +15 -0
  40. package/dist/route-read-model.d.ts.map +1 -1
  41. package/dist/route-read-model.js +21 -9
  42. package/dist/route-read-model.js.map +1 -1
  43. package/dist/scope-do.d.ts +48 -1
  44. package/dist/scope-do.d.ts.map +1 -1
  45. package/dist/scope-do.js +434 -29
  46. package/dist/scope-do.js.map +1 -1
  47. package/dist/scope-sweeper-do.d.ts +24 -0
  48. package/dist/scope-sweeper-do.d.ts.map +1 -1
  49. package/dist/scope-sweeper-do.js +90 -1
  50. package/dist/scope-sweeper-do.js.map +1 -1
  51. package/dist/scope-work.d.ts +2 -2
  52. package/dist/scope-work.js +2 -2
  53. package/dist/scope-work.js.map +1 -1
  54. package/package.json +18 -13
@@ -1,12 +1,12 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
- import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, reservedRoleDefinitionRefusal, reservedRoleRefusal, TENANT_SEATED_ROLES_SQL, tenantCoverage, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
2
+ import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, reservedRoleDefinitionRefusal, reservedRoleRefusal, TENANT_SEATED_ROLES_SQL, tenantCoverage, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, SWITCH_OWED_DDL, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
3
3
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, } from '@substrat-run/kernel';
4
4
  import { replyOf } from './do-reply.js';
5
5
  import { rowBytes, switchSqlOver } from './scope-do.js';
6
6
  import { DIRECTORY_COPY_BY_REFERENCE, quoteIdent, referenceCompareSql, referenceExtraSql, } from './directory-copy-reference.js';
7
7
  import { blankSqlComments, boundShapesColumn, executableSqlStatements, installsReconciledOf, PROVISIONED_VERSIONS_SQL, provisionedVersionsParams, } from '@substrat-run/kernel';
8
8
  import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
9
- import { autoAdmittedProdRefusal, listedPromoteRefusal, opsFailureReferenceWhere } from '@substrat-run/kernel';
9
+ import { autoAdmittedProdRefusal, breakingWithinMajorRefusal, listedPromoteRefusal, ON_EARLIER_MAJOR_SQL, opsFailureReferenceWhere, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
10
10
  import { canonicalInstant } from '@substrat-run/kernel';
11
11
  import { doBuiltColumnsOf, doRedactionSql } from './sql.js';
12
12
  import { ROUTE_READ_MODEL_TABLE_GLOB, RouteReadModelPublisher, routeKvWriterOf, uninstallRouteReadModel, } from './route-read-model-publisher.js';
@@ -14,6 +14,8 @@ import { readPeerCallTarget } from './peer-call-target.js';
14
14
  // K-68 step 3b: the directory's dual-write to the registry and the tenant objects (off by default).
15
15
  import { DIRECTORY_MIRROR_TABLE_GLOB, directoryMirrorFor, isDirectoryMirrorTable } from './directory-mirror.js';
16
16
  import { durableMirrorSender } from './directory-objects.js';
17
+ import { directoryBackfillFor } from './directory-mirror-backfill.js';
18
+ import { directoryVerifyFor } from './directory-mirror-verify.js';
17
19
  import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
18
20
  /**
19
21
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
@@ -22,20 +24,23 @@ import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, ops
22
24
  */
23
25
  export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug, h.surface, h.region,
24
26
  COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
25
- CASE WHEN s.serving_ref IS NOT NULL
27
+ -- #3530 step 4: a scope on its environment's own script (\`ae\`) runs the version it is
28
+ -- bound to, which is what that script was last served: its policy is that version's.
29
+ CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
26
30
  THEN json_extract(sv.manifest_json, '$.outbound')
27
31
  ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
28
- CASE WHEN s.serving_ref IS NOT NULL
32
+ CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
29
33
  THEN json_extract(sv.manifest_json, '$.calls')
30
34
  ELSE json_extract(vv.manifest_json, '$.calls') END AS calls_json,
31
35
  -- #2207: the stores of the version the scope's script runs. A scope pinned to a
32
36
  -- script other than its vertical's current serving one (stamped at provision, a
33
37
  -- fork kept on its copy's script) runs a version this row cannot name: NULL, so
34
38
  -- its store calls are refused. The control plane reads the same rule
35
- -- (scopeStoresOf in control-plane-api).
36
- CASE WHEN s.serving_ref IS NULL
39
+ -- (scopeStoresOf in control-plane-api). A scope on an earlier major's script runs
40
+ -- that major's version (K-65, #3539), which the row names: its stores.
41
+ CASE WHEN s.serving_ref IS NULL OR ae.serving_ref IS NOT NULL
37
42
  THEN json_extract(vv.manifest_json, '$.scopeStores')
38
- WHEN s.serving_ref = vr.serving_ref
43
+ WHEN s.serving_ref = vr.serving_ref OR ${ON_EARLIER_MAJOR_SQL}
39
44
  THEN json_extract(sv.manifest_json, '$.scopeStores')
40
45
  ELSE NULL END AS scope_stores_json,
41
46
  s.kind, s.forked_from,
@@ -51,7 +56,9 @@ export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug,
51
56
  JOIN tenants t ON t.tenant_id = s.tenant_id
52
57
  LEFT JOIN vertical_versions vv ON vv.id = s.vertical_version_id
53
58
  LEFT JOIN verticals vr ON vr.slug = s.vertical
54
- LEFT JOIN vertical_versions sv ON sv.id = vr.serving_version_id
59
+ -- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
60
+ LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
61
+ ${ENVIRONMENT_SCRIPT_JOIN_SQL}
55
62
  WHERE h.hostname = ? AND h.status = 'active'
56
63
  AND s.status = 'active' AND t.status = 'active'`;
57
64
  /** snake_case row → the camelCase `issueEntry` shape (#1233). */
@@ -222,6 +229,8 @@ const DIRECTORY_DDL = `
222
229
  );
223
230
  CREATE INDEX IF NOT EXISTS scope_script_copies_state ON scope_script_copies (state, scope_id);
224
231
  ${PEER_BINDINGS_DDL}
232
+ -- D-83 (#3530 step 3): an app's named environments, each over its tagged, pinned preview.
233
+ ${APP_ENVIRONMENTS_DDL}
225
234
  CREATE TABLE IF NOT EXISTS hostnames (
226
235
  hostname TEXT PRIMARY KEY,
227
236
  tenant_id TEXT NOT NULL,
@@ -314,6 +323,9 @@ const DIRECTORY_DDL = `
314
323
  serving_version_id TEXT,
315
324
  serving_do_classes TEXT,
316
325
  serving_migration_tag TEXT,
326
+ -- K-65 (#3539 part 2): each earlier major still served beside the current one, on a script
327
+ -- of its own (JSON, oldest first: earlierMajor). NULL: one major, one script.
328
+ earlier_majors TEXT,
317
329
  created_at TEXT NOT NULL
318
330
  );
319
331
  CREATE TABLE IF NOT EXISTS vertical_versions (
@@ -798,6 +810,9 @@ const SCOPE_COLUMNS_ADDED = [
798
810
  'serving_ref TEXT',
799
811
  'archived_at TEXT',
800
812
  'archived_from_status TEXT',
813
+ // #2993: the declared type a scope was provisioned as. Null on every row, which reads as 'home':
814
+ // this host provisions no other type yet, and the pure directory writes 'home' as null too.
815
+ 'scope_type TEXT',
801
816
  ];
802
817
  /**
803
818
  * A directory DDL's statements in the order `applyDirectorySchema` runs them: `loop` before
@@ -958,6 +973,12 @@ export const REPLIED_METHODS = [
958
973
  'writeImpersonationAndAudit',
959
974
  'endImpersonationAndAudit',
960
975
  'setIssueStatusAndAudit',
976
+ // D-83 (#3530 step 3): an environment named or unnamed, with its admin row in the same transaction.
977
+ 'defineEnvironmentAndAudit',
978
+ 'removeEnvironmentAndAudit',
979
+ // #3530 step 4: an environment's own serving script recorded, with its admin row.
980
+ 'setEnvironmentServingAndAudit',
981
+ 'claimEnvironmentServe',
961
982
  ];
962
983
  /**
963
984
  * #1713: the directory's epoch describes THIS store's history, not its data, so it never leaves in
@@ -1066,7 +1087,18 @@ export class ControlPlaneDO extends DurableObject {
1066
1087
  await ctx.storage.setAlarm(at);
1067
1088
  },
1068
1089
  });
1069
- this.backfillArmed = ctx.blockConcurrencyWhile(() => this.armVersionMigrationsBackfill());
1090
+ this.directoryBackfill = directoryBackfillFor(env, this.directoryMirror, this.directoryBackfillLimits());
1091
+ this.directoryVerify = directoryVerifyFor(env, this.directoryMirror, this.directoryVerifyLimits());
1092
+ this.backfillArmed = ctx.blockConcurrencyWhile(async () => {
1093
+ await this.armVersionMigrationsBackfill();
1094
+ // K-68 step 3c: the backfill's passes ride the alarm (directory-mirror-backfill.ts).
1095
+ if (this.directoryMirror?.backfillWanted()) {
1096
+ const current = await ctx.storage.getAlarm();
1097
+ const at = Date.now() + 1_000;
1098
+ if (current === null || current > at)
1099
+ await ctx.storage.setAlarm(at);
1100
+ }
1101
+ });
1070
1102
  }
1071
1103
  // -- K-68 step 3b: the dual-write to the split's objects (directory-mirror.ts) -----
1072
1104
  /** Set where `DIRECTORY_MIRROR` is on and the two object namespaces are bound; null otherwise. */
@@ -1082,6 +1114,40 @@ export class ControlPlaneDO extends DurableObject {
1082
1114
  directoryMirrorStatus() {
1083
1115
  return this.directoryMirror ? this.directoryMirror.status() : { enabled: false };
1084
1116
  }
1117
+ // -- K-68 step 3c: the backfill into the split's objects (directory-mirror-backfill.ts) -----
1118
+ /** Set where `DIRECTORY_BACKFILL` is on beside the mirror; null otherwise. */
1119
+ directoryBackfill;
1120
+ /** The backfill's page and pass budget: the production defaults, smaller in a test directory. */
1121
+ directoryBackfillLimits() {
1122
+ return undefined;
1123
+ }
1124
+ /** Run backfill passes now until none is wanted or one makes no progress (staff, and tests). */
1125
+ async settleDirectoryBackfill(maxPasses) {
1126
+ return this.directoryMirror && this.directoryBackfill ? this.directoryMirror.settleBackfill(maxPasses, this.directoryBackfill) : null;
1127
+ }
1128
+ /** Where the backfill stands, and a page of owners (per tenant: filled or not) after `after`. */
1129
+ directoryBackfillStatus(query = {}) {
1130
+ if (!this.directoryBackfill)
1131
+ return { enabled: false };
1132
+ return { ...this.directoryBackfill.status(), owners: this.directoryBackfill.owners(query) };
1133
+ }
1134
+ // -- K-68 step 3d: the comparison of the directory with the split's objects (directory-mirror-verify.ts) --
1135
+ /** Set where `DIRECTORY_VERIFY` is on beside the mirror; null otherwise. */
1136
+ directoryVerify;
1137
+ /** The comparison's page and pass budget and its interval: the production defaults, smaller in a test directory. */
1138
+ directoryVerifyLimits() {
1139
+ return undefined;
1140
+ }
1141
+ /** Run comparison passes now until the run is done or one makes no progress (staff, and tests). */
1142
+ async settleDirectoryVerify(maxPasses) {
1143
+ return this.directoryMirror && this.directoryVerify ? this.directoryMirror.settleBackfill(maxPasses, this.directoryVerify) : null;
1144
+ }
1145
+ /** The last comparison, per run and per owner: a page after `after`, or the one `owner` names. */
1146
+ directoryVerifyStatus(query = {}) {
1147
+ if (!this.directoryVerify)
1148
+ return { enabled: false };
1149
+ return { ...this.directoryVerify.status(), owners: this.directoryVerify.owners(query) };
1150
+ }
1085
1151
  // -- the routing read model (#3395) -------------------------------------------
1086
1152
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1087
1153
  routePublisher = null;
@@ -1670,6 +1736,8 @@ export class ControlPlaneDO extends DurableObject {
1670
1736
  this.addColumn('verticals', 'serving_version_id TEXT');
1671
1737
  this.addColumn('verticals', 'serving_do_classes TEXT');
1672
1738
  this.addColumn('verticals', 'serving_migration_tag TEXT');
1739
+ // K-65 (#3539 part 2): the earlier majors still served beside the current one.
1740
+ this.addColumn('verticals', 'earlier_majors TEXT');
1673
1741
  this.addColumn('vertical_versions', 'manifest_json TEXT');
1674
1742
  // Push provenance (git CI vs a terminal), as pushed-alongside JSON. NULL = pushed
1675
1743
  // before origin tracking, or by an old CLI.
@@ -1688,6 +1756,15 @@ export class ControlPlaneDO extends DurableObject {
1688
1756
  this.addColumn('_substrat_entitlements', 'plan TEXT');
1689
1757
  this.addColumn('_substrat_entitlements', 'granted_at TEXT');
1690
1758
  this.addColumn('_substrat_entitlements', 'granted_by TEXT');
1759
+ // #3530 step 4: an environment's own serving script; NULL on every row (no script of its own).
1760
+ // Written out, not looped over the kernel's list: lint:spine-ddl reads each call, and
1761
+ // directory-placement.ts's copy (`APP_ENVIRONMENT_SERVING_COLUMNS`) is held to these by directory-objects.
1762
+ this.addColumn('app_environments', 'serving_ref TEXT');
1763
+ this.addColumn('app_environments', 'serving_version_id TEXT');
1764
+ this.addColumn('app_environments', 'serving_do_classes TEXT');
1765
+ this.addColumn('app_environments', 'serving_migration_tag TEXT');
1766
+ this.addColumn('app_environments', 'serve_claim TEXT');
1767
+ this.addColumn('app_environments', 'serve_claimed_until TEXT');
1691
1768
  for (const stmt of LEGACY_SCOPE_ROWS_BACKFILL)
1692
1769
  this.sql.exec(stmt);
1693
1770
  // #2501: an ownership period for every vertical registered before the history existed.
@@ -2364,6 +2441,7 @@ export class ControlPlaneDO extends DurableObject {
2364
2441
  '_substrat_membership_fences', // #1184: the latest removal, per principal
2365
2442
  '_substrat_peer_switches', // #2029: the peer switch's record, per scope
2366
2443
  'peer_bindings', // #1720: a tenant's explicit caller-to-target choices
2444
+ 'app_environments', // D-83: the names over the tenant's pinned previews
2367
2445
  '_substrat_switch_owed', // #2045: subjects owed a re-assert, per scope
2368
2446
  '_substrat_findings', // #1748: the tenant's findings
2369
2447
  '_substrat_finding_rules', // #1748: the tenant's suppress rules
@@ -2636,7 +2714,15 @@ export class ControlPlaneDO extends DurableObject {
2636
2714
  // Idempotency is on the scope_id (§3.3: idempotent and journaled — safe to
2637
2715
  // re-run), so an existing scope short-circuits before the slug check:
2638
2716
  // re-provisioning must not collide with itself.
2639
- const existed = this.sql.exec('SELECT 1 FROM scopes WHERE scope_id = ?', scopeId).toArray()[0] !== undefined;
2717
+ const existing = this.sql.exec('SELECT scope_type FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
2718
+ const existed = existing !== undefined;
2719
+ // #2993: a scope's type is fixed when it is provisioned. The host judged it against the row it
2720
+ // read; judged again here, in the write's own unit, so a provision racing another with a
2721
+ // different type cannot both succeed. Absent: a host with no declared types, as before.
2722
+ if (existing && record.scopeType !== undefined && (existing.scope_type ?? null) !== record.scopeType) {
2723
+ throw substratError('conflict', `scope ${scopeId} is a '${existing.scope_type ?? 'home'}' scope, and a scope's type is fixed when it is ` +
2724
+ `provisioned: it cannot become '${record.scopeType ?? 'home'}'`);
2725
+ }
2640
2726
  if (!existed) {
2641
2727
  // An `archived` scope (a deleted app) has released its name — and `reaped` is past
2642
2728
  // archived, so it too has released it — both excluded so the slug can be reclaimed.
@@ -2661,11 +2747,13 @@ export class ControlPlaneDO extends DurableObject {
2661
2747
  // sub-select yields NULL and routing falls through to the bound version's ref.
2662
2748
  const inheritServingSlug = record.kind === 'preview' ? null : record.vertical;
2663
2749
  this.sql.exec(`INSERT INTO scopes
2664
- (scope_id, tenant_id, parent_scope_id, slug, kind, name, vertical,
2750
+ (scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
2665
2751
  storage_shape, jurisdiction, status, forked_from, forked_at, expires_at,
2666
2752
  serving_ref, created_at)
2667
- VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2668
- (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, inheritServingSlug, createdAt);
2753
+ VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2754
+ (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId,
2755
+ // #2993: NULL for 'home', so a host with no declared types writes exactly the row it always did.
2756
+ record.scopeType ?? null, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, inheritServingSlug, createdAt);
2669
2757
  }
2670
2758
  return !existed;
2671
2759
  }
@@ -2717,6 +2805,17 @@ export class ControlPlaneDO extends DurableObject {
2717
2805
  const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
2718
2806
  return this.sql.exec(sql, ...params).toArray();
2719
2807
  }
2808
+ /**
2809
+ * #2993 part 4: the scope types other than `home` that the vertical's scopes hold, every tenant's
2810
+ * and every status but `reaped`, each once. What a promote judges the incoming version's declared
2811
+ * types against. A vertical none of whose scopes is typed answers `[]`.
2812
+ */
2813
+ scopeTypesHeldBy(vertical) {
2814
+ return this.sql
2815
+ .exec("SELECT DISTINCT scope_type FROM scopes WHERE vertical = ? AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type", vertical)
2816
+ .toArray()
2817
+ .map((r) => String(r.scope_type));
2818
+ }
2720
2819
  /** #2178: `PROVISIONED_VERSIONS_SQL` over the directory — one row per version, however many scopes. */
2721
2820
  provisionedVersionsOf(vertical, serving, ownerTenant) {
2722
2821
  return installsReconciledOf(this.sql.exec(PROVISIONED_VERSIONS_SQL, ...provisionedVersionsParams(vertical, serving, ownerTenant)).toArray());
@@ -3090,6 +3189,70 @@ export class ControlPlaneDO extends DurableObject {
3090
3189
  peerBindings(tenantId, callerScopeId) {
3091
3190
  return this.sql.exec('SELECT vertical, target_scope_id, invalidated FROM peer_bindings WHERE tenant_id = ? AND caller_scope_id = ? ORDER BY vertical', tenantId, callerScopeId).toArray();
3092
3191
  }
3192
+ /** D-83 (#3530 step 3): the app's environments in the tenant, production first (kernel `environmentsOf`). */
3193
+ listEnvironments(tenantId, vertical) {
3194
+ return environmentsOf(this.kernelSql, tenantId, vertical);
3195
+ }
3196
+ /**
3197
+ * Name the app's preview tagged `name` an environment: read, decided and written in one
3198
+ * transaction with its admin row, which names the preview's scope and never the name. A name that
3199
+ * is already one writes nothing and no row.
3200
+ */
3201
+ defineEnvironmentAndAudit(input, by, audit) {
3202
+ let out;
3203
+ this.writeAndAudit(() => {
3204
+ out = defineEnvironmentIn(this.kernelSql, input, { at: new Date().toISOString(), by });
3205
+ return out.created;
3206
+ }, () => ({ ...audit, scopeId: out.scopeId, after: { vertical: input.vertical, scopeId: out.scopeId } }));
3207
+ return { environment: out.environment, created: out.created };
3208
+ }
3209
+ /** Take an environment's name off its preview, with its admin row; the preview stays. */
3210
+ removeEnvironmentAndAudit(input, audit) {
3211
+ let out;
3212
+ this.writeAndAudit(() => {
3213
+ out = removeEnvironmentIn(this.kernelSql, input);
3214
+ return out.removed;
3215
+ }, () => ({ ...audit, scopeId: out.scopeId, before: { vertical: input.vertical, scopeId: out.scopeId } }));
3216
+ return { removed: out.removed };
3217
+ }
3218
+ /**
3219
+ * #3530 step 4: record what an environment's own serving script now runs, compare-and-set on the
3220
+ * record the upload diffed from (kernel `setEnvironmentServingIn`), with its admin row in the
3221
+ * same transaction. False, with nothing written and no row, when the record moved since.
3222
+ */
3223
+ setEnvironmentServingAndAudit(input, next, expected, audit, claim) {
3224
+ let out;
3225
+ this.writeAndAudit(() => {
3226
+ out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim);
3227
+ return out.moved;
3228
+ }, () => ({
3229
+ ...audit,
3230
+ scopeId: out.scopeId,
3231
+ before: out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
3232
+ after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId },
3233
+ }));
3234
+ return out.moved;
3235
+ }
3236
+ /**
3237
+ * #3530 step 4: take an environment's serve lease (kernel `claimEnvironmentServeIn`), so its serves
3238
+ * run one at a time. Unaudited: it moves nothing a reader sees, and the serve it guards is audited.
3239
+ */
3240
+ claimEnvironmentServe(input, claim, leaseMs) {
3241
+ let held = false;
3242
+ this.writeAndAudit(() => {
3243
+ const now = Date.now();
3244
+ held = claimEnvironmentServeIn(this.kernelSql, input, claim, { now: new Date(now).toISOString(), until: new Date(now + leaseMs).toISOString() });
3245
+ return held;
3246
+ });
3247
+ return held;
3248
+ }
3249
+ /** #3530 step 4: give the lease back, if `claim` still holds it. */
3250
+ releaseEnvironmentServe(input, claim) {
3251
+ this.writeAndAudit(() => {
3252
+ releaseEnvironmentServeIn(this.kernelSql, input, claim);
3253
+ return true;
3254
+ });
3255
+ }
3093
3256
  /** Directory write and endpoint checks share this DO's serialized unit. */
3094
3257
  setPeerBinding(tenantId, callerScopeId, vertical, targetScopeId) {
3095
3258
  const caller = this.sql.exec('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?', callerScopeId).toArray()[0];
@@ -3534,7 +3697,7 @@ export class ControlPlaneDO extends DurableObject {
3534
3697
  * coordinator from before still sends the ref and version alone and gets the CAS it always had;
3535
3698
  * `expected` is trailing, so one from before #2528 still writes unconditionally.
3536
3699
  */
3537
- setVerticalServing(slug, s, audit, expected) {
3700
+ setVerticalServing(slug, s, audit, expected, supersede) {
3538
3701
  let before = null;
3539
3702
  let raced = false;
3540
3703
  this.writeAndAudit(() => {
@@ -3545,8 +3708,24 @@ export class ControlPlaneDO extends DurableObject {
3545
3708
  raced = expected !== undefined && !servesAsFrom(r, expected);
3546
3709
  if (raced)
3547
3710
  return false;
3711
+ // K-65 (#3539 part 2): a new major's first serve moves what the row serves to its earlier
3712
+ // majors, judged against this row, in the write that moves it.
3713
+ const earlier = supersede
3714
+ ? supersededMajorsJson({
3715
+ vertical: slug,
3716
+ earlierJson: r.earlier_majors,
3717
+ current: {
3718
+ ref: r.serving_ref,
3719
+ versionId: r.serving_version_id,
3720
+ doClasses: r.serving_do_classes ? JSON.parse(r.serving_do_classes) : [],
3721
+ migrationTag: r.serving_migration_tag,
3722
+ },
3723
+ nextRef: s.ref,
3724
+ supersede,
3725
+ })
3726
+ : (r.earlier_majors ?? null);
3548
3727
  this.sql.exec(`UPDATE verticals SET serving_ref = ?, serving_version_id = ?,
3549
- serving_do_classes = ?, serving_migration_tag = ? WHERE slug = ?`, s.ref, s.versionId, s.doClassesJson, s.migrationTag, slug);
3728
+ serving_do_classes = ?, serving_migration_tag = ?, earlier_majors = ? WHERE slug = ?`, s.ref, s.versionId, s.doClassesJson, s.migrationTag, earlier, slug);
3550
3729
  return true;
3551
3730
  }, audit && (() => ({ ...audit, before })));
3552
3731
  return !raced;
@@ -3990,8 +4169,12 @@ export class ControlPlaneDO extends DurableObject {
3990
4169
  * `unlistedOnly`, and an auto-admitted version as a listed vertical's new prod. It replaces
3991
4170
  * `moveChannel`, which judged neither: a new name, so a DO from before refuses the call and a
3992
4171
  * coordinator from before finds no `moveChannel` to call. Both fail closed.
4172
+ *
4173
+ * #3539: `breakingWithinMajor` is the K-65 refusal the coordinator ranked the promote to earn, if
4174
+ * any, thrown here only when the vertical is listed. A DO from before ignores it; the coordinator
4175
+ * refuses on the listing it read itself first, so only a listing landing inside that window passes.
3993
4176
  */
3994
- promoteChannel(from, history, unlistedOnly, audit) {
4177
+ promoteChannel(from, history, unlistedOnly, audit, breakingWithinMajor) {
3995
4178
  return this.writeAndAudit(() => {
3996
4179
  const now = this.readChannel(history.vertical_slug, history.channel);
3997
4180
  if ((now?.version_id ?? null) !== from)
@@ -4000,6 +4183,10 @@ export class ControlPlaneDO extends DurableObject {
4000
4183
  const listed = vertical?.listed;
4001
4184
  if (listed && unlistedOnly)
4002
4185
  throw listedPromoteRefusal();
4186
+ // #3539 (K-65): the coordinator ranked the promote; whether the vertical is listed is this unit's
4187
+ // to read, so a listing that landed while it ranked is seen. A private app's promote is not judged.
4188
+ if (listed && history.channel === 'prod' && breakingWithinMajor)
4189
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
4003
4190
  // A re-promote of what prod already names, and what serves (if anything does), moves
4004
4191
  // nothing, so it is not judged again. One whose serve would change what runs is.
4005
4192
  const serving = vertical?.serving_ref && vertical.serving_version_id ? vertical.serving_version_id : history.version_id;
@@ -5840,6 +6027,10 @@ const ROUTE_KICK_EXEMPT = new Set([
5840
6027
  'armRouteReadModelRetry', 'retryRouteReadModel',
5841
6028
  // K-68 step 3b: the dual-write's flush is kicked by the same return, and drives itself.
5842
6029
  'kickDirectoryMirror', 'settleDirectoryMirror',
6030
+ // K-68 step 3c: the backfill runs inside the mirror's flush, and must see the directory quiet.
6031
+ 'settleDirectoryBackfill', 'directoryBackfillStatus', 'directoryBackfillLimits',
6032
+ // K-68 step 3d: the comparison runs the same way.
6033
+ 'settleDirectoryVerify', 'directoryVerifyStatus', 'directoryVerifyLimits',
5843
6034
  ]);
5844
6035
  for (const name of Object.getOwnPropertyNames(ControlPlaneDO.prototype)) {
5845
6036
  if (ROUTE_KICK_EXEMPT.has(name))