@delmaredigital/payload-experiments 0.4.0 → 0.5.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 (290) hide show
  1. package/README.md +10 -4
  2. package/dist/admin/blocks/model.js +2 -0
  3. package/dist/admin/copy/blocks.d.ts +1 -0
  4. package/dist/admin/copy/blocks.js +1 -0
  5. package/dist/admin/copy/status.d.ts +3 -0
  6. package/dist/admin/copy/status.js +3 -0
  7. package/dist/admin/placementStatus.model.js +3 -0
  8. package/dist/admin/status.model.d.ts +3 -2
  9. package/dist/admin/status.model.js +9 -3
  10. package/dist/admin/surface/ResultsRoute.js +2 -1
  11. package/dist/admin/surface/TestsHome.d.ts +2 -1
  12. package/dist/admin/surface/TestsHome.js +31 -11
  13. package/dist/admin/surface/TestsSurface.js +4 -0
  14. package/dist/admin/surface/home.model.d.ts +11 -6
  15. package/dist/admin/surface/home.model.js +19 -8
  16. package/dist/admin/surface/newTest/PageWizard.js +13 -3
  17. package/dist/admin/surface/results/ResultsHeader.js +43 -9
  18. package/dist/admin/surface/test/TestPage.js +11 -1
  19. package/dist/admin/useLayerUsage.d.ts +1 -1
  20. package/dist/admin/views/buildSurfaceProps.js +3 -0
  21. package/dist/cohorts/build.d.ts +35 -0
  22. package/dist/cohorts/build.js +134 -0
  23. package/dist/cohorts/key.d.ts +12 -0
  24. package/dist/cohorts/key.js +15 -0
  25. package/dist/cohorts/maintenance.d.ts +10 -0
  26. package/dist/cohorts/maintenance.js +70 -0
  27. package/dist/cohorts/readiness.d.ts +30 -0
  28. package/dist/cohorts/readiness.js +54 -0
  29. package/dist/cohorts/readinessData.d.ts +29 -0
  30. package/dist/cohorts/readinessData.js +123 -0
  31. package/dist/cohorts/rule.d.ts +33 -0
  32. package/dist/cohorts/rule.js +50 -0
  33. package/dist/collections/cohortMembers.d.ts +4 -0
  34. package/dist/collections/cohortMembers.js +95 -0
  35. package/dist/collections/experiments/config.js +157 -7
  36. package/dist/collections/experiments/editability.js +10 -6
  37. package/dist/collections/experiments/lockHook.js +39 -20
  38. package/dist/collections/index.js +4 -1
  39. package/dist/collections/phases.js +4 -1
  40. package/dist/constants.d.ts +2 -0
  41. package/dist/constants.js +2 -0
  42. package/dist/db/adapter.d.ts +1 -1
  43. package/dist/db/adapter.js +14 -4
  44. package/dist/db/appends.js +1 -1
  45. package/dist/db/cohortMembership.d.ts +11 -0
  46. package/dist/db/cohortMembership.js +31 -0
  47. package/dist/db/cohortPool.d.ts +9 -0
  48. package/dist/db/cohortPool.js +53 -0
  49. package/dist/db/cohortTransactions.d.ts +3 -0
  50. package/dist/db/cohortTransactions.js +52 -0
  51. package/dist/db/cohorts.d.ts +72 -0
  52. package/dist/db/cohorts.js +280 -0
  53. package/dist/db/erase.d.ts +2 -0
  54. package/dist/db/erase.js +21 -2
  55. package/dist/db/events.d.ts +2 -0
  56. package/dist/db/events.js +8 -0
  57. package/dist/db/executor.d.ts +2 -0
  58. package/dist/db/executor.js +8 -0
  59. package/dist/db/locks.d.ts +7 -0
  60. package/dist/db/locks.js +13 -1
  61. package/dist/db/names.d.ts +95 -1
  62. package/dist/db/names.js +95 -1
  63. package/dist/db/occupancy.d.ts +21 -0
  64. package/dist/db/occupancy.js +46 -0
  65. package/dist/db/pageOccupancy.d.ts +4 -4
  66. package/dist/db/pageOccupancy.js +13 -10
  67. package/dist/db/pgExecutor.d.ts +4 -0
  68. package/dist/db/pgExecutor.js +1 -1
  69. package/dist/db/placements.js +1 -1
  70. package/dist/db/results.d.ts +5 -2
  71. package/dist/db/results.js +32 -5
  72. package/dist/db/slices.d.ts +9 -2
  73. package/dist/db/slices.js +15 -8
  74. package/dist/db/snapshots.d.ts +16 -1
  75. package/dist/db/snapshots.js +27 -2
  76. package/dist/db/sql.d.ts +2 -2
  77. package/dist/db/sql.js +1 -2
  78. package/dist/endpoints/cohortSources.d.ts +16 -0
  79. package/dist/endpoints/cohortSources.js +335 -0
  80. package/dist/endpoints/contentLocale.d.ts +1 -1
  81. package/dist/endpoints/events.js +82 -18
  82. package/dist/endpoints/index.js +45 -1
  83. package/dist/endpoints/pausedBy.d.ts +14 -0
  84. package/dist/endpoints/pausedBy.js +94 -0
  85. package/dist/endpoints/preflight.js +4 -1
  86. package/dist/endpoints/previewToken.js +2 -0
  87. package/dist/endpoints/results.d.ts +2 -2
  88. package/dist/endpoints/results.js +111 -3
  89. package/dist/endpoints/routeId.d.ts +2 -1
  90. package/dist/endpoints/routeId.js +6 -2
  91. package/dist/endpoints/summary.js +24 -1
  92. package/dist/endpoints/transitions.d.ts +7 -0
  93. package/dist/endpoints/transitions.js +50 -1
  94. package/dist/events/rows.d.ts +1 -1
  95. package/dist/events/rows.js +5 -3
  96. package/dist/exports/index.d.ts +2 -0
  97. package/dist/exports/index.js +1 -0
  98. package/dist/exports/runtimeProxy.d.ts +1 -0
  99. package/dist/exports/runtimeProxy.js +1 -0
  100. package/dist/hooks/blockRemovalRule.js +7 -4
  101. package/dist/hooks/pageGuard.js +1 -1
  102. package/dist/labels/status.d.ts +15 -0
  103. package/dist/labels/status.js +12 -0
  104. package/dist/manifest/compile.d.ts +15 -4
  105. package/dist/manifest/compile.js +91 -3
  106. package/dist/onInit.js +4 -1
  107. package/dist/options.d.ts +1 -0
  108. package/dist/options.js +10 -0
  109. package/dist/proxy/consentFallback.d.ts +1 -1
  110. package/dist/proxy/consentFallback.js +4 -4
  111. package/dist/proxy/control.d.ts +1 -1
  112. package/dist/proxy/control.js +2 -2
  113. package/dist/proxy/pageRewrite.d.ts +1 -1
  114. package/dist/proxy/pageRewrite.js +3 -2
  115. package/dist/proxy/resolve.js +76 -17
  116. package/dist/puck/ExperimentPicker.js +2 -1
  117. package/dist/puck/copy.d.ts +6 -5
  118. package/dist/puck/copy.js +3 -7
  119. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  120. package/dist/puck/editor/QuickTestActions.js +7 -1
  121. package/dist/puck/editor/armWrites.js +6 -1
  122. package/dist/puck/editor/copy.d.ts +3 -0
  123. package/dist/puck/editor/copy.js +3 -0
  124. package/dist/puck/editor/editor.css +2 -1
  125. package/dist/puck/editor/editor.model.d.ts +2 -1
  126. package/dist/puck/editor/editor.model.js +2 -0
  127. package/dist/puck/editor/placementsCache.d.ts +1 -1
  128. package/dist/puck/editor/placementsCache.js +6 -3
  129. package/dist/results/analyse.d.ts +3 -1
  130. package/dist/results/analyse.js +20 -3
  131. package/dist/results/health.d.ts +11 -0
  132. package/dist/results/health.js +38 -0
  133. package/dist/results/power.d.ts +1 -1
  134. package/dist/results/power.js +1 -1
  135. package/dist/results/snapshot.d.ts +8 -2
  136. package/dist/results/snapshot.js +23 -1
  137. package/dist/results/unitValues.d.ts +48 -0
  138. package/dist/results/unitValues.js +166 -0
  139. package/dist/runtime/assign.d.ts +7 -3
  140. package/dist/runtime/assign.js +12 -4
  141. package/dist/runtime/cohortCookie.d.ts +15 -0
  142. package/dist/runtime/cohortCookie.js +72 -0
  143. package/dist/runtime/cohortLookup.d.ts +9 -0
  144. package/dist/runtime/cohortLookup.js +25 -0
  145. package/dist/runtime/eligibility.d.ts +11 -5
  146. package/dist/runtime/eligibility.js +33 -7
  147. package/dist/runtime/header.d.ts +1 -0
  148. package/dist/runtime/header.js +1 -1
  149. package/dist/runtime/proxyRuntime.js +5 -1
  150. package/dist/runtime/targeting.d.ts +3 -2
  151. package/dist/runtime/targeting.js +2 -1
  152. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  153. package/dist/sanitizeReadinessDetail.js +41 -4
  154. package/dist/schedule/activeTime.d.ts +28 -0
  155. package/dist/schedule/activeTime.js +322 -0
  156. package/dist/schedule/ranges.d.ts +13 -0
  157. package/dist/schedule/ranges.js +11 -0
  158. package/dist/schedule/roundTime.d.ts +10 -0
  159. package/dist/schedule/roundTime.js +45 -0
  160. package/dist/schedule/types.d.ts +29 -0
  161. package/dist/schedule/types.js +1 -0
  162. package/dist/server/cohortLookup.d.ts +3 -0
  163. package/dist/server/cohortLookup.js +7 -0
  164. package/dist/server/eraseUser.d.ts +1 -0
  165. package/dist/server/getAssignments.js +63 -40
  166. package/dist/server/previewDraft.d.ts +1 -1
  167. package/dist/server/previewDraft.js +3 -2
  168. package/dist/server/recordExposures.js +4 -2
  169. package/dist/server/runResults.js +97 -150
  170. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  171. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  172. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  173. package/dist/testSurface/actions/actions.model.js +38 -5
  174. package/dist/testSurface/api.d.ts +13 -1
  175. package/dist/testSurface/api.js +19 -0
  176. package/dist/testSurface/copy/actions.d.ts +13 -0
  177. package/dist/testSurface/copy/actions.js +13 -0
  178. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  179. package/dist/testSurface/copy/cohorts.js +81 -0
  180. package/dist/testSurface/copy/common.d.ts +2 -3
  181. package/dist/testSurface/copy/common.js +4 -4
  182. package/dist/testSurface/copy/inputs.d.ts +3 -0
  183. package/dist/testSurface/copy/inputs.js +3 -0
  184. package/dist/testSurface/copy/readiness.d.ts +20 -6
  185. package/dist/testSurface/copy/readiness.js +42 -9
  186. package/dist/testSurface/copy/results.d.ts +1 -0
  187. package/dist/testSurface/copy/results.js +1 -0
  188. package/dist/testSurface/copy/schedule.d.ts +58 -0
  189. package/dist/testSurface/copy/schedule.js +150 -0
  190. package/dist/testSurface/copy/surface.d.ts +2 -0
  191. package/dist/testSurface/copy/surface.js +2 -0
  192. package/dist/testSurface/copy/testPage.d.ts +12 -2
  193. package/dist/testSurface/copy/testPage.js +17 -2
  194. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  195. package/dist/testSurface/format/roundProgress.js +34 -5
  196. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  197. package/dist/testSurface/format/scheduleStatus.js +93 -0
  198. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  199. package/dist/testSurface/format/useScheduleClock.js +20 -0
  200. package/dist/testSurface/labels.d.ts +4 -9
  201. package/dist/testSurface/labels.js +2 -7
  202. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  203. package/dist/testSurface/lockedNotice.model.js +16 -3
  204. package/dist/testSurface/readPreflight.d.ts +3 -0
  205. package/dist/testSurface/readPreflight.js +14 -0
  206. package/dist/testSurface/readinessRead.d.ts +2 -2
  207. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  208. package/dist/testSurface/results/results.model.d.ts +1 -1
  209. package/dist/testSurface/results/results.model.js +34 -6
  210. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  211. package/dist/testSurface/review/cohortEstimate.js +32 -0
  212. package/dist/testSurface/surface/contracts.d.ts +2 -1
  213. package/dist/testSurface/surface/contracts.js +1 -0
  214. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  215. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  216. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  217. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  218. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  219. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  220. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  221. package/dist/testSurface/surface/results/ResultsBody.js +46 -10
  222. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  223. package/dist/testSurface/surface/results/useResults.js +17 -6
  224. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  225. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  226. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  227. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  228. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  229. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  230. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  231. package/dist/testSurface/surface/test/Section.js +1 -1
  232. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  233. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  234. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  235. package/dist/testSurface/surface/test/fields.js +3 -3
  236. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  237. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  238. package/dist/testSurface/surface/test/testPage.css +26 -0
  239. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  240. package/dist/testSurface/surface/testDocument.model.js +2 -1
  241. package/dist/testSurface/surface/useTestDocument.js +11 -4
  242. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  243. package/dist/testSurface/targeting/targeting.model.js +1 -1
  244. package/dist/testSurface/useApi.d.ts +12 -0
  245. package/dist/transitions/addMetric.js +5 -2
  246. package/dist/transitions/allocate.js +6 -1
  247. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  248. package/dist/transitions/assertNoOverlap.js +24 -0
  249. package/dist/transitions/buildCohorts.d.ts +10 -0
  250. package/dist/transitions/buildCohorts.js +68 -0
  251. package/dist/transitions/cancelSchedule.d.ts +4 -0
  252. package/dist/transitions/cancelSchedule.js +42 -0
  253. package/dist/transitions/checkStart.d.ts +17 -3
  254. package/dist/transitions/checkStart.js +20 -7
  255. package/dist/transitions/decide.js +35 -11
  256. package/dist/transitions/kernel.d.ts +3 -1
  257. package/dist/transitions/kernel.js +5 -2
  258. package/dist/transitions/pause.d.ts +4 -0
  259. package/dist/transitions/pause.js +35 -0
  260. package/dist/transitions/phaseRecord.d.ts +19 -2
  261. package/dist/transitions/phaseRecord.js +50 -11
  262. package/dist/transitions/placementInteractions.js +1 -1
  263. package/dist/transitions/preflightData.d.ts +11 -3
  264. package/dist/transitions/preflightData.js +134 -81
  265. package/dist/transitions/reschedule.d.ts +4 -0
  266. package/dist/transitions/reschedule.js +58 -0
  267. package/dist/transitions/resume.d.ts +4 -0
  268. package/dist/transitions/resume.js +32 -0
  269. package/dist/transitions/scheduledRound.d.ts +18 -0
  270. package/dist/transitions/scheduledRound.js +42 -0
  271. package/dist/transitions/start.d.ts +4 -0
  272. package/dist/transitions/start.js +136 -55
  273. package/dist/transitions/startReads.d.ts +14 -0
  274. package/dist/transitions/startReads.js +27 -0
  275. package/dist/transitions/stop.d.ts +10 -0
  276. package/dist/transitions/stop.js +35 -22
  277. package/dist/types/admin.d.ts +1 -1
  278. package/dist/types/contracts.d.ts +7 -1
  279. package/dist/types/endpoints.d.ts +72 -3
  280. package/dist/types/manifest.d.ts +9 -0
  281. package/dist/types/runtime.d.ts +5 -0
  282. package/dist/types/snapshot.d.ts +10 -0
  283. package/dist/types/status.d.ts +1 -0
  284. package/dist/types/status.js +1 -0
  285. package/dist/types/surface.d.ts +1 -0
  286. package/dist/ui/Feedback.d.ts +9 -6
  287. package/dist/ui/Feedback.js +10 -9
  288. package/dist/ui/SelectControl.js +1 -1
  289. package/dist/ui/ui.css +2 -1
  290. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  import { commitTransaction, killTransaction } from 'payload';
2
2
  import { assertReadCommitted, initTransitionTransaction } from '../db/adapter.js';
3
- import { pooledExecutor, txExecutor } from '../db/executor.js';
3
+ import { pooledExecutor, setTransitionTimeout, txExecutor } from '../db/executor.js';
4
4
  import { lockTransitionScope } from '../db/locks.js';
5
5
  import { currentTxid, txidStatus } from '../db/txid.js';
6
6
  import { contentChangeSavepoint } from '../db/appends.js';
@@ -25,10 +25,11 @@ import { buildAndStoreManifest } from '../manifest/compile.js';
25
25
  const previousTransition = req.context.xpTransition;
26
26
  let borrowedAudit = scope.audit === true && req.transactionID != null;
27
27
  try {
28
- const owns = await initTransitionTransaction(req);
28
+ const owns = await initTransitionTransaction(req, scope.deadline);
29
29
  borrowedAudit = scope.audit === true && !owns;
30
30
  const exec = txExecutor(req);
31
31
  const work = async ()=>{
32
+ if (scope.deadline !== undefined) await setTransitionTimeout(exec, scope.deadline);
32
33
  if (!owns) await assertReadCommitted(req);
33
34
  if (!scope.edit) req.context.xpTransition = true;
34
35
  await lockTransitionScope(exec, scope);
@@ -45,10 +46,12 @@ import { buildAndStoreManifest } from '../manifest/compile.js';
45
46
  }
46
47
  result = audit.result;
47
48
  } else result = await work();
49
+ if (scope.deadline !== undefined) await setTransitionTimeout(exec, scope.deadline);
48
50
  const revision = scope.bump === false ? undefined : (await buildAndStoreManifest(req, {
49
51
  excludeIds: scope.excludeIds
50
52
  })).revision;
51
53
  if (owns) {
54
+ if (scope.deadline !== undefined) await setTransitionTimeout(exec, scope.deadline);
52
55
  const xid = await currentTxid(exec);
53
56
  await commitTransaction(req);
54
57
  const status = await txidStatus(pooledExecutor(req.payload), xid);
@@ -0,0 +1,4 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { PauseBody, TransitionSuccess } from '../types/endpoints.js';
4
+ export declare function pauseExperiment(req: PayloadRequest, id: DocId, { reason, phase: expectedPhase }: PauseBody): Promise<TransitionSuccess>;
@@ -0,0 +1,35 @@
1
+ import { readPhaseRecord, requireCurrentRound, updatePhaseRecord } from './phaseRecord.js';
2
+ import { requireStarted, withScheduledRound } from './scheduledRound.js';
3
+ import { refuse, updateExperiment } from './start.js';
4
+ export async function pauseExperiment(req, id, { reason, phase: expectedPhase }) {
5
+ if (reason !== undefined && (typeof reason !== 'string' || reason.length > 500)) refuse('invalid-body');
6
+ return withScheduledRound(req, id, async (req, _exec, current)=>{
7
+ requireCurrentRound(expectedPhase, current.phase);
8
+ const now = new Date();
9
+ if (current.status !== 'running' && current.status !== 'decided') refuse('not-live');
10
+ requireStarted(current.startedAt, now);
11
+ const phase = await readPhaseRecord(req, id, current.phase);
12
+ if (phase.phaseKind === 'rollout') refuse('not-pausable');
13
+ if (current.status !== 'running') refuse('not-live');
14
+ const from = now.toISOString();
15
+ const by = String(req.user.id);
16
+ await updatePhaseRecord(req, phase.id, {
17
+ pauses: [
18
+ ...phase.pauses,
19
+ {
20
+ from,
21
+ by,
22
+ ...reason !== undefined ? {
23
+ reason
24
+ } : {}
25
+ }
26
+ ]
27
+ });
28
+ return updateExperiment(req, id, {
29
+ status: 'paused',
30
+ pausedAt: from,
31
+ pausedBy: by,
32
+ pauseReason: reason ?? null
33
+ });
34
+ });
35
+ }
@@ -1,6 +1,8 @@
1
+ import type { FrozenCohortRule } from '../cohorts/rule.js';
1
2
  import type { PayloadRequest } from 'payload';
2
3
  import type { Arm, DocId, TargetingRule } from '../types/contracts.js';
3
4
  import type { AllocationChange, ContentChange } from '../db/appends.js';
5
+ import type { ExperimentSchedule, PauseInterval } from '../schedule/types.js';
4
6
  /** Check the round after acquiring the experiment lock and before writing. */
5
7
  export declare function requireCurrentRound(expected: number | undefined, current: number | undefined): void;
6
8
  export interface PhaseRecord {
@@ -13,23 +15,38 @@ export interface PhaseRecord {
13
15
  arms: Arm[];
14
16
  allocation: number;
15
17
  allocationChanges?: AllocationChange[];
16
- targeting: TargetingRule[];
18
+ targeting: Array<TargetingRule | FrozenCohortRule>;
17
19
  metricDefinitions?: Array<Record<string, unknown>>;
18
20
  analysis?: Record<string, unknown> & {
19
21
  sequentialTuningParameter?: number | null;
22
+ beforeSchedule?: {
23
+ arms?: Arm[];
24
+ timeZone?: string | null;
25
+ };
20
26
  };
21
27
  placementDocs?: import('../db/placements.js').PlacementDoc[] | null;
22
28
  contentChanges?: ContentChange[];
29
+ pauses: PauseInterval[];
30
+ schedule?: ExperimentSchedule;
31
+ scheduleChanges: Array<{
32
+ at: string;
33
+ from: string | null;
34
+ to: string | null;
35
+ by: string;
36
+ }>;
23
37
  }
24
38
  export declare function readPhaseRecord(req: PayloadRequest, experimentId: DocId, phase: number): Promise<PhaseRecord & {
25
39
  id: DocId;
26
40
  }>;
27
41
  /** Caller holds the experiment lock and passes the kernel's transaction req. */
28
- export declare function writePhaseRecord(req: PayloadRequest, record: PhaseRecord & {
42
+ export declare function writePhaseRecord(req: PayloadRequest, record: Omit<PhaseRecord, 'pauses' | 'scheduleChanges'> & Partial<Pick<PhaseRecord, 'pauses' | 'scheduleChanges'>> & {
29
43
  analysis: Record<string, unknown> & {
30
44
  sequentialTuningParameter: number;
31
45
  };
32
46
  }): Promise<import("payload").JsonObject & import("payload").TypeWithID>;
47
+ export declare function readLatestPhase(req: PayloadRequest, experimentId: DocId): Promise<Pick<PhaseRecord, "phase" | "seed" | "startedAt" | "endedAt"> | undefined>;
48
+ export declare function latestPhaseNumber(req: PayloadRequest, experimentId: DocId): Promise<number>;
49
+ export declare function updatePhaseRecord(req: PayloadRequest, id: DocId, data: Partial<Pick<PhaseRecord, 'pauses' | 'schedule' | 'scheduleChanges' | 'endedAt'>>): Promise<import("payload").JsonObject & import("payload").TypeWithID>;
33
50
  /** End only an open phase, preserving the original stop time on a later decide.
34
51
  * Caller holds the experiment lock and passes the kernel's transaction req.
35
52
  */
@@ -31,14 +31,60 @@ export async function readPhaseRecord(req, experimentId, phase) {
31
31
  experimentId,
32
32
  phase
33
33
  }, 404);
34
- return docs[0];
34
+ const record = docs[0];
35
+ return {
36
+ ...record,
37
+ pauses: record.pauses ?? [],
38
+ schedule: record.schedule ?? undefined,
39
+ scheduleChanges: record.scheduleChanges ?? []
40
+ };
35
41
  }
36
42
  /** Caller holds the experiment lock and passes the kernel's transaction req. */ export async function writePhaseRecord(req, record) {
37
43
  // §7.8: transition endpoints' writes to plugin collections.
38
44
  return req.payload.create({
39
45
  collection: 'xp-phases',
40
- data: record,
46
+ data: {
47
+ ...record,
48
+ pauses: record.pauses ?? [],
49
+ scheduleChanges: record.scheduleChanges ?? []
50
+ },
51
+ req,
52
+ overrideAccess: true
53
+ });
54
+ }
55
+ export async function readLatestPhase(req, experimentId) {
56
+ // §7.8: Start and Cancel schedule read phase history inside the authorized transition.
57
+ const { docs } = await req.payload.find({
58
+ collection: 'xp-phases',
59
+ req,
60
+ overrideAccess: true,
61
+ depth: 0,
62
+ limit: 1,
63
+ select: {
64
+ phase: true,
65
+ seed: true,
66
+ startedAt: true,
67
+ endedAt: true
68
+ },
69
+ where: {
70
+ experiment: {
71
+ equals: experimentId
72
+ }
73
+ },
74
+ sort: '-phase'
75
+ });
76
+ return docs[0];
77
+ }
78
+ export async function latestPhaseNumber(req, experimentId) {
79
+ return Number((await readLatestPhase(req, experimentId))?.phase ?? 0);
80
+ }
81
+ export async function updatePhaseRecord(req, id, data) {
82
+ // §7.8: the authorized transition writes the phase audit or close under the experiment lock.
83
+ return req.payload.update({
84
+ collection: 'xp-phases',
41
85
  req,
86
+ id,
87
+ data,
42
88
  overrideAccess: true
43
89
  });
44
90
  }
@@ -73,14 +119,7 @@ export async function readPhaseRecord(req, experimentId, phase) {
73
119
  phase
74
120
  }, 404);
75
121
  if (record.endedAt) return record;
76
- // §7.8: transition endpoints' writes to plugin collections.
77
- return req.payload.update({
78
- collection: 'xp-phases',
79
- req,
80
- id: record.id,
81
- data: {
82
- endedAt: at
83
- },
84
- overrideAccess: true
122
+ return updatePhaseRecord(req, record.id, {
123
+ endedAt: at
85
124
  });
86
125
  }
@@ -53,7 +53,7 @@ export async function placementPaths(req, options, docs) {
53
53
  ...paths
54
54
  ]);
55
55
  }
56
- const active = (test)=>test.status === 'running' || test.status === 'decided';
56
+ const active = (test)=>test.status === 'running' || test.status === 'paused' || test.status === 'decided';
57
57
  export async function placementInteractions(req, exec, options, experiment, paths, system = false) {
58
58
  const result = [];
59
59
  for (const test of (await placementTests(exec))){
@@ -16,7 +16,9 @@ export declare function loadStartInputs<TUser extends {
16
16
  }>(req: PayloadRequest, options: ResolvedOptions<TUser>, experimentId: DocId, system?: boolean): Promise<CheckStartInput | null>;
17
17
  /** Occupancy from the arms the runtime routes on (frozen rounds), shared by preflight and
18
18
  * Start's locked recheck. Raw SQL on the request's transaction when there is one. */
19
- export declare function loadPageTestsInUse(req: PayloadRequest): Promise<NonNullable<CheckStartInput['pageTestsInUse']>>;
19
+ export declare function loadPageTestsInUse(req: PayloadRequest): Promise<(import("../db/occupancy.js").OccupancyRow & {
20
+ arms: import("../types/contracts.js").Arm[];
21
+ })[]>;
20
22
  /** Page targets no registered collection reports as published. A lookup that throws counts as
21
23
  * unpublished (logged) unless propagateErrors is requested by decide. Start calls it again under its page-path locks on a detached request. */
22
24
  export declare function unpublishedPageTargets<TUser extends {
@@ -27,11 +29,17 @@ export declare function unpublishedPageTargets<TUser extends {
27
29
  */
28
30
  export declare function loadStartInputsBatch<TUser extends {
29
31
  id: DocId;
30
- }>(req: PayloadRequest, options: ResolvedOptions<TUser>, experiments: StartExperiment[], tolerateErrors?: boolean, system?: boolean): Promise<Map<string, CheckStartInput | null>>;
32
+ }>(req: PayloadRequest, options: ResolvedOptions<TUser>, experiments: StartExperiment[], tolerateErrors?: boolean, system?: boolean, { checkOccupancy, now, readCohorts }?: {
33
+ checkOccupancy?: boolean | undefined;
34
+ now?: Date | undefined;
35
+ readCohorts?: boolean | undefined;
36
+ }): Promise<Map<string, CheckStartInput | null>>;
31
37
  export declare function preflightData<TUser extends {
32
38
  id: DocId;
33
- }>(req: PayloadRequest, { experimentId, options, placementLocale }: {
39
+ }>(req: PayloadRequest, { experimentId, options, placementLocale, viewingReq, seenPause }: {
34
40
  experimentId: DocId;
35
41
  options: ResolvedOptions<TUser>;
36
42
  placementLocale?: string;
43
+ viewingReq?: PayloadRequest;
44
+ seenPause?: string | null;
37
45
  }, { now, estimate }?: PreflightDependencies): Promise<PreflightResult | null>;
@@ -1,3 +1,8 @@
1
+ import { savedCohortSources } from '../endpoints/cohortSources.js';
2
+ import { readPauseAttributions } from '../endpoints/pausedBy.js';
3
+ import { isCohortRule, readCohortRule } from '../cohorts/rule.js';
4
+ import { cohortRuleSummary } from '../testSurface/copy/cohorts.js';
5
+ import { loadCohortFacts } from '../cohorts/readinessData.js';
1
6
  import { findDraftPageByPath } from './pageAddress.js';
2
7
  import { nestedPlacementNames, nameNestedPlacements } from './nestedPlacementNames.js';
3
8
  import { placementReader } from '../blocks/placementLocale.js';
@@ -12,11 +17,16 @@ import { resolvePageCollection } from './pageCollection.js';
12
17
  import { identicalPageVersions } from './pageVersions.js';
13
18
  import { safeError } from '../log.js';
14
19
  import { powerMetricWeeks } from '@delmaredigital/experiments-stats';
15
- import { checkStart, relationshipId } from './checkStart.js';
20
+ import { activeWeek } from '../schedule/activeTime.js';
21
+ import { checkStart, pageTargetPaths, relationshipId } from './checkStart.js';
16
22
  import { flagPlacements, scanBlockPlacements } from './placements.js';
17
23
  import { routedPageTests } from '../db/pageOccupancy.js';
18
24
  import { pooledExecutor, txExecutor } from '../db/executor.js';
19
- import { findStartDocuments, readStartState } from './startReads.js';
25
+ import { findStartDocuments, readStartPeers, readStartState } from './startReads.js';
26
+ import { occupancyDetail, overlapsClaim } from '../db/occupancy.js';
27
+ import { currentRoundTiming } from '../db/snapshots.js';
28
+ import { publicRoundTiming } from '../schedule/roundTime.js';
29
+ import { claimRange } from '../schedule/ranges.js';
20
30
  const failureDetail = (cause)=>{
21
31
  const name = cause instanceof Error ? cause.name : undefined;
22
32
  return cause instanceof Forbidden || name === 'Forbidden' ? 'forbidden' : cause instanceof NotFound || name === 'NotFound' ? 'not-found' : 'placements-failed';
@@ -79,7 +89,7 @@ const metricIds = (experiment)=>[
79
89
  ].map(relationshipId).filter((id)=>id !== undefined);
80
90
  /** Shared, request-scoped reads for summary; a failed row is null in tolerant mode.
81
91
  * Preflight/Start use the same builder and retain their throwing read behaviour.
82
- */ export async function loadStartInputsBatch(req, options, experiments, tolerateErrors = false, system = false) {
92
+ */ export async function loadStartInputsBatch(req, options, experiments, tolerateErrors = false, system = false, { checkOccupancy = true, now = new Date(), readCohorts = true } = {}) {
83
93
  const ids = [
84
94
  ...new Set(experiments.flatMap(metricIds))
85
95
  ];
@@ -105,11 +115,16 @@ const metricIds = (experiment)=>[
105
115
  let nestedNames;
106
116
  let state;
107
117
  const busyPoints = new Map();
118
+ const layerPeers = new Map();
108
119
  const layers = new Map();
109
120
  const inputs = new Map();
110
121
  for (const experiment of experiments){
111
122
  try {
112
123
  const ownIds = new Set(metricIds(experiment).map(String));
124
+ const claim = claimRange({
125
+ startedAt: now,
126
+ schedule: experiment.schedule
127
+ });
113
128
  const localization = req.payload.config.localization;
114
129
  const input = {
115
130
  placementLocaleCodes: localization ? localization.localeCodes : undefined,
@@ -121,6 +136,9 @@ const metricIds = (experiment)=>[
121
136
  flagPoints: options.flagPoints,
122
137
  attributeKeys: options.attributeKeys
123
138
  };
139
+ if (readCohorts && experiment.targeting?.some(isCohortRule)) {
140
+ input.cohortFacts = await loadCohortFacts(req, pooledExecutor(req.payload), experiment, options, system, now);
141
+ }
124
142
  const placementFailure = (cause)=>{
125
143
  const collection = experiment.flagPoint ?? 'xp-experiments';
126
144
  req.payload.logger.error({
@@ -132,8 +150,14 @@ const metricIds = (experiment)=>[
132
150
  return failureDetail(cause);
133
151
  };
134
152
  if (experiment.kind === 'page') {
135
- pageTestsInUse ??= loadPageTestsInUse(req);
136
- input.pageTestsInUse = await pageTestsInUse;
153
+ if (checkOccupancy) {
154
+ pageTestsInUse ??= loadPageTestsInUse(req);
155
+ const paths = new Set(pageTargetPaths(experiment.arms));
156
+ const peers = (await pageTestsInUse).filter((peer)=>String(peer.id) !== String(experiment.id) && overlapsClaim(peer, claim));
157
+ input.pageTestsInUse = peers;
158
+ const peer = peers.find((row)=>pageTargetPaths(row.arms).some((path)=>paths.has(path)));
159
+ if (peer?.name) input.pageOccupancy = occupancyDetail(peer, 'page');
160
+ }
137
161
  input.pageTargetsUnchecked = options.pages === undefined;
138
162
  input.unknownPageCollection = Boolean(experiment.pageCollection && !options.pages?.collections.some((entry)=>entry.slug === experiment.pageCollection));
139
163
  if (options.pages) {
@@ -190,35 +214,16 @@ const metricIds = (experiment)=>[
190
214
  input.flagPlacementError = placementFailure(cause);
191
215
  }
192
216
  }
193
- if (experiment.flagPoint) {
217
+ if (checkOccupancy && experiment.flagPoint) {
194
218
  const key = experiment.flagPoint;
195
- if (!busyPoints.has(key)) busyPoints.set(key, (async ()=>{
196
- // Two rows suffice to find a peer, including when the batch contains that peer.
197
- const busy = await findStartDocuments(req, {
198
- collection: 'xp-experiments',
199
- depth: 0,
200
- limit: 2,
201
- where: {
202
- and: [
203
- {
204
- flagPoint: {
205
- equals: key
206
- }
207
- },
208
- {
209
- status: {
210
- in: [
211
- 'running',
212
- 'decided'
213
- ]
214
- }
215
- }
216
- ]
217
- }
218
- }, system);
219
- return busy.docs;
220
- })());
221
- input.flagPointBusy = (await busyPoints.get(key)).some((doc)=>String(doc.id) !== String(experiment.id));
219
+ if (!busyPoints.has(key)) busyPoints.set(key, readStartPeers(req, {
220
+ flagPoint: {
221
+ equals: key
222
+ }
223
+ }, system));
224
+ const peer = (await busyPoints.get(key)).find((doc)=>String(doc.id) !== String(experiment.id) && overlapsClaim(doc, claim));
225
+ input.flagPointBusy = Boolean(peer);
226
+ if (peer?.name) input.flagOccupancy = occupancyDetail(peer, 'setting');
222
227
  }
223
228
  }
224
229
  const layerId = relationshipId(experiment.layer);
@@ -235,43 +240,24 @@ const metricIds = (experiment)=>[
235
240
  }
236
241
  }
237
242
  }, system);
238
- const layer = result.docs[0];
239
- const usedSlices = [];
240
- let page = 1;
241
- while(true){
242
- const usage = await findStartDocuments(req, {
243
- collection: 'xp-experiments',
244
- depth: 0,
245
- limit: 100,
246
- page,
247
- where: {
248
- and: [
249
- {
250
- layer: {
251
- equals: layerId
252
- }
253
- },
254
- {
255
- status: {
256
- in: [
257
- 'running',
258
- 'decided'
259
- ]
260
- }
261
- }
262
- ]
263
- }
264
- }, system);
265
- for (const doc of usage.docs)if (Array.isArray(doc.layerSlices)) usedSlices.push(...doc.layerSlices);
266
- if (!usage.hasNextPage) break;
267
- page++;
268
- }
269
- return layer ? {
270
- unitType: layer.unitType,
271
- usedSlices
272
- } : null;
243
+ return result.docs[0]?.unitType;
273
244
  })());
274
- input.layer = await layers.get(key);
245
+ const unitType = await layers.get(key);
246
+ if (unitType && checkOccupancy && !layerPeers.has(key)) layerPeers.set(key, readStartPeers(req, {
247
+ layer: {
248
+ equals: layerId
249
+ }
250
+ }, system));
251
+ const peers = (await layerPeers.get(key))?.filter((peer)=>String(peer.id) !== String(experiment.id) && overlapsClaim(peer, claim)) ?? [];
252
+ const usedSlices = peers.flatMap((peer)=>peer.layerSlices ?? []);
253
+ const occupyingPeer = peers.find((peer)=>peer.layerSlices?.length);
254
+ if (occupyingPeer?.name && 100 - new Set(usedSlices).size < experiment.allocation) {
255
+ input.layerOccupancy = occupancyDetail(occupyingPeer, 'traffic group');
256
+ }
257
+ input.layer = unitType ? {
258
+ unitType,
259
+ usedSlices
260
+ } : null;
275
261
  }
276
262
  if ((experiment.kind === 'page' || experiment.kind === 'block') && options.pages?.collections.length) {
277
263
  const paths = experiment.kind === 'page' ? experiment.arms.flatMap((a)=>typeof a.pageTarget === 'string' ? [
@@ -386,8 +372,13 @@ async function primaryHistory(source, now) {
386
372
  return null;
387
373
  }
388
374
  }
389
- export async function preflightData(req, { experimentId, options, placementLocale }, { now = new Date(), estimate = powerMetricWeeks } = {}) {
390
- const input = await loadStartInputs(req, options, experimentId);
375
+ export async function preflightData(req, { experimentId, options, placementLocale, viewingReq = req, seenPause }, { now = new Date(), estimate = powerMetricWeeks } = {}) {
376
+ const experiment = await readStartInputExperiment(req, experimentId);
377
+ const input = experiment && (await loadStartInputsBatch(req, options, [
378
+ experiment
379
+ ], false, false, {
380
+ now
381
+ })).get(String(experiment.id));
391
382
  if (!input) return null;
392
383
  // Advisory title selection never changes the request used by scans or host adapters.
393
384
  if (placementLocale !== undefined) input.placementLocale = placementLocale;
@@ -408,16 +399,18 @@ export async function preflightData(req, { experimentId, options, placementLocal
408
399
  };
409
400
  let power = null;
410
401
  if (trafficPerDay !== null && baseline && source && history) {
402
+ const week = activeWeek(e.schedule?.windows ?? []);
411
403
  const compared = e.arms.filter((arm)=>arm.kind !== 'holdout');
412
404
  const control = compared.find((arm)=>arm.kind === 'control');
413
405
  const variant = compared.find((arm)=>arm.kind === 'variant');
414
406
  const planned = 14;
415
- const enrolled = trafficPerDay * e.allocation / 100;
407
+ const enrolledPerWeek = trafficPerDay / 24 * week.hours * e.allocation / 100;
408
+ const enrolledPerActiveDay = enrolledPerWeek / week.days;
416
409
  const pairShare = ((control?.weight ?? 0) + (variant?.weight ?? 0)) / 100;
417
- const tuning = enrolled * planned * pairShare;
410
+ const tuning = enrolledPerActiveDay * planned * pairShare;
418
411
  // Power's equal-arm model uses the smallest compared arm, so unequal weights
419
412
  // and holdout traffic never overstate the information in a comparison.
420
- const usersPerWeek = enrolled * 7 * Math.min(...compared.map((arm)=>arm.weight / 100)) * compared.length;
413
+ const usersPerWeek = enrolledPerWeek * Math.min(...compared.map((arm)=>arm.weight / 100)) * compared.length;
421
414
  const n = Math.max(trafficPerDay * 28, history.length);
422
415
  const mean = history.reduce((sum, value)=>sum + value, 0) / n;
423
416
  const variance = history.reduce((sum, value)=>sum + value * value, 0) / n - mean * mean;
@@ -436,12 +429,13 @@ export async function preflightData(req, { experimentId, options, placementLocal
436
429
  if (control && variant && usersPerWeek > 0 && tuning > 0 && (source.kind !== 'binomial' || conversionRate > 0 && conversionRate < 1) && (source.kind === 'binomial' || mean > 0)) {
437
430
  try {
438
431
  const alpha = e.analysis?.method === 'bayesian' ? 0.05 : 0.05 / Math.max(1, compared.filter((arm)=>arm.kind === 'variant').length);
432
+ const nWeeks = Math.ceil(90 / week.days);
439
433
  const estimateAt = (sequentialTuningParameter)=>estimate({
440
434
  metrics: {
441
435
  primary: params
442
436
  },
443
437
  nVariations: compared.length,
444
- nWeeks: 13,
438
+ nWeeks,
445
439
  alpha,
446
440
  usersPerWeek,
447
441
  targetPower: 0.8,
@@ -453,17 +447,17 @@ export async function preflightData(req, { experimentId, options, placementLocal
453
447
  }
454
448
  });
455
449
  let result = await estimateAt(tuning);
456
- let weeks = result.sampleSizeAndRuntime.primary?.weeks ?? result.weekThreshold ?? 13;
457
- const plannedDurationDays = Math.ceil(weeks * 7);
458
- const sequentialTuningParameter = enrolled * plannedDurationDays * pairShare;
450
+ let weeks = result.sampleSizeAndRuntime.primary?.weeks ?? result.weekThreshold ?? nWeeks;
451
+ const plannedDurationDays = Math.ceil(weeks * week.days);
452
+ const sequentialTuningParameter = enrolledPerActiveDay * plannedDurationDays * pairShare;
459
453
  // Re-evaluate using exactly the power-derived duration and tuning Apply will save.
460
454
  result = await estimateAt(sequentialTuningParameter);
461
- weeks = result.sampleSizeAndRuntime.primary?.weeks ?? result.weekThreshold ?? 13;
455
+ weeks = result.sampleSizeAndRuntime.primary?.weeks ?? result.weekThreshold ?? nWeeks;
462
456
  power = {
463
457
  weeks,
464
458
  plannedDurationDays,
465
459
  sequentialTuningParameter,
466
- feasible: Number.isFinite(weeks) && weeks * 7 <= 90 && result.sampleSizeAndRuntime.primary !== undefined
460
+ feasible: Number.isFinite(weeks) && weeks * week.days <= 90 && result.sampleSizeAndRuntime.primary !== undefined
467
461
  };
468
462
  } catch {}
469
463
  }
@@ -685,13 +679,72 @@ export async function preflightData(req, { experimentId, options, placementLocal
685
679
  });
686
680
  }
687
681
  }
682
+ const cohortSummaries = (e.targeting ?? []).flatMap((row, index)=>{
683
+ const rule = readCohortRule(row);
684
+ const fact = input.cohortFacts?.rules.get(index);
685
+ if (!rule || !fact?.source) return [];
686
+ const phase = fact.source.phase;
687
+ const goal = phase.metricDefinitions?.find((definition)=>String(definition.metricId) === rule.goal?.metricId)?.name;
688
+ const summary = cohortRuleSummary(rule, {
689
+ experiment: fact.sourceName,
690
+ arms: Object.fromEntries(phase.arms.map((arm)=>[
691
+ arm.key,
692
+ arm.label
693
+ ])),
694
+ goal
695
+ });
696
+ return [
697
+ {
698
+ rule,
699
+ summary
700
+ }
701
+ ];
702
+ });
703
+ const sourceIds = [
704
+ ...new Set((e.targeting ?? []).flatMap((row)=>{
705
+ const rule = readCohortRule(row);
706
+ return rule ? [
707
+ rule.experiment
708
+ ] : [];
709
+ }))
710
+ ].filter((id)=>id !== String(e.id));
711
+ const cohortSources = sourceIds.length ? await savedCohortSources(req, options, sourceIds) : [];
712
+ const [timing] = e.status === 'paused' ? await currentRoundTiming(pooledExecutor(req.payload), [
713
+ e.id
714
+ ]) : [];
715
+ const pausedAt = e.status === 'paused' ? e.pausedAt ?? null : undefined;
716
+ const pauseLookupSkipped = pausedAt !== undefined && seenPause === (pausedAt ?? '');
717
+ const pauseAttribution = pausedAt !== undefined && !pauseLookupSkipped ? (await readPauseAttributions(viewingReq, [
718
+ e
719
+ ])).get(String(e.id)) : undefined;
688
720
  return {
721
+ ...cohortSources.length ? {
722
+ cohortSources
723
+ } : {},
724
+ ...cohortSummaries.length ? {
725
+ cohortSummaries
726
+ } : {},
689
727
  document: {
690
728
  status: e.status,
691
729
  phase: e.phase,
692
- updatedAt: e.updatedAt
730
+ updatedAt: e.updatedAt,
731
+ ...pausedAt === undefined ? {} : {
732
+ pausedAt
733
+ }
693
734
  },
735
+ ...pauseAttribution ? {
736
+ pauseAttribution
737
+ } : {},
738
+ ...pauseLookupSkipped ? {
739
+ pauseLookupSkipped: true
740
+ } : {},
741
+ ...timing && Number(timing.phase) === e.phase ? {
742
+ timing: publicRoundTiming(timing)
743
+ } : {},
694
744
  checks: checkStart(input),
745
+ ...e.schedule?.windows?.length && (e.schedule.timeZone || options.timeZone) ? {
746
+ scheduleTimeZone: e.schedule.timeZone || options.timeZone
747
+ } : {},
695
748
  ...metric && browserWritableMetric(metric.source, options) ? {
696
749
  browserWritablePrimaryId: metric.id
697
750
  } : {},
@@ -0,0 +1,4 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { RescheduleBody, TransitionSuccess } from '../types/endpoints.js';
4
+ export declare function rescheduleExperiment(req: PayloadRequest, id: DocId, { endAt, phase: expectedPhase }: RescheduleBody): Promise<TransitionSuccess>;
@@ -0,0 +1,58 @@
1
+ import { storedClaim } from '../db/occupancy.js';
2
+ import { readPhaseRecord, requireCurrentRound, updatePhaseRecord } from './phaseRecord.js';
3
+ import { checkRoundClaim, withScheduledRound } from './scheduledRound.js';
4
+ import { refuse, updateExperiment } from './start.js';
5
+ export async function rescheduleExperiment(req, id, { endAt, phase: expectedPhase }) {
6
+ const end = endAt === null ? null : new Date(endAt);
7
+ if (end !== null && (typeof endAt !== 'string' || !Number.isFinite(+end))) refuse('invalid-body', {
8
+ field: 'schedule.endAt'
9
+ });
10
+ return withScheduledRound(req, id, async (req, exec, current)=>{
11
+ requireCurrentRound(expectedPhase, current.phase);
12
+ if (current.status !== 'running' && current.status !== 'paused') refuse('invalid-status');
13
+ const phase = await readPhaseRecord(req, id, current.phase);
14
+ if (end !== null && (end <= new Date() || end <= new Date(phase.startedAt))) refuse('reschedule-past', {
15
+ field: 'schedule.endAt'
16
+ });
17
+ await checkRoundClaim(exec, current, {
18
+ ...storedClaim(current),
19
+ to: end
20
+ });
21
+ const now = new Date();
22
+ if (end !== null && end <= now) refuse('reschedule-past', {
23
+ field: 'schedule.endAt'
24
+ });
25
+ const to = end?.toISOString() ?? null;
26
+ const options = req.payload.config.custom?.xp;
27
+ // An end-only schedule has no wall-clock windows. UTC supplies the zone if none was configured.
28
+ const timeZone = phase.schedule?.timeZone || current.schedule?.timeZone || options.timeZone || 'UTC';
29
+ const schedule = {
30
+ ...phase.schedule,
31
+ windows: phase.schedule?.windows ?? [],
32
+ timeZone
33
+ };
34
+ if (to === null) delete schedule.endAt;
35
+ else schedule.endAt = to;
36
+ const entry = {
37
+ at: now.toISOString(),
38
+ from: phase.schedule?.endAt ?? null,
39
+ to,
40
+ by: String(req.user.id)
41
+ };
42
+ await updatePhaseRecord(req, phase.id, {
43
+ schedule,
44
+ scheduleChanges: [
45
+ ...phase.scheduleChanges,
46
+ entry
47
+ ]
48
+ });
49
+ return updateExperiment(req, id, {
50
+ schedule: {
51
+ ...current.schedule,
52
+ timeZone,
53
+ endAt: to
54
+ },
55
+ claimTo: to
56
+ });
57
+ });
58
+ }
@@ -0,0 +1,4 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { RoundBody, TransitionSuccess } from '../types/endpoints.js';
4
+ export declare function resumeExperiment(req: PayloadRequest, id: DocId, { phase: expectedPhase }?: RoundBody): Promise<TransitionSuccess>;