All files / scripts capacity-calibration-policy.ts

95.03% Statements 134/141
84.67% Branches 116/137
100% Functions 33/33
96.55% Lines 112/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 3472x                                                                             2x 2x                   2x                   99x       51x 2x   49x       43x 41x       11x         11x 11x 11x 11x 11x 11x 2x   5x 4x       9x 9x 9x 5x 5x 11x 5x 5x       2x 2x 2x 2x 2x 14x 2x               3x 3x 4x 3x 3x 3x 3x 3x 2x 2x 6x   2x     1x                 8x 8x 8x 8x 8x       8x 1x   7x       21x                       21x 15x 10x 11x 5x               5x 2x 1x               4x                   5x 5x 5x 4x   4x   4x   4x               4x 10x 9x 8x 8x 5x 4x 1x   3x 8x 8x 5x 3x 4x     4x     3x                   8x                 5x 1x               4x                           7x 3x   4x                 2x 1x   1x 2x 2x                           2x 6x 2x     2x 2x 2x 1x               1x                           8x 7x 3x    
export const CALIBRATION_POLICY_VERSION = "1" as const;
 
export type CalibrationOptions = {
  expectedUsers: number;
  targetCpuPercent: number;
  maxCpuPercent: number;
  maxUserWaitSec: number;
  maxDurationMin: number;
  classroomDurationSec: 60;
};
 
export type ActiveMeasurement = {
  requested: number;
  stable: boolean;
  cpuP95Percent: number | null;
  cpuMaxPercent: number | null;
  minAvailableMemoryBytes: number | null;
  lifecycleDockerPeak: number;
  pollingDockerPeak: number;
  errors: string[];
  elapsedMs: number;
};
 
export type StartupMeasurement = {
  requested: number;
  stable: boolean;
  startupSlotWaitP95Ms: number | null;
  startupSlotWaitMaxMs: number | null;
  startupDurationP95Ms: number | null;
  cpuP95Percent: number | null;
  iowaitP95Percent: number | null;
  minAvailableMemoryBytes: number | null;
  failures: number;
  timeouts: number;
  /** True only when backend semaphore samples cover every startup attempt. */
  startupSlotWaitSamplesComplete?: boolean;
  startupSlotWaitSampleCount?: number;
};
 
export const CLASSROOM_QUEUE_SAFETY_MARGIN_MS = 30_000;
export const CLASSROOM_MEASUREMENT_QUEUE_TIMEOUT_MAX_MS = 900_000;
 
export type Recommendation<T> = {
  value: T | null;
  status: "recommended" | "not-calibrated" | "infeasible" | "out-of-range";
  confidence: "HIGH" | "MEDIUM" | "LOW";
  measuredBasis: string[];
  warnings: string[];
};
 
const DEFAULTS: CalibrationOptions = {
  expectedUsers: 200,
  targetCpuPercent: 75,
  maxCpuPercent: 85,
  maxUserWaitSec: 240,
  maxDurationMin: 30,
  classroomDurationSec: 60,
};
 
function finiteNumber(value: unknown): value is number {
  return typeof value === "number" && Number.isFinite(value);
}
 
function positiveInteger(value: unknown, name: string): number {
  if (!finiteNumber(value) || !Number.isInteger(value) || value <= 0) {
    throw new Error(`${name} must be a positive integer`);
  }
  return value;
}
 
function positiveNumber(value: unknown, name: string): number {
  if (!finiteNumber(value) || value <= 0) throw new Error(`${name} must be positive`);
  return value;
}
 
export function validateCalibrationOptions(input: Partial<CalibrationOptions>): CalibrationOptions {
  const options: CalibrationOptions = {
    ...DEFAULTS,
    ...input,
    classroomDurationSec: 60,
  };
  positiveInteger(options.expectedUsers, "expectedUsers");
  positiveNumber(options.targetCpuPercent, "targetCpuPercent");
  positiveNumber(options.maxCpuPercent, "maxCpuPercent");
  positiveNumber(options.maxUserWaitSec, "maxUserWaitSec");
  positiveNumber(options.maxDurationMin, "maxDurationMin");
  if (options.targetCpuPercent >= options.maxCpuPercent) {
    throw new Error("targetCpuPercent must be less than maxCpuPercent");
  }
  if (options.maxCpuPercent > 95) throw new Error("maxCpuPercent must be at most 95");
  return options;
}
 
export function planActiveCandidates(options: CalibrationOptions, logicalCpus: number): number[] {
  positiveInteger(logicalCpus, "logicalCpus");
  const cap = Math.min(options.expectedUsers, 128, Math.max(20, logicalCpus * 4));
  if (cap <= 20) return [cap];
  const increment = Math.max(20, logicalCpus);
  const candidates: number[] = [];
  for (let value = 20; value < cap; value += increment) candidates.push(value);
  candidates.push(cap);
  return [...new Set(candidates)];
}
 
export function planDownwardRefinement(firstExceeded: number, _options: CalibrationOptions, logicalCpus: number): number[] {
  positiveInteger(firstExceeded, "firstExceeded");
  positiveInteger(logicalCpus, "logicalCpus");
  const step = Math.max(5, Math.ceil(logicalCpus / 2));
  const lowerBound = Math.max(1, Math.ceil(logicalCpus / 2));
  const candidates: number[] = [];
  for (let value = firstExceeded - step; value >= lowerBound; value -= step) candidates.push(value);
  return candidates;
}
 
export function planBracketRefinement(
  measurements: ActiveMeasurement[],
  options: CalibrationOptions,
  logicalCpus: number,
): number[] {
  positiveInteger(logicalCpus, "logicalCpus");
  const step = Math.max(5, Math.ceil(logicalCpus / 2));
  const ordered = [...measurements].sort((left, right) => left.requested - right.requested);
  for (let index = 0; index < ordered.length - 1; index++) {
    const lower = ordered[index];
    const upper = ordered[index + 1];
    Iif (!lower || !upper || !lower.stable || !upper.stable || lower.cpuP95Percent === null || upper.cpuP95Percent === null) continue;
    if (lower.cpuP95Percent <= options.targetCpuPercent && upper.cpuP95Percent > options.targetCpuPercent) {
      const candidates: number[] = [];
      for (let value = lower.requested + step; value < upper.requested; value += step) {
        Eif (!ordered.some((measurement) => measurement.requested === value)) candidates.push(value);
      }
      return candidates;
    }
  }
  return [];
}
 
export function measurementQueueTimeoutMs(
  productionDefaultMs: number,
  maxUserWaitSec: number,
  classroomDurationSec: number,
  startupSafetyMarginMs = CLASSROOM_QUEUE_SAFETY_MARGIN_MS,
): number {
  positiveInteger(productionDefaultMs, "productionDefaultMs");
  positiveNumber(maxUserWaitSec, "maxUserWaitSec");
  positiveInteger(classroomDurationSec, "classroomDurationSec");
  positiveInteger(startupSafetyMarginMs, "startupSafetyMarginMs");
  const result = Math.max(
    productionDefaultMs,
    Math.ceil(maxUserWaitSec * 1_000) + classroomDurationSec * 1_000 + startupSafetyMarginMs,
  );
  if (result > CLASSROOM_MEASUREMENT_QUEUE_TIMEOUT_MAX_MS) {
    throw new Error(`measurement queue timeout ${result}ms exceeds the configured maximum ${CLASSROOM_MEASUREMENT_QUEUE_TIMEOUT_MAX_MS}ms`);
  }
  return result;
}
 
function activeIsStable(measurement: ActiveMeasurement, options: CalibrationOptions): boolean {
  return measurement.stable
    && measurement.errors.length === 0
    && measurement.cpuP95Percent !== null
    && measurement.cpuP95Percent <= options.maxCpuPercent
    && measurement.lifecycleDockerPeak === measurement.requested
    && measurement.pollingDockerPeak >= measurement.requested;
}
 
export function selectActiveRecommendation(
  measurements: ActiveMeasurement[],
  options: CalibrationOptions,
): Recommendation<number> {
  const stable = measurements.filter((measurement) => activeIsStable(measurement, options));
  const target = stable.filter((measurement) => (measurement.cpuP95Percent ?? Infinity) <= options.targetCpuPercent);
  if (target.length > 0) {
    const selected = target.reduce((best, current) => current.requested > best.requested ? current : best, target[0]);
    return {
      value: selected.requested,
      status: "recommended",
      confidence: target.length >= 2 ? "HIGH" : "MEDIUM",
      measuredBasis: [`${selected.requested} active simulations directly measured`, `CPU p95 ${selected.cpuP95Percent}%`],
      warnings: [],
    };
  }
  if (stable.length > 0) {
    const selected = stable.reduce((best, current) => current.requested > best.requested ? current : best, stable[0]);
    return {
      value: selected.requested,
      status: "recommended",
      confidence: "MEDIUM",
      measuredBasis: [`${selected.requested} active simulations directly measured`, `CPU p95 ${selected.cpuP95Percent}%`],
      warnings: ["No directly measured stable candidate met the target CPU; selected the highest stable candidate below the hard ceiling."],
    };
  }
  return {
    value: null,
    status: "not-calibrated",
    confidence: "LOW",
    measuredBasis: [],
    warnings: ["No stable directly measured active-simulation candidate was available."],
  };
}
 
function materialStartupRegression(candidate: StartupMeasurement, baseline: StartupMeasurement): boolean {
  Iif (candidate.failures > 0 || candidate.timeouts > 0) return true;
  Eif (candidate.cpuP95Percent !== null && baseline.cpuP95Percent !== null) {
    if (candidate.cpuP95Percent - baseline.cpuP95Percent > 5) return true;
    Iif (baseline.cpuP95Percent > 0 && candidate.cpuP95Percent / baseline.cpuP95Percent > 1.1) return true;
  }
  Iif (candidate.iowaitP95Percent !== null && baseline.iowaitP95Percent !== null
      && candidate.iowaitP95Percent - baseline.iowaitP95Percent > 5) return true;
  Iif (candidate.minAvailableMemoryBytes !== null && baseline.minAvailableMemoryBytes !== null
      && candidate.minAvailableMemoryBytes < baseline.minAvailableMemoryBytes * 0.9) return true;
  return false;
}
 
export function selectStartupRecommendation(
  measurements: StartupMeasurement[],
  productionDefault: number,
  maxActive: number,
): Recommendation<number> {
  const safe = measurements
    .filter((measurement) => measurement.requested <= maxActive)
    .filter((measurement) => measurement.stable && measurement.failures === 0 && measurement.timeouts === 0)
    .filter((measurement) => measurement.startupSlotWaitSamplesComplete === true)
    .filter((measurement) => measurement.startupDurationP95Ms !== null)
    .sort((left, right) => left.requested - right.requested);
  if (safe.length === 0) {
    return { value: null, status: "not-calibrated", confidence: "LOW", measuredBasis: [], warnings: ["No safe startup candidate was directly measured."] };
  }
  const baseline = safe[0];
  const best = Math.min(...safe.map((measurement) => measurement.startupDurationP95Ms ?? Infinity));
  const nearBest = safe.filter((measurement) => (measurement.startupDurationP95Ms ?? Infinity) <= best * 1.1);
  const eligible = nearBest.filter((measurement) => !materialStartupRegression(measurement, baseline));
  const selected = eligible[0] ?? baseline;
  const warnings = eligible.length === 0
    ? ["Every near-best startup candidate had a material resource or error regression; kept the smallest safe baseline."]
    : [];
  Iif (selected.requested < productionDefault) {
    warnings.push(`Measured startup candidate ${selected.requested} is below the current default ${productionDefault}; review before applying.`);
  }
  return {
    value: selected.requested,
    status: "recommended",
    confidence: safe.length >= 3 ? "HIGH" : "MEDIUM",
    measuredBasis: [`startup candidate ${selected.requested} directly measured`, `best startup p95 ${best}ms`, `baseline candidate ${baseline.requested}`],
    warnings,
  };
}
 
function roundUp(value: number, quantum: number): number {
  return Math.ceil(value / quantum) * quantum;
}
 
function rangeRecommendation(
  technical: number,
  productionDefault: number,
  range: { min: number; max: number },
  basis: string[],
): Recommendation<number> {
  if (technical > range.max) {
    return {
      value: null,
      status: "out-of-range",
      confidence: "HIGH",
      measuredBasis: [...basis, `technical recommendation ${technical}`],
      warnings: [`Technical recommendation ${technical}ms exceeds configured maximum ${range.max}ms; no value was emitted.`],
    };
  }
  return {
    value: Math.max(productionDefault, range.min, technical),
    status: "recommended",
    confidence: "HIGH",
    measuredBasis: [...basis, `technical recommendation ${technical}`],
    warnings: technical < productionDefault ? ["Measured latency supports the existing production default; it was not reduced."] : [],
  };
}
 
export function recommendDockerControlTimeout(
  p99Ms: number | null,
  productionDefault: number,
  range: { min: number; max: number },
): Recommendation<number> {
  if (p99Ms === null || !finiteNumber(p99Ms) || p99Ms < 0) {
    return { value: null, status: "not-calibrated", confidence: "LOW", measuredBasis: [], warnings: ["Docker control p99 was not measured."] };
  }
  return rangeRecommendation(roundUp(p99Ms * 1.5, 100), productionDefault, range, [`Docker control p99 ${p99Ms}ms`]);
}
 
export function recommendSandboxStartSlotTimeout(
  p99Ms: number | null,
  maxObservedMs: number | null,
  productionDefault: number,
  range: { min: number; max: number },
): Recommendation<number> {
  if ((p99Ms === null || !finiteNumber(p99Ms)) && (maxObservedMs === null || !finiteNumber(maxObservedMs))) {
    return { value: null, status: "not-calibrated", confidence: "LOW", measuredBasis: [], warnings: ["Sandbox-start-slot waits were not measured."] };
  }
  const technical = roundUp(Math.max(p99Ms ?? 0, 0) * 2 || 0, 1_000);
  const maxMargin = roundUp(Math.max(maxObservedMs ?? 0, 0) * 1.5, 1_000);
  return rangeRecommendation(
    Math.max(technical, maxMargin),
    productionDefault,
    range,
    [`sandbox-start-slot p99 ${p99Ms ?? "n/a"}ms`, `max observed ${maxObservedMs ?? "n/a"}ms`],
  );
}
 
export function recommendQueueTimeout(
  queueP95Ms: number | null,
  queueP99Ms: number | null,
  queueMaxMs: number | null,
  maxUserWaitSec: number,
): Recommendation<number> {
  const values = [queueP95Ms === null ? null : queueP95Ms * 1.5, queueP99Ms === null ? null : queueP99Ms * 1.25, queueMaxMs === null ? null : queueMaxMs * 1.1]
    .filter((value): value is number => value !== null && Number.isFinite(value));
  Iif (values.length === 0) {
    return { value: null, status: "not-calibrated", confidence: "LOW", measuredBasis: [], warnings: ["Simulation queue waits were not measured."] };
  }
  const technical = roundUp(Math.max(...values), 1_000);
  const ceiling = maxUserWaitSec * 1_000;
  if (technical > ceiling) {
    return {
      value: null,
      status: "infeasible",
      confidence: "MEDIUM",
      measuredBasis: [`technical queue minimum ${technical}ms`, `UX ceiling ${ceiling}ms`],
      warnings: [`Technical queue timeout ${technical}ms exceeds the maximum user wait policy ${ceiling}ms.`],
    };
  }
  return {
    value: technical,
    status: "recommended",
    confidence: "MEDIUM",
    measuredBasis: [`technical queue minimum ${technical}ms`, `UX ceiling ${ceiling}ms`],
    warnings: [],
  };
}
 
export function scoreCalibrationConfidence(
  measuredPhases: number,
  complete: boolean,
  safetyEvents: number,
): "HIGH" | "MEDIUM" | "LOW" {
  if (measuredPhases >= 3 && complete && safetyEvents === 0) return "HIGH";
  if (measuredPhases > 0) return "MEDIUM";
  return "LOW";
}