/** * scale-architecture.md ยง44. Soak classification. * * The leak signal is sustained positive growth after warm-up, not an * arbitrary absolute maximum. The classifier fits a least-squares line over * the post-warm-up samples and reports `unbounded-growth` only when both the * slope and the total relative growth are material. */ export type SlopeSample = Readonly<{ minute: number; heapMb: number }>; export type MemorySlopeClass = "stable" | "unbounded-growth" | "insufficient-data"; export type MemorySlopeOptions = Readonly<{ /** Samples before this minute are warm-up. Default 0. */ warmupMinutes?: number; /** Largest tolerated post-warm-up slope in MB per minute. Default 0.5. */ maxSlopeMbPerMinute?: number; /** Largest tolerated relative growth first->last fitted value. Default 0.1. */ maxRelativeGrowth?: number; }>; export function linearSlope(points: readonly Readonly<{ x: number; y: number }>[]): number { const count = points.length; if (count < 2) return 0; const meanX = points.reduce((sum, point) => sum + point.x, 0) / count; const meanY = points.reduce((sum, point) => sum + point.y, 0) / count; let numerator = 0; let denominator = 0; for (const point of points) { numerator += (point.x - meanX) * (point.y - meanY); denominator += (point.x - meanX) ** 2; } return denominator === 0 ? 0 : numerator / denominator; } export function classifyMemorySlope( samples: readonly SlopeSample[], options: MemorySlopeOptions = {}, ): MemorySlopeClass { const warmup = options.warmupMinutes ?? 0; const maxSlope = options.maxSlopeMbPerMinute ?? 0.5; const maxGrowth = options.maxRelativeGrowth ?? 0.1; const measured = samples .filter((sample) => sample.minute >= warmup) .filter((sample) => Number.isFinite(sample.minute) && Number.isFinite(sample.heapMb)) .sort((left, right) => left.minute - right.minute); if (measured.length < 3) return "insufficient-data"; const slope = linearSlope(measured.map((sample) => ({ x: sample.minute, y: sample.heapMb }))); const first = measured[0] as SlopeSample; const last = measured[measured.length - 1] as SlopeSample; const fittedStart = Math.max(first.heapMb, Number.MIN_VALUE); const growth = (slope * (last.minute - first.minute)) / fittedStart; return slope > maxSlope && growth > maxGrowth ? "unbounded-growth" : "stable"; } /** Generic variant for logical counters (timers, listeners, buffered events). */ export function classifyCounterSeries( values: readonly number[], options: Readonly<{ warmupSamples?: number; maxSlopePerSample?: number }> = {}, ): MemorySlopeClass { const warmup = options.warmupSamples ?? 0; const measured = values.slice(warmup); if (measured.length < 3) return "insufficient-data"; const slope = linearSlope(measured.map((y, x) => ({ x, y }))); return slope > (options.maxSlopePerSample ?? 0.01) ? "unbounded-growth" : "stable"; }