Files
patriothacks/src/lib/fairshare.test.ts
T
OmO Orchestrator d21e2dfe34 fix(farms): additive food supply (no starvation) + wire grow-light power budget
Farms->Fair Share credited food via seed.resource.food (latest-wins), so the demo's 20kg forecast OVERWROTE the 410 baseline (food 410->20, the farm starved the settlement). Farms now appends a signed fairshare.contribution that Fair Share SUMS onto the baseline per-contributor-latest, so growing food only raises the pool and multiple growers sum. Also wires the advertised-but-inert grow-light power budget into FarmsScreen + shows energy vs budget in ForecastPanel.
2026-11-20 03:14:49 -05:00

426 lines
17 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "./db";
import { init } from "./identity";
import { append, readAll, type StoredEventLogEntry } from "./eventlog";
import {
computeAllocationTrend,
computeFairshareAllocation,
FAIRSHARE_RESOURCES,
InvalidFairshareFloorError,
postFairshareFloor,
} from "./fairshare";
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
afterEach(() => {
vi.unstubAllGlobals();
});
async function seedResource(resource: string, value: number): Promise<void> {
await append({ type: `seed.resource.${resource}`, resource, value });
}
async function reportNeed(
agent: string,
resource: string,
value: number,
): Promise<void> {
await append({ type: "fairshare.need", agent, resource, value });
}
describe("fairshare.contribution (additive supply)", () => {
const entry = (id: number, payload: unknown, pk: number[]): StoredEventLogEntry =>
({
id,
lamportTs: id,
payload,
authorPubkey: new Uint8Array(pk),
signature: new Uint8Array([id]),
}) as unknown as StoredEventLogEntry;
it("sums contributions across distinct contributors onto the seeded baseline, latest-per-contributor", () => {
const entries = [
entry(1, { type: "seed.resource.food", resource: "food", value: 410 }, [1]),
entry(2, { type: "fairshare.contribution", resource: "food", value: 20 }, [2]),
entry(3, { type: "fairshare.contribution", resource: "food", value: 30 }, [3]),
entry(4, { type: "fairshare.contribution", resource: "food", value: 50 }, [2]),
];
// 410 baseline + contributor[2] latest 50 + contributor[3] 30 = 490 (NOT 410+20+30+50)
expect(computeFairshareAllocation(entries).supply.food).toBe(490);
});
it("ignores a negative or non-finite contribution (never shrinks the pool)", () => {
const entries = [
entry(1, { type: "seed.resource.food", resource: "food", value: 100 }, [1]),
entry(2, { type: "fairshare.contribution", resource: "food", value: -40 }, [2]),
entry(3, { type: "fairshare.contribution", resource: "food", value: Number.NaN }, [3]),
];
expect(computeFairshareAllocation(entries).supply.food).toBe(100);
});
});
describe("computeFairshareAllocation (happy path - 4 resources, 10 agents)", () => {
it("allocates exactly the seeded supply across all 4 resources and stays envy-free", async () => {
const supplies: Record<string, number> = {
power: 1000,
water: 800,
food: 600,
cooling: 400,
};
for (const [resource, value] of Object.entries(supplies)) {
await seedResource(resource, value);
}
const agents = Array.from({ length: 10 }, (_, i) => `agent-${i}`);
for (const agent of agents) {
for (const resource of FAIRSHARE_RESOURCES) {
// Each agent reports a distinct positive need per resource so the
// market is genuinely heterogeneous, not a degenerate tie.
const seed = agents.indexOf(agent) + 1;
const resourceWeight = FAIRSHARE_RESOURCES.indexOf(resource) + 1;
await reportNeed(agent, resource, seed * resourceWeight);
}
}
const entries = await readAll();
const result = computeFairshareAllocation(entries);
expect(result.insufficientData).toBe(false);
expect(result.agents).toHaveLength(10);
for (const resource of FAIRSHARE_RESOURCES) {
const total = result.agents.reduce(
(sum, agent) => sum + result.allocation[agent][resource],
0,
);
expect(total).toBeCloseTo(supplies[resource], 6);
}
// Envy-freeness within the CEEI guarantee: every agent's realised
// utility from its own bundle is at least as large as the utility it
// would realise from swapping to any other agent's bundle, valued under
// its own linear utility weights (the standard CEEI envy-free check).
for (const agentA of result.agents) {
for (const agentB of result.agents) {
if (agentA === agentB) continue;
const ownUtility = result.utilities[agentA];
const seedA = agents.indexOf(agentA) + 1;
let utilityFromOthersBundle = 0;
for (const resource of FAIRSHARE_RESOURCES) {
const resourceWeight = FAIRSHARE_RESOURCES.indexOf(resource) + 1;
const weight = seedA * resourceWeight;
utilityFromOthersBundle += weight * result.allocation[agentB][resource];
}
expect(ownUtility).toBeGreaterThanOrEqual(utilityFromOthersBundle - 1e-6);
}
}
});
it("reflects 3 real allocation-history points in the trend for a resource", async () => {
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: 100 });
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: 120 });
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: 140 });
const entries = await readAll();
const trend = computeAllocationTrend(entries, "power");
expect(trend.status).toBe("trend");
if (trend.status === "trend") {
expect(trend.points).toBe(3);
expect(trend.slope).toBeCloseTo(20, 6);
}
});
});
describe("computeFairshareAllocation (failure path - zero-seeded resource)", () => {
it("returns a valid all-zero allocation for a resource seeded at zero, no crash", async () => {
await seedResource("power", 500);
await seedResource("water", 0);
await seedResource("food", 300);
await seedResource("cooling", 200);
await reportNeed("agent-a", "power", 3);
await reportNeed("agent-a", "water", 5);
await reportNeed("agent-a", "food", 1);
await reportNeed("agent-a", "cooling", 2);
await reportNeed("agent-b", "power", 1);
await reportNeed("agent-b", "water", 2);
await reportNeed("agent-b", "food", 4);
await reportNeed("agent-b", "cooling", 1);
const entries = await readAll();
const result = computeFairshareAllocation(entries);
expect(result.insufficientData).toBe(false);
expect(result.allocation["agent-a"].water).toBe(0);
expect(result.allocation["agent-b"].water).toBe(0);
expect(result.prices.water).toBeUndefined();
// The other 3 resources still clear normally despite water's zero pool.
for (const resource of ["power", "food", "cooling"] as const) {
const total =
result.allocation["agent-a"][resource] + result.allocation["agent-b"][resource];
expect(total).toBeCloseTo(result.supply[resource], 6);
}
});
it("reports 'no trend yet' for the zero-seeded resource's history", async () => {
await append({ type: "fairshare.allocation.cycle", resource: "water", totalAllocated: 0 });
const entries = await readAll();
const trend = computeAllocationTrend(entries, "water");
expect(trend.status).toBe("no-trend-yet");
expect(trend.points).toBe(1);
});
it("returns insufficientData when no agent has reported any need at all", async () => {
await seedResource("power", 1000);
const entries = await readAll();
const result = computeFairshareAllocation(entries);
expect(result.insufficientData).toBe(true);
expect(result.agents).toHaveLength(0);
});
});
describe("postFairshareFloor (survival floor ahead of the CEEI solve)", () => {
it("guarantees an agent at least its floor while conserving total supply", async () => {
await seedResource("power", 100);
await seedResource("water", 100);
// Diagonal preferences: agent-a overwhelmingly wants power, agent-b
// overwhelmingly wants water. With equal CEEI budgets and a single
// shared market across both goods, this is the textbook instance where
// each agent's linear-utility optimum spends its whole budget on the
// one good it prefers, so the unfloored equilibrium gives agent-b
// ~0 power (confirmed below) - a real starving case, not a no-op.
await reportNeed("agent-a", "power", 100);
await reportNeed("agent-a", "water", 1);
await reportNeed("agent-b", "power", 1);
await reportNeed("agent-b", "water", 100);
const unflooredEntries = await readAll();
const unfloored = computeFairshareAllocation(unflooredEntries);
expect(unfloored.allocation["agent-b"].power).toBeLessThan(20);
await postFairshareFloor("power", 20);
const entries = await readAll();
const result = computeFairshareAllocation(entries);
expect(result.floor.power).toBeCloseTo(20, 6);
expect(result.allocation["agent-b"].power).toBeGreaterThanOrEqual(20 - 1e-6);
// Conservation: floor + residual CEEI share still sums to exactly the
// seeded total supply, for every agent combined, for every resource.
const totalPower =
result.allocation["agent-a"].power + result.allocation["agent-b"].power;
expect(totalPower).toBeCloseTo(100, 6);
const totalWater =
result.allocation["agent-a"].water + result.allocation["agent-b"].water;
expect(totalWater).toBeCloseTo(100, 6);
});
it("clamps a floor above supply/agents.length instead of exceeding supply", async () => {
await seedResource("power", 100);
await reportNeed("agent-a", "power", 1);
await reportNeed("agent-b", "power", 1);
// Requested floor (80) is far above the 50-per-agent the 100-unit pool
// could ever guarantee both agents - must clamp to 50, not propagate.
await postFairshareFloor("power", 80);
const entries = await readAll();
const result = computeFairshareAllocation(entries);
expect(result.floor.power).toBeCloseTo(50, 6);
const total =
result.allocation["agent-a"].power + result.allocation["agent-b"].power;
expect(total).toBeCloseTo(100, 6);
expect(result.allocation["agent-a"].power).toBeLessThanOrEqual(100 + 1e-6);
expect(result.allocation["agent-b"].power).toBeLessThanOrEqual(100 + 1e-6);
});
it("rejects a NaN/negative/Infinity floor before ever appending it", async () => {
const before = await readAll();
expect(before).toHaveLength(0);
await expect(postFairshareFloor("power", Number.NaN)).rejects.toThrow(
InvalidFairshareFloorError,
);
await expect(postFairshareFloor("power", -5)).rejects.toThrow(
InvalidFairshareFloorError,
);
await expect(postFairshareFloor("power", Number.POSITIVE_INFINITY)).rejects.toThrow(
InvalidFairshareFloorError,
);
// None of the rejected calls reached append() - the log stays empty.
const after = await readAll();
expect(after).toHaveLength(0);
});
it("applies the floor correctly on a cold replay of the event log (not only a live session)", async () => {
await seedResource("power", 100);
await seedResource("water", 100);
await reportNeed("agent-a", "power", 100);
await reportNeed("agent-a", "water", 1);
await reportNeed("agent-b", "power", 1);
await reportNeed("agent-b", "water", 100);
await postFairshareFloor("power", 20);
// Simulate a cold replay: read every entry back from storage (as a
// freshly-opened replica would) and recompute from scratch, rather than
// reusing any in-memory state from the calls above.
const replayedEntries = await readAll();
const result = computeFairshareAllocation([...replayedEntries]);
expect(result.floor.power).toBeCloseTo(20, 6);
expect(result.allocation["agent-b"].power).toBeGreaterThanOrEqual(20 - 1e-6);
const total =
result.allocation["agent-a"].power + result.allocation["agent-b"].power;
expect(total).toBeCloseTo(100, 6);
});
});
describe("postFairshareFloor backend sync wiring (plan todo 3)", () => {
it("observably calls trySyncWithBackend() after the write, without delaying or altering the local-first append", async () => {
const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
vi.stubGlobal("fetch", fetchMock);
const stored = await postFairshareFloor("power", 10);
// The local-first write's own result is unaffected by the sync call
// (same value whether or not the relay is reachable) and was never
// reordered/delayed by it - the append() above already resolved before
// postFairshareFloor returned.
expect(stored.payload).toMatchObject({ type: "fairshare.floor", resource: "power", perAgentFloor: 10 });
const entries = await readAll();
expect(entries).toHaveLength(1);
// trySyncWithBackend() is fire-and-forget (not awaited by
// postFairshareFloor), so give its microtask a turn to run before
// asserting the relay was actually invoked.
await Promise.resolve();
await Promise.resolve();
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBe("/api/sync");
expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: "POST" });
});
it("never throws into the caller when the relay is unreachable - the write still resolves normally", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down")));
await expect(postFairshareFloor("water", 5)).resolves.toMatchObject({
payload: { type: "fairshare.floor", resource: "water", perAgentFloor: 5 },
});
});
});
describe("computeFairshareAllocation (adversarial robustness)", () => {
it("never emits an Infinity clearing price when a floor consumes the entire pool", async () => {
await seedResource("power", 100);
await reportNeed("agent-a", "power", 1);
await reportNeed("agent-b", "power", 1);
// A clamped floor of 50 for 2 agents reserves the whole 100-unit pool,
// leaving zero residual supply for the CEEI sub-market. The residual
// good must be excluded from the solve, not fed to solveCeeiWaterFilling
// (which would divide by its zero supply and emit an Infinity price).
await postFairshareFloor("power", 50);
const result = computeFairshareAllocation(await readAll());
expect(result.prices.power).toBeUndefined();
expect(result.floor.power).toBeCloseTo(50, 6);
const total =
result.allocation["agent-a"].power + result.allocation["agent-b"].power;
expect(total).toBeCloseTo(100, 6);
for (const agent of result.agents) {
expect(Number.isFinite(result.allocation[agent].power)).toBe(true);
expect(Number.isFinite(result.utilities[agent])).toBe(true);
}
});
it("rejects a non-finite need value so it can never produce NaN allocations", async () => {
await seedResource("power", 100);
await reportNeed("agent-a", "power", Number.POSITIVE_INFINITY);
await reportNeed("agent-b", "power", 5);
const result = computeFairshareAllocation(await readAll());
expect(result.agents).not.toContain("agent-a");
expect(result.agents).toContain("agent-b");
expect(Number.isFinite(result.allocation["agent-b"].power)).toBe(true);
});
it("rejects a non-finite seeded supply so it can never produce NaN allocations", async () => {
await seedResource("power", Number.POSITIVE_INFINITY);
await reportNeed("agent-a", "power", 2);
await reportNeed("agent-b", "power", 3);
const result = computeFairshareAllocation(await readAll());
expect(result.supply.power).toBe(0);
expect(result.insufficientData).toBe(true);
for (const agent of result.agents) {
expect(Number.isFinite(result.allocation[agent].power)).toBe(true);
}
});
it("drops a non-finite allocation.cycle point so the trend slope stays finite", async () => {
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: Number.NaN });
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: 100 });
await append({ type: "fairshare.allocation.cycle", resource: "power", totalAllocated: 120 });
const trend = computeAllocationTrend(await readAll(), "power");
expect(trend.status).toBe("trend");
if (trend.status === "trend") {
expect(trend.points).toBe(2);
expect(Number.isFinite(trend.slope)).toBe(true);
expect(trend.slope).toBeCloseTo(20, 6);
}
});
});
describe("computeAllocationTrend", () => {
it("reports 'no trend yet' at exactly 1 history entry", async () => {
await append({ type: "fairshare.allocation.cycle", resource: "food", totalAllocated: 50 });
const entries = await readAll();
const trend = computeAllocationTrend(entries, "food");
expect(trend).toEqual({ status: "no-trend-yet", points: 1 });
});
it("computes a correct slope at 5 history entries", async () => {
const values = [10, 12, 15, 25, 20];
for (const totalAllocated of values) {
await append({
type: "fairshare.allocation.cycle",
resource: "cooling",
totalAllocated,
});
}
const entries = await readAll();
const trend = computeAllocationTrend(entries, "cooling");
expect(trend.status).toBe("trend");
if (trend.status === "trend") {
expect(trend.points).toBe(5);
// Hand-computed OLS slope of [10, 12, 15, 25, 20] against x=[0..4]:
// meanX=2, meanY=16.4
// numerator = sum((x-2)(y-16.4)) = (-2)(-6.4)+(-1)(-4.4)+0(-1.4)+1(8.6)+2(3.6)
// = 12.8 + 4.4 + 0 + 8.6 + 7.2 = 33
// denominator = sum((x-2)^2) = 4+1+0+1+4 = 10
// slope = 33/10 = 3.3
expect(trend.slope).toBeCloseTo(3.3, 6);
}
});
});