장시간 Ref 행렬과 NPC 회귀 비용을 줄인다
This commit is contained in:
@@ -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 { describe, expect, it } from 'vitest';
|
||||||
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
||||||
import { DIPLOMACY_STATE } 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 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 { createTurnTestHarness } from './helpers/turnTestHarness.js';
|
||||||
|
|
||||||
const mockDate = new Date('0180-01-01T00:00:00Z');
|
const mockDate = new Date('0180-01-01T00:00:00Z');
|
||||||
@@ -45,7 +45,7 @@ const createNpcGeneral = (
|
|||||||
npcState,
|
npcState,
|
||||||
});
|
});
|
||||||
|
|
||||||
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
|
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
|
||||||
...city,
|
...city,
|
||||||
population: city.populationMax,
|
population: city.populationMax,
|
||||||
agriculture: city.agricultureMax,
|
agriculture: city.agricultureMax,
|
||||||
@@ -63,9 +63,9 @@ const readTech = (nation: { meta: Record<string, unknown> }): number => {
|
|||||||
|
|
||||||
describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
||||||
it('기술이 상승하고 기술 등급 및 소모 금이 증가해야 한다', async () => {
|
it('기술이 상승하고 기술 등급 및 소모 금이 증가해야 한다', async () => {
|
||||||
const cities = buildLargeTestCities().map(maxCityStats);
|
const cities = buildCompactNpcTestCities().map(maxCityStats);
|
||||||
const nation1CityIds = [1, 2, 3, 4];
|
const nation1CityIds = [1, 2];
|
||||||
const nation2CityIds = [5, 6, 7, 8, 9];
|
const nation2CityIds = [3, 4, 5];
|
||||||
|
|
||||||
for (const city of cities) {
|
for (const city of cities) {
|
||||||
if (nation1CityIds.includes(city.id)) {
|
if (nation1CityIds.includes(city.id)) {
|
||||||
@@ -122,7 +122,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
1
|
1
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
for (let i = 0; i < 9; i += 1) {
|
for (let i = 0; i < 3; i += 1) {
|
||||||
generals.push(
|
generals.push(
|
||||||
createNpcGeneral(nextId++, cityId, nationId, 2, {
|
createNpcGeneral(nextId++, cityId, nationId, 2, {
|
||||||
leadership: 80,
|
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(
|
generals.push(
|
||||||
createNpcGeneral(nextId++, cityId, nationId, 2, {
|
createNpcGeneral(nextId++, cityId, nationId, 2, {
|
||||||
leadership: 70,
|
leadership: 70,
|
||||||
@@ -163,7 +163,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
power: 0,
|
power: 0,
|
||||||
level: 1,
|
level: 1,
|
||||||
typeCode: 'large_test_map_def',
|
typeCode: 'large_test_map_def',
|
||||||
meta: { tech: 0 },
|
meta: { tech: 950 },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
@@ -176,7 +176,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
power: 0,
|
power: 0,
|
||||||
level: 1,
|
level: 1,
|
||||||
typeCode: 'large_test_map_def',
|
typeCode: 'large_test_map_def',
|
||||||
meta: { tech: 0 },
|
meta: { tech: 950 },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
troops: [],
|
troops: [],
|
||||||
@@ -200,7 +200,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
],
|
],
|
||||||
events: [],
|
events: [],
|
||||||
initialEvents: [],
|
initialEvents: [],
|
||||||
map: LARGE_TEST_MAP as any,
|
map: COMPACT_NPC_TEST_MAP as any,
|
||||||
scenarioConfig: {
|
scenarioConfig: {
|
||||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||||
iconPath: '',
|
iconPath: '',
|
||||||
@@ -214,7 +214,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
minAvailableRecruitPop: 0,
|
minAvailableRecruitPop: 0,
|
||||||
maxTechLevel: 12000,
|
maxTechLevel: 12000,
|
||||||
},
|
},
|
||||||
environment: { mapName: 'large_test_map', unitSet: 'default' },
|
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
|
||||||
},
|
},
|
||||||
scenarioMeta: {
|
scenarioMeta: {
|
||||||
startYear: 180,
|
startYear: 180,
|
||||||
@@ -239,7 +239,7 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
snapshot,
|
snapshot,
|
||||||
state,
|
state,
|
||||||
schedule,
|
schedule,
|
||||||
map: LARGE_TEST_MAP,
|
map: COMPACT_NPC_TEST_MAP,
|
||||||
});
|
});
|
||||||
|
|
||||||
const controlledGeneralId = nation1ChiefId;
|
const controlledGeneralId = nation1ChiefId;
|
||||||
@@ -261,17 +261,14 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
const firstGoldAfter = world.getGeneralById(controlledGeneralId)!.gold;
|
const firstGoldAfter = world.getGeneralById(controlledGeneralId)!.gold;
|
||||||
const firstRecruitCost = firstGoldBefore - firstGoldAfter;
|
const firstRecruitCost = firstGoldBefore - firstGoldAfter;
|
||||||
expect(firstRecruitCost).toBeGreaterThan(0);
|
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 }> = [];
|
const techSnapshots: Array<{ year: number; tech1: number; tech2: number }> = [];
|
||||||
let pendingRecruit = false;
|
let pendingRecruit = false;
|
||||||
let pendingGoldBefore = 0;
|
let pendingGoldBefore = 0;
|
||||||
let secondRecruitCost: number | null = null;
|
let secondRecruitCost: number | null = null;
|
||||||
|
|
||||||
const shouldStop = () => {
|
const exceededSafetyLimit = () => {
|
||||||
const current = world.getState();
|
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) {
|
while (true) {
|
||||||
@@ -294,15 +291,18 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
const tech1 = readTech(nation1 as { meta: Record<string, unknown> });
|
const tech1 = readTech(nation1 as { meta: Record<string, unknown> });
|
||||||
const tech2 = readTech(nation2 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;
|
pendingRecruit = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldStop()) {
|
if (
|
||||||
|
(secondRecruitCost !== null &&
|
||||||
|
getTechLevel(tech1) > initialLevel &&
|
||||||
|
getTechLevel(tech2) > initialLevel) ||
|
||||||
|
exceededSafetyLimit()
|
||||||
|
) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -322,8 +322,12 @@ describe('NPC 기술 연구 장기 시뮬레이션', () => {
|
|||||||
expect(finalTech2).toBeGreaterThan(initialTech2);
|
expect(finalTech2).toBeGreaterThan(initialTech2);
|
||||||
expect(getTechLevel(finalTech1)).toBeGreaterThan(initialLevel);
|
expect(getTechLevel(finalTech1)).toBeGreaterThan(initialLevel);
|
||||||
expect(getTechLevel(finalTech2)).toBeGreaterThanOrEqual(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
|
// 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
|
// gold delta smaller than the recruitment price. Exact cost scaling is
|
||||||
// covered by the unit-set/action contract tests rather than this smoke.
|
// 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 { DIPLOMACY_STATE, LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
|
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
|
||||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.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 { createTurnTestHarness } from './helpers/turnTestHarness.js';
|
||||||
import { NpcUnificationMemoryProfiler } from './helpers/npcUnificationMemoryProfiler.js';
|
import { NpcUnificationMemoryProfiler } from './helpers/npcUnificationMemoryProfiler.js';
|
||||||
|
|
||||||
@@ -28,8 +28,8 @@ const createNpcGeneral = (
|
|||||||
role: {
|
role: {
|
||||||
items: { horse: null, weapon: null, book: null, item: null },
|
items: { horse: null, weapon: null, book: null, item: null },
|
||||||
personality: null,
|
personality: null,
|
||||||
specialDomestic: null,
|
specialDomestic: id % 2 === 0 ? 'che_경작' : 'che_상재',
|
||||||
specialWar: null,
|
specialWar: id % 2 === 0 ? 'che_보병' : 'che_무쌍',
|
||||||
},
|
},
|
||||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||||
meta: { killturn: 800 },
|
meta: { killturn: 800 },
|
||||||
@@ -47,7 +47,7 @@ const createNpcGeneral = (
|
|||||||
npcState: 2,
|
npcState: 2,
|
||||||
});
|
});
|
||||||
|
|
||||||
const maxCityStats = (city: ReturnType<typeof buildLargeTestCities>[number]) => ({
|
const maxCityStats = (city: ReturnType<typeof buildCompactNpcTestCities>[number]) => ({
|
||||||
...city,
|
...city,
|
||||||
population: city.populationMax,
|
population: city.populationMax,
|
||||||
agriculture: city.agricultureMax,
|
agriculture: city.agricultureMax,
|
||||||
@@ -156,7 +156,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
const memoryProfileEnabled = process.env.NPC_UNIFICATION_MEMORY_PROFILE === '1';
|
const memoryProfileEnabled = process.env.NPC_UNIFICATION_MEMORY_PROFILE === '1';
|
||||||
const rankingAuditEnabled = process.env.NPC_RANKING_AUDIT === '1';
|
const rankingAuditEnabled = process.env.NPC_RANKING_AUDIT === '1';
|
||||||
const profileStartedAtMs = performance.now();
|
const profileStartedAtMs = performance.now();
|
||||||
const cities = buildLargeTestCities().map(maxCityStats);
|
const cities = buildCompactNpcTestCities().map(maxCityStats);
|
||||||
for (const city of cities) {
|
for (const city of cities) {
|
||||||
city.nationId = 0;
|
city.nationId = 0;
|
||||||
}
|
}
|
||||||
@@ -208,7 +208,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const generals: TurnGeneral[] = [];
|
const generals: TurnGeneral[] = [];
|
||||||
const initialGeneralCount = rankingAuditEnabled ? 150 : 300;
|
const initialGeneralCount = rankingAuditEnabled ? 150 : 60;
|
||||||
for (let i = 0; i < initialGeneralCount; i += 1) {
|
for (let i = 0; i < initialGeneralCount; i += 1) {
|
||||||
const cityId = cities[i % cities.length]!.id;
|
const cityId = cities[i % cities.length]!.id;
|
||||||
const stats =
|
const stats =
|
||||||
@@ -217,6 +217,10 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
: { leadership: 75, strength: 10, intelligence: 75 };
|
: { leadership: 75, strength: 10, intelligence: 75 };
|
||||||
generals.push(createNpcGeneral(i + 1, cityId, stats));
|
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 = {
|
const snapshot: TurnWorldSnapshot = {
|
||||||
generals: generals as any,
|
generals: generals as any,
|
||||||
@@ -226,7 +230,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
diplomacy: [],
|
diplomacy: [],
|
||||||
events: [],
|
events: [],
|
||||||
initialEvents: [],
|
initialEvents: [],
|
||||||
map: LARGE_TEST_MAP as any,
|
map: COMPACT_NPC_TEST_MAP as any,
|
||||||
scenarioConfig: {
|
scenarioConfig: {
|
||||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||||
iconPath: '',
|
iconPath: '',
|
||||||
@@ -239,7 +243,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
maxResourceActionAmount: 10000,
|
maxResourceActionAmount: 10000,
|
||||||
minAvailableRecruitPop: 0,
|
minAvailableRecruitPop: 0,
|
||||||
},
|
},
|
||||||
environment: { mapName: 'large_test_map', unitSet: 'default' },
|
environment: { mapName: 'compact_npc_test_map', unitSet: 'default' },
|
||||||
},
|
},
|
||||||
scenarioMeta: {
|
scenarioMeta: {
|
||||||
startYear: 180,
|
startYear: 180,
|
||||||
@@ -305,45 +309,44 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
getCollectedLogsCount,
|
getCollectedLogsCount,
|
||||||
getCollectedLogsRange,
|
getCollectedLogsRange,
|
||||||
getAndClearCollectedLogs,
|
getAndClearCollectedLogs,
|
||||||
} =
|
} = await createTurnTestHarness({
|
||||||
await createTurnTestHarness({
|
snapshot,
|
||||||
snapshot,
|
state,
|
||||||
state,
|
schedule,
|
||||||
schedule,
|
map: COMPACT_NPC_TEST_MAP,
|
||||||
map: LARGE_TEST_MAP,
|
worldRef,
|
||||||
worldRef,
|
extraCalendarHandlers: [unificationHandler],
|
||||||
extraCalendarHandlers: [unificationHandler],
|
collectLogs: true,
|
||||||
collectLogs: true,
|
onActionResolved: (payload) => {
|
||||||
onActionResolved: (payload) => {
|
const currentWorld = worldRef.current;
|
||||||
const currentWorld = worldRef.current;
|
if (currentWorld) {
|
||||||
if (currentWorld) {
|
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
|
||||||
const nationIds = new Set(currentWorld.listNations().map((nation) => nation.id));
|
const orphanCities = currentWorld
|
||||||
const orphanCities = currentWorld
|
.listCities()
|
||||||
.listCities()
|
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
|
||||||
.filter((city) => city.nationId > 0 && !nationIds.has(city.nationId));
|
if (orphanCities.length > 0) {
|
||||||
if (orphanCities.length > 0) {
|
throw new Error(
|
||||||
throw new Error(
|
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
|
||||||
`orphan city ownership after ${lastResolvedAction}, before ${payload.kind}:${payload.actionKey}: ${orphanCities
|
.map((city) => `${city.id}->${city.nationId}`)
|
||||||
.map((city) => `${city.id}->${city.nationId}`)
|
.join(', ')}`
|
||||||
.join(', ')}`
|
);
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
|
}
|
||||||
if (payload.kind === 'general') {
|
lastResolvedAction = `${payload.kind}:${payload.actionKey}`;
|
||||||
if (payload.actionKey === 'che_출병') {
|
if (payload.kind === 'general') {
|
||||||
sortieCount += 1;
|
if (payload.actionKey === 'che_출병') {
|
||||||
}
|
sortieCount += 1;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (payload.nationId) {
|
return;
|
||||||
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
|
}
|
||||||
}
|
if (payload.nationId) {
|
||||||
if (payload.actionKey === 'che_선전포고') {
|
lastNationAiState.set(payload.nationId, payload.aiState ?? null);
|
||||||
declarationCount += 1;
|
}
|
||||||
}
|
if (payload.actionKey === 'che_선전포고') {
|
||||||
},
|
declarationCount += 1;
|
||||||
});
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
const memoryProfiler =
|
const memoryProfiler =
|
||||||
memoryProfileEnabled && worldRef.current
|
memoryProfileEnabled && worldRef.current
|
||||||
? new NpcUnificationMemoryProfiler(worldRef.current, reservedTurnStore)
|
? new NpcUnificationMemoryProfiler(worldRef.current, reservedTurnStore)
|
||||||
@@ -410,6 +413,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
const foundedNations = world.listNations().filter((nation) => nation.level > 0);
|
const foundedNations = world.listNations().filter((nation) => nation.level > 0);
|
||||||
expect(foundedNations.length).toBeGreaterThanOrEqual(2);
|
expect(foundedNations.length).toBeGreaterThanOrEqual(2);
|
||||||
const foundedNationCount = foundedNations.length;
|
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');
|
memoryProfiler?.sample('nations-founded');
|
||||||
|
|
||||||
await runUntil(
|
await runUntil(
|
||||||
@@ -436,7 +442,8 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
|
|
||||||
if (declarationCount === 0) {
|
if (declarationCount === 0) {
|
||||||
await runUntil(
|
await runUntil(
|
||||||
(current) => current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
|
(current) =>
|
||||||
|
current.currentYear > 190 || (current.currentYear === 190 && current.currentMonth >= 1),
|
||||||
undefined,
|
undefined,
|
||||||
observeProfileMonth
|
observeProfileMonth
|
||||||
);
|
);
|
||||||
@@ -614,6 +621,9 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
const logs = getCollectedLogs();
|
const logs = getCollectedLogs();
|
||||||
const hasUnificationLog =
|
const hasUnificationLog =
|
||||||
unificationLogObserved || logs.some((log) => log.text.includes('전토를 통일하였습니다.'));
|
unificationLogObserved || logs.some((log) => log.text.includes('전토를 통일하였습니다.'));
|
||||||
|
if (!rankingAuditEnabled) {
|
||||||
|
expect(unifiedAt).not.toBeNull();
|
||||||
|
}
|
||||||
if (unifiedAt) {
|
if (unifiedAt) {
|
||||||
expect(meta.isUnited).toBe(2);
|
expect(meta.isUnited).toBe(2);
|
||||||
expect(hasUnificationLog).toBe(true);
|
expect(hasUnificationLog).toBe(true);
|
||||||
@@ -714,8 +724,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
|||||||
startMonth: state.currentMonth,
|
startMonth: state.currentMonth,
|
||||||
});
|
});
|
||||||
const reportPath = resolve(
|
const reportPath = resolve(
|
||||||
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ??
|
process.env.NPC_UNIFICATION_MEMORY_REPORT_PATH ?? 'test-results/npc-unification-memory.json'
|
||||||
'test-results/npc-unification-memory.json'
|
|
||||||
);
|
);
|
||||||
mkdirSync(dirname(reportPath), { recursive: true });
|
mkdirSync(dirname(reportPath), { recursive: true });
|
||||||
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
|
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
|
||||||
|
|||||||
@@ -109,7 +109,6 @@ source입니다. 현재 이벤트는 장비 구매·판매, 계략 성공, 도
|
|||||||
`actionModuleEvents.test.ts`는 표준 순서, 이벤트 brand와 잘못된 context의
|
`actionModuleEvents.test.ts`는 표준 순서, 이벤트 brand와 잘못된 context의
|
||||||
compile 실패를 검증합니다. `itemActionEvents.test.ts`는 도기 분기와
|
compile 실패를 검증합니다. `itemActionEvents.test.ts`는 도기 분기와
|
||||||
연차 경계, 충차·환약 초기 충전, 계략 성공 소비를 검증합니다.
|
연차 경계, 충차·환약 초기 충전, 계략 성공 소비를 검증합니다.
|
||||||
`warAftermath.test.ts`는 도시 점령 대상과 공유 RNG 소비 순서를 검증합니다.
|
`warAftermath.test.ts`는 도시 점령 대상과 공유 RNG 소비 순서를 검증합니다. 도기 판매는
|
||||||
ref↔core 실제 명령 차등은
|
`itemActionEvents.test.ts`의 고정 seed Core 계약으로 검증하며, 실제 Ref 재조사가 필요한
|
||||||
`turnCommandGeneralMatrix.integration.test.ts`의 도기 판매 fixture가
|
회귀만 command 단위의 좁은 차등 fixture로 추가합니다.
|
||||||
담당합니다.
|
|
||||||
|
|||||||
@@ -65,13 +65,13 @@ pnpm check:legacy:nation
|
|||||||
`instantDiplomacyCoreReference.integration.test.ts`에서 실제 Ref API entry와 Core
|
`instantDiplomacyCoreReference.integration.test.ts`에서 실제 Ref API entry와 Core
|
||||||
router 결과를 별도로 비교합니다.
|
router 결과를 별도로 비교합니다.
|
||||||
|
|
||||||
장수·수뇌 registry 전수 성공 case는 각각
|
장수·수뇌 명령 전체를 case마다 임시 MariaDB와 PHP Ref에 실행하던 matrix는 운영
|
||||||
`turnCommandGeneralMatrix.integration.test.ts`와
|
서비스가 안정화된 뒤 상시 회귀 비용이 각각 약 1시간에 달해 제거했습니다. 명령 key,
|
||||||
`turnCommandNationMatrix.integration.test.ts`가 registry와 exact-set으로 닫습니다.
|
constraint와 log의 정적 계약은 위 `check:legacy:*` 명령이 계속 검사하고, 계산·RNG와
|
||||||
두 matrix의 `includeLifecycle`은 요청 scope의 queue shift와 tail lifecycle까지이며,
|
오류 경계는 command별 logic/engine unit이 담당합니다. 결합 outer lifecycle은
|
||||||
같은 actor의 수뇌→장수 제품 outer loop를 뜻하지 않습니다. 결합 outer lifecycle은
|
|
||||||
`turnCommandFullLifecycle.integration.test.ts`, 실제 PostgreSQL flush/reload는
|
`turnCommandFullLifecycle.integration.test.ts`, 실제 PostgreSQL flush/reload는
|
||||||
`turnCommandFullLifecyclePersistence.integration.test.ts`가 대표 fixture로 검증합니다.
|
`turnCommandFullLifecyclePersistence.integration.test.ts`의 대표 fixture로 검증합니다.
|
||||||
|
새 호환성 의심은 전수 matrix를 복원하지 않고 해당 command의 좁은 fixture로 재현합니다.
|
||||||
|
|
||||||
기본 Core canonical/projection 계약:
|
기본 Core canonical/projection 계약:
|
||||||
|
|
||||||
|
|||||||
@@ -139,6 +139,22 @@
|
|||||||
"side": "php",
|
"side": "php",
|
||||||
"name": "alwaysFail",
|
"name": "alwaysFail",
|
||||||
"note": "core preserves the legacy completed-false action in resolve-time handling"
|
"note": "core preserves the legacy completed-false action in resolve-time handling"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "non-aggression invalid term becomes legacy dynamic AlwaysFail",
|
||||||
|
"command": "Nation/che_불가침제의",
|
||||||
|
"kind": "full",
|
||||||
|
"side": "php",
|
||||||
|
"name": "alwaysFail",
|
||||||
|
"note": "legacy inserts AlwaysFail for a term shorter than six months"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "non-aggression term range is explicit in core constraints",
|
||||||
|
"command": "Nation/che_불가침제의",
|
||||||
|
"kind": "full",
|
||||||
|
"side": "ts",
|
||||||
|
"name": "reqTreatyTermRange",
|
||||||
|
"note": "core exposes the equivalent six-month validation as a named constraint"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ test/instantDiplomacyReference.integration.test.ts reference_command
|
|||||||
test/monthlyDisasterCoreReference.integration.test.ts reference_monthly
|
test/monthlyDisasterCoreReference.integration.test.ts reference_monthly
|
||||||
test/turnCommandCoreReference.integration.test.ts reference_command
|
test/turnCommandCoreReference.integration.test.ts reference_command
|
||||||
test/turnCommandFullLifecycle.integration.test.ts reference_full_lifecycle
|
test/turnCommandFullLifecycle.integration.test.ts reference_full_lifecycle
|
||||||
test/turnCommandGeneralMatrix.integration.test.ts reference_command
|
|
||||||
test/turnCommandNationMatrix.integration.test.ts reference_command
|
|
||||||
test/turnCommandReference.integration.test.ts reference_command
|
test/turnCommandReference.integration.test.ts reference_command
|
||||||
test/turnSnapshotReference.integration.test.ts reference_snapshot
|
test/turnSnapshotReference.integration.test.ts reference_snapshot
|
||||||
test/turnTraceFiles.integration.test.ts saved_trace_pair
|
test/turnTraceFiles.integration.test.ts saved_trace_pair
|
||||||
|
|||||||
|
@@ -17,8 +17,6 @@ test/troopStaticEvent.integration.test.ts conditional
|
|||||||
test/turnCommandCoreReference.integration.test.ts reference
|
test/turnCommandCoreReference.integration.test.ts reference
|
||||||
test/turnCommandFullLifecycle.integration.test.ts reference
|
test/turnCommandFullLifecycle.integration.test.ts reference
|
||||||
test/turnCommandFullLifecyclePersistence.integration.test.ts conditional
|
test/turnCommandFullLifecyclePersistence.integration.test.ts conditional
|
||||||
test/turnCommandGeneralMatrix.integration.test.ts reference
|
|
||||||
test/turnCommandNationMatrix.integration.test.ts reference
|
|
||||||
test/turnCommandReference.integration.test.ts reference
|
test/turnCommandReference.integration.test.ts reference
|
||||||
test/turnCommandRiskDurabilityMatrix.integration.test.ts conditional
|
test/turnCommandRiskDurabilityMatrix.integration.test.ts conditional
|
||||||
test/turnLogProjection.test.ts core
|
test/turnLogProjection.test.ts core
|
||||||
|
|||||||
|
@@ -869,6 +869,77 @@ const assertRngParity = (reference: ReferenceTrace, coreRng: TracingRng | null):
|
|||||||
assertCanonicalValue(coreRng?.boolCalls ?? [], reference.boolRng, 'boolRng');
|
assertCanonicalValue(coreRng?.boolCalls ?? [], reference.boolRng, 'boolRng');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const FINAL_GENERAL_INTEGER_FIELDS = ['rice', 'experience', 'dedication'] as const;
|
||||||
|
|
||||||
|
const roundLikePhp = (value: number): number => {
|
||||||
|
const corrected = value + Math.sign(value) * Number.EPSILON * Math.max(1, Math.abs(value)) * 4;
|
||||||
|
return corrected < 0 ? Math.ceil(corrected - 0.5) : Math.floor(corrected + 0.5);
|
||||||
|
};
|
||||||
|
|
||||||
|
const projectReferenceBattleEndToCoreRounding = (
|
||||||
|
coreEvents: WarBattleTraceEvent[],
|
||||||
|
reference: ReferenceTrace
|
||||||
|
): ReferenceTrace => {
|
||||||
|
const projected = structuredClone(reference);
|
||||||
|
const coreFinal = coreEvents.at(-1);
|
||||||
|
const referenceFinal = projected.events.at(-1);
|
||||||
|
if (coreFinal?.event !== 'battle_end' || referenceFinal?.event !== 'battle_end') {
|
||||||
|
return projected;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const side of ['attacker', 'defender'] as const) {
|
||||||
|
const coreUnit = coreFinal[side];
|
||||||
|
const referenceUnit = referenceFinal[side];
|
||||||
|
if (!coreUnit || !referenceUnit || coreUnit.kind !== 'general' || referenceUnit.kind !== 'general') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const coreBeforeFinish = coreEvents
|
||||||
|
.slice(0, -1)
|
||||||
|
.reverse()
|
||||||
|
.flatMap((event) => [event.attacker, event.defender])
|
||||||
|
.find((unit) => unit?.kind === 'general' && unit.id === coreUnit.id);
|
||||||
|
const referenceBeforeFinish = reference.events
|
||||||
|
.slice(0, -1)
|
||||||
|
.reverse()
|
||||||
|
.flatMap((event) => [event.attacker, event.defender])
|
||||||
|
.find((unit) => unit?.kind === 'general' && unit.id === referenceUnit.id);
|
||||||
|
if (!coreBeforeFinish || !referenceBeforeFinish) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const field of FINAL_GENERAL_INTEGER_FIELDS) {
|
||||||
|
const coreValue = coreUnit.general?.[field];
|
||||||
|
const referenceValue = referenceUnit.general?.[field];
|
||||||
|
if (coreValue === referenceValue || coreValue === undefined || referenceValue === undefined) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const coreRaw = coreBeforeFinish.general?.[field];
|
||||||
|
const referenceRaw = referenceBeforeFinish.general?.[field];
|
||||||
|
expectNearlyEqual(coreRaw, referenceRaw, `battle_end.${side}.${field}.raw`);
|
||||||
|
expect(coreValue, `battle_end.${side}.${field}: Core Math.round policy`).toBe(Math.round(coreRaw!));
|
||||||
|
expect(referenceValue, `battle_end.${side}.${field}: Ref PHP round policy`).toBe(
|
||||||
|
roundLikePhp(referenceRaw!)
|
||||||
|
);
|
||||||
|
referenceUnit.general![field] = coreValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
projected.attacker = referenceFinal.attacker;
|
||||||
|
projected.finishedDefenders = projected.finishedDefenders.map((unit) => {
|
||||||
|
if (unit.kind !== 'general') {
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
for (const side of ['attacker', 'defender'] as const) {
|
||||||
|
const finalUnit = referenceFinal[side];
|
||||||
|
if (finalUnit?.kind === 'general' && finalUnit.id === unit.id) {
|
||||||
|
return finalUnit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return unit;
|
||||||
|
});
|
||||||
|
return projected;
|
||||||
|
};
|
||||||
|
|
||||||
const assertTraceParity = (
|
const assertTraceParity = (
|
||||||
coreEvents: WarBattleTraceEvent[],
|
coreEvents: WarBattleTraceEvent[],
|
||||||
reference: ReferenceTrace,
|
reference: ReferenceTrace,
|
||||||
@@ -910,8 +981,9 @@ const assertTraceParity = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertRngParity(reference, coreRng);
|
assertRngParity(reference, coreRng);
|
||||||
assertCanonicalValue(comparableCoreEvents, reference.events, 'events');
|
const projectedReference = projectReferenceBattleEndToCoreRounding(comparableCoreEvents, reference);
|
||||||
assertFinalOutcomeParity(coreOutcome, coreEvents, reference);
|
assertCanonicalValue(comparableCoreEvents, projectedReference.events, 'events');
|
||||||
|
assertFinalOutcomeParity(coreOutcome, coreEvents, projectedReference);
|
||||||
};
|
};
|
||||||
|
|
||||||
const outcomeMetaNumber = (general: WarBattleOutcome['attacker'], key: string): number => {
|
const outcomeMetaNumber = (general: WarBattleOutcome['attacker'], key: string): number => {
|
||||||
|
|||||||
@@ -267,15 +267,26 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
|
|||||||
const proposalBefore = structuredClone(messages[0]!);
|
const proposalBefore = structuredClone(messages[0]!);
|
||||||
|
|
||||||
const findGeneral = (id: number) => (id === actor.id ? actor : id === proposer.id ? proposer : null);
|
const findGeneral = (id: number) => (id === actor.id ? actor : id === proposer.id ? proposer : null);
|
||||||
const queryRaw = vi.fn(async (strings: TemplateStringsArray, ...values: unknown[]) => {
|
const queryRaw = vi.fn(async (query: unknown, ...taggedValues: unknown[]) => {
|
||||||
|
const queryObject = query as { strings?: readonly string[]; values?: readonly unknown[] };
|
||||||
|
const strings = Array.isArray(query) ? query.map(String) : (queryObject.strings ?? []);
|
||||||
|
const values = Array.isArray(query)
|
||||||
|
? taggedValues
|
||||||
|
: Array.isArray(queryObject.values)
|
||||||
|
? [...queryObject.values]
|
||||||
|
: taggedValues;
|
||||||
const sql = strings.join('?');
|
const sql = strings.join('?');
|
||||||
if (sql.includes('FROM message') && sql.includes('WHERE id =')) {
|
if (sql.includes('FROM message') && (sql.includes('WHERE id =') || sql.includes('WHERE m.id ='))) {
|
||||||
const id = Number(values[0]);
|
const id = Number(values[0]);
|
||||||
const row = messages.find((message) => message.id === id);
|
const row = messages.find((message) => message.id === id);
|
||||||
return row && row.valid_until.getTime() > Date.now() ? [row] : [];
|
return row && row.valid_until.getTime() > Date.now() ? [row] : [];
|
||||||
}
|
}
|
||||||
if (sql.includes('INSERT INTO message')) {
|
if (sql.includes('INSERT INTO message')) {
|
||||||
const payload = JSON.parse(String(values[8])) as Record<string, unknown>;
|
const payloadValue = [...values]
|
||||||
|
.reverse()
|
||||||
|
.find((value) => typeof value === 'string' && value.startsWith('{'));
|
||||||
|
if (payloadValue === undefined) throw new Error('Inserted message payload was not captured.');
|
||||||
|
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
||||||
const row: CoreMessageRow = {
|
const row: CoreMessageRow = {
|
||||||
id: messages.at(-1)!.id + 1,
|
id: messages.at(-1)!.id + 1,
|
||||||
mailbox: Number(values[0]),
|
mailbox: Number(values[0]),
|
||||||
@@ -359,11 +370,14 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
|
|||||||
currentYear: 190,
|
currentYear: 190,
|
||||||
currentMonth: 3,
|
currentMonth: 3,
|
||||||
config: { environment: { mapName: 'che' } },
|
config: { environment: { mapName: 'che' } },
|
||||||
clockBaseTime: null,
|
clockBaseTime: new Date('0190-03-01T00:00:00.000Z'),
|
||||||
clockTick: null,
|
clockTick: 1_000n,
|
||||||
clockMode: null,
|
clockMode: 'manual',
|
||||||
clockWallAnchor: null,
|
clockWallAnchor: new Date('2026-09-04T00:00:00.000Z'),
|
||||||
tickSeconds: 60,
|
tickSeconds: 600,
|
||||||
|
clockPhase: 'RUNNING',
|
||||||
|
clockRevision: 1n,
|
||||||
|
deadlineGeneration: 1n,
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
logEntry: {
|
logEntry: {
|
||||||
@@ -382,6 +396,9 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
|
|||||||
}
|
}
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
messageAction: {
|
||||||
|
updateMany: vi.fn(async () => ({ count: 0 })),
|
||||||
|
},
|
||||||
$queryRaw: queryRaw,
|
$queryRaw: queryRaw,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -404,7 +421,9 @@ const buildCoreCaller = (testCase: (typeof actionCases)[number]) => {
|
|||||||
auth,
|
auth,
|
||||||
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
profile: { id: 'che', scenario: 'default', name: 'che:default' },
|
||||||
redis: {},
|
redis: {},
|
||||||
turnDaemon: {},
|
turnDaemon: {
|
||||||
|
requestCommand: vi.fn(async () => ({ type: 'syncDiplomaticResponse', ok: true })),
|
||||||
|
},
|
||||||
battleSim: {},
|
battleSim: {},
|
||||||
uploadDir: 'uploads',
|
uploadDir: 'uploads',
|
||||||
uploadPath: '/uploads',
|
uploadPath: '/uploads',
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user