장시간 Ref 행렬과 NPC 회귀 비용을 줄인다

This commit is contained in:
2026-09-04 08:59:10 +00:00
parent 07897d9765
commit 5d220de739
12 changed files with 253 additions and 11346 deletions
+41
View File
@@ -0,0 +1,41 @@
import type { City, MapDefinition } from '@sammo-ts/logic';
import { LARGE_TEST_MAP } from './largeTestMap.js';
const COMPACT_CITY_IDS = new Set([1, 2, 3, 4, 5]);
export const COMPACT_NPC_TEST_MAP: MapDefinition = {
id: 'compact_npc_test_map',
name: 'NPC 장기 시뮬레이션용 소형 맵',
cities: LARGE_TEST_MAP.cities
.filter((city) => COMPACT_CITY_IDS.has(city.id))
.map((city) => ({
...city,
connections: city.connections.filter((cityId) => COMPACT_CITY_IDS.has(cityId)),
})),
defaults: { ...LARGE_TEST_MAP.defaults },
};
export const buildCompactNpcTestCities = (): City[] =>
COMPACT_NPC_TEST_MAP.cities.map((city) => ({
id: city.id,
name: city.name,
nationId: 0,
level: city.level,
state: 0,
population: city.initial.population,
populationMax: city.max.population,
agriculture: city.initial.agriculture,
agricultureMax: city.max.agriculture,
commerce: city.initial.commerce,
commerceMax: city.max.commerce,
security: city.initial.security,
securityMax: city.max.security,
supplyState: 1,
frontState: 0,
defence: city.initial.defence,
defenceMax: city.max.defence,
wall: city.initial.wall,
wallMax: city.max.wall,
meta: { trust: 95 },
}));
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
import { DIPLOMACY_STATE } from '@sammo-ts/logic';
import { getTechLevel } from '@sammo-ts/logic/world/unitSet.js';
import { getTechCost, getTechLevel } from '@sammo-ts/logic/world/unitSet.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
import { COMPACT_NPC_TEST_MAP, buildCompactNpcTestCities } from './fixtures/compactNpcTestScenario.js';
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
const mockDate = new Date('0180-01-01T00:00:00Z');
@@ -45,7 +45,7 @@ const createNpcGeneral = (
npcState,
});
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
...city,
population: city.populationMax,
agriculture: city.agricultureMax,
@@ -63,9 +63,9 @@ const readTech = (nation: { meta: Record<string, unknown> }): number => {
describe('NPC 기술 연구 장기 시뮬레이션', () => {
it('기술이 상승하고 기술 등급 및 소모 금이 증가해야 한다', async () => {
const cities = buildLargeTestCities().map(maxCityStats);
const nation1CityIds = [1, 2, 3, 4];
const nation2CityIds = [5, 6, 7, 8, 9];
const cities = buildCompactNpcTestCities().map(maxCityStats);
const nation1CityIds = [1, 2];
const nation2CityIds = [3, 4, 5];
for (const city of cities) {
if (nation1CityIds.includes(city.id)) {
@@ -122,7 +122,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
1
)
);
for (let i = 0; i < 9; i += 1) {
for (let i = 0; i < 3; i += 1) {
generals.push(
createNpcGeneral(nextId++, cityId, nationId, 2, {
leadership: 80,
@@ -131,7 +131,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
})
);
}
for (let i = 0; i < 40; i += 1) {
for (let i = 0; i < 6; i += 1) {
generals.push(
createNpcGeneral(nextId++, cityId, nationId, 2, {
leadership: 70,
@@ -163,7 +163,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
power: 0,
level: 1,
typeCode: 'large_test_map_def',
meta: { tech: 0 },
meta: { tech: 950 },
},
{
id: 2,
@@ -176,7 +176,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
power: 0,
level: 1,
typeCode: 'large_test_map_def',
meta: { tech: 0 },
meta: { tech: 950 },
},
],
troops: [],
@@ -200,7 +200,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
],
events: [],
initialEvents: [],
map: LARGE_TEST_MAP as any,
map: COMPACT_NPC_TEST_MAP as any,
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
@@ -214,7 +214,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
minAvailableRecruitPop: 0,
maxTechLevel: 12000,
},
environment: { mapName: 'large_test_map', unitSet: 'default' },
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
},
scenarioMeta: {
startYear: 180,
@@ -239,7 +239,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
snapshot,
state,
schedule,
map: LARGE_TEST_MAP,
map: COMPACT_NPC_TEST_MAP,
});
const controlledGeneralId = nation1ChiefId;
@@ -261,17 +261,14 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
const firstGoldAfter = world.getGeneralById(controlledGeneralId)!.gold;
const firstRecruitCost = firstGoldBefore - firstGoldAfter;
expect(firstRecruitCost).toBeGreaterThan(0);
const firstTechValue = readTech(world.getNationById(1)! as { meta: Record<string, unknown> });
const firstTechLevel = getTechLevel(firstTechValue);
const techSnapshots: Array<{ year: number; tech1: number; tech2: number }> = [];
let pendingRecruit = false;
let pendingGoldBefore = 0;
let secondRecruitCost: number | null = null;
const shouldStop = () => {
const exceededSafetyLimit = () => {
const current = world.getState();
return current.currentYear > 230 || (current.currentYear === 230 && current.currentMonth >= 1);
return current.currentYear > 185 || (current.currentYear === 185 && current.currentMonth >= 1);
};
while (true) {
@@ -294,15 +291,18 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
const tech1 = readTech(nation1 as { meta: Record<string, unknown> });
const tech2 = readTech(nation2 as { meta: Record<string, unknown> });
if (current.currentMonth === 1) {
techSnapshots.push({ year: current.currentYear, tech1, tech2 });
}
techSnapshots.push({ year: current.currentYear, tech1, tech2 });
if (secondRecruitCost === null && getTechLevel(tech1) > firstTechLevel) {
if (secondRecruitCost === null && getTechLevel(tech1) > initialLevel) {
pendingRecruit = true;
}
if (shouldStop()) {
if (
(secondRecruitCost !== null &&
getTechLevel(tech1) > initialLevel &&
getTechLevel(tech2) > initialLevel) ||
exceededSafetyLimit()
) {
break;
}
}
@@ -322,8 +322,12 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
expect(finalTech2).toBeGreaterThan(initialTech2);
expect(getTechLevel(finalTech1)).toBeGreaterThan(initialLevel);
expect(getTechLevel(finalTech2)).toBeGreaterThanOrEqual(initialLevel);
expect(getTechCost(finalTech1)).toBeGreaterThan(getTechCost(initialTech1));
expect(secondRecruitCost).not.toBeNull();
expect(
secondRecruitCost,
`second recruit was not observed (tech1=${finalTech1}, tech2=${finalTech2}, level=${initialLevel})`
).not.toBeNull();
// Nation awards can occur in the same tick and make the general's net
// gold delta smaller than the recruitment price. Exact cost scaling is
// covered by the unit-set/action contract tests rather than this smoke.
@@ -7,7 +7,7 @@ import type { LogEntryDraft, TurnSchedule, UnitSetDefinition } from '@sammo-ts/l
import { DIPLOMACY_STATE, LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
import { COMPACT_NPC_TEST_MAP, buildCompactNpcTestCities } from './fixtures/compactNpcTestScenario.js';
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
import { NpcUnificationMemoryProfiler } from './helpers/npcUnificationMemoryProfiler.js';
@@ -28,8 +28,8 @@ const createNpcGeneral = (
role: {
items: { horse: null, weapon: null, book: null, item: null },
personality: null,
specialDomestic: null,
specialWar: null,
specialDomestic: id % 2 === 0 ? 'che_경작' : 'che_상재',
specialWar: id % 2 === 0 ? 'che_보병' : 'che_무쌍',
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: { killturn: 800 },
@@ -47,7 +47,7 @@ const createNpcGeneral = (
npcState: 2,
});
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
...city,
population: city.populationMax,
agriculture: city.agricultureMax,
@@ -156,7 +156,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
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);
const cities = buildCompactNpcTestCities().map(maxCityStats);
for (const city of cities) {
city.nationId = 0;
}
@@ -208,7 +208,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
};
const generals: TurnGeneral[] = [];
const initialGeneralCount = rankingAuditEnabled ? 150 : 300;
const initialGeneralCount = rankingAuditEnabled ? 150 : 60;
for (let i = 0; i < initialGeneralCount; i += 1) {
const cityId = cities[i % cities.length]!.id;
const stats =
@@ -217,6 +217,10 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
: { leadership: 75, strength: 10, intelligence: 75 };
generals.push(createNpcGeneral(i + 1, cityId, stats));
}
expect(new Set(generals.map((general) => general.role.specialDomestic))).toEqual(
new Set(['che_경작', 'che_상재'])
);
expect(new Set(generals.map((general) => general.role.specialWar))).toEqual(new Set(['che_보병', 'che_무쌍']));
const snapshot: TurnWorldSnapshot = {
generals: generals as any,
@@ -226,7 +230,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
diplomacy: [],
events: [],
initialEvents: [],
map: LARGE_TEST_MAP as any,
map: COMPACT_NPC_TEST_MAP as any,
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
@@ -239,7 +243,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
maxResourceActionAmount: 10000,
minAvailableRecruitPop: 0,
},
environment: { mapName: 'large_test_map', unitSet: 'default' },
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
},
scenarioMeta: {
startYear: 180,
@@ -305,45 +309,44 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
getCollectedLogsCount,
getCollectedLogsRange,
getAndClearCollectedLogs,
} =
await createTurnTestHarness({
snapshot,
state,
schedule,
map: LARGE_TEST_MAP,
worldRef,
extraCalendarHandlers: [unificationHandler],
collectLogs: true,
onActionResolved: (payload) => {
const currentWorld = worldRef.current;
if (currentWorld) {
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
const orphanCities = currentWorld
.listCities()
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
if (orphanCities.length > 0) {
throw new Error(
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
.map((city) => `${city.id}->${city.nationId}`)
.join(', ')}`
);
}
} = await createTurnTestHarness({
snapshot,
state,
schedule,
map: COMPACT_NPC_TEST_MAP,
worldRef,
extraCalendarHandlers: [unificationHandler],
collectLogs: true,
onActionResolved: (payload) => {
const currentWorld = worldRef.current;
if (currentWorld) {
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
const orphanCities = currentWorld
.listCities()
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
if (orphanCities.length > 0) {
throw new Error(
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
.map((city) => `${city.id}->${city.nationId}`)
.join(', ')}`
);
}
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
if (payload.kind === 'general') {
if (payload.actionKey === 'che_출병') {
sortieCount += 1;
}
return;
}
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
if (payload.kind === 'general') {
if (payload.actionKey === 'che_출병') {
sortieCount += 1;
}
if (payload.nationId) {
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
}
if (payload.actionKey === 'che_선전포고') {
declarationCount += 1;
}
},
});
return;
}
if (payload.nationId) {
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
}
if (payload.actionKey === 'che_선전포고') {
declarationCount += 1;
}
},
});
const memoryProfiler =
memoryProfileEnabled && worldRef.current
? new NpcUnificationMemoryProfiler(worldRef.current, reservedTurnStore)
@@ -410,6 +413,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
const foundedNations = world.listNations().filter((nation) => nation.level > 0);
expect(foundedNations.length).toBeGreaterThanOrEqual(2);
const foundedNationCount = foundedNations.length;
const foundedGenerals = world.listGenerals().filter((general) => general.nationId > 0);
expect(foundedGenerals.some((general) => general.role.specialDomestic !== null)).toBe(true);
expect(foundedGenerals.some((general) => general.role.specialWar !== null)).toBe(true);
memoryProfiler?.sample('nations-founded');
await runUntil(
@@ -436,7 +442,8 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
if (declarationCount === 0) {
await runUntil(
(current) => current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
(current) =>
current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
undefined,
observeProfileMonth
);
@@ -614,6 +621,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
const logs = getCollectedLogs();
const hasUnificationLog =
unificationLogObserved || logs.some((log) => log.text.includes('전토를 통일하였습니다.'));
if (!rankingAuditEnabled) {
expect(unifiedAt).not.toBeNull();
}
if (unifiedAt) {
expect(meta.isUnited).toBe(2);
expect(hasUnificationLog).toBe(true);
@@ -714,8 +724,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
startMonth: state.currentMonth,
});
const reportPath = resolve(
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ??
'test-results/npc-unification-memory.json'
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ?? 'test-results/npc-unification-memory.json'
);
mkdirSync(dirname(reportPath), { recursive: true });
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');