@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
@@ -1,6 +1,9 @@
1
- import { XP_HEADER, XP_REQUEST_HEADER } from '../constants.js';
1
+ import { XP_COHORT_COOKIE, XP_HEADER, XP_REQUEST_HEADER } from '../constants.js';
2
2
  import { createManifestCache } from '../manifest/cache.js';
3
3
  import { assign, fillFlagPoints } from '../runtime/assign.js';
4
+ import { cohortKeysToResolve, isEntryActive } from '../runtime/eligibility.js';
5
+ import { closedCohortKeys, readCohortCookie, updateCohortCookie } from '../runtime/cohortCookie.js';
6
+ import { resolveCohorts } from '../runtime/cohortLookup.js';
4
7
  import { sign } from '../runtime/signing.js';
5
8
  import { requestAttributes } from '../runtime/normalisePath.js';
6
9
  import { isBot } from '../runtime/bot.js';
@@ -15,6 +18,12 @@ import { isPageNavigation, looksLikeNormalizedAppRouterRequest } from './pageNav
15
18
  import { assertCookieOptions } from '../runtime/cookieOptions.js';
16
19
  const caches = new WeakMap();
17
20
  let warnedAboutUrlNormalization = false;
21
+ function forwardCookie(headers, name, value) {
22
+ const cookies = (headers.get('cookie') ?? '').split(';').map((cookie)=>cookie.trim()).filter((cookie)=>cookie && cookie.split('=', 1)[0]?.trim() !== name);
23
+ if (value) cookies.push(`${name}=${encodeURIComponent(value)}`);
24
+ if (cookies.length) headers.set('cookie', cookies.join('; '));
25
+ else headers.delete('cookie');
26
+ }
18
27
  export async function resolveExperiments(request, proxyRuntime) {
19
28
  const requestHeaders = new Headers(request.headers);
20
29
  const result = {
@@ -39,7 +48,8 @@ export async function resolveExperiments(request, proxyRuntime) {
39
48
  } catch {
40
49
  console.error('[payload-experiments] consent failed; treating consent as false');
41
50
  }
42
- const nowMs = Date.now();
51
+ const clock = proxyRuntime.now ?? (()=>new Date());
52
+ const nowMs = clock().getTime();
43
53
  const signedUnit = consent ? readSignedUnit(request, proxyRuntime, nowMs) : null;
44
54
  let visitorId = signedUnit?.unitId;
45
55
  let cookieValue;
@@ -48,7 +58,7 @@ export async function resolveExperiments(request, proxyRuntime) {
48
58
  const limit = proxyRuntime.rateLimitUnit;
49
59
  if (limit === false || await limit?.(request) === true) {
50
60
  const id = mintUnitId();
51
- cookieValue = encodeUnitCookie(id, proxyRuntime.secrets);
61
+ cookieValue = encodeUnitCookie(id, proxyRuntime.secrets, nowMs);
52
62
  visitorId = id;
53
63
  }
54
64
  } catch {
@@ -65,7 +75,7 @@ export async function resolveExperiments(request, proxyRuntime) {
65
75
  const signedContext = `${requestContext}|${sign(`xp:request:${requestContext}`, proxyRuntime.secrets)}`;
66
76
  if (Buffer.byteLength(signedContext) <= 2048) requestHeaders.set(XP_REQUEST_HEADER, signedContext);
67
77
  if (!visitorId || cookieValue) {
68
- const cookies = (requestHeaders.get('cookie') ?? '').split(';').map((cookie)=>cookie.trim()).filter((cookie)=>cookie && cookie.split('=', 1)[0]?.trim() !== name);
78
+ forwardCookie(requestHeaders, name, cookieValue);
69
79
  if (cookieValue) {
70
80
  result.requestCookies.push({
71
81
  name,
@@ -78,10 +88,7 @@ export async function resolveExperiments(request, proxyRuntime) {
78
88
  https: request.nextUrl.protocol === 'https:'
79
89
  })
80
90
  });
81
- cookies.push(`${name}=${cookieValue}`);
82
91
  }
83
- if (cookies.length) requestHeaders.set('cookie', cookies.join('; '));
84
- else requestHeaders.delete('cookie');
85
92
  }
86
93
  let resolvedUnit = {
87
94
  attributes: {}
@@ -104,8 +111,8 @@ export async function resolveExperiments(request, proxyRuntime) {
104
111
  caches.set(proxyRuntime, cache);
105
112
  }
106
113
  const manifest = await cache?.get() ?? null;
107
- const now = Math.floor(Date.now() / 1000);
108
- const token = verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxyRuntime.secrets, now);
114
+ let now = clock();
115
+ const token = verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxyRuntime.secrets, Math.floor(now.getTime() / 1000));
109
116
  const previewExperiment = token && manifest?.experiments.find((experiment)=>experiment.id === token.e && experiment.phase === token.p && (experiment.status === 'running' || experiment.status === 'decided') && experiment.arms.some((arm)=>arm.key === token.a));
110
117
  const currentManifest = manifest ?? {
111
118
  v: 1,
@@ -128,38 +135,90 @@ export async function resolveExperiments(request, proxyRuntime) {
128
135
  let assignmentFailed = false;
129
136
  if (!consent) {
130
137
  try {
131
- assignments = consentFallback(currentManifest, attributes, context);
138
+ assignments = consentFallback(currentManifest, attributes, context, now);
132
139
  } catch {
133
140
  console.error('[payload-experiments] identity-free fallback failed; serving non-exposable control');
134
141
  assignmentFailed = true;
135
142
  try {
136
- assignments = controlAssignments(currentManifest, context);
143
+ assignments = controlAssignments(currentManifest, context, now);
137
144
  } catch {
138
145
  assignments = emptyAssignments(context);
139
146
  }
140
147
  }
141
148
  } else {
142
149
  try {
143
- assignments = assign(currentManifest, {
150
+ const unit = {
144
151
  visitorId,
145
152
  userId,
146
153
  sessionUnknown
147
- }, attributes, {
154
+ };
155
+ const opts = {
148
156
  ...context,
149
157
  now
158
+ };
159
+ const keys = cohortKeysToResolve(currentManifest, unit, attributes, opts);
160
+ let cohorts;
161
+ if (keys.length) {
162
+ // A host may already use xp_c as its unit cookie. Preserve that identity and skip caching.
163
+ const closed = name === XP_COHORT_COOKIE ? undefined : closedCohortKeys(currentManifest, +now);
164
+ const current = closed?.size ? readCohortCookie(request.cookies.get(XP_COHORT_COOKIE)?.value, unit, proxyRuntime.secrets, +now) : null;
165
+ const known = new Map();
166
+ const remaining = keys.filter((key)=>{
167
+ const member = closed?.has(key) ? current?.entries.get(key) : undefined;
168
+ if (member === undefined) return true;
169
+ known.set(key, member);
170
+ return false;
171
+ });
172
+ let answered;
173
+ if (!signedUnit && visitorId && !userId) answered = new Map(remaining.map((key)=>[
174
+ key,
175
+ false
176
+ ]));
177
+ else if (remaining.length && proxyRuntime.lookupCohorts) {
178
+ answered = await resolveCohorts(proxyRuntime.lookupCohorts, {
179
+ keys: remaining,
180
+ visitorId,
181
+ userId
182
+ });
183
+ now = clock();
184
+ }
185
+ if (answered?.size) {
186
+ for (const [key, member] of answered)known.set(key, member);
187
+ const updated = closed && updateCohortCookie(current, answered, closed, unit, proxyRuntime.secrets, +now);
188
+ if (updated) {
189
+ forwardCookie(requestHeaders, XP_COHORT_COOKIE, updated.value);
190
+ result.requestCookies.push({
191
+ name: XP_COHORT_COOKIE,
192
+ value: updated.value
193
+ });
194
+ result.setCookies.push({
195
+ name: XP_COHORT_COOKIE,
196
+ ...cookieAttributes(proxyRuntime, {
197
+ https: request.nextUrl.protocol === 'https:'
198
+ }),
199
+ ...updated
200
+ });
201
+ }
202
+ }
203
+ cohorts = known;
204
+ }
205
+ assignments = assign(currentManifest, unit, attributes, {
206
+ ...opts,
207
+ now,
208
+ cohorts
150
209
  });
151
210
  } catch {
152
211
  console.error('[payload-experiments] assign failed; serving non-exposable control');
153
212
  assignmentFailed = true;
154
213
  try {
155
- assignments = controlAssignments(currentManifest, context);
214
+ assignments = controlAssignments(currentManifest, context, now);
156
215
  } catch {
157
216
  assignments = emptyAssignments(context);
158
217
  }
159
218
  }
160
219
  }
161
220
  if (previewExperiment && token) {
162
- if (visitorId && !assignmentFailed) {
221
+ if (visitorId && !assignmentFailed && isEntryActive(previewExperiment, now)) {
163
222
  assignments.deferred = assignments.deferred.filter((slug)=>slug !== previewExperiment.slug);
164
223
  assignments.bySlug[previewExperiment.slug] = {
165
224
  slug: previewExperiment.slug,
@@ -170,13 +229,13 @@ export async function resolveExperiments(request, proxyRuntime) {
170
229
  policy: previewExperiment.exposurePolicy,
171
230
  source: 'preview'
172
231
  };
173
- fillFlagPoints(assignments, currentManifest);
232
+ fillFlagPoints(assignments, currentManifest, now);
174
233
  }
175
234
  }
176
235
  if (token) result.responseHeaders = new Headers({
177
236
  'Cache-Control': 'no-store'
178
237
  });
179
- if (manifest && !assignmentFailed) result.rewrite = pageRewrite(manifest, assignments, request.nextUrl);
238
+ if (manifest && !assignmentFailed) result.rewrite = pageRewrite(manifest, assignments, request.nextUrl, now);
180
239
  try {
181
240
  requestHeaders.set(XP_HEADER, encodeAssignmentsHeader(assignments, {
182
241
  secrets: proxyRuntime.secrets,
@@ -5,6 +5,7 @@ import { useEffect, useId, useState } from 'react';
5
5
  import { fetchAllDocs } from '../lib/fetchAllDocs.js';
6
6
  import { usePuckRoutes } from './hostContext.js';
7
7
  import { pickerCopy } from './copy.js';
8
+ import { displayStatus, statusLabel } from '../testSurface/labels.js';
8
9
  function isExperimentOption(value) {
9
10
  if (!value || typeof value !== 'object') return false;
10
11
  const doc = value;
@@ -122,7 +123,7 @@ export function ExperimentPicker({ value, onChange, allowEmpty = true }) {
122
123
  children: [
123
124
  doc.name,
124
125
  " · ",
125
- pickerCopy.statuses[doc.status]
126
+ statusLabel(displayStatus(doc))
126
127
  ]
127
128
  }, doc.id))
128
129
  ]
@@ -17,10 +17,11 @@ export declare const pickerCopy: {
17
17
  readonly unavailable: "This test isn't available to you. You can still edit its content.";
18
18
  readonly resultsOnly: "You can view this test's results.";
19
19
  readonly statuses: {
20
- readonly draft: "Draft";
21
- readonly running: "Running";
22
- readonly stopped: "Stopped";
23
- readonly decided: "Decided";
24
- readonly archived: "Archived";
20
+ draft: string;
21
+ running: string;
22
+ stopped: string;
23
+ decided: string;
24
+ archived: string;
25
+ paused: string;
25
26
  };
26
27
  };
package/dist/puck/copy.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { ARM_LABELS } from '../labels/arms.js';
2
+ import { STATUS_LABELS } from '../testSurface/labels.js';
3
+ const { scheduled: _scheduled, ...storedStatuses } = STATUS_LABELS;
2
4
  export const categoryTitle = 'A/B tests';
3
5
  export const slotLabels = {
4
6
  control: ARM_LABELS.control,
@@ -17,11 +19,5 @@ export const pickerCopy = {
17
19
  forbiddenUnbound: "You don't have access to tests.",
18
20
  unavailable: "This test isn't available to you. You can still edit its content.",
19
21
  resultsOnly: "You can view this test's results.",
20
- statuses: {
21
- draft: 'Draft',
22
- running: 'Running',
23
- stopped: 'Stopped',
24
- decided: 'Decided',
25
- archived: 'Archived'
26
- }
22
+ statuses: storedStatuses
27
23
  };
@@ -8,6 +8,8 @@ import { BLOCK_SLOTS } from '../../blocks/model.js';
8
8
  import { publishOutlineVersion } from './outlineVersion.js';
9
9
  import { LeftoverVersions } from './LeftoverVersions.js';
10
10
  import { Button } from '../../ui/Button.js';
11
+ import { useScheduleClock } from '../../testSurface/format/useScheduleClock.js';
12
+ import { scheduleStatus } from '../../testSurface/format/scheduleStatus.js';
11
13
  import { StatusChip } from '../../ui/StatusChip.js';
12
14
  import { Banner } from '../../ui/Banner.js';
13
15
  import { Tabs } from '../../ui/Tabs.js';
@@ -792,7 +794,11 @@ function EditorRender(props) {
792
794
  const contentNotice = sidebar && editable && surface && quickTest.doc ? editorContentNotice(currentPreflight, pageReadinessContext(quickTest.doc, currentPreflight, surface)) : undefined;
793
795
  usePlacementNotice(api, experimentId, canManage ? placementNotice ?? contentNotice : undefined, contentLocale);
794
796
  usePageSaveReadiness(api, sidebar && canManage ? experimentId : undefined, editorPage, contentLocale);
795
- const runningInSidebar = !!(sidebar && showVersions && experiment.status === 'running' && !statusChanged);
797
+ const now = useScheduleClock(experiment ? [
798
+ experiment
799
+ ] : [], surface?.timeZone);
800
+ const schedule = experiment && !statusChanged ? scheduleStatus(experiment, now, currentPreflight?.timing, surface?.timeZone, currentPreflight?.pauseAttribution) : undefined;
801
+ const runningInSidebar = !!(sidebar && showVersions && (schedule?.status === 'running' || schedule?.status === 'scheduled'));
796
802
  const runningPlacement = runningInSidebar && canManage && !quickTest.preflightRead?.message ? placementMessage : undefined;
797
803
  const placementNoticeView = (inSidebar)=>/*#__PURE__*/ _jsxs(_Fragment, {
798
804
  children: [
@@ -885,7 +891,7 @@ function EditorRender(props) {
885
891
  }) : runningInSidebar ? null : /*#__PURE__*/ _jsxs(Banner, {
886
892
  tone: experiment?.status === 'running' ? 'warning' : 'info',
887
893
  children: [
888
- experimentId === undefined ? bannerFor() : experiment ? statusChanged ? READINESS_COPY.checking : bannerFor(experiment.status, winner, originalLabel, experiment.decision ?? null) : editorCopy.loading,
894
+ experimentId === undefined ? bannerFor() : experiment ? statusChanged ? READINESS_COPY.checking : schedule?.status === 'scheduled' ? schedule.line : bannerFor(experiment.status, winner, originalLabel, experiment.decision ?? null) : editorCopy.loading,
889
895
  !statusChanged && experiment?.status === 'archived' ? /*#__PURE__*/ _jsxs(_Fragment, {
890
896
  children: [
891
897
  /*#__PURE__*/ _jsx("p", {
@@ -900,7 +906,7 @@ function EditorRender(props) {
900
906
  }) : null
901
907
  ]
902
908
  });
903
- const versionLockMessage = editable || !experiment ? undefined : canManage ? editorCopy.locked[experiment.status] ?? editorCopy.lockedGeneric : editorCopy.readOnlyVersions;
909
+ const versionLockMessage = editable || !experiment ? undefined : canManage ? editorCopy.locked[schedule?.status ?? experiment.status] ?? editorCopy.lockedGeneric : editorCopy.readOnlyVersions;
904
910
  const removeDialog = removing?.key === bindingKey ? /*#__PURE__*/ _jsx(RemoveVersion, {
905
911
  name: experiment?.name,
906
912
  count: countSlotBlocks(getPuck().getItemById(props.id)?.props[removing.arm.key]),
@@ -943,10 +949,15 @@ function EditorRender(props) {
943
949
  children: experiment.name
944
950
  }),
945
951
  !statusChanged ? /*#__PURE__*/ _jsx(StatusChip, {
946
- status: experiment.status
952
+ status: schedule?.status ?? experiment.status
947
953
  }) : null
948
954
  ]
949
955
  }) : null,
956
+ schedule?.line ? /*#__PURE__*/ _jsx("p", {
957
+ className: "xp-ui-help",
958
+ role: "status",
959
+ children: schedule.line
960
+ }) : null,
950
961
  accessNotice,
951
962
  shared ? /*#__PURE__*/ _jsx(Banner, {
952
963
  tone: "info",
@@ -1220,7 +1231,7 @@ function EditorRender(props) {
1220
1231
  children: experimentId === undefined ? editorCopy.unbound : result?.missing ? editorCopy.deleted : experiment?.name ?? experimentSlotLabel
1221
1232
  }),
1222
1233
  experiment && !statusChanged ? /*#__PURE__*/ _jsx(StatusChip, {
1223
- status: experiment.status
1234
+ status: schedule?.status ?? experiment.status
1224
1235
  }) : null
1225
1236
  ]
1226
1237
  }),
@@ -3,6 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
3
3
  import { READINESS_COPY } from '../../testSurface/copy/readiness.js';
4
4
  import { canStartTest, hasBrowserWritablePrimary, readyToStart } from '../../testSurface/readinessRead.js';
5
5
  import { METRICS_COPY } from '../../testSurface/copy/metrics.js';
6
+ import { useScheduleClock } from '../../testSurface/format/useScheduleClock.js';
6
7
  import { useState } from 'react';
7
8
  import { Banner } from '../../ui/Feedback.js';
8
9
  import { availableActions } from '../../testSurface/actions/actions.model.js';
@@ -11,11 +12,16 @@ import { actionWaitMessage } from '../../testSurface/surface/readiness/SaveStatu
11
12
  /** Render sidebar actions in the lifecycle model's order. */ export function QuickTestActions({ test, surface }) {
12
13
  const [confirm, setConfirm] = useState(null);
13
14
  const doc = test.doc;
15
+ const now = useScheduleClock([
16
+ doc
17
+ ], surface.timeZone);
14
18
  const actions = availableActions({
15
19
  ...doc,
20
+ now,
21
+ timeZone: surface.timeZone,
16
22
  canManage: surface.canManage,
17
23
  canReadResults: surface.canReadResults
18
- }).filter((action)=>doc.status === 'running' || action.id === 'start');
24
+ }).filter((action)=>doc.status === 'running' || doc.status === 'paused' || action.id === 'start');
19
25
  const start = actions.some((action)=>action.id === 'start');
20
26
  const startVisible = start && readyToStart(test, surface.editorPlacementMessage) && !test.hasUnsaved;
21
27
  const ready = canStartTest(test, surface.editorPlacementMessage);
@@ -4,6 +4,7 @@ import { addVariant, balanceWeight, removeArm, splitEvenly, totalWeight, withSlo
4
4
  import { XP_IF_UPDATED_AT_HEADER } from '../../constants.js';
5
5
  import { slotLabels } from '../copy.js';
6
6
  import { editorCopy, writeRefusal } from './copy.js';
7
+ import { displayStatus } from '../../testSurface/labels.js';
7
8
  export class ArmWriteError extends Error {
8
9
  }
9
10
  /** Refuse obsolete intents before a no-op can become a successful PATCH. */ export function removeVersionArms(arms, key) {
@@ -62,6 +63,7 @@ export async function readExperiment(url, signal) {
62
63
  'draft',
63
64
  'stopped',
64
65
  'running',
66
+ 'paused',
65
67
  'decided',
66
68
  'archived'
67
69
  ].includes(value.status)) throw new ArmWriteError(editorCopy.lockedGeneric);
@@ -73,7 +75,10 @@ export async function readExperiment(url, signal) {
73
75
  // A later cache read can supersede this baseline before this GET finishes.
74
76
  if (accepted.updatedAt !== fresh.updatedAt) throw new ArmWriteError(editorCopy.staleEdit);
75
77
  if (draftOnly && fresh.status !== 'draft') throw new ArmWriteError(editorCopy.draftOnly);
76
- if (fresh.status !== 'draft' && fresh.status !== 'stopped') throw new ArmWriteError(editorCopy.locked[fresh.status]);
78
+ if (fresh.status !== 'draft' && fresh.status !== 'stopped') {
79
+ const status = displayStatus(fresh);
80
+ throw new ArmWriteError(status === 'draft' || status === 'stopped' ? editorCopy.lockedGeneric : editorCopy.locked[status]);
81
+ }
77
82
  if (!fresh.updatedAt || !Array.isArray(fresh.arms)) throw new ArmWriteError(editorCopy.writeUnreadable);
78
83
  const arms = withSlotsFor(transform(fresh.arms), 'block');
79
84
  const issue = checkArms(arms, 'block')[0];
@@ -22,6 +22,7 @@ export declare const editorCopy: {
22
22
  readonly deleted: "The test for this block was deleted.";
23
23
  readonly unbound: "This Test block has no test yet.";
24
24
  readonly draft: (label: string) => string;
25
+ readonly paused: "This test is paused. Changing its content now can affect the comparison when it resumes.";
25
26
  readonly running: "Changing this content mid-test mixes two versions in one result";
26
27
  readonly decided: (winner: string) => string;
27
28
  readonly archived: (winner: string) => string;
@@ -86,6 +87,8 @@ export declare const editorCopy: {
86
87
  readonly invalidShare: "Use a whole number from 0 to 100.";
87
88
  readonly split: "Split evenly";
88
89
  readonly locked: {
90
+ readonly scheduled: "Cancel the schedule to change the versions.";
91
+ readonly paused: "This test is paused, so its versions can't change. Editing content now can affect the comparison when it resumes.";
89
92
  readonly running: "This test is running, so its versions can't change. Editing content during the test mixes two versions in one result.";
90
93
  readonly decided: "This test has a decision, so its versions can't change. View the results on the test page.";
91
94
  readonly archived: "This test is archived, so its versions can't change. View the results on the test page.";
@@ -18,6 +18,7 @@ export const editorCopy = {
18
18
  deleted: 'The test for this block was deleted.',
19
19
  unbound: 'This Test block has no test yet.',
20
20
  draft: (label)=>`This block shows ${controlVersionName(label)} to everyone until the test starts.`,
21
+ paused: 'This test is paused. Changing its content now can affect the comparison when it resumes.',
21
22
  running: 'Changing this content mid-test mixes two versions in one result',
22
23
  decided: (winner)=>`Decided: ${winner}. Use 'Make it the content' on the test to finish.`,
23
24
  archived: (winner)=>`Archived: this block serves ${winner}, or nothing if that version is empty.`,
@@ -88,6 +89,8 @@ export const editorCopy = {
88
89
  invalidShare: 'Use a whole number from 0 to 100.',
89
90
  split: 'Split evenly',
90
91
  locked: {
92
+ scheduled: 'Cancel the schedule to change the versions.',
93
+ paused: "This test is paused, so its versions can't change. Editing content now can affect the comparison when it resumes.",
91
94
  running: "This test is running, so its versions can't change. Editing content during the test mixes two versions in one result.",
92
95
  decided: "This test has a decision, so its versions can't change. View the results on the test page.",
93
96
  archived: "This test is archived, so its versions can't change. View the results on the test page."
@@ -315,7 +315,8 @@
315
315
  .xp-ui-tabpanel { padding-block: 16px; }
316
316
  .xp-ui-status { display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 8px; border-radius: var(--xp-radius-chip); border: 1px solid var(--xp-border-strong); background: var(--xp-surface-2); color: var(--xp-text-2); font: 500 12px/18px var(--xp-font); white-space: nowrap; }
317
317
  .xp-ui-status--running, .xp-ui-status--ready { background: var(--xp-success-bg); color: var(--xp-success); border-color: var(--xp-success-border); }
318
- .xp-ui-status--needs-attention { background: var(--xp-warning-bg); color: var(--xp-warning); border-color: var(--xp-warning-border); }
318
+ .xp-ui-status--needs-attention, .xp-ui-status--paused { background: var(--xp-warning-bg); color: var(--xp-warning); border-color: var(--xp-warning-border); }
319
+ .xp-ui-status--scheduled { color: var(--xp-accent-text); }
319
320
  .xp-ui-status--decided { background: var(--xp-text); color: var(--xp-surface); border-color: var(--xp-text); }
320
321
  .xp-ui-banner { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; padding: 14px 20px; border: 1px solid var(--xp-border); border-radius: var(--xp-radius-control); background: var(--xp-surface-2); color: var(--xp-text); font: var(--xp-text-body); }
321
322
  .xp-ui-banner p, .xp-ui-empty p { margin: 0; }
@@ -1,7 +1,8 @@
1
1
  import type { Arm, DocId, Status, UnitType } from '../../types/contracts.js';
2
2
  import type { ArmSlot } from '../../types/puck.js';
3
3
  import type { PreflightResult } from '../../types/endpoints.js';
4
- export type EditorExperiment = {
4
+ import type { TestDocument } from '../../testSurface/surface/testDocument.model.js';
5
+ export type EditorExperiment = Pick<TestDocument, 'startedAt' | 'schedule' | 'pausedAt' | 'pauseReason' | 'analysis'> & {
5
6
  name: string;
6
7
  phase?: number;
7
8
  updatedAt?: string;
@@ -20,6 +20,8 @@ export function bannerFor(status, winner = editorCopy.labels.control, original =
20
20
  case 'draft':
21
21
  case 'stopped':
22
22
  return editorCopy.draft(original);
23
+ case 'paused':
24
+ return editorCopy.paused;
23
25
  case 'running':
24
26
  return editorCopy.running;
25
27
  case 'decided':
@@ -50,7 +50,7 @@ export declare function cachedReadinessRead(api: string, id: DocId, contentLocal
50
50
  loadState: "forbidden" | "error" | "missing" | "ready";
51
51
  kind: string;
52
52
  answer: PreflightResult | undefined;
53
- message: "Couldn't check where this test is used. Try again." | "You don't have permission to check where this test is used." | "A page used by this test no longer exists. Choose another page." | "This test's setup couldn't be checked." | "Couldn't check readiness. Try again." | "This test no longer exists." | "This isn't available yet." | "Your session has expired. Sign in again." | "Couldn't load this test. Try selecting it again." | "You don't have access to this test." | "Couldn't load this test." | "You don't have access to this test. You can still edit its content." | "This test isn't available to you. You can still edit its content." | "You can view this test's results." | undefined;
53
+ message: "Couldn't check where this test is used. Try again." | "You don't have permission to check where this test is used." | "A page used by this test no longer exists. Choose another page." | "This test's setup couldn't be checked." | "Couldn't check readiness. Try again." | "This test no longer exists." | "This isn't available yet." | "Your session has expired. Sign in again." | "You don't have access to this test." | "Couldn't load this test." | "Couldn't load this test. Try selecting it again." | "You don't have access to this test. You can still edit its content." | "This test isn't available to you. You can still edit its content." | "You can view this test's results." | undefined;
54
54
  failed: boolean;
55
55
  retry: boolean;
56
56
  pollDelay: number | null;
@@ -1,5 +1,4 @@
1
- import { contentLocaleURL } from '../../testSurface/contentLocaleURL.js';
2
- import { isPreflightResult, readPreflight } from '../../testSurface/readPreflight.js';
1
+ import { isPreflightResult, preflightURL, readPreflight, retainPauseAttribution } from '../../testSurface/readPreflight.js';
3
2
  import { classifyReadinessRead } from '../../testSurface/readinessRead.js';
4
3
  const cache = new Map();
5
4
  const latest = new Map();
@@ -25,6 +24,7 @@ function read(api, id, fresh, blocking = false, contentLocale) {
25
24
  failures: previous?.failures ?? 0,
26
25
  value: previous?.value,
27
26
  previousPreflight: previous?.preflight ?? (previous?.pending ? previous.previousPreflight : undefined),
27
+ lastPreflight: previous?.lastPreflight,
28
28
  previousRead: previous?.read ?? previous?.previousRead,
29
29
  promise: undefined
30
30
  };
@@ -33,15 +33,17 @@ function read(api, id, fresh, blocking = false, contentLocale) {
33
33
  for (const notify of consumers.get(key)?.listeners ?? [])notify(entry.value);
34
34
  entry.promise = (async ()=>{
35
35
  try {
36
- const { response, body: data } = await readPreflight((signal)=>fetch(contentLocaleURL(`${api}/xp/experiments/${encodeURIComponent(id)}/preflight`, contentLocale), {
36
+ const { response, body } = await readPreflight((signal)=>fetch(preflightURL(`${api}/xp/experiments/${encodeURIComponent(id)}/preflight`, contentLocale, entry.lastPreflight), {
37
37
  credentials: 'include',
38
38
  cache: 'no-store',
39
39
  signal
40
40
  }), controller.signal);
41
+ const data = response.ok ? retainPauseAttribution(body, entry.lastPreflight) : body;
41
42
  entry.read = classifyReadinessRead(response.status, data, entry.failures + 1, {
42
43
  kind: 'where-used'
43
44
  });
44
45
  if (!response.ok) {
46
+ if (response.status === 401 || response.status === 403 || response.status === 404) entry.lastPreflight = undefined;
45
47
  entry.response = new Response(JSON.stringify(data), {
46
48
  status: response.status,
47
49
  headers: response.headers
@@ -50,6 +52,7 @@ function read(api, id, fresh, blocking = false, contentLocale) {
50
52
  }
51
53
  if (!isPreflightResult(data)) return;
52
54
  entry.preflight = data;
55
+ entry.lastPreflight = data;
53
56
  if (data.checks?.some((check)=>!check.ok && check.code === 'no-placements' && check.detail !== undefined)) return;
54
57
  return Array.isArray(data.placements) ? data.placements : undefined;
55
58
  } catch {
@@ -3,6 +3,7 @@ import type { MetricUnavailableReason } from '../types/reasons.js';
3
3
  import type { Arm, DocId, MetricSource } from '../types/contracts.js';
4
4
  import type { Snapshot } from '../types/snapshot.js';
5
5
  import type { ExposedUnit, Timestamp } from './aggregate.js';
6
+ import type { RoundTiming } from '../schedule/types.js';
6
7
  export interface FrozenMetric {
7
8
  metricId: DocId;
8
9
  name: string;
@@ -23,7 +24,7 @@ export interface FrozenMetric {
23
24
  * settings are read by analysis. Rollout arms carry weights {100-h,h} and include
24
25
  * only the shipped arm and holdout; units have already passed rolloutAnalysisUnits.
25
26
  */
26
- export interface AnalysisPhase {
27
+ export interface AnalysisPhase extends RoundTiming {
27
28
  experiment: DocId;
28
29
  phase: number;
29
30
  phaseKind: 'test' | 'rollout';
@@ -70,6 +71,7 @@ export type AnalysePhaseInput = {
70
71
  units: ReadonlyMap<string, ExposedUnit>;
71
72
  metricData: readonly MetricUnitData[];
72
73
  excludedMultiArm?: number;
74
+ cohortExits?: number;
73
75
  armMismatch?: number;
74
76
  /** Diagnostic from identity credit, supplied by the caller with its denominator. */
75
77
  identityConflictShare?: number;
@@ -8,6 +8,9 @@ import { remainingPower } from './power.js';
8
8
  import { assembleSnapshot, jsonInterval } from './snapshot.js';
9
9
  import { exposureSrm } from './srm.js';
10
10
  import { computeVerdict, verdictGroupLabel } from './verdict.js';
11
+ import { DAY_MS, hasRoundTiming, roundActiveSpec } from '../schedule/roundTime.js';
12
+ import { activeDays } from '../schedule/activeTime.js';
13
+ import { timeHealth } from './health.js';
11
14
  const severity = {
12
15
  ok: 0,
13
16
  insufficient: 1,
@@ -50,8 +53,15 @@ const severity = {
50
53
  }
51
54
  const from = timestampMs(phase.startedAt);
52
55
  const now = timestampMs(input.now);
53
- const to = Math.min(now, phase.endedAt == null ? now : timestampMs(phase.endedAt));
56
+ const to = Math.min(now, phase.endedAt == null ? now : timestampMs(phase.endedAt), phase.schedule?.endAt ? timestampMs(phase.schedule.endAt) : Infinity);
54
57
  if (to < from) throw new XpAnalysisError('window-before-start');
58
+ const range = {
59
+ from: new Date(from),
60
+ to: new Date(to)
61
+ };
62
+ const activeDayCount = hasRoundTiming(phase) ? activeDays(roundActiveSpec(phase), phase.pauses ?? [], range) : undefined;
63
+ const elapsedActiveDays = activeDayCount ?? (to - from) / DAY_MS;
64
+ const health = timeHealth(phase, range);
55
65
  const byArm = new Map(phase.arms.map((arm)=>[
56
66
  arm.key,
57
67
  []
@@ -72,6 +82,7 @@ const severity = {
72
82
  total: units.size,
73
83
  perArm,
74
84
  excludedMultiArm,
85
+ cohortExits: input.cohortExits ?? 0,
75
86
  multiArmShare: units.size + excludedMultiArm === 0 ? 0 : excludedMultiArm / (units.size + excludedMultiArm),
76
87
  armMismatch: input.armMismatch ?? 0,
77
88
  identityConflictShare: input.identityConflictShare ?? 0,
@@ -340,7 +351,7 @@ const severity = {
340
351
  srm,
341
352
  guardrails: verdictGuardrails,
342
353
  power,
343
- plannedDurationPassed: to - from >= analysis.plannedDurationDays * 86_400_000,
354
+ plannedDurationPassed: elapsedActiveDays >= analysis.plannedDurationDays,
344
355
  originalLabel: verdictGroupLabel('control', input.controlLabel ?? phase.arms.find((arm)=>arm.kind === 'control')?.label),
345
356
  controlArm: baselineArm.key
346
357
  };
@@ -358,7 +369,7 @@ const severity = {
358
369
  power = remainingPower({
359
370
  baseline: primaryStatistics.get(baselineArm.key),
360
371
  variants: compared.map((arm)=>primaryStatistics.get(arm.key)),
361
- elapsedDays: (to - from) / 86_400_000,
372
+ elapsedDays: elapsedActiveDays,
362
373
  alpha: alphaAdjusted,
363
374
  method: analysis.method,
364
375
  prior,
@@ -391,6 +402,12 @@ const severity = {
391
402
  guardrails,
392
403
  power,
393
404
  verdict,
405
+ ...activeDayCount === undefined ? {} : {
406
+ activeDays: activeDayCount
407
+ },
408
+ ...health.length ? {
409
+ health
410
+ } : {},
394
411
  contentChanges: (phase.contentChanges ?? []).map((change)=>({
395
412
  ...change,
396
413
  doc: {
@@ -1,4 +1,15 @@
1
1
  import type { Snapshot, SnapshotHealth } from '../types/snapshot.js';
2
+ import type { Status } from '../types/contracts.js';
3
+ import type { RoundTiming } from '../schedule/types.js';
4
+ import { type Timestamp } from './aggregate.js';
5
+ export declare function cohortNoExposures(round: RoundTiming & {
6
+ startedAt: Timestamp;
7
+ targeting?: readonly unknown[];
8
+ }, status: Status, now: Date, exposures: number): SnapshotHealth | undefined;
9
+ export declare function timeHealth({ schedule, pauses }: RoundTiming, range: {
10
+ from: Date;
11
+ to: Date;
12
+ }): SnapshotHealth[];
2
13
  /** A diagnostic for a large difference in rapid activity, not an inference test.
3
14
  * Compare only arms with enough observations and age coverage. Ordinary
4
15
  * same-speed activity (including immediate pageviews) should not warn.
@@ -1,5 +1,43 @@
1
+ import { isCohortRule } from '../cohorts/rule.js';
2
+ import { inactiveIntervals } from '../schedule/activeTime.js';
3
+ import { DAY_MS, roundActiveSpec } from '../schedule/roundTime.js';
4
+ import { scheduleWindowsCopy } from '../testSurface/copy/schedule.js';
5
+ import { timestampMs } from './aggregate.js';
1
6
  const rapidAgeMs = 5_000;
2
7
  const minimumKnownPerArm = 30;
8
+ const HOUR_MS = 60 * 60 * 1000;
9
+ export function cohortNoExposures(round, status, now, exposures) {
10
+ if (status !== 'running' || exposures !== 0 || !round.targeting?.some(isCohortRule)) return undefined;
11
+ const from = new Date(timestampMs(round.startedAt));
12
+ const elapsed = +now - +from;
13
+ if (elapsed < HOUR_MS) return undefined;
14
+ const inactive = inactiveIntervals(roundActiveSpec(round), round.pauses ?? [], {
15
+ from,
16
+ to: now
17
+ });
18
+ const inactiveMs = inactive.reduce((total, interval)=>total + (+interval.to - +interval.from), 0);
19
+ return elapsed - inactiveMs >= HOUR_MS ? {
20
+ code: 'cohort-no-exposures'
21
+ } : undefined;
22
+ }
23
+ export function timeHealth({ schedule, pauses }, range) {
24
+ const health = [];
25
+ if (pauses?.length) {
26
+ const paused = inactiveIntervals({
27
+ tz: 'UTC',
28
+ windows: []
29
+ }, pauses, range).reduce((total, { from, to })=>total + (+to - +from), 0);
30
+ if (paused > (+range.to - +range.from) / 4) health.push({
31
+ code: 'paused-share',
32
+ pausedDays: paused / DAY_MS
33
+ });
34
+ }
35
+ if (schedule?.windows.length) health.push({
36
+ code: 'schedule-population',
37
+ summary: scheduleWindowsCopy(schedule.windows, schedule.timeZone, range.from)
38
+ });
39
+ return health;
40
+ }
3
41
  /** A diagnostic for a large difference in rapid activity, not an inference test.
4
42
  * Compare only arms with enough observations and age coverage. Ordinary
5
43
  * same-speed activity (including immediate pageviews) should not warn.