@delmaredigital/payload-experiments 0.4.1 → 0.5.1

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 (310) hide show
  1. package/README.md +9 -5
  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/blocks/placementLocale.d.ts +14 -0
  22. package/dist/blocks/placementLocale.js +80 -13
  23. package/dist/blocks/placementPublication.d.ts +14 -0
  24. package/dist/blocks/placementPublication.js +24 -0
  25. package/dist/cohorts/build.d.ts +35 -0
  26. package/dist/cohorts/build.js +134 -0
  27. package/dist/cohorts/key.d.ts +12 -0
  28. package/dist/cohorts/key.js +15 -0
  29. package/dist/cohorts/maintenance.d.ts +10 -0
  30. package/dist/cohorts/maintenance.js +70 -0
  31. package/dist/cohorts/readiness.d.ts +30 -0
  32. package/dist/cohorts/readiness.js +54 -0
  33. package/dist/cohorts/readinessData.d.ts +29 -0
  34. package/dist/cohorts/readinessData.js +123 -0
  35. package/dist/cohorts/rule.d.ts +33 -0
  36. package/dist/cohorts/rule.js +50 -0
  37. package/dist/collections/cohortMembers.d.ts +4 -0
  38. package/dist/collections/cohortMembers.js +95 -0
  39. package/dist/collections/experiments/config.js +157 -7
  40. package/dist/collections/experiments/editability.js +10 -6
  41. package/dist/collections/experiments/lockHook.js +39 -20
  42. package/dist/collections/index.js +4 -1
  43. package/dist/collections/phases.js +4 -1
  44. package/dist/constants.d.ts +2 -0
  45. package/dist/constants.js +2 -0
  46. package/dist/db/adapter.d.ts +2 -1
  47. package/dist/db/adapter.js +17 -4
  48. package/dist/db/appends.d.ts +2 -1
  49. package/dist/db/appends.js +3 -2
  50. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  51. package/dist/db/bulkPlacementRemoval.js +7 -2
  52. package/dist/db/cohortMembership.d.ts +11 -0
  53. package/dist/db/cohortMembership.js +31 -0
  54. package/dist/db/cohortPool.d.ts +9 -0
  55. package/dist/db/cohortPool.js +53 -0
  56. package/dist/db/cohortTransactions.d.ts +3 -0
  57. package/dist/db/cohortTransactions.js +52 -0
  58. package/dist/db/cohorts.d.ts +72 -0
  59. package/dist/db/cohorts.js +280 -0
  60. package/dist/db/erase.d.ts +2 -0
  61. package/dist/db/erase.js +21 -2
  62. package/dist/db/events.d.ts +2 -0
  63. package/dist/db/events.js +8 -0
  64. package/dist/db/executor.d.ts +2 -0
  65. package/dist/db/executor.js +8 -0
  66. package/dist/db/locks.d.ts +7 -0
  67. package/dist/db/locks.js +13 -1
  68. package/dist/db/names.d.ts +95 -1
  69. package/dist/db/names.js +95 -1
  70. package/dist/db/occupancy.d.ts +21 -0
  71. package/dist/db/occupancy.js +46 -0
  72. package/dist/db/pageBindings.d.ts +2 -2
  73. package/dist/db/pageBindings.js +3 -3
  74. package/dist/db/pageOccupancy.d.ts +4 -4
  75. package/dist/db/pageOccupancy.js +13 -10
  76. package/dist/db/pgExecutor.d.ts +4 -0
  77. package/dist/db/pgExecutor.js +1 -1
  78. package/dist/db/placements.d.ts +6 -1
  79. package/dist/db/placements.js +27 -1
  80. package/dist/db/results.d.ts +5 -2
  81. package/dist/db/results.js +32 -5
  82. package/dist/db/slices.d.ts +9 -2
  83. package/dist/db/slices.js +15 -8
  84. package/dist/db/snapshots.d.ts +16 -1
  85. package/dist/db/snapshots.js +27 -2
  86. package/dist/db/sql.d.ts +2 -2
  87. package/dist/db/sql.js +1 -2
  88. package/dist/endpoints/cohortSources.d.ts +16 -0
  89. package/dist/endpoints/cohortSources.js +335 -0
  90. package/dist/endpoints/contentLocale.d.ts +1 -1
  91. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  92. package/dist/endpoints/events.js +82 -18
  93. package/dist/endpoints/index.js +45 -1
  94. package/dist/endpoints/pausedBy.d.ts +14 -0
  95. package/dist/endpoints/pausedBy.js +94 -0
  96. package/dist/endpoints/preflight.js +4 -1
  97. package/dist/endpoints/previewToken.js +2 -0
  98. package/dist/endpoints/results.d.ts +2 -2
  99. package/dist/endpoints/results.js +111 -3
  100. package/dist/endpoints/routeId.d.ts +2 -1
  101. package/dist/endpoints/routeId.js +6 -2
  102. package/dist/endpoints/summary.js +24 -1
  103. package/dist/endpoints/transitions.d.ts +7 -0
  104. package/dist/endpoints/transitions.js +50 -1
  105. package/dist/events/rows.d.ts +1 -1
  106. package/dist/events/rows.js +5 -3
  107. package/dist/exports/index.d.ts +2 -0
  108. package/dist/exports/index.js +1 -0
  109. package/dist/exports/runtimeProxy.d.ts +1 -0
  110. package/dist/exports/runtimeProxy.js +1 -0
  111. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  112. package/dist/hooks/blockRemovalRule.js +12 -8
  113. package/dist/hooks/pageGuard.d.ts +7 -1
  114. package/dist/hooks/pageGuard.js +177 -4
  115. package/dist/hooks/puckNestedTests.d.ts +1 -1
  116. package/dist/hooks/puckNestedTests.js +3 -1
  117. package/dist/labels/status.d.ts +15 -0
  118. package/dist/labels/status.js +12 -0
  119. package/dist/manifest/compile.d.ts +15 -4
  120. package/dist/manifest/compile.js +91 -3
  121. package/dist/onInit.js +4 -6
  122. package/dist/options.d.ts +1 -0
  123. package/dist/options.js +10 -0
  124. package/dist/proxy/consentFallback.d.ts +1 -1
  125. package/dist/proxy/consentFallback.js +4 -4
  126. package/dist/proxy/control.d.ts +1 -1
  127. package/dist/proxy/control.js +2 -2
  128. package/dist/proxy/pageRewrite.d.ts +1 -1
  129. package/dist/proxy/pageRewrite.js +3 -2
  130. package/dist/proxy/resolve.js +76 -17
  131. package/dist/puck/ExperimentPicker.js +2 -1
  132. package/dist/puck/copy.d.ts +6 -5
  133. package/dist/puck/copy.js +3 -7
  134. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  135. package/dist/puck/editor/QuickTestActions.js +7 -1
  136. package/dist/puck/editor/armWrites.js +6 -1
  137. package/dist/puck/editor/copy.d.ts +3 -0
  138. package/dist/puck/editor/copy.js +3 -0
  139. package/dist/puck/editor/editor.css +2 -1
  140. package/dist/puck/editor/editor.model.d.ts +2 -1
  141. package/dist/puck/editor/editor.model.js +2 -0
  142. package/dist/puck/editor/placementsCache.d.ts +1 -1
  143. package/dist/puck/editor/placementsCache.js +6 -3
  144. package/dist/results/analyse.d.ts +3 -1
  145. package/dist/results/analyse.js +20 -3
  146. package/dist/results/health.d.ts +11 -0
  147. package/dist/results/health.js +38 -0
  148. package/dist/results/power.d.ts +1 -1
  149. package/dist/results/power.js +1 -1
  150. package/dist/results/snapshot.d.ts +8 -2
  151. package/dist/results/snapshot.js +23 -1
  152. package/dist/results/unitValues.d.ts +48 -0
  153. package/dist/results/unitValues.js +166 -0
  154. package/dist/runtime/assign.d.ts +7 -3
  155. package/dist/runtime/assign.js +12 -4
  156. package/dist/runtime/cohortCookie.d.ts +15 -0
  157. package/dist/runtime/cohortCookie.js +72 -0
  158. package/dist/runtime/cohortLookup.d.ts +9 -0
  159. package/dist/runtime/cohortLookup.js +25 -0
  160. package/dist/runtime/eligibility.d.ts +11 -5
  161. package/dist/runtime/eligibility.js +33 -7
  162. package/dist/runtime/header.d.ts +1 -0
  163. package/dist/runtime/header.js +1 -1
  164. package/dist/runtime/proxyRuntime.js +5 -1
  165. package/dist/runtime/targeting.d.ts +3 -2
  166. package/dist/runtime/targeting.js +2 -1
  167. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  168. package/dist/sanitizeReadinessDetail.js +41 -4
  169. package/dist/schedule/activeTime.d.ts +28 -0
  170. package/dist/schedule/activeTime.js +322 -0
  171. package/dist/schedule/ranges.d.ts +13 -0
  172. package/dist/schedule/ranges.js +11 -0
  173. package/dist/schedule/roundTime.d.ts +10 -0
  174. package/dist/schedule/roundTime.js +45 -0
  175. package/dist/schedule/types.d.ts +29 -0
  176. package/dist/schedule/types.js +1 -0
  177. package/dist/server/cohortLookup.d.ts +3 -0
  178. package/dist/server/cohortLookup.js +7 -0
  179. package/dist/server/eraseUser.d.ts +1 -0
  180. package/dist/server/getAssignments.js +63 -40
  181. package/dist/server/previewDraft.d.ts +1 -1
  182. package/dist/server/previewDraft.js +3 -2
  183. package/dist/server/recordContentChange.d.ts +1 -1
  184. package/dist/server/recordContentChange.js +42 -20
  185. package/dist/server/recordExposures.js +4 -2
  186. package/dist/server/runResults.js +97 -150
  187. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  188. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  189. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  190. package/dist/testSurface/actions/actions.model.js +38 -5
  191. package/dist/testSurface/api.d.ts +13 -1
  192. package/dist/testSurface/api.js +19 -0
  193. package/dist/testSurface/copy/actions.d.ts +13 -0
  194. package/dist/testSurface/copy/actions.js +13 -0
  195. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  196. package/dist/testSurface/copy/cohorts.js +81 -0
  197. package/dist/testSurface/copy/common.d.ts +2 -3
  198. package/dist/testSurface/copy/common.js +4 -4
  199. package/dist/testSurface/copy/inputs.d.ts +3 -0
  200. package/dist/testSurface/copy/inputs.js +3 -0
  201. package/dist/testSurface/copy/readiness.d.ts +20 -6
  202. package/dist/testSurface/copy/readiness.js +42 -9
  203. package/dist/testSurface/copy/results.d.ts +1 -0
  204. package/dist/testSurface/copy/results.js +1 -0
  205. package/dist/testSurface/copy/schedule.d.ts +58 -0
  206. package/dist/testSurface/copy/schedule.js +150 -0
  207. package/dist/testSurface/copy/surface.d.ts +2 -0
  208. package/dist/testSurface/copy/surface.js +2 -0
  209. package/dist/testSurface/copy/testPage.d.ts +12 -2
  210. package/dist/testSurface/copy/testPage.js +17 -2
  211. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  212. package/dist/testSurface/format/roundProgress.js +34 -5
  213. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  214. package/dist/testSurface/format/scheduleStatus.js +93 -0
  215. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  216. package/dist/testSurface/format/useScheduleClock.js +20 -0
  217. package/dist/testSurface/labels.d.ts +4 -9
  218. package/dist/testSurface/labels.js +2 -7
  219. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  220. package/dist/testSurface/lockedNotice.model.js +16 -3
  221. package/dist/testSurface/readPreflight.d.ts +3 -0
  222. package/dist/testSurface/readPreflight.js +14 -0
  223. package/dist/testSurface/readinessRead.d.ts +2 -2
  224. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  225. package/dist/testSurface/results/results.model.d.ts +1 -1
  226. package/dist/testSurface/results/results.model.js +34 -6
  227. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  228. package/dist/testSurface/review/cohortEstimate.js +32 -0
  229. package/dist/testSurface/surface/contracts.d.ts +2 -1
  230. package/dist/testSurface/surface/contracts.js +1 -0
  231. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  232. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  233. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  234. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  235. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  236. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  237. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  238. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  239. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  240. package/dist/testSurface/surface/results/useResults.js +17 -6
  241. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  242. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  243. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  244. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  245. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  246. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  247. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  248. package/dist/testSurface/surface/test/Section.js +1 -1
  249. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  250. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  251. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  252. package/dist/testSurface/surface/test/fields.js +3 -3
  253. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  254. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  255. package/dist/testSurface/surface/test/testPage.css +26 -0
  256. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  257. package/dist/testSurface/surface/testDocument.model.js +2 -1
  258. package/dist/testSurface/surface/useTestDocument.js +11 -4
  259. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  260. package/dist/testSurface/targeting/targeting.model.js +1 -1
  261. package/dist/testSurface/useApi.d.ts +12 -0
  262. package/dist/transitions/addMetric.js +5 -2
  263. package/dist/transitions/allocate.js +6 -1
  264. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  265. package/dist/transitions/assertNoOverlap.js +24 -0
  266. package/dist/transitions/buildCohorts.d.ts +10 -0
  267. package/dist/transitions/buildCohorts.js +68 -0
  268. package/dist/transitions/cancelSchedule.d.ts +4 -0
  269. package/dist/transitions/cancelSchedule.js +42 -0
  270. package/dist/transitions/checkStart.d.ts +17 -3
  271. package/dist/transitions/checkStart.js +20 -7
  272. package/dist/transitions/decide.js +40 -13
  273. package/dist/transitions/kernel.d.ts +3 -1
  274. package/dist/transitions/kernel.js +5 -2
  275. package/dist/transitions/pause.d.ts +4 -0
  276. package/dist/transitions/pause.js +35 -0
  277. package/dist/transitions/phaseRecord.d.ts +19 -2
  278. package/dist/transitions/phaseRecord.js +50 -11
  279. package/dist/transitions/placementInteractions.d.ts +7 -2
  280. package/dist/transitions/placementInteractions.js +9 -7
  281. package/dist/transitions/placements.d.ts +4 -3
  282. package/dist/transitions/placements.js +28 -14
  283. package/dist/transitions/preflightData.d.ts +11 -3
  284. package/dist/transitions/preflightData.js +134 -81
  285. package/dist/transitions/reschedule.d.ts +4 -0
  286. package/dist/transitions/reschedule.js +58 -0
  287. package/dist/transitions/resume.d.ts +4 -0
  288. package/dist/transitions/resume.js +32 -0
  289. package/dist/transitions/scheduledRound.d.ts +18 -0
  290. package/dist/transitions/scheduledRound.js +42 -0
  291. package/dist/transitions/start.d.ts +4 -0
  292. package/dist/transitions/start.js +139 -56
  293. package/dist/transitions/startReads.d.ts +14 -0
  294. package/dist/transitions/startReads.js +27 -0
  295. package/dist/transitions/stop.d.ts +10 -0
  296. package/dist/transitions/stop.js +35 -22
  297. package/dist/types/admin.d.ts +1 -1
  298. package/dist/types/contracts.d.ts +7 -1
  299. package/dist/types/endpoints.d.ts +72 -3
  300. package/dist/types/manifest.d.ts +9 -0
  301. package/dist/types/runtime.d.ts +5 -0
  302. package/dist/types/snapshot.d.ts +10 -0
  303. package/dist/types/status.d.ts +1 -0
  304. package/dist/types/status.js +1 -0
  305. package/dist/types/surface.d.ts +1 -0
  306. package/dist/ui/Feedback.d.ts +9 -6
  307. package/dist/ui/Feedback.js +10 -9
  308. package/dist/ui/SelectControl.js +1 -1
  309. package/dist/ui/ui.css +2 -1
  310. package/package.json +2 -2
@@ -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>;
@@ -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;