@substrat-run/adapter-cloudflare 0.219.0 → 0.220.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 +69 -5
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +126 -9
  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 +7 -1
  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 +3 -1
  27. package/dist/directory-split-inventory.js.map +1 -1
  28. package/dist/host.d.ts +33 -4
  29. package/dist/host.d.ts.map +1 -1
  30. package/dist/host.js +129 -14
  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 +37 -1
  36. package/dist/route-read-model-publisher.d.ts.map +1 -1
  37. package/dist/route-read-model-publisher.js +127 -44
  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 +31 -1
  44. package/dist/scope-do.d.ts.map +1 -1
  45. package/dist/scope-do.js +207 -18
  46. package/dist/scope-do.js.map +1 -1
  47. package/dist/scope-sweeper-do.d.ts +18 -0
  48. package/dist/scope-sweeper-do.d.ts.map +1 -1
  49. package/dist/scope-sweeper-do.js +72 -1
  50. package/dist/scope-sweeper-do.js.map +1 -1
  51. package/dist/scope-work.d.ts +1 -1
  52. package/dist/scope-work.js +1 -1
  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, defineEnvironmentIn, environmentsOf, removeEnvironmentIn, 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
@@ -32,10 +34,11 @@ export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug,
32
34
  -- script other than its vertical's current serving one (stamped at provision, a
33
35
  -- fork kept on its copy's script) runs a version this row cannot name: NULL, so
34
36
  -- its store calls are refused. The control plane reads the same rule
35
- -- (scopeStoresOf in control-plane-api).
37
+ -- (scopeStoresOf in control-plane-api). A scope on an earlier major's script runs
38
+ -- that major's version (K-65, #3539), which the row names: its stores.
36
39
  CASE WHEN s.serving_ref IS NULL
37
40
  THEN json_extract(vv.manifest_json, '$.scopeStores')
38
- WHEN s.serving_ref = vr.serving_ref
41
+ WHEN s.serving_ref = vr.serving_ref OR ${ON_EARLIER_MAJOR_SQL}
39
42
  THEN json_extract(sv.manifest_json, '$.scopeStores')
40
43
  ELSE NULL END AS scope_stores_json,
41
44
  s.kind, s.forked_from,
@@ -51,7 +54,8 @@ export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug,
51
54
  JOIN tenants t ON t.tenant_id = s.tenant_id
52
55
  LEFT JOIN vertical_versions vv ON vv.id = s.vertical_version_id
53
56
  LEFT JOIN verticals vr ON vr.slug = s.vertical
54
- LEFT JOIN vertical_versions sv ON sv.id = vr.serving_version_id
57
+ -- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
58
+ LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
55
59
  WHERE h.hostname = ? AND h.status = 'active'
56
60
  AND s.status = 'active' AND t.status = 'active'`;
57
61
  /** snake_case row → the camelCase `issueEntry` shape (#1233). */
@@ -222,6 +226,8 @@ const DIRECTORY_DDL = `
222
226
  );
223
227
  CREATE INDEX IF NOT EXISTS scope_script_copies_state ON scope_script_copies (state, scope_id);
224
228
  ${PEER_BINDINGS_DDL}
229
+ -- D-83 (#3530 step 3): an app's named environments, each over its tagged, pinned preview.
230
+ ${APP_ENVIRONMENTS_DDL}
225
231
  CREATE TABLE IF NOT EXISTS hostnames (
226
232
  hostname TEXT PRIMARY KEY,
227
233
  tenant_id TEXT NOT NULL,
@@ -314,6 +320,9 @@ const DIRECTORY_DDL = `
314
320
  serving_version_id TEXT,
315
321
  serving_do_classes TEXT,
316
322
  serving_migration_tag TEXT,
323
+ -- K-65 (#3539 part 2): each earlier major still served beside the current one, on a script
324
+ -- of its own (JSON, oldest first: earlierMajor). NULL: one major, one script.
325
+ earlier_majors TEXT,
317
326
  created_at TEXT NOT NULL
318
327
  );
319
328
  CREATE TABLE IF NOT EXISTS vertical_versions (
@@ -798,6 +807,9 @@ const SCOPE_COLUMNS_ADDED = [
798
807
  'serving_ref TEXT',
799
808
  'archived_at TEXT',
800
809
  'archived_from_status TEXT',
810
+ // #2993: the declared type a scope was provisioned as. Null on every row, which reads as 'home':
811
+ // this host provisions no other type yet, and the pure directory writes 'home' as null too.
812
+ 'scope_type TEXT',
801
813
  ];
802
814
  /**
803
815
  * A directory DDL's statements in the order `applyDirectorySchema` runs them: `loop` before
@@ -958,6 +970,9 @@ export const REPLIED_METHODS = [
958
970
  'writeImpersonationAndAudit',
959
971
  'endImpersonationAndAudit',
960
972
  'setIssueStatusAndAudit',
973
+ // D-83 (#3530 step 3): an environment named or unnamed, with its admin row in the same transaction.
974
+ 'defineEnvironmentAndAudit',
975
+ 'removeEnvironmentAndAudit',
961
976
  ];
962
977
  /**
963
978
  * #1713: the directory's epoch describes THIS store's history, not its data, so it never leaves in
@@ -1066,7 +1081,18 @@ export class ControlPlaneDO extends DurableObject {
1066
1081
  await ctx.storage.setAlarm(at);
1067
1082
  },
1068
1083
  });
1069
- this.backfillArmed = ctx.blockConcurrencyWhile(() => this.armVersionMigrationsBackfill());
1084
+ this.directoryBackfill = directoryBackfillFor(env, this.directoryMirror, this.directoryBackfillLimits());
1085
+ this.directoryVerify = directoryVerifyFor(env, this.directoryMirror, this.directoryVerifyLimits());
1086
+ this.backfillArmed = ctx.blockConcurrencyWhile(async () => {
1087
+ await this.armVersionMigrationsBackfill();
1088
+ // K-68 step 3c: the backfill's passes ride the alarm (directory-mirror-backfill.ts).
1089
+ if (this.directoryMirror?.backfillWanted()) {
1090
+ const current = await ctx.storage.getAlarm();
1091
+ const at = Date.now() + 1_000;
1092
+ if (current === null || current > at)
1093
+ await ctx.storage.setAlarm(at);
1094
+ }
1095
+ });
1070
1096
  }
1071
1097
  // -- K-68 step 3b: the dual-write to the split's objects (directory-mirror.ts) -----
1072
1098
  /** Set where `DIRECTORY_MIRROR` is on and the two object namespaces are bound; null otherwise. */
@@ -1082,6 +1108,40 @@ export class ControlPlaneDO extends DurableObject {
1082
1108
  directoryMirrorStatus() {
1083
1109
  return this.directoryMirror ? this.directoryMirror.status() : { enabled: false };
1084
1110
  }
1111
+ // -- K-68 step 3c: the backfill into the split's objects (directory-mirror-backfill.ts) -----
1112
+ /** Set where `DIRECTORY_BACKFILL` is on beside the mirror; null otherwise. */
1113
+ directoryBackfill;
1114
+ /** The backfill's page and pass budget: the production defaults, smaller in a test directory. */
1115
+ directoryBackfillLimits() {
1116
+ return undefined;
1117
+ }
1118
+ /** Run backfill passes now until none is wanted or one makes no progress (staff, and tests). */
1119
+ async settleDirectoryBackfill(maxPasses) {
1120
+ return this.directoryMirror && this.directoryBackfill ? this.directoryMirror.settleBackfill(maxPasses, this.directoryBackfill) : null;
1121
+ }
1122
+ /** Where the backfill stands, and a page of owners (per tenant: filled or not) after `after`. */
1123
+ directoryBackfillStatus(query = {}) {
1124
+ if (!this.directoryBackfill)
1125
+ return { enabled: false };
1126
+ return { ...this.directoryBackfill.status(), owners: this.directoryBackfill.owners(query) };
1127
+ }
1128
+ // -- K-68 step 3d: the comparison of the directory with the split's objects (directory-mirror-verify.ts) --
1129
+ /** Set where `DIRECTORY_VERIFY` is on beside the mirror; null otherwise. */
1130
+ directoryVerify;
1131
+ /** The comparison's page and pass budget and its interval: the production defaults, smaller in a test directory. */
1132
+ directoryVerifyLimits() {
1133
+ return undefined;
1134
+ }
1135
+ /** Run comparison passes now until the run is done or one makes no progress (staff, and tests). */
1136
+ async settleDirectoryVerify(maxPasses) {
1137
+ return this.directoryMirror && this.directoryVerify ? this.directoryMirror.settleBackfill(maxPasses, this.directoryVerify) : null;
1138
+ }
1139
+ /** The last comparison, per run and per owner: a page after `after`, or the one `owner` names. */
1140
+ directoryVerifyStatus(query = {}) {
1141
+ if (!this.directoryVerify)
1142
+ return { enabled: false };
1143
+ return { ...this.directoryVerify.status(), owners: this.directoryVerify.owners(query) };
1144
+ }
1085
1145
  // -- the routing read model (#3395) -------------------------------------------
1086
1146
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1087
1147
  routePublisher = null;
@@ -1670,6 +1730,8 @@ export class ControlPlaneDO extends DurableObject {
1670
1730
  this.addColumn('verticals', 'serving_version_id TEXT');
1671
1731
  this.addColumn('verticals', 'serving_do_classes TEXT');
1672
1732
  this.addColumn('verticals', 'serving_migration_tag TEXT');
1733
+ // K-65 (#3539 part 2): the earlier majors still served beside the current one.
1734
+ this.addColumn('verticals', 'earlier_majors TEXT');
1673
1735
  this.addColumn('vertical_versions', 'manifest_json TEXT');
1674
1736
  // Push provenance (git CI vs a terminal), as pushed-alongside JSON. NULL = pushed
1675
1737
  // before origin tracking, or by an old CLI.
@@ -2364,6 +2426,7 @@ export class ControlPlaneDO extends DurableObject {
2364
2426
  '_substrat_membership_fences', // #1184: the latest removal, per principal
2365
2427
  '_substrat_peer_switches', // #2029: the peer switch's record, per scope
2366
2428
  'peer_bindings', // #1720: a tenant's explicit caller-to-target choices
2429
+ 'app_environments', // D-83: the names over the tenant's pinned previews
2367
2430
  '_substrat_switch_owed', // #2045: subjects owed a re-assert, per scope
2368
2431
  '_substrat_findings', // #1748: the tenant's findings
2369
2432
  '_substrat_finding_rules', // #1748: the tenant's suppress rules
@@ -3090,6 +3153,32 @@ export class ControlPlaneDO extends DurableObject {
3090
3153
  peerBindings(tenantId, callerScopeId) {
3091
3154
  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
3155
  }
3156
+ /** D-83 (#3530 step 3): the app's environments in the tenant, production first (kernel `environmentsOf`). */
3157
+ listEnvironments(tenantId, vertical) {
3158
+ return environmentsOf(this.kernelSql, tenantId, vertical);
3159
+ }
3160
+ /**
3161
+ * Name the app's preview tagged `name` an environment: read, decided and written in one
3162
+ * transaction with its admin row, which names the preview's scope and never the name. A name that
3163
+ * is already one writes nothing and no row.
3164
+ */
3165
+ defineEnvironmentAndAudit(input, by, audit) {
3166
+ let out;
3167
+ this.writeAndAudit(() => {
3168
+ out = defineEnvironmentIn(this.kernelSql, input, { at: new Date().toISOString(), by });
3169
+ return out.created;
3170
+ }, () => ({ ...audit, scopeId: out.scopeId, after: { vertical: input.vertical, scopeId: out.scopeId } }));
3171
+ return { environment: out.environment, created: out.created };
3172
+ }
3173
+ /** Take an environment's name off its preview, with its admin row; the preview stays. */
3174
+ removeEnvironmentAndAudit(input, audit) {
3175
+ let out;
3176
+ this.writeAndAudit(() => {
3177
+ out = removeEnvironmentIn(this.kernelSql, input);
3178
+ return out.removed;
3179
+ }, () => ({ ...audit, scopeId: out.scopeId, before: { vertical: input.vertical, scopeId: out.scopeId } }));
3180
+ return { removed: out.removed };
3181
+ }
3093
3182
  /** Directory write and endpoint checks share this DO's serialized unit. */
3094
3183
  setPeerBinding(tenantId, callerScopeId, vertical, targetScopeId) {
3095
3184
  const caller = this.sql.exec('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?', callerScopeId).toArray()[0];
@@ -3534,7 +3623,7 @@ export class ControlPlaneDO extends DurableObject {
3534
3623
  * coordinator from before still sends the ref and version alone and gets the CAS it always had;
3535
3624
  * `expected` is trailing, so one from before #2528 still writes unconditionally.
3536
3625
  */
3537
- setVerticalServing(slug, s, audit, expected) {
3626
+ setVerticalServing(slug, s, audit, expected, supersede) {
3538
3627
  let before = null;
3539
3628
  let raced = false;
3540
3629
  this.writeAndAudit(() => {
@@ -3545,8 +3634,24 @@ export class ControlPlaneDO extends DurableObject {
3545
3634
  raced = expected !== undefined && !servesAsFrom(r, expected);
3546
3635
  if (raced)
3547
3636
  return false;
3637
+ // K-65 (#3539 part 2): a new major's first serve moves what the row serves to its earlier
3638
+ // majors, judged against this row, in the write that moves it.
3639
+ const earlier = supersede
3640
+ ? supersededMajorsJson({
3641
+ vertical: slug,
3642
+ earlierJson: r.earlier_majors,
3643
+ current: {
3644
+ ref: r.serving_ref,
3645
+ versionId: r.serving_version_id,
3646
+ doClasses: r.serving_do_classes ? JSON.parse(r.serving_do_classes) : [],
3647
+ migrationTag: r.serving_migration_tag,
3648
+ },
3649
+ nextRef: s.ref,
3650
+ supersede,
3651
+ })
3652
+ : (r.earlier_majors ?? null);
3548
3653
  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);
3654
+ serving_do_classes = ?, serving_migration_tag = ?, earlier_majors = ? WHERE slug = ?`, s.ref, s.versionId, s.doClassesJson, s.migrationTag, earlier, slug);
3550
3655
  return true;
3551
3656
  }, audit && (() => ({ ...audit, before })));
3552
3657
  return !raced;
@@ -3990,8 +4095,12 @@ export class ControlPlaneDO extends DurableObject {
3990
4095
  * `unlistedOnly`, and an auto-admitted version as a listed vertical's new prod. It replaces
3991
4096
  * `moveChannel`, which judged neither: a new name, so a DO from before refuses the call and a
3992
4097
  * coordinator from before finds no `moveChannel` to call. Both fail closed.
4098
+ *
4099
+ * #3539: `breakingWithinMajor` is the K-65 refusal the coordinator ranked the promote to earn, if
4100
+ * any, thrown here only when the vertical is listed. A DO from before ignores it; the coordinator
4101
+ * refuses on the listing it read itself first, so only a listing landing inside that window passes.
3993
4102
  */
3994
- promoteChannel(from, history, unlistedOnly, audit) {
4103
+ promoteChannel(from, history, unlistedOnly, audit, breakingWithinMajor) {
3995
4104
  return this.writeAndAudit(() => {
3996
4105
  const now = this.readChannel(history.vertical_slug, history.channel);
3997
4106
  if ((now?.version_id ?? null) !== from)
@@ -4000,6 +4109,10 @@ export class ControlPlaneDO extends DurableObject {
4000
4109
  const listed = vertical?.listed;
4001
4110
  if (listed && unlistedOnly)
4002
4111
  throw listedPromoteRefusal();
4112
+ // #3539 (K-65): the coordinator ranked the promote; whether the vertical is listed is this unit's
4113
+ // to read, so a listing that landed while it ranked is seen. A private app's promote is not judged.
4114
+ if (listed && history.channel === 'prod' && breakingWithinMajor)
4115
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
4003
4116
  // A re-promote of what prod already names, and what serves (if anything does), moves
4004
4117
  // nothing, so it is not judged again. One whose serve would change what runs is.
4005
4118
  const serving = vertical?.serving_ref && vertical.serving_version_id ? vertical.serving_version_id : history.version_id;
@@ -5840,6 +5953,10 @@ const ROUTE_KICK_EXEMPT = new Set([
5840
5953
  'armRouteReadModelRetry', 'retryRouteReadModel',
5841
5954
  // K-68 step 3b: the dual-write's flush is kicked by the same return, and drives itself.
5842
5955
  'kickDirectoryMirror', 'settleDirectoryMirror',
5956
+ // K-68 step 3c: the backfill runs inside the mirror's flush, and must see the directory quiet.
5957
+ 'settleDirectoryBackfill', 'directoryBackfillStatus', 'directoryBackfillLimits',
5958
+ // K-68 step 3d: the comparison runs the same way.
5959
+ 'settleDirectoryVerify', 'directoryVerifyStatus', 'directoryVerifyLimits',
5843
5960
  ]);
5844
5961
  for (const name of Object.getOwnPropertyNames(ControlPlaneDO.prototype)) {
5845
5962
  if (ROUTE_KICK_EXEMPT.has(name))