@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
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,
@@ -1,11 +1,15 @@
1
+ import type { FrozenCohortRule } from '../cohorts/rule.js';
2
+ import type { TargetingRule } from '../types/contracts.js';
1
3
  import type { Payload } from 'payload';
2
4
  import type { Arm, DocId, ExperimentKind, Status, UnitType } from '../types/contracts.js';
3
5
  import type { PlacementDoc } from './placements.js';
4
6
  import type { Snapshot } from '../types/snapshot.js';
5
7
  import type { AnalysisPhase, FrozenMetric } from '../results/analyse.js';
6
8
  import { type Executor } from './executor.js';
9
+ import type { RoundTiming } from '../schedule/types.js';
7
10
  export interface ResultsPhase extends AnalysisPhase {
8
11
  arms: Array<AnalysisPhase['arms'][number] & Pick<Arm, 'pageTarget'>>;
12
+ targeting?: Array<TargetingRule | FrozenCohortRule>;
9
13
  seed: string;
10
14
  allocation: number;
11
15
  metricDefinitions: Array<FrozenMetric & {
@@ -27,7 +31,7 @@ export interface ResultsCandidate {
27
31
  currentPhase?: number;
28
32
  winnerArm?: string | null;
29
33
  unitType: UnitType;
30
- status: 'running' | 'stopped' | 'decided' | 'archived';
34
+ status: Exclude<Status, 'draft'>;
31
35
  latestComputedAt: string | null;
32
36
  testArms: Array<{
33
37
  key: string;
@@ -42,6 +46,12 @@ export interface ResultsCandidate {
42
46
  /** Each query gets its own pooled connection and timeout transaction. A failed
43
47
  * metric query cannot poison the next metric's transaction. */
44
48
  export declare function resultsExecutor(payload: Payload, timeoutMs: () => number): Executor;
49
+ export declare const LATE_BEACON_GRACE_MS: number;
50
+ /** The claim end mirrors the frozen schedule. Stop verifies the phase under its locks. */
51
+ export declare function dueScheduledStops(exec: Executor, now: string, experimentId?: DocId): Promise<{
52
+ id: DocId;
53
+ phase: number;
54
+ }[]>;
45
55
  /** Scheduling and immutable assignment metadata only; metric/config data comes
46
56
  * from the phase JSON, never from live metric or experiment analysis fields. */
47
57
  export declare function resultsCandidates(exec: Executor, { cutoff, experimentId }: {
@@ -55,6 +65,11 @@ export declare function writeSnapshots(exec: Executor, snapshots: Snapshot[]): P
55
65
  /** Fetch pointers only, then the endpoint reads the bounded set through Payload
56
66
  * with req/overrideAccess:false. Called behind the readResults/manage gate. */
57
67
  export declare function newestSnapshotIds(exec: Executor, ids: DocId[], per: 'phase' | 'experiment'): Promise<DocId[]>;
68
+ /** Current timing for the bounded results summary, even before the first snapshot. */
69
+ export declare function currentRoundTiming(exec: Executor, ids: DocId[]): Promise<(RoundTiming & {
70
+ experiment: DocId;
71
+ phase: number;
72
+ })[]>;
58
73
  type ResultsMetadata = {
59
74
  name: string | null;
60
75
  kind: ExperimentKind;
@@ -16,7 +16,21 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
16
16
  }
17
17
  // CORE-16 README: allow late beacons for 24 hours after a phase ends, then keep
18
18
  // its final snapshot frozen. This is internal scheduling policy, not public API.
19
- const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
19
+ export const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
20
+ /** The claim end mirrors the frozen schedule. Stop verifies the phase under its locks. */ export async function dueScheduledStops(exec, now, experimentId) {
21
+ const e = COLUMNS.experiments;
22
+ const { rows } = await exec.query(`SELECT ${q(e.id)} AS "id", ${q(e.phase)} AS "phase"
23
+ FROM ${qualifiedTable(exec, TABLES.experiments)}
24
+ WHERE ${q(e.status)} = 'running' AND ${q(e.claimTo)} <= $1
25
+ ${experimentId === undefined ? '' : `AND ${q(e.id)} = $2`}
26
+ ORDER BY ${q(e.claimTo)}, ${q(e.id)}`, experimentId === undefined ? [
27
+ now
28
+ ] : [
29
+ now,
30
+ experimentId
31
+ ]);
32
+ return rows;
33
+ }
20
34
  /** Scheduling and immutable assignment metadata only; metric/config data comes
21
35
  * from the phase JSON, never from live metric or experiment analysis fields. */ export async function resultsCandidates(exec, { cutoff, experimentId }) {
22
36
  const p = COLUMNS.phases, e = COLUMNS.experiments, s = COLUMNS.resultsSnapshots, l = COLUMNS.layers;
@@ -30,7 +44,8 @@ const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
30
44
  jsonb_build_object('experiment', p.${q(p.experimentId)}, 'phase', p.${q(p.phase)}, 'phaseKind', p.${q(p.phaseKind)},
31
45
  'startedAt', p.${q(p.startedAt)}, 'endedAt', p.${q(p.endedAt)}, 'seed', p.${q(p.seed)},
32
46
  'arms', p.${q(p.arms)}, 'allocation', p.${q(p.allocation)}, 'metricDefinitions', p.${q(p.metricDefinitions)},
33
- 'analysis', p.${q(p.analysis)}, 'contentChanges', p.${q(p.contentChanges)}) AS "phase",
47
+ 'analysis', p.${q(p.analysis)}, 'targeting', p.${q(p.targeting)}, 'contentChanges', p.${q(p.contentChanges)},
48
+ 'schedule', p.${q(p.schedule)}, 'pauses', p.${q(p.pauses)}) AS "phase",
34
49
  e.${q(e.slug)} AS "slug",
35
50
  (SELECT t.${q(p.placementDocs)} FROM ${phases} t WHERE t.${q(p.experimentId)} = p.${q(p.experimentId)} AND t.${q(p.phaseKind)} = 'test' AND t.${q(p.phase)} <= p.${q(p.phase)} ORDER BY t.${q(p.phase)} DESC LIMIT 1) AS "testPlacementDocs",
36
51
  e.${q(e.pageCollection)} AS "pageCollection", e.${q(e.kind)} AS "kind", e.${q(e.phase)} AS "currentPhase", e.${q(e.unitType)} AS "unitType", e.${q(e.status)} AS "status", e.${q(e.decisionWinnerArm)} AS "winnerArm",
@@ -99,6 +114,16 @@ export async function writeSnapshot(exec, snapshot) {
99
114
  const { rows } = await exec.query(`SELECT DISTINCT ON (${partition}) ${q(c.id)} AS "id" FROM ${qualifiedTable(exec, TABLES.resultsSnapshots)} WHERE ${q(c.experimentId)} IN (${placeholders.join(', ')}) ORDER BY ${partition}, ${q(c.computedAt)} DESC, ${q(c.id)} DESC`, params);
100
115
  return rows.map((row)=>row.id);
101
116
  }
117
+ /** Current timing for the bounded results summary, even before the first snapshot. */ export async function currentRoundTiming(exec, ids) {
118
+ if (!ids.length) return [];
119
+ const p = COLUMNS.phases, e = COLUMNS.experiments;
120
+ const { rows } = await exec.query(`SELECT p.${q(p.experimentId)} AS "experiment", p.${q(p.phase)} AS "phase", p.${q(p.schedule)} AS "schedule", p.${q(p.pauses)} AS "pauses"
121
+ FROM ${qualifiedTable(exec, TABLES.phases)} p JOIN ${qualifiedTable(exec, TABLES.experiments)} e
122
+ ON e.${q(e.id)} = p.${q(p.experimentId)} AND e.${q(e.phase)} = p.${q(p.phase)}
123
+ WHERE p.${q(p.experimentId)} IN (${ids.map((_, index)=>`$${index + 1}`).join(', ')}) AND p.${q(p.endedAt)} IS NULL
124
+ AND (p.${q(p.schedule)} IS NOT NULL OR p.${q(p.pauses)} <> '[]'::jsonb)`, ids);
125
+ return rows;
126
+ }
102
127
  /** Called only behind the endpoint's readResults gate. Experiment collection
103
128
  * reads require manage, so read only the identity and decision metadata needed by results. */ export async function resultsMetadata(exec, id) {
104
129
  const c = COLUMNS.experiments;
package/dist/db/sql.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Executor } from './executor.js';
1
+ import type { Executor } from './pgExecutor.js';
2
2
  /** Quote schema/table/column identifiers; data values still use parameters. */
3
3
  export declare const quoteIdentifier: (name: string) => string;
4
4
  /** Preserve the schema carried by the request's executor for raw plugin SQL. */
5
- export declare function qualifiedTable(exec: Executor, name: string): string;
5
+ export declare function qualifiedTable({ schemaName }: Partial<Executor>, name: string): string;
package/dist/db/sql.js CHANGED
@@ -1,5 +1,4 @@
1
1
  /** Quote schema/table/column identifiers; data values still use parameters. */ export const quoteIdentifier = (name)=>`"${name.replaceAll('"', '""')}"`;
2
- /** Preserve the schema carried by the request's executor for raw plugin SQL. */ export function qualifiedTable(exec, name) {
3
- const schemaName = exec.schemaName;
2
+ /** Preserve the schema carried by the request's executor for raw plugin SQL. */ export function qualifiedTable({ schemaName }, name) {
4
3
  return `${schemaName ? `${quoteIdentifier(schemaName)}.` : ''}${quoteIdentifier(name)}`;
5
4
  }
@@ -0,0 +1,16 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ import type { CohortSourceRound, EndpointContext } from '../types/endpoints.js';
4
+ /** Load saved choices directly so a previously chosen source is available even outside the search cap. */
5
+ export declare function savedCohortSources<TUser extends {
6
+ id: DocId;
7
+ }>(req: PayloadRequest, options: EndpointContext<TUser>['options'], ids: string[]): Promise<{
8
+ id: DocId;
9
+ name: string;
10
+ status: "running" | "decided" | "draft" | "paused" | "stopped" | "archived" | "scheduled";
11
+ unitType: import("../types/contracts.js").UnitType;
12
+ rounds: CohortSourceRound[];
13
+ }[]>;
14
+ export declare function handleCohortSources<TUser extends {
15
+ id: DocId;
16
+ }>(req: PayloadRequest, { options }: EndpointContext<TUser>): Promise<Response>;
@@ -0,0 +1,335 @@
1
+ import { latestCohortRounds } from '../db/cohorts.js';
2
+ import { reachesTarget } from '../cohorts/readinessData.js';
3
+ import { cohortRelationshipId } from '../cohorts/rule.js';
4
+ import { pooledExecutor } from '../db/executor.js';
5
+ import { LATE_BEACON_GRACE_MS } from '../db/snapshots.js';
6
+ import { timestampMs } from '../results/aggregate.js';
7
+ import { COHORT_EDITOR } from '../testSurface/copy/cohorts.js';
8
+ import { displayStatus } from '../testSurface/labels.js';
9
+ import { experimentId } from './routeId.js';
10
+ import { phasesCollection } from '../collections/phases.js';
11
+ import { readSnapshots, resultsError } from './results.js';
12
+ const PAGE_SIZE = 20;
13
+ /** Round numbers and dates follow xp-phases read access exactly: the collection's own access function
14
+ * (built from the same options), called with the manager's req. */ async function canReadPhases(req, options) {
15
+ // phasesCollection reads only options.access.
16
+ const read = phasesCollection(options).access?.read;
17
+ if (typeof read !== 'function') return false;
18
+ try {
19
+ return await read({
20
+ req
21
+ }) === true;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ const LIVE = [
27
+ 'running',
28
+ 'paused'
29
+ ];
30
+ const PAST = [
31
+ 'draft',
32
+ 'stopped',
33
+ 'decided',
34
+ 'archived'
35
+ ];
36
+ function roundDates(start, end) {
37
+ return {
38
+ startedAt: new Date(timestampMs(start)).toISOString(),
39
+ endedAt: end == null ? null : new Date(timestampMs(end)).toISOString(),
40
+ closedAt: end == null ? null : new Date(timestampMs(end) + LATE_BEACON_GRACE_MS).toISOString()
41
+ };
42
+ }
43
+ function roundVersions(arms) {
44
+ return arms.map(({ key, label, kind })=>({
45
+ key: key,
46
+ label,
47
+ kind
48
+ }));
49
+ }
50
+ function snapshotEstimate({ computedAt, snapshot }, round) {
51
+ return {
52
+ computedAt,
53
+ perArm: Object.fromEntries(round.arms.map(({ key })=>[
54
+ key,
55
+ {
56
+ exposed: snapshot.exposures.perArm[key] ?? 0,
57
+ converters: Object.fromEntries(snapshot.metrics.flatMap((metric)=>{
58
+ const count = metric.unavailable === undefined ? metric.perArm.find((arm)=>arm.arm === key)?.converters : undefined;
59
+ return count === undefined ? [] : [
60
+ [
61
+ String(metric.metricId),
62
+ count
63
+ ]
64
+ ];
65
+ }))
66
+ }
67
+ ]))
68
+ };
69
+ }
70
+ async function frozenRounds(req, ids) {
71
+ const { docs } = await req.payload.find({
72
+ collection: 'xp-phases',
73
+ req,
74
+ overrideAccess: false,
75
+ depth: 0,
76
+ pagination: false,
77
+ limit: 0,
78
+ where: {
79
+ and: [
80
+ {
81
+ experiment: {
82
+ in: ids
83
+ }
84
+ },
85
+ {
86
+ phaseKind: {
87
+ equals: 'test'
88
+ }
89
+ }
90
+ ]
91
+ },
92
+ sort: '-phase'
93
+ });
94
+ const roundsByTest = new Map();
95
+ for (const record of docs.sort((a, b)=>b.phase - a.phase)){
96
+ const key = String(record.experiment);
97
+ const rounds = roundsByTest.get(key) ?? [];
98
+ rounds.push({
99
+ phase: record.phase,
100
+ ...roundDates(record.startedAt, record.endedAt),
101
+ arms: roundVersions(record.arms),
102
+ goals: record.metricDefinitions.map(({ metricId, name })=>({
103
+ metricId,
104
+ name
105
+ }))
106
+ });
107
+ roundsByTest.set(key, rounds);
108
+ }
109
+ return roundsByTest;
110
+ }
111
+ function metricIds(metrics) {
112
+ return [
113
+ metrics?.primary,
114
+ ...metrics?.secondary ?? [],
115
+ ...metrics?.guardrails ?? []
116
+ ].flatMap((value)=>{
117
+ const id = cohortRelationshipId(value);
118
+ return id == null ? [] : [
119
+ id
120
+ ];
121
+ });
122
+ }
123
+ /** Without xp-phases read access, show no round number or dates: only the test document's own fields. */ async function currentRounds(req, candidates) {
124
+ const goals = [
125
+ ...new Set(candidates.flatMap((doc)=>metricIds(doc.metrics)))
126
+ ];
127
+ const names = new Map();
128
+ if (goals.length) {
129
+ const { docs } = await req.payload.find({
130
+ collection: 'xp-metrics',
131
+ req,
132
+ overrideAccess: false,
133
+ depth: 0,
134
+ pagination: false,
135
+ limit: 0,
136
+ where: {
137
+ id: {
138
+ in: goals
139
+ }
140
+ },
141
+ select: {
142
+ name: true
143
+ }
144
+ });
145
+ for (const doc of docs)names.set(String(doc.id), String(doc.name));
146
+ }
147
+ const roundsByTest = new Map();
148
+ for (const doc of candidates){
149
+ roundsByTest.set(String(doc.id), [
150
+ {
151
+ phase: null,
152
+ startedAt: null,
153
+ endedAt: null,
154
+ closedAt: null,
155
+ arms: roundVersions(doc.arms),
156
+ goals: metricIds(doc.metrics).flatMap((metricId)=>{
157
+ const name = names.get(String(metricId));
158
+ return name === undefined ? [] : [
159
+ {
160
+ metricId,
161
+ name
162
+ }
163
+ ];
164
+ })
165
+ }
166
+ ]);
167
+ }
168
+ return roundsByTest;
169
+ }
170
+ async function optionsFor(req, candidates, phasesReadable, now) {
171
+ if (!candidates.length) return [];
172
+ const rounds = phasesReadable ? await frozenRounds(req, candidates.map((doc)=>doc.id)) : await currentRounds(req, candidates);
173
+ return candidates.flatMap((doc)=>{
174
+ const available = rounds.get(String(doc.id));
175
+ return available?.length ? [
176
+ {
177
+ id: doc.id,
178
+ name: doc.name,
179
+ status: displayStatus(doc, now),
180
+ unitType: doc.unitType,
181
+ rounds: available
182
+ }
183
+ ] : [];
184
+ });
185
+ }
186
+ async function addEstimates(req, sources) {
187
+ if (!sources.length) return;
188
+ const snapshots = await readSnapshots(req, sources.map((source)=>source.id));
189
+ const byRound = new Map(snapshots.map((snapshot)=>[
190
+ JSON.stringify([
191
+ String(cohortRelationshipId(snapshot.experiment)),
192
+ snapshot.phase
193
+ ]),
194
+ snapshot
195
+ ]));
196
+ for (const source of sources){
197
+ for (const round of source.rounds){
198
+ const snapshot = byRound.get(JSON.stringify([
199
+ String(source.id),
200
+ round.phase
201
+ ]));
202
+ if (snapshot) round.estimate = snapshotEstimate(snapshot, round);
203
+ }
204
+ }
205
+ }
206
+ const selectCandidate = {
207
+ name: true,
208
+ status: true,
209
+ unitType: true,
210
+ startedAt: true,
211
+ arms: {
212
+ key: true,
213
+ label: true,
214
+ kind: true
215
+ },
216
+ metrics: true
217
+ };
218
+ /** Load saved choices directly so a previously chosen source is available even outside the search cap. */ export async function savedCohortSources(req, options, ids) {
219
+ const wanted = ids.flatMap((id)=>{
220
+ const stored = experimentId(req, id);
221
+ return stored === undefined ? [] : [
222
+ stored
223
+ ];
224
+ });
225
+ if (!wanted.length) return [];
226
+ const canRead = await (options.access.readResults ?? options.access.manage)({
227
+ req
228
+ }) === true;
229
+ const { docs } = await req.payload.find({
230
+ collection: 'xp-experiments',
231
+ req,
232
+ overrideAccess: false,
233
+ depth: 0,
234
+ pagination: false,
235
+ limit: 0,
236
+ where: {
237
+ id: {
238
+ in: wanted
239
+ }
240
+ },
241
+ select: selectCandidate
242
+ });
243
+ const phasesReadable = await canReadPhases(req, options);
244
+ const sources = await optionsFor(req, docs, phasesReadable, Date.now());
245
+ if (canRead && phasesReadable) await addEstimates(req, sources);
246
+ return sources;
247
+ }
248
+ export async function handleCohortSources(req, { options }) {
249
+ const url = new URL(req.url ?? 'http://localhost');
250
+ const q = url.searchParams.get('q') ?? '';
251
+ const rawExclude = url.searchParams.get('exclude');
252
+ const exclude = rawExclude == null ? undefined : experimentId(req, rawExclude, 'query');
253
+ if (url.searchParams.getAll('q').length > 1 || url.searchParams.getAll('exclude').length > 1 || q.length > 100 || /[\x00-\x1f\x7f\ufffd]/.test(q) || rawExclude != null && (!rawExclude.trim() || rawExclude !== rawExclude.trim() || rawExclude.length > 128 || /[\x00-\x20\x7f\ufffd,]/.test(rawExclude) || exclude === undefined)) {
254
+ return resultsError(400, 'invalid-body', COHORT_EDITOR.invalidSearch);
255
+ }
256
+ const term = q.trim().replace(/[\\%_]/g, '\\$&');
257
+ const canRead = await (options.access.readResults ?? options.access.manage)({
258
+ req
259
+ }) === true;
260
+ const now = Date.now();
261
+ const phasesReadable = await canReadPhases(req, options);
262
+ const dependencies = new Map();
263
+ const exec = pooledExecutor(req.payload);
264
+ const selected = [];
265
+ for (const statuses of [
266
+ LIVE,
267
+ PAST
268
+ ]){
269
+ if (selected.length === PAGE_SIZE) break;
270
+ const and = [
271
+ {
272
+ status: {
273
+ in: statuses
274
+ }
275
+ }
276
+ ];
277
+ if (term) and.push({
278
+ or: [
279
+ {
280
+ name: {
281
+ contains: term
282
+ }
283
+ },
284
+ {
285
+ slug: {
286
+ contains: term
287
+ }
288
+ }
289
+ ]
290
+ });
291
+ if (exclude !== undefined) and.push({
292
+ id: {
293
+ not_equals: exclude
294
+ }
295
+ });
296
+ const { docs } = await req.payload.find({
297
+ collection: 'xp-experiments',
298
+ req,
299
+ overrideAccess: false,
300
+ depth: 0,
301
+ pagination: false,
302
+ limit: 0,
303
+ where: {
304
+ and
305
+ },
306
+ select: selectCandidate
307
+ });
308
+ const candidates = docs;
309
+ // Only tests with a test round are listed. Without xp-phases access the phase rows decide existence
310
+ // only; nothing from them is returned, and ordering uses the test document's own start time.
311
+ const latestRounds = await latestCohortRounds(exec, candidates.map((doc)=>doc.id));
312
+ const started = new Map(latestRounds.map((round)=>[
313
+ String(round.id),
314
+ phasesReadable ? timestampMs(round.startedAt) : (()=>{
315
+ const doc = candidates.find((candidate)=>String(candidate.id) === String(round.id));
316
+ return doc?.startedAt ? timestampMs(doc.startedAt) : 0;
317
+ })()
318
+ ]));
319
+ const ordered = candidates.filter((doc)=>started.has(String(doc.id))).sort((a, b)=>started.get(String(b.id)) - started.get(String(a.id)) || String(a.id).localeCompare(String(b.id)));
320
+ for (const doc of ordered){
321
+ if (selected.length === PAGE_SIZE) break;
322
+ if (exclude !== undefined && await reachesTarget(exec, String(doc.id), String(exclude), dependencies)) continue;
323
+ selected.push(doc);
324
+ }
325
+ }
326
+ const docs = await optionsFor(req, selected, phasesReadable, now);
327
+ if (canRead && phasesReadable) await addEstimates(req, docs);
328
+ return Response.json({
329
+ docs
330
+ }, {
331
+ headers: {
332
+ 'Cache-Control': 'private, no-store'
333
+ }
334
+ });
335
+ }
@@ -2,5 +2,5 @@ import { type PayloadRequest } from 'payload';
2
2
  /** Validate advisory-read metadata language; placement discovery still scans all languages. */
3
3
  export declare function contentLocale(req: PayloadRequest): {
4
4
  locale: string | null | undefined;
5
- fallbackLocale: false | "none" | "false" | "null" | ({} & string) | ({} & string)[] | null | undefined;
5
+ fallbackLocale: false | "false" | "none" | "null" | ({} & string) | ({} & string)[] | null | undefined;
6
6
  };