Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

fix mismatch in data in chart and conversions table

Blue Moused5c769d25501
diff --git a/backend/apps/cloud/src/experiment/bayesian.ts b/backend/apps/cloud/src/experiment/bayesian.ts
index b935fa61f..733782bc9 100644
--- a/backend/apps/cloud/src/experiment/bayesian.ts
+++ b/backend/apps/cloud/src/experiment/bayesian.ts
@@ -11,6 +11,44 @@ export interface VariantData {
conversions: number
}
+type RandomFn = () => number
+
+/**
+ * Deterministic (seeded) PRNG: mulberry32
+ * Returns a function that generates numbers in [0, 1).
+ */
+function mulberry32(seed: number): RandomFn {
+ let a = seed >>> 0
+ return () => {
+ a |= 0
+ a = (a + 0x6d2b79f5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+function fnv1a32(input: string): number {
+ let hash = 0x811c9dc5
+ for (let i = 0; i < input.length; i++) {
+ hash ^= input.charCodeAt(i)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return hash >>> 0
+}
+
+function seedFromVariants(
+ variants: VariantData[],
+ simulations: number,
+): number {
+ const normalized = [...variants]
+ .sort((a, b) => a.key.localeCompare(b.key))
+ .map(v => `${v.key}:${v.exposures}:${v.conversions}`)
+ .join('|')
+ // Mix in simulations so changing it changes output deterministically.
+ return (fnv1a32(normalized) ^ (simulations >>> 0)) >>> 0
+}
+
/**
* Beta distribution sampling using the Box-Muller transform
* and the relationship between Beta and Gamma distributions.
@@ -19,7 +57,7 @@ export interface VariantData {
* X ~ Gamma(alpha, 1), Y ~ Gamma(beta, 1)
* Then X / (X + Y) ~ Beta(alpha, beta)
*/
-function sampleGamma(shape: number): number {
+function sampleGamma(shape: number, random: RandomFn): number {
// For shape >= 1, use Marsaglia and Tsang's method
if (shape >= 1) {
const d = shape - 1 / 3
@@ -31,14 +69,14 @@ function sampleGamma(shape: number): number {
do {
// Generate standard normal using Box-Muller
- const u1 = Math.random()
- const u2 = Math.random()
+ const u1 = Math.max(random(), Number.EPSILON)
+ const u2 = random()
x = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)
v = 1 + c * x
} while (v <= 0)
v = v * v * v
- const u = Math.random()
+ const u = random()
if (u < 1 - 0.0331 * x * x * x * x) {
return d * v
@@ -53,8 +91,8 @@ function sampleGamma(shape: number): number {
// For shape < 1, use the transformation:
// If X ~ Gamma(shape + 1, 1), then X * U^(1/shape) ~ Gamma(shape, 1)
// where U ~ Uniform(0, 1)
- const sample = sampleGamma(shape + 1)
- const u = Math.random()
+ const sample = sampleGamma(shape + 1, random)
+ const u = random()
return sample * Math.pow(u, 1 / shape)
}
@@ -65,9 +103,9 @@ function sampleGamma(shape: number): number {
* @param beta - Second shape parameter (failures + 1)
* @returns A sample from Beta(alpha, beta)
*/
-function sampleBeta(alpha: number, beta: number): number {
- const x = sampleGamma(alpha)
- const y = sampleGamma(beta)
+function sampleBeta(alpha: number, beta: number, random: RandomFn): number {
+ const x = sampleGamma(alpha, random)
+ const y = sampleGamma(beta, random)
return x / (x + y)
}
@@ -109,6 +147,10 @@ export function calculateBayesianProbabilities(
wins.set(v.key, 0)
}
+ // Use deterministic PRNG so the same input always produces the same output.
+ // This prevents slight "drift" between the table value and the last chart point.
+ const random = mulberry32(seedFromVariants(variants, simulations))
+
// Run Monte Carlo simulation
for (let i = 0; i < simulations; i++) {
let bestRate = -1
@@ -122,7 +164,7 @@ export function calculateBayesianProbabilities(
const beta = Math.max(1, variant.exposures - variant.conversions + 1)
// Sample from the Beta distribution
- const rate = sampleBeta(alpha, beta)
+ const rate = sampleBeta(alpha, beta, random)
if (rate > bestRate) {
bestRate = rate
@@ -166,8 +208,11 @@ export function calculateCredibleInterval(
// Use numerical approximation for Beta distribution quantiles
// Sample many times and find percentiles
const samples: number[] = []
+ const random = mulberry32(
+ seedFromVariants([{ key: 'v', exposures, conversions }], 10000),
+ )
for (let i = 0; i < 10000; i++) {
- samples.push(sampleBeta(alpha, beta))
+ samples.push(sampleBeta(alpha, beta, random))
}
samples.sort((a, b) => a - b)
@@ -204,10 +249,27 @@ export function calculateExpectedLift(
const testBeta = testExposures - testConversions + 1
let totalLift = 0
+ const random = mulberry32(
+ seedFromVariants(
+ [
+ {
+ key: 'c',
+ exposures: controlExposures,
+ conversions: controlConversions,
+ },
+ {
+ key: 't',
+ exposures: testExposures,
+ conversions: testConversions,
+ },
+ ],
+ simulations,
+ ),
+ )
for (let i = 0; i < simulations; i++) {
- const controlRate = sampleBeta(controlAlpha, controlBeta)
- const testRate = sampleBeta(testAlpha, testBeta)
+ const controlRate = sampleBeta(controlAlpha, controlBeta, random)
+ const testRate = sampleBeta(testAlpha, testBeta, random)
if (controlRate > 0) {
totalLift += (testRate - controlRate) / controlRate
diff --git a/backend/apps/cloud/src/experiment/experiment.controller.ts b/backend/apps/cloud/src/experiment/experiment.controller.ts
index aa4e388bc..4d5aace8d 100644
--- a/backend/apps/cloud/src/experiment/experiment.controller.ts
+++ b/backend/apps/cloud/src/experiment/experiment.controller.ts
@@ -1039,22 +1039,38 @@ export class ExperimentController {
safeTimezone,
)
- // Get date grouping columns for SQL
- const dateColumns = this.getTimeBucketDateColumns(timeBucket)
+ // Important: table results use overall uniqExact(profileId) counts per variant.
+ // For the time-series we must avoid "summing per-bucket uniques", because a profile
+ // can appear in multiple time buckets (re-exposed / repeated events). Instead we:
+ // - bucket exposures by the first exposure per (variantKey, profileId)
+ // - bucket conversions by the first conversion per (variantKey, profileId)
+ // This guarantees that the last chart point uses the same data as the table.
+ const dateColumnsGroupBy = this.getTimeBucketDateColumnsGroupBy(timeBucket)
+ const exposuresDateColumnsSelect = this.getTimeBucketDateColumnsSelect(
+ timeBucket,
+ 'firstCreated',
+ )
- // Query exposures grouped by time bucket and variant
+ // Query exposures grouped by time bucket and variant (first exposure per profile)
const exposuresQuery = `
SELECT
- ${dateColumns},
+ ${exposuresDateColumnsSelect},
variantKey,
- uniqExact(profileId) as exposures
- FROM experiment_exposures
- WHERE
- pid = {pid:FixedString(12)}
- AND experimentId = {experimentId:String}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
- GROUP BY ${dateColumns}, variantKey
- ORDER BY ${dateColumns}
+ count() as exposures
+ FROM (
+ SELECT
+ variantKey,
+ profileId,
+ min(created) as firstCreated
+ FROM experiment_exposures
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND experimentId = {experimentId:String}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY variantKey, profileId
+ )
+ GROUP BY ${dateColumnsGroupBy}, variantKey
+ ORDER BY ${dateColumnsGroupBy}
`
const queryParams = {
@@ -1082,6 +1098,10 @@ export class ExperimentController {
const table = goalType === 'custom_event' ? 'customEV' : 'analytics'
const matchColumn = goalType === 'custom_event' ? 'ev' : 'pg'
const goalValue = experiment.goal.value || ''
+ const conversionsDateColumnsSelect = this.getTimeBucketDateColumnsSelect(
+ timeBucket,
+ 'firstConversion',
+ )
// Build match condition based on goal match type
let matchCondition = ''
@@ -1111,20 +1131,29 @@ export class ExperimentController {
const conversionsQuery = `
SELECT
- ${this.getTimeBucketDateColumnsForJoin(timeBucket, 'e')},
- e.variantKey,
- uniqExact(e.profileId) as conversions
- FROM experiment_exposures e
- INNER JOIN ${table} c ON e.pid = c.pid AND e.profileId = assumeNotNull(c.profileId)
- WHERE
- e.pid = {pid:FixedString(12)}
- AND e.experimentId = {experimentId:String}
- AND e.created BETWEEN {groupFrom:String} AND {groupTo:String}
- AND c.created >= e.created
- AND ${matchCondition}
- ${metaCondition}
- GROUP BY ${this.getTimeBucketDateColumnsForJoin(timeBucket, 'e')}, e.variantKey
- ORDER BY ${this.getTimeBucketDateColumnsForJoin(timeBucket, 'e')}
+ ${conversionsDateColumnsSelect},
+ variantKey,
+ count() as conversions
+ FROM (
+ SELECT
+ e.variantKey as variantKey,
+ e.profileId as profileId,
+ min(c.created) as firstConversion
+ FROM experiment_exposures e
+ INNER JOIN ${table} c ON e.pid = c.pid AND e.profileId = assumeNotNull(c.profileId)
+ WHERE
+ e.pid = {pid:FixedString(12)}
+ AND e.experimentId = {experimentId:String}
+ AND e.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND c.profileId IS NOT NULL
+ AND c.created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND c.created >= e.created
+ AND ${matchCondition}
+ ${metaCondition}
+ GROUP BY e.variantKey, e.profileId
+ )
+ GROUP BY ${dateColumnsGroupBy}, variantKey
+ ORDER BY ${dateColumnsGroupBy}
`
try {
@@ -1158,28 +1187,45 @@ export class ExperimentController {
cumulativeConversions[key] = 0
}
+ // Index bucket deltas for O(buckets * variants) processing
+ const exposuresByBucket: Record<string, Record<string, number>> = {}
+ for (const row of exposuresData) {
+ const rowDate = this.generateDateStringFromRow(row, timeBucket)
+ const key = row.variantKey
+ if (!rowDate || !key) continue
+ exposuresByBucket[rowDate] ||= {}
+ exposuresByBucket[rowDate][key] = Number(row.exposures) || 0
+ }
+
+ const conversionsByBucket: Record<string, Record<string, number>> = {}
+ for (const row of conversionsData) {
+ const rowDate = this.generateDateStringFromRow(row, timeBucket)
+ const key = row.variantKey
+ if (!rowDate || !key) continue
+ conversionsByBucket[rowDate] ||= {}
+ conversionsByBucket[rowDate][key] = Number(row.conversions) || 0
+ }
+
// Process each time bucket
for (let i = 0; i < xShifted.length; i++) {
const bucketDate = xShifted[i]
// Add exposures for this bucket
- for (const row of exposuresData) {
- const rowDate = this.generateDateStringFromRow(row, timeBucket)
- if (rowDate === bucketDate) {
- const key = row.variantKey
- if (variantKeys.includes(key)) {
- cumulativeExposures[key] += Number(row.exposures) || 0
+ const exposuresDelta = exposuresByBucket[bucketDate]
+ if (exposuresDelta) {
+ for (const [key, value] of Object.entries(exposuresDelta)) {
+ if (typeof cumulativeExposures[key] === 'number') {
+ cumulativeExposures[key] += value
}
}
}
// Add conversions for this bucket
- for (const row of conversionsData) {
- const rowDate = this.generateDateStringFromRow(row, timeBucket)
- if (rowDate === bucketDate) {
- const key = row.variantKey
- if (variantKeys.includes(key)) {
- cumulativeConversions[key] += Number(row.conversions) || 0
+ const conversionsDelta = conversionsByBucket[bucketDate]
+ if (conversionsDelta) {
+ for (const [key, value] of Object.entries(conversionsDelta)) {
+ if (typeof cumulativeConversions[key] === 'number') {
+ cumulativeConversions[key] += value
}
}
}
@@ -1208,43 +1254,40 @@ export class ExperimentController {
/**
* Get SQL date columns for time bucket grouping
*/
- private getTimeBucketDateColumns(timeBucket: string): string {
+ private getTimeBucketDateColumnsSelect(
+ timeBucket: string,
+ dateExpr: string,
+ ): string {
switch (timeBucket) {
case 'minute':
- return 'toYear(created) as year, toMonth(created) as month, toDayOfMonth(created) as day, toHour(created) as hour, toMinute(created) as minute'
+ return `toYear(${dateExpr}, {timezone:String}) as year, toMonth(${dateExpr}, {timezone:String}) as month, toDayOfMonth(${dateExpr}, {timezone:String}) as day, toHour(${dateExpr}, {timezone:String}) as hour, toMinute(${dateExpr}, {timezone:String}) as minute`
case 'hour':
- return 'toYear(created) as year, toMonth(created) as month, toDayOfMonth(created) as day, toHour(created) as hour'
+ return `toYear(${dateExpr}, {timezone:String}) as year, toMonth(${dateExpr}, {timezone:String}) as month, toDayOfMonth(${dateExpr}, {timezone:String}) as day, toHour(${dateExpr}, {timezone:String}) as hour`
case 'day':
- return 'toYear(created) as year, toMonth(created) as month, toDayOfMonth(created) as day'
+ return `toYear(${dateExpr}, {timezone:String}) as year, toMonth(${dateExpr}, {timezone:String}) as month, toDayOfMonth(${dateExpr}, {timezone:String}) as day`
case 'month':
- return 'toYear(created) as year, toMonth(created) as month'
+ return `toYear(${dateExpr}, {timezone:String}) as year, toMonth(${dateExpr}, {timezone:String}) as month`
case 'year':
- return 'toYear(created) as year'
+ return `toYear(${dateExpr}, {timezone:String}) as year`
default:
- return 'toYear(created) as year, toMonth(created) as month, toDayOfMonth(created) as day'
+ return `toYear(${dateExpr}, {timezone:String}) as year, toMonth(${dateExpr}, {timezone:String}) as month, toDayOfMonth(${dateExpr}, {timezone:String}) as day`
}
}
- /**
- * Get SQL date columns for time bucket grouping with table alias
- */
- private getTimeBucketDateColumnsForJoin(
- timeBucket: string,
- alias: string,
- ): string {
+ private getTimeBucketDateColumnsGroupBy(timeBucket: string): string {
switch (timeBucket) {
case 'minute':
- return `toYear(${alias}.created) as year, toMonth(${alias}.created) as month, toDayOfMonth(${alias}.created) as day, toHour(${alias}.created) as hour, toMinute(${alias}.created) as minute`
+ return 'year, month, day, hour, minute'
case 'hour':
- return `toYear(${alias}.created) as year, toMonth(${alias}.created) as month, toDayOfMonth(${alias}.created) as day, toHour(${alias}.created) as hour`
+ return 'year, month, day, hour'
case 'day':
- return `toYear(${alias}.created) as year, toMonth(${alias}.created) as month, toDayOfMonth(${alias}.created) as day`
+ return 'year, month, day'
case 'month':
- return `toYear(${alias}.created) as year, toMonth(${alias}.created) as month`
+ return 'year, month'
case 'year':
- return `toYear(${alias}.created) as year`
+ return 'year'
default:
- return `toYear(${alias}.created) as year, toMonth(${alias}.created) as month, toDayOfMonth(${alias}.created) as day`
+ return 'year, month, day'
}
}