@delmaredigital/payload-experiments 0.4.1 → 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 +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/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 +44 -8
  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
@@ -5,6 +5,8 @@ import { TEST_PAGE as C } from '../../../testSurface/copy/testPage.js';
5
5
  import { formatAdminURL } from '../../../testSurface/format/adminURL.js';
6
6
  import { surfaceUrls } from '../../../testSurface/surfaceUrls.js';
7
7
  import { Button } from '../../../ui/Button.js';
8
+ import { useScheduleClock } from '../../../testSurface/format/useScheduleClock.js';
9
+ import { scheduleStatus } from '../../../testSurface/format/scheduleStatus.js';
8
10
  import { StatusChip } from '../../../ui/StatusChip.js';
9
11
  import { useXpStepNav } from '../useXpStepNav.js';
10
12
  import { SurfaceShell } from '../SurfaceShell.js';
@@ -22,6 +24,10 @@ export function TestPage({ id, surface, onTitleChange }) {
22
24
  }
23
25
  function TestPageFrame({ test, surface, children }) {
24
26
  const doc = test.doc;
27
+ const now = useScheduleClock(doc ? [
28
+ doc
29
+ ] : [], surface.timeZone);
30
+ const schedule = doc ? scheduleStatus(doc, now, test.preflight?.timing, surface.timeZone, test.preflight?.pauseAttribution) : undefined;
25
31
  const crumbs = [
26
32
  {
27
33
  label: C.tests,
@@ -47,10 +53,14 @@ function TestPageFrame({ test, surface, children }) {
47
53
  children: C.kinds[doc.kind]
48
54
  }),
49
55
  !test.statusReadPending ? /*#__PURE__*/ _jsx(StatusChip, {
50
- status: doc.status
56
+ status: schedule?.status ?? doc.status
51
57
  }) : null
52
58
  ]
53
59
  }) : undefined,
60
+ subtitle: !test.statusReadPending && schedule?.line ? /*#__PURE__*/ _jsx("p", {
61
+ role: "status",
62
+ children: schedule.line
63
+ }) : undefined,
54
64
  actions: doc && !test.statusReadPending && surface.canReadResults && doc.status !== 'draft' ? /*#__PURE__*/ _jsx(Button, {
55
65
  variant: "secondary",
56
66
  href: formatAdminURL({
@@ -4,7 +4,7 @@ export declare function useLayerExperiments(layerId: DocId | null): {
4
4
  free: number;
5
5
  rows: {
6
6
  name: string;
7
- status: import("../types/contracts.js").Status;
7
+ status: import("../types/status.js").Status;
8
8
  slices: number;
9
9
  }[];
10
10
  } | null;
@@ -67,6 +67,9 @@ export async function buildSurfaceProps({ req, route, id, searchParams }) {
67
67
  },
68
68
  adminRoute,
69
69
  apiRoute: req.payload.config.routes.api,
70
+ ...options.timeZone ? {
71
+ timeZone: options.timeZone
72
+ } : {},
70
73
  ...req.payload.config.localization ? {
71
74
  contentLanguageLabels: placementLanguageNames(req, req.payload.config.localization.localeCodes)
72
75
  } : {},
@@ -0,0 +1,35 @@
1
+ import type { FrozenCohortRule } from './rule.js';
2
+ import type { ResolvedOptions } from '../types/contracts.js';
3
+ import { type ResultsPhase } from '../db/snapshots.js';
4
+ import { type CohortSource } from '../db/cohorts.js';
5
+ import { type Executor } from '../db/executor.js';
6
+ import { XpRefusal } from '../errors.js';
7
+ export declare function cohortClosed(phase: ResultsPhase, now: Date): boolean;
8
+ export declare function cohortExposureQuery(phase: ResultsPhase, now: Date): {
9
+ experiment: import("../types/contracts.js").DocId;
10
+ phase: number;
11
+ from: Date;
12
+ to: Date;
13
+ inactive: {
14
+ from: Date;
15
+ to: Date;
16
+ }[];
17
+ };
18
+ type BuildOptions = {
19
+ budgetMs: number;
20
+ now: Date;
21
+ options: Pick<ResolvedOptions, 'eventSources' | 'metricSources'>;
22
+ readExec: Executor;
23
+ source?: CohortSource;
24
+ };
25
+ export declare function deriveCohort(exec: Executor, rule: FrozenCohortRule, { now, options, readExec, source }: Omit<BuildOptions, 'budgetMs'>, deadline: number): Promise<{
26
+ members: number;
27
+ }>;
28
+ export declare function cohortBuildTimeout(cohortKeys: string[]): XpRefusal;
29
+ /** Build and mark the audience ready on the caller's transaction. */
30
+ export declare function buildCohort(exec: Executor, rule: FrozenCohortRule, opts: BuildOptions): Promise<{
31
+ members: number;
32
+ }>;
33
+ /** Hold every key from the first build through the transition's commit. */
34
+ export declare function buildStartCohorts(exec: Executor, rules: FrozenCohortRule[], sources: Map<string, CohortSource>, opts: BuildOptions): Promise<void>;
35
+ export {};
@@ -0,0 +1,134 @@
1
+ import { roundActiveSpec } from '../schedule/roundTime.js';
2
+ import { inactiveIntervals } from '../schedule/activeTime.js';
3
+ import { timestampMs } from '../results/aggregate.js';
4
+ import { metricUnitValues, readUnitMetricEvents, unitValueContext } from '../results/unitValues.js';
5
+ import { LATE_BEACON_GRACE_MS } from '../db/snapshots.js';
6
+ import { cohortExposureUnits, isCohortTimeout, readCohort, readCohortSource, replaceExposureCohort, replaceGoalCohort, withCohortTimeout, writeCohort } from '../db/cohorts.js';
7
+ import { ResultsBudgetError } from '../db/executor.js';
8
+ import { lockCohortErasure, lockCohorts, sortLockKeys } from '../db/locks.js';
9
+ import { XpRefusal } from '../errors.js';
10
+ import { COHORT_COPY } from '../testSurface/copy/cohorts.js';
11
+ export function cohortClosed(phase, now) {
12
+ return phase.endedAt != null && +now >= timestampMs(phase.endedAt) + LATE_BEACON_GRACE_MS;
13
+ }
14
+ export function cohortExposureQuery(phase, now) {
15
+ const from = new Date(timestampMs(phase.startedAt));
16
+ const spec = roundActiveSpec(phase);
17
+ const to = new Date(Math.min(+now, phase.endedAt == null ? Infinity : timestampMs(phase.endedAt), spec.to ? timestampMs(spec.to) : Infinity));
18
+ const inactive = inactiveIntervals(spec, phase.pauses ?? [], {
19
+ from,
20
+ to
21
+ });
22
+ return {
23
+ experiment: phase.experiment,
24
+ phase: phase.phase,
25
+ from,
26
+ to,
27
+ inactive
28
+ };
29
+ }
30
+ export async function deriveCohort(exec, rule, { now, options, readExec, source }, deadline) {
31
+ source ??= await readCohortSource(readExec, rule.experiment, rule.phase);
32
+ if (!source) throw new XpRefusal('cohort-source-invalid', COHORT_COPY.invalid, {
33
+ reason: 'round'
34
+ }, 422);
35
+ const { phase, unitType } = source;
36
+ const closed = cohortClosed(phase, now);
37
+ const query = cohortExposureQuery(phase, now);
38
+ let members;
39
+ if (!rule.goal) {
40
+ // The write statement reads committed exposure rows on the transaction and
41
+ // materializes them in SQL without transferring ids to the application.
42
+ members = await replaceExposureCohort(exec, rule.key, now, query, rule.arms);
43
+ } else {
44
+ if (!rule.goal.completed && !closed) throw new XpRefusal('cohort-source-open', COHORT_COPY.open, undefined, 422);
45
+ const definition = phase.metricDefinitions?.find((metric)=>String(metric.metricId) === rule.goal.metricId);
46
+ if (!definition) throw new XpRefusal('cohort-source-invalid', COHORT_COPY.invalid, {
47
+ reason: 'goal'
48
+ }, 422);
49
+ const exposed = await cohortExposureUnits(readExec, query);
50
+ const units = new Map(exposed.map((unit)=>[
51
+ unit.unitId,
52
+ {
53
+ arm: unit.arm,
54
+ firstTs: new Date(unit.firstTs)
55
+ }
56
+ ]));
57
+ const context = await unitValueContext(readExec, unitType, units);
58
+ const metric = await readUnitMetricEvents(readExec, {
59
+ phase,
60
+ unitType,
61
+ units,
62
+ context,
63
+ definition,
64
+ options,
65
+ to: query.to,
66
+ deadline
67
+ });
68
+ const { values } = metricUnitValues(units, definition, metric, query.to);
69
+ const arms = new Set(rule.arms);
70
+ const desired = [
71
+ ...units.keys()
72
+ ].filter((id)=>arms.has(units.get(id).arm) && (rule.goal.completed ? values.get(id) > 0 : values.get(id) === 0));
73
+ members = await replaceGoalCohort(exec, rule.key, now, desired);
74
+ }
75
+ await writeCohort(exec, rule, {
76
+ closed,
77
+ members,
78
+ now
79
+ });
80
+ return {
81
+ members
82
+ };
83
+ }
84
+ export function cohortBuildTimeout(cohortKeys) {
85
+ return new XpRefusal('cohort-build-timeout', COHORT_COPY.timeout, {
86
+ cohortKeys
87
+ }, 409);
88
+ }
89
+ /** Build and mark the audience ready on the caller's transaction. */ export async function buildCohort(exec, rule, opts) {
90
+ const deadline = Date.now() + opts.budgetMs;
91
+ try {
92
+ return await withCohortTimeout(exec, deadline, async (timed)=>{
93
+ await lockCohortErasure(timed);
94
+ await lockCohorts(timed, [
95
+ rule.key
96
+ ]);
97
+ const existing = await readCohort(timed, rule.key);
98
+ if (existing?.closed) return {
99
+ members: existing.members
100
+ };
101
+ return deriveCohort(timed, rule, opts, deadline);
102
+ });
103
+ } catch (error) {
104
+ if (isCohortTimeout(error)) throw cohortBuildTimeout([
105
+ rule.key
106
+ ]);
107
+ throw error;
108
+ }
109
+ }
110
+ /** Hold every key from the first build through the transition's commit. */ export async function buildStartCohorts(exec, rules, sources, opts) {
111
+ const keys = sortLockKeys(rules.map((rule)=>rule.key));
112
+ if (!keys.length) return;
113
+ const deadline = Date.now() + opts.budgetMs;
114
+ try {
115
+ await withCohortTimeout(exec, deadline, async (timed)=>{
116
+ await lockCohortErasure(timed);
117
+ await lockCohorts(timed, keys);
118
+ for (const key of keys){
119
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
120
+ const rule = rules.find((rule)=>rule.key === key);
121
+ const existing = await readCohort(timed, key);
122
+ if (existing && (existing.closed || rule.goal)) continue;
123
+ await deriveCohort(timed, rule, {
124
+ ...opts,
125
+ now: new Date(),
126
+ source: sources.get(key)
127
+ }, deadline);
128
+ }
129
+ });
130
+ } catch (error) {
131
+ if (isCohortTimeout(error)) throw cohortBuildTimeout(keys);
132
+ throw error;
133
+ }
134
+ }
@@ -0,0 +1,12 @@
1
+ import type { CohortRule } from './rule.js';
2
+ type KeyRule = Omit<CohortRule, 'phase' | 'experiment' | 'goal'> & {
3
+ phase: number;
4
+ experiment: string | number;
5
+ goal?: {
6
+ metricId: string | number;
7
+ completed: boolean;
8
+ };
9
+ };
10
+ /** Server-only key. Object fields are emitted in lexical order at both levels. */
11
+ export declare function cohortKey(rule: KeyRule): string;
12
+ export {};
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** Server-only key. Object fields are emitted in lexical order at both levels. */ export function cohortKey(rule) {
3
+ const canonical = JSON.stringify({
4
+ arms: [
5
+ ...rule.arms
6
+ ].sort(),
7
+ experiment: String(rule.experiment),
8
+ goal: rule.goal ? {
9
+ completed: rule.goal.completed,
10
+ metricId: String(rule.goal.metricId)
11
+ } : null,
12
+ phase: rule.phase
13
+ });
14
+ return createHash('sha256').update('xp:cohort:' + canonical).digest('hex').slice(0, 16);
15
+ }
@@ -0,0 +1,10 @@
1
+ import type { Payload } from 'payload';
2
+ export declare function refreshCohorts(payload: Payload, { budgetMs, now }: {
3
+ budgetMs: number;
4
+ now?: Date;
5
+ }): Promise<void>;
6
+ export declare function sweepCohorts(payload: Payload, { now, retentionDays, deadline }: {
7
+ now: Date;
8
+ retentionDays: number;
9
+ deadline: number;
10
+ }): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { inCohortTransaction } from '../db/cohortTransactions.js';
2
+ import { cohortIsReferenced, isCohortTimeout, readCohort, readCohortSource, refreshableCohortKeys, sweepableCohortKeys, sweepCohortKey, withCohortTimeout } from '../db/cohorts.js';
3
+ import { lockCohortErasure, lockCohorts } from '../db/locks.js';
4
+ import { LATE_BEACON_GRACE_MS, resultsExecutor } from '../db/snapshots.js';
5
+ import { safeError } from '../log.js';
6
+ import { XpRefusal } from '../errors.js';
7
+ import { deriveCohort } from './build.js';
8
+ import { DAY_MS } from '../schedule/roundTime.js';
9
+ export async function refreshCohorts(payload, { budgetMs, now = new Date() }) {
10
+ const deadline = Date.now() + budgetMs;
11
+ const options = payload.config.custom?.xp;
12
+ if (budgetMs <= 0) return;
13
+ const readExec = resultsExecutor(payload, ()=>deadline - Date.now());
14
+ try {
15
+ for (const key of (await refreshableCohortKeys(readExec))){
16
+ if (Date.now() >= deadline) break;
17
+ try {
18
+ await inCohortTransaction(payload, deadline, (exec)=>withCohortTimeout(exec, deadline, async (timed)=>{
19
+ await lockCohortErasure(timed);
20
+ await lockCohorts(timed, [
21
+ key
22
+ ]);
23
+ const current = await readCohort(timed, key);
24
+ if (!current || current.closed || +new Date(current.builtAt) >= +now || !await cohortIsReferenced(timed, key)) return;
25
+ const source = await readCohortSource(timed, current.rule.experiment, current.rule.phase);
26
+ if (!source || source.phase.endedAt != null && +new Date(source.phase.endedAt) < +now - (options.events?.retentionDays ?? 180) * DAY_MS) return;
27
+ await deriveCohort(timed, {
28
+ ...current.rule,
29
+ include: true
30
+ }, {
31
+ now,
32
+ options,
33
+ readExec,
34
+ source
35
+ }, deadline);
36
+ }));
37
+ } catch (error) {
38
+ if (isCohortTimeout(error) || error instanceof XpRefusal && error.code === 'cohort-build-timeout') break;
39
+ payload.logger.warn({
40
+ err: safeError(error)
41
+ }, 'Experiment audience refresh failed');
42
+ }
43
+ }
44
+ } catch (error) {
45
+ if (!isCohortTimeout(error)) payload.logger.warn({
46
+ err: safeError(error)
47
+ }, 'Experiment audience refresh could not be scheduled');
48
+ }
49
+ }
50
+ export async function sweepCohorts(payload, { now, retentionDays, deadline }) {
51
+ const readExec = resultsExecutor(payload, ()=>deadline - Date.now());
52
+ const stale = new Date(+now - LATE_BEACON_GRACE_MS);
53
+ const cutoff = new Date(+now - retentionDays * DAY_MS);
54
+ try {
55
+ for (const key of (await sweepableCohortKeys(readExec, stale, cutoff))){
56
+ if (Date.now() >= deadline) return;
57
+ await inCohortTransaction(payload, deadline, (exec)=>withCohortTimeout(exec, deadline, async (timed)=>{
58
+ await lockCohortErasure(timed);
59
+ await lockCohorts(timed, [
60
+ key
61
+ ]);
62
+ await sweepCohortKey(timed, key, stale, cutoff);
63
+ }));
64
+ }
65
+ } catch (error) {
66
+ if (!isCohortTimeout(error)) payload.logger.warn({
67
+ err: safeError(error)
68
+ }, 'Experiment audience retention sweep failed');
69
+ }
70
+ }
@@ -0,0 +1,30 @@
1
+ import type { CohortSource } from '../db/cohorts.js';
2
+ import type { DocId, TargetingRule } from '../types/contracts.js';
3
+ import { type CohortRule } from './rule.js';
4
+ export type CohortReadinessCode = 'cohort-source-invalid' | 'cohort-cycle' | 'cohort-source-open' | 'cohort-lookup-missing';
5
+ export declare const isCohortReadiness: (code: string) => code is CohortReadinessCode;
6
+ export type CohortSourceIssue = 'source' | 'self' | 'round' | 'arms' | 'goal' | 'no-exposure' | 'retention' | 'invalid-rule';
7
+ type CohortFact = {
8
+ source?: CohortSource;
9
+ sourceName?: string;
10
+ hasExposure?: boolean;
11
+ cycle?: boolean;
12
+ };
13
+ export type CohortFacts = {
14
+ proxyLookup: boolean;
15
+ now: Date;
16
+ cutoff: Date;
17
+ rules: Map<number, CohortFact>;
18
+ };
19
+ export declare function checkCohorts(experiment: {
20
+ id: DocId;
21
+ targeting?: Array<TargetingRule | CohortRule> | null;
22
+ }, facts?: CohortFacts): {
23
+ code: CohortReadinessCode;
24
+ ok: boolean;
25
+ detail?: {
26
+ rule: number;
27
+ reason?: CohortSourceIssue;
28
+ };
29
+ }[];
30
+ export {};
@@ -0,0 +1,54 @@
1
+ import { cohortClosed } from './build.js';
2
+ import { timestampMs } from '../results/aggregate.js';
3
+ import { isCohortRule, readCohortRule } from './rule.js';
4
+ export const isCohortReadiness = (code)=>code.startsWith('cohort-') && code !== 'cohort-build-timeout';
5
+ function invalidSource(rule, fact, cutoff) {
6
+ const phase = fact?.source?.phase;
7
+ if (!phase) return 'round';
8
+ if (phase.phaseKind !== 'test') return 'round';
9
+ if (phase.endedAt != null && timestampMs(phase.endedAt) < +cutoff) return 'retention';
10
+ if (rule.arms.some((arm)=>!phase.arms.some((version)=>version.key === arm))) return 'arms';
11
+ if (rule.goal && !phase.metricDefinitions?.some((metric)=>String(metric.metricId) === rule.goal.metricId)) return 'goal';
12
+ if (!fact?.hasExposure) return 'no-exposure';
13
+ }
14
+ export function checkCohorts(experiment, facts) {
15
+ const checks = [];
16
+ if (!facts?.proxyLookup && experiment.targeting?.some(isCohortRule)) {
17
+ checks.push({
18
+ code: 'cohort-lookup-missing',
19
+ ok: false
20
+ });
21
+ return checks;
22
+ }
23
+ for (const [index, row] of (experiment.targeting ?? []).entries()){
24
+ if (!isCohortRule(row)) continue;
25
+ const rule = readCohortRule(row);
26
+ const fact = facts?.rules.get(index);
27
+ const reason = !rule ? 'invalid-rule' : rule.experiment === String(experiment.id) ? 'self' : !fact ? 'source' : invalidSource(rule, fact, facts.cutoff);
28
+ if (reason) checks.push({
29
+ code: 'cohort-source-invalid',
30
+ ok: false,
31
+ detail: {
32
+ rule: index,
33
+ reason
34
+ }
35
+ });
36
+ if (fact?.cycle) checks.push({
37
+ code: 'cohort-cycle',
38
+ ok: false,
39
+ detail: {
40
+ rule: index
41
+ }
42
+ });
43
+ if (rule?.goal?.completed === false && fact?.source && !cohortClosed(fact.source.phase, facts.now)) {
44
+ checks.push({
45
+ code: 'cohort-source-open',
46
+ ok: false,
47
+ detail: {
48
+ rule: index
49
+ }
50
+ });
51
+ }
52
+ }
53
+ return checks;
54
+ }
@@ -0,0 +1,29 @@
1
+ import { type PayloadRequest } from 'payload';
2
+ import type { ResolvedOptions } from '../types/contracts.js';
3
+ import type { StartExperiment } from '../transitions/checkStart.js';
4
+ import { type CohortSource } from '../db/cohorts.js';
5
+ import { type Executor } from '../db/executor.js';
6
+ import { type FrozenCohortRule } from './rule.js';
7
+ import type { CohortFacts } from './readiness.js';
8
+ /** A detached Local API request must retain Fetch prototype properties for
9
+ * host access callbacks and get its own Payload data loader. */
10
+ export declare function cohortReadRequest(req: PayloadRequest): PayloadRequest;
11
+ export declare function reachesTarget(exec: Executor, source: string, target: string, dependencies?: Map<string, string[]>): Promise<boolean>;
12
+ export declare function loadCohortFacts(req: PayloadRequest, exec: Executor, experiment: StartExperiment, options: Pick<ResolvedOptions, 'cohorts' | 'events'>, system: boolean, now: Date, deadline?: number): Promise<CohortFacts>;
13
+ /** Called only after the readiness checks have passed on these facts. */
14
+ export declare function freezeCohortTargeting(experiment: StartExperiment, facts: CohortFacts): {
15
+ targeting: (import("../types/contracts.js").TargetingRule | {
16
+ key: string;
17
+ experiment: string;
18
+ phase: number;
19
+ arms: import("../types/armKey.js").ArmKey[];
20
+ kind: "cohort";
21
+ goal?: {
22
+ metricId: string;
23
+ completed: boolean;
24
+ };
25
+ include: boolean;
26
+ })[];
27
+ rules: FrozenCohortRule[];
28
+ sources: Map<string, CohortSource>;
29
+ };
@@ -0,0 +1,123 @@
1
+ import { Forbidden, NotFound } from 'payload';
2
+ import { findStartDocuments } from '../transitions/startReads.js';
3
+ import { cohortDependencies, hasExposure, readCohortSource } from '../db/cohorts.js';
4
+ import { raceDeadline } from '../db/executor.js';
5
+ import { isCohortRule, readCohortRule } from './rule.js';
6
+ import { cohortExposureQuery } from './build.js';
7
+ import { DAY_MS } from '../schedule/roundTime.js';
8
+ import { cohortKey } from './key.js';
9
+ /** A detached Local API request must retain Fetch prototype properties for
10
+ * host access callbacks and get its own Payload data loader. */ export function cohortReadRequest(req) {
11
+ const detached = {
12
+ ...req,
13
+ headers: req.headers,
14
+ url: req.url,
15
+ method: req.method,
16
+ signal: req.signal,
17
+ context: {
18
+ ...req.context
19
+ },
20
+ transactionID: undefined
21
+ };
22
+ const { payloadDataLoader: _loader, ...read } = detached;
23
+ return read;
24
+ }
25
+ export async function reachesTarget(exec, source, target, dependencies = new Map()) {
26
+ const pending = [
27
+ source
28
+ ];
29
+ const visited = new Set();
30
+ while(pending.length){
31
+ const id = pending.pop();
32
+ if (id === target) return true;
33
+ if (visited.has(id)) continue;
34
+ visited.add(id);
35
+ let edges = dependencies.get(id);
36
+ if (!edges) {
37
+ edges = await cohortDependencies(exec, id);
38
+ dependencies.set(id, edges);
39
+ }
40
+ for (const edge of edges)pending.push(edge);
41
+ }
42
+ return false;
43
+ }
44
+ export async function loadCohortFacts(req, exec, experiment, options, system, now, deadline) {
45
+ const proxyLookup = options.cohorts?.proxyLookup === true;
46
+ const facts = {
47
+ proxyLookup,
48
+ now,
49
+ cutoff: new Date(+now - (options.events?.retentionDays ?? 180) * DAY_MS),
50
+ rules: new Map()
51
+ };
52
+ if (!proxyLookup) return facts;
53
+ const dependencies = new Map();
54
+ const target = String(experiment.id);
55
+ for (const [index, row] of (experiment.targeting ?? []).entries()){
56
+ const rule = readCohortRule(row);
57
+ if (!rule || rule.experiment === target) continue;
58
+ // An access refusal must not roll back an enclosing Start transaction.
59
+ const detachedReq = cohortReadRequest(req);
60
+ const read = async ()=>{
61
+ try {
62
+ const result = await findStartDocuments(detachedReq, {
63
+ collection: 'xp-experiments',
64
+ depth: 0,
65
+ limit: 1,
66
+ where: {
67
+ id: {
68
+ equals: rule.experiment
69
+ }
70
+ }
71
+ }, system);
72
+ return result.docs[0];
73
+ } catch (error) {
74
+ if (error instanceof Forbidden || error instanceof NotFound || [
75
+ 'Forbidden',
76
+ 'NotFound'
77
+ ].includes(error?.name ?? '')) return undefined;
78
+ throw error;
79
+ }
80
+ };
81
+ const visible = deadline === undefined ? await read() : await raceDeadline(deadline, read);
82
+ if (!visible) continue;
83
+ const source = await readCohortSource(exec, visible.id, rule.phase);
84
+ const cycle = await reachesTarget(exec, String(visible.id), target, dependencies);
85
+ const exposed = source ? await hasExposure(exec, cohortExposureQuery(source.phase, now)) : false;
86
+ facts.rules.set(index, {
87
+ source,
88
+ sourceName: typeof visible.name === 'string' ? visible.name : undefined,
89
+ cycle,
90
+ hasExposure: exposed
91
+ });
92
+ }
93
+ return facts;
94
+ }
95
+ /** Called only after the readiness checks have passed on these facts. */ export function freezeCohortTargeting(experiment, facts) {
96
+ const rules = [];
97
+ const sources = new Map();
98
+ const targeting = (experiment.targeting ?? []).map((row, index)=>{
99
+ if (!isCohortRule(row)) return row;
100
+ const rule = readCohortRule(row);
101
+ const source = facts.rules.get(index).source;
102
+ const resolved = {
103
+ ...rule,
104
+ experiment: String(source.phase.experiment),
105
+ phase: source.phase.phase,
106
+ arms: [
107
+ ...rule.arms
108
+ ].sort()
109
+ };
110
+ const frozen = {
111
+ ...resolved,
112
+ key: cohortKey(resolved)
113
+ };
114
+ rules.push(frozen);
115
+ sources.set(frozen.key, source);
116
+ return frozen;
117
+ });
118
+ return {
119
+ targeting,
120
+ rules,
121
+ sources
122
+ };
123
+ }
@@ -0,0 +1,33 @@
1
+ import type { ArmKey, DocId } from '../types/contracts.js';
2
+ export type CohortRule = {
3
+ kind: 'cohort';
4
+ experiment: string;
5
+ phase: number | 'latest';
6
+ arms: ArmKey[];
7
+ goal?: {
8
+ metricId: string;
9
+ completed: boolean;
10
+ };
11
+ include: boolean;
12
+ };
13
+ export type FrozenCohortRule = Omit<CohortRule, 'phase'> & {
14
+ phase: number;
15
+ key: string;
16
+ };
17
+ export declare const COHORT_ARMS: readonly ["control", "variantA", "variantB", "variantC", "holdout"];
18
+ export declare function isCohortRule(rule: unknown): rule is CohortRule | FrozenCohortRule;
19
+ export declare function cohortRelationshipId(value: unknown): DocId | undefined;
20
+ /** Read either Payload's flattened array row or a rule already in domain form. */
21
+ export declare function readCohortRule(row: unknown): CohortRule | undefined;
22
+ export type StoredCohortRule = ReturnType<typeof writeCohortRule> & {
23
+ id?: string;
24
+ };
25
+ export declare function writeCohortRule(rule: CohortRule): {
26
+ kind: "cohort";
27
+ sourceExperiment: string;
28
+ sourcePhase: number | null;
29
+ arms: ArmKey[];
30
+ goalMetric: string | null;
31
+ goalCompleted: string | null;
32
+ include: boolean;
33
+ };
@@ -0,0 +1,50 @@
1
+ export const COHORT_ARMS = [
2
+ 'control',
3
+ 'variantA',
4
+ 'variantB',
5
+ 'variantC',
6
+ 'holdout'
7
+ ];
8
+ export function isCohortRule(rule) {
9
+ return typeof rule === 'object' && rule !== null && 'kind' in rule && rule.kind === 'cohort';
10
+ }
11
+ export function cohortRelationshipId(value) {
12
+ const id = value && typeof value === 'object' && 'id' in value ? value.id : value;
13
+ if (typeof id === 'string' && id.trim() || typeof id === 'number' && Number.isSafeInteger(id)) return id;
14
+ }
15
+ /** Read either Payload's flattened array row or a rule already in domain form. */ export function readCohortRule(row) {
16
+ if (!isCohortRule(row)) return;
17
+ const fields = row;
18
+ const experiment = cohortRelationshipId(fields.sourceExperiment ?? fields.experiment);
19
+ const phase = fields.sourcePhase ?? fields.phase ?? 'latest';
20
+ const metric = cohortRelationshipId(fields.goalMetric ?? fields.goal?.metricId);
21
+ if (metric === undefined && (fields.goalCompleted != null || fields.goal != null)) return;
22
+ const completed = fields.goalMetric != null ? fields.goalCompleted === 'completed' ? true : fields.goalCompleted === 'notCompleted' ? false : undefined : fields.goal?.completed;
23
+ if (experiment === undefined || phase !== 'latest' && !(typeof phase === 'number' && Number.isSafeInteger(phase) && phase > 0) || !Array.isArray(fields.arms) || !fields.arms.length || !fields.arms.every((arm)=>COHORT_ARMS.includes(arm)) || metric !== undefined && typeof completed !== 'boolean') return;
24
+ return {
25
+ kind: 'cohort',
26
+ experiment: String(experiment),
27
+ phase: phase,
28
+ arms: [
29
+ ...fields.arms
30
+ ],
31
+ ...metric === undefined ? {} : {
32
+ goal: {
33
+ metricId: String(metric),
34
+ completed: completed
35
+ }
36
+ },
37
+ include: fields.include !== false
38
+ };
39
+ }
40
+ export function writeCohortRule(rule) {
41
+ return {
42
+ kind: rule.kind,
43
+ sourceExperiment: rule.experiment,
44
+ sourcePhase: rule.phase === 'latest' ? null : rule.phase,
45
+ arms: rule.arms,
46
+ goalMetric: rule.goal?.metricId ?? null,
47
+ goalCompleted: rule.goal ? rule.goal.completed ? 'completed' : 'notCompleted' : null,
48
+ include: rule.include
49
+ };
50
+ }
@@ -0,0 +1,4 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ import type { ResolvedOptions } from '../types/contracts.js';
3
+ export declare function cohortMembersCollection(options: ResolvedOptions): CollectionConfig;
4
+ export declare function cohortsCollection(options: ResolvedOptions): CollectionConfig;