test: audit live best-general rankings
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { RANK_DATA_TYPES, rankDataMetaKey } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
|
||||
import type { GeneralMeta } from '@sammo-ts/logic';
|
||||
|
||||
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
|
||||
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
|
||||
const integration = describe.skipIf(!databaseUrl);
|
||||
const worldId = 992_400;
|
||||
const nationId = 992_400;
|
||||
const cityId = 992_400;
|
||||
const generalIds = Array.from({ length: 12 }, (_, index) => 992_401 + index);
|
||||
|
||||
const makeGeneral = (id: number): TurnGeneral => ({
|
||||
id,
|
||||
name: `랭킹감사${id}`,
|
||||
nationId,
|
||||
cityId,
|
||||
troopId: 0,
|
||||
stats: { leadership: 70, strength: 70, intelligence: 70 },
|
||||
turnTime: new Date('0190-01-01T00:10:00.000Z'),
|
||||
recentWarTime: null,
|
||||
role: {
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
},
|
||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||
meta: { killturn: 24 },
|
||||
penalty: {},
|
||||
officerLevel: 1,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
injury: 0,
|
||||
gold: 1_000,
|
||||
rice: 1_000,
|
||||
crew: 100,
|
||||
crewTypeId: 1,
|
||||
train: 100,
|
||||
atmos: 100,
|
||||
age: 30,
|
||||
npcState: 2,
|
||||
});
|
||||
|
||||
integration('best-general rank persistence', () => {
|
||||
let db: GamePrismaClient;
|
||||
let closeDb: (() => Promise<void>) | undefined;
|
||||
|
||||
const cleanup = async () => {
|
||||
await db.rankData.deleteMany({ where: { generalId: { in: generalIds } } });
|
||||
await db.general.deleteMany({ where: { id: { in: generalIds } } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: nationId } });
|
||||
await db.worldState.deleteMany({ where: { id: worldId } });
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||
await connector.connect();
|
||||
db = connector.prisma;
|
||||
closeDb = () => connector.disconnect();
|
||||
await cleanup();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await closeDb?.();
|
||||
});
|
||||
|
||||
it('flushes every ranking field for twelve active NPCs and keeps the ordered top ten', async () => {
|
||||
await db.worldState.create({
|
||||
data: {
|
||||
id: worldId,
|
||||
scenarioCode: 'best-general-rank-persistence',
|
||||
currentYear: 190,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
config: {},
|
||||
meta: {},
|
||||
},
|
||||
});
|
||||
await db.nation.create({
|
||||
data: {
|
||||
id: nationId,
|
||||
name: '랭킹감사국',
|
||||
color: '#330000',
|
||||
level: 1,
|
||||
},
|
||||
});
|
||||
await db.city.create({
|
||||
data: {
|
||||
id: cityId,
|
||||
name: '랭킹감사성',
|
||||
level: 5,
|
||||
nationId,
|
||||
population: 10_000,
|
||||
populationMax: 20_000,
|
||||
agriculture: 1_000,
|
||||
agricultureMax: 2_000,
|
||||
commerce: 1_000,
|
||||
commerceMax: 2_000,
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
defence: 1_000,
|
||||
defenceMax: 2_000,
|
||||
wall: 1_000,
|
||||
wallMax: 2_000,
|
||||
region: 1,
|
||||
},
|
||||
});
|
||||
const initialGenerals = generalIds.map(makeGeneral);
|
||||
await db.general.createMany({
|
||||
data: initialGenerals.map((general) => ({
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
nationId,
|
||||
cityId,
|
||||
npcState: general.npcState,
|
||||
leadership: general.stats.leadership,
|
||||
strength: general.stats.strength,
|
||||
intel: general.stats.intelligence,
|
||||
turnTime: general.turnTime,
|
||||
meta: general.meta,
|
||||
})),
|
||||
});
|
||||
|
||||
const state: TurnWorldState = {
|
||||
id: worldId,
|
||||
currentYear: 190,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
lastTurnTime: new Date('0190-01-01T00:00:00.000Z'),
|
||||
meta: {},
|
||||
};
|
||||
const snapshot: TurnWorldSnapshot = {
|
||||
generals: initialGenerals,
|
||||
cities: [],
|
||||
nations: [],
|
||||
troops: [],
|
||||
diplomacy: [],
|
||||
events: [],
|
||||
initialEvents: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: '랭킹 감사 지도',
|
||||
cities: [],
|
||||
},
|
||||
scenarioConfig: {
|
||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||
iconPath: '',
|
||||
map: {},
|
||||
const: {},
|
||||
environment: { mapName: 'test', unitSet: 'test' },
|
||||
},
|
||||
};
|
||||
const world = new InMemoryTurnWorld(state, snapshot, {
|
||||
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
|
||||
});
|
||||
for (const [index, generalId] of generalIds.entries()) {
|
||||
const value = index + 1;
|
||||
const meta: GeneralMeta = { killturn: 24 };
|
||||
for (const type of RANK_DATA_TYPES) {
|
||||
if (type !== 'experience' && type !== 'dedication') {
|
||||
meta[rankDataMetaKey(type)] = value;
|
||||
}
|
||||
}
|
||||
world.updateGeneral(generalId, {
|
||||
experience: value,
|
||||
dedication: value,
|
||||
meta,
|
||||
});
|
||||
}
|
||||
|
||||
const dbHooks = await createDatabaseTurnHooks(databaseUrl!, world);
|
||||
try {
|
||||
await dbHooks.hooks.flushChanges?.({
|
||||
lastTurnTime: state.lastTurnTime.toISOString(),
|
||||
processedGenerals: generalIds.length,
|
||||
processedTurns: generalIds.length,
|
||||
durationMs: 0,
|
||||
partial: false,
|
||||
});
|
||||
} finally {
|
||||
await dbHooks.close();
|
||||
}
|
||||
|
||||
const rows = await db.rankData.findMany({
|
||||
where: { generalId: { in: generalIds } },
|
||||
orderBy: [{ type: 'asc' }, { value: 'desc' }, { generalId: 'asc' }],
|
||||
});
|
||||
expect(rows).toHaveLength(generalIds.length * RANK_DATA_TYPES.length);
|
||||
for (const type of RANK_DATA_TYPES) {
|
||||
const topTen = rows.filter((row) => row.type === type).slice(0, 10);
|
||||
expect(topTen.map((row) => row.value)).toEqual([12, 11, 10, 9, 8, 7, 6, 5, 4, 3]);
|
||||
expect(topTen.map((row) => row.generalId)).toEqual(generalIds.slice(2).reverse());
|
||||
}
|
||||
|
||||
const persistedGenerals = await db.general.findMany({
|
||||
where: { id: { in: generalIds } },
|
||||
orderBy: { experience: 'desc' },
|
||||
select: { id: true, experience: true, dedication: true, meta: true },
|
||||
});
|
||||
expect(persistedGenerals.slice(0, 10).map((general) => general.id)).toEqual(generalIds.slice(2).reverse());
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { RANK_DATA_TYPES, rankDataMetaKey } from '@sammo-ts/common';
|
||||
import type { LogEntryDraft, TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
||||
import { DIPLOMACY_STATE, LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
|
||||
@@ -153,6 +154,7 @@ const dumpWorldStatus = (world: InMemoryTurnWorld, label: string) => {
|
||||
describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
it('건국, 선포, 출병, 점령과 장기 국가 감소가 안정적으로 진행되어야 한다', async () => {
|
||||
const memoryProfileEnabled = process.env.NPC_UNIFICATION_MEMORY_PROFILE === '1';
|
||||
const rankingAuditEnabled = process.env.NPC_RANKING_AUDIT === '1';
|
||||
const profileStartedAtMs = performance.now();
|
||||
const cities = buildLargeTestCities().map(maxCityStats);
|
||||
for (const city of cities) {
|
||||
@@ -206,7 +208,8 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
};
|
||||
|
||||
const generals: TurnGeneral[] = [];
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
const initialGeneralCount = rankingAuditEnabled ? 150 : 300;
|
||||
for (let i = 0; i < initialGeneralCount; i += 1) {
|
||||
const cityId = cities[i % cities.length]!.id;
|
||||
const stats =
|
||||
i % 2 === 0
|
||||
@@ -580,6 +583,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
}
|
||||
|
||||
if (
|
||||
(rankingAuditEnabled && sortieCount >= 50) ||
|
||||
world.getState().currentYear > 260 ||
|
||||
(world.getState().currentYear === 260 && world.getState().currentMonth >= 1)
|
||||
) {
|
||||
@@ -595,11 +599,85 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
expect(meta.isUnited).toBe(2);
|
||||
expect(hasUnificationLog).toBe(true);
|
||||
} else {
|
||||
expect(prevNationCount).toBeLessThan(foundedNationCount);
|
||||
if (!rankingAuditEnabled) {
|
||||
expect(prevNationCount).toBeLessThan(foundedNationCount);
|
||||
}
|
||||
expect(meta.isUnited ?? 0).toBe(0);
|
||||
}
|
||||
expect(sortieCount).toBeGreaterThan(0);
|
||||
|
||||
if (rankingAuditEnabled) {
|
||||
const rankingAudit = RANK_DATA_TYPES.map((type) => {
|
||||
const entries = world
|
||||
.listGenerals()
|
||||
.map((general) => {
|
||||
const rawValue =
|
||||
type === 'experience'
|
||||
? general.experience
|
||||
: type === 'dedication'
|
||||
? general.dedication
|
||||
: general.meta[rankDataMetaKey(type)];
|
||||
const value = typeof rawValue === 'number' && Number.isFinite(rawValue) ? rawValue : 0;
|
||||
return { generalId: general.id, name: general.name, value };
|
||||
})
|
||||
.filter((entry) => entry.value > 0)
|
||||
.sort((lhs, rhs) => rhs.value - lhs.value || lhs.generalId - rhs.generalId)
|
||||
.slice(0, 10);
|
||||
return { type, entries };
|
||||
});
|
||||
const byType = new Map(rankingAudit.map((entry) => [entry.type, entry.entries]));
|
||||
expect(byType.get('firenum')).toHaveLength(0);
|
||||
for (const type of [
|
||||
'experience',
|
||||
'dedication',
|
||||
'warnum',
|
||||
'killnum',
|
||||
'deathnum',
|
||||
'killcrew',
|
||||
'deathcrew',
|
||||
'killcrew_person',
|
||||
'deathcrew_person',
|
||||
'dex1',
|
||||
'dex2',
|
||||
'dex3',
|
||||
'dex4',
|
||||
'dex5',
|
||||
] as const) {
|
||||
expect(byType.get(type), type).toHaveLength(10);
|
||||
}
|
||||
const reportPath = resolve(
|
||||
process.env.NPC_RANKING_AUDIT_REPORT_PATH ?? 'test-results/npc-ranking-audit.json'
|
||||
);
|
||||
mkdirSync(dirname(reportPath), { recursive: true });
|
||||
writeFileSync(
|
||||
reportPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
year: world.getState().currentYear,
|
||||
month: world.getState().currentMonth,
|
||||
initialGeneralCount,
|
||||
finalGeneralCount: world.listGenerals().length,
|
||||
declarationCount,
|
||||
sortieCount,
|
||||
rankingAudit,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}\n`,
|
||||
'utf8'
|
||||
);
|
||||
console.log(
|
||||
`[NPC_RANKING_AUDIT]${JSON.stringify({
|
||||
reportPath,
|
||||
year: world.getState().currentYear,
|
||||
month: world.getState().currentMonth,
|
||||
declarationCount,
|
||||
sortieCount,
|
||||
topTenTypes: Array.from(byType.values()).filter((entries) => entries.length === 10).length,
|
||||
})}`
|
||||
);
|
||||
}
|
||||
|
||||
if (memoryProfiler) {
|
||||
expect(typeof globalThis.gc).toBe('function');
|
||||
expect(unifiedAt).not.toBeNull();
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { TurnSchedule } from '@sammo-ts/logic';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||
import { buildPersistedRankRows } from '../src/turn/rankData.js';
|
||||
|
||||
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
|
||||
|
||||
@@ -116,6 +117,46 @@ describe('tournament world commands', () => {
|
||||
expect(world.getGeneralById(1)?.meta).not.toHaveProperty('rank_betwin');
|
||||
});
|
||||
|
||||
it('records all four tournament types and NPC betting for at least ten generals', async () => {
|
||||
const generals = Array.from({ length: 12 }, (_, index) => buildGeneral(index + 1));
|
||||
const world = buildWorld(generals);
|
||||
const handler = createTurnDaemonCommandHandler({ world });
|
||||
|
||||
for (const tournamentType of [0, 1, 2, 3] as const) {
|
||||
for (const general of generals) {
|
||||
const result = await handler.handle({
|
||||
type: 'tournamentMatchResult',
|
||||
tournamentType,
|
||||
attackerId: general.id,
|
||||
defenderId: (general.id % generals.length) + 1,
|
||||
result: 'attacker',
|
||||
});
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
}
|
||||
}
|
||||
await handler.handle({
|
||||
type: 'adjustGeneralMeta',
|
||||
reason: 'tournamentNpcBet',
|
||||
adjustments: generals.map((general) => ({
|
||||
generalId: general.id,
|
||||
metaDelta: { betgold: 1_000 },
|
||||
})),
|
||||
});
|
||||
await handler.handle({
|
||||
type: 'tournamentBettingPayout',
|
||||
bettingId: 1,
|
||||
payouts: generals.map((general) => ({ generalId: general.id, amount: 2_000 })),
|
||||
});
|
||||
|
||||
for (const type of ['ttw', 'tlw', 'tsw', 'tiw', 'betgold', 'betwin', 'betwingold'] as const) {
|
||||
const positiveRows = world
|
||||
.listGenerals()
|
||||
.flatMap(buildPersistedRankRows)
|
||||
.filter((row) => row.type === type && row.value > 0);
|
||||
expect(positiveRows, type).toHaveLength(12);
|
||||
}
|
||||
});
|
||||
|
||||
it('enforces a command-specific minimum remaining gold atomically', async () => {
|
||||
const world = buildWorld([buildGeneral(1)]);
|
||||
const handler = createTurnDaemonCommandHandler({ world });
|
||||
|
||||
Reference in New Issue
Block a user