Rename mentor matching to similar players

This commit is contained in:
dahyeon committed 2026-07-03 03:18:59 -07:00
1 parent cfbc74d882
commit ce00bc84b5
14 files changed
+529 -388

No files matched your search

@@ -3,9 +3,9 @@ import {
FEATURE_SCHEMA_VERSION,
METRICS,
type AnalysisJobStatusDto,
type MentorMatchesDto,
type MetricValueDto,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import { ConnectionService } from '../global/database/connection.service';
import type {
@@ -14,8 +14,8 @@ import type {
PlayerProfile,
TierInfo,
} from '../global/database/schemas';
import { MentorMatchService } from './mentor-match.service';
import type { MentorMatch } from './analysis.types';
import { SimilarPlayerService } from './similar-player.service';
import type { SimilarPlayer } from './analysis.types';
type JobStatusRecord = Pick<
AnalysisJob,
@@ -27,7 +27,7 @@ type AccountSummaryRecord = Pick<
'gameName' | 'profileIconId' | 'tagLine' | 'tiers'
>;
type MentorAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
type CounterpartAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
type PlayerProfileRecord = Pick<
PlayerProfile,
@@ -45,7 +45,7 @@ type PlayerProfileRecord = Pick<
export class AnalysisReadService {
constructor(
private readonly connectionService: ConnectionService,
private readonly mentorMatchService?: MentorMatchService,
private readonly similarPlayerService?: SimilarPlayerService,
) {}
public async getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
@@ -113,34 +113,27 @@ export class AnalysisReadService {
};
}
public async getMentorMatches(
public async getSimilarPlayers(
puuid: string,
queueId: number,
limit: number,
): Promise<MentorMatchesDto> {
if (!this.mentorMatchService) {
throw new Error('MentorMatchService is not configured.');
): Promise<SimilarPlayersDto> {
if (!this.similarPlayerService) {
throw new Error('SimilarPlayerService is not configured.');
}
const mentorMatchesResult = await this.mentorMatchService.findMentorMatches(
puuid,
queueId,
limit,
);
const mentorAccountsByPuuid = await this.findMentorAccounts(
mentorMatchesResult.matches.map((match) => match.puuid),
const similarPlayersResult =
await this.similarPlayerService.findSimilarPlayers(puuid, queueId, limit);
const accountsByPuuid = await this.findCounterpartAccounts(
similarPlayersResult.matches.map((match) => match.puuid),
);
return {
puuid: mentorMatchesResult.puuid,
queueId: mentorMatchesResult.queueId,
profileUpdatedAt: mentorMatchesResult.profileUpdatedAt.toISOString(),
matches: mentorMatchesResult.matches.map((match, index) =>
this.toMentorMatchDto(
match,
mentorAccountsByPuuid.get(match.puuid),
index,
),
puuid: similarPlayersResult.puuid,
queueId: similarPlayersResult.queueId,
profileUpdatedAt: similarPlayersResult.profileUpdatedAt.toISOString(),
matches: similarPlayersResult.matches.map((match, index) =>
this.toSimilarPlayerDto(match, accountsByPuuid.get(match.puuid), index),
),
};
}
@@ -152,16 +145,16 @@ export class AnalysisReadService {
return accountModel.findOne({ puuid }).lean<AccountSummaryRecord>().exec();
}
private async findMentorAccounts(
private async findCounterpartAccounts(
puuids: string[],
): Promise<Map<string, MentorAccountRecord>> {
): Promise<Map<string, CounterpartAccountRecord>> {
const uniquePuuids = Array.from(new Set(puuids));
if (uniquePuuids.length === 0) return new Map();
const accountModel = await this.connectionService.getModel('account');
const accounts = await accountModel
.find({ puuid: { $in: uniquePuuids } })
.lean<MentorAccountRecord[]>()
.lean<CounterpartAccountRecord[]>()
.exec();
return new Map(accounts.map((account) => [account.puuid, account]));
@@ -224,13 +217,13 @@ export class AnalysisReadService {
};
}
private toMentorMatchDto(
match: MentorMatch,
account: MentorAccountRecord | undefined,
private toSimilarPlayerDto(
match: SimilarPlayer,
account: CounterpartAccountRecord | undefined,
index: number,
): MentorMatchesDto['matches'][number] {
): SimilarPlayersDto['matches'][number] {
return {
mentorDisplayId: `mentor-${index + 1}`,
displayId: `similar-${index + 1}`,
riotId: account
? {
gameName: account.gameName,
@@ -242,11 +235,13 @@ export class AnalysisReadService {
tier: match.tier,
division: match.division,
leaguePoints: match.leaguePoints,
tierComparison: match.tierComparison,
mainRole: match.mainRole,
mainChampions: match.mainChampions,
sampleGameCount: match.sampleGameCount,
similarMetrics: match.similarMetrics,
gapMetrics: match.gapMetrics,
strongerMetrics: match.strongerMetrics,
weakerMetrics: match.weakerMetrics,
};
}
@@ -12,8 +12,8 @@ import {
import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
MentorMatchesDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared';
import {
RIOT_PLATFORM_ROUTES,
@@ -70,16 +70,16 @@ export class AnalysisController {
);
}
@Get('players/:puuid/mentor-matches')
public async getMentorMatches(
@Get('players/:puuid/similar-players')
public async getSimilarPlayers(
@Param('puuid') puuid: string,
@Query('queueId') rawQueueId?: string,
@Query('limit') rawLimit?: string,
): Promise<MentorMatchesDto> {
return this.analysisReadService.getMentorMatches(
): Promise<SimilarPlayersDto> {
return this.analysisReadService.getSimilarPlayers(
this.parsePuuid(puuid),
this.parseQueueId(rawQueueId),
this.parseMentorMatchLimit(rawLimit),
this.parseSimilarPlayersLimit(rawLimit),
);
}
@@ -165,7 +165,7 @@ export class AnalysisController {
return queueId;
}
private parseMentorMatchLimit(value?: string): number {
private parseSimilarPlayersLimit(value?: string): number {
if (value === undefined) return 10;
const limit = Number(value);
if (!Number.isInteger(limit) || limit < 1) {
@@ -20,10 +20,10 @@ import { createBullMqOptions } from './bullmq.config';
import { FeatureExtractorService } from './feature-extractor.service';
import { MetricBaselineService } from './metric-baseline.service';
import { MetricNormalizationService } from './metric-normalization.service';
import { MentorMatchService } from './mentor-match.service';
import { ProfileBuilderService } from './profile-builder.service';
import { SeedCollectionProcessor } from './seed-collection.processor';
import { SeedCollectionService } from './seed-collection.service';
import { SimilarPlayerService } from './similar-player.service';
import { TimelineDerivedService } from './timeline-derived.service';
import { TimelineMetricService } from './timeline-metric.service';
@@ -61,9 +61,9 @@ import { TimelineMetricService } from './timeline-metric.service';
FeatureExtractorService,
MetricBaselineService,
MetricNormalizationService,
MentorMatchService,
ProfileBuilderService,
SeedCollectionService,
SimilarPlayerService,
TimelineDerivedService,
TimelineMetricService,
],
@@ -73,8 +73,8 @@ import { TimelineMetricService } from './timeline-metric.service';
AnalysisPipelineService,
MetricBaselineService,
MetricNormalizationService,
MentorMatchService,
SeedCollectionService,
SimilarPlayerService,
],
})
export class AnalysisModule {}
+15 -13
View File
@@ -1,4 +1,4 @@
import type { MetricId, Role } from '@persona-lenz/shared';
import type { MetricId, Role, TierComparison } from '@persona-lenz/shared';
import type {
BaselineCohort,
LaneOpponentRef,
@@ -97,43 +97,45 @@ export interface BuiltPlayerProfile {
leaguePoints?: number;
}
export interface MentorChampionPoolEntry {
export interface ChampionPoolEntry {
championId: number;
games: number;
wins: number;
}
export interface SimilarMentorMetric {
export interface SimilarMetric {
metricId: MetricId;
currentValue: number;
mentorValue: number;
otherValue: number;
absoluteGap: number;
}
export interface GapMentorMetric {
export interface LeadMetric {
metricId: MetricId;
currentValue: number;
mentorValue: number;
mentorAdvantage: number;
otherValue: number;
lead: number;
}
export interface MentorMatch {
export interface SimilarPlayer {
puuid: string;
similarityScore: number;
finalScore: number;
tier?: string;
division?: string;
leaguePoints?: number;
tierComparison: TierComparison;
mainRole: Role;
mainChampions: MentorChampionPoolEntry[];
mainChampions: ChampionPoolEntry[];
sampleGameCount: number;
similarMetrics: SimilarMentorMetric[];
gapMetrics: GapMentorMetric[];
similarMetrics: SimilarMetric[];
strongerMetrics: LeadMetric[];
weakerMetrics: LeadMetric[];
}
export interface MentorMatchesResult {
export interface SimilarPlayersResult {
puuid: string;
queueId: number;
profileUpdatedAt: Date;
matches: MentorMatch[];
matches: SimilarPlayer[];
}
@@ -1,6 +1,6 @@
import { FEATURE_SCHEMA_VERSION, VECTOR_DIMENSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import { MentorMatchService } from './mentor-match.service';
import { SimilarPlayerService } from './similar-player.service';
function createLeanExec<T>(value: T) {
return {
@@ -64,7 +64,7 @@ function createProfile(overrides: Record<string, unknown> = {}) {
};
}
describe('MentorMatchService', () => {
describe('SimilarPlayerService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-03T00:00:00.000Z'));
});
@@ -73,7 +73,7 @@ describe('MentorMatchService', () => {
jest.useRealTimers();
});
it('queries high-tier seed profiles with Atlas Vector Search and reranks candidates', async () => {
it('queries similar profiles without tier filters and ranks by style similarity', async () => {
const currentProfile = createProfile();
const findOne = jest.fn(() => createLeanExec(currentProfile));
const recommendationFindOne = jest.fn(() => createSortedLeanExec(null));
@@ -81,7 +81,7 @@ describe('MentorMatchService', () => {
const aggregate = jest.fn(() =>
createAggregateExec([
createProfile({
puuid: 'mentor-low-style-better-context',
puuid: 'lower-style-better-context',
championPool: [
{ championId: 103, games: 12, wins: 8 },
{ championId: 84, games: 5, wins: 4 },
@@ -101,7 +101,7 @@ describe('MentorMatchService', () => {
score: 0.8,
}),
createProfile({
puuid: 'mentor-high-style-weaker-context',
puuid: 'higher-style-similar-player',
championPool: [{ championId: 222, games: 30, wins: 20 }],
profile: {
kda: 0.4,
@@ -111,13 +111,13 @@ describe('MentorMatchService', () => {
deathsPerMin: 0.6,
},
sampleGameCount: 30,
tier: 'MASTER',
tier: 'PLATINUM',
lastMatchAt: new Date('2026-06-19T00:00:00.000Z'),
score: 0.9,
}),
]),
);
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
@@ -127,7 +127,7 @@ describe('MentorMatchService', () => {
),
} as unknown as ConnectionService);
const result = await service.findMentorMatches('target-puuid', 420, 2);
const result = await service.findSimilarPlayers('target-puuid', 420, 2);
expect(findOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
@@ -145,8 +145,6 @@ describe('MentorMatchService', () => {
filter: {
mainRole: 'MIDDLE',
queueId: 420,
tier: { $in: ['MASTER', 'GRANDMASTER', 'CHALLENGER'] },
isSeed: true,
sampleGameCount: { $gte: 20 },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
@@ -173,63 +171,89 @@ describe('MentorMatchService', () => {
expect(result.profileUpdatedAt).toEqual(
new Date('2026-07-02T00:00:00.000Z'),
);
// 스타일 유사도(0.9)가 컨텍스트(챔피언 풀·최근성)보다 랭킹을 지배한다.
expect(result.matches.map((match) => match.puuid)).toEqual([
'mentor-low-style-better-context',
'mentor-high-style-weaker-context',
]);
expect(result.matches[0].finalScore).toBeGreaterThan(
result.matches[1].finalScore,
);
expect(result.matches[0].mainChampions).toEqual([
{ championId: 103, games: 12, wins: 8 },
{ championId: 84, games: 5, wins: 4 },
{ championId: 777, games: 5, wins: 3 },
'higher-style-similar-player',
'lower-style-better-context',
]);
expect(result.matches[0].finalScore).toBeCloseTo(0.69, 6);
expect(result.matches[1].finalScore).toBeCloseTo(0.67, 6);
expect(result.matches[0].tierComparison).toBe('lower');
expect(result.matches[1].tierComparison).toBe('higher');
expect(result.matches[0].similarMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
mentorValue: 0.49,
absoluteGap: 0.01,
},
{
metricId: 'csPerMin',
currentValue: 0.5,
mentorValue: 0.51,
absoluteGap: 0.01,
otherValue: 0.52,
absoluteGap: 0.02,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
absoluteGap: 0.3,
otherValue: 0.55,
absoluteGap: 0.05,
},
]);
expect(result.matches[0].gapMetrics).toEqual([
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.9,
mentorAdvantage: 0.6,
otherValue: 0.4,
absoluteGap: 0.1,
},
]);
expect(result.matches[0].strongerMetrics).toEqual([
{
metricId: 'csPerMin',
currentValue: 0.5,
otherValue: 0.7,
lead: 0.2,
},
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.4,
lead: 0.1,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
mentorValue: 0.2,
mentorAdvantage: 0.5,
otherValue: 0.6,
lead: 0.1,
},
]);
expect(result.matches[0].weakerMetrics).toEqual([]);
expect(result.matches[1].strongerMetrics).toEqual([
{
metricId: 'kda',
currentValue: 0.3,
otherValue: 0.9,
lead: 0.6,
},
{
metricId: 'deathsPerMin',
currentValue: 0.7,
otherValue: 0.2,
lead: 0.5,
},
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
]);
expect(result.matches[1].weakerMetrics).toEqual([
{
metricId: 'killParticipation',
currentValue: 0.5,
otherValue: 0.49,
lead: 0.01,
},
]);
expect(updateOne).toHaveBeenCalledWith(
{
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
},
@@ -237,7 +261,7 @@ describe('MentorMatchService', () => {
$set: {
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
result: { matches: result.matches },
@@ -252,13 +276,14 @@ describe('MentorMatchService', () => {
);
});
it('returns a fresh cached mentor recommendation without running vector search', async () => {
it('returns a fresh cached similar-player recommendation without running vector search', async () => {
const currentProfile = createProfile();
const cachedMatch = {
puuid: 'cached-mentor',
puuid: 'cached-similar-player',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -266,18 +291,19 @@ describe('MentorMatchService', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [],
};
const findOne = jest.fn(() => createLeanExec(currentProfile));
const aggregate = jest.fn();
@@ -288,7 +314,7 @@ describe('MentorMatchService', () => {
}),
);
const updateOne = jest.fn();
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn((modelKey: string) =>
Promise.resolve(
modelKey === 'playerProfile'
@@ -298,12 +324,12 @@ describe('MentorMatchService', () => {
),
} as unknown as ConnectionService);
const result = await service.findMentorMatches('target-puuid', 420, 10);
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
expect(recommendationFindOne).toHaveBeenCalledWith({
puuid: 'target-puuid',
queueId: 420,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
});
@@ -320,12 +346,12 @@ describe('MentorMatchService', () => {
it('throws when the player profile has not been built yet', async () => {
const findOne = jest.fn(() => createLeanExec(null));
const aggregate = jest.fn();
const service = new MentorMatchService({
const service = new SimilarPlayerService({
getModel: jest.fn().mockResolvedValue({ findOne, aggregate }),
} as unknown as ConnectionService);
await expect(
service.findMentorMatches('missing-puuid', 420),
service.findSimilarPlayers('missing-puuid', 420),
).rejects.toThrow('Player profile not found.');
expect(aggregate).not.toHaveBeenCalled();
});
@@ -6,33 +6,51 @@ import {
VECTOR_DIMENSION,
type MetricDefinition,
type Role,
type TierComparison,
} from '@persona-lenz/shared';
import type { PipelineStage } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
GapMentorMetric,
MentorChampionPoolEntry,
MentorMatch,
MentorMatchesResult,
SimilarMentorMetric,
ChampionPoolEntry,
LeadMetric,
SimilarMetric,
SimilarPlayer,
SimilarPlayersResult,
} from './analysis.types';
const MENTOR_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
const MENTOR_VECTOR_SEARCH_NUM_CANDIDATES = 200;
const MENTOR_VECTOR_SEARCH_LIMIT = 50;
const DEFAULT_MENTOR_MATCH_LIMIT = 10;
const MINIMUM_MENTOR_SAMPLE_GAME_COUNT = 20;
const SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
const SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES = 200;
const SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT = 50;
const DEFAULT_SIMILAR_PLAYER_LIMIT = 10;
const MINIMUM_SAMPLE_GAME_COUNT = 20;
const LOW_SAMPLE_GAME_COUNT_THRESHOLD = 30;
const LOW_SAMPLE_PENALTY = 0.1;
const RECENCY_HALF_LIFE_MS = 14 * 24 * 60 * 60 * 1000;
const HIGH_TIER_MENTOR_TIERS = ['MASTER', 'GRANDMASTER', 'CHALLENGER'];
const TIER_ORDER = [
'IRON',
'BRONZE',
'SILVER',
'GOLD',
'PLATINUM',
'EMERALD',
'DIAMOND',
'MASTER',
'GRANDMASTER',
'CHALLENGER',
];
const TIER_COMPARISONS: TierComparison[] = [
'higher',
'same',
'lower',
'unknown',
];
interface MentorProfileRecord {
interface PlayerProfileRecord {
puuid: string;
queueId: number;
mainRole: Role;
sampleGameCount: number;
championPool: MentorChampionPoolEntry[];
championPool: ChampionPoolEntry[];
profile: Record<string, number>;
vector: number[];
updatedAt: Date;
@@ -42,23 +60,29 @@ interface MentorProfileRecord {
leaguePoints?: number;
}
interface MentorVectorSearchRecord extends Omit<MentorProfileRecord, 'vector'> {
interface VectorSearchRecord extends Omit<PlayerProfileRecord, 'vector'> {
score?: number;
}
interface MentorRecommendationCacheRecord {
interface RecommendationCacheRecord {
result?: Record<string, unknown>;
}
/**
* 나와 플레이스타일 벡터가 가까운 유저를 찾는다. 목적은 "따라 할 멘토"가 아니라
* "스타일은 비슷한데 왜 점수(티어)가 다른가"라는 인사이트 제공이므로,
* 후보를 티어로 거르지 않고 유사도 중심으로 랭킹한 뒤 티어 관계와
* 지표 우위(양방향)를 함께 반환한다.
*/
@Injectable()
export class MentorMatchService {
export class SimilarPlayerService {
constructor(private readonly connectionService: ConnectionService) {}
public async findMentorMatches(
public async findSimilarPlayers(
puuid: string,
queueId: number,
requestedLimit = DEFAULT_MENTOR_MATCH_LIMIT,
): Promise<MentorMatchesResult> {
requestedLimit = DEFAULT_SIMILAR_PLAYER_LIMIT,
): Promise<SimilarPlayersResult> {
const playerProfileModel =
await this.connectionService.getModel('playerProfile');
const recommendationModel =
@@ -66,14 +90,14 @@ export class MentorMatchService {
const normalizedLimit = this.normalizeLimit(requestedLimit);
const currentProfile = await playerProfileModel
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
.lean<MentorProfileRecord>()
.lean<PlayerProfileRecord>()
.exec();
if (!currentProfile) {
throw new NotFoundException('Player profile not found.');
}
const cacheFilter = this.createMentorRecommendationFilter(
const cacheFilter = this.createRecommendationFilter(
puuid,
queueId,
currentProfile.updatedAt,
@@ -81,9 +105,9 @@ export class MentorMatchService {
const cachedRecommendation = await recommendationModel
.findOne(cacheFilter)
.sort({ generatedAt: -1 })
.lean<MentorRecommendationCacheRecord>()
.lean<RecommendationCacheRecord>()
.exec();
const cachedMatches = this.extractCachedMentorMatches(cachedRecommendation);
const cachedMatches = this.extractCachedMatches(cachedRecommendation);
if (cachedMatches) {
return {
puuid,
@@ -103,13 +127,13 @@ export class MentorMatchService {
}
const candidates = await playerProfileModel
.aggregate<MentorVectorSearchRecord>(
this.createMentorCandidatePipeline(currentProfile, puuid, queueId),
.aggregate<VectorSearchRecord>(
this.createCandidatePipeline(currentProfile, puuid, queueId),
)
.exec();
const matches = candidates
.map((candidate) => this.toMentorMatch(currentProfile, candidate))
.map((candidate) => this.toSimilarPlayer(currentProfile, candidate))
.sort((left, right) => right.finalScore - left.finalScore)
.slice(0, normalizedLimit);
@@ -120,13 +144,13 @@ export class MentorMatchService {
$set: {
puuid,
queueId,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt: currentProfile.updatedAt,
result: { matches },
evidence: {
candidateCount: candidates.length,
vectorSearchIndex: MENTOR_VECTOR_SEARCH_INDEX_NAME,
vectorSearchIndex: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
},
generatedAt: new Date(),
},
@@ -143,45 +167,43 @@ export class MentorMatchService {
};
}
private createMentorRecommendationFilter(
private createRecommendationFilter(
puuid: string,
queueId: number,
profileUpdatedAt: Date,
): {
puuid: string;
queueId: number;
type: 'mentor-match';
type: 'similar-player';
featureSchemaVersion: number;
profileUpdatedAt: Date;
} {
return {
puuid,
queueId,
type: 'mentor-match',
type: 'similar-player',
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
profileUpdatedAt,
};
}
private createMentorCandidatePipeline(
currentProfile: MentorProfileRecord,
private createCandidatePipeline(
currentProfile: PlayerProfileRecord,
puuid: string,
queueId: number,
): PipelineStage[] {
return [
{
$vectorSearch: {
index: MENTOR_VECTOR_SEARCH_INDEX_NAME,
index: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
path: 'vector',
queryVector: currentProfile.vector,
numCandidates: MENTOR_VECTOR_SEARCH_NUM_CANDIDATES,
limit: MENTOR_VECTOR_SEARCH_LIMIT,
numCandidates: SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES,
limit: SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT,
filter: {
mainRole: currentProfile.mainRole,
queueId,
tier: { $in: HIGH_TIER_MENTOR_TIERS },
isSeed: true,
sampleGameCount: { $gte: MINIMUM_MENTOR_SAMPLE_GAME_COUNT },
sampleGameCount: { $gte: MINIMUM_SAMPLE_GAME_COUNT },
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
},
},
@@ -206,81 +228,99 @@ export class MentorMatchService {
];
}
private toMentorMatch(
currentProfile: MentorProfileRecord,
mentorProfile: MentorVectorSearchRecord,
): MentorMatch {
const similarityScore = this.clamp01(mentorProfile.score ?? 0);
private toSimilarPlayer(
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
): SimilarPlayer {
const similarityScore = this.clamp01(candidate.score ?? 0);
return {
puuid: mentorProfile.puuid,
puuid: candidate.puuid,
similarityScore,
finalScore: this.calculateFinalScore(
currentProfile,
mentorProfile,
candidate,
similarityScore,
),
tier: mentorProfile.tier,
division: mentorProfile.division,
leaguePoints: mentorProfile.leaguePoints,
mainRole: mentorProfile.mainRole,
mainChampions: mentorProfile.championPool.slice(0, 3),
sampleGameCount: mentorProfile.sampleGameCount,
tier: candidate.tier,
division: candidate.division,
leaguePoints: candidate.leaguePoints,
tierComparison: this.compareTier(currentProfile.tier, candidate.tier),
mainRole: candidate.mainRole,
mainChampions: candidate.championPool.slice(0, 3),
sampleGameCount: candidate.sampleGameCount,
similarMetrics: this.resolveSimilarMetrics(
currentProfile.profile,
mentorProfile.profile,
candidate.profile,
),
gapMetrics: this.resolveGapMetrics(
strongerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
mentorProfile.profile,
candidate.profile,
'other',
),
weakerMetrics: this.resolveLeadMetrics(
currentProfile.profile,
candidate.profile,
'current',
),
};
}
private calculateFinalScore(
currentProfile: MentorProfileRecord,
mentorProfile: MentorVectorSearchRecord,
currentProfile: PlayerProfileRecord,
candidate: VectorSearchRecord,
similarityScore: number,
): number {
const championPoolSimilarity = this.calculateChampionPoolSimilarity(
currentProfile.championPool,
mentorProfile.championPool,
candidate.championPool,
);
const recencyScore = this.calculateRecencyScore(mentorProfile.lastMatchAt);
const tierScore = this.resolveTierScore(mentorProfile.tier);
const recencyScore = this.calculateRecencyScore(candidate.lastMatchAt);
const lowSamplePenalty =
mentorProfile.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
candidate.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
? LOW_SAMPLE_PENALTY
: 0;
// 유사도가 랭킹을 지배해야 한다 — 티어는 랭킹 요소가 아니라 인사이트(tierComparison)로만 쓴다.
return this.clamp01(
0.6 * similarityScore +
0.2 * championPoolSimilarity +
0.12 * recencyScore +
0.08 * tierScore -
0.7 * similarityScore +
0.18 * championPoolSimilarity +
0.12 * recencyScore -
lowSamplePenalty,
);
}
private compareTier(
currentTier: string | undefined,
otherTier: string | undefined,
): TierComparison {
const currentTierRank = TIER_ORDER.indexOf(currentTier ?? '');
const otherTierRank = TIER_ORDER.indexOf(otherTier ?? '');
if (currentTierRank < 0 || otherTierRank < 0) return 'unknown';
if (otherTierRank > currentTierRank) return 'higher';
if (otherTierRank < currentTierRank) return 'lower';
return 'same';
}
private calculateChampionPoolSimilarity(
currentChampionPool: MentorChampionPoolEntry[],
mentorChampionPool: MentorChampionPoolEntry[],
currentChampionPool: ChampionPoolEntry[],
otherChampionPool: ChampionPoolEntry[],
): number {
const currentChampionIds = new Set(
currentChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const mentorChampionIds = new Set(
mentorChampionPool.slice(0, 5).map((entry) => entry.championId),
const otherChampionIds = new Set(
otherChampionPool.slice(0, 5).map((entry) => entry.championId),
);
const unionChampionIds = new Set([
...currentChampionIds,
...mentorChampionIds,
...otherChampionIds,
]);
if (unionChampionIds.size === 0) return 0;
let sharedChampionCount = 0;
currentChampionIds.forEach((championId) => {
if (mentorChampionIds.has(championId)) sharedChampionCount += 1;
if (otherChampionIds.has(championId)) sharedChampionCount += 1;
});
return sharedChampionCount / unionChampionIds.size;
@@ -293,21 +333,14 @@ export class MentorMatchService {
return this.clamp01(Math.pow(0.5, ageMs / RECENCY_HALF_LIFE_MS));
}
private resolveTierScore(tier: string | undefined): number {
if (tier === 'CHALLENGER') return 1;
if (tier === 'GRANDMASTER') return 0.8;
if (tier === 'MASTER') return 0.6;
return 0;
}
private resolveSimilarMetrics(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
): SimilarMentorMetric[] {
otherProfile: Record<string, number>,
): SimilarMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
mentorProfile,
otherProfile,
metric,
);
if (!comparison) return [];
@@ -315,9 +348,9 @@ export class MentorMatchService {
return {
metricId: metric.id,
currentValue: comparison.currentValue,
mentorValue: comparison.mentorValue,
otherValue: comparison.otherValue,
absoluteGap: this.roundMetricGap(
Math.abs(comparison.mentorValue - comparison.currentValue),
Math.abs(comparison.otherValue - comparison.currentValue),
),
};
})
@@ -325,57 +358,59 @@ export class MentorMatchService {
.slice(0, 3);
}
private resolveGapMetrics(
private resolveLeadMetrics(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
): GapMentorMetric[] {
otherProfile: Record<string, number>,
leader: 'current' | 'other',
): LeadMetric[] {
return METRICS.flatMap((metric) => {
const comparison = this.createMetricValues(
currentProfile,
mentorProfile,
otherProfile,
metric,
);
if (!comparison) return [];
const rawMentorAdvantage =
const otherAdvantage =
metric.direction === 'lowerIsBetter'
? comparison.currentValue - comparison.mentorValue
: comparison.mentorValue - comparison.currentValue;
if (rawMentorAdvantage <= 0) return [];
? comparison.currentValue - comparison.otherValue
: comparison.otherValue - comparison.currentValue;
const lead = leader === 'other' ? otherAdvantage : -otherAdvantage;
if (lead <= 0) return [];
return {
metricId: metric.id,
currentValue: comparison.currentValue,
mentorValue: comparison.mentorValue,
mentorAdvantage: this.roundMetricGap(rawMentorAdvantage),
otherValue: comparison.otherValue,
lead: this.roundMetricGap(lead),
};
})
.sort((left, right) => right.mentorAdvantage - left.mentorAdvantage)
.sort((left, right) => right.lead - left.lead)
.slice(0, 3);
}
private createMetricValues(
currentProfile: Record<string, number>,
mentorProfile: Record<string, number>,
otherProfile: Record<string, number>,
metric: MetricDefinition,
): { currentValue: number; mentorValue: number } | null {
): { currentValue: number; otherValue: number } | null {
const currentValue = currentProfile[metric.id];
const mentorValue = mentorProfile[metric.id];
if (!Number.isFinite(currentValue) || !Number.isFinite(mentorValue)) {
const otherValue = otherProfile[metric.id];
if (!Number.isFinite(currentValue) || !Number.isFinite(otherValue)) {
return null;
}
return {
currentValue: this.clamp01(currentValue),
mentorValue: this.clamp01(mentorValue),
otherValue: this.clamp01(otherValue),
};
}
private normalizeLimit(requestedLimit: number): number {
if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
return DEFAULT_MENTOR_MATCH_LIMIT;
return DEFAULT_SIMILAR_PLAYER_LIMIT;
}
return Math.min(requestedLimit, DEFAULT_MENTOR_MATCH_LIMIT);
return Math.min(requestedLimit, DEFAULT_SIMILAR_PLAYER_LIMIT);
}
private roundMetricGap(value: number): number {
@@ -387,18 +422,18 @@ export class MentorMatchService {
return Math.max(0, Math.min(1, value));
}
private extractCachedMentorMatches(
recommendation: MentorRecommendationCacheRecord | null,
): MentorMatch[] | null {
private extractCachedMatches(
recommendation: RecommendationCacheRecord | null,
): SimilarPlayer[] | null {
const matches = recommendation?.result?.matches;
if (!Array.isArray(matches)) return null;
if (!matches.every((match) => this.isCachedMentorMatch(match))) {
if (!matches.every((match) => this.isCachedSimilarPlayer(match))) {
return null;
}
return matches;
}
private isCachedMentorMatch(value: unknown): value is MentorMatch {
private isCachedSimilarPlayer(value: unknown): value is SimilarPlayer {
const record = this.asRecord(value);
if (!record) return false;
@@ -406,6 +441,8 @@ export class MentorMatchService {
typeof record.puuid === 'string' &&
this.isFiniteNumber(record.similarityScore) &&
this.isFiniteNumber(record.finalScore) &&
typeof record.tierComparison === 'string' &&
TIER_COMPARISONS.includes(record.tierComparison as TierComparison) &&
typeof record.mainRole === 'string' &&
ROLES.includes(record.mainRole as Role) &&
Array.isArray(record.mainChampions) &&
@@ -414,13 +451,14 @@ export class MentorMatchService {
record.similarMetrics,
'absoluteGap',
) &&
this.isCachedMetricComparisonArray(record.gapMetrics, 'mentorAdvantage')
this.isCachedMetricComparisonArray(record.strongerMetrics, 'lead') &&
this.isCachedMetricComparisonArray(record.weakerMetrics, 'lead')
);
}
private isCachedMetricComparisonArray(
value: unknown,
scoreFieldName: 'absoluteGap' | 'mentorAdvantage',
scoreFieldName: 'absoluteGap' | 'lead',
): boolean {
return (
Array.isArray(value) &&
@@ -430,7 +468,7 @@ export class MentorMatchService {
record !== null &&
typeof record.metricId === 'string' &&
this.isFiniteNumber(record.currentValue) &&
this.isFiniteNumber(record.mentorValue) &&
this.isFiniteNumber(record.otherValue) &&
this.isFiniteNumber(record[scoreFieldName])
);
})
@@ -107,7 +107,7 @@ export const PlayerProfileSchema = new Schema<PlayerProfile>(
);
PlayerProfileSchema.index({ puuid: 1, queueId: 1 }, { unique: true });
// 운영 조회용 (멘토 검색 자체는 Atlas Vector Search 인덱스 사용)
// 운영 조회용 (유사 유저 검색 자체는 Atlas Vector Search 인덱스 사용)
PlayerProfileSchema.index({ isSeed: 1, mainRole: 1, tier: 1 });
export type PlayerProfileDocument = HydratedDocument<PlayerProfile>;
@@ -2,14 +2,14 @@ import { HydratedDocument, Schema } from 'mongoose';
import { MongooseTimestamps } from './common';
/**
* - mentor-match: 유사 고티어 유저 Top-K (MVP 3)
* - similar-player: 플레이스타일이 비슷한 유저 Top-K (MVP 3)
* - champion-recommendation: Fit/Growth/Stretch 챔피언 추천 (MVP 4)
* - llm-feedback: LLM 생성 피드백 (MVP 5)
*/
export type RecommendationType =
'mentor-match' | 'champion-recommendation' | 'llm-feedback';
'similar-player' | 'champion-recommendation' | 'llm-feedback';
export const RECOMMENDATION_TYPES: RecommendationType[] = [
'mentor-match',
'similar-player',
'champion-recommendation',
'llm-feedback',
];
+43 -25
View File
@@ -3,8 +3,8 @@ import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import {
FEATURE_SCHEMA_VERSION,
type MentorMatchesDto,
type PlayerAnalysisDto,
type SimilarPlayersDto,
} from '@persona-lenz/shared';
import request from 'supertest';
import { App } from 'supertest/types';
@@ -15,7 +15,7 @@ import {
ANALYSIS_QUEUE_NAME,
SEED_COLLECTION_QUEUE_NAME,
} from './../src/modules/analysis/analysis.constants';
import { MentorMatchService } from './../src/modules/analysis/mentor-match.service';
import { SimilarPlayerService } from './../src/modules/analysis/similar-player.service';
import { ConnectionService } from './../src/modules/global/database/connection.service';
import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants';
import { SecretService } from './../src/modules/global/secret/secret.service';
@@ -25,8 +25,8 @@ describe('AppController (e2e)', () => {
let analysisQueueService: {
enqueueUserAnalysis: jest.Mock;
};
let mentorMatchService: {
findMentorMatches: jest.Mock;
let similarPlayerService: {
findSimilarPlayers: jest.Mock;
};
let connectionService: {
getModel: jest.Mock;
@@ -44,8 +44,8 @@ describe('AppController (e2e)', () => {
analysisQueueService = {
enqueueUserAnalysis: jest.fn(),
};
mentorMatchService = {
findMentorMatches: jest.fn(),
similarPlayerService = {
findSimilarPlayers: jest.fn(),
};
connectionService = {
getModel: jest.fn(),
@@ -57,8 +57,8 @@ describe('AppController (e2e)', () => {
.useValue(connectionService)
.overrideProvider(AnalysisQueueService)
.useValue(analysisQueueService)
.overrideProvider(MentorMatchService)
.useValue(mentorMatchService)
.overrideProvider(SimilarPlayerService)
.useValue(similarPlayerService)
.overrideProvider(SecretService)
.useValue({
get: jest.fn((key: string) => {
@@ -446,18 +446,19 @@ describe('AppController (e2e)', () => {
});
});
it('/api/players/:puuid/mentor-matches (GET) returns mentor matches with display Riot IDs', async () => {
mentorMatchService.findMentorMatches.mockResolvedValue({
it('/api/players/:puuid/similar-players (GET) returns similar players with display Riot IDs', async () => {
similarPlayerService.findSimilarPlayers.mockResolvedValue({
puuid: 'target-puuid',
queueId: 420,
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
matches: [
{
puuid: 'mentor-puuid',
puuid: 'similar-player-puuid',
similarityScore: 0.87,
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -465,16 +466,24 @@ describe('AppController (e2e)', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},
@@ -483,7 +492,7 @@ describe('AppController (e2e)', () => {
const accountFind = jest.fn(() =>
createLeanExec([
{
puuid: 'mentor-puuid',
puuid: 'similar-player-puuid',
gameName: '프리리',
tagLine: 'KR1',
},
@@ -494,17 +503,17 @@ describe('AppController (e2e)', () => {
});
const response = await request(app.getHttpServer())
.get('/api/players/target-puuid/mentor-matches?limit=3')
.get('/api/players/target-puuid/similar-players?limit=3')
.expect(200);
const responseBody = response.body as MentorMatchesDto;
const responseBody = response.body as SimilarPlayersDto;
expect(mentorMatchService.findMentorMatches).toHaveBeenCalledWith(
expect(similarPlayerService.findSimilarPlayers).toHaveBeenCalledWith(
'target-puuid',
420,
3,
);
expect(accountFind).toHaveBeenCalledWith({
puuid: { $in: ['mentor-puuid'] },
puuid: { $in: ['similar-player-puuid'] },
});
expect(responseBody).toEqual({
puuid: 'target-puuid',
@@ -512,7 +521,7 @@ describe('AppController (e2e)', () => {
profileUpdatedAt: '2026-07-02T00:00:00.000Z',
matches: [
{
mentorDisplayId: 'mentor-1',
displayId: 'similar-1',
riotId: {
gameName: '프리리',
tagLine: 'KR1',
@@ -521,6 +530,7 @@ describe('AppController (e2e)', () => {
finalScore: 0.81,
tier: 'CHALLENGER',
leaguePoints: 900,
tierComparison: 'higher',
mainRole: 'MIDDLE',
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
sampleGameCount: 40,
@@ -528,16 +538,24 @@ describe('AppController (e2e)', () => {
{
metricId: 'kda',
currentValue: 0.3,
mentorValue: 0.31,
otherValue: 0.31,
absoluteGap: 0.01,
},
],
gapMetrics: [
strongerMetrics: [
{
metricId: 'goldPerMin',
currentValue: 0.5,
mentorValue: 0.8,
mentorAdvantage: 0.3,
otherValue: 0.8,
lead: 0.3,
},
],
weakerMetrics: [
{
metricId: 'visionScorePerMin',
currentValue: 0.6,
otherValue: 0.4,
lead: 0.2,
},
],
},