@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
package/dist/db/names.js CHANGED
@@ -1,7 +1,13 @@
1
- /** SQL identifiers from the Payload 3.90.2 generated-schema fixture (2026-10-30).
1
+ /** SQL identifiers from the Payload 3.90.2 generated-schema fixture (2026-12-04).
2
2
  * All main, array, relationship and version tables are included. Access through
3
3
  * these literal keys is checked by TypeScript; names.test.ts checks fixture parity.
4
4
  */ export const TABLES = {
5
+ experimentsTargetingArms: 'xp_experiments_targeting_arms',
6
+ experimentsVersionsVersionTargetingArms: '_xp_experiments_v_version_targeting_arms',
7
+ experimentsScheduleWindows: 'xp_experiments_schedule_windows',
8
+ experimentsVersionsVersionScheduleWindows: '_xp_experiments_v_version_schedule_windows',
9
+ cohortMembers: 'xp_cohort_members',
10
+ cohorts: 'xp_cohorts',
5
11
  experimentsTargeting: 'xp_experiments_targeting',
6
12
  experimentsArms: 'xp_experiments_arms',
7
13
  experiments: 'xp_experiments',
@@ -19,6 +25,56 @@
19
25
  state: 'xp_state'
20
26
  };
21
27
  export const COLUMNS = {
28
+ cohorts: {
29
+ id: 'id',
30
+ cohortKey: 'cohort_key',
31
+ rule: 'rule',
32
+ state: 'state',
33
+ closed: 'closed',
34
+ members: 'members',
35
+ builtAt: 'built_at',
36
+ updatedAt: 'updated_at',
37
+ createdAt: 'created_at'
38
+ },
39
+ cohortMembers: {
40
+ id: 'id',
41
+ cohortKey: 'cohort_key',
42
+ unitId: 'unit_id',
43
+ builtAt: 'built_at',
44
+ enteredAt: 'entered_at',
45
+ exitedAt: 'exited_at',
46
+ updatedAt: 'updated_at',
47
+ createdAt: 'created_at'
48
+ },
49
+ experimentsVersionsVersionScheduleWindows: {
50
+ _order: '_order',
51
+ _parentId: '_parent_id',
52
+ id: 'id',
53
+ days: 'days',
54
+ from: 'from',
55
+ to: 'to',
56
+ _uuid: '_uuid'
57
+ },
58
+ experimentsScheduleWindows: {
59
+ _order: '_order',
60
+ _parentId: '_parent_id',
61
+ id: 'id',
62
+ days: 'days',
63
+ from: 'from',
64
+ to: 'to'
65
+ },
66
+ experimentsVersionsVersionTargetingArms: {
67
+ order: 'order',
68
+ parentId: 'parent_id',
69
+ value: 'value',
70
+ id: 'id'
71
+ },
72
+ experimentsTargetingArms: {
73
+ order: 'order',
74
+ parentId: 'parent_id',
75
+ value: 'value',
76
+ id: 'id'
77
+ },
22
78
  state: {
23
79
  id: 'id',
24
80
  revision: 'revision',
@@ -29,6 +85,12 @@ export const COLUMNS = {
29
85
  createdAt: 'created_at'
30
86
  },
31
87
  experimentsTargeting: {
88
+ kind: 'kind',
89
+ sourceExperimentId: 'source_experiment_id',
90
+ sourcePhase: 'source_phase',
91
+ goalMetricId: 'goal_metric_id',
92
+ goalCompleted: 'goal_completed',
93
+ include: 'include',
32
94
  _order: '_order',
33
95
  _parentId: '_parent_id',
34
96
  id: 'id',
@@ -49,6 +111,12 @@ export const COLUMNS = {
49
111
  pageTarget: 'page_target'
50
112
  },
51
113
  experiments: {
114
+ scheduleStartAt: 'schedule_start_at',
115
+ scheduleEndAt: 'schedule_end_at',
116
+ scheduleTimeZone: 'schedule_time_zone',
117
+ pausedAt: 'paused_at',
118
+ pausedBy: 'paused_by',
119
+ pauseReason: 'pause_reason',
52
120
  id: 'id',
53
121
  status: 'status',
54
122
  name: 'name',
@@ -76,6 +144,8 @@ export const COLUMNS = {
76
144
  stoppedAt: 'stopped_at',
77
145
  decidedAt: 'decided_at',
78
146
  archivedAt: 'archived_at',
147
+ claimFrom: 'claim_from',
148
+ claimTo: 'claim_to',
79
149
  decisionWinnerArm: 'decision_winner_arm',
80
150
  decisionVerdictCode: 'decision_verdict_code',
81
151
  decisionNote: 'decision_note',
@@ -97,6 +167,12 @@ export const COLUMNS = {
97
167
  xpMetricsId: 'xp_metrics_id'
98
168
  },
99
169
  experimentsVersionsVersionTargeting: {
170
+ kind: 'kind',
171
+ sourceExperimentId: 'source_experiment_id',
172
+ sourcePhase: 'source_phase',
173
+ goalMetricId: 'goal_metric_id',
174
+ goalCompleted: 'goal_completed',
175
+ include: 'include',
100
176
  _order: '_order',
101
177
  _parentId: '_parent_id',
102
178
  id: 'id',
@@ -119,6 +195,12 @@ export const COLUMNS = {
119
195
  _uuid: '_uuid'
120
196
  },
121
197
  experimentsVersions: {
198
+ versionScheduleStartAt: 'version_schedule_start_at',
199
+ versionScheduleEndAt: 'version_schedule_end_at',
200
+ versionScheduleTimeZone: 'version_schedule_time_zone',
201
+ versionPausedAt: 'version_paused_at',
202
+ versionPausedBy: 'version_paused_by',
203
+ versionPauseReason: 'version_pause_reason',
122
204
  id: 'id',
123
205
  parentId: 'parent_id',
124
206
  versionStatus: 'version_status',
@@ -147,6 +229,8 @@ export const COLUMNS = {
147
229
  versionStoppedAt: 'version_stopped_at',
148
230
  versionDecidedAt: 'version_decided_at',
149
231
  versionArchivedAt: 'version_archived_at',
232
+ versionClaimFrom: 'version_claim_from',
233
+ versionClaimTo: 'version_claim_to',
150
234
  versionDecisionWinnerArm: 'version_decision_winner_arm',
151
235
  versionDecisionVerdictCode: 'version_decision_verdict_code',
152
236
  versionDecisionNote: 'version_decision_note',
@@ -170,6 +254,9 @@ export const COLUMNS = {
170
254
  xpMetricsId: 'xp_metrics_id'
171
255
  },
172
256
  phases: {
257
+ pauses: 'pauses',
258
+ schedule: 'schedule',
259
+ scheduleChanges: 'schedule_changes',
173
260
  id: 'id',
174
261
  experimentId: 'experiment_id',
175
262
  phase: 'phase',
@@ -250,6 +337,13 @@ export const COLUMNS = {
250
337
  }
251
338
  };
252
339
  export const ENUMS = {
340
+ cohortsState: 'enum_xp_cohorts_state',
341
+ experimentsTargetingArms: 'enum_xp_experiments_targeting_arms',
342
+ experimentsTargetingKind: 'enum_xp_experiments_targeting_kind',
343
+ experimentsTargetingGoalCompleted: 'enum_xp_experiments_targeting_goal_completed',
344
+ experimentsVersionsVersionTargetingArms: 'enum__xp_experiments_v_version_targeting_arms',
345
+ experimentsVersionsVersionTargetingKind: 'enum__xp_experiments_v_version_targeting_kind',
346
+ experimentsVersionsVersionTargetingGoalCompleted: 'enum__xp_experiments_v_version_targeting_goal_completed',
253
347
  experimentsTargetingOp: 'enum_xp_experiments_targeting_op',
254
348
  experimentsArmsKey: 'enum_xp_experiments_arms_key',
255
349
  experimentsArmsKind: 'enum_xp_experiments_arms_kind',
@@ -0,0 +1,21 @@
1
+ import { type Claim } from '../schedule/ranges.js';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { OccupiedInRangeDetail } from '../types/endpoints.js';
4
+ import type { Executor } from './executor.js';
5
+ export interface OccupancyRow {
6
+ id: DocId;
7
+ name: string;
8
+ status?: string;
9
+ claimFrom?: string | Date | null;
10
+ claimTo?: string | Date | null;
11
+ startedAt?: string | Date | null;
12
+ scheduleTimeZone?: string | null;
13
+ }
14
+ export declare const OCCUPYING_STATUSES: string[];
15
+ /** Older live rows have no claim bounds. A standing winner has no scheduled end. */
16
+ export declare function storedClaim(row: Omit<OccupancyRow, 'id' | 'name'>): Claim;
17
+ export declare function overlapsClaim(row: Omit<OccupancyRow, 'id' | 'name'>, claim: Claim): boolean;
18
+ export declare function occupancyDetail(row: OccupancyRow, place: NonNullable<OccupiedInRangeDetail['place']>): OccupiedInRangeDetail;
19
+ export declare function refuseOccupancy(row: OccupancyRow, place: NonNullable<OccupiedInRangeDetail['place']>): never;
20
+ /** Only called on the transition executor after taking the flag point lock. */
21
+ export declare function flagPointClaims(exec: Executor, flagPoint: string): Promise<OccupancyRow[]>;
@@ -0,0 +1,46 @@
1
+ import { XpRefusal } from '../errors.js';
2
+ import { rangesOverlap } from '../schedule/ranges.js';
3
+ import { occupiedInRangeCopy } from '../testSurface/copy/readiness.js';
4
+ import { COLUMNS, TABLES } from './names.js';
5
+ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
6
+ export const OCCUPYING_STATUSES = [
7
+ 'running',
8
+ 'paused',
9
+ 'decided'
10
+ ];
11
+ /** Older live rows have no claim bounds. A standing winner has no scheduled end. */ export function storedClaim(row) {
12
+ return {
13
+ from: new Date(row.claimFrom ?? row.startedAt ?? 0),
14
+ to: row.claimTo == null || row.status === 'decided' || row.status === 'archived' ? null : new Date(row.claimTo)
15
+ };
16
+ }
17
+ export function overlapsClaim(row, claim) {
18
+ return rangesOverlap(storedClaim(row), claim);
19
+ }
20
+ export function occupancyDetail(row, place) {
21
+ const { from, to } = storedClaim(row);
22
+ return {
23
+ otherTestId: row.id,
24
+ otherTestName: row.name,
25
+ from: from.toISOString(),
26
+ to: to?.toISOString() ?? null,
27
+ place,
28
+ ...row.scheduleTimeZone ? {
29
+ timeZone: row.scheduleTimeZone
30
+ } : {}
31
+ };
32
+ }
33
+ export function refuseOccupancy(row, place) {
34
+ const detail = occupancyDetail(row, place);
35
+ throw new XpRefusal('occupied-in-range', occupiedInRangeCopy(detail, place), detail, 409);
36
+ }
37
+ /** Only called on the transition executor after taking the flag point lock. */ export async function flagPointClaims(exec, flagPoint) {
38
+ const c = COLUMNS.experiments;
39
+ const { rows } = await exec.query(`SELECT ${q(c.id)} AS "id", ${q(c.name)} AS "name", ${q(c.status)} AS "status",
40
+ ${q(c.startedAt)} AS "startedAt", ${q(c.claimFrom)} AS "claimFrom", ${q(c.claimTo)} AS "claimTo", ${q(c.scheduleTimeZone)} AS "scheduleTimeZone"
41
+ FROM ${qualifiedTable(exec, TABLES.experiments)}
42
+ WHERE ${q(c.flagPoint)} = $1 AND ${q(c.status)} IN ('running', 'paused', 'decided') ORDER BY ${q(c.id)}`, [
43
+ flagPoint
44
+ ]);
45
+ return rows;
46
+ }
@@ -1,4 +1,4 @@
1
1
  import type { DocId } from '../types/contracts.js';
2
2
  import type { Executor } from './executor.js';
3
- /** Current running round, independent of manifest compilation and typed targeting. */
4
- export declare function pageContentBindings(exec: Executor, collection: string, paths: readonly string[]): Promise<DocId[]>;
3
+ /** Current round, independent of manifest compilation and typed targeting. */
4
+ export declare function pageContentBindings(exec: Executor, collection: string, paths: readonly string[], includePaused?: boolean): Promise<DocId[]>;
@@ -1,14 +1,14 @@
1
1
  import { TABLES, COLUMNS } from './names.js';
2
2
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
3
  import { normalisePath } from '../runtime/normalisePath.js';
4
- /** Current running round, independent of manifest compilation and typed targeting. */ // Legacy tests without pageCollection match the same path in any collection; stored collections narrow the match.
5
- export async function pageContentBindings(exec, collection, paths) {
4
+ /** Current round, independent of manifest compilation and typed targeting. */ // Legacy tests without pageCollection match the same path in any collection; stored collections narrow the match.
5
+ export async function pageContentBindings(exec, collection, paths, includePaused = false) {
6
6
  if (!paths.length) return [];
7
7
  const e = COLUMNS.experiments, p = COLUMNS.phases;
8
8
  const { rows } = await exec.query(`SELECT x.${q(e.id)} AS id, p.${q(p.arms)} AS arms
9
9
  FROM ${qualifiedTable(exec, TABLES.experiments)} x JOIN ${qualifiedTable(exec, TABLES.phases)} p
10
10
  ON p.${q(p.experimentId)} = x.${q(e.id)} AND p.${q(p.phase)} = x.${q(e.phase)}
11
- WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} = 'running'
11
+ WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} ${includePaused ? "IN ('running', 'paused')" : "= 'running'"}
12
12
  AND (x.${q(e.pageCollection)} = $1 OR x.${q(e.pageCollection)} IS NULL)`, [
13
13
  collection
14
14
  ]);
@@ -1,12 +1,12 @@
1
- import type { Arm, DocId } from '../types/contracts.js';
1
+ import type { Arm } from '../types/contracts.js';
2
2
  import type { Executor } from './executor.js';
3
+ import type { OccupancyRow } from './occupancy.js';
3
4
  /** Page tests that occupy paths, with the arms the runtime routes on (`compileManifest`):
4
- * - running or decided: the latest round's arms, or for a rollout the latest test round's;
5
+ * - running, paused or decided: the latest round's arms, or for a rollout the latest test round's;
5
6
  * - archived with a standing result (winner, not discarded, pages not released): the latest test
6
7
  * round's arms whose paths are rewritten to the winner (archivedPages), so a new test cannot
7
8
  * silently take them over.
8
9
  * Documents' arms may have been edited while stopped, so occupancy never reads them. */
9
- export declare function routedPageTests(exec: Executor): Promise<Array<{
10
- id: DocId;
10
+ export declare function routedPageTests(exec: Executor): Promise<Array<OccupancyRow & {
11
11
  arms: Arm[];
12
12
  }>>;
@@ -1,7 +1,7 @@
1
1
  import { COLUMNS, TABLES } from './names.js';
2
2
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
3
  /** Page tests that occupy paths, with the arms the runtime routes on (`compileManifest`):
4
- * - running or decided: the latest round's arms, or for a rollout the latest test round's;
4
+ * - running, paused or decided: the latest round's arms, or for a rollout the latest test round's;
5
5
  * - archived with a standing result (winner, not discarded, pages not released): the latest test
6
6
  * round's arms whose paths are rewritten to the winner (archivedPages), so a new test cannot
7
7
  * silently take them over.
@@ -10,34 +10,37 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
10
10
  const experiments = qualifiedTable(exec, TABLES.experiments), phases = qualifiedTable(exec, TABLES.phases);
11
11
  const testRound = `LEFT JOIN LATERAL (SELECT ${q(p.arms)} AS arms FROM ${phases}
12
12
  WHERE ${q(p.experimentId)} = x.${q(e.id)} AND ${q(p.phaseKind)} = 'test' ORDER BY ${q(p.phase)} DESC LIMIT 1) test ON true`;
13
+ const bounds = `x.${q(e.id)} AS "id", x.${q(e.name)} AS "name", x.${q(e.status)} AS "status",
14
+ x.${q(e.startedAt)} AS "startedAt", x.${q(e.claimFrom)} AS "claimFrom", x.${q(e.claimTo)} AS "claimTo",
15
+ x.${q(e.scheduleTimeZone)} AS "scheduleTimeZone"`;
13
16
  const { rows } = await exec.query(`
14
- SELECT x.${q(e.id)} AS "id", CASE WHEN latest.kind = 'rollout' THEN test.arms ELSE latest.arms END AS "arms", NULL::text AS "winnerArm"
17
+ SELECT ${bounds}, CASE WHEN latest.kind = 'rollout' THEN test.arms ELSE latest.arms END AS "arms", NULL::text AS "winnerArm"
15
18
  FROM ${experiments} x
16
19
  JOIN LATERAL (SELECT ${q(p.phaseKind)} AS kind, ${q(p.arms)} AS arms FROM ${phases}
17
20
  WHERE ${q(p.experimentId)} = x.${q(e.id)} ORDER BY ${q(p.phase)} DESC LIMIT 1) latest ON true
18
21
  ${testRound}
19
- WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} IN ('running', 'decided')
22
+ WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} IN ('running', 'paused', 'decided')
20
23
  UNION ALL
21
- SELECT x.${q(e.id)} AS "id", test.arms AS "arms", x.${q(e.decisionWinnerArm)} AS "winnerArm"
24
+ SELECT ${bounds}, test.arms AS "arms", x.${q(e.decisionWinnerArm)} AS "winnerArm"
22
25
  FROM ${experiments} x
23
26
  ${testRound}
24
27
  WHERE x.${q(e.kind)} = 'page' AND x.${q(e.status)} = 'archived' AND x.${q(e.decisionWinnerArm)} IS NOT NULL
25
28
  AND x.${q(e.decisionDiscardedAt)} IS NULL AND x.${q(e.decisionPagesReleasedAt)} IS NULL
26
29
  ORDER BY "id"`, []);
27
30
  const occupied = [];
28
- for (const row of rows){
29
- const arms = Array.isArray(row.arms) ? row.arms : [];
30
- if (row.winnerArm == null) {
31
+ for (const { arms: frozenArms, winnerArm, ...row } of rows){
32
+ const arms = Array.isArray(frozenArms) ? frozenArms : [];
33
+ if (winnerArm == null) {
31
34
  occupied.push({
32
- id: row.id,
35
+ ...row,
33
36
  arms
34
37
  });
35
38
  continue;
36
39
  }
37
40
  // compileManifest's archivedPages rule: every arm path other than the winner's.
38
- const winnerPath = arms.find((arm)=>arm.key === row.winnerArm)?.pageTarget;
41
+ const winnerPath = arms.find((arm)=>arm.key === winnerArm)?.pageTarget;
39
42
  if (winnerPath) occupied.push({
40
- id: row.id,
43
+ ...row,
41
44
  arms: arms.filter((arm)=>arm.pageTarget && arm.pageTarget !== winnerPath)
42
45
  });
43
46
  }
@@ -1,5 +1,6 @@
1
1
  import type { Pool, PoolClient } from 'pg';
2
2
  export interface Executor {
3
+ schemaName?: string;
3
4
  query<R>(text: string, params?: unknown[]): Promise<{
4
5
  rows: R[];
5
6
  rowCount: number;
@@ -35,6 +36,9 @@ export declare class ResultsBudgetError extends Error {
35
36
  name: string;
36
37
  constructor();
37
38
  }
39
+ /** SQL errors leave a usable connection after rollback. Transport failures and
40
+ * deadline races can leave queries in flight, so those clients must be discarded. */
41
+ export declare function connectionError(error: unknown): Error | undefined;
38
42
  /** Invoke lazily so expired work never starts. Promise.race observes late source
39
43
  * rejections too; clearing the timer keeps successful cron calls from lingering. */
40
44
  export declare function raceDeadline<T>(deadline: number, work: () => Promise<T>): Promise<T>;
@@ -146,7 +146,7 @@ export class ResultsBudgetError extends Error {
146
146
  }
147
147
  }
148
148
  /** SQL errors leave a usable connection after rollback. Transport failures and
149
- * deadline races can leave queries in flight, so those clients must be discarded. */ function connectionError(error) {
149
+ * deadline races can leave queries in flight, so those clients must be discarded. */ export function connectionError(error) {
150
150
  const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
151
151
  if (!(error instanceof ResultsBudgetError) && typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code) && !code.startsWith('08') && !code.startsWith('57P')) return undefined;
152
152
  return error instanceof Error ? error : new Error('Query failed', {
@@ -1,6 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
+ import type { PublicationStatus } from '../blocks/placementPublication.js';
2
3
  import type { Arm, DocId } from '../types/contracts.js';
3
- import type { Executor } from './executor.js';
4
+ import { type Executor } from './executor.js';
4
5
  export interface PlacementDoc {
5
6
  collection: string;
6
7
  id: DocId;
@@ -27,6 +28,10 @@ export declare function removableBlockTests(exec: Executor, slugs: readonly stri
27
28
  export declare function placementPathContent(req: PayloadRequest, collection: string, id: DocId): Promise<(Record<string, unknown> & {
28
29
  id: DocId;
29
30
  }) | null>;
31
+ /** Read localized publication from the main collection's locale table.
32
+ * The caller supplies the IDs selected by the placement read.
33
+ */
34
+ export declare function storedPlacementStatuses(req: PayloadRequest, collection: string, ids: readonly DocId[]): Promise<Map<string, Record<string, PublicationStatus>>>;
30
35
  /** Caller holds E. Never coalesce null: old rounds must continue to scan. */
31
36
  export declare function appendPlacementDoc(exec: Executor, experimentId: DocId, phase: number, doc: PlacementDoc): Promise<void>;
32
37
  /** Deciding a stopped modern round restores routing on its detached rescan.
@@ -1,3 +1,4 @@
1
+ import { pooledExecutor, txExecutor } from './executor.js';
1
2
  import { COLUMNS, TABLES } from './names.js';
2
3
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
4
  /** Raw reads only: guard discovery includes every status, interaction checks filter under the locks. */ export async function placementTests(exec) {
@@ -17,7 +18,7 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
17
18
  /** Indexed slug lookup for the removal guard; startable tests share E with Start before status is rechecked. */ export async function removableBlockTests(exec, slugs) {
18
19
  const e = COLUMNS.experiments;
19
20
  const { rows } = await exec.query(`SELECT ${q(e.id)} AS id, ${q(e.slug)} AS slug, ${q(e.name)} AS name, ${q(e.status)} AS status
20
- FROM ${qualifiedTable(exec, TABLES.experiments)} WHERE ${q(e.slug)} = ANY($1::text[]) AND ${q(e.kind)} = 'block' AND ${q(e.status)} IN ('draft', 'stopped', 'running')`, [
21
+ FROM ${qualifiedTable(exec, TABLES.experiments)} WHERE ${q(e.slug)} = ANY($1::text[]) AND ${q(e.kind)} = 'block' AND ${q(e.status)} IN ('draft', 'stopped', 'running', 'paused')`, [
21
22
  slugs
22
23
  ]);
23
24
  return rows;
@@ -35,6 +36,31 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
35
36
  overrideAccess: true
36
37
  });
37
38
  }
39
+ /** Read localized publication from the main collection's locale table.
40
+ * The caller supplies the IDs selected by the placement read.
41
+ */ export async function storedPlacementStatuses(req, collection, ids) {
42
+ const statuses = new Map();
43
+ if (!ids.length) return statuses;
44
+ const db = req.payload.db;
45
+ // Resolve the adapter's table name, including a collection's custom dbName.
46
+ const camelCase = !/[_:.-]|\s/.test(collection) && /[a-z][A-Z]|[A-Z][a-z]/.test(collection);
47
+ const key = camelCase ? collection.replace(/(.)([A-Z]+)/g, (_match, first, rest)=>`${first} ${[
48
+ ...rest
49
+ ].join(' ')}`) : collection;
50
+ const main = db.tableNameMap.get(key.toLowerCase().replace(/[\W_]+/g, '_').replace(/^_|_$/g, ''));
51
+ if (!main) throw new Error(`The placement table for ${collection} was not found.`);
52
+ const exec = await req.transactionID == null ? pooledExecutor(req.payload) : txExecutor(req);
53
+ const table = qualifiedTable(exec, `${main}${db.localesSuffix}`);
54
+ const params = ids.map((_, i)=>`$${i + 1}`).join(', ');
55
+ const { rows } = await exec.query(`SELECT _parent_id AS id, _locale AS locale, _status AS status FROM ${table} WHERE _parent_id IN (${params})`, [
56
+ ...ids
57
+ ]);
58
+ for (const { id, locale, status } of rows)statuses.set(String(id), {
59
+ ...statuses.get(String(id)),
60
+ [locale]: status
61
+ });
62
+ return statuses;
63
+ }
38
64
  /** Caller holds E. Never coalesce null: old rounds must continue to scan. */ export async function appendPlacementDoc(exec, experimentId, phase, doc) {
39
65
  const p = COLUMNS.phases, column = q(p.placementDocs);
40
66
  await exec.query(`UPDATE ${qualifiedTable(exec, TABLES.phases)} SET ${column} = ${column} || $1::jsonb
@@ -1,6 +1,7 @@
1
1
  import type { DocId } from '../types/contracts.js';
2
2
  import { type Timestamp } from '../results/aggregate.js';
3
3
  import type { Executor } from './executor.js';
4
+ import type { RoundTiming } from '../schedule/types.js';
4
5
  export interface PhaseExposureRow {
5
6
  unitId: string;
6
7
  arm: string;
@@ -29,15 +30,17 @@ type PhaseQuery = {
29
30
  experimentId: DocId;
30
31
  phase: number;
31
32
  endedAt?: Timestamp;
32
- };
33
+ startedAt?: Timestamp;
34
+ } & RoundTiming;
33
35
  /** All phase exposures, including multi-arm rows for firstExposures to exclude. */
34
36
  export declare function phaseExposureRows(exec: Executor, opts: PhaseQuery): Promise<PhaseExposureRow[]>;
35
37
  /** Diagnostic distinct units only; this never contributes to multi-arm exclusion. */
36
38
  export declare function armMismatchCount(exec: Executor, opts: PhaseQuery): Promise<number>;
37
39
  /** All phases are required to identify first-ever exposure for rollout X1. */
38
- export declare function rolloutExposureRows(exec: Executor, { experimentId, respectPhaseEnds }: {
40
+ export declare function rolloutExposureRows(exec: Executor, { experimentId, respectPhaseEnds, now }: {
39
41
  experimentId: DocId;
40
42
  respectPhaseEnds?: boolean;
43
+ now?: Date;
41
44
  }): Promise<RolloutExposureRow[]>;
42
45
  /** events:<name> conversion rows in [from, to). Choose unitIds for stored unit_id,
43
46
  * or userIds for stored user_id (user units and visitor identity credit). Each distinct
@@ -2,6 +2,8 @@ import { timestampMs } from '../results/aggregate.js';
2
2
  import { COLUMNS, TABLES } from './names.js';
3
3
  import { USER_BROWSER_CONVERSION_PREFIX } from '../constants.js';
4
4
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
5
+ import { roundActiveSpec } from '../schedule/roundTime.js';
6
+ import { inactiveTimeFilter } from './cohorts.js';
5
7
  const c = COLUMNS.events;
6
8
  const batchSize = 10_000;
7
9
  const iso = (ts)=>new Date(timestampMs(ts)).toISOString();
@@ -17,7 +19,7 @@ function knownAge(unitAgeMs) {
17
19
  unitAgeMs
18
20
  } : {};
19
21
  }
20
- function phaseFilter({ experimentId, phase, endedAt }, type) {
22
+ function phaseFilter({ experimentId, phase, endedAt, startedAt, schedule, pauses }, type) {
21
23
  const params = [
22
24
  experimentId,
23
25
  phase,
@@ -28,6 +30,15 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
28
30
  params.push(iso(endedAt));
29
31
  text += ` AND ${q(c.ts)} < $4`;
30
32
  }
33
+ if (startedAt !== undefined) text += ` AND ${q(c.ts)} >= $${params.push(iso(startedAt))}`;
34
+ if ((schedule || pauses?.length) && startedAt !== undefined && endedAt !== undefined) {
35
+ text += ` AND ${inactiveTimeFilter(roundActiveSpec({
36
+ schedule
37
+ }), pauses ?? [], {
38
+ from: new Date(timestampMs(startedAt)),
39
+ to: new Date(timestampMs(endedAt))
40
+ }, params)}`;
41
+ }
31
42
  return {
32
43
  text,
33
44
  params
@@ -48,13 +59,29 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
48
59
  const { rows } = await exec.query(`SELECT count(DISTINCT ${q(c.unitId)}) AS "unitCount" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text}`, filter.params);
49
60
  return Number(rows[0].unitCount);
50
61
  }
51
- /** All phases are required to identify first-ever exposure for rollout X1. */ export async function rolloutExposureRows(exec, { experimentId, respectPhaseEnds = false }) {
62
+ /** All phases are required to identify first-ever exposure for rollout X1. */ export async function rolloutExposureRows(exec, { experimentId, respectPhaseEnds = false, now }) {
52
63
  const p = COLUMNS.phases;
53
- const cutoff = respectPhaseEnds ? ` AND NOT EXISTS (SELECT 1 FROM ${qualifiedTable(exec, TABLES.phases)} p WHERE p.${q(p.experimentId)} = ${qualifiedTable(exec, TABLES.events)}.${q(c.experimentId)} AND p.${q(p.phase)} = ${qualifiedTable(exec, TABLES.events)}.${q(c.phase)} AND p.${q(p.endedAt)} <= ${qualifiedTable(exec, TABLES.events)}.${q(c.ts)})` : '';
54
- const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.phase)} AS "phase", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.experimentId)} = $1 AND ${q(c.type)} = $2${cutoff} ORDER BY ${q(c.ts)}, ${q(c.unitId)}, ${q(c.phase)}`, [
64
+ const phases = qualifiedTable(exec, TABLES.phases);
65
+ const params = [
55
66
  experimentId,
56
67
  'exposure'
57
- ]);
68
+ ];
69
+ let cutoff = respectPhaseEnds ? ` AND NOT EXISTS (SELECT 1 FROM ${phases} p WHERE p.${q(p.experimentId)} = event.${q(c.experimentId)} AND p.${q(p.phase)} = event.${q(c.phase)} AND (p.${q(p.endedAt)} <= event.${q(c.ts)} OR p.${q(p.startedAt)} > event.${q(c.ts)}))` : '';
70
+ if (now) {
71
+ cutoff += ` AND ${q(c.ts)} < $${params.push(iso(now))}`;
72
+ const timed = await exec.query(`SELECT ${q(p.phase)} AS "phase", ${q(p.startedAt)} AS "startedAt", ${q(p.endedAt)} AS "endedAt", ${q(p.schedule)} AS "schedule", ${q(p.pauses)} AS "pauses" FROM ${phases} WHERE ${q(p.experimentId)} = $1 AND (${q(p.schedule)} IS NOT NULL OR ${q(p.pauses)} <> '[]'::jsonb)`, [
73
+ experimentId
74
+ ]);
75
+ for (const record of timed.rows){
76
+ const phaseParam = params.push(record.phase);
77
+ const filter = inactiveTimeFilter(roundActiveSpec(record), record.pauses ?? [], {
78
+ from: new Date(timestampMs(record.startedAt)),
79
+ to: new Date(Math.min(+now, record.endedAt == null ? Infinity : timestampMs(record.endedAt)))
80
+ }, params, 'event');
81
+ cutoff += ` AND (event.${q(c.phase)} <> $${phaseParam} OR ${filter})`;
82
+ }
83
+ }
84
+ const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.phase)} AS "phase", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)}${respectPhaseEnds || now ? ' event' : ''} WHERE ${q(c.experimentId)} = $1 AND ${q(c.type)} = $2${cutoff} ORDER BY ${q(c.ts)}, ${q(c.unitId)}, ${q(c.phase)}`, params);
58
85
  return rows.map((row)=>({
59
86
  unitId: row.unitId,
60
87
  phase: Number(row.phase),
@@ -1,18 +1,25 @@
1
1
  import type { Executor } from './executor.js';
2
2
  import type { DocId } from '../types/contracts.js';
3
+ import { type OccupancyRow } from './occupancy.js';
4
+ import type { Claim } from '../schedule/ranges.js';
5
+ export declare function layerClaims(exec: Executor, layerId: DocId): Promise<(OccupancyRow & {
6
+ slices: number[] | null;
7
+ })[]>;
3
8
  /** Reclaim exactly the stopped test's slices while holding the layer lock. */
4
- export declare function reclaimSlices(exec: Executor, { layerId, experimentId, slices }: {
9
+ export declare function reclaimSlices(exec: Executor, { layerId, experimentId, slices, claim }: {
5
10
  layerId: DocId;
6
11
  experimentId: DocId;
7
12
  slices: number[];
13
+ claim: Claim;
8
14
  }): Promise<number[]>;
9
15
  /** Caller holds the layer lock on this transaction executor. Returns additional
10
16
  * free slices; the caller persists them in layerSlices. Existing slices, even
11
17
  * those of experimentId itself, stay occupied until explicitly freed with [].
12
18
  */
13
- export declare function claimSlices(exec: Executor, { layerId, experimentId, count, random }: {
19
+ export declare function claimSlices(exec: Executor, { layerId, experimentId, count, claim, random }: {
14
20
  layerId: DocId;
15
21
  experimentId: DocId;
16
22
  count: number;
23
+ claim?: Claim;
17
24
  random?: () => number;
18
25
  }): Promise<number[]>;
package/dist/db/slices.js CHANGED
@@ -1,11 +1,20 @@
1
1
  import { COLUMNS, TABLES } from './names.js';
2
2
  import { XpRefusal } from '../errors.js';
3
3
  import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
4
- /** Reclaim exactly the stopped test's slices while holding the layer lock. */ export async function reclaimSlices(exec, { layerId, experimentId, slices }) {
4
+ import { overlapsClaim, refuseOccupancy } from './occupancy.js';
5
+ export async function layerClaims(exec, layerId) {
5
6
  const c = COLUMNS.experiments;
6
- const { rows } = await exec.query(`SELECT ${quote(c.layerSlices)} AS slices FROM ${qualifiedTable(exec, TABLES.experiments)} WHERE ${quote(c.layerId)} = $1 AND ${quote(c.status)} IN ('running', 'decided')`, [
7
+ const { rows } = await exec.query(`SELECT ${quote(c.layerSlices)} AS slices, ${quote(c.id)} AS "id", ${quote(c.name)} AS "name", ${quote(c.status)} AS "status",
8
+ ${quote(c.startedAt)} AS "startedAt", ${quote(c.claimFrom)} AS "claimFrom", ${quote(c.claimTo)} AS "claimTo",
9
+ ${quote(c.scheduleTimeZone)} AS "scheduleTimeZone"
10
+ FROM ${qualifiedTable(exec, TABLES.experiments)}
11
+ WHERE ${quote(c.layerId)} = $1 AND ${quote(c.status)} IN ('running', 'paused', 'decided') ORDER BY ${quote(c.id)}`, [
7
12
  layerId
8
13
  ]);
14
+ return rows;
15
+ }
16
+ /** Reclaim exactly the stopped test's slices while holding the layer lock. */ export async function reclaimSlices(exec, { layerId, experimentId, slices, claim }) {
17
+ const rows = (await layerClaims(exec, layerId)).filter((row)=>String(row.id) !== String(experimentId) && overlapsClaim(row, claim));
9
18
  const occupied = new Set(rows.flatMap((row)=>row.slices ?? []));
10
19
  if (slices.some((slice)=>occupied.has(slice))) throw new XpRefusal('slices-taken', 'The original layer slices are now in use.', {
11
20
  layerId,
@@ -18,18 +27,16 @@ import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
18
27
  /** Caller holds the layer lock on this transaction executor. Returns additional
19
28
  * free slices; the caller persists them in layerSlices. Existing slices, even
20
29
  * those of experimentId itself, stay occupied until explicitly freed with [].
21
- */ export async function claimSlices(exec, { layerId, experimentId, count, random = Math.random }) {
30
+ */ export async function claimSlices(exec, { layerId, experimentId, count, claim, random = Math.random }) {
22
31
  if (!Number.isSafeInteger(count) || count < 0) throw new RangeError('Slice count must be a non-negative integer');
23
- const table = qualifiedTable(exec, TABLES.experiments);
24
- const c = COLUMNS.experiments;
25
- const { rows } = await exec.query(`SELECT ${quote(c.layerSlices)} AS slices FROM ${table} WHERE ${quote(c.layerId)} = $1 AND ${quote(c.status)} IN ('running', 'decided')`, [
26
- layerId
27
- ]);
32
+ const rows = (await layerClaims(exec, layerId)).filter((row)=>!claim || overlapsClaim(row, claim));
28
33
  const occupied = new Set(rows.flatMap((row)=>row.slices ?? []));
29
34
  const free = Array.from({
30
35
  length: 100
31
36
  }, (_, slice)=>slice).filter((slice)=>!occupied.has(slice));
32
37
  if (free.length < count) {
38
+ const other = claim && rows.find((row)=>String(row.id) !== String(experimentId) && row.slices?.length);
39
+ if (other) refuseOccupancy(other, 'traffic group');
33
40
  throw new XpRefusal('layer-full', 'There is not enough room in this layer.', {
34
41
  layerId,
35
42
  experimentId,