Add metric baseline computation service
This commit is contained in:
1 parent
d18e36e962
commit
3ef86b0b66
3 files changed
+437
No files matched your search
@@ -0,0 +1,218 @@
|
||||
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
|
||||
import type { ConnectionService } from '../global/database/connection.service';
|
||||
import type { PlayerMatchFeature } from '../global/database/schemas';
|
||||
import { MetricBaselineService } from './metric-baseline.service';
|
||||
|
||||
interface ExecQuery<T> {
|
||||
exec: jest.Mock<Promise<T>, []>;
|
||||
}
|
||||
|
||||
type AcknowledgedUpdate = { acknowledged: boolean };
|
||||
type AggregateMock = jest.Mock<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>;
|
||||
type UpdateOneMock = jest.Mock<
|
||||
ExecQuery<AcknowledgedUpdate>,
|
||||
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
|
||||
>;
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function execResolved<T>(value: T): ExecQuery<T> {
|
||||
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
function createStoredFeature(
|
||||
overrides: Partial<PlayerMatchFeature> = {},
|
||||
): PlayerMatchFeature {
|
||||
return {
|
||||
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||
matchId: 'KR_1',
|
||||
puuid: 'seed-puuid',
|
||||
queueId: 420,
|
||||
role: 'MIDDLE',
|
||||
championId: 103,
|
||||
gameCreation: 1_700_000_000_000,
|
||||
gameDurationSec: 1_800,
|
||||
win: true,
|
||||
patch: '26.13',
|
||||
features: {
|
||||
csPerMin: 8,
|
||||
kda: 3,
|
||||
},
|
||||
normalized: {},
|
||||
vector: [],
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
normalizationMethod: 'registry-baseline',
|
||||
confidence: 1,
|
||||
timelineProcessed: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('MetricBaselineService', () => {
|
||||
it('computes p5-p95 breakpoints from seed raw feature values', async () => {
|
||||
const seedFeatures = [10, 20, 30, 40, 50].map((kda, index) =>
|
||||
createStoredFeature({
|
||||
matchId: `KR_${index + 1}`,
|
||||
features: {
|
||||
kda,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const aggregate: AggregateMock = jest
|
||||
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
|
||||
.mockReturnValue(execResolved(seedFeatures));
|
||||
const updateOne: UpdateOneMock = jest
|
||||
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||
const connectionService = {
|
||||
getModel: jest.fn((modelKey: string) =>
|
||||
Promise.resolve(
|
||||
modelKey === 'playerMatchFeature'
|
||||
? { aggregate }
|
||||
: {
|
||||
updateOne,
|
||||
},
|
||||
),
|
||||
),
|
||||
} as unknown as ConnectionService;
|
||||
const service = new MetricBaselineService(connectionService);
|
||||
const computedAt = new Date('2026-07-03T12:00:00.000Z');
|
||||
|
||||
const result = await service.computeMetricBaselines({
|
||||
cohort: 'MASTER_PLUS',
|
||||
computedAt,
|
||||
patch: 'ALL',
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
baselinesWritten: 1,
|
||||
cohort: 'MASTER_PLUS',
|
||||
computedAt,
|
||||
patch: 'ALL',
|
||||
samplesRead: 5,
|
||||
});
|
||||
const aggregatePipeline = aggregate.mock.calls[0]?.[0];
|
||||
expect(aggregatePipeline).toContainEqual({
|
||||
$match: {
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
role: {
|
||||
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(aggregatePipeline).toContainEqual({
|
||||
$lookup: {
|
||||
as: 'account',
|
||||
foreignField: 'puuid',
|
||||
from: 'account',
|
||||
localField: 'puuid',
|
||||
},
|
||||
});
|
||||
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||
const [, update, options] = updateOne.mock.calls[0];
|
||||
const updateSet = asRecord(asRecord(update).$set);
|
||||
expect(updateSet).toMatchObject({
|
||||
cohort: 'MASTER_PLUS',
|
||||
computedAt,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
metricId: 'kda',
|
||||
patch: 'ALL',
|
||||
role: 'MIDDLE',
|
||||
sampleCount: 5,
|
||||
});
|
||||
const breakpoints = updateSet.percentileBreakpoints;
|
||||
expect(Array.isArray(breakpoints)).toBe(true);
|
||||
const numericBreakpoints = (breakpoints as unknown[]).filter(
|
||||
(value): value is number => typeof value === 'number',
|
||||
);
|
||||
expect(numericBreakpoints).toHaveLength(19);
|
||||
expect(numericBreakpoints[0]).toBe(12);
|
||||
expect(numericBreakpoints[9]).toBe(30);
|
||||
expect(numericBreakpoints[18]).toBe(48);
|
||||
expect(options).toEqual({ upsert: true });
|
||||
});
|
||||
|
||||
it('groups baseline values by metric and role and skips unknown roles', async () => {
|
||||
const seedFeatures = [
|
||||
createStoredFeature({
|
||||
role: 'MIDDLE',
|
||||
features: {
|
||||
csPerMin: 8,
|
||||
kda: 3,
|
||||
},
|
||||
}),
|
||||
createStoredFeature({
|
||||
matchId: 'KR_2',
|
||||
role: 'MIDDLE',
|
||||
features: {
|
||||
csPerMin: 9,
|
||||
kda: 5,
|
||||
},
|
||||
}),
|
||||
createStoredFeature({
|
||||
matchId: 'KR_3',
|
||||
role: 'TOP',
|
||||
features: {
|
||||
kda: 2,
|
||||
},
|
||||
}),
|
||||
createStoredFeature({
|
||||
matchId: 'KR_4',
|
||||
role: 'UNKNOWN',
|
||||
features: {
|
||||
kda: 99,
|
||||
},
|
||||
}),
|
||||
];
|
||||
const aggregate: AggregateMock = jest
|
||||
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
|
||||
.mockReturnValue(execResolved(seedFeatures));
|
||||
const updateOne: UpdateOneMock = jest
|
||||
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||
const connectionService = {
|
||||
getModel: jest.fn((modelKey: string) =>
|
||||
Promise.resolve(
|
||||
modelKey === 'playerMatchFeature'
|
||||
? { aggregate }
|
||||
: {
|
||||
updateOne,
|
||||
},
|
||||
),
|
||||
),
|
||||
} as unknown as ConnectionService;
|
||||
const service = new MetricBaselineService(connectionService);
|
||||
|
||||
await service.computeMetricBaselines({
|
||||
cohort: 'MASTER_PLUS',
|
||||
patch: '26.13',
|
||||
});
|
||||
|
||||
const writtenBaselines = updateOne.mock.calls.map(([filter]) => filter);
|
||||
expect(writtenBaselines).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ metricId: 'kda', role: 'MIDDLE' }),
|
||||
expect.objectContaining({ metricId: 'csPerMin', role: 'MIDDLE' }),
|
||||
expect.objectContaining({ metricId: 'kda', role: 'TOP' }),
|
||||
]),
|
||||
);
|
||||
expect(writtenBaselines).not.toContainEqual(
|
||||
expect.objectContaining({ role: 'UNKNOWN' }),
|
||||
);
|
||||
expect(aggregate.mock.calls[0]?.[0]).toContainEqual({
|
||||
$match: {
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
patch: '26.13',
|
||||
role: {
|
||||
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user