@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
@@ -0,0 +1,32 @@
1
+ import { storedClaim } from '../db/occupancy.js';
2
+ import { readPhaseRecord, requireCurrentRound, updatePhaseRecord } from './phaseRecord.js';
3
+ import { checkRoundClaim, clearPauseFields, withScheduledRound } from './scheduledRound.js';
4
+ import { stopRound } from './stop.js';
5
+ import { refuse, updateExperiment } from './start.js';
6
+ export async function resumeExperiment(req, id, { phase: expectedPhase } = {}) {
7
+ return withScheduledRound(req, id, async (req, exec, current)=>{
8
+ requireCurrentRound(expectedPhase, current.phase);
9
+ if (current.status !== 'paused') refuse('invalid-status');
10
+ const phase = await readPhaseRecord(req, id, current.phase);
11
+ const endAt = phase.schedule?.endAt ? new Date(phase.schedule.endAt) : null;
12
+ if (endAt && endAt <= new Date()) return stopRound(req, current, endAt.toISOString());
13
+ await checkRoundClaim(exec, current, storedClaim(current));
14
+ const now = new Date();
15
+ if (endAt && endAt <= now) return stopRound(req, current, endAt.toISOString());
16
+ const open = phase.pauses.at(-1);
17
+ if (!open || open.to !== undefined) refuse('invalid-phase');
18
+ await updatePhaseRecord(req, phase.id, {
19
+ pauses: [
20
+ ...phase.pauses.slice(0, -1),
21
+ {
22
+ ...open,
23
+ to: now.toISOString()
24
+ }
25
+ ]
26
+ });
27
+ return updateExperiment(req, id, {
28
+ status: 'running',
29
+ ...clearPauseFields
30
+ });
31
+ });
32
+ }
@@ -0,0 +1,18 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import { type Executor } from '../db/executor.js';
3
+ import type { Claim } from '../schedule/ranges.js';
4
+ import type { DocId } from '../types/contracts.js';
5
+ import { type TransitionExperiment } from './start.js';
6
+ /** Status and claim checks use the document read after acquiring the transition locks. */
7
+ export declare function withScheduledRound<T>(req: PayloadRequest, id: DocId, apply: (req: PayloadRequest, exec: Executor, current: TransitionExperiment) => Promise<T>, deadline?: number): Promise<{
8
+ doc: T;
9
+ revision: number;
10
+ }>;
11
+ export declare function startsInFuture(startedAt: string | null | undefined, now: Date): boolean;
12
+ export declare function requireStarted(startedAt: string | null | undefined, now: Date): void;
13
+ export declare function checkRoundClaim(exec: Executor, current: TransitionExperiment, claim: Claim): Promise<void>;
14
+ export declare const clearPauseFields: {
15
+ readonly pausedAt: null;
16
+ readonly pausedBy: null;
17
+ readonly pauseReason: null;
18
+ };
@@ -0,0 +1,42 @@
1
+ import { lockPagePaths } from '../db/locks.js';
2
+ import { raceDeadline } from '../db/executor.js';
3
+ import { assertNoOverlap } from './assertNoOverlap.js';
4
+ import { pageTargetPaths, relationshipId } from './checkStart.js';
5
+ import { withTransition } from './kernel.js';
6
+ import { readExperiment, refuse } from './start.js';
7
+ /** Status and claim checks use the document read after acquiring the transition locks. */ export async function withScheduledRound(req, id, apply, deadline) {
8
+ const before = await (deadline === undefined ? readExperiment(req, id) : raceDeadline(deadline, ()=>readExperiment(req, id)));
9
+ const flagPointId = before.kind === 'flag' ? before.flagPoint : undefined;
10
+ const { result: doc, revision } = await withTransition(req, {
11
+ experimentId: id,
12
+ layerId: relationshipId(before.layer),
13
+ flagPointId,
14
+ ...deadline === undefined ? {} : {
15
+ deadline,
16
+ requireOwnedTransaction: true
17
+ }
18
+ }, async ({ req, exec })=>{
19
+ const current = await readExperiment(req, id);
20
+ if (current.kind === 'flag' && current.flagPoint !== flagPointId) refuse('stale-edit');
21
+ return apply(req, exec, current);
22
+ });
23
+ return {
24
+ doc,
25
+ revision: revision
26
+ };
27
+ }
28
+ export function startsInFuture(startedAt, now) {
29
+ return startedAt != null && new Date(startedAt) > now;
30
+ }
31
+ export function requireStarted(startedAt, now) {
32
+ if (startsInFuture(startedAt, now)) refuse('not-live');
33
+ }
34
+ export async function checkRoundClaim(exec, current, claim) {
35
+ if (current.kind === 'page') await lockPagePaths(exec, pageTargetPaths(current.arms));
36
+ await assertNoOverlap(exec, current, claim);
37
+ }
38
+ export const clearPauseFields = {
39
+ pausedAt: null,
40
+ pausedBy: null,
41
+ pauseReason: null
42
+ };
@@ -5,6 +5,10 @@ import { type StartExperiment } from './checkStart.js';
5
5
  export type TransitionExperiment = StartExperiment & Record<string, unknown> & {
6
6
  seed?: string;
7
7
  layerSlices?: number[] | null;
8
+ claimFrom?: string | null;
9
+ claimTo?: string | null;
10
+ startedAt?: string | null;
11
+ pausedAt?: string | null;
8
12
  };
9
13
  export declare function readExperiment(req: PayloadRequest, id: DocId): Promise<TransitionExperiment>;
10
14
  export declare function refuse(code: RefusalCode, detail?: unknown, controlLabel?: string): never;
@@ -1,3 +1,10 @@
1
+ import { isCohortTimeout, withCohortTimeout } from '../db/cohorts.js';
2
+ import { isCohortRule } from '../cohorts/rule.js';
3
+ import { checkCohorts, isCohortReadiness } from '../cohorts/readiness.js';
4
+ import { freezeCohortTargeting, loadCohortFacts } from '../cohorts/readinessData.js';
5
+ import { buildStartCohorts, cohortBuildTimeout } from '../cohorts/build.js';
6
+ import { resultsExecutor } from '../db/snapshots.js';
7
+ import { COHORT_COPY } from '../testSurface/copy/cohorts.js';
1
8
  import { withSlotsFor } from '../arms/model.js';
2
9
  import { nestedPlacementNames, nameNestedPlacements } from './nestedPlacementNames.js';
3
10
  import { nestedTestCopy } from '../puck/nestedTestCopy.js';
@@ -7,9 +14,9 @@ import { detached } from './placementInteractions.js';
7
14
  import { lockAndRescanPlacements, placementInteractions } from './placementInteractions.js';
8
15
  import { lockPagePaths } from '../db/locks.js';
9
16
  import { lockMetricsForFreeze } from '../db/metricUsage.js';
10
- import { DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
17
+ import { COHORT_START_BUDGET_MS, DEFAULT_SEQUENTIAL_TUNING_PARAMETER } from '../constants.js';
11
18
  import { claimSlices } from '../db/slices.js';
12
- import { READINESS_COPY, asymmetricGoalsCopy, firstStartOnlyCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
19
+ import { READINESS_COPY, asymmetricGoalsCopy, firstStartOnlyCopy, sameAddressCopy, interactingTestsCopy, pageInUseCopy, scheduleOccupancyCopy, unpublishedPageCopy } from '../testSurface/copy/readiness.js';
13
20
  import { GROUP_LABELS } from '../testSurface/copy/arms.js';
14
21
  import { controlVersionLabel } from '../labels/arms.js';
15
22
  import { XpRefusal } from '../errors.js';
@@ -17,10 +24,13 @@ import { isOpValid } from '../targeting/ops.js';
17
24
  import { newSeed } from '../runtime/seed.js';
18
25
  import { checkStart, pageTargetPaths, relationshipId } from './checkStart.js';
19
26
  import { withTransition } from './kernel.js';
20
- import { requireCurrentRound, writePhaseRecord } from './phaseRecord.js';
21
- import { loadPageTestsInUse, loadStartInputsBatch, readStartInputExperiment, unpublishedPageTargets } from './preflightData.js';
27
+ import { latestPhaseNumber, requireCurrentRound, writePhaseRecord } from './phaseRecord.js';
28
+ import { loadStartInputsBatch, readStartInputExperiment, unpublishedPageTargets } from './preflightData.js';
22
29
  import { resolveCaps } from './resolveCaps.js';
23
- import { findStartDocuments, readStartState } from './startReads.js';
30
+ import { readStartState } from './startReads.js';
31
+ import { assertNoOverlap } from './assertNoOverlap.js';
32
+ import { claimRange } from '../schedule/ranges.js';
33
+ import { isValidTimeZone } from '../schedule/activeTime.js';
24
34
  export async function readExperiment(req, id) {
25
35
  // §7.8: internal lookup serves the authorised transition write. Preserve
26
36
  // admin-only analysis.method/kind for freezing; return access-filtered docs.
@@ -42,6 +52,11 @@ export async function readExperiment(req, id) {
42
52
  export function refuse(code, detail, controlLabel) {
43
53
  const groupLabel = (key)=>key === 'control' ? controlVersionLabel(controlLabel) : GROUP_LABELS[key];
44
54
  const messages = {
55
+ 'cohort-source-invalid': COHORT_COPY.invalid,
56
+ 'cohort-cycle': COHORT_COPY.cycle,
57
+ 'cohort-source-open': COHORT_COPY.open,
58
+ 'cohort-lookup-missing': COHORT_COPY.lookup,
59
+ 'cohort-build-timeout': COHORT_COPY.timeout,
45
60
  'nested-tests': nestedTestCopy.readiness(detail),
46
61
  'goal-in-some-versions': asymmetricGoalsCopy(detail),
47
62
  'placements-changed': "This test's pages changed while it was starting. Try again.",
@@ -68,14 +83,21 @@ export function refuse(code, detail, controlLabel) {
68
83
  'entry-not-found': 'That page is not in the report.',
69
84
  'entry-ok': 'That page was already updated.',
70
85
  'entry-dismissed': 'That page was already dismissed.',
71
- 'entry-not-dismissed': 'That page is not dismissed.'
86
+ 'entry-not-dismissed': 'That page is not dismissed.',
87
+ 'not-live': scheduleOccupancyCopy.notLive,
88
+ 'not-pausable': scheduleOccupancyCopy.notPausable,
89
+ paused: scheduleOccupancyCopy.paused,
90
+ 'reschedule-past': scheduleOccupancyCopy.reschedulePast,
91
+ 'schedule-started': scheduleOccupancyCopy.scheduleStarted
72
92
  };
73
93
  const conflict = [
94
+ 'cohort-build-timeout',
74
95
  'page-busy',
75
96
  'placements-changed',
76
97
  'interacting-tests',
77
98
  'invalid-status',
78
99
  'stale-draft',
100
+ 'stale-edit',
79
101
  'page-in-use',
80
102
  'flag-point-busy',
81
103
  'layer-full',
@@ -83,12 +105,16 @@ export function refuse(code, detail, controlLabel) {
83
105
  'not-decided',
84
106
  'entry-ok',
85
107
  'entry-dismissed',
86
- 'entry-not-dismissed'
108
+ 'entry-not-dismissed',
109
+ 'not-live',
110
+ 'not-pausable',
111
+ 'paused',
112
+ 'schedule-started'
87
113
  ].includes(code);
88
114
  throw new XpRefusal(code, messages[code] ?? 'The experiment is not ready to start.', detail, code === 'entry-not-found' ? 404 : conflict ? 409 : 422);
89
115
  }
90
116
  export async function updateExperiment(req, id, data, system = false) {
91
- // §7.8: an authorized manager transition or trusted system Start writes locked plugin fields.
117
+ // §7.8: an authorized manager transition, trusted system Start or scheduled Stop writes locked plugin fields.
92
118
  const updated = await req.payload.update({
93
119
  collection: 'xp-experiments',
94
120
  req,
@@ -112,10 +138,36 @@ export async function updateExperiment(req, id, data, system = false) {
112
138
  if (!docs[0]) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
113
139
  return docs[0];
114
140
  }
141
+ function scheduleForStart(value, defaultZone, now) {
142
+ const { startAt, endAt, timeZone, windows } = value ?? {};
143
+ // Payload stores no array rows for both omitted and empty windows.
144
+ if (startAt == null && endAt == null && !windows?.length) return undefined;
145
+ const zone = timeZone || defaultZone;
146
+ const invalid = (field, message)=>{
147
+ throw new XpRefusal('schedule-invalid', message, {
148
+ field: `schedule.${field}`
149
+ }, 422);
150
+ };
151
+ if (!zone || !isValidTimeZone(zone)) return invalid('timeZone', scheduleOccupancyCopy.timeZone);
152
+ const start = startAt == null ? +now : Date.parse(startAt);
153
+ if (!Number.isFinite(start)) return invalid('startAt', scheduleOccupancyCopy.invalidStart);
154
+ if (endAt != null && !(Date.parse(endAt) > Math.max(+now, start))) return invalid('endAt', scheduleOccupancyCopy.pastEnd);
155
+ if (windows?.some((window)=>!window.days?.length)) return invalid('windows', scheduleOccupancyCopy.windows);
156
+ return {
157
+ startAt: startAt ?? undefined,
158
+ endAt: endAt ?? undefined,
159
+ timeZone: zone,
160
+ windows: windows ?? []
161
+ };
162
+ }
115
163
  async function prepareStart(req, options, before, system) {
164
+ // Start checks occupancy on the locked transaction. Preflight shows advisory readiness.
116
165
  const input = (await loadStartInputsBatch(req, options, [
117
166
  before
118
- ], false, system)).get(String(before.id));
167
+ ], false, system, {
168
+ checkOccupancy: false,
169
+ readCohorts: false
170
+ })).get(String(before.id));
119
171
  if (!input) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
120
172
  const full = await readExperiment(req, before.id);
121
173
  if (full.updatedAt !== before.updatedAt) refuse('stale-draft');
@@ -127,13 +179,11 @@ async function prepareStart(req, options, before, system) {
127
179
  };
128
180
  // Warning-only codes always have ok: true. These exclusions narrow
129
181
  // ReadinessCode to RefusalCode, which intentionally excludes warnings.
130
- const failed = checkStart(input).find((check)=>!check.ok);
182
+ const failed = checkStart(input).find((check)=>!check.ok && !isCohortReadiness(check.code));
131
183
  if (failed && failed.code !== 'page-targets-unchecked' && failed.code !== 'make-content-unsupported') refuse(failed.code, failed.detail, before.arms.find((arm)=>arm.kind === 'control')?.label);
132
- const at = new Date();
133
- const caps = await resolveCaps(input.metrics, options.metricSources ?? [], at);
184
+ const caps = await resolveCaps(input.metrics, options.metricSources ?? [], new Date());
134
185
  return {
135
186
  input,
136
- at,
137
187
  caps
138
188
  };
139
189
  }
@@ -157,10 +207,11 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
157
207
  }, async ({ req, exec })=>{
158
208
  const current = await readExperiment(req, experimentId);
159
209
  // A concurrent Start or Stop must yield the locked status before considering a stale snapshot.
160
- if (onlyIfNeverStarted && (current.status !== 'draft' || (current.phase ?? 0) !== 0)) {
210
+ const lastPhase = current.phase || await latestPhaseNumber(req, experimentId);
211
+ if (onlyIfNeverStarted && (current.status !== 'draft' || lastPhase !== 0)) {
161
212
  const detail = {
162
213
  status: current.status,
163
- phase: current.phase ?? 0
214
+ phase: lastPhase
164
215
  };
165
216
  throw new XpRefusal('first-start-only', firstStartOnlyCopy(current.status), detail, 409);
166
217
  }
@@ -168,7 +219,22 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
168
219
  if (current.updatedAt !== updatedAt) refuse('stale-draft');
169
220
  if (current.status !== 'draft' && current.status !== 'stopped') refuse('invalid-status');
170
221
  if ('error' in prepared) throw prepared.error;
171
- const { input, at, caps } = prepared;
222
+ const { input, caps } = prepared;
223
+ if (current.kind === 'page') await lockPagePaths(exec, pageTargetPaths(current.arms));
224
+ const at = new Date();
225
+ const schedule = scheduleForStart(current.schedule, options.timeZone, at);
226
+ const claim = claimRange({
227
+ startedAt: at,
228
+ schedule
229
+ });
230
+ const startedAt = new Date(Math.max(+at, +claim.from)).toISOString();
231
+ const scheduled = +claim.from > +at;
232
+ const previousArms = current.arms;
233
+ const inheritedTimeZone = schedule && schedule.timeZone !== current.schedule?.timeZone ? schedule.timeZone : undefined;
234
+ await assertNoOverlap(exec, {
235
+ ...current,
236
+ layerSlices: undefined
237
+ }, claim);
172
238
  const controlLabel = current.arms.find((arm)=>arm.kind === 'control')?.label;
173
239
  let placementDocs;
174
240
  if (current.kind === 'block') {
@@ -178,20 +244,10 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
178
244
  ...input,
179
245
  experiment: current,
180
246
  placements: nameNestedPlacements(rescan.placements, await nestedPlacementNames(req, rescan.placements, system))
181
- }).find((check)=>!check.ok);
247
+ }).find((check)=>!check.ok && !isCohortReadiness(check.code));
182
248
  if (failure && failure.code !== 'page-targets-unchecked' && failure.code !== 'make-content-unsupported') refuse(failure.code, failure.detail, controlLabel);
183
249
  }
184
250
  if (current.kind === 'page') {
185
- // Independent experiment/layer locks do not serialize overlapping pages.
186
- // Re-read occupancy after acquiring sorted path locks; hold through commit.
187
- // A waiting Start then sees the first Start's live test on this transaction.
188
- await lockPagePaths(exec, pageTargetPaths(current.arms));
189
- const recheck = checkStart({
190
- ...input,
191
- experiment: current,
192
- pageTestsInUse: await loadPageTestsInUse(req)
193
- }).find((check)=>check.code === 'page-in-use' && !check.ok);
194
- if (recheck) refuse('page-in-use', recheck.detail);
195
251
  const conflicts = await placementInteractions(req, exec, options, current, pageTargetPaths(current.arms), system);
196
252
  if (conflicts.length) refuse('interacting-tests', conflicts);
197
253
  if (options.pages) {
@@ -211,29 +267,6 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
211
267
  }
212
268
  }
213
269
  if (current.kind === 'flag' && current.flagPoint) {
214
- const busy = await findStartDocuments(req, {
215
- collection: 'xp-experiments',
216
- depth: 0,
217
- limit: 2,
218
- where: {
219
- and: [
220
- {
221
- flagPoint: {
222
- equals: current.flagPoint
223
- }
224
- },
225
- {
226
- status: {
227
- in: [
228
- 'running',
229
- 'decided'
230
- ]
231
- }
232
- }
233
- ]
234
- }
235
- }, system);
236
- if (busy.docs.some((doc)=>String(doc.id) !== String(experimentId))) refuse('flag-point-busy');
237
270
  const point = options.flagPoints.find((point)=>point.id === current.flagPoint);
238
271
  const state = await readStartState(req, system);
239
272
  const defaults = state.flagDefaults;
@@ -244,7 +277,7 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
244
277
  const recheck = checkStart({
245
278
  ...input,
246
279
  experiment: current
247
- }).find((check)=>!check.ok);
280
+ }).find((check)=>!check.ok && !isCohortReadiness(check.code));
248
281
  if (recheck && recheck.code !== 'page-targets-unchecked' && recheck.code !== 'make-content-unsupported') refuse(recheck.code, recheck.detail, controlLabel);
249
282
  }
250
283
  if (input.metrics.some((metric)=>metric.source.startsWith('click:'))) {
@@ -265,7 +298,20 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
265
298
  const locked = lockedMetrics.find((row)=>String(row.id) === String(metric.id));
266
299
  return locked.slug !== metric.slug || locked.source !== metric.source;
267
300
  })) throw new XpRefusal('stale-draft', 'A goal changed. Review it again before starting.', undefined, 409);
268
- const targeting = (current.targeting ?? []).map((rule)=>{
301
+ const cohortNow = new Date();
302
+ if (current.targeting?.some(isCohortRule) && options.cohorts?.proxyLookup !== true) refuse('cohort-lookup-missing');
303
+ const deadline = +cohortNow + COHORT_START_BUDGET_MS;
304
+ const frozen = !current.targeting?.some(isCohortRule) ? undefined : await withCohortTimeout(exec, deadline, async (timed)=>{
305
+ const facts = await loadCohortFacts(req, timed, current, options, system, cohortNow, deadline);
306
+ const failure = checkCohorts(current, facts)[0];
307
+ if (failure) refuse(failure.code, failure.detail);
308
+ return freezeCohortTargeting(current, facts);
309
+ }).catch((error)=>{
310
+ if (isCohortTimeout(error)) throw cohortBuildTimeout([]);
311
+ throw error;
312
+ });
313
+ const targeting = (frozen?.targeting ?? (current.targeting ?? []).filter((rule)=>!isCohortRule(rule))).map((rule)=>{
314
+ if (isCohortRule(rule)) return rule;
269
315
  const type = Object.hasOwn(options.attributeKeys ?? {}, rule.attribute) ? options.attributeKeys[rule.attribute].type : undefined;
270
316
  const validValue = type === 'string' && [
271
317
  'in',
@@ -282,15 +328,23 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
282
328
  type
283
329
  };
284
330
  });
331
+ if (frozen) {
332
+ await buildStartCohorts(exec, frozen.rules, frozen.sources, {
333
+ options,
334
+ now: cohortNow,
335
+ budgetMs: deadline - Date.now(),
336
+ readExec: resultsExecutor(req.payload, ()=>deadline - Date.now())
337
+ });
338
+ }
285
339
  const layerId = relationshipId(current.layer);
286
340
  const layerSlices = layerId === undefined ? [] : await claimSlices(exec, {
287
341
  layerId,
288
342
  experimentId,
289
- count: current.allocation
343
+ count: current.allocation,
344
+ claim
290
345
  });
291
- const phase = (current.phase ?? 0) + 1;
346
+ const phase = lastPhase + 1;
292
347
  const seed = newSeed();
293
- const startedAt = at.toISOString();
294
348
  const definitions = caps.definitions.map((metric)=>({
295
349
  ...metric,
296
350
  metricId: metric.id,
@@ -299,6 +353,16 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
299
353
  role: String(relationshipId(current.metrics?.primary)) === String(metric.id) ? 'primary' : current.metrics?.guardrails?.some((id)=>String(relationshipId(id)) === String(metric.id)) ? 'guardrail' : 'secondary'
300
354
  }));
301
355
  const arms = current.kind === 'block' ? withSlotsFor(current.arms, 'block') : current.arms;
356
+ // Cancel needs the editable values from just before Schedule, which may
357
+ // differ from the frozen values of any earlier round.
358
+ const beforeSchedule = scheduled && (current.kind === 'flag' || inheritedTimeZone) ? {
359
+ ...current.kind === 'flag' ? {
360
+ arms: previousArms
361
+ } : {},
362
+ ...inheritedTimeZone ? {
363
+ timeZone: current.schedule?.timeZone ?? null
364
+ } : {}
365
+ } : undefined;
302
366
  await writePhaseRecord(req, {
303
367
  experiment: experimentId,
304
368
  phase,
@@ -310,6 +374,9 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
310
374
  allocationChanges: [],
311
375
  targeting,
312
376
  metricDefinitions: definitions,
377
+ ...schedule ? {
378
+ schedule
379
+ } : {},
313
380
  ...placementDocs ? {
314
381
  placementDocs
315
382
  } : {},
@@ -317,6 +384,9 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
317
384
  ...current.analysis,
318
385
  method: current.analysis?.method ?? 'sequential',
319
386
  alpha: 0.05,
387
+ ...beforeSchedule ? {
388
+ beforeSchedule
389
+ } : {},
320
390
  sequentialTuningParameter: current.analysis?.sequentialTuningParameter ?? DEFAULT_SEQUENTIAL_TUNING_PARAMETER,
321
391
  cupedLookbackDays: 14,
322
392
  layerSlices,
@@ -341,6 +411,17 @@ export async function start(req, { experimentId, options, phase: expectedPhase,
341
411
  seed,
342
412
  startedAt,
343
413
  stoppedAt: null,
414
+ pausedAt: null,
415
+ pausedBy: null,
416
+ pauseReason: null,
417
+ ...inheritedTimeZone ? {
418
+ schedule: {
419
+ ...current.schedule,
420
+ timeZone: inheritedTimeZone
421
+ }
422
+ } : {},
423
+ claimFrom: claim.from.toISOString(),
424
+ claimTo: claim.to?.toISOString() ?? null,
344
425
  layerSlices,
345
426
  arms
346
427
  }, system);
@@ -1,7 +1,21 @@
1
1
  import type { PayloadRequest } from 'payload';
2
+ import { type OccupancyRow } from '../db/occupancy.js';
3
+ import type { DocId } from '../types/contracts.js';
2
4
  type StartReadQuery = Parameters<PayloadRequest['payload']['find']>[0] & {
3
5
  collection: 'xp-experiments' | 'xp-metrics' | 'xp-layers';
4
6
  };
5
7
  export declare function findStartDocuments(req: PayloadRequest, query: StartReadQuery, system?: boolean): Promise<import("payload").PaginatedDocs<import("payload").JsonObject & import("payload").TypeWithID>>;
6
8
  export declare function readStartState(req: PayloadRequest, system?: boolean): Promise<import("payload").JsonObject>;
9
+ /** Cache the peer rows in batched readiness, then test each draft's own range. */
10
+ export declare function readStartPeers(req: PayloadRequest, where: {
11
+ layer: {
12
+ equals: DocId;
13
+ };
14
+ } | {
15
+ flagPoint: {
16
+ equals: string;
17
+ };
18
+ }, system: boolean): Promise<(OccupancyRow & {
19
+ layerSlices?: number[] | null;
20
+ })[]>;
7
21
  export {};
@@ -1,3 +1,4 @@
1
+ import { OCCUPYING_STATUSES } from '../db/occupancy.js';
1
2
  export function findStartDocuments(req, query, system = false) {
2
3
  // §7.8: Start from trusted host code reads plugin readiness data without a manager actor.
3
4
  if (system) return req.payload.find({
@@ -26,3 +27,29 @@ export function readStartState(req, system = false) {
26
27
  depth: 0
27
28
  });
28
29
  }
30
+ /** Cache the peer rows in batched readiness, then test each draft's own range. */ export async function readStartPeers(req, where, system) {
31
+ const peers = [];
32
+ for(let page = 1;; page++){
33
+ const usage = await findStartDocuments(req, {
34
+ collection: 'xp-experiments',
35
+ depth: 0,
36
+ limit: 100,
37
+ page,
38
+ where: {
39
+ and: [
40
+ where,
41
+ {
42
+ status: {
43
+ in: OCCUPYING_STATUSES
44
+ }
45
+ }
46
+ ]
47
+ }
48
+ }, system);
49
+ peers.push(...usage.docs.map((doc)=>({
50
+ ...doc,
51
+ scheduleTimeZone: doc.schedule?.timeZone
52
+ })));
53
+ if (!usage.hasNextPage) return peers;
54
+ }
55
+ }
@@ -1,9 +1,19 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
3
  import type { RoundBody } from '../types/endpoints.js';
4
+ import { type TransitionExperiment } from './start.js';
5
+ export declare function stopRound(req: PayloadRequest, current: TransitionExperiment, at: string, system?: boolean): Promise<import("payload").JsonObject & import("payload").TypeWithID>;
4
6
  export declare function stop(req: PayloadRequest, { experimentId, phase: expectedPhase }: RoundBody & {
5
7
  experimentId: DocId;
6
8
  }): Promise<{
7
9
  doc: import("payload").JsonObject & import("payload").TypeWithID;
8
10
  revision: number;
9
11
  }>;
12
+ /** System-only Stop. Re-read the frozen end inside the lock so a concurrent
13
+ * reschedule, pause, decision or new round wins over discovery by runResults. */
14
+ export declare function stopScheduledExperiment(req: PayloadRequest, { experimentId, phase, dueBy, deadline }: {
15
+ experimentId: DocId;
16
+ phase: number;
17
+ dueBy: Date;
18
+ deadline: number;
19
+ }): Promise<void>;
@@ -1,26 +1,39 @@
1
- import { relationshipId } from './checkStart.js';
2
- import { withTransition } from './kernel.js';
3
- import { requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
4
- import { readExperiment, refuse, updateExperiment } from './start.js';
1
+ import { readPhaseRecord, requireCurrentRound, setPhaseEndedAt } from './phaseRecord.js';
2
+ import { requireStarted, withScheduledRound } from './scheduledRound.js';
3
+ import { refuse, updateExperiment } from './start.js';
4
+ export async function stopRound(req, current, at, system = false) {
5
+ await setPhaseEndedAt(req, current.id, current.phase, at);
6
+ return updateExperiment(req, current.id, {
7
+ status: 'stopped',
8
+ layerSlices: [],
9
+ stoppedAt: at
10
+ }, system);
11
+ }
5
12
  export async function stop(req, { experimentId, phase: expectedPhase }) {
6
- const before = await readExperiment(req, experimentId);
7
- const { result: doc, revision } = await withTransition(req, {
8
- experimentId,
9
- layerId: relationshipId(before.layer)
10
- }, async ({ req })=>{
11
- const current = await readExperiment(req, experimentId);
13
+ return withScheduledRound(req, experimentId, async (req, _exec, current)=>{
12
14
  requireCurrentRound(expectedPhase, current.phase);
13
- if (current.status !== 'running') refuse('invalid-status');
14
- const at = new Date().toISOString();
15
- await setPhaseEndedAt(req, experimentId, current.phase, at);
16
- return updateExperiment(req, experimentId, {
17
- status: 'stopped',
18
- layerSlices: [],
19
- stoppedAt: at
20
- });
15
+ if (current.status !== 'running' && current.status !== 'paused') refuse('invalid-status');
16
+ const now = new Date();
17
+ requireStarted(current.startedAt, now);
18
+ const scheduledEnd = current.claimTo ? new Date(current.claimTo) : null;
19
+ const at = current.status === 'paused' ? current.pausedAt : scheduledEnd && scheduledEnd <= now ? scheduledEnd.toISOString() : now.toISOString();
20
+ if (!at) refuse('invalid-phase');
21
+ return stopRound(req, current, at);
21
22
  });
22
- return {
23
- doc,
24
- revision: revision
25
- };
23
+ }
24
+ class ScheduleNoLongerDue extends Error {
25
+ }
26
+ /** System-only Stop. Re-read the frozen end inside the lock so a concurrent
27
+ * reschedule, pause, decision or new round wins over discovery by runResults. */ export async function stopScheduledExperiment(req, { experimentId, phase, dueBy, deadline }) {
28
+ try {
29
+ await withScheduledRound(req, experimentId, async (req, _exec, current)=>{
30
+ if (current.status !== 'running' || current.phase !== phase) throw new ScheduleNoLongerDue();
31
+ const record = await readPhaseRecord(req, experimentId, phase);
32
+ const endAt = record.schedule?.endAt;
33
+ if (record.phaseKind !== 'test' || !endAt || new Date(endAt) > dueBy) throw new ScheduleNoLongerDue();
34
+ return stopRound(req, current, new Date(endAt).toISOString(), true);
35
+ }, deadline);
36
+ } catch (error) {
37
+ if (!(error instanceof ScheduleNoLongerDue)) throw error;
38
+ }
26
39
  }
@@ -18,4 +18,4 @@ export type SerializedAttributeKeys = Record<string, {
18
18
  type: 'string' | 'number' | 'boolean';
19
19
  values?: string[];
20
20
  }>;
21
- export type EditableField = 'name' | 'hypothesis' | 'arms' | 'targeting' | 'allocation' | 'flagPoint' | 'metrics' | 'analysis' | 'exposurePolicy' | 'pageCollection';
21
+ export type EditableField = 'name' | 'hypothesis' | 'arms' | 'targeting' | 'allocation' | 'flagPoint' | 'metrics' | 'analysis' | 'exposurePolicy' | 'pageCollection' | 'schedule';
@@ -14,12 +14,13 @@ export interface PreviewPlacement {
14
14
  export type Attributes = Record<string, string | number | boolean>;
15
15
  export type ExposurePolicy = 'render' | 'viewport' | 'pageview' | 'manual';
16
16
  export type ExperimentKind = 'block' | 'page' | 'flag' | 'code';
17
- export type Status = 'draft' | 'running' | 'stopped' | 'decided' | 'archived';
17
+ export type { Status } from './status.js';
18
18
  export type UnitType = 'visitor' | 'user';
19
19
  import type { ArmKey } from './armKey.js';
20
20
  export type { ArmKey };
21
21
  export type ArmKind = 'control' | 'variant' | 'holdout';
22
22
  export interface TargetingRule {
23
+ kind?: 'attribute';
23
24
  attribute: string;
24
25
  op: TargetingOp;
25
26
  value: string | number | boolean | string[];
@@ -137,6 +138,11 @@ export interface ExperimentsPluginOptions<TUser extends {
137
138
  readResults?: ExperimentsAccess;
138
139
  readIdentities?: ExperimentsAccess;
139
140
  };
141
+ /** Default IANA time zone for experiment schedules. */
142
+ timeZone?: string;
143
+ cohorts?: {
144
+ proxyLookup: boolean;
145
+ };
140
146
  theme?: {
141
147
  accent?: string;
142
148
  };