1414 lines
43 KiB
TypeScript
1414 lines
43 KiB
TypeScript
import { Logger } from '@nestjs/common';
|
|
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
|
|
import type { ConnectionService } from '../global/database/connection.service';
|
|
import type {
|
|
Account,
|
|
PlayerMatchFeature,
|
|
RiotMatch,
|
|
} from '../global/database/schemas';
|
|
import { RiotNotFoundError, type RiotApiClient } from '../riot/riot-api.client';
|
|
import type { MetricBaselineService } from './metric-baseline.service';
|
|
import type { MetricNormalizationService } from './metric-normalization.service';
|
|
import type {
|
|
BaselineComputationJobData,
|
|
ExtractedPlayerMatchFeature,
|
|
FeatureRecomputeJobData,
|
|
UserAnalysisJobData,
|
|
} from './analysis.types';
|
|
import {
|
|
BASELINE_COMPUTATION_JOB_NAME,
|
|
FEATURE_RECOMPUTE_JOB_NAME,
|
|
} from './analysis.constants';
|
|
import { FeatureExtractorService } from './feature-extractor.service';
|
|
import { AnalysisPipelineService } from './analysis-pipeline.service';
|
|
import { ProfileBuilderService } from './profile-builder.service';
|
|
import { TimelineDerivedService } from './timeline-derived.service';
|
|
import { TimelineMetricService } from './timeline-metric.service';
|
|
|
|
function createJobData(): UserAnalysisJobData {
|
|
return {
|
|
gameName: 'Hide on bush',
|
|
tagLine: 'KR1',
|
|
platformRoute: 'kr',
|
|
regionalRoute: 'asia',
|
|
queueId: 420,
|
|
requestedMatchCount: 20,
|
|
};
|
|
}
|
|
|
|
function createMatchPayload(matchId = 'KR_1') {
|
|
return {
|
|
metadata: {
|
|
matchId,
|
|
participants: ['target-puuid', 'ally-puuid'],
|
|
},
|
|
info: {
|
|
gameCreation: 1_700_000_000_000,
|
|
gameDuration: 1800,
|
|
gameVersion: '26.13.123.456',
|
|
queueId: 420,
|
|
participants: [
|
|
{
|
|
participantId: 1,
|
|
puuid: 'target-puuid',
|
|
teamId: 100,
|
|
teamPosition: 'MIDDLE',
|
|
championId: 103,
|
|
kills: 6,
|
|
deaths: 2,
|
|
assists: 8,
|
|
totalDamageDealtToChampions: 24_000,
|
|
goldEarned: 12_000,
|
|
totalMinionsKilled: 210,
|
|
neutralMinionsKilled: 12,
|
|
visionScore: 24,
|
|
wardsKilled: 4,
|
|
detectorWardsPlaced: 3,
|
|
win: true,
|
|
challenges: {
|
|
kda: 7,
|
|
killParticipation: 0.7,
|
|
teamDamagePercentage: 0.32,
|
|
damagePerMinute: 800,
|
|
goldPerMinute: 400,
|
|
visionScorePerMinute: 0.8,
|
|
controlWardsPlaced: 3,
|
|
soloKills: 2,
|
|
},
|
|
},
|
|
{
|
|
participantId: 2,
|
|
puuid: 'ally-puuid',
|
|
teamId: 100,
|
|
teamPosition: 'JUNGLE',
|
|
championId: 64,
|
|
kills: 10,
|
|
totalDamageDealtToChampions: 30_000,
|
|
},
|
|
{
|
|
participantId: 6,
|
|
puuid: 'enemy-puuid',
|
|
teamId: 200,
|
|
teamPosition: 'MIDDLE',
|
|
championId: 134,
|
|
kills: 4,
|
|
totalDamageDealtToChampions: 16_000,
|
|
},
|
|
],
|
|
},
|
|
};
|
|
}
|
|
|
|
function createTimelinePayload(
|
|
matchId = 'KR_1',
|
|
events: Record<string, unknown>[] = [],
|
|
) {
|
|
return {
|
|
metadata: {
|
|
matchId,
|
|
participants: ['target-puuid', 'ally-puuid'],
|
|
},
|
|
info: {
|
|
frameInterval: 60_000,
|
|
frames: [{ timestamp: 0, events, participantFrames: {} }],
|
|
},
|
|
};
|
|
}
|
|
|
|
function createTimelinePayloadWithFrames(
|
|
matchId = 'KR_1',
|
|
frames: Array<{
|
|
timestamp?: number;
|
|
events?: Record<string, unknown>[];
|
|
participantFrames?: Record<string, unknown>;
|
|
}> = [],
|
|
) {
|
|
return {
|
|
metadata: {
|
|
matchId,
|
|
participants: ['target-puuid', 'ally-puuid'],
|
|
},
|
|
info: {
|
|
frameInterval: 60_000,
|
|
frames: frames.map((frame, index) => ({
|
|
timestamp: frame.timestamp ?? index * 60_000,
|
|
events: frame.events ?? [],
|
|
participantFrames: frame.participantFrames ?? {},
|
|
})),
|
|
},
|
|
};
|
|
}
|
|
|
|
interface ExecQuery<T> {
|
|
exec: jest.Mock<Promise<T>, []>;
|
|
}
|
|
|
|
type AcknowledgedUpdate = { acknowledged: boolean };
|
|
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 findTimelineSet(updateRiotMatch: UpdateOneMock) {
|
|
const timelineUpdate = updateRiotMatch.mock.calls.find(([, update]) =>
|
|
Boolean(asRecord(asRecord(update).$set).timeline),
|
|
);
|
|
expect(timelineUpdate).toBeDefined();
|
|
return asRecord(asRecord(timelineUpdate?.[1]).$set);
|
|
}
|
|
|
|
function execResolved<T>(value: T): ExecQuery<T> {
|
|
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
|
|
}
|
|
|
|
function leanExecResolved<T>(value: T) {
|
|
return {
|
|
lean: jest.fn(() => execResolved(value)),
|
|
};
|
|
}
|
|
|
|
function findManyChain<T>(value: T) {
|
|
const exec = jest.fn<Promise<T>, []>().mockResolvedValue(value);
|
|
const lean = jest.fn(() => ({ exec }));
|
|
const limit = jest.fn(() => ({ lean }));
|
|
const sort = jest.fn(() => ({ limit }));
|
|
return {
|
|
chain: { sort },
|
|
exec,
|
|
lean,
|
|
limit,
|
|
sort,
|
|
};
|
|
}
|
|
|
|
function createStoredAccount(overrides: Partial<Account> = {}): Account {
|
|
return {
|
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
|
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
|
puuid: 'target-puuid',
|
|
gameName: 'Hide on bush',
|
|
tagLine: 'KR1',
|
|
platformRoute: 'kr',
|
|
regionalRoute: 'asia',
|
|
profileIconId: 1,
|
|
summonerLevel: 500,
|
|
tiers: [],
|
|
isSeed: false,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
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: 'target-puuid',
|
|
queueId: 420,
|
|
role: 'MIDDLE',
|
|
championId: 103,
|
|
gameCreation: 1_700_000_000_000,
|
|
gameDurationSec: 1_800,
|
|
win: true,
|
|
patch: '26.13',
|
|
features: { kda: 7 },
|
|
normalized: { kda: 1 },
|
|
vector: [],
|
|
featureSchemaVersion: 1,
|
|
normalizationMethod: 'registry-baseline',
|
|
confidence: 1,
|
|
timelineProcessed: false,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function createFeatureRecomputeJobData(
|
|
overrides: Partial<FeatureRecomputeJobData> = {},
|
|
): FeatureRecomputeJobData {
|
|
return {
|
|
platformRoute: 'kr',
|
|
queueId: 420,
|
|
batchSize: 100,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function createBaselineComputationJobData(
|
|
overrides: Partial<BaselineComputationJobData> = {},
|
|
): BaselineComputationJobData {
|
|
return {
|
|
platformRoute: 'kr',
|
|
queueId: 420,
|
|
cohort: 'MASTER_PLUS',
|
|
patch: 'ALL',
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function suppressLoggerError() {
|
|
return jest
|
|
.spyOn(Logger.prototype, 'error')
|
|
.mockImplementation(() => undefined);
|
|
}
|
|
|
|
interface PipelineHarnessOptions {
|
|
accountError?: Error;
|
|
computeMetricBaselines?: jest.Mock;
|
|
existingMatchRaw?: Record<string, unknown> | null;
|
|
existingTimeline?: Record<string, unknown>;
|
|
findOneAccountResult?: Account | null;
|
|
getMatch?: jest.Mock<Promise<Record<string, unknown>>, [string, string]>;
|
|
getMatchTimeline?: jest.Mock<
|
|
Promise<Record<string, unknown>>,
|
|
[string, string]
|
|
>;
|
|
matchIds?: string[];
|
|
normalizeFeature?: jest.Mock;
|
|
storedAccount?: Account;
|
|
}
|
|
|
|
function createPipelineHarness(options: PipelineHarnessOptions = {}) {
|
|
const updateAnalysisJob: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const findOneAndUpdateAccount = jest
|
|
.fn()
|
|
.mockReturnValue(
|
|
leanExecResolved(options.storedAccount ?? createStoredAccount()),
|
|
);
|
|
const updateAccount: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const findOneAccount = jest
|
|
.fn()
|
|
.mockReturnValue(
|
|
leanExecResolved(
|
|
options.findOneAccountResult === undefined
|
|
? (options.storedAccount ?? createStoredAccount())
|
|
: options.findOneAccountResult,
|
|
),
|
|
);
|
|
const findOneRiotMatch = jest.fn().mockReturnValue(
|
|
leanExecResolved(
|
|
options.existingMatchRaw
|
|
? {
|
|
raw: options.existingMatchRaw,
|
|
timeline: options.existingTimeline,
|
|
}
|
|
: null,
|
|
),
|
|
);
|
|
const updateRiotMatch: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updatePlayerMatchFeature: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updatePlayerProfile: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
|
|
const models = {
|
|
account: {
|
|
findOne: findOneAccount,
|
|
findOneAndUpdate: findOneAndUpdateAccount,
|
|
updateOne: updateAccount,
|
|
},
|
|
analysisJob: {
|
|
updateOne: updateAnalysisJob,
|
|
},
|
|
playerMatchFeature: {
|
|
updateOne: updatePlayerMatchFeature,
|
|
},
|
|
playerProfile: {
|
|
updateOne: updatePlayerProfile,
|
|
},
|
|
riotMatch: {
|
|
findOne: findOneRiotMatch,
|
|
updateOne: updateRiotMatch,
|
|
},
|
|
};
|
|
const connectionService = {
|
|
getModel: jest.fn((modelKey: keyof typeof models) =>
|
|
Promise.resolve(models[modelKey]),
|
|
),
|
|
} as unknown as ConnectionService;
|
|
const getAccountByRiotId = options.accountError
|
|
? jest.fn().mockRejectedValue(options.accountError)
|
|
: jest.fn().mockResolvedValue({
|
|
puuid: 'target-puuid',
|
|
gameName: 'Hide on bush',
|
|
tagLine: 'KR1',
|
|
});
|
|
const getMatch =
|
|
options.getMatch ??
|
|
jest
|
|
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
|
.mockResolvedValue(createMatchPayload());
|
|
const getMatchTimeline =
|
|
options.getMatchTimeline ??
|
|
jest
|
|
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
|
.mockResolvedValue(createTimelinePayload());
|
|
const getMatchIds = jest
|
|
.fn<Promise<string[]>, [string, Record<string, unknown>]>()
|
|
.mockResolvedValue(options.matchIds ?? ['KR_1']);
|
|
const computeMetricBaselines =
|
|
options.computeMetricBaselines ??
|
|
jest.fn().mockResolvedValue({
|
|
baselinesWritten: 3,
|
|
cohort: 'MASTER_PLUS',
|
|
computedAt: new Date('2026-07-03T12:00:00.000Z'),
|
|
patch: 'ALL',
|
|
samplesRead: 30,
|
|
});
|
|
const normalizeFeature =
|
|
options.normalizeFeature ?? jest.fn((feature) => Promise.resolve(feature));
|
|
const riotApiClient = {
|
|
getAccountByRiotId,
|
|
getSummonerByPuuid: jest.fn().mockResolvedValue({
|
|
puuid: 'target-puuid',
|
|
profileIconId: 1,
|
|
summonerLevel: 500,
|
|
}),
|
|
getLeagueEntriesByPuuid: jest.fn().mockResolvedValue([]),
|
|
getMatchIds,
|
|
getMatch,
|
|
getMatchTimeline,
|
|
} as unknown as RiotApiClient;
|
|
|
|
return {
|
|
findOneAccount,
|
|
findOneRiotMatch,
|
|
computeMetricBaselines,
|
|
getMatchIds,
|
|
getMatch,
|
|
getMatchTimeline,
|
|
normalizeFeature,
|
|
service: new AnalysisPipelineService(
|
|
connectionService,
|
|
riotApiClient,
|
|
new FeatureExtractorService(),
|
|
new ProfileBuilderService(),
|
|
new TimelineDerivedService(),
|
|
new TimelineMetricService(),
|
|
{
|
|
computeMetricBaselines,
|
|
} as unknown as MetricBaselineService,
|
|
{
|
|
normalizeFeature,
|
|
} as unknown as MetricNormalizationService,
|
|
),
|
|
updateAnalysisJob,
|
|
updatePlayerMatchFeature,
|
|
updatePlayerProfile,
|
|
updateRiotMatch,
|
|
};
|
|
}
|
|
|
|
interface FeatureRecomputeHarnessOptions {
|
|
account?: Account | null;
|
|
profileFeatures?: PlayerMatchFeature[];
|
|
remainingTargets?: PlayerMatchFeature[];
|
|
scanError?: Error;
|
|
storedMatch?: Pick<RiotMatch, 'raw' | 'timeline'> | null;
|
|
targetFeatures?: PlayerMatchFeature[];
|
|
}
|
|
|
|
function createFeatureRecomputeHarness(
|
|
options: FeatureRecomputeHarnessOptions = {},
|
|
) {
|
|
const scanChain = findManyChain(
|
|
options.targetFeatures ?? [createStoredFeature()],
|
|
);
|
|
if (options.scanError) {
|
|
scanChain.exec.mockRejectedValueOnce(options.scanError);
|
|
}
|
|
const remainingTargetsChain = findManyChain(options.remainingTargets ?? []);
|
|
const profileFeaturesChain = findManyChain(
|
|
options.profileFeatures ?? [
|
|
createStoredFeature({
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
timelineProcessed: true,
|
|
}),
|
|
],
|
|
);
|
|
const findPlayerMatchFeatures = jest
|
|
.fn()
|
|
.mockReturnValueOnce(scanChain.chain)
|
|
.mockReturnValueOnce(remainingTargetsChain.chain)
|
|
.mockReturnValueOnce(profileFeaturesChain.chain);
|
|
const updatePlayerMatchFeature: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updatePlayerProfile: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updateAnalysisJob: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updateAccount: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const findOneAccount = jest
|
|
.fn()
|
|
.mockReturnValue(
|
|
leanExecResolved(
|
|
options.account === undefined ? createStoredAccount() : options.account,
|
|
),
|
|
);
|
|
const storedMatch =
|
|
options.storedMatch === undefined
|
|
? {
|
|
raw: createMatchPayload(),
|
|
timeline: createTimelinePayload(),
|
|
}
|
|
: options.storedMatch;
|
|
const findOneRiotMatch = jest
|
|
.fn()
|
|
.mockReturnValue(leanExecResolved(storedMatch));
|
|
const models = {
|
|
account: {
|
|
findOne: findOneAccount,
|
|
updateOne: updateAccount,
|
|
},
|
|
analysisJob: {
|
|
updateOne: updateAnalysisJob,
|
|
},
|
|
playerMatchFeature: {
|
|
find: findPlayerMatchFeatures,
|
|
updateOne: updatePlayerMatchFeature,
|
|
},
|
|
playerProfile: {
|
|
updateOne: updatePlayerProfile,
|
|
},
|
|
riotMatch: {
|
|
findOne: findOneRiotMatch,
|
|
},
|
|
};
|
|
const connectionService = {
|
|
getModel: jest.fn((modelKey: keyof typeof models) =>
|
|
Promise.resolve(models[modelKey]),
|
|
),
|
|
} as unknown as ConnectionService;
|
|
|
|
return {
|
|
findOneAccount,
|
|
findOneRiotMatch,
|
|
findPlayerMatchFeatures,
|
|
profileFeaturesChain,
|
|
remainingTargetsChain,
|
|
scanChain,
|
|
service: new AnalysisPipelineService(
|
|
connectionService,
|
|
{} as RiotApiClient,
|
|
new FeatureExtractorService(),
|
|
new ProfileBuilderService(),
|
|
new TimelineDerivedService(),
|
|
new TimelineMetricService(),
|
|
),
|
|
updateAnalysisJob,
|
|
updatePlayerMatchFeature,
|
|
updatePlayerProfile,
|
|
};
|
|
}
|
|
|
|
describe('AnalysisPipelineService', () => {
|
|
it('fetches missing match details, stores features, builds a profile, and completes the job', async () => {
|
|
const {
|
|
findOneRiotMatch,
|
|
getMatch,
|
|
getMatchTimeline,
|
|
service,
|
|
updateAnalysisJob,
|
|
updatePlayerMatchFeature,
|
|
updatePlayerProfile,
|
|
updateRiotMatch,
|
|
} = createPipelineHarness();
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(findOneRiotMatch).toHaveBeenCalledWith({ matchId: 'KR_1' });
|
|
expect(getMatch).toHaveBeenCalledWith('KR_1', 'asia');
|
|
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
|
|
|
|
const riotMatchUpdate = updateRiotMatch.mock.calls[0][1];
|
|
expect(riotMatchUpdate).toMatchObject({
|
|
$setOnInsert: {
|
|
matchId: 'KR_1',
|
|
queueId: 420,
|
|
},
|
|
});
|
|
const timelineSet = findTimelineSet(updateRiotMatch);
|
|
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
|
expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date);
|
|
|
|
const playerMatchFeatureUpdate = updatePlayerMatchFeature.mock.calls[0][1];
|
|
expect(playerMatchFeatureUpdate).toMatchObject({
|
|
$set: {
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
matchId: 'KR_1',
|
|
},
|
|
});
|
|
|
|
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
|
expect(playerProfileUpdate).toMatchObject({
|
|
$set: {
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
puuid: 'target-puuid',
|
|
sampleGameCount: 1,
|
|
},
|
|
});
|
|
|
|
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
|
|
);
|
|
expect(completedJobUpdate).toBeDefined();
|
|
expect(asRecord(asRecord(completedJobUpdate?.[1]).$set)).toMatchObject({
|
|
status: 'completed',
|
|
stage: 'completed',
|
|
});
|
|
});
|
|
|
|
it('processes a stored seed account through the shared match feature pipeline', async () => {
|
|
const {
|
|
findOneAccount,
|
|
getMatchIds,
|
|
service,
|
|
updateAnalysisJob,
|
|
updatePlayerMatchFeature,
|
|
updatePlayerProfile,
|
|
} = createPipelineHarness({
|
|
findOneAccountResult: createStoredAccount({
|
|
isSeed: true,
|
|
puuid: 'target-puuid',
|
|
}),
|
|
});
|
|
|
|
const result = await service.processSeedAccountPipeline(
|
|
{
|
|
puuid: 'target-puuid',
|
|
platformRoute: 'kr',
|
|
regionalRoute: 'asia',
|
|
queueId: 420,
|
|
requestedMatchCount: 30,
|
|
},
|
|
'seed-job-1',
|
|
);
|
|
|
|
expect(result).toEqual({
|
|
puuid: 'target-puuid',
|
|
fetchedMatches: 1,
|
|
extractedFeatures: 1,
|
|
profileBuilt: true,
|
|
});
|
|
expect(findOneAccount).toHaveBeenCalledWith({
|
|
puuid: 'target-puuid',
|
|
isSeed: true,
|
|
});
|
|
expect(getMatchIds).toHaveBeenCalledWith('target-puuid', {
|
|
count: 30,
|
|
queue: 420,
|
|
regionalRoute: 'asia',
|
|
});
|
|
expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
|
|
|
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
|
expect(playerProfileUpdate).toMatchObject({
|
|
$set: {
|
|
isSeed: true,
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
sampleGameCount: 1,
|
|
},
|
|
});
|
|
const seedStageUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) =>
|
|
asRecord(asRecord(update).$set).jobType === 'seed-collection' &&
|
|
asRecord(asRecord(update).$set).stage === 'extract-features',
|
|
);
|
|
expect(seedStageUpdate).toBeDefined();
|
|
});
|
|
|
|
it('stores population-percentile normalized features and profiles when baselines are available', async () => {
|
|
const normalizeFeature = jest.fn((feature: ExtractedPlayerMatchFeature) =>
|
|
Promise.resolve({
|
|
...feature,
|
|
normalized: {
|
|
...feature.normalized,
|
|
kda: 0.42,
|
|
},
|
|
normalizationMethod: 'population-percentile',
|
|
}),
|
|
);
|
|
const { service, updatePlayerMatchFeature, updatePlayerProfile } =
|
|
createPipelineHarness({
|
|
normalizeFeature,
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(normalizeFeature).toHaveBeenCalledTimes(1);
|
|
const featureSet = asRecord(
|
|
asRecord(updatePlayerMatchFeature.mock.calls[0]?.[1]).$set,
|
|
);
|
|
expect(asRecord(featureSet.normalized).kda).toBe(0.42);
|
|
expect(featureSet.normalizationMethod).toBe('population-percentile');
|
|
|
|
const profileSet = asRecord(
|
|
asRecord(updatePlayerProfile.mock.calls[0]?.[1]).$set,
|
|
);
|
|
expect(profileSet.normalizationMethod).toBe('population-percentile');
|
|
});
|
|
|
|
it('denormalizes ranked solo tier fields when storing player profiles', async () => {
|
|
const { service, updatePlayerProfile } = createPipelineHarness({
|
|
storedAccount: createStoredAccount({
|
|
tiers: [
|
|
{
|
|
fetchedAt: new Date('2026-07-03T00:00:00.000Z'),
|
|
leaguePoints: 987,
|
|
losses: 10,
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
rank: '',
|
|
tier: 'CHALLENGER',
|
|
wins: 20,
|
|
},
|
|
],
|
|
}),
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
const profileSet = asRecord(
|
|
asRecord(updatePlayerProfile.mock.calls[0]?.[1]).$set,
|
|
);
|
|
expect(profileSet).toMatchObject({
|
|
isSeed: false,
|
|
tier: 'CHALLENGER',
|
|
division: '',
|
|
leaguePoints: 987,
|
|
});
|
|
});
|
|
|
|
it('skips seed pipeline processing when the seed account is missing', async () => {
|
|
const { findOneAccount, getMatchIds, service, updatePlayerProfile } =
|
|
createPipelineHarness({
|
|
findOneAccountResult: null,
|
|
});
|
|
|
|
const result = await service.processSeedAccountPipeline(
|
|
{
|
|
puuid: 'missing-puuid',
|
|
platformRoute: 'kr',
|
|
regionalRoute: 'asia',
|
|
queueId: 420,
|
|
requestedMatchCount: 30,
|
|
},
|
|
'seed-job-1',
|
|
);
|
|
|
|
expect(result).toEqual({
|
|
puuid: 'missing-puuid',
|
|
fetchedMatches: 0,
|
|
extractedFeatures: 0,
|
|
profileBuilt: false,
|
|
});
|
|
expect(findOneAccount).toHaveBeenCalledWith({
|
|
puuid: 'missing-puuid',
|
|
isSeed: true,
|
|
});
|
|
expect(getMatchIds).not.toHaveBeenCalled();
|
|
expect(updatePlayerProfile).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('computes metric baselines and completes the baseline job', async () => {
|
|
const { computeMetricBaselines, service, updateAnalysisJob } =
|
|
createPipelineHarness();
|
|
|
|
await service.processBaselineComputationJob(
|
|
createBaselineComputationJobData(),
|
|
'baseline-job-1',
|
|
);
|
|
|
|
expect(computeMetricBaselines).toHaveBeenCalledWith({
|
|
cohort: 'MASTER_PLUS',
|
|
patch: 'ALL',
|
|
});
|
|
const processingUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) =>
|
|
asRecord(asRecord(update).$set).jobType ===
|
|
BASELINE_COMPUTATION_JOB_NAME &&
|
|
asRecord(asRecord(update).$set).status === 'processing',
|
|
);
|
|
expect(processingUpdate).toBeDefined();
|
|
const completedUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) =>
|
|
asRecord(asRecord(update).$set).jobType ===
|
|
BASELINE_COMPUTATION_JOB_NAME &&
|
|
asRecord(asRecord(update).$set).status === 'completed',
|
|
);
|
|
expect(completedUpdate).toBeDefined();
|
|
expect(asRecord(asRecord(completedUpdate?.[1]).$set)).toMatchObject({
|
|
progress: {
|
|
fetchedMatches: 30,
|
|
totalMatches: 3,
|
|
},
|
|
stage: 'completed',
|
|
});
|
|
});
|
|
|
|
it('completes without building a profile when no ranked matches are returned', async () => {
|
|
const { service, updateAnalysisJob, updatePlayerProfile } =
|
|
createPipelineHarness({
|
|
matchIds: [],
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(updatePlayerProfile).not.toHaveBeenCalled();
|
|
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
|
|
);
|
|
expect(completedJobUpdate).toBeDefined();
|
|
});
|
|
|
|
it('uses cached match details without recalling Riot Match-V5', async () => {
|
|
const {
|
|
getMatch,
|
|
getMatchTimeline,
|
|
service,
|
|
updatePlayerMatchFeature,
|
|
updateRiotMatch,
|
|
} = createPipelineHarness({
|
|
existingMatchRaw: createMatchPayload(),
|
|
existingTimeline: createTimelinePayload(),
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(getMatch).not.toHaveBeenCalled();
|
|
expect(getMatchTimeline).not.toHaveBeenCalled();
|
|
expect(
|
|
updateRiotMatch.mock.calls.find(([, update]) =>
|
|
Boolean(asRecord(asRecord(update).$set).timeline),
|
|
),
|
|
).toBeUndefined();
|
|
expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('fetches a missing timeline for cached match details', async () => {
|
|
const { getMatch, getMatchTimeline, service, updateRiotMatch } =
|
|
createPipelineHarness({
|
|
existingMatchRaw: createMatchPayload(),
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(getMatch).not.toHaveBeenCalled();
|
|
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
|
|
const timelineSet = findTimelineSet(updateRiotMatch);
|
|
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
|
expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date);
|
|
});
|
|
|
|
it('refetches cached timeline data when it is malformed', async () => {
|
|
const { getMatchTimeline, service, updateRiotMatch } =
|
|
createPipelineHarness({
|
|
existingMatchRaw: createMatchPayload(),
|
|
existingTimeline: {},
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
|
|
const timelineSet = findTimelineSet(updateRiotMatch);
|
|
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
|
});
|
|
|
|
it('stores derived timeline data when a timeline is available', async () => {
|
|
const timeline = createTimelinePayloadWithFrames('KR_1', [
|
|
{
|
|
timestamp: 0,
|
|
participantFrames: {
|
|
'1': { position: { x: 4_020, y: 6_000 } },
|
|
'6': { position: { x: 3_000, y: 6_000 } },
|
|
'7': { position: { x: 8_000, y: 6_000 } },
|
|
},
|
|
},
|
|
{
|
|
timestamp: 10_000,
|
|
events: [
|
|
{
|
|
type: 'CHAMPION_KILL',
|
|
timestamp: 10_000,
|
|
killerId: 1,
|
|
victimId: 6,
|
|
assistingParticipantIds: [2],
|
|
},
|
|
],
|
|
},
|
|
{
|
|
timestamp: 60_000,
|
|
participantFrames: {
|
|
'1': { position: { x: 4_020, y: 6_000 } },
|
|
'6': { position: { x: 9_000, y: 6_000 } },
|
|
'7': { position: { x: 14_000, y: 6_000 } },
|
|
},
|
|
},
|
|
{
|
|
timestamp: 8 * 60_000,
|
|
participantFrames: {
|
|
'1': { position: { x: 8_000, y: 7_000 } },
|
|
'2': { position: { x: 8_000, y: 7_000 } },
|
|
},
|
|
},
|
|
{
|
|
timestamp: 900_000,
|
|
events: [
|
|
{
|
|
type: 'WARD_PLACED',
|
|
timestamp: 850_000,
|
|
creatorId: 1,
|
|
},
|
|
{
|
|
type: 'ELITE_MONSTER_KILL',
|
|
timestamp: 900_000,
|
|
killerId: 4,
|
|
killerTeamId: 100,
|
|
monsterType: 'DRAGON',
|
|
assistingParticipantIds: [1],
|
|
},
|
|
],
|
|
},
|
|
]);
|
|
const getMatchTimeline = jest
|
|
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
|
.mockResolvedValue(timeline);
|
|
const { service, updatePlayerMatchFeature, updatePlayerProfile } =
|
|
createPipelineHarness({
|
|
getMatchTimeline,
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
const playerMatchFeatureSet = asRecord(
|
|
asRecord(updatePlayerMatchFeature.mock.calls[0][1]).$set,
|
|
);
|
|
const playerMatchFeatureSetFeatures = asRecord(
|
|
playerMatchFeatureSet.features,
|
|
);
|
|
const playerMatchFeatureSetNormalized = asRecord(
|
|
playerMatchFeatureSet.normalized,
|
|
);
|
|
const playerMatchFeatureSetVector =
|
|
playerMatchFeatureSet.vector as number[];
|
|
expect(playerMatchFeatureSet.timelineProcessed).toBe(true);
|
|
expect(playerMatchFeatureSetFeatures).toMatchObject({
|
|
objectivePreWardRateNumerator: 1,
|
|
objectivePreWardRateDenominator: 1,
|
|
eliteObjectiveParticipationRateNumerator: 1,
|
|
eliteObjectiveParticipationRateDenominator: 1,
|
|
});
|
|
expect(playerMatchFeatureSetNormalized.objectivePreWardRate).toBe(1);
|
|
expect(
|
|
playerMatchFeatureSetVector[
|
|
VECTOR_METRICS.findIndex(
|
|
(metric) => metric.id === 'objectivePreWardRate',
|
|
)
|
|
],
|
|
).toBe(1);
|
|
expect(playerMatchFeatureSet.derived).toEqual({
|
|
fightClusters: [
|
|
{
|
|
startTimeMs: 10_000,
|
|
endTimeMs: 10_000,
|
|
killCount: 1,
|
|
participantIds: [1, 2, 6],
|
|
openerParticipantIds: [1, 2],
|
|
cleanupParticipantIds: [1, 2, 6],
|
|
isTeamfight: false,
|
|
},
|
|
],
|
|
advantageEvents: [
|
|
{
|
|
timestampMs: 10_000,
|
|
teamId: 100,
|
|
type: 'championKill',
|
|
score: 1,
|
|
participantIds: [1, 2],
|
|
},
|
|
{
|
|
timestampMs: 900_000,
|
|
teamId: 100,
|
|
type: 'dragon',
|
|
score: 1.5,
|
|
participantIds: [4],
|
|
},
|
|
],
|
|
deathEvents: [
|
|
{
|
|
t: 10_000,
|
|
victimParticipantId: 6,
|
|
x: 4_000,
|
|
y: 6_000,
|
|
zone: 'southWestJungle',
|
|
shutdownBountyGiven: 0,
|
|
nearestAllyDistanceApprox: 5_000,
|
|
},
|
|
],
|
|
objectiveWindows: [
|
|
{
|
|
objectiveTimeMs: 900_000,
|
|
startTimeMs: 780_000,
|
|
endTimeMs: 930_000,
|
|
killerParticipantId: 4,
|
|
killerTeamId: 100,
|
|
monsterType: 'DRAGON',
|
|
},
|
|
],
|
|
roamFrames: [
|
|
{
|
|
t: 8 * 60_000,
|
|
participantId: 1,
|
|
teamId: 100,
|
|
x: 8_000,
|
|
y: 7_000,
|
|
zone: 'river',
|
|
assignedLaneZone: 'middleLane',
|
|
},
|
|
],
|
|
});
|
|
const playerProfileSet = asRecord(
|
|
asRecord(updatePlayerProfile.mock.calls[0][1]).$set,
|
|
);
|
|
const playerProfileSetProfile = asRecord(playerProfileSet.profile);
|
|
const playerProfileSetVector = playerProfileSet.vector as number[];
|
|
expect(playerProfileSetProfile.objectivePreWardRate).toBe(1);
|
|
expect(
|
|
playerProfileSetVector[
|
|
VECTOR_METRICS.findIndex(
|
|
(metric) => metric.id === 'objectivePreWardRate',
|
|
)
|
|
],
|
|
).toBe(1);
|
|
});
|
|
|
|
it('continues raw match analysis when timeline fetch fails', async () => {
|
|
const loggerWarnSpy = jest
|
|
.spyOn(Logger.prototype, 'warn')
|
|
.mockImplementation(() => undefined);
|
|
const getMatchTimeline = jest
|
|
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
|
.mockRejectedValue(new Error('timeline upstream failure'));
|
|
const { service, updatePlayerProfile } = createPipelineHarness({
|
|
getMatchTimeline,
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(updatePlayerProfile).toHaveBeenCalled();
|
|
expect(loggerWarnSpy).toHaveBeenCalledWith(
|
|
expect.stringContaining('Skipping timeline fetch'),
|
|
);
|
|
loggerWarnSpy.mockRestore();
|
|
});
|
|
|
|
it('skips individual match fetch failures and still builds from successful matches', async () => {
|
|
const getMatch = jest
|
|
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
|
.mockRejectedValueOnce(new Error('temporary upstream failure'))
|
|
.mockResolvedValueOnce(createMatchPayload('KR_2'));
|
|
const {
|
|
getMatchTimeline,
|
|
service,
|
|
updateAnalysisJob,
|
|
updatePlayerProfile,
|
|
} = createPipelineHarness({
|
|
getMatch,
|
|
matchIds: ['KR_1', 'KR_2'],
|
|
});
|
|
|
|
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
|
|
|
expect(getMatch).toHaveBeenCalledTimes(2);
|
|
expect(getMatchTimeline).toHaveBeenCalledTimes(1);
|
|
expect(getMatchTimeline).toHaveBeenCalledWith('KR_2', 'asia');
|
|
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
|
expect(playerProfileUpdate).toMatchObject({
|
|
$set: {
|
|
sampleGameCount: 1,
|
|
},
|
|
});
|
|
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
|
|
);
|
|
expect(completedJobUpdate).toBeDefined();
|
|
});
|
|
|
|
it('recomputes stale stored features and rebuilds affected profiles', async () => {
|
|
const staleFeature = createStoredFeature({
|
|
featureSchemaVersion: 1,
|
|
timelineProcessed: false,
|
|
});
|
|
const currentProfileFeature = createStoredFeature({
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
normalized: { kda: 1 },
|
|
vector: VECTOR_METRICS.map((metric) => (metric.id === 'kda' ? 1 : 0)),
|
|
timelineProcessed: true,
|
|
});
|
|
const scanChain = findManyChain([staleFeature]);
|
|
const remainingTargetsChain = findManyChain([]);
|
|
const profileFeaturesChain = findManyChain([currentProfileFeature]);
|
|
const findPlayerMatchFeatures = jest
|
|
.fn()
|
|
.mockReturnValueOnce(scanChain.chain)
|
|
.mockReturnValueOnce(remainingTargetsChain.chain)
|
|
.mockReturnValueOnce(profileFeaturesChain.chain);
|
|
const updatePlayerMatchFeature: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updatePlayerProfile: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updateAnalysisJob: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const updateAccount: UpdateOneMock = jest
|
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
|
const findOneAccount = jest
|
|
.fn()
|
|
.mockReturnValue(leanExecResolved(createStoredAccount()));
|
|
const findOneRiotMatch = jest.fn().mockReturnValue(
|
|
leanExecResolved({
|
|
matchId: 'KR_1',
|
|
raw: createMatchPayload(),
|
|
timeline: createTimelinePayload(),
|
|
}),
|
|
);
|
|
const models = {
|
|
account: {
|
|
findOne: findOneAccount,
|
|
updateOne: updateAccount,
|
|
},
|
|
analysisJob: {
|
|
updateOne: updateAnalysisJob,
|
|
},
|
|
playerMatchFeature: {
|
|
find: findPlayerMatchFeatures,
|
|
updateOne: updatePlayerMatchFeature,
|
|
},
|
|
playerProfile: {
|
|
updateOne: updatePlayerProfile,
|
|
},
|
|
riotMatch: {
|
|
findOne: findOneRiotMatch,
|
|
},
|
|
};
|
|
const connectionService = {
|
|
getModel: jest.fn((modelKey: keyof typeof models) =>
|
|
Promise.resolve(models[modelKey]),
|
|
),
|
|
} as unknown as ConnectionService;
|
|
const service = new AnalysisPipelineService(
|
|
connectionService,
|
|
{} as RiotApiClient,
|
|
new FeatureExtractorService(),
|
|
new ProfileBuilderService(),
|
|
new TimelineDerivedService(),
|
|
new TimelineMetricService(),
|
|
);
|
|
|
|
await service.processFeatureRecomputeJob(
|
|
createFeatureRecomputeJobData(),
|
|
'recompute-job-1',
|
|
);
|
|
|
|
expect(findPlayerMatchFeatures).toHaveBeenNthCalledWith(
|
|
1,
|
|
expect.objectContaining({
|
|
queueId: 420,
|
|
$or: [
|
|
{ featureSchemaVersion: { $lt: FEATURE_SCHEMA_VERSION } },
|
|
{
|
|
timelineProcessed: false,
|
|
'derived.timelineUnavailableForFeatureSchemaVersion': {
|
|
$ne: FEATURE_SCHEMA_VERSION,
|
|
},
|
|
},
|
|
{ normalizationMethod: { $ne: 'population-percentile' } },
|
|
],
|
|
}),
|
|
);
|
|
expect(scanChain.sort).toHaveBeenCalledWith({ gameCreation: -1 });
|
|
expect(scanChain.limit).toHaveBeenCalledWith(100);
|
|
expect(findOneRiotMatch).toHaveBeenCalledWith({ matchId: 'KR_1' });
|
|
const recomputedFeatureSet = asRecord(
|
|
asRecord(updatePlayerMatchFeature.mock.calls[0][1]).$set,
|
|
);
|
|
expect(recomputedFeatureSet).toMatchObject({
|
|
matchId: 'KR_1',
|
|
puuid: 'target-puuid',
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
timelineProcessed: true,
|
|
});
|
|
expect(findPlayerMatchFeatures).toHaveBeenNthCalledWith(
|
|
2,
|
|
expect.objectContaining({
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
$or: [
|
|
{ featureSchemaVersion: { $lt: FEATURE_SCHEMA_VERSION } },
|
|
{
|
|
timelineProcessed: false,
|
|
'derived.timelineUnavailableForFeatureSchemaVersion': {
|
|
$ne: FEATURE_SCHEMA_VERSION,
|
|
},
|
|
},
|
|
{ normalizationMethod: { $ne: 'population-percentile' } },
|
|
],
|
|
}),
|
|
);
|
|
expect(remainingTargetsChain.limit).toHaveBeenCalledWith(1);
|
|
expect(findPlayerMatchFeatures).toHaveBeenNthCalledWith(3, {
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
});
|
|
expect(profileFeaturesChain.limit).toHaveBeenCalledWith(50);
|
|
const playerProfileSet = asRecord(
|
|
asRecord(updatePlayerProfile.mock.calls[0][1]).$set,
|
|
);
|
|
expect(playerProfileSet).toMatchObject({
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
sampleGameCount: 1,
|
|
});
|
|
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
|
|
);
|
|
expect(asRecord(asRecord(completedJobUpdate?.[1]).$set)).toMatchObject({
|
|
jobType: FEATURE_RECOMPUTE_JOB_NAME,
|
|
status: 'completed',
|
|
stage: 'completed',
|
|
});
|
|
});
|
|
|
|
it('marks timeline-less recomputed features as current but missing timeline coverage', async () => {
|
|
const targetFeature = createStoredFeature({
|
|
featureSchemaVersion: 1,
|
|
timelineProcessed: false,
|
|
});
|
|
const currentProfileFeature = createStoredFeature({
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
normalized: { kda: 1 },
|
|
vector: VECTOR_METRICS.map((metric) => (metric.id === 'kda' ? 1 : 0)),
|
|
timelineProcessed: false,
|
|
});
|
|
const { service, updatePlayerMatchFeature, updatePlayerProfile } =
|
|
createFeatureRecomputeHarness({
|
|
profileFeatures: [currentProfileFeature],
|
|
storedMatch: {
|
|
raw: createMatchPayload(),
|
|
},
|
|
targetFeatures: [targetFeature],
|
|
});
|
|
|
|
await service.processFeatureRecomputeJob(
|
|
createFeatureRecomputeJobData(),
|
|
'recompute-job-1',
|
|
);
|
|
|
|
const recomputedFeatureSet = asRecord(
|
|
asRecord(updatePlayerMatchFeature.mock.calls[0][1]).$set,
|
|
);
|
|
expect(recomputedFeatureSet).toMatchObject({
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
timelineProcessed: false,
|
|
derived: {
|
|
timelineUnavailableForFeatureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
},
|
|
});
|
|
expect(asRecord(recomputedFeatureSet.normalized).objectivePreWardRate).toBe(
|
|
undefined,
|
|
);
|
|
const playerProfileSet = asRecord(
|
|
asRecord(updatePlayerProfile.mock.calls[0][1]).$set,
|
|
);
|
|
expect(playerProfileSet.sampleGameCount).toBe(1);
|
|
expect(playerProfileSet.confidence).toBeCloseTo(0.14);
|
|
});
|
|
|
|
it('does not publish a partial profile while stale features remain for that player', async () => {
|
|
const { findOneAccount, service, updatePlayerProfile } =
|
|
createFeatureRecomputeHarness({
|
|
remainingTargets: [
|
|
createStoredFeature({
|
|
matchId: 'KR_2',
|
|
featureSchemaVersion: 1,
|
|
timelineProcessed: false,
|
|
}),
|
|
],
|
|
targetFeatures: [
|
|
createStoredFeature({
|
|
matchId: 'KR_1',
|
|
featureSchemaVersion: 1,
|
|
timelineProcessed: false,
|
|
}),
|
|
],
|
|
});
|
|
|
|
await service.processFeatureRecomputeJob(
|
|
createFeatureRecomputeJobData(),
|
|
'recompute-job-1',
|
|
);
|
|
|
|
expect(updatePlayerProfile).not.toHaveBeenCalled();
|
|
expect(findOneAccount).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('does not mark feature recompute jobs failed before BullMQ exhausts retries', async () => {
|
|
const { service, updateAnalysisJob } = createFeatureRecomputeHarness({
|
|
scanError: new Error('database unavailable'),
|
|
});
|
|
|
|
await expect(
|
|
service.processFeatureRecomputeJob(
|
|
createFeatureRecomputeJobData(),
|
|
'recompute-job-1',
|
|
{ isFinalAttempt: false },
|
|
),
|
|
).rejects.toThrow('database unavailable');
|
|
|
|
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
|
|
);
|
|
expect(failedJobUpdate).toBeUndefined();
|
|
});
|
|
|
|
it('marks feature recompute jobs failed with a public error on the final attempt', async () => {
|
|
const loggerErrorSpy = suppressLoggerError();
|
|
const { service, updateAnalysisJob } = createFeatureRecomputeHarness({
|
|
scanError: new Error('database unavailable'),
|
|
});
|
|
|
|
await expect(
|
|
service.processFeatureRecomputeJob(
|
|
createFeatureRecomputeJobData({ puuid: 'target-puuid' }),
|
|
'recompute-job-1',
|
|
{ isFinalAttempt: true },
|
|
),
|
|
).rejects.toThrow('database unavailable');
|
|
|
|
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
|
|
);
|
|
expect(asRecord(asRecord(failedJobUpdate?.[1]).$set)).toMatchObject({
|
|
jobType: FEATURE_RECOMPUTE_JOB_NAME,
|
|
status: 'failed',
|
|
error: 'Analysis failed during processing.',
|
|
});
|
|
expect(loggerErrorSpy).toHaveBeenCalledWith(
|
|
expect.stringContaining('Feature recompute job failed'),
|
|
expect.any(String),
|
|
);
|
|
expect(loggerErrorSpy.mock.calls[0][0]).toContain('puuid="target-puuid"');
|
|
loggerErrorSpy.mockRestore();
|
|
});
|
|
|
|
it('does not mark the job failed before BullMQ exhausts retries', async () => {
|
|
const { service, updateAnalysisJob } = createPipelineHarness({
|
|
accountError: new Error('upstream unavailable'),
|
|
});
|
|
|
|
await expect(
|
|
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
|
|
isFinalAttempt: false,
|
|
}),
|
|
).rejects.toThrow('upstream unavailable');
|
|
|
|
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
|
|
);
|
|
expect(failedJobUpdate).toBeUndefined();
|
|
});
|
|
|
|
it('marks the job failed with a public error on the final BullMQ attempt', async () => {
|
|
const loggerErrorSpy = suppressLoggerError();
|
|
const { service, updateAnalysisJob } = createPipelineHarness({
|
|
accountError: new Error('internal host redis.local refused connection'),
|
|
});
|
|
|
|
await expect(
|
|
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
|
|
isFinalAttempt: true,
|
|
}),
|
|
).rejects.toThrow('internal host redis.local refused connection');
|
|
|
|
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
|
|
);
|
|
expect(asRecord(asRecord(failedJobUpdate?.[1]).$set)).toMatchObject({
|
|
status: 'failed',
|
|
error: 'Analysis failed during processing.',
|
|
});
|
|
loggerErrorSpy.mockRestore();
|
|
});
|
|
|
|
it('marks Riot account lookup misses with a public not-found error', async () => {
|
|
const loggerErrorSpy = suppressLoggerError();
|
|
const { service, updateAnalysisJob } = createPipelineHarness({
|
|
accountError: new RiotNotFoundError(404),
|
|
});
|
|
|
|
await expect(
|
|
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
|
|
isFinalAttempt: true,
|
|
}),
|
|
).rejects.toThrow(RiotNotFoundError);
|
|
|
|
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
|
|
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
|
|
);
|
|
expect(asRecord(asRecord(failedJobUpdate?.[1]).$set)).toMatchObject({
|
|
status: 'failed',
|
|
error: 'Riot account was not found for the selected region.',
|
|
});
|
|
loggerErrorSpy.mockRestore();
|
|
});
|
|
|
|
it('logs final pipeline failures with job context', async () => {
|
|
const loggerErrorSpy = suppressLoggerError();
|
|
const { service } = createPipelineHarness({
|
|
accountError: new Error('internal host redis.local refused connection'),
|
|
});
|
|
|
|
await expect(
|
|
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
|
|
isFinalAttempt: true,
|
|
}),
|
|
).rejects.toThrow('internal host redis.local refused connection');
|
|
|
|
expect(loggerErrorSpy).toHaveBeenCalledWith(
|
|
expect.stringContaining('Analysis job failed jobId="analysis-job-1"'),
|
|
expect.any(String),
|
|
);
|
|
expect(loggerErrorSpy.mock.calls[0][0]).toContain(
|
|
'publicError="Analysis failed during processing."',
|
|
);
|
|
|
|
loggerErrorSpy.mockRestore();
|
|
});
|
|
});
|