@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
@@ -5,19 +5,23 @@ import { NextRequest } from 'next/server.js';
5
5
  import { DEFAULT_MAX_BODY_BYTES } from '../constants.js';
6
6
  import { pooledExecutor } from '../db/executor.js';
7
7
  import { insertEvents } from '../db/events.js';
8
+ import { readManifestRow } from '../db/manifest.js';
8
9
  import { EventsBodyError, readEvents } from '../events/body.js';
9
10
  import { isPreview } from '../events/preview.js';
10
11
  import { eventRequestContext, publicEventOrigin } from '../events/request.js';
11
12
  import { eventRows } from '../events/rows.js';
12
13
  import { assign } from '../runtime/assign.js';
14
+ import { cohortKeysToResolve, isEntryActive } from '../runtime/eligibility.js';
13
15
  import { isBot } from '../runtime/bot.js';
14
16
  import { readSignedUnit } from '../runtime/cookie.js';
15
17
  import { requestAttributes } from '../runtime/normalisePath.js';
16
18
  import { serverManifest } from '../server/context.js';
19
+ import { resolveServerCohorts } from '../server/cohortLookup.js';
17
20
  const accepted = ()=>Response.json({}, {
18
21
  status: 202
19
22
  });
20
23
  const originDrops = new WeakMap();
24
+ const inactiveDrops = new WeakMap();
21
25
  function logSessionLookupError(payload, error) {
22
26
  try {
23
27
  payload.logger.error({
@@ -25,25 +29,40 @@ function logSessionLookupError(payload, error) {
25
29
  }, 'Experiments: events session lookup failed');
26
30
  } catch {}
27
31
  }
28
- function countOriginDrop(payload, now) {
29
- const drops = originDrops.get(payload) ?? {
32
+ function countDrop(payload, counts, now) {
33
+ const drops = counts.get(payload) ?? {
30
34
  count: 0,
31
35
  nextLogAt: 0
32
36
  };
33
- originDrops.set(payload, drops);
34
- drops.count++;
37
+ counts.set(payload, drops);
38
+ drops.count += 1;
35
39
  if (now < drops.nextLogAt) return;
36
40
  drops.nextLogAt = now + 60_000;
37
41
  try {
38
- payload.logger.warn({
39
- droppedRequests: drops.count
40
- }, 'Experiments: browser event requests dropped by origin check');
42
+ if (counts === originDrops) {
43
+ payload.logger.warn({
44
+ droppedRequests: drops.count
45
+ }, 'Experiments: browser event requests dropped by origin check');
46
+ } else {
47
+ payload.logger.warn({
48
+ droppedRequests: drops.count
49
+ }, 'Experiments: browser event requests with exposures dropped for inactive or unavailable tests');
50
+ }
41
51
  drops.count = 0;
42
52
  } catch {}
43
53
  }
54
+ function isExposure(event) {
55
+ return event !== null && typeof event === 'object' && 'type' in event && event.type === 'exposure' && 'experiment' in event && typeof event.experiment === 'string' && 'phase' in event && typeof event.phase === 'number' && 'arm' in event && typeof event.arm === 'string' && 'policy' in event && typeof event.policy === 'string' && [
56
+ 'manual',
57
+ 'viewport',
58
+ 'pageview'
59
+ ].includes(event.policy);
60
+ }
44
61
  export async function handleEvents(req, { options }) {
45
- const receivedAt = Date.now();
46
62
  const runtime = options.runtime, proxy = runtime.proxyRuntime;
63
+ const clock = proxy.now ?? (()=>new Date(Date.now()));
64
+ const receipt = clock();
65
+ const receivedAt = receipt.getTime();
47
66
  const unitCookie = readSignedUnit(req.headers, proxy, receivedAt);
48
67
  const visitorId = unitCookie?.unitId;
49
68
  const issuedAtMs = unitCookie?.issuedAtMs;
@@ -55,7 +74,7 @@ export async function handleEvents(req, { options }) {
55
74
  });
56
75
  const { allowed, source } = eventRequestContext(request, options.events?.origin ?? publicEventOrigin(req.payload.config?.serverURL));
57
76
  if (!allowed) {
58
- countOriginDrop(req.payload, receivedAt);
77
+ countDrop(req.payload, originDrops, receivedAt);
59
78
  return accepted();
60
79
  }
61
80
  // API paths bypass the proxy: re-check consent even when a stale signed cookie exists.
@@ -113,8 +132,8 @@ export async function handleEvents(req, { options }) {
113
132
  }) !== true) return accepted();
114
133
  }
115
134
  const events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
116
- const manifest = await serverManifest(proxy);
117
- if (!manifest) return accepted();
135
+ const cached = await serverManifest(proxy);
136
+ if (!cached) return accepted();
118
137
  const unit = source || !useProxySession ? await proxy.getUnit?.(source ?? request) : requestUnit;
119
138
  // The beacon URL is an API route, not the page whose content was rendered.
120
139
  // A referrer supplies page context only, never an identity or an assigned arm.
@@ -126,13 +145,58 @@ export async function handleEvents(req, { options }) {
126
145
  ...serverAttributes
127
146
  }, source?.nextUrl.pathname);
128
147
  const unresolvedStaff = Boolean(options.attributeKeys?.staff && !user && (sessionUnresolved || unit?.sessionUnknown || requestUnit?.sessionUnknown));
129
- const assignments = assign(manifest, {
148
+ const exec = events.some(isExposure) ? pooledExecutor(req.payload) : undefined;
149
+ // A manual pause removes the entry at commit. Recheck committed routing state
150
+ // before accepting exposures even while the request caches still serve it.
151
+ const committed = exec && await readManifestRow(exec).then((row)=>row?.manifest, (error)=>{
152
+ try {
153
+ req.payload.logger.error({
154
+ err: safeError(error)
155
+ }, 'Experiments: committed exposure state unavailable');
156
+ } catch {}
157
+ return undefined;
158
+ });
159
+ const manifest = committed ?? cached;
160
+ const validatedAt = clock();
161
+ const sessionUnknown = sessionUnresolved || requestUnit?.sessionUnknown === true;
162
+ let droppedInactiveExposure = false;
163
+ const cohortEntries = new Set();
164
+ const eligibleEvents = events.filter((event)=>{
165
+ if (!isExposure(event)) return true;
166
+ const entry = committed && committed.experiments.find((exp)=>exp.slug === event.experiment);
167
+ if (entry && isEntryActive(entry, receipt) && isEntryActive(entry, validatedAt)) {
168
+ if (entry.cohorts?.length && event.phase === entry.phase && event.policy === entry.exposurePolicy) cohortEntries.add(entry);
169
+ return true;
170
+ }
171
+ droppedInactiveExposure = true;
172
+ return false;
173
+ });
174
+ if (droppedInactiveExposure) countDrop(req.payload, inactiveDrops, receivedAt);
175
+ const ids = {
130
176
  visitorId,
131
177
  userId
132
- }, attributes, {
133
- now: Math.floor(Date.now() / 1000),
178
+ };
179
+ const keysToResolve = cohortEntries.size ? cohortKeysToResolve({
180
+ ...manifest,
181
+ experiments: [
182
+ ...cohortEntries
183
+ ]
184
+ }, ids, attributes, {
185
+ now: validatedAt,
186
+ sessionUnknown
187
+ }) : [];
188
+ const cohorts = keysToResolve.length ? await resolveServerCohorts(req.payload, {
189
+ ...ids,
190
+ keys: keysToResolve
191
+ }) : undefined;
192
+ const assignmentAt = keysToResolve.length ? clock() : validatedAt;
193
+ const cohortRejected = new Set();
194
+ const assignments = assign(manifest, ids, attributes, {
195
+ now: assignmentAt,
134
196
  method: req.method,
135
- sessionUnknown: sessionUnresolved,
197
+ sessionUnknown,
198
+ cohorts,
199
+ onCohortIneligible: (slug)=>cohortRejected.add(slug),
136
200
  staff: requestUnit?.attributes.staff === true || unit?.attributes.staff === true || attributes.staff === true,
137
201
  bot: isBot(req.headers.get('user-agent')),
138
202
  preview: isPreview(request)
@@ -140,10 +204,10 @@ export async function handleEvents(req, { options }) {
140
204
  if (unresolvedStaff) for (const assignment of Object.values(assignments.bySlug))assignment.exposable = false;
141
205
  const keys = events.some((event)=>event && typeof event === 'object' && 'eventName' in event && validClickSource(event.eventName)) ? await clickKeys(req.payload) : undefined;
142
206
  // Age measures arrival. Keep attribution at the time the round was validated.
143
- const rows = eventRows(events, manifest, assignments, options, visitorId, userId, new Date().toISOString(), unitAgeMs, attributes, keys);
144
- // §7.8 events insert / assignment lookup exception: pooled SQL and cached manifest,
207
+ const rows = eventRows(eligibleEvents, manifest, assignments, options, visitorId, userId, validatedAt.toISOString(), unitAgeMs, attributes, keys, unresolvedStaff ? undefined : cohortRejected);
208
+ // §7.8 events insert / assignment lookup exception: pooled SQL,
145
209
  // no Local API calls (and hence no implicit overrideAccess defaults).
146
- if (rows.length) await insertEvents(pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
210
+ if (rows.length) await insertEvents(exec ?? pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
147
211
  } catch (error) {
148
212
  if (error instanceof EventsBodyError) return Response.json({
149
213
  errors: [
@@ -6,7 +6,7 @@ import { XP_MANIFEST_KEY_HEADER } from '../constants.js';
6
6
  import { XpNotImplemented, XpRefusal } from '../errors.js';
7
7
  import { handleManifest } from './manifest.js';
8
8
  import { handleEvents } from './events.js';
9
- import { handleStart, handleAllocate, handleAddMetric, handleStop, handleDecide, handleReleaseHoldout, handleReleasePages, handleMakeContent, handleDismissContentEntry, handleRestoreContentEntry, handleArchive } from './transitions.js';
9
+ import { handleBuildCohorts, handleStart, handleAllocate, handleAddMetric, handleStop, handlePause, handleResume, handleReschedule, handleCancelSchedule, handleDecide, handleReleaseHoldout, handleReleasePages, handleMakeContent, handleDismissContentEntry, handleRestoreContentEntry, handleArchive } from './transitions.js';
10
10
  import { handlePreflight } from './preflight.js';
11
11
  import { handleTestVersion } from './testVersion.js';
12
12
  import { handlePreviewToken } from './previewToken.js';
@@ -14,9 +14,11 @@ import { handleResults } from './results.js';
14
14
  import { handleRecompute } from './recompute.js';
15
15
  import { handleWrapBlock } from './wrapBlock.js';
16
16
  import { handleDuplicateOriginal } from './duplicateOriginal.js';
17
+ import { handleCohortSources } from './cohortSources.js';
17
18
  import { handlePages } from './pages.js';
18
19
  import { handlePlacementStatus } from './placementStatus.js';
19
20
  import { handleSummary } from './summary.js';
21
+ import { handlePausedBy } from './pausedBy.js';
20
22
  export const ROUTES = [
21
23
  {
22
24
  method: 'get',
@@ -30,6 +32,12 @@ export const ROUTES = [
30
32
  access: 'browserEvents',
31
33
  handler: handleEvents
32
34
  },
35
+ {
36
+ method: 'post',
37
+ path: '/xp/experiments/:id/build-cohorts',
38
+ access: 'manage',
39
+ handler: handleBuildCohorts
40
+ },
33
41
  {
34
42
  method: 'post',
35
43
  path: '/xp/experiments/:id/start',
@@ -54,6 +62,30 @@ export const ROUTES = [
54
62
  access: 'manage',
55
63
  handler: handleStop
56
64
  },
65
+ {
66
+ method: 'post',
67
+ path: '/xp/experiments/:id/pause',
68
+ access: 'manage',
69
+ handler: handlePause
70
+ },
71
+ {
72
+ method: 'post',
73
+ path: '/xp/experiments/:id/resume',
74
+ access: 'manage',
75
+ handler: handleResume
76
+ },
77
+ {
78
+ method: 'post',
79
+ path: '/xp/experiments/:id/reschedule',
80
+ access: 'manage',
81
+ handler: handleReschedule
82
+ },
83
+ {
84
+ method: 'post',
85
+ path: '/xp/experiments/:id/cancel-schedule',
86
+ access: 'manage',
87
+ handler: handleCancelSchedule
88
+ },
57
89
  {
58
90
  method: 'post',
59
91
  path: '/xp/experiments/:id/decide',
@@ -138,6 +170,12 @@ export const ROUTES = [
138
170
  access: 'readResults',
139
171
  handler: handleSummary
140
172
  },
173
+ {
174
+ method: 'get',
175
+ path: '/xp/experiments/paused-by',
176
+ access: 'manage',
177
+ handler: handlePausedBy
178
+ },
141
179
  {
142
180
  method: 'post',
143
181
  path: '/xp/blocks/wrap',
@@ -156,6 +194,12 @@ export const ROUTES = [
156
194
  access: 'manage',
157
195
  handler: handlePages
158
196
  },
197
+ {
198
+ method: 'get',
199
+ path: '/xp/cohort-sources',
200
+ access: 'manage',
201
+ handler: handleCohortSources
202
+ },
159
203
  {
160
204
  method: 'get',
161
205
  path: '/xp/experiments/:id/duplicate-original',
@@ -0,0 +1,14 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { DocId, Status } from '../types/contracts.js';
3
+ import type { PauseAttribution } from '../types/endpoints.js';
4
+ type TestPause = {
5
+ id: DocId;
6
+ status: Status;
7
+ pausedAt?: string | null;
8
+ pausedBy?: string | null;
9
+ };
10
+ /** Resolve only the host's configured title, through the viewing manager's access. */
11
+ export declare function readPauseAttributions(req: PayloadRequest, tests: readonly TestPause[]): Promise<Map<string, PauseAttribution>>;
12
+ /** Supply every paused list row with at most one host user collection read. */
13
+ export declare function handlePausedBy(req: PayloadRequest): Promise<Response>;
14
+ export {};
@@ -0,0 +1,94 @@
1
+ import { collectionIDType } from './routeId.js';
2
+ /** Resolve only the host's configured title, through the viewing manager's access. */ export async function readPauseAttributions(req, tests) {
3
+ const paused = tests.filter((test)=>test.status === 'paused' && typeof test.pausedBy === 'string' && test.pausedBy.length > 0);
4
+ const ids = [
5
+ ...new Set(paused.map((test)=>test.pausedBy))
6
+ ];
7
+ const [id] = ids;
8
+ const attributions = new Map();
9
+ const collection = req.payload.config.admin?.user;
10
+ if (!id || !collection) return attributions;
11
+ const config = req.payload.config.collections.find((entry)=>entry.slug === collection);
12
+ if (!config) return attributions;
13
+ const title = config.admin?.useAsTitle;
14
+ const field = title && title !== 'id' ? title : 'email';
15
+ const select = {
16
+ [field]: true
17
+ };
18
+ const userIds = collectionIDType(req, collection) === 'number' ? ids.map(Number).filter(Number.isFinite) : ids;
19
+ const [userId] = userIds;
20
+ if (userId === undefined) return attributions;
21
+ try {
22
+ // A single test can use collection read rules that depend on the requested user id.
23
+ const { docs } = userIds.length === 1 ? {
24
+ docs: [
25
+ await req.payload.findByID({
26
+ collection,
27
+ id: userId,
28
+ req,
29
+ overrideAccess: false,
30
+ depth: 0,
31
+ select,
32
+ disableErrors: true
33
+ })
34
+ ]
35
+ } : await req.payload.find({
36
+ collection,
37
+ req,
38
+ overrideAccess: false,
39
+ depth: 0,
40
+ select,
41
+ pagination: false,
42
+ limit: 0,
43
+ where: {
44
+ id: {
45
+ in: userIds
46
+ }
47
+ }
48
+ });
49
+ const names = new Map(docs.flatMap((doc)=>{
50
+ if (!doc) return [];
51
+ const value = doc[field];
52
+ return typeof value === 'string' && value.trim() ? [
53
+ [
54
+ String(doc.id),
55
+ value.trim()
56
+ ]
57
+ ] : [];
58
+ }));
59
+ for (const test of paused){
60
+ const name = names.get(test.pausedBy);
61
+ if (name) attributions.set(String(test.id), {
62
+ name,
63
+ pausedAt: test.pausedAt ?? null
64
+ });
65
+ }
66
+ } catch {}
67
+ return attributions;
68
+ }
69
+ /** Supply every paused list row with at most one host user collection read. */ export async function handlePausedBy(req) {
70
+ const { docs } = await req.payload.find({
71
+ collection: 'xp-experiments',
72
+ req,
73
+ overrideAccess: false,
74
+ depth: 0,
75
+ pagination: false,
76
+ limit: 0,
77
+ where: {
78
+ status: {
79
+ equals: 'paused'
80
+ }
81
+ },
82
+ select: {
83
+ status: true,
84
+ pausedAt: true,
85
+ pausedBy: true
86
+ }
87
+ });
88
+ const attributions = await readPauseAttributions(req, docs);
89
+ return Response.json(Object.fromEntries(attributions), {
90
+ headers: {
91
+ 'Cache-Control': 'private, no-store'
92
+ }
93
+ });
94
+ }
@@ -5,6 +5,7 @@ import { preflightData } from '../transitions/preflightData.js';
5
5
  import { routeId } from './routeId.js';
6
6
  export async function handlePreflight(req, ctx, dependencies) {
7
7
  const id = routeId(req);
8
+ const seenPause = new URL(req.url ?? 'http://xp.invalid').searchParams.get('seenPause');
8
9
  const placementLocale = contentLocale(req).locale ?? undefined;
9
10
  const localization = req.payload.config.localization;
10
11
  // The query selects readiness labels only. Host reads must match Start's default request.
@@ -19,7 +20,9 @@ export async function handlePreflight(req, ctx, dependencies) {
19
20
  const result = id !== undefined ? await preflightData(readinessReq, {
20
21
  experimentId: id,
21
22
  options: ctx.options,
22
- placementLocale
23
+ placementLocale,
24
+ viewingReq: req,
25
+ seenPause
23
26
  }, dependencies) : null;
24
27
  const headers = {
25
28
  'Cache-Control': 'no-store'
@@ -31,9 +31,11 @@ export async function handlePreviewToken(req, { options }) {
31
31
  });
32
32
  const experiment = result.docs[0];
33
33
  if (!experiment) return refuse(404, 'not-found', 'Experiment not found');
34
+ // 0.5 T3/T8 refines
34
35
  if (![
35
36
  'draft',
36
37
  'running',
38
+ 'paused',
37
39
  'stopped',
38
40
  'decided'
39
41
  ].includes(experiment.status)) return refuse(409, 'invalid-status', 'This experiment cannot be previewed');
@@ -1,7 +1,7 @@
1
+ import { type SnapshotWithLegacyExposures } from '../results/snapshot.js';
1
2
  import type { PayloadRequest } from 'payload';
2
3
  import type { EndpointContext, RefusalCode } from '../types/endpoints.js';
3
4
  import type { DocId } from '../types/contracts.js';
4
- import type { Snapshot } from '../types/snapshot.js';
5
5
  export declare function resultsError(status: number, code: RefusalCode, message: string): Response;
6
6
  export type SnapshotDocument = {
7
7
  id: DocId;
@@ -10,7 +10,7 @@ export type SnapshotDocument = {
10
10
  };
11
11
  phase: number;
12
12
  computedAt: string;
13
- snapshot: Snapshot;
13
+ snapshot: SnapshotWithLegacyExposures;
14
14
  };
15
15
  export declare function readSnapshots(req: PayloadRequest, ids: DocId[], { per, decisionId, seriesPhase }?: {
16
16
  per?: 'phase' | 'experiment';
@@ -1,8 +1,12 @@
1
+ import { cohortRelationshipId, readCohortRule } from '../cohorts/rule.js';
2
+ import { cohortRuleSummary } from '../testSurface/copy/cohorts.js';
3
+ import { withCohortExitDefault } from '../results/snapshot.js';
1
4
  import { resultsMetadata, newestSnapshotIds } from '../db/snapshots.js';
2
5
  import { pooledExecutor } from '../db/executor.js';
3
6
  import { routeId } from './routeId.js';
4
7
  import { isClickSource } from '../goals/key.js';
5
8
  import { browserWritableMetric } from '../events/writable.js';
9
+ import { publicRoundTiming } from '../schedule/roundTime.js';
6
10
  const headers = {
7
11
  'Cache-Control': 'no-store'
8
12
  };
@@ -54,6 +58,97 @@ export async function readSnapshots(req, ids, { per = 'phase', decisionId, serie
54
58
  numeric: true
55
59
  }));
56
60
  }
61
+ async function readAudienceSummaries(req, records, canManage) {
62
+ const rulesByRound = records.map((record)=>(record.targeting ?? []).flatMap((row)=>{
63
+ const rule = readCohortRule(row);
64
+ return rule ? [
65
+ rule
66
+ ] : [];
67
+ }));
68
+ const rules = rulesByRound.flat();
69
+ if (!rules.length) return [];
70
+ const ids = [
71
+ ...new Set(rules.map((rule)=>rule.experiment))
72
+ ];
73
+ const sources = await req.payload.find({
74
+ collection: 'xp-phases',
75
+ req,
76
+ overrideAccess: false,
77
+ depth: 0,
78
+ pagination: false,
79
+ limit: 0,
80
+ where: {
81
+ and: [
82
+ {
83
+ experiment: {
84
+ in: ids
85
+ }
86
+ },
87
+ {
88
+ phaseKind: {
89
+ equals: 'test'
90
+ }
91
+ },
92
+ {
93
+ phase: {
94
+ in: [
95
+ ...new Set(rules.flatMap((rule)=>typeof rule.phase === 'number' ? [
96
+ rule.phase
97
+ ] : []))
98
+ ]
99
+ }
100
+ }
101
+ ]
102
+ },
103
+ select: {
104
+ experiment: true,
105
+ phase: true,
106
+ arms: true,
107
+ metricDefinitions: true
108
+ }
109
+ });
110
+ const sourceByRound = new Map(sources.docs.map((source)=>[
111
+ JSON.stringify([
112
+ String(cohortRelationshipId(source.experiment)),
113
+ source.phase
114
+ ]),
115
+ source
116
+ ]));
117
+ const names = new Map();
118
+ if (await canManage()) {
119
+ const { docs } = await req.payload.find({
120
+ collection: 'xp-experiments',
121
+ req,
122
+ overrideAccess: false,
123
+ depth: 0,
124
+ pagination: false,
125
+ limit: 0,
126
+ where: {
127
+ id: {
128
+ in: ids
129
+ }
130
+ },
131
+ select: {
132
+ name: true
133
+ }
134
+ });
135
+ for (const doc of docs)if (typeof doc.name === 'string') names.set(String(doc.id), doc.name);
136
+ }
137
+ return rulesByRound.map((entries)=>entries.map((rule)=>{
138
+ const source = sourceByRound.get(JSON.stringify([
139
+ rule.experiment,
140
+ rule.phase
141
+ ]));
142
+ return cohortRuleSummary(rule, {
143
+ experiment: names.get(rule.experiment),
144
+ arms: source && Object.fromEntries(source.arms.map((arm)=>[
145
+ arm.key,
146
+ arm.label
147
+ ])),
148
+ goal: source?.metricDefinitions.find((goal)=>String(goal.metricId) === rule.goal?.metricId)?.name
149
+ });
150
+ }));
151
+ }
57
152
  export async function handleResults(req, { options }) {
58
153
  const id = routeId(req);
59
154
  if (id === undefined) return resultsError(404, 'not-found', 'Experiment not found');
@@ -77,11 +172,24 @@ export async function handleResults(req, { options }) {
77
172
  sort: 'phase'
78
173
  });
79
174
  const records = docs.sort((a, b)=>a.phase - b.phase);
80
- const phases = records.map((record)=>({
175
+ const cohortSummaries = await readAudienceSummaries(req, records, async ()=>{
176
+ try {
177
+ return await options.access.manage({
178
+ req
179
+ }) === true;
180
+ } catch {
181
+ return false;
182
+ }
183
+ });
184
+ const phases = records.map((record, index)=>({
81
185
  phase: record.phase,
82
186
  phaseKind: record.phaseKind,
83
187
  startedAt: String(record.startedAt),
84
188
  endedAt: record.endedAt == null ? null : String(record.endedAt),
189
+ ...publicRoundTiming(record),
190
+ ...cohortSummaries[index]?.length ? {
191
+ cohortSummaries: cohortSummaries[index]
192
+ } : {},
85
193
  ...record.phaseKind === 'test' && record.analysis?.plannedDurationDays != null ? {
86
194
  plannedDurationDays: record.analysis.plannedDurationDays
87
195
  } : {},
@@ -128,9 +236,9 @@ export async function handleResults(req, { options }) {
128
236
  status: metadata.status
129
237
  },
130
238
  phases,
131
- snapshot,
239
+ snapshot: snapshot ? withCohortExitDefault(snapshot) : null,
132
240
  ...decision ? {
133
- decisionSnapshot: decision
241
+ decisionSnapshot: withCohortExitDefault(decision)
134
242
  } : {}
135
243
  };
136
244
  const decisionPhase = decision?.phase ?? records.filter((record)=>record.phaseKind === 'test').at(-1)?.phase;
@@ -1,5 +1,6 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
+ export declare function collectionIDType(req: PayloadRequest, collection: string): "number" | "text";
3
4
  /** Use the stored spelling for PostgreSQL IDs before any lock or comparison. */
4
- export declare function experimentId(req: PayloadRequest, value: unknown, source?: 'route' | 'payload'): DocId | undefined;
5
+ export declare function experimentId(req: PayloadRequest, value: unknown, source?: 'route' | 'payload' | 'query'): DocId | undefined;
5
6
  export declare function routeId(req: PayloadRequest): DocId | undefined;
@@ -1,15 +1,19 @@
1
+ export function collectionIDType(req, collection) {
2
+ return req.payload.collections?.[collection]?.customIDType ?? req.payload.db.defaultIDType;
3
+ }
1
4
  /** Use the stored spelling for PostgreSQL IDs before any lock or comparison. */ export function experimentId(req, value, source = 'route') {
2
5
  if (typeof value !== 'string' && typeof value !== 'number') return undefined;
3
6
  const id = String(value);
4
7
  const customIDType = req.payload.collections?.['xp-experiments']?.customIDType;
5
- const idType = customIDType ?? req.payload.db.defaultIDType;
8
+ const idType = collectionIDType(req, 'xp-experiments');
6
9
  if (idType !== 'number') {
7
10
  // The Postgres adapter reports a native UUID as text. Custom text IDs are opaque.
8
11
  const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
12
+ if (source === 'query' && idType === 'text' && customIDType !== 'text' && !uuid.test(id)) return undefined;
9
13
  return customIDType !== 'text' && uuid.test(id) ? id.toLowerCase() : id;
10
14
  }
11
15
  // Native Payload deletes already use Number() for their ID lookup.
12
- if (source === 'route' && !/^\d+$/.test(id)) return undefined;
16
+ if (source !== 'payload' && !/^\d+$/.test(id)) return undefined;
13
17
  const number = Number(id);
14
18
  // Payload's Postgres serial ids are int4; larger values would reach SQL and fail with 22003.
15
19
  return Number.isInteger(number) && number >= -2_147_483_648 && number <= 2_147_483_647 ? number : undefined;
@@ -4,6 +4,9 @@ import { loadStartInputsBatch } from '../transitions/preflightData.js';
4
4
  import { readSnapshots, resultsError } from './results.js';
5
5
  import { experimentId } from './routeId.js';
6
6
  import { sanitizeReadinessDetail } from './sanitizeReadinessDetail.js';
7
+ import { currentRoundTiming } from '../db/snapshots.js';
8
+ import { pooledExecutor } from '../db/executor.js';
9
+ import { hasRoundTiming, publicRoundTiming } from '../schedule/roundTime.js';
7
10
  /** Use the batch scan's saved drafts. As in preflight, every matching block on
8
11
  * a page in the affected language needs content before suggesting publication. */ function draftReadySlots(placements) {
9
12
  const location = (row)=>JSON.stringify([
@@ -52,12 +55,13 @@ export async function handleSummary(req, { options }) {
52
55
  const snapshots = uniqueIds.length ? await readSnapshots(req, uniqueIds, {
53
56
  per: 'experiment'
54
57
  }) : [];
58
+ const timing = uniqueIds.length ? await currentRoundTiming(pooledExecutor(req.payload), uniqueIds) : [];
55
59
  const response = Object.create(null);
56
60
  for (const { key, id } of requested){
57
61
  const snapshot = snapshots.find((row)=>String(typeof row.experiment === 'object' ? row.experiment.id : row.experiment) === String(id))?.snapshot;
58
62
  response[key] = snapshot ? {
59
63
  exposures: snapshot.exposures.total,
60
- days: Math.max(0, (Date.parse(snapshot.window.to) - Date.parse(snapshot.window.from)) / 86_400_000),
64
+ days: snapshot.activeDays ?? Math.max(0, (Date.parse(snapshot.window.to) - Date.parse(snapshot.window.from)) / 86_400_000),
61
65
  verdict: {
62
66
  code: snapshot.verdict.code,
63
67
  headline: snapshot.verdict.headline
@@ -80,6 +84,20 @@ export async function handleSummary(req, { options }) {
80
84
  return {
81
85
  code: item.code
82
86
  };
87
+ case 'cohort-no-exposures':
88
+ return {
89
+ code: item.code
90
+ };
91
+ case 'paused-share':
92
+ return {
93
+ code: item.code,
94
+ pausedDays: item.pausedDays
95
+ };
96
+ case 'schedule-population':
97
+ return {
98
+ code: item.code,
99
+ summary: item.summary.slice(0, 512)
100
+ };
83
101
  default:
84
102
  return {
85
103
  code: item.code,
@@ -93,6 +111,11 @@ export async function handleSummary(req, { options }) {
93
111
  days: 0,
94
112
  verdict: null
95
113
  };
114
+ const current = timing.find((row)=>String(row.experiment) === String(id));
115
+ if (current && hasRoundTiming(current)) response[key].timing = {
116
+ phase: Number(current.phase),
117
+ ...publicRoundTiming(current)
118
+ };
96
119
  }
97
120
  try {
98
121
  if (uniqueIds.length && await options.access.manage({