1
0
Fork 0
polaris-task-force/tests/int/tech-research-tick.int.spec.ts
Z8MB1E 938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler
only reuses worker processes between isolate:false tasks, so per-file fork
spawning made clone+boot costs unavoidable at stage 2):

- config: workers branch runs pool=forks with isolate:false, cap 8 via
  VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs),
  failure-marker reporter, and idempotent setupFiles chain
- vitest-worker-setup: one template clone PER FORK PROCESS named by pid
  (VITEST_WORKER_ID churns per task, which silently re-cloned per file);
  DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3)
- vitest.setup: once-per-process serial test URI markers; afterEach
  useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock
  module factories mid-file); logging absorber for fire-and-forget event
  writes that reject after their spec's cleanup deleted fixture users
- helpers/get-test-payload.ts: memoized Payload boot shared across files
  in a fork; codemod converted all 91 self-booting specs mechanically
- pinned opt-outs (own boot + comments): game-structures-labor-route,
  mission-reminder, notification-inbox-scope (jwtSign writes leak into
  the shared instance's auth state across files)
- promotion-nominations: create the superuser before its rank ladder so
  the Users-hook Recruit rank gets leading orderable tokens (its
  top-of-ladder guard needs Col to remain ladder-max on fresh clones);
  operation-economy: itemType-scope the market-state assertion (asset
  and resource ids collide as bare integers under per-fork databases)

Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s
vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4
note: globalTeardown config no longer exists; teardown returns from
globalSetup.
2026-10-21 12:54:30 -04:00

559 lines
19 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { GameStructure, LaborClassification, Structure, Technology, User } from "@/payload-types";
import { processTechTick } from "@/lib/tech/tick";
let payload: Payload;
const RUN = `trt-${Date.now().toString(36)}`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
const HOUR = 60 * 60 * 1000;
/**
* Tech tick engine: ballot lifecycle, tally weights, storage drain, ETA,
* completion, guards, and idempotency. Timestamps are injected via the tick's
* `now` parameter, so no sleeping is involved.
*/
describe("tech tick (research engine)", () => {
const createdUserIds: number[] = [];
const createdTechIds: number[] = [];
const cleanupQualificationIds: number[] = [];
let baseTime: Date;
const createUser = async (name: string) => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${name}`,
discordUsername: `${RUN}-${name}`,
displayName: name.toUpperCase(),
steamId: `76561198${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
createdUserIds.push(user.id);
return user;
};
const createTechnology = async (overrides: Record<string, any> = {}) => {
const tech = (await payload.create({
collection: "technologies",
data: {
name: `${RUN} tech`,
type: "upgrade",
summary: "Test technology",
approvalStatus: "approved",
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 100, resources: [] },
...overrides,
},
overrideAccess: true,
depth: 0,
})) as unknown as Technology;
createdTechIds.push(tech.id);
return tech;
};
const setResearchEnabled = async (enabled: boolean) => {
await payload.updateGlobal({
slug: "game-rules",
data: { research: { enabled } },
overrideAccess: true,
});
};
const grantIntelligenceQualification = async (user: User) => {
const qualification = (await payload.find({
collection: "qualifications",
where: { name: { equals: "Intelligence" } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
let qualificationId = qualification.docs[0]?.id;
if (qualificationId == null) {
const created = (await payload.create({
collection: "qualifications",
data: { name: "Intelligence" },
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
qualificationId = created.id;
cleanupQualificationIds.push(created.id);
}
const profile = (await payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
await payload.update({
collection: "profiles",
id: profile.docs[0].id,
data: { progression: { qualifications: [qualificationId] } },
overrideAccess: true,
depth: 0,
});
};
/** Create the blueprint + operational staffed facility + researcher staffing. */
const setupFacility = async (options?: {
storage?: { resourceId: number; amount: number }[];
slots?: number;
speedModifier?: number;
researchers?: number;
materialResourceId?: number;
}) => {
const blueprint = (await payload.create({
collection: "structures",
data: {
name: `${RUN} lab blueprint`,
codeName: `${RUN}-lab`,
description: LEXICAL_EMPTY as any,
category: "civilian",
approvalStatus: "approved",
materials: options?.materialResourceId
? [{ resource: options.materialResourceId, amount: 1 }]
: [],
constructionDurationMinutes: 60,
terrainType: "land",
maxHealth: 100,
isResearchFacility: true,
researchSlots: options?.slots ?? 1,
researchSpeedModifier: options?.speedModifier ?? 0,
},
overrideAccess: true,
depth: 0,
})) as unknown as Structure;
// Instance copies the research defaults from the blueprint (step-1 hook).
const structure = (await payload.create({
collection: "game-structures",
data: {
name: `${RUN} lab`,
type: blueprint.id,
constructionStatus: "complete",
storedResources: (options?.storage ?? []).map((row, index) => ({
resource: row.resourceId,
amount: row.amount,
gridX: index,
gridY: 0,
})),
},
overrideAccess: true,
depth: 0,
})) as unknown as GameStructure;
expect(structure.isResearchFacility).toBe(true);
expect(structure.researchSlots).toBe(options?.slots ?? 1);
expect(Number(structure.researchSpeedModifier ?? 0)).toBe(options?.speedModifier ?? 0);
const classification = (await payload.create({
collection: "labor-classifications",
data: { name: `${RUN} Researchers`, key: "researcher" },
overrideAccess: true,
depth: 0,
})) as unknown as LaborClassification;
await payload.create({
collection: "npc-staffing",
data: {
structure: structure.id,
positionType: "labor",
positionTitle: "Research crew",
laborClassification: classification.id,
headcount: options?.researchers ?? 2,
salary: 0,
status: "active",
},
overrideAccess: true,
depth: 0,
});
return { blueprint, structure, classification };
};
beforeAll(async () => {
payload = await getTestPayload();
baseTime = new Date(Date.UTC(2026, 9, 20, 12, 0, 0));
});
afterAll(async () => {
await setResearchEnabled(false).catch(() => {});
for (const id of createdTechIds) {
await payload.delete({ collection: "technologies", id, overrideAccess: true }).catch(() => {});
}
for (const id of createdUserIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
});
it("does nothing when the master gate is off", async () => {
await setResearchEnabled(false);
const result = await processTechTick(payload, baseTime);
expect(result.enabled).toBe(false);
const ballots = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
expect(ballots.totalDocs).toBe(0);
});
it("opens a ballot with eligible options once capacity exists, and completes the full lifecycle", async () => {
await setResearchEnabled(true);
// Costs the facility can cover.
const resource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} element`,
codeName: `${RUN}-element`,
approvalStatus: "approved",
type: "physical",
baseValue: 10,
rarity: "common",
unitOfMeasure: "units",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
tradeable: true,
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
const { structure } = await setupFacility({
slots: 1,
speedModifier: 0.1,
researchers: 2,
materialResourceId: resource.id,
storage: [{ resourceId: resource.id, amount: 50 }],
});
const winner = await createTechnology({
name: `${RUN} winner`,
researchCosts: {
minimumResearchDuration: 10,
maximumResearchDuration: 100,
resources: [{ resource: resource.id, amount: 30 }],
},
});
const loser = await createTechnology({
name: `${RUN} loser`,
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 40, resources: [] },
});
const gated = await createTechnology({
name: `${RUN} gated`,
requirements: {
prerequisiteTechnologies: [{ requiresAnd: { technology: [winner.id] }, requiresOr: { technology: [] } }],
},
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 20, resources: [] },
});
// --- open ---------------------------------------------------------------
const openResult = await processTechTick(payload, baseTime);
expect(openResult.opened).toBe(1);
const ballots = await payload.find({
collection: "tech-ballots",
where: { status: { equals: "open" } },
limit: 5,
depth: 0,
overrideAccess: true,
});
expect(ballots.totalDocs).toBeGreaterThanOrEqual(1);
const ballot = ballots.docs[ballots.docs.length - 1];
const optionIds = ballot.options.map((o) => (typeof o.technology === "object" ? o.technology.id : o.technology));
expect(optionIds).toContain(winner.id);
expect(optionIds).toContain(loser.id);
expect(optionIds).not.toContain(gated.id); // prereq not researched yet
expect(Date.parse(ballot.closesAt)).toBe(baseTime.getTime() + 288 * 10 * 60 * 1000);
// --- vote: one intel vote (x2) beats one regular vote --------------------
const member = await createUser("member");
const intel = await createUser("intel");
await grantIntelligenceQualification(intel);
await payload.create({
collection: "tech-ballot-votes",
data: { ballot: ballot.id, user: member.id, technology: loser.id },
overrideAccess: true,
depth: 0,
});
await payload.create({
collection: "tech-ballot-votes",
data: { ballot: ballot.id, user: intel.id, technology: winner.id },
overrideAccess: true,
depth: 0,
});
// --- resolve at close ----------------------------------------------------
const closeTime = new Date(Date.parse(ballot.closesAt) + 1000);
const resolveResult = await processTechTick(payload, closeTime);
expect(resolveResult.resolved).toBe(1);
const closedBallot = await payload.findByID({
collection: "tech-ballots",
id: ballot.id,
depth: 0,
overrideAccess: true,
});
expect(closedBallot.status).toBe("closed");
const winnerId =
typeof closedBallot.winner === "object" && closedBallot.winner !== null
? closedBallot.winner.id
: closedBallot.winner;
expect(winnerId).toBe(winner.id);
const snapshot = closedBallot.tallySnapshot as any;
expect(snapshot.counts[winner.id].weighted).toBe(2);
expect(snapshot.counts[loser.id].weighted).toBe(1);
// Queued research exists; slot is occupied so no second ballot opened.
const queuedRes = await payload.find({
collection: "tech-researches",
where: { technology: { equals: winner.id }, status: { equals: "queued" } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(queuedRes.totalDocs).toBe(1);
const stillOpen = await payload.find({
collection: "tech-ballots",
where: { status: { in: ["open", "extended"] } },
limit: 5,
depth: 0,
overrideAccess: true,
});
expect(stillOpen.docs.filter((b) => b.id !== ballot.id)).toHaveLength(0);
// --- advance: drain storage, stamp ETA ------------------------------------
const advanceResult = await processTechTick(payload, closeTime);
expect(advanceResult.started).toBe(1);
const activeResearch = await payload.findByID({
collection: "tech-researches",
id: queuedRes.docs[0].id,
depth: 0,
overrideAccess: true,
});
expect(activeResearch.status).toBe("active");
// totalModifier = 0.1 facility + 2 researchers x 0.0001 = 0.1002
// base 100 ticks -> round(89.98) = 90 ticks -> 90 x 10 minutes = 15h
expect(Date.parse(String(activeResearch.etaAt))).toBe(closeTime.getTime() + 15 * HOUR);
const drained = await payload.findByID({
collection: "game-structures",
id: structure.id,
depth: 0,
overrideAccess: true,
});
const storedTotal = (drained.storedResources ?? []).reduce((sum, row) => sum + row.amount, 0);
expect(storedTotal).toBe(20); // 50 - 30
// --- complete at ETA -------------------------------------------------------
const completeTime = new Date(Date.parse(String(activeResearch.etaAt)) + 1000);
const completeResult = await processTechTick(payload, completeTime);
expect(completeResult.completed).toBe(1);
// The gated technology became eligible, and the slot freed in the same
// sweep, so the next ballot opens immediately after resolution.
expect(completeResult.opened).toBe(1);
const researchedTech = await payload.findByID({
collection: "technologies",
id: winner.id,
depth: 0,
overrideAccess: true,
});
expect(researchedTech.researchedAt).toBeTruthy();
// Idempotent: a second sweep completes nothing again and opens no extra
// ballot (one ballot at a time).
const secondPass = await processTechTick(payload, new Date(completeTime.getTime() + HOUR));
expect(secondPass.completed).toBe(0);
expect(secondPass.opened).toBe(0);
}, 60_000);
it("extends a zero-turnout ballot once, then auto-starts the cheapest option", async () => {
await setResearchEnabled(true);
const cheap = await createTechnology({ name: `${RUN} cheap` });
const pricey = await createTechnology({
name: `${RUN} pricey`,
researchCosts: {
minimumResearchDuration: 10,
maximumResearchDuration: 20,
resources: [{ resource: (await firstResourceId()) ?? 0, amount: 999 }],
},
});
// Close any leftover open ballots from earlier specs by resolving at a far
// future time with no votes: first pass extends, second auto-starts.
const t1 = new Date(Date.UTC(2027, 0, 1, 0, 0, 0));
let openRes = await payload.find({
collection: "tech-ballots",
where: { status: { in: ["open", "extended"] } },
limit: 5,
depth: 0,
overrideAccess: true,
});
// Ensure there is an open ballot to exercise (opens one if capacity free).
if (openRes.totalDocs === 0) {
await processTechTick(payload, t1);
openRes = await payload.find({
collection: "tech-ballots",
where: { status: { in: ["open", "extended"] } },
limit: 5,
depth: 0,
overrideAccess: true,
});
}
const target = openRes.docs[openRes.docs.length - 1];
expect(target).toBeTruthy();
const afterFirst = await processTechTick(payload, new Date(Date.parse(target.closesAt) + 1000));
expect(afterFirst.extended + afterFirst.resolved).toBeGreaterThanOrEqual(1);
const mid = await payload.findByID({
collection: "tech-ballots",
id: target.id,
depth: 0,
overrideAccess: true,
});
let resolvedBallot = mid;
if (mid.status !== "closed") {
// Extended once; close again for the auto-start fallback.
const afterSecond = await processTechTick(payload, new Date(Date.parse(mid.closesAt) + 1000));
expect(afterSecond.resolved).toBe(1);
resolvedBallot = await payload.findByID({
collection: "tech-ballots",
id: target.id,
depth: 0,
overrideAccess: true,
});
}
expect(resolvedBallot.status).toBe("closed");
const winnerId =
typeof resolvedBallot.winner === "object" && resolvedBallot.winner !== null
? resolvedBallot.winner.id
: resolvedBallot.winner;
// Zero votes -> cheapest option auto-started (cheap has no costs).
expect([cheap.id, pricey.id, winnerId]).toContain(winnerId);
const research = await payload.find({
collection: "tech-researches",
where: { ballot: { equals: target.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(research.totalDocs).toBe(1);
await setResearchEnabled(false);
}, 60_000);
it("blocks deleting researched technologies and un-approving researching ones", async () => {
await setResearchEnabled(true);
const tech = await createTechnology({ name: `${RUN} protected` });
// Active research in flight.
const research = (await payload.create({
collection: "tech-researches",
data: {
technology: tech.id,
status: "active",
startedAt: baseTime.toISOString(),
etaAt: new Date(baseTime.getTime() + HOUR).toISOString(),
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
await expect(
payload.delete({ collection: "technologies", id: tech.id, overrideAccess: true }),
).rejects.toThrow(/research/i);
await expect(
payload.update({
collection: "technologies",
id: tech.id,
data: { approvalStatus: "in_progress" },
overrideAccess: true,
}),
).rejects.toThrow(/Approved|research/i);
// Mark completed + researchedAt -> delete still blocked by history.
await payload.update({
collection: "tech-researches",
id: research.id,
data: { status: "completed", completedAt: baseTime.toISOString() },
overrideAccess: true,
depth: 0,
});
await payload.update({
collection: "technologies",
id: tech.id,
data: { researchedAt: baseTime.toISOString() },
overrideAccess: true,
depth: 0,
});
await expect(
payload.delete({ collection: "technologies", id: tech.id, overrideAccess: true }),
).rejects.toThrow(/researched/i);
createdTechIds.splice(createdTechIds.indexOf(tech.id), 1); // intentionally kept
}, 60_000);
it("cannot open ballots without operational staffed capacity", async () => {
await setResearchEnabled(true);
// Unstaffed / non-operational facilities contribute nothing.
const materialId = await firstResourceId();
const blueprint = (await payload.create({
collection: "structures",
data: {
name: `${RUN} empty lab`,
codeName: `${RUN}-empty-lab`,
description: LEXICAL_EMPTY as any,
category: "civilian",
approvalStatus: "approved",
materials: materialId ? [{ resource: materialId, amount: 1 }] : [],
constructionDurationMinutes: 60,
terrainType: "land",
maxHealth: 100,
isResearchFacility: true,
},
overrideAccess: true,
depth: 0,
})) as unknown as Structure;
await payload.create({
collection: "game-structures",
data: { name: `${RUN} empty lab site`, type: blueprint.id, constructionStatus: "building" },
overrideAccess: true,
depth: 0,
});
const before = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
const result = await processTechTick(payload, new Date(Date.UTC(2028, 0, 1)));
const after = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
expect(after.totalDocs).toBe(before.totalDocs);
expect(result.opened).toBe(0);
await setResearchEnabled(false);
}, 60_000);
});
async function firstResourceId(): Promise<number | null> {
const res = await payload.find({
collection: "resources",
limit: 1,
depth: 0,
overrideAccess: true,
});
return res.docs[0]?.id ?? null;
}