vpp-ai-platform/packages/services/src/ledger.ts
Thomas Bayes 8796faca63 M2: skill contracts, Python skill service, L2 eval harness with baseline
- packages/domain: ForecastRequest, BidOptimizationRequest/Result,
  ReportRequest, SkillReport (+ golden and invalid fixtures, exported to
  contracts/ and regenerated as pydantic models).
- skills-py/vpp_skills: FastAPI service with versioned registry; load/PV/
  price forecasts (same-day-type EWM point forecast, conformal residual
  quantiles — coverage test as acceptance gate); bid-optimization MILP on
  HiGHS (binary block participation, hard ledger energy bounds, exact
  Decimal fit of the rounded curve inside the bounds, revenue distribution
  over quantile paths); report generator whose every figure is a
  {tool_call_id, path} reference, with a verifier. 48 tests incl. hypothesis
  property test that bids respect ledger constraints.
- packages/services: LedgerService.dayAheadBounds (the P7 cascade band
  handed to the optimizer); Decimal resolved once for CJS/ESM interop.
- packages/evals: L2 metrics (MAPE, nRMSE, coverage, direction accuracy,
  naive/hindsight revenue baselines), HTTP skill client, rolling-origin
  harness that pushes each bid through the real ledger, CLI with
  --check/--write-baseline; committed baseline on the SYNTHETIC dataset
  (no historical Hubei data yet — baselines measure the harness, not KPI).
- CI: evals job boots the skill service and fails on baseline digest drift.
- docs/open-questions: A6 (flexibility marginal cost = offer floor); A4/B6
  wired as placeholders. README/CLAUDE.md status → M2 done, M3 next.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoYoGYzHkFyv3ALenkRPhA
2026-09-02 06:29:08 -04:00

125 lines
4.5 KiB
TypeScript

import { Decimal } from './decimal.js'
import type { LedgerView, PositionBounds, PositionEntry, PositionUpdate, Timescale } from '@vpp/domain'
import { PositionUpdate as PositionUpdateSchema } from '@vpp/domain'
export class LedgerConcurrencyError extends Error {
constructor(expected: number, actual: number) {
super(`ledger version mismatch: update expected ${expected}, current is ${actual}`)
this.name = 'LedgerConcurrencyError'
}
}
export class CascadeViolation extends Error {
constructor(message: string) {
super(message)
this.name = 'CascadeViolation'
}
}
export interface LedgerConfig {
/**
* Allowed relative deviation of a day-ahead bid's daily energy from the
* pro-rata daily share of the monthly contracted position.
* OPEN-QUESTION A5: the real Hubei decomposition-band rule may differ in
* shape (cumulative month-to-date band? asymmetric?) — see docs/open-questions.md.
*/
daMonthlyDeviationBand: string // e.g. "0.05" = ±5%
clock?: () => string
}
/**
* Position ledger v1 (docs/00 §4, P7): in-memory, optimistic concurrency,
* per-timescale views, and the constraint cascade — upper-timescale positions
* bound lower-timescale writes. Storage adapter (Postgres) arrives with M3.
*/
export class LedgerService {
private version = 0
private entries: PositionEntry[] = []
constructor(private readonly cfg: LedgerConfig) {}
read(): LedgerView {
return { version: this.version, entries: [...this.entries] }
}
viewByTimescale(timescale: Timescale): PositionEntry[] {
return this.entries.filter((e) => e.timescale === timescale)
}
/**
* Daily energy bounds for a day-ahead bid on `date`, derived from the
* MONTHLY CONTRACT position (the same rule checkCascade enforces). Handed
* to the bid-optimization skill as hard constraints so the optimizer can
* never produce a bid the ledger would then reject. Throws when there is
* no monthly anchor — same policy as append.
*/
dayAheadBounds(date: string): PositionBounds {
const { min, max } = this.cascadeBand(date)
return {
ledger_version: this.version,
daily_energy_min_mwh: min.toString(),
daily_energy_max_mwh: max.toString(),
}
}
append(update: PositionUpdate): LedgerView {
PositionUpdateSchema.parse(update)
if (update.expected_version !== this.version) {
throw new LedgerConcurrencyError(update.expected_version, this.version)
}
this.checkCascade(update)
const { expected_version: _ignored, ...rest } = update
const entry: PositionEntry = {
...rest,
recorded_at: this.cfg.clock?.() ?? new Date().toISOString(),
}
this.entries.push(entry)
this.version += 1
return this.read()
}
/**
* Constraint cascade (P7): a DAY_AHEAD bid submission must stay within the
* band around the pro-rata daily share of the MONTHLY contracted position.
* No monthly position for the month → nothing to cascade from → reject
* (bidding without a position of record is a lineage failure, not a default-allow).
*/
private checkCascade(update: PositionUpdate): void {
if (update.kind !== 'BID_SUBMITTED' || update.timescale !== 'DAY_AHEAD') return
const { min, max, contracted, daysInMonth, band } = this.cascadeBand(update.period)
const bid = new Decimal(update.energy_mwh)
if (bid.lt(min) || bid.gt(max)) {
throw new CascadeViolation(
`day-ahead bid ${bid.toString()} MWh outside monthly cascade band ` +
`[${min.toString()}, ${max.toString()}] (contracted ${contracted.toString()} MWh / ${daysInMonth} days ± ${band.mul(100).toString()}%)`,
)
}
}
private cascadeBand(date: string) {
const month = date.slice(0, 7)
const monthly = this.entries.filter(
(e) => e.timescale === 'MONTHLY' && e.kind === 'CONTRACT' && e.period === month,
)
if (monthly.length === 0) {
throw new CascadeViolation(
`no MONTHLY CONTRACT position recorded for ${month}; day-ahead bid has no cascade anchor`,
)
}
const contracted = monthly.reduce((sum, e) => sum.add(new Decimal(e.energy_mwh)), new Decimal(0))
const daysInMonth = new Date(
Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0),
).getUTCDate()
const dailyShare = contracted.div(daysInMonth)
const band = new Decimal(this.cfg.daMonthlyDeviationBand)
return {
min: dailyShare.mul(new Decimal(1).sub(band)),
max: dailyShare.mul(new Decimal(1).add(band)),
contracted,
daysInMonth,
band,
}
}
}