Cache mentor match recommendations
This commit is contained in:
1 parent
1db1d1d1d6
commit
4f70e07cb7
2 files changed
+251
-5
No files matched your search
@@ -16,6 +16,22 @@ function createAggregateExec<T>(value: T) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createSortedLeanExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
sort: jest.fn(() => ({
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createUpdateExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function createVector(fillValue = 0.5): number[] {
|
function createVector(fillValue = 0.5): number[] {
|
||||||
return Array.from({ length: VECTOR_DIMENSION }, () => fillValue);
|
return Array.from({ length: VECTOR_DIMENSION }, () => fillValue);
|
||||||
}
|
}
|
||||||
@@ -60,6 +76,8 @@ describe('MentorMatchService', () => {
|
|||||||
it('queries high-tier seed profiles with Atlas Vector Search and reranks candidates', async () => {
|
it('queries high-tier seed profiles with Atlas Vector Search and reranks candidates', async () => {
|
||||||
const currentProfile = createProfile();
|
const currentProfile = createProfile();
|
||||||
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||||
|
const recommendationFindOne = jest.fn(() => createSortedLeanExec(null));
|
||||||
|
const updateOne = jest.fn(() => createUpdateExec({ acknowledged: true }));
|
||||||
const aggregate = jest.fn(() =>
|
const aggregate = jest.fn(() =>
|
||||||
createAggregateExec([
|
createAggregateExec([
|
||||||
createProfile({
|
createProfile({
|
||||||
@@ -100,7 +118,13 @@ describe('MentorMatchService', () => {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
const service = new MentorMatchService({
|
const service = new MentorMatchService({
|
||||||
getModel: jest.fn().mockResolvedValue({ findOne, aggregate }),
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerProfile'
|
||||||
|
? { findOne, aggregate }
|
||||||
|
: { findOne: recommendationFindOne, updateOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
} as unknown as ConnectionService);
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
const result = await service.findMentorMatches('target-puuid', 420, 2);
|
const result = await service.findMentorMatches('target-puuid', 420, 2);
|
||||||
@@ -201,6 +225,96 @@ describe('MentorMatchService', () => {
|
|||||||
mentorAdvantage: 0.3,
|
mentorAdvantage: 0.3,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'mentor-match',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'mentor-match',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
result: { matches: result.matches },
|
||||||
|
evidence: {
|
||||||
|
candidateCount: 2,
|
||||||
|
vectorSearchIndex: 'player_profile_vector_index',
|
||||||
|
},
|
||||||
|
generatedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns a fresh cached mentor recommendation without running vector search', async () => {
|
||||||
|
const currentProfile = createProfile();
|
||||||
|
const cachedMatch = {
|
||||||
|
puuid: 'cached-mentor',
|
||||||
|
similarityScore: 0.87,
|
||||||
|
finalScore: 0.81,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
||||||
|
sampleGameCount: 40,
|
||||||
|
similarMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
mentorValue: 0.31,
|
||||||
|
absoluteGap: 0.01,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
gapMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
mentorValue: 0.8,
|
||||||
|
mentorAdvantage: 0.3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||||
|
const aggregate = jest.fn();
|
||||||
|
const recommendationFindOne = jest.fn(() =>
|
||||||
|
createSortedLeanExec({
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
result: { matches: [cachedMatch] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const updateOne = jest.fn();
|
||||||
|
const service = new MentorMatchService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerProfile'
|
||||||
|
? { findOne, aggregate }
|
||||||
|
: { findOne: recommendationFindOne, updateOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
const result = await service.findMentorMatches('target-puuid', 420, 10);
|
||||||
|
|
||||||
|
expect(recommendationFindOne).toHaveBeenCalledWith({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'mentor-match',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
});
|
||||||
|
expect(aggregate).not.toHaveBeenCalled();
|
||||||
|
expect(updateOne).not.toHaveBeenCalled();
|
||||||
|
expect(result).toEqual({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
matches: [cachedMatch],
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws when the player profile has not been built yet', async () => {
|
it('throws when the player profile has not been built yet', async () => {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Injectable, NotFoundException } from '@nestjs/common';
|
|||||||
import {
|
import {
|
||||||
FEATURE_SCHEMA_VERSION,
|
FEATURE_SCHEMA_VERSION,
|
||||||
METRICS,
|
METRICS,
|
||||||
|
ROLES,
|
||||||
VECTOR_DIMENSION,
|
VECTOR_DIMENSION,
|
||||||
type MetricDefinition,
|
type MetricDefinition,
|
||||||
type Role,
|
type Role,
|
||||||
@@ -45,6 +46,10 @@ interface MentorVectorSearchRecord extends Omit<MentorProfileRecord, 'vector'> {
|
|||||||
score?: number;
|
score?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface MentorRecommendationCacheRecord {
|
||||||
|
result?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MentorMatchService {
|
export class MentorMatchService {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
@@ -56,6 +61,9 @@ export class MentorMatchService {
|
|||||||
): Promise<MentorMatchesResult> {
|
): Promise<MentorMatchesResult> {
|
||||||
const playerProfileModel =
|
const playerProfileModel =
|
||||||
await this.connectionService.getModel('playerProfile');
|
await this.connectionService.getModel('playerProfile');
|
||||||
|
const recommendationModel =
|
||||||
|
await this.connectionService.getModel('recommendation');
|
||||||
|
const normalizedLimit = this.normalizeLimit(requestedLimit);
|
||||||
const currentProfile = await playerProfileModel
|
const currentProfile = await playerProfileModel
|
||||||
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
|
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
|
||||||
.lean<MentorProfileRecord>()
|
.lean<MentorProfileRecord>()
|
||||||
@@ -65,6 +73,26 @@ export class MentorMatchService {
|
|||||||
throw new NotFoundException('Player profile not found.');
|
throw new NotFoundException('Player profile not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const cacheFilter = this.createMentorRecommendationFilter(
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
currentProfile.updatedAt,
|
||||||
|
);
|
||||||
|
const cachedRecommendation = await recommendationModel
|
||||||
|
.findOne(cacheFilter)
|
||||||
|
.sort({ generatedAt: -1 })
|
||||||
|
.lean<MentorRecommendationCacheRecord>()
|
||||||
|
.exec();
|
||||||
|
const cachedMatches = this.extractCachedMentorMatches(cachedRecommendation);
|
||||||
|
if (cachedMatches) {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
matches: cachedMatches.slice(0, normalizedLimit),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (currentProfile.vector.length !== VECTOR_DIMENSION) {
|
if (currentProfile.vector.length !== VECTOR_DIMENSION) {
|
||||||
return {
|
return {
|
||||||
puuid,
|
puuid,
|
||||||
@@ -80,14 +108,58 @@ export class MentorMatchService {
|
|||||||
)
|
)
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
|
const matches = candidates
|
||||||
|
.map((candidate) => this.toMentorMatch(currentProfile, candidate))
|
||||||
|
.sort((left, right) => right.finalScore - left.finalScore)
|
||||||
|
.slice(0, normalizedLimit);
|
||||||
|
|
||||||
|
await recommendationModel
|
||||||
|
.updateOne(
|
||||||
|
cacheFilter,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
type: 'mentor-match',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
result: { matches },
|
||||||
|
evidence: {
|
||||||
|
candidateCount: candidates.length,
|
||||||
|
vectorSearchIndex: MENTOR_VECTOR_SEARCH_INDEX_NAME,
|
||||||
|
},
|
||||||
|
generatedAt: new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
puuid,
|
puuid,
|
||||||
queueId,
|
queueId,
|
||||||
profileUpdatedAt: currentProfile.updatedAt,
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
matches: candidates
|
matches,
|
||||||
.map((candidate) => this.toMentorMatch(currentProfile, candidate))
|
};
|
||||||
.sort((left, right) => right.finalScore - left.finalScore)
|
}
|
||||||
.slice(0, this.normalizeLimit(requestedLimit)),
|
|
||||||
|
private createMentorRecommendationFilter(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
profileUpdatedAt: Date,
|
||||||
|
): {
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
type: 'mentor-match';
|
||||||
|
featureSchemaVersion: number;
|
||||||
|
profileUpdatedAt: Date;
|
||||||
|
} {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
type: 'mentor-match',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -314,4 +386,64 @@ export class MentorMatchService {
|
|||||||
if (!Number.isFinite(value)) return 0;
|
if (!Number.isFinite(value)) return 0;
|
||||||
return Math.max(0, Math.min(1, value));
|
return Math.max(0, Math.min(1, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private extractCachedMentorMatches(
|
||||||
|
recommendation: MentorRecommendationCacheRecord | null,
|
||||||
|
): MentorMatch[] | null {
|
||||||
|
const matches = recommendation?.result?.matches;
|
||||||
|
if (!Array.isArray(matches)) return null;
|
||||||
|
if (!matches.every((match) => this.isCachedMentorMatch(match))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isCachedMentorMatch(value: unknown): value is MentorMatch {
|
||||||
|
const record = this.asRecord(value);
|
||||||
|
if (!record) return false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
typeof record.puuid === 'string' &&
|
||||||
|
this.isFiniteNumber(record.similarityScore) &&
|
||||||
|
this.isFiniteNumber(record.finalScore) &&
|
||||||
|
typeof record.mainRole === 'string' &&
|
||||||
|
ROLES.includes(record.mainRole as Role) &&
|
||||||
|
Array.isArray(record.mainChampions) &&
|
||||||
|
this.isFiniteNumber(record.sampleGameCount) &&
|
||||||
|
this.isCachedMetricComparisonArray(
|
||||||
|
record.similarMetrics,
|
||||||
|
'absoluteGap',
|
||||||
|
) &&
|
||||||
|
this.isCachedMetricComparisonArray(record.gapMetrics, 'mentorAdvantage')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isCachedMetricComparisonArray(
|
||||||
|
value: unknown,
|
||||||
|
scoreFieldName: 'absoluteGap' | 'mentorAdvantage',
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
Array.isArray(value) &&
|
||||||
|
value.every((entry) => {
|
||||||
|
const record = this.asRecord(entry);
|
||||||
|
return (
|
||||||
|
record !== null &&
|
||||||
|
typeof record.metricId === 'string' &&
|
||||||
|
this.isFiniteNumber(record.currentValue) &&
|
||||||
|
this.isFiniteNumber(record.mentorValue) &&
|
||||||
|
this.isFiniteNumber(record[scoreFieldName])
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private asRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isFiniteNumber(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user