@delmaredigital/payload-experiments 0.4.1 → 0.5.1
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.
- package/README.md +9 -5
- package/dist/admin/blocks/model.js +2 -0
- package/dist/admin/copy/blocks.d.ts +1 -0
- package/dist/admin/copy/blocks.js +1 -0
- package/dist/admin/copy/status.d.ts +3 -0
- package/dist/admin/copy/status.js +3 -0
- package/dist/admin/placementStatus.model.js +3 -0
- package/dist/admin/status.model.d.ts +3 -2
- package/dist/admin/status.model.js +9 -3
- package/dist/admin/surface/ResultsRoute.js +2 -1
- package/dist/admin/surface/TestsHome.d.ts +2 -1
- package/dist/admin/surface/TestsHome.js +31 -11
- package/dist/admin/surface/TestsSurface.js +4 -0
- package/dist/admin/surface/home.model.d.ts +11 -6
- package/dist/admin/surface/home.model.js +19 -8
- package/dist/admin/surface/newTest/PageWizard.js +13 -3
- package/dist/admin/surface/results/ResultsHeader.js +43 -9
- package/dist/admin/surface/test/TestPage.js +11 -1
- package/dist/admin/useLayerUsage.d.ts +1 -1
- package/dist/admin/views/buildSurfaceProps.js +3 -0
- package/dist/blocks/placementLocale.d.ts +14 -0
- package/dist/blocks/placementLocale.js +80 -13
- package/dist/blocks/placementPublication.d.ts +14 -0
- package/dist/blocks/placementPublication.js +24 -0
- package/dist/cohorts/build.d.ts +35 -0
- package/dist/cohorts/build.js +134 -0
- package/dist/cohorts/key.d.ts +12 -0
- package/dist/cohorts/key.js +15 -0
- package/dist/cohorts/maintenance.d.ts +10 -0
- package/dist/cohorts/maintenance.js +70 -0
- package/dist/cohorts/readiness.d.ts +30 -0
- package/dist/cohorts/readiness.js +54 -0
- package/dist/cohorts/readinessData.d.ts +29 -0
- package/dist/cohorts/readinessData.js +123 -0
- package/dist/cohorts/rule.d.ts +33 -0
- package/dist/cohorts/rule.js +50 -0
- package/dist/collections/cohortMembers.d.ts +4 -0
- package/dist/collections/cohortMembers.js +95 -0
- package/dist/collections/experiments/config.js +157 -7
- package/dist/collections/experiments/editability.js +10 -6
- package/dist/collections/experiments/lockHook.js +39 -20
- package/dist/collections/index.js +4 -1
- package/dist/collections/phases.js +4 -1
- package/dist/constants.d.ts +2 -0
- package/dist/constants.js +2 -0
- package/dist/db/adapter.d.ts +2 -1
- package/dist/db/adapter.js +17 -4
- package/dist/db/appends.d.ts +2 -1
- package/dist/db/appends.js +3 -2
- package/dist/db/bulkPlacementRemoval.d.ts +5 -0
- package/dist/db/bulkPlacementRemoval.js +7 -2
- package/dist/db/cohortMembership.d.ts +11 -0
- package/dist/db/cohortMembership.js +31 -0
- package/dist/db/cohortPool.d.ts +9 -0
- package/dist/db/cohortPool.js +53 -0
- package/dist/db/cohortTransactions.d.ts +3 -0
- package/dist/db/cohortTransactions.js +52 -0
- package/dist/db/cohorts.d.ts +72 -0
- package/dist/db/cohorts.js +280 -0
- package/dist/db/erase.d.ts +2 -0
- package/dist/db/erase.js +21 -2
- package/dist/db/events.d.ts +2 -0
- package/dist/db/events.js +8 -0
- package/dist/db/executor.d.ts +2 -0
- package/dist/db/executor.js +8 -0
- package/dist/db/locks.d.ts +7 -0
- package/dist/db/locks.js +13 -1
- package/dist/db/names.d.ts +95 -1
- package/dist/db/names.js +95 -1
- package/dist/db/occupancy.d.ts +21 -0
- package/dist/db/occupancy.js +46 -0
- package/dist/db/pageBindings.d.ts +2 -2
- package/dist/db/pageBindings.js +3 -3
- package/dist/db/pageOccupancy.d.ts +4 -4
- package/dist/db/pageOccupancy.js +13 -10
- package/dist/db/pgExecutor.d.ts +4 -0
- package/dist/db/pgExecutor.js +1 -1
- package/dist/db/placements.d.ts +6 -1
- package/dist/db/placements.js +27 -1
- package/dist/db/results.d.ts +5 -2
- package/dist/db/results.js +32 -5
- package/dist/db/slices.d.ts +9 -2
- package/dist/db/slices.js +15 -8
- package/dist/db/snapshots.d.ts +16 -1
- package/dist/db/snapshots.js +27 -2
- package/dist/db/sql.d.ts +2 -2
- package/dist/db/sql.js +1 -2
- package/dist/endpoints/cohortSources.d.ts +16 -0
- package/dist/endpoints/cohortSources.js +335 -0
- package/dist/endpoints/contentLocale.d.ts +1 -1
- package/dist/endpoints/duplicateOriginal.d.ts +1 -0
- package/dist/endpoints/events.js +82 -18
- package/dist/endpoints/index.js +45 -1
- package/dist/endpoints/pausedBy.d.ts +14 -0
- package/dist/endpoints/pausedBy.js +94 -0
- package/dist/endpoints/preflight.js +4 -1
- package/dist/endpoints/previewToken.js +2 -0
- package/dist/endpoints/results.d.ts +2 -2
- package/dist/endpoints/results.js +111 -3
- package/dist/endpoints/routeId.d.ts +2 -1
- package/dist/endpoints/routeId.js +6 -2
- package/dist/endpoints/summary.js +24 -1
- package/dist/endpoints/transitions.d.ts +7 -0
- package/dist/endpoints/transitions.js +50 -1
- package/dist/events/rows.d.ts +1 -1
- package/dist/events/rows.js +5 -3
- package/dist/exports/index.d.ts +2 -0
- package/dist/exports/index.js +1 -0
- package/dist/exports/runtimeProxy.d.ts +1 -0
- package/dist/exports/runtimeProxy.js +1 -0
- package/dist/hooks/blockRemovalRule.d.ts +1 -1
- package/dist/hooks/blockRemovalRule.js +12 -8
- package/dist/hooks/pageGuard.d.ts +7 -1
- package/dist/hooks/pageGuard.js +177 -4
- package/dist/hooks/puckNestedTests.d.ts +1 -1
- package/dist/hooks/puckNestedTests.js +3 -1
- package/dist/labels/status.d.ts +15 -0
- package/dist/labels/status.js +12 -0
- package/dist/manifest/compile.d.ts +15 -4
- package/dist/manifest/compile.js +91 -3
- package/dist/onInit.js +4 -6
- package/dist/options.d.ts +1 -0
- package/dist/options.js +10 -0
- package/dist/proxy/consentFallback.d.ts +1 -1
- package/dist/proxy/consentFallback.js +4 -4
- package/dist/proxy/control.d.ts +1 -1
- package/dist/proxy/control.js +2 -2
- package/dist/proxy/pageRewrite.d.ts +1 -1
- package/dist/proxy/pageRewrite.js +3 -2
- package/dist/proxy/resolve.js +76 -17
- package/dist/puck/ExperimentPicker.js +2 -1
- package/dist/puck/copy.d.ts +6 -5
- package/dist/puck/copy.js +3 -7
- package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
- package/dist/puck/editor/QuickTestActions.js +7 -1
- package/dist/puck/editor/armWrites.js +6 -1
- package/dist/puck/editor/copy.d.ts +3 -0
- package/dist/puck/editor/copy.js +3 -0
- package/dist/puck/editor/editor.css +2 -1
- package/dist/puck/editor/editor.model.d.ts +2 -1
- package/dist/puck/editor/editor.model.js +2 -0
- package/dist/puck/editor/placementsCache.d.ts +1 -1
- package/dist/puck/editor/placementsCache.js +6 -3
- package/dist/results/analyse.d.ts +3 -1
- package/dist/results/analyse.js +20 -3
- package/dist/results/health.d.ts +11 -0
- package/dist/results/health.js +38 -0
- package/dist/results/power.d.ts +1 -1
- package/dist/results/power.js +1 -1
- package/dist/results/snapshot.d.ts +8 -2
- package/dist/results/snapshot.js +23 -1
- package/dist/results/unitValues.d.ts +48 -0
- package/dist/results/unitValues.js +166 -0
- package/dist/runtime/assign.d.ts +7 -3
- package/dist/runtime/assign.js +12 -4
- package/dist/runtime/cohortCookie.d.ts +15 -0
- package/dist/runtime/cohortCookie.js +72 -0
- package/dist/runtime/cohortLookup.d.ts +9 -0
- package/dist/runtime/cohortLookup.js +25 -0
- package/dist/runtime/eligibility.d.ts +11 -5
- package/dist/runtime/eligibility.js +33 -7
- package/dist/runtime/header.d.ts +1 -0
- package/dist/runtime/header.js +1 -1
- package/dist/runtime/proxyRuntime.js +5 -1
- package/dist/runtime/targeting.d.ts +3 -2
- package/dist/runtime/targeting.js +2 -1
- package/dist/sanitizeReadinessDetail.d.ts +2 -2
- package/dist/sanitizeReadinessDetail.js +41 -4
- package/dist/schedule/activeTime.d.ts +28 -0
- package/dist/schedule/activeTime.js +322 -0
- package/dist/schedule/ranges.d.ts +13 -0
- package/dist/schedule/ranges.js +11 -0
- package/dist/schedule/roundTime.d.ts +10 -0
- package/dist/schedule/roundTime.js +45 -0
- package/dist/schedule/types.d.ts +29 -0
- package/dist/schedule/types.js +1 -0
- package/dist/server/cohortLookup.d.ts +3 -0
- package/dist/server/cohortLookup.js +7 -0
- package/dist/server/eraseUser.d.ts +1 -0
- package/dist/server/getAssignments.js +63 -40
- package/dist/server/previewDraft.d.ts +1 -1
- package/dist/server/previewDraft.js +3 -2
- package/dist/server/recordContentChange.d.ts +1 -1
- package/dist/server/recordContentChange.js +42 -20
- package/dist/server/recordExposures.js +4 -2
- package/dist/server/runResults.js +97 -150
- package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
- package/dist/testSurface/actions/LifecycleAction.js +15 -5
- package/dist/testSurface/actions/actions.model.d.ts +13 -2
- package/dist/testSurface/actions/actions.model.js +38 -5
- package/dist/testSurface/api.d.ts +13 -1
- package/dist/testSurface/api.js +19 -0
- package/dist/testSurface/copy/actions.d.ts +13 -0
- package/dist/testSurface/copy/actions.js +13 -0
- package/dist/testSurface/copy/cohorts.d.ts +68 -0
- package/dist/testSurface/copy/cohorts.js +81 -0
- package/dist/testSurface/copy/common.d.ts +2 -3
- package/dist/testSurface/copy/common.js +4 -4
- package/dist/testSurface/copy/inputs.d.ts +3 -0
- package/dist/testSurface/copy/inputs.js +3 -0
- package/dist/testSurface/copy/readiness.d.ts +20 -6
- package/dist/testSurface/copy/readiness.js +42 -9
- package/dist/testSurface/copy/results.d.ts +1 -0
- package/dist/testSurface/copy/results.js +1 -0
- package/dist/testSurface/copy/schedule.d.ts +58 -0
- package/dist/testSurface/copy/schedule.js +150 -0
- package/dist/testSurface/copy/surface.d.ts +2 -0
- package/dist/testSurface/copy/surface.js +2 -0
- package/dist/testSurface/copy/testPage.d.ts +12 -2
- package/dist/testSurface/copy/testPage.js +17 -2
- package/dist/testSurface/format/roundProgress.d.ts +13 -1
- package/dist/testSurface/format/roundProgress.js +34 -5
- package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
- package/dist/testSurface/format/scheduleStatus.js +93 -0
- package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
- package/dist/testSurface/format/useScheduleClock.js +20 -0
- package/dist/testSurface/labels.d.ts +4 -9
- package/dist/testSurface/labels.js +2 -7
- package/dist/testSurface/lockedNotice.model.d.ts +2 -2
- package/dist/testSurface/lockedNotice.model.js +16 -3
- package/dist/testSurface/readPreflight.d.ts +3 -0
- package/dist/testSurface/readPreflight.js +14 -0
- package/dist/testSurface/readinessRead.d.ts +2 -2
- package/dist/testSurface/results/DataQualityPanel.js +7 -7
- package/dist/testSurface/results/results.model.d.ts +1 -1
- package/dist/testSurface/results/results.model.js +34 -6
- package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
- package/dist/testSurface/review/cohortEstimate.js +32 -0
- package/dist/testSurface/surface/contracts.d.ts +2 -1
- package/dist/testSurface/surface/contracts.js +1 -0
- package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
- package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
- package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
- package/dist/testSurface/surface/readiness/Banner.js +29 -11
- package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
- package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
- package/dist/testSurface/surface/readiness/useTransition.js +17 -5
- package/dist/testSurface/surface/results/ResultsBody.js +44 -8
- package/dist/testSurface/surface/results/useResults.d.ts +16 -1
- package/dist/testSurface/surface/results/useResults.js +17 -6
- package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
- package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
- package/dist/testSurface/surface/test/LengthSection.js +26 -6
- package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
- package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
- package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
- package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
- package/dist/testSurface/surface/test/Section.js +1 -1
- package/dist/testSurface/surface/test/TargetingSection.js +306 -182
- package/dist/testSurface/surface/test/TestSurface.js +9 -0
- package/dist/testSurface/surface/test/fields.d.ts +2 -1
- package/dist/testSurface/surface/test/fields.js +3 -3
- package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
- package/dist/testSurface/surface/test/jumpToSection.js +4 -4
- package/dist/testSurface/surface/test/testPage.css +26 -0
- package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
- package/dist/testSurface/surface/testDocument.model.js +2 -1
- package/dist/testSurface/surface/useTestDocument.js +11 -4
- package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
- package/dist/testSurface/targeting/targeting.model.js +1 -1
- package/dist/testSurface/useApi.d.ts +12 -0
- package/dist/transitions/addMetric.js +5 -2
- package/dist/transitions/allocate.js +6 -1
- package/dist/transitions/assertNoOverlap.d.ts +9 -0
- package/dist/transitions/assertNoOverlap.js +24 -0
- package/dist/transitions/buildCohorts.d.ts +10 -0
- package/dist/transitions/buildCohorts.js +68 -0
- package/dist/transitions/cancelSchedule.d.ts +4 -0
- package/dist/transitions/cancelSchedule.js +42 -0
- package/dist/transitions/checkStart.d.ts +17 -3
- package/dist/transitions/checkStart.js +20 -7
- package/dist/transitions/decide.js +40 -13
- package/dist/transitions/kernel.d.ts +3 -1
- package/dist/transitions/kernel.js +5 -2
- package/dist/transitions/pause.d.ts +4 -0
- package/dist/transitions/pause.js +35 -0
- package/dist/transitions/phaseRecord.d.ts +19 -2
- package/dist/transitions/phaseRecord.js +50 -11
- package/dist/transitions/placementInteractions.d.ts +7 -2
- package/dist/transitions/placementInteractions.js +9 -7
- package/dist/transitions/placements.d.ts +4 -3
- package/dist/transitions/placements.js +28 -14
- package/dist/transitions/preflightData.d.ts +11 -3
- package/dist/transitions/preflightData.js +134 -81
- package/dist/transitions/reschedule.d.ts +4 -0
- package/dist/transitions/reschedule.js +58 -0
- package/dist/transitions/resume.d.ts +4 -0
- package/dist/transitions/resume.js +32 -0
- package/dist/transitions/scheduledRound.d.ts +18 -0
- package/dist/transitions/scheduledRound.js +42 -0
- package/dist/transitions/start.d.ts +4 -0
- package/dist/transitions/start.js +139 -56
- package/dist/transitions/startReads.d.ts +14 -0
- package/dist/transitions/startReads.js +27 -0
- package/dist/transitions/stop.d.ts +10 -0
- package/dist/transitions/stop.js +35 -22
- package/dist/types/admin.d.ts +1 -1
- package/dist/types/contracts.d.ts +7 -1
- package/dist/types/endpoints.d.ts +72 -3
- package/dist/types/manifest.d.ts +9 -0
- package/dist/types/runtime.d.ts +5 -0
- package/dist/types/snapshot.d.ts +10 -0
- package/dist/types/status.d.ts +1 -0
- package/dist/types/status.js +1 -0
- package/dist/types/surface.d.ts +1 -0
- package/dist/ui/Feedback.d.ts +9 -6
- package/dist/ui/Feedback.js +10 -9
- package/dist/ui/SelectControl.js +1 -1
- package/dist/ui/ui.css +2 -1
- package/package.json +2 -2
|
@@ -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
|
+
}
|
package/dist/db/erase.d.ts
CHANGED
|
@@ -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
|
]);
|
package/dist/db/events.d.ts
CHANGED
|
@@ -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)){
|
package/dist/db/executor.d.ts
CHANGED
|
@@ -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;
|
package/dist/db/executor.js
CHANGED
|
@@ -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) {
|
package/dist/db/locks.d.ts
CHANGED
|
@@ -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
|
+
}
|
package/dist/db/names.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
/** SQL identifiers from the Payload 3.90.2 generated-schema fixture (2026-
|
|
1
|
+
/** SQL identifiers from the Payload 3.90.2 generated-schema fixture (2026-12-04).
|
|
2
2
|
* All main, array, relationship and version tables are included. Access through
|
|
3
3
|
* these literal keys is checked by TypeScript; names.test.ts checks fixture parity.
|
|
4
4
|
*/
|
|
5
5
|
export declare const TABLES: {
|
|
6
|
+
readonly experimentsTargetingArms: "xp_experiments_targeting_arms";
|
|
7
|
+
readonly experimentsVersionsVersionTargetingArms: "_xp_experiments_v_version_targeting_arms";
|
|
8
|
+
readonly experimentsScheduleWindows: "xp_experiments_schedule_windows";
|
|
9
|
+
readonly experimentsVersionsVersionScheduleWindows: "_xp_experiments_v_version_schedule_windows";
|
|
10
|
+
readonly cohortMembers: "xp_cohort_members";
|
|
11
|
+
readonly cohorts: "xp_cohorts";
|
|
6
12
|
readonly experimentsTargeting: "xp_experiments_targeting";
|
|
7
13
|
readonly experimentsArms: "xp_experiments_arms";
|
|
8
14
|
readonly experiments: "xp_experiments";
|
|
@@ -20,6 +26,56 @@ export declare const TABLES: {
|
|
|
20
26
|
readonly state: "xp_state";
|
|
21
27
|
};
|
|
22
28
|
export declare const COLUMNS: {
|
|
29
|
+
readonly cohorts: {
|
|
30
|
+
readonly id: "id";
|
|
31
|
+
readonly cohortKey: "cohort_key";
|
|
32
|
+
readonly rule: "rule";
|
|
33
|
+
readonly state: "state";
|
|
34
|
+
readonly closed: "closed";
|
|
35
|
+
readonly members: "members";
|
|
36
|
+
readonly builtAt: "built_at";
|
|
37
|
+
readonly updatedAt: "updated_at";
|
|
38
|
+
readonly createdAt: "created_at";
|
|
39
|
+
};
|
|
40
|
+
readonly cohortMembers: {
|
|
41
|
+
readonly id: "id";
|
|
42
|
+
readonly cohortKey: "cohort_key";
|
|
43
|
+
readonly unitId: "unit_id";
|
|
44
|
+
readonly builtAt: "built_at";
|
|
45
|
+
readonly enteredAt: "entered_at";
|
|
46
|
+
readonly exitedAt: "exited_at";
|
|
47
|
+
readonly updatedAt: "updated_at";
|
|
48
|
+
readonly createdAt: "created_at";
|
|
49
|
+
};
|
|
50
|
+
readonly experimentsVersionsVersionScheduleWindows: {
|
|
51
|
+
readonly _order: "_order";
|
|
52
|
+
readonly _parentId: "_parent_id";
|
|
53
|
+
readonly id: "id";
|
|
54
|
+
readonly days: "days";
|
|
55
|
+
readonly from: "from";
|
|
56
|
+
readonly to: "to";
|
|
57
|
+
readonly _uuid: "_uuid";
|
|
58
|
+
};
|
|
59
|
+
readonly experimentsScheduleWindows: {
|
|
60
|
+
readonly _order: "_order";
|
|
61
|
+
readonly _parentId: "_parent_id";
|
|
62
|
+
readonly id: "id";
|
|
63
|
+
readonly days: "days";
|
|
64
|
+
readonly from: "from";
|
|
65
|
+
readonly to: "to";
|
|
66
|
+
};
|
|
67
|
+
readonly experimentsVersionsVersionTargetingArms: {
|
|
68
|
+
readonly order: "order";
|
|
69
|
+
readonly parentId: "parent_id";
|
|
70
|
+
readonly value: "value";
|
|
71
|
+
readonly id: "id";
|
|
72
|
+
};
|
|
73
|
+
readonly experimentsTargetingArms: {
|
|
74
|
+
readonly order: "order";
|
|
75
|
+
readonly parentId: "parent_id";
|
|
76
|
+
readonly value: "value";
|
|
77
|
+
readonly id: "id";
|
|
78
|
+
};
|
|
23
79
|
readonly state: {
|
|
24
80
|
readonly id: "id";
|
|
25
81
|
readonly revision: "revision";
|
|
@@ -30,6 +86,12 @@ export declare const COLUMNS: {
|
|
|
30
86
|
readonly createdAt: "created_at";
|
|
31
87
|
};
|
|
32
88
|
readonly experimentsTargeting: {
|
|
89
|
+
readonly kind: "kind";
|
|
90
|
+
readonly sourceExperimentId: "source_experiment_id";
|
|
91
|
+
readonly sourcePhase: "source_phase";
|
|
92
|
+
readonly goalMetricId: "goal_metric_id";
|
|
93
|
+
readonly goalCompleted: "goal_completed";
|
|
94
|
+
readonly include: "include";
|
|
33
95
|
readonly _order: "_order";
|
|
34
96
|
readonly _parentId: "_parent_id";
|
|
35
97
|
readonly id: "id";
|
|
@@ -50,6 +112,12 @@ export declare const COLUMNS: {
|
|
|
50
112
|
readonly pageTarget: "page_target";
|
|
51
113
|
};
|
|
52
114
|
readonly experiments: {
|
|
115
|
+
readonly scheduleStartAt: "schedule_start_at";
|
|
116
|
+
readonly scheduleEndAt: "schedule_end_at";
|
|
117
|
+
readonly scheduleTimeZone: "schedule_time_zone";
|
|
118
|
+
readonly pausedAt: "paused_at";
|
|
119
|
+
readonly pausedBy: "paused_by";
|
|
120
|
+
readonly pauseReason: "pause_reason";
|
|
53
121
|
readonly id: "id";
|
|
54
122
|
readonly status: "status";
|
|
55
123
|
readonly name: "name";
|
|
@@ -77,6 +145,8 @@ export declare const COLUMNS: {
|
|
|
77
145
|
readonly stoppedAt: "stopped_at";
|
|
78
146
|
readonly decidedAt: "decided_at";
|
|
79
147
|
readonly archivedAt: "archived_at";
|
|
148
|
+
readonly claimFrom: "claim_from";
|
|
149
|
+
readonly claimTo: "claim_to";
|
|
80
150
|
readonly decisionWinnerArm: "decision_winner_arm";
|
|
81
151
|
readonly decisionVerdictCode: "decision_verdict_code";
|
|
82
152
|
readonly decisionNote: "decision_note";
|
|
@@ -98,6 +168,12 @@ export declare const COLUMNS: {
|
|
|
98
168
|
readonly xpMetricsId: "xp_metrics_id";
|
|
99
169
|
};
|
|
100
170
|
readonly experimentsVersionsVersionTargeting: {
|
|
171
|
+
readonly kind: "kind";
|
|
172
|
+
readonly sourceExperimentId: "source_experiment_id";
|
|
173
|
+
readonly sourcePhase: "source_phase";
|
|
174
|
+
readonly goalMetricId: "goal_metric_id";
|
|
175
|
+
readonly goalCompleted: "goal_completed";
|
|
176
|
+
readonly include: "include";
|
|
101
177
|
readonly _order: "_order";
|
|
102
178
|
readonly _parentId: "_parent_id";
|
|
103
179
|
readonly id: "id";
|
|
@@ -120,6 +196,12 @@ export declare const COLUMNS: {
|
|
|
120
196
|
readonly _uuid: "_uuid";
|
|
121
197
|
};
|
|
122
198
|
readonly experimentsVersions: {
|
|
199
|
+
readonly versionScheduleStartAt: "version_schedule_start_at";
|
|
200
|
+
readonly versionScheduleEndAt: "version_schedule_end_at";
|
|
201
|
+
readonly versionScheduleTimeZone: "version_schedule_time_zone";
|
|
202
|
+
readonly versionPausedAt: "version_paused_at";
|
|
203
|
+
readonly versionPausedBy: "version_paused_by";
|
|
204
|
+
readonly versionPauseReason: "version_pause_reason";
|
|
123
205
|
readonly id: "id";
|
|
124
206
|
readonly parentId: "parent_id";
|
|
125
207
|
readonly versionStatus: "version_status";
|
|
@@ -148,6 +230,8 @@ export declare const COLUMNS: {
|
|
|
148
230
|
readonly versionStoppedAt: "version_stopped_at";
|
|
149
231
|
readonly versionDecidedAt: "version_decided_at";
|
|
150
232
|
readonly versionArchivedAt: "version_archived_at";
|
|
233
|
+
readonly versionClaimFrom: "version_claim_from";
|
|
234
|
+
readonly versionClaimTo: "version_claim_to";
|
|
151
235
|
readonly versionDecisionWinnerArm: "version_decision_winner_arm";
|
|
152
236
|
readonly versionDecisionVerdictCode: "version_decision_verdict_code";
|
|
153
237
|
readonly versionDecisionNote: "version_decision_note";
|
|
@@ -171,6 +255,9 @@ export declare const COLUMNS: {
|
|
|
171
255
|
readonly xpMetricsId: "xp_metrics_id";
|
|
172
256
|
};
|
|
173
257
|
readonly phases: {
|
|
258
|
+
readonly pauses: "pauses";
|
|
259
|
+
readonly schedule: "schedule";
|
|
260
|
+
readonly scheduleChanges: "schedule_changes";
|
|
174
261
|
readonly id: "id";
|
|
175
262
|
readonly experimentId: "experiment_id";
|
|
176
263
|
readonly phase: "phase";
|
|
@@ -251,6 +338,13 @@ export declare const COLUMNS: {
|
|
|
251
338
|
};
|
|
252
339
|
};
|
|
253
340
|
export declare const ENUMS: {
|
|
341
|
+
readonly cohortsState: "enum_xp_cohorts_state";
|
|
342
|
+
readonly experimentsTargetingArms: "enum_xp_experiments_targeting_arms";
|
|
343
|
+
readonly experimentsTargetingKind: "enum_xp_experiments_targeting_kind";
|
|
344
|
+
readonly experimentsTargetingGoalCompleted: "enum_xp_experiments_targeting_goal_completed";
|
|
345
|
+
readonly experimentsVersionsVersionTargetingArms: "enum__xp_experiments_v_version_targeting_arms";
|
|
346
|
+
readonly experimentsVersionsVersionTargetingKind: "enum__xp_experiments_v_version_targeting_kind";
|
|
347
|
+
readonly experimentsVersionsVersionTargetingGoalCompleted: "enum__xp_experiments_v_version_targeting_goal_completed";
|
|
254
348
|
readonly experimentsTargetingOp: "enum_xp_experiments_targeting_op";
|
|
255
349
|
readonly experimentsArmsKey: "enum_xp_experiments_arms_key";
|
|
256
350
|
readonly experimentsArmsKind: "enum_xp_experiments_arms_kind";
|