@delmaredigital/payload-experiments 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +9 -5
  2. package/dist/admin/blocks/model.js +2 -0
  3. package/dist/admin/copy/blocks.d.ts +1 -0
  4. package/dist/admin/copy/blocks.js +1 -0
  5. package/dist/admin/copy/status.d.ts +3 -0
  6. package/dist/admin/copy/status.js +3 -0
  7. package/dist/admin/placementStatus.model.js +3 -0
  8. package/dist/admin/status.model.d.ts +3 -2
  9. package/dist/admin/status.model.js +9 -3
  10. package/dist/admin/surface/ResultsRoute.js +2 -1
  11. package/dist/admin/surface/TestsHome.d.ts +2 -1
  12. package/dist/admin/surface/TestsHome.js +31 -11
  13. package/dist/admin/surface/TestsSurface.js +4 -0
  14. package/dist/admin/surface/home.model.d.ts +11 -6
  15. package/dist/admin/surface/home.model.js +19 -8
  16. package/dist/admin/surface/newTest/PageWizard.js +13 -3
  17. package/dist/admin/surface/results/ResultsHeader.js +43 -9
  18. package/dist/admin/surface/test/TestPage.js +11 -1
  19. package/dist/admin/useLayerUsage.d.ts +1 -1
  20. package/dist/admin/views/buildSurfaceProps.js +3 -0
  21. package/dist/cohorts/build.d.ts +35 -0
  22. package/dist/cohorts/build.js +134 -0
  23. package/dist/cohorts/key.d.ts +12 -0
  24. package/dist/cohorts/key.js +15 -0
  25. package/dist/cohorts/maintenance.d.ts +10 -0
  26. package/dist/cohorts/maintenance.js +70 -0
  27. package/dist/cohorts/readiness.d.ts +30 -0
  28. package/dist/cohorts/readiness.js +54 -0
  29. package/dist/cohorts/readinessData.d.ts +29 -0
  30. package/dist/cohorts/readinessData.js +123 -0
  31. package/dist/cohorts/rule.d.ts +33 -0
  32. package/dist/cohorts/rule.js +50 -0
  33. package/dist/collections/cohortMembers.d.ts +4 -0
  34. package/dist/collections/cohortMembers.js +95 -0
  35. package/dist/collections/experiments/config.js +157 -7
  36. package/dist/collections/experiments/editability.js +10 -6
  37. package/dist/collections/experiments/lockHook.js +39 -20
  38. package/dist/collections/index.js +4 -1
  39. package/dist/collections/phases.js +4 -1
  40. package/dist/constants.d.ts +2 -0
  41. package/dist/constants.js +2 -0
  42. package/dist/db/adapter.d.ts +1 -1
  43. package/dist/db/adapter.js +14 -4
  44. package/dist/db/appends.js +1 -1
  45. package/dist/db/cohortMembership.d.ts +11 -0
  46. package/dist/db/cohortMembership.js +31 -0
  47. package/dist/db/cohortPool.d.ts +9 -0
  48. package/dist/db/cohortPool.js +53 -0
  49. package/dist/db/cohortTransactions.d.ts +3 -0
  50. package/dist/db/cohortTransactions.js +52 -0
  51. package/dist/db/cohorts.d.ts +72 -0
  52. package/dist/db/cohorts.js +280 -0
  53. package/dist/db/erase.d.ts +2 -0
  54. package/dist/db/erase.js +21 -2
  55. package/dist/db/events.d.ts +2 -0
  56. package/dist/db/events.js +8 -0
  57. package/dist/db/executor.d.ts +2 -0
  58. package/dist/db/executor.js +8 -0
  59. package/dist/db/locks.d.ts +7 -0
  60. package/dist/db/locks.js +13 -1
  61. package/dist/db/names.d.ts +95 -1
  62. package/dist/db/names.js +95 -1
  63. package/dist/db/occupancy.d.ts +21 -0
  64. package/dist/db/occupancy.js +46 -0
  65. package/dist/db/pageOccupancy.d.ts +4 -4
  66. package/dist/db/pageOccupancy.js +13 -10
  67. package/dist/db/pgExecutor.d.ts +4 -0
  68. package/dist/db/pgExecutor.js +1 -1
  69. package/dist/db/placements.js +1 -1
  70. package/dist/db/results.d.ts +5 -2
  71. package/dist/db/results.js +32 -5
  72. package/dist/db/slices.d.ts +9 -2
  73. package/dist/db/slices.js +15 -8
  74. package/dist/db/snapshots.d.ts +16 -1
  75. package/dist/db/snapshots.js +27 -2
  76. package/dist/db/sql.d.ts +2 -2
  77. package/dist/db/sql.js +1 -2
  78. package/dist/endpoints/cohortSources.d.ts +16 -0
  79. package/dist/endpoints/cohortSources.js +335 -0
  80. package/dist/endpoints/contentLocale.d.ts +1 -1
  81. package/dist/endpoints/events.js +82 -18
  82. package/dist/endpoints/index.js +45 -1
  83. package/dist/endpoints/pausedBy.d.ts +14 -0
  84. package/dist/endpoints/pausedBy.js +94 -0
  85. package/dist/endpoints/preflight.js +4 -1
  86. package/dist/endpoints/previewToken.js +2 -0
  87. package/dist/endpoints/results.d.ts +2 -2
  88. package/dist/endpoints/results.js +111 -3
  89. package/dist/endpoints/routeId.d.ts +2 -1
  90. package/dist/endpoints/routeId.js +6 -2
  91. package/dist/endpoints/summary.js +24 -1
  92. package/dist/endpoints/transitions.d.ts +7 -0
  93. package/dist/endpoints/transitions.js +50 -1
  94. package/dist/events/rows.d.ts +1 -1
  95. package/dist/events/rows.js +5 -3
  96. package/dist/exports/index.d.ts +2 -0
  97. package/dist/exports/index.js +1 -0
  98. package/dist/exports/runtimeProxy.d.ts +1 -0
  99. package/dist/exports/runtimeProxy.js +1 -0
  100. package/dist/hooks/blockRemovalRule.js +7 -4
  101. package/dist/hooks/pageGuard.js +1 -1
  102. package/dist/labels/status.d.ts +15 -0
  103. package/dist/labels/status.js +12 -0
  104. package/dist/manifest/compile.d.ts +15 -4
  105. package/dist/manifest/compile.js +91 -3
  106. package/dist/onInit.js +4 -1
  107. package/dist/options.d.ts +1 -0
  108. package/dist/options.js +10 -0
  109. package/dist/proxy/consentFallback.d.ts +1 -1
  110. package/dist/proxy/consentFallback.js +4 -4
  111. package/dist/proxy/control.d.ts +1 -1
  112. package/dist/proxy/control.js +2 -2
  113. package/dist/proxy/pageRewrite.d.ts +1 -1
  114. package/dist/proxy/pageRewrite.js +3 -2
  115. package/dist/proxy/resolve.js +76 -17
  116. package/dist/puck/ExperimentPicker.js +2 -1
  117. package/dist/puck/copy.d.ts +6 -5
  118. package/dist/puck/copy.js +3 -7
  119. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  120. package/dist/puck/editor/QuickTestActions.js +7 -1
  121. package/dist/puck/editor/armWrites.js +6 -1
  122. package/dist/puck/editor/copy.d.ts +3 -0
  123. package/dist/puck/editor/copy.js +3 -0
  124. package/dist/puck/editor/editor.css +2 -1
  125. package/dist/puck/editor/editor.model.d.ts +2 -1
  126. package/dist/puck/editor/editor.model.js +2 -0
  127. package/dist/puck/editor/placementsCache.d.ts +1 -1
  128. package/dist/puck/editor/placementsCache.js +6 -3
  129. package/dist/results/analyse.d.ts +3 -1
  130. package/dist/results/analyse.js +20 -3
  131. package/dist/results/health.d.ts +11 -0
  132. package/dist/results/health.js +38 -0
  133. package/dist/results/power.d.ts +1 -1
  134. package/dist/results/power.js +1 -1
  135. package/dist/results/snapshot.d.ts +8 -2
  136. package/dist/results/snapshot.js +23 -1
  137. package/dist/results/unitValues.d.ts +48 -0
  138. package/dist/results/unitValues.js +166 -0
  139. package/dist/runtime/assign.d.ts +7 -3
  140. package/dist/runtime/assign.js +12 -4
  141. package/dist/runtime/cohortCookie.d.ts +15 -0
  142. package/dist/runtime/cohortCookie.js +72 -0
  143. package/dist/runtime/cohortLookup.d.ts +9 -0
  144. package/dist/runtime/cohortLookup.js +25 -0
  145. package/dist/runtime/eligibility.d.ts +11 -5
  146. package/dist/runtime/eligibility.js +33 -7
  147. package/dist/runtime/header.d.ts +1 -0
  148. package/dist/runtime/header.js +1 -1
  149. package/dist/runtime/proxyRuntime.js +5 -1
  150. package/dist/runtime/targeting.d.ts +3 -2
  151. package/dist/runtime/targeting.js +2 -1
  152. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  153. package/dist/sanitizeReadinessDetail.js +41 -4
  154. package/dist/schedule/activeTime.d.ts +28 -0
  155. package/dist/schedule/activeTime.js +322 -0
  156. package/dist/schedule/ranges.d.ts +13 -0
  157. package/dist/schedule/ranges.js +11 -0
  158. package/dist/schedule/roundTime.d.ts +10 -0
  159. package/dist/schedule/roundTime.js +45 -0
  160. package/dist/schedule/types.d.ts +29 -0
  161. package/dist/schedule/types.js +1 -0
  162. package/dist/server/cohortLookup.d.ts +3 -0
  163. package/dist/server/cohortLookup.js +7 -0
  164. package/dist/server/eraseUser.d.ts +1 -0
  165. package/dist/server/getAssignments.js +63 -40
  166. package/dist/server/previewDraft.d.ts +1 -1
  167. package/dist/server/previewDraft.js +3 -2
  168. package/dist/server/recordExposures.js +4 -2
  169. package/dist/server/runResults.js +97 -150
  170. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  171. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  172. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  173. package/dist/testSurface/actions/actions.model.js +38 -5
  174. package/dist/testSurface/api.d.ts +13 -1
  175. package/dist/testSurface/api.js +19 -0
  176. package/dist/testSurface/copy/actions.d.ts +13 -0
  177. package/dist/testSurface/copy/actions.js +13 -0
  178. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  179. package/dist/testSurface/copy/cohorts.js +81 -0
  180. package/dist/testSurface/copy/common.d.ts +2 -3
  181. package/dist/testSurface/copy/common.js +4 -4
  182. package/dist/testSurface/copy/inputs.d.ts +3 -0
  183. package/dist/testSurface/copy/inputs.js +3 -0
  184. package/dist/testSurface/copy/readiness.d.ts +20 -6
  185. package/dist/testSurface/copy/readiness.js +42 -9
  186. package/dist/testSurface/copy/results.d.ts +1 -0
  187. package/dist/testSurface/copy/results.js +1 -0
  188. package/dist/testSurface/copy/schedule.d.ts +58 -0
  189. package/dist/testSurface/copy/schedule.js +150 -0
  190. package/dist/testSurface/copy/surface.d.ts +2 -0
  191. package/dist/testSurface/copy/surface.js +2 -0
  192. package/dist/testSurface/copy/testPage.d.ts +12 -2
  193. package/dist/testSurface/copy/testPage.js +17 -2
  194. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  195. package/dist/testSurface/format/roundProgress.js +34 -5
  196. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  197. package/dist/testSurface/format/scheduleStatus.js +93 -0
  198. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  199. package/dist/testSurface/format/useScheduleClock.js +20 -0
  200. package/dist/testSurface/labels.d.ts +4 -9
  201. package/dist/testSurface/labels.js +2 -7
  202. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  203. package/dist/testSurface/lockedNotice.model.js +16 -3
  204. package/dist/testSurface/readPreflight.d.ts +3 -0
  205. package/dist/testSurface/readPreflight.js +14 -0
  206. package/dist/testSurface/readinessRead.d.ts +2 -2
  207. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  208. package/dist/testSurface/results/results.model.d.ts +1 -1
  209. package/dist/testSurface/results/results.model.js +34 -6
  210. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  211. package/dist/testSurface/review/cohortEstimate.js +32 -0
  212. package/dist/testSurface/surface/contracts.d.ts +2 -1
  213. package/dist/testSurface/surface/contracts.js +1 -0
  214. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  215. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  216. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  217. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  218. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  219. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  220. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  221. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  222. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  223. package/dist/testSurface/surface/results/useResults.js +17 -6
  224. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  225. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  226. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  227. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  228. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  229. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  230. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  231. package/dist/testSurface/surface/test/Section.js +1 -1
  232. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  233. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  234. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  235. package/dist/testSurface/surface/test/fields.js +3 -3
  236. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  237. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  238. package/dist/testSurface/surface/test/testPage.css +26 -0
  239. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  240. package/dist/testSurface/surface/testDocument.model.js +2 -1
  241. package/dist/testSurface/surface/useTestDocument.js +11 -4
  242. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  243. package/dist/testSurface/targeting/targeting.model.js +1 -1
  244. package/dist/testSurface/useApi.d.ts +12 -0
  245. package/dist/transitions/addMetric.js +5 -2
  246. package/dist/transitions/allocate.js +6 -1
  247. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  248. package/dist/transitions/assertNoOverlap.js +24 -0
  249. package/dist/transitions/buildCohorts.d.ts +10 -0
  250. package/dist/transitions/buildCohorts.js +68 -0
  251. package/dist/transitions/cancelSchedule.d.ts +4 -0
  252. package/dist/transitions/cancelSchedule.js +42 -0
  253. package/dist/transitions/checkStart.d.ts +17 -3
  254. package/dist/transitions/checkStart.js +20 -7
  255. package/dist/transitions/decide.js +35 -11
  256. package/dist/transitions/kernel.d.ts +3 -1
  257. package/dist/transitions/kernel.js +5 -2
  258. package/dist/transitions/pause.d.ts +4 -0
  259. package/dist/transitions/pause.js +35 -0
  260. package/dist/transitions/phaseRecord.d.ts +19 -2
  261. package/dist/transitions/phaseRecord.js +50 -11
  262. package/dist/transitions/placementInteractions.js +1 -1
  263. package/dist/transitions/preflightData.d.ts +11 -3
  264. package/dist/transitions/preflightData.js +134 -81
  265. package/dist/transitions/reschedule.d.ts +4 -0
  266. package/dist/transitions/reschedule.js +58 -0
  267. package/dist/transitions/resume.d.ts +4 -0
  268. package/dist/transitions/resume.js +32 -0
  269. package/dist/transitions/scheduledRound.d.ts +18 -0
  270. package/dist/transitions/scheduledRound.js +42 -0
  271. package/dist/transitions/start.d.ts +4 -0
  272. package/dist/transitions/start.js +136 -55
  273. package/dist/transitions/startReads.d.ts +14 -0
  274. package/dist/transitions/startReads.js +27 -0
  275. package/dist/transitions/stop.d.ts +10 -0
  276. package/dist/transitions/stop.js +35 -22
  277. package/dist/types/admin.d.ts +1 -1
  278. package/dist/types/contracts.d.ts +7 -1
  279. package/dist/types/endpoints.d.ts +72 -3
  280. package/dist/types/manifest.d.ts +9 -0
  281. package/dist/types/runtime.d.ts +5 -0
  282. package/dist/types/snapshot.d.ts +10 -0
  283. package/dist/types/status.d.ts +1 -0
  284. package/dist/types/status.js +1 -0
  285. package/dist/types/surface.d.ts +1 -0
  286. package/dist/ui/Feedback.d.ts +9 -6
  287. package/dist/ui/Feedback.js +10 -9
  288. package/dist/ui/SelectControl.js +1 -1
  289. package/dist/ui/ui.css +2 -1
  290. package/package.json +2 -2
@@ -0,0 +1,53 @@
1
+ import { cohortMembershipQuery } from './cohortMembership.js';
2
+ import { connectionError, raceDeadline, ResultsBudgetError } from './pgExecutor.js';
3
+ export const COHORT_LOOKUP_TIMEOUT_MS = 200;
4
+ export async function lookupPooledCohorts(pool, schemaName, { keys, visitorId, userId }) {
5
+ const deadline = Date.now() + COHORT_LOOKUP_TIMEOUT_MS;
6
+ if (keys.some((key)=>typeof key !== 'string' || key.length !== 16 || /[^0-9a-f]/.test(key))) {
7
+ throw new Error('Invalid cohort key');
8
+ }
9
+ if (visitorId !== undefined && (typeof visitorId !== 'string' || !visitorId.length || /[^A-Za-z0-9_-]/.test(visitorId))) {
10
+ throw new Error('Invalid cohort visitor id');
11
+ }
12
+ if (!keys.length || !visitorId && !userId) return new Set();
13
+ const keyArray = `ARRAY[${keys.map((key)=>`'${key}'`).join(', ')}]`;
14
+ const visitor = visitorId === undefined ? 'NULL' : `'${visitorId}'`;
15
+ const user = userId === undefined ? 'NULL' : `convert_from(decode('${Buffer.from(userId, 'utf8').toString('hex')}', 'hex'), 'UTF8')`;
16
+ // A single simple Query runs both statements in an implicit transaction.
17
+ // PostgreSQL restores SET LOCAL when that transaction ends, including on cancellation.
18
+ const sql = `SET LOCAL statement_timeout = 150; ${cohortMembershipQuery({
19
+ schemaName
20
+ }, keyArray, visitor, user)}`;
21
+ let client;
22
+ let releaseError;
23
+ let finished = false;
24
+ try {
25
+ return await raceDeadline(deadline, async ()=>{
26
+ const acquired = await pool.connect();
27
+ if (finished) {
28
+ acquired.release();
29
+ throw new ResultsBudgetError();
30
+ }
31
+ client = acquired;
32
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
33
+ const results = await acquired.query(sql);
34
+ const select = Array.isArray(results) ? results.at(-1) : undefined;
35
+ if (select?.command !== 'SELECT') throw new Error('Cohort lookup returned no SELECT result');
36
+ return new Set(select.rows.map((row)=>row.cohort_key));
37
+ });
38
+ } catch (error) {
39
+ releaseError = connectionError(error);
40
+ throw error;
41
+ } finally{
42
+ finished = true;
43
+ client?.release(releaseError);
44
+ }
45
+ }
46
+ export function payloadCohortPool(payload) {
47
+ // §0.5 cohorts: cohort lookup (design 2026-12-04 §8), using the adapter's pool directly.
48
+ const db = payload.db;
49
+ return db?.pool ? {
50
+ pool: db.pool,
51
+ schemaName: db.schemaName
52
+ } : undefined;
53
+ }
@@ -0,0 +1,3 @@
1
+ import type { Payload } from 'payload';
2
+ import { type Executor } from './executor.js';
3
+ export declare function inCohortTransaction<T>(payload: Payload, deadline: number, work: (exec: Executor) => Promise<T>): Promise<T>;
@@ -0,0 +1,52 @@
1
+ import { resultsExecutor } from './snapshots.js';
2
+ import { raceDeadline, ResultsBudgetError, txExecutor } from './executor.js';
3
+ import { currentTxid, txidStatus } from './txid.js';
4
+ import { XpRefusal } from '../errors.js';
5
+ export async function inCohortTransaction(payload, deadline, work) {
6
+ let abandoned = false;
7
+ const begin = async ()=>{
8
+ const db = payload.db;
9
+ const id = await db.beginTransaction({
10
+ ...db.transactionOptions,
11
+ isolationLevel: 'read committed'
12
+ });
13
+ if (id == null) throw new Error('Experiments: cohort writes require a transaction');
14
+ if (abandoned) await payload.db.rollbackTransaction(id);
15
+ return id;
16
+ };
17
+ let transactionID;
18
+ try {
19
+ transactionID = await raceDeadline(deadline, begin);
20
+ } catch (error) {
21
+ abandoned = true;
22
+ throw error;
23
+ }
24
+ const exec = txExecutor({
25
+ payload,
26
+ transactionID
27
+ });
28
+ let xid;
29
+ let result;
30
+ try {
31
+ result = await raceDeadline(deadline, ()=>work(exec));
32
+ xid = await raceDeadline(deadline, ()=>currentTxid(exec));
33
+ if (Date.now() >= deadline) {
34
+ throw new ResultsBudgetError();
35
+ }
36
+ } catch (error) {
37
+ const rollback = payload.db.rollbackTransaction(transactionID);
38
+ // Observe a late rollback without allowing it to block the remaining cron work.
39
+ void rollback.catch(()=>undefined);
40
+ if (Date.now() < deadline) await raceDeadline(deadline, ()=>rollback).catch(()=>undefined);
41
+ throw error;
42
+ }
43
+ // No rollback once commit has started. If it settles late, the next attempt
44
+ // rechecks the registry under the key lock before using or refreshing it.
45
+ const commit = payload.db.commitTransaction(transactionID);
46
+ void commit.catch(()=>undefined);
47
+ await raceDeadline(deadline, ()=>commit);
48
+ if (await txidStatus(resultsExecutor(payload, ()=>deadline - Date.now()), xid) !== 'committed') {
49
+ throw new XpRefusal('commit-unverified', 'The cohort build commit could not be verified.', undefined, 500);
50
+ }
51
+ return result;
52
+ }
@@ -0,0 +1,72 @@
1
+ import type { FrozenCohortRule } from '../cohorts/rule.js';
2
+ import type { ActiveSpec, RoundTiming } from '../schedule/types.js';
3
+ import type { ResultsPhase } from './snapshots.js';
4
+ import type { DocId, UnitType } from '../types/contracts.js';
5
+ import { type Executor } from './executor.js';
6
+ export type CohortSource = {
7
+ phase: ResultsPhase;
8
+ unitType: UnitType;
9
+ };
10
+ export type CohortRegistry = {
11
+ key: string;
12
+ rule: Omit<FrozenCohortRule, 'include'>;
13
+ closed: boolean;
14
+ members: number;
15
+ builtAt: string;
16
+ };
17
+ type ExposureQuery = {
18
+ experiment: DocId;
19
+ phase: number;
20
+ to: Date;
21
+ from?: Date;
22
+ inactive: Array<{
23
+ from: Date;
24
+ to: Date;
25
+ }>;
26
+ };
27
+ /** Exclude the same half-open intervals from cohort membership and results. */
28
+ export declare function inactiveRangesPredicate(column: string, fromParam: string, toParam: string): string;
29
+ /** Append the bound inactive ranges to the results query. */
30
+ export declare function inactiveTimeFilter(spec: ActiveSpec, pauses: NonNullable<RoundTiming['pauses']>, range: {
31
+ from: Date;
32
+ to: Date;
33
+ }, params: unknown[], alias?: string): string;
34
+ export declare function sourceExposureCount(exec: Executor, query: ExposureQuery): Promise<number>;
35
+ export declare function hasExposure(exec: Executor, query: ExposureQuery): Promise<boolean>;
36
+ export declare function cohortExposureUnits(exec: Executor, query: ExposureQuery): Promise<{
37
+ unitId: string;
38
+ arm: string;
39
+ firstTs: string;
40
+ }[]>;
41
+ export declare function replaceExposureCohort(exec: Executor, key: string, now: Date, query: ExposureQuery, arms: readonly string[]): Promise<number>;
42
+ export declare function replaceGoalCohort(exec: Executor, key: string, now: Date, ids: readonly string[]): Promise<number>;
43
+ export declare function readCohort(exec: Executor, key: string): Promise<CohortRegistry | undefined>;
44
+ export declare function writeCohort(exec: Executor, rule: FrozenCohortRule, { closed, members, now }: {
45
+ closed: boolean;
46
+ members: number;
47
+ now: Date;
48
+ }): Promise<void>;
49
+ export declare function readCohortSource(exec: Executor, experiment: DocId, phase: number | 'latest'): Promise<CohortSource | undefined>;
50
+ /** Managers may see the latest test round's dates and number. Frozen settings
51
+ * and snapshots are still read through Payload under readResults. */
52
+ export declare function latestCohortRounds(exec: Executor, ids: DocId[]): Promise<{
53
+ id: DocId;
54
+ phase: number;
55
+ startedAt: string | Date;
56
+ endedAt: string | Date | null;
57
+ }[]>;
58
+ export declare function cohortDependencies(exec: Executor, experiment: DocId): Promise<string[]>;
59
+ export declare function referencedCohortKeys(exec: Executor): Promise<string[]>;
60
+ export declare function cohortIsReferenced(exec: Executor, key: string): Promise<boolean>;
61
+ export declare function refreshableCohortKeys(exec: Executor): Promise<string[]>;
62
+ export declare function sweepableCohortKeys(exec: Executor, stale: Date, cutoff: Date): Promise<string[]>;
63
+ /** Recheck after obtaining the key lock in case Start claimed it meanwhile. */
64
+ export declare function sweepCohortKey(exec: Executor, key: string, stale: Date, cutoff: Date): Promise<void>;
65
+ export declare function cohortExitedUnits(exec: Executor, rule: FrozenCohortRule, unitType: UnitType, units: ReadonlyMap<string, {
66
+ firstTs: Date | string | number;
67
+ }>): Promise<Set<string>>;
68
+ export declare function isCohortTimeout(error: unknown): boolean;
69
+ /** The wrapped executor stays on the caller's transaction. A failed statement
70
+ * aborts it, so rollback restores settings. On success restore them explicitly. */
71
+ export declare function withCohortTimeout<T>(exec: Executor, deadline: number, work: (timed: Executor) => Promise<T>): Promise<T>;
72
+ export {};
@@ -0,0 +1,280 @@
1
+ import { inactiveIntervals } from '../schedule/activeTime.js';
2
+ import { cohortIdentitySet } from './cohortMembership.js';
3
+ import { ResultsBudgetError } from './executor.js';
4
+ import { COLUMNS, TABLES } from './names.js';
5
+ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
6
+ const e = COLUMNS.events;
7
+ const m = COLUMNS.cohortMembers;
8
+ const c = COLUMNS.cohorts;
9
+ const p = COLUMNS.phases;
10
+ const x = COLUMNS.experiments;
11
+ const BATCH_SIZE = 10_000;
12
+ /** Exclude the same half-open intervals from cohort membership and results. */ export function inactiveRangesPredicate(column, fromParam, toParam) {
13
+ return `NOT EXISTS (SELECT 1 FROM unnest(${fromParam}::timestamptz[], ${toParam}::timestamptz[]) g(f, t)
14
+ WHERE ${column} >= g.f AND ${column} < g.t)`;
15
+ }
16
+ /** Append the bound inactive ranges to the results query. */ export function inactiveTimeFilter(spec, pauses, range, params, alias) {
17
+ const intervals = inactiveIntervals(spec, pauses, range);
18
+ if (intervals.length === 0) return 'TRUE';
19
+ const starts = params.push(intervals.map((interval)=>interval.from.toISOString()));
20
+ const ends = params.push(intervals.map((interval)=>interval.to.toISOString()));
21
+ const ts = `${alias === undefined ? '' : `${q(alias)}.`}${q(e.ts)}`;
22
+ return inactiveRangesPredicate(ts, `$${starts}`, `$${ends}`);
23
+ }
24
+ function exposureFilter(exec, offset = 0) {
25
+ return `FROM ${qualifiedTable(exec, TABLES.events)}
26
+ WHERE ${q(e.experimentId)} = $${offset + 1} AND ${q(e.phase)} = $${offset + 2} AND ${q(e.type)} = 'exposure'
27
+ AND ${q(e.ts)} < $${offset + 3} AND ${q(e.ts)} >= $${offset + 6} AND ${inactiveRangesPredicate(q(e.ts), `$${offset + 4}`, `$${offset + 5}`)}`;
28
+ }
29
+ function exposureParams({ experiment, phase, from, to, inactive }) {
30
+ return [
31
+ experiment,
32
+ phase,
33
+ to.toISOString(),
34
+ inactive.map((g)=>g.from.toISOString()),
35
+ inactive.map((g)=>g.to.toISOString()),
36
+ from?.toISOString() ?? '-infinity'
37
+ ];
38
+ }
39
+ export async function sourceExposureCount(exec, query) {
40
+ const { rows } = await exec.query(`SELECT count(*) AS exposure_count ${exposureFilter(exec)}`, exposureParams(query));
41
+ return rows[0].exposure_count;
42
+ }
43
+ export async function hasExposure(exec, query) {
44
+ const { rows } = await exec.query(`SELECT EXISTS (SELECT 1 ${exposureFilter(exec)}) AS present`, exposureParams(query));
45
+ return rows[0]?.present === true;
46
+ }
47
+ export async function cohortExposureUnits(exec, query) {
48
+ const { rows } = await exec.query(`SELECT ${q(e.unitId)} AS "unitId",
49
+ min(${q(e.arm)}) AS arm, min(${q(e.ts)}) AS "firstTs" ${exposureFilter(exec)}
50
+ GROUP BY ${q(e.unitId)} HAVING count(DISTINCT ${q(e.arm)}) = 1 AND count(${q(e.arm)}) = count(*)`, exposureParams(query));
51
+ return rows;
52
+ }
53
+ async function replaceMembers(exec, key, now, desired, params = []) {
54
+ const members = qualifiedTable(exec, TABLES.cohortMembers);
55
+ const { rows } = await exec.query(`WITH desired AS MATERIALIZED (${desired}),
56
+ present AS (
57
+ INSERT INTO ${members} AS m (${q(m.cohortKey)}, ${q(m.unitId)}, ${q(m.builtAt)}, ${q(m.enteredAt)})
58
+ SELECT $1, unit_id, $2, $2 FROM desired
59
+ ON CONFLICT (${q(m.cohortKey)}, ${q(m.unitId)}) DO UPDATE SET
60
+ ${q(m.builtAt)} = excluded.${q(m.builtAt)}, ${q(m.updatedAt)} = excluded.${q(m.builtAt)},
61
+ ${q(m.enteredAt)} = CASE WHEN m.${q(m.exitedAt)} IS NULL THEN m.${q(m.enteredAt)} ELSE excluded.${q(m.enteredAt)} END,
62
+ ${q(m.exitedAt)} = NULL
63
+ RETURNING 1
64
+ ), exited AS (
65
+ UPDATE ${members} m SET ${q(m.exitedAt)} = $2, ${q(m.updatedAt)} = $2
66
+ WHERE m.${q(m.cohortKey)} = $1 AND m.${q(m.exitedAt)} IS NULL
67
+ AND NOT EXISTS (SELECT 1 FROM desired d WHERE d.unit_id = m.${q(m.unitId)})
68
+ ) SELECT count(*) AS member_count FROM present`, [
69
+ key,
70
+ now.toISOString(),
71
+ ...params
72
+ ]);
73
+ return rows[0].member_count;
74
+ }
75
+ export function replaceExposureCohort(exec, key, now, query, arms) {
76
+ return replaceMembers(exec, key, now, `SELECT ${q(e.unitId)} AS unit_id ${exposureFilter(exec, 2)}
77
+ GROUP BY ${q(e.unitId)} HAVING count(DISTINCT ${q(e.arm)}) = 1 AND count(${q(e.arm)}) = count(*) AND min(${q(e.arm)})::text = ANY($9::text[])`, [
78
+ ...exposureParams(query),
79
+ arms
80
+ ]);
81
+ }
82
+ export async function replaceGoalCohort(exec, key, now, ids) {
83
+ // One staging table per transaction. Multiple goal rules in Start reuse it.
84
+ await exec.query('CREATE TEMP TABLE IF NOT EXISTS xp_cohort_desired (unit_id text PRIMARY KEY) ON COMMIT DROP');
85
+ await exec.query('TRUNCATE pg_temp.xp_cohort_desired');
86
+ for(let offset = 0; offset < ids.length; offset += BATCH_SIZE){
87
+ await exec.query('INSERT INTO pg_temp.xp_cohort_desired SELECT unnest($1::text[])', [
88
+ ids.slice(offset, offset + BATCH_SIZE)
89
+ ]);
90
+ }
91
+ return replaceMembers(exec, key, now, 'SELECT unit_id FROM pg_temp.xp_cohort_desired');
92
+ }
93
+ const registryColumns = `${q(c.cohortKey)} AS key, ${q(c.rule)}, ${q(c.closed)}, ${q(c.members)}, ${q(c.builtAt)} AS "builtAt"`;
94
+ export async function readCohort(exec, key) {
95
+ const { rows } = await exec.query(`SELECT ${registryColumns} FROM ${qualifiedTable(exec, TABLES.cohorts)}
96
+ WHERE ${q(c.cohortKey)} = $1 AND ${q(c.state)} = 'ready'`, [
97
+ key
98
+ ]);
99
+ return rows[0];
100
+ }
101
+ export async function writeCohort(exec, rule, { closed, members, now }) {
102
+ const { include: _include, ...criteria } = rule;
103
+ await exec.query(`INSERT INTO ${qualifiedTable(exec, TABLES.cohorts)} (${q(c.cohortKey)}, ${q(c.rule)}, ${q(c.state)},
104
+ ${q(c.closed)}, ${q(c.members)}, ${q(c.builtAt)}) VALUES ($1, $2::jsonb, 'ready', $3, $4, $5)
105
+ ON CONFLICT (${q(c.cohortKey)}) DO UPDATE SET ${q(c.closed)} = excluded.${q(c.closed)},
106
+ ${q(c.members)} = excluded.${q(c.members)}, ${q(c.builtAt)} = excluded.${q(c.builtAt)}, ${q(c.updatedAt)} = excluded.${q(c.builtAt)}`, [
107
+ rule.key,
108
+ JSON.stringify(criteria),
109
+ closed,
110
+ members,
111
+ now.toISOString()
112
+ ]);
113
+ }
114
+ export async function readCohortSource(exec, experiment, phase) {
115
+ const params = phase === 'latest' ? [
116
+ experiment
117
+ ] : [
118
+ experiment,
119
+ phase
120
+ ];
121
+ const { rows } = await exec.query(`SELECT e.${q(x.unitType)} AS "unitType",
122
+ jsonb_build_object('experiment', p.${q(p.experimentId)}, 'phase', p.${q(p.phase)}, 'phaseKind', p.${q(p.phaseKind)},
123
+ 'startedAt', p.${q(p.startedAt)}, 'endedAt', p.${q(p.endedAt)}, 'seed', p.${q(p.seed)}, 'arms', p.${q(p.arms)},
124
+ 'allocation', p.${q(p.allocation)}, 'metricDefinitions', p.${q(p.metricDefinitions)}, 'analysis', p.${q(p.analysis)},
125
+ 'targeting', p.${q(p.targeting)}, 'schedule', p.${q(p.schedule)}, 'pauses', p.${q(p.pauses)}) AS phase
126
+ FROM ${qualifiedTable(exec, TABLES.phases)} p
127
+ JOIN ${qualifiedTable(exec, TABLES.experiments)} e ON e.${q(x.id)} = p.${q(p.experimentId)}
128
+ WHERE p.${q(p.experimentId)} = $1 AND p.${q(p.phaseKind)} = 'test'
129
+ ${phase === 'latest' ? '' : `AND p.${q(p.phase)} = $2`}
130
+ ORDER BY p.${q(p.phase)} DESC LIMIT 1`, params);
131
+ return rows[0];
132
+ }
133
+ /** Managers may see the latest test round's dates and number. Frozen settings
134
+ * and snapshots are still read through Payload under readResults. */ export async function latestCohortRounds(exec, ids) {
135
+ if (!ids.length) return [];
136
+ const p = COLUMNS.phases;
137
+ const { rows } = await exec.query(`SELECT DISTINCT ON (${q(p.experimentId)}) ${q(p.experimentId)} AS id, ${q(p.phase)} AS phase,
138
+ ${q(p.startedAt)} AS "startedAt", ${q(p.endedAt)} AS "endedAt"
139
+ FROM ${qualifiedTable(exec, TABLES.phases)}
140
+ WHERE ${q(p.experimentId)} = ANY($1) AND ${q(p.phaseKind)} = 'test'
141
+ ORDER BY ${q(p.experimentId)}, ${q(p.phase)} DESC`, [
142
+ ids
143
+ ]);
144
+ return rows;
145
+ }
146
+ export async function cohortDependencies(exec, experiment) {
147
+ const t = COLUMNS.experimentsTargeting;
148
+ const { rows } = await exec.query(`SELECT t.${q(t.sourceExperimentId)}::text AS source
149
+ FROM ${qualifiedTable(exec, TABLES.experimentsTargeting)} t
150
+ WHERE t.${q(t._parentId)} = $1 AND t.${q(t.kind)} = 'cohort' AND t.${q(t.sourceExperimentId)} IS NOT NULL
151
+ UNION SELECT targeting.rule->>'experiment'
152
+ FROM ${qualifiedTable(exec, TABLES.experiments)} e JOIN ${qualifiedTable(exec, TABLES.phases)} p
153
+ ON p.${q(p.experimentId)} = e.${q(x.id)} AND p.${q(p.phase)} = e.${q(x.phase)},
154
+ jsonb_array_elements(p.${q(p.targeting)}) AS targeting(rule)
155
+ WHERE e.${q(x.id)} = $1 AND targeting.rule->>'kind' = 'cohort' AND targeting.rule->>'experiment' IS NOT NULL`, [
156
+ experiment
157
+ ]);
158
+ return rows.map((row)=>row.source);
159
+ }
160
+ function references(exec) {
161
+ return `SELECT DISTINCT targeting.rule->>'key' AS key FROM ${qualifiedTable(exec, TABLES.experiments)} e
162
+ JOIN ${qualifiedTable(exec, TABLES.phases)} p ON p.${q(p.experimentId)} = e.${q(x.id)} AND p.${q(p.phase)} = e.${q(x.phase)},
163
+ jsonb_array_elements(p.${q(p.targeting)}) AS targeting(rule) WHERE e.${q(x.status)} IN ('running', 'paused', 'decided')
164
+ AND targeting.rule->>'kind' = 'cohort' AND targeting.rule->>'key' IS NOT NULL`;
165
+ }
166
+ export async function referencedCohortKeys(exec) {
167
+ const { rows } = await exec.query(references(exec));
168
+ return rows.map((row)=>row.key);
169
+ }
170
+ export async function cohortIsReferenced(exec, key) {
171
+ const { rows } = await exec.query(`SELECT $1::text IN (${references(exec)}) AS present`, [
172
+ key
173
+ ]);
174
+ return rows[0]?.present === true;
175
+ }
176
+ export async function refreshableCohortKeys(exec) {
177
+ const { rows } = await exec.query(`SELECT ${q(c.cohortKey)} AS key FROM ${qualifiedTable(exec, TABLES.cohorts)}
178
+ WHERE ${q(c.closed)} IS NOT TRUE AND ${q(c.cohortKey)} IN (${references(exec)})
179
+ ORDER BY ${q(c.builtAt)}, ${q(c.cohortKey)}`);
180
+ return rows.map((row)=>row.key);
181
+ }
182
+ function sweepPredicate(exec) {
183
+ return `(r.${q(c.builtAt)} < $1 AND r.${q(c.cohortKey)} NOT IN (${references(exec)}))
184
+ OR NOT EXISTS (SELECT 1 FROM ${qualifiedTable(exec, TABLES.phases)} p
185
+ WHERE p.${q(p.experimentId)}::text = r.${q(c.rule)}->>'experiment'
186
+ AND p.${q(p.phase)} = (r.${q(c.rule)}->>'phase')::numeric
187
+ AND (p.${q(p.endedAt)} IS NULL OR p.${q(p.endedAt)} >= $2))`;
188
+ }
189
+ export async function sweepableCohortKeys(exec, stale, cutoff) {
190
+ const { rows } = await exec.query(`SELECT r.${q(c.cohortKey)} AS key FROM ${qualifiedTable(exec, TABLES.cohorts)} r
191
+ WHERE ${sweepPredicate(exec)} ORDER BY r.${q(c.builtAt)}, r.${q(c.cohortKey)}`, [
192
+ stale.toISOString(),
193
+ cutoff.toISOString()
194
+ ]);
195
+ return rows.map((row)=>row.key);
196
+ }
197
+ /** Recheck after obtaining the key lock in case Start claimed it meanwhile. */ export async function sweepCohortKey(exec, key, stale, cutoff) {
198
+ const removed = await exec.query(`DELETE FROM ${qualifiedTable(exec, TABLES.cohorts)} r WHERE r.${q(c.cohortKey)} = $3
199
+ AND (${sweepPredicate(exec)}) RETURNING r.${q(c.cohortKey)}`, [
200
+ stale.toISOString(),
201
+ cutoff.toISOString(),
202
+ key
203
+ ]);
204
+ if (!removed.rows.length) return;
205
+ const members = qualifiedTable(exec, TABLES.cohortMembers);
206
+ while(true){
207
+ const batch = await exec.query(`DELETE FROM ${members} WHERE ${q(m.id)} IN (SELECT ${q(m.id)} FROM ${members}
208
+ WHERE ${q(m.cohortKey)} = $1 LIMIT ${BATCH_SIZE}) RETURNING ${q(m.id)}`, [
209
+ key
210
+ ]);
211
+ if (batch.rows.length < BATCH_SIZE) return;
212
+ }
213
+ }
214
+ export async function cohortExitedUnits(exec, rule, unitType, units) {
215
+ const ids = [
216
+ ...units.keys()
217
+ ];
218
+ const table = qualifiedTable(exec, TABLES.cohortMembers);
219
+ const current = `m.${q(m.exitedAt)} IS NULL`;
220
+ const condition = rule.include ? `NOT coalesce(bool_or(${current}), false) AND bool_or(m.${q(m.exitedAt)} > u.first_ts)` : `bool_or(${current} AND m.${q(m.enteredAt)} > u.first_ts)`;
221
+ const identitySet = cohortIdentitySet(exec, unitType === 'visitor' ? 'u.id' : 'NULL', unitType === 'user' ? 'u.id' : 'NULL');
222
+ const exited = new Set();
223
+ for(let i = 0; i < ids.length; i += BATCH_SIZE){
224
+ const batch = ids.slice(i, i + BATCH_SIZE);
225
+ const { rows } = await exec.query(`SELECT u.id FROM unnest($2::text[], $3::timestamptz[]) u(id, first_ts)
226
+ WHERE (WITH ${identitySet} SELECT ${condition}
227
+ FROM ids JOIN ${table} m ON m.${q(m.unitId)} = ids.id AND m.${q(m.cohortKey)} = $1)`, [
228
+ rule.key,
229
+ batch,
230
+ batch.map((id)=>new Date(units.get(id).firstTs).toISOString())
231
+ ]);
232
+ for (const row of rows)exited.add(row.id);
233
+ }
234
+ return exited;
235
+ }
236
+ export function isCohortTimeout(error) {
237
+ const seen = new Set();
238
+ for(let current = error; current && typeof current === 'object' && !seen.has(current);){
239
+ seen.add(current);
240
+ if (current instanceof ResultsBudgetError || 'code' in current && current.code === '57014') return true;
241
+ if (!('cause' in current) || current.cause === current) return false;
242
+ current = current.cause;
243
+ }
244
+ return false;
245
+ }
246
+ /** The wrapped executor stays on the caller's transaction. A failed statement
247
+ * aborts it, so rollback restores settings. On success restore them explicitly. */ export async function withCohortTimeout(exec, deadline, work) {
248
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
249
+ const { rows } = await exec.query("SELECT current_setting('statement_timeout') AS timeout");
250
+ let aborted = false;
251
+ let completed = false;
252
+ const timed = Object.assign({
253
+ async query (statement, params) {
254
+ const remaining = Math.floor(deadline - Date.now());
255
+ if (remaining <= 0) throw new ResultsBudgetError();
256
+ try {
257
+ await exec.query("SELECT set_config('statement_timeout', $1, true)", [
258
+ `${remaining}ms`
259
+ ]);
260
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
261
+ return await exec.query(statement, params);
262
+ } catch (error) {
263
+ aborted = true;
264
+ throw error;
265
+ }
266
+ }
267
+ }, {
268
+ schemaName: exec.schemaName
269
+ });
270
+ try {
271
+ const result = await work(timed);
272
+ if (Date.now() >= deadline) throw new ResultsBudgetError();
273
+ completed = true;
274
+ return result;
275
+ } finally{
276
+ if (!aborted && (completed || Date.now() < deadline)) await exec.query("SELECT set_config('statement_timeout', $1, true)", [
277
+ rows[0].timeout
278
+ ]);
279
+ }
280
+ }
@@ -4,9 +4,11 @@ import { type Executor } from './executor.js';
4
4
  export declare function eraseUserRows(exec: Executor, userId: string): Promise<{
5
5
  identities: number;
6
6
  events: number;
7
+ cohortMembers: number;
7
8
  }>;
8
9
  /** Own a Payload transaction, then verify on the pool: Payload can swallow COMMIT errors. */
9
10
  export declare function eraseUserInTransaction(payload: Payload, userId: string): Promise<{
10
11
  identities: number;
11
12
  events: number;
13
+ cohortMembers: number;
12
14
  }>;
package/dist/db/erase.js CHANGED
@@ -1,14 +1,18 @@
1
+ import { lockCohortErasure } from './locks.js';
1
2
  import { pooledExecutor, txExecutor } from './executor.js';
2
3
  import { COLUMNS, TABLES } from './names.js';
3
4
  const quote = (name)=>`"${name.replaceAll('"', '""')}"`;
4
5
  const i = COLUMNS.identities;
5
6
  const e = COLUMNS.events;
7
+ const m = COLUMNS.cohortMembers;
8
+ const memberPredicate = `${quote(m.unitId)} = $1 OR ${quote(m.unitId)} = ANY($2::text[])`;
6
9
  function table(exec, name) {
7
10
  const schema = exec.schemaName;
8
11
  return `${schema ? `${quote(schema)}.` : ''}${quote(name)}`;
9
12
  }
10
13
  const eventPredicate = `${quote(e.userId)} = $1 OR (${quote(e.unitType)} = 'user' AND ${quote(e.unitId)} = $1) OR ${quote(e.unitId)} = ANY($2::text[])`;
11
14
  async function erase(exec, userId) {
15
+ await lockCohortErasure(exec, true);
12
16
  const linked = await exec.query(`SELECT ${quote(i.anonymousId)} AS "anonymousId" FROM ${table(exec, TABLES.identities)} WHERE ${quote(i.userId)} = $1`, [
13
17
  userId
14
18
  ]);
@@ -20,10 +24,25 @@ async function erase(exec, userId) {
20
24
  const identities = await exec.query(`DELETE FROM ${table(exec, TABLES.identities)} WHERE ${quote(i.userId)} = $1 RETURNING ${quote(i.id)}`, [
21
25
  userId
22
26
  ]);
27
+ const c = COLUMNS.cohorts;
28
+ const members = await exec.query(`WITH removed AS (
29
+ DELETE FROM ${table(exec, TABLES.cohortMembers)} WHERE ${memberPredicate}
30
+ RETURNING ${quote(m.cohortKey)}, ${quote(m.exitedAt)}
31
+ ), affected AS (
32
+ SELECT ${quote(m.cohortKey)}, count(*) AS removed_live FROM removed
33
+ WHERE ${quote(m.exitedAt)} IS NULL GROUP BY ${quote(m.cohortKey)}
34
+ ), registry AS (
35
+ UPDATE ${table(exec, TABLES.cohorts)} c SET ${quote(c.members)} = greatest(0, c.${quote(c.members)} - affected.removed_live)
36
+ FROM affected WHERE c.${quote(c.cohortKey)} = affected.${quote(m.cohortKey)}
37
+ ) SELECT count(*) AS member_count FROM removed`, [
38
+ userId,
39
+ anonymousIds
40
+ ]);
23
41
  return {
24
42
  counts: {
25
43
  identities: identities.rows.length,
26
- events: events.rows.length
44
+ events: events.rows.length,
45
+ cohortMembers: members.rows[0]?.member_count ?? 0
27
46
  },
28
47
  anonymousIds
29
48
  };
@@ -46,7 +65,7 @@ async function erase(exec, userId) {
46
65
  throw error;
47
66
  }
48
67
  const exec = pooledExecutor(payload);
49
- const verified = await exec.query(`SELECT EXISTS (SELECT 1 FROM ${table(exec, TABLES.events)} WHERE ${eventPredicate}) OR EXISTS (SELECT 1 FROM ${table(exec, TABLES.identities)} WHERE ${quote(i.userId)} = $1) AS remaining`, [
68
+ const verified = await exec.query(`SELECT EXISTS (SELECT 1 FROM ${table(exec, TABLES.events)} WHERE ${eventPredicate}) OR EXISTS (SELECT 1 FROM ${table(exec, TABLES.identities)} WHERE ${quote(i.userId)} = $1) OR EXISTS (SELECT 1 FROM ${table(exec, TABLES.cohortMembers)} WHERE ${memberPredicate}) AS remaining`, [
50
69
  userId,
51
70
  result.anonymousIds
52
71
  ]);
@@ -17,6 +17,8 @@ export interface EventRow {
17
17
  attributes?: Record<string, unknown>;
18
18
  dedupeKey: string;
19
19
  }
20
+ /** A scheduled round can be canceled only before any exposure was recorded. */
21
+ export declare function hasPhaseExposures(exec: Executor, experimentId: DocId, phase: number): Promise<boolean>;
20
22
  type ServerConversion = Pick<EventRow, 'unitId' | 'unitType' | 'userId' | 'ts'> & {
21
23
  eventName: string;
22
24
  value: number;
package/dist/db/events.js CHANGED
@@ -9,6 +9,14 @@ import { qualifiedTable, quoteIdentifier } from './sql.js';
9
9
  }
10
10
  const quote = quoteIdentifier;
11
11
  const c = COLUMNS.events;
12
+ /** A scheduled round can be canceled only before any exposure was recorded. */ export async function hasPhaseExposures(exec, experimentId, phase) {
13
+ const { rows } = await exec.query(`SELECT 1 FROM ${qualifiedTable(exec, TABLES.events)}
14
+ WHERE ${quote(c.experimentId)} = $1 AND ${quote(c.phase)} = $2 AND ${quote(c.type)} = 'exposure' LIMIT 1`, [
15
+ experimentId,
16
+ phase
17
+ ]);
18
+ return rows.length > 0;
19
+ }
12
20
  function foreignKeyViolation(error) {
13
21
  const seen = new Set();
14
22
  while(error && typeof error === 'object' && !seen.has(error)){
@@ -2,6 +2,8 @@ import type { Payload, PayloadRequest } from 'payload';
2
2
  import type { Executor } from './pgExecutor.js';
3
3
  export type { Executor } from './pgExecutor.js';
4
4
  export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, ResultsBudgetError, RESULTS_TIMEOUT_MARGIN_MS } from './pgExecutor.js';
5
+ /** Bound statements in an owned results transition without racing a write or commit. */
6
+ export declare function setTransitionTimeout(exec: Executor, deadline: number): Promise<void>;
5
7
  type TransactionRequest = Pick<PayloadRequest, 'payload' | 'transactionID'>;
6
8
  export declare function transactionSession(req: TransactionRequest): Promise<{
7
9
  db: unknown;
@@ -1,7 +1,15 @@
1
1
  import { sql } from '@payloadcms/db-postgres/drizzle';
2
2
  import { XpNoTransactionError } from '../errors.js';
3
3
  import { normalise, scanParameters } from './pgExecutor.js';
4
+ import { ResultsBudgetError } from './pgExecutor.js';
4
5
  export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, ResultsBudgetError, RESULTS_TIMEOUT_MARGIN_MS } from './pgExecutor.js';
6
+ /** Bound statements in an owned results transition without racing a write or commit. */ export async function setTransitionTimeout(exec, deadline) {
7
+ const remaining = Math.floor(deadline - Date.now());
8
+ if (remaining <= 0) throw new ResultsBudgetError();
9
+ await exec.query("SELECT set_config('statement_timeout', $1, true)", [
10
+ String(remaining)
11
+ ]);
12
+ }
5
13
  /** Convert code-only $n placeholders to sql.raw chunks and sql.param values.
6
14
  * Repeated/out-of-order placeholders rebind; arrays are always one parameter.
7
15
  */ function bind(text, params) {
@@ -6,6 +6,8 @@ export declare const LOCK_NAMESPACES: {
6
6
  readonly experiment: "xp:experiment";
7
7
  readonly pagePath: "xp:pagepath";
8
8
  readonly slug: "xp:slug";
9
+ readonly cohort: "xp:cohort";
10
+ readonly cohortErasure: "xp:cohort-erasure";
9
11
  };
10
12
  /** Transaction executor only. Call in layer → flag point → experiment order;
11
13
  * the manifest builder takes the state lock last, after transition writes.
@@ -27,3 +29,8 @@ export declare function lockSlug(exec: Executor, slug: string): Promise<void>;
27
29
  * SET LOCAL reverts on abort. Restore explicitly only after successful work.
28
30
  */
29
31
  export declare function lockPlacementScope(exec: Executor, experiments: readonly string[], paths: readonly string[]): Promise<void>;
32
+ /** Shared across cohort writes, exclusive while erasing a person's source rows.
33
+ * Acquire before any cohort key lock to keep erasure and materialization ordered. */
34
+ export declare function lockCohortErasure(exec: Executor, exclusive?: boolean): Promise<void>;
35
+ /** Take these after experiment, page-path and slug locks, before state. */
36
+ export declare function lockCohorts(exec: Executor, keys: readonly string[]): Promise<void>;
package/dist/db/locks.js CHANGED
@@ -3,9 +3,12 @@ export const LOCK_NAMESPACES = {
3
3
  flagPoint: 'xp:flagpoint',
4
4
  experiment: 'xp:experiment',
5
5
  pagePath: 'xp:pagepath',
6
- slug: 'xp:slug'
6
+ slug: 'xp:slug',
7
+ cohort: 'xp:cohort',
8
+ cohortErasure: 'xp:cohort-erasure'
7
9
  };
8
10
  const LOCK_STATEMENTS = {
11
+ cohort: `SELECT pg_advisory_xact_lock(hashtext('${LOCK_NAMESPACES.cohort}'), hashtext($1))`,
9
12
  layer: `SELECT pg_advisory_xact_lock(hashtext('${LOCK_NAMESPACES.layer}'), hashtext($1))`,
10
13
  flagPoint: `SELECT pg_advisory_xact_lock(hashtext('${LOCK_NAMESPACES.flagPoint}'), hashtext($1))`,
11
14
  slug: `SELECT pg_advisory_xact_lock(hashtext('${LOCK_NAMESPACES.slug}'), hashtext($1))`,
@@ -56,3 +59,12 @@ export async function lockSlug(exec, slug) {
56
59
  rows[0].timeout
57
60
  ]);
58
61
  }
62
+ /** Shared across cohort writes, exclusive while erasing a person's source rows.
63
+ * Acquire before any cohort key lock to keep erasure and materialization ordered. */ export async function lockCohortErasure(exec, exclusive = false) {
64
+ await exec.query(exclusive ? `SELECT pg_advisory_xact_lock(hashtext('${LOCK_NAMESPACES.cohortErasure}'), 0)` : `SELECT pg_advisory_xact_lock_shared(hashtext('${LOCK_NAMESPACES.cohortErasure}'), 0)`);
65
+ }
66
+ /** Take these after experiment, page-path and slug locks, before state. */ export async function lockCohorts(exec, keys) {
67
+ for (const key of sortLockKeys(keys))await exec.query(LOCK_STATEMENTS.cohort, [
68
+ key
69
+ ]);
70
+ }