Files
patriothacks/src/lib/fairshare.ts
T

301 lines
11 KiB
TypeScript

import type { StoredEventLogEntry } from "./eventlog";
import { sortForReplay } from "./ledger";
import { solveCeeiWaterFilling } from "./ceeiSpike";
/**
* Production ma-fairshare allocation engine (plan todo 14).
*
* This is the approach VALIDATED by todo 13's CEEI spike (src/lib/ceeiSpike.ts),
* generalised across the 4 resource types and N agents.
*
* Design decision - which of todo 13's two validated approaches generalises:
* `solveCeeiPriceSearch` (and the `solveCeei` orchestrator that calls it
* first) is explicitly scoped to a 2-good Fisher market: it bisects a single
* free price coordinate and THROWS for any instance whose `supply.length !==
* 2`. That scalar-bisection structure has no sound N-good generalisation
* without reintroducing a full vector tatonnement search (a materially
* different, unvalidated algorithm). `solveCeeiWaterFilling`, by contrast,
* was *already written* for arbitrary agents/goods in todo 13: it is
* proportional-response dynamics over per-agent, per-good bids, and prices
* fall out of the bid matrix for however many goods are present. Proportional
* response dynamics are a standard, well-studied algorithm that converges to
* the Fisher-market (CEEI) equilibrium for linear utilities for ANY number
* of goods and agents - todo 13's own tests already proved it recovers the
* textbook 2-good closed-form answer independently of the price-search path.
* This module therefore calls `solveCeeiWaterFilling` directly (never the
* `solveCeei` orchestrator, which would throw immediately on a 4-good
* instance) as the one real market solved across all 4 resources at once
* with each agent's single equal-income budget - that is what makes it a
* genuine CEEI (Competitive Equilibrium from Equal Incomes): the "equal
* income" constraint is a single shared budget spent across every good
* together, not four independent per-resource budgets.
*
* Event shapes read via replay of the signed Event Log:
* `{ type: "seed.resource.<resource>", resource, value }` - latest value
* per resource (by replay order) is that resource's current supply pool.
* Written by the admin seed panel (todo 8/9); never fabricated here.
* `{ type: "fairshare.need", agent, resource, value }` - agent `agent`'s
* reported need for `resource` (a non-negative linear utility weight).
* An agent that never reports a need for a resource gets weight 0 for
* it (it can still receive some if useful to clear the shared market,
* but never demands it).
*
* No fabricated/synthetic reading or invented default is ever used: a
* resource with no `seed.resource.*` event has supply 0 (honest "not seeded
* yet", not a guessed pool size), and an agent set built only from agents
* who actually appear in `fairshare.need` events (never an invented
* population).
*/
export const FAIRSHARE_RESOURCES = ["power", "water", "food", "cooling"] as const;
export type FairshareResource = (typeof FAIRSHARE_RESOURCES)[number];
interface SeedResourcePayload {
type: `seed.resource.${FairshareResource}`;
resource: FairshareResource;
value: number;
}
export interface FairshareNeedPayload {
type: "fairshare.need";
agent: string;
resource: FairshareResource;
value: number;
}
/**
* Payload for one completed allocation cycle, written after a solve so the
* allocation-history trend (see `computeAllocationTrend`) has real signed
* history to replay instead of ever guessing a line.
*/
export interface FairshareAllocationCyclePayload {
type: "fairshare.allocation.cycle";
resource: FairshareResource;
/** Sum of every agent's allocated quantity for `resource` in this cycle. */
totalAllocated: number;
}
function isSeedResourcePayload(
payload: unknown,
): payload is SeedResourcePayload {
if (typeof payload !== "object" || payload === null) return false;
const p = payload as Record<string, unknown>;
return (
typeof p.type === "string" &&
p.type.startsWith("seed.resource.") &&
FAIRSHARE_RESOURCES.includes(p.resource as FairshareResource) &&
typeof p.value === "number"
);
}
function isFairshareNeedPayload(
payload: unknown,
): payload is FairshareNeedPayload {
if (typeof payload !== "object" || payload === null) return false;
const p = payload as Record<string, unknown>;
return (
p.type === "fairshare.need" &&
typeof p.agent === "string" &&
FAIRSHARE_RESOURCES.includes(p.resource as FairshareResource) &&
typeof p.value === "number" &&
p.value >= 0
);
}
function isAllocationCyclePayload(
payload: unknown,
): payload is FairshareAllocationCyclePayload {
if (typeof payload !== "object" || payload === null) return false;
const p = payload as Record<string, unknown>;
return (
p.type === "fairshare.allocation.cycle" &&
FAIRSHARE_RESOURCES.includes(p.resource as FairshareResource) &&
typeof p.totalAllocated === "number"
);
}
export interface FairshareAllocation {
/** Resources with a seeded pool (even if seeded at 0), in canonical order. */
resources: FairshareResource[];
/** Agents that reported at least one need, in canonical (sorted) order. */
agents: string[];
/** Current supply pool per resource (latest `seed.resource.*` value, 0 if unseeded). */
supply: Record<FairshareResource, number>;
/** `allocation[agent][resource]` = that agent's allocated quantity. */
allocation: Record<string, Record<FairshareResource, number>>;
/** Clearing price per resource good actually solved (absent for zero-supply resources). */
prices: Partial<Record<FairshareResource, number>>;
/** Realised linear utility per agent, summed across all resources. */
utilities: Record<string, number>;
/**
* True when there is not enough real seeded data to run a market (no
* agents reported any need, or no resource has positive supply) - the
* allocation returned is then honestly all-zero, never a crash or a
* guessed number.
*/
insufficientData: boolean;
}
function zeroAllocation(
resources: FairshareResource[],
agents: string[],
): Record<string, Record<FairshareResource, number>> {
const allocation: Record<string, Record<FairshareResource, number>> = {};
for (const agent of agents) {
allocation[agent] = Object.fromEntries(
resources.map((r) => [r, 0]),
) as Record<FairshareResource, number>;
}
return allocation;
}
/**
* Replays the signed Event Log into a Pareto-efficient, envy-free CEEI
* allocation across all 4 resources for every agent that reported a need.
*
* Conservation: for every resource with positive supply, the sum of every
* agent's allocation for that resource equals the seeded supply exactly
* (water-filling's bid-share construction clears the market by construction
* - see `solveCeeiWaterFilling`'s doc comment in ceeiSpike.ts). A resource
* seeded at (or left at, i.e. unseeded) 0 supply is excluded from the solved
* sub-market entirely and every agent's allocation for it is hard-set to 0 -
* this sidesteps `solveCeeiWaterFilling`'s `prices[j] /= supply[j]` division
* by construction, so a zero pool can never divide-by-zero or crash.
*/
export function computeFairshareAllocation(
entries: readonly StoredEventLogEntry[],
): FairshareAllocation {
const ordered = sortForReplay(entries);
const supply: Record<FairshareResource, number> = {
power: 0,
water: 0,
food: 0,
cooling: 0,
};
const needs = new Map<string, Record<FairshareResource, number>>();
for (const entry of ordered) {
if (isSeedResourcePayload(entry.payload)) {
supply[entry.payload.resource] = entry.payload.value;
continue;
}
if (isFairshareNeedPayload(entry.payload)) {
const { agent, resource, value } = entry.payload;
const existing =
needs.get(agent) ??
({ power: 0, water: 0, food: 0, cooling: 0 } as Record<
FairshareResource,
number
>);
existing[resource] = value;
needs.set(agent, existing);
}
}
const resources = [...FAIRSHARE_RESOURCES];
const agents = [...needs.keys()].sort();
if (agents.length === 0) {
return {
resources,
agents,
supply,
allocation: {},
prices: {},
utilities: {},
insufficientData: true,
};
}
const solvedResources = resources.filter((r) => supply[r] > 0);
const allocation = zeroAllocation(resources, agents);
const utilities: Record<string, number> = Object.fromEntries(
agents.map((a) => [a, 0]),
);
const prices: Partial<Record<FairshareResource, number>> = {};
if (solvedResources.length > 0) {
const utilityMatrix = agents.map((agent) =>
solvedResources.map((r) => needs.get(agent)![r]),
);
const budgets = agents.map(() => 1);
const supplyVector = solvedResources.map((r) => supply[r]);
const result = solveCeeiWaterFilling({
utilities: utilityMatrix,
budgets,
supply: supplyVector,
});
agents.forEach((agent, i) => {
let utility = 0;
solvedResources.forEach((r, j) => {
const qty = result.allocation[i][j];
allocation[agent][r] = qty;
utility += needs.get(agent)![r] * qty;
});
utilities[agent] = utility;
});
solvedResources.forEach((r, j) => {
prices[r] = result.prices[j];
});
}
const noPositiveSupply = solvedResources.length === 0;
return {
resources,
agents,
supply,
allocation,
prices,
utilities,
insufficientData: noPositiveSupply,
};
}
export type AllocationTrend =
| { status: "no-trend-yet"; points: number }
| { status: "trend"; points: number; slope: number; average: number };
/**
* Computes an allocation-history trend (slope of the real signed
* `fairshare.allocation.cycle` history for `resource`, replayed in Lamport
* order) via ordinary-least-squares linear regression of `totalAllocated`
* against cycle index. With fewer than 2 real history points there is no
* line to fit, so this honestly reports "no-trend-yet" rather than
* guessing a slope from a single point or a synthesized default.
*/
export function computeAllocationTrend(
entries: readonly StoredEventLogEntry[],
resource: FairshareResource,
): AllocationTrend {
const points = sortForReplay(entries)
.filter(
(entry) =>
isAllocationCyclePayload(entry.payload) &&
entry.payload.resource === resource,
)
.map((entry) => (entry.payload as FairshareAllocationCyclePayload).totalAllocated);
if (points.length < 2) {
return { status: "no-trend-yet", points: points.length };
}
const n = points.length;
const xs = points.map((_, i) => i);
const meanX = xs.reduce((s, x) => s + x, 0) / n;
const meanY = points.reduce((s, y) => s + y, 0) / n;
let numerator = 0;
let denominator = 0;
for (let i = 0; i < n; i++) {
numerator += (xs[i] - meanX) * (points[i] - meanY);
denominator += (xs[i] - meanX) ** 2;
}
const slope = denominator === 0 ? 0 : numerator / denominator;
return { status: "trend", points: n, slope, average: meanY };
}