import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import type { Json } from './log.ts' /** Checked-in rollout policy. Override a run with `--policy `. */ // Every numeric threshold in the policy file has a provenance entry in scripts/calibrate/thresholds.json: a cited // distribution or `PRIOR (uncalibrated)` (issue #73, test/calibrate-provenance.test.ts). export const DEFAULT_POLICY_PATH = fileURLToPath(new URL('./cd.policy.json', import.meta.url)) export type SignalMode = 'hard' | 'informational' export type ProbeCall = { readonly method: 'GET' | 'POST' readonly path: string readonly auth: boolean } /** * Where a harness fault above 0% leaves traffic. Rollback restores `previous` at 100%. * `telemetry` does not decide on the probe window at all: the loss is recorded, and the * step is judged on the new version's own telemetry (a probe-tail loss is the harness, * not the Worker). The checked-in ramp uses it since 2026-11-08: under `rollback`, runs * 2026-11-06T17-32-11-293Z (6/2000) and 18-44-58-475Z (5/2000) rolled back clean versions on * probe-tail loss alone. */ export type ProbeFaultAction = 'rollback' | 'hold' | 'telemetry' /** * Citation for `probe.maxLossRate`, per issue #73: source, window, date, n, and headroom. * The number is the 100% step of run 2026-11-01T17-06-08-780Z: 1 client abort in 790 probes. */ export type ProbeCalibration = { readonly source: string readonly date: string readonly window: string readonly n: number readonly lost: number readonly web: string readonly ply: string readonly observedRate: string readonly percentile: string readonly headroom: string } /** * Citation for the probe scheduler, per issue #73. * Run 2026-11-01T19-40-35-485Z (web 22bfb79), 50% step: healthy p50 41–101ms on * both versions, then a client stall at ~69830ms. 128 issued, 10 never answered. */ export type ProbeScheduleCalibration = { readonly source: string readonly date: string readonly window: string readonly n: number readonly responded: number readonly lost: number readonly healthyN: number readonly web: string readonly oldVersion: string readonly newVersion: string readonly healthyP50Ms: string readonly observedStallMs: number readonly dwellMs: number readonly observedRate: string readonly percentile: string readonly headroom: string } export type RolloutStep = { readonly percent: number readonly dwellMs: number } /** `gate` without thresholds is not a value of this type. The parser rejects it. */ export type LatencyPolicy = | { readonly mode: 'off' } | { readonly mode: 'informational' } | { readonly mode: 'gate'; readonly minSamples: number; readonly p99Ratio: number; readonly effectFloorMs: number } export type RolloutGates = { readonly smoke: SignalMode readonly fivexx: SignalMode readonly exceptions: SignalMode readonly errorLogs: SignalMode readonly nonOk: SignalMode readonly burn: SignalMode readonly latency: LatencyPolicy } /** What a routed-share miss does. It does not advance. */ export type SplitAction = 'hold' | 'rollback' /** What too few new-version requests does. Rollback is not a choice: thin evidence is not a fault. */ export type EvidenceAction = 'advance' | 'hold' /** * Citation for scratch-repo delete, per issue #73. * `latencyMs` is the timed-out delete on run 2026-11-01T17-29-43-122Z (web 9558b10): 103s, then 404. */ export type CleanupCalibration = { readonly source: string readonly date: string readonly window: string readonly n: number readonly latencyMs: number readonly web: string readonly namespace: string readonly observed: string readonly percentile: string readonly headroom: string } /** How a scratch repo is deleted. `attempts` bounds the retries. A miss is a leak, not a failed release. */ export type CleanupPolicy = { readonly attempts: number readonly backoffMs: number readonly staleMinutes: number readonly calibration: CleanupCalibration } export type SplitPolicy = { /** Half-width of the acceptance band, in standard errors of a binomial at the target percent. */ readonly z: number /** New-version fetch invocations required before a step may advance. */ readonly minNewRequests: number readonly onMismatch: SplitAction readonly onInsufficient: EvidenceAction } /** * Workers Observability drops whole invocations in bursts. A smoke id with no log line or no trace is * telemetry loss: recorded with a count, rate and id list, and only fails the run above `maxLossRate`. * * `query` bounds retries of `cf o11y telemetry query`. The citation is run 2026-11-01T19-17-18-170Z: * one timeout at the 100% step. A recovered query is a normal sample. A query that never returns * does not invent zeroes for the series it did not fetch. */ export type QueryCalibration = { readonly source: string readonly date: string readonly window: string readonly n: number readonly web: string readonly ply: string readonly observed: string readonly percentile: string readonly headroom: string } export type TelemetryQueryPolicy = { readonly attempts: number readonly backoffMs: number readonly calibration: QueryCalibration } export type TelemetryPolicy = { /** Fraction of smoke ids in (0, 1] that may be missing from telemetry before the run fails. */ readonly maxLossRate: number readonly query: TelemetryQueryPolicy } /** Default when the policy omits `telemetry`: fail only when more than half of the smoke is missing. */ export const DEFAULT_MAX_LOSS_RATE = 0.5 /** * The rate limiter's silent-degradation gate (scripts/cd/rate-gate.ts, docs/rate-limit.md "CD gate"). Every number has * its evidence in `calibration`. Omitted from a policy file: DEFAULT_RATE_GATE (the same numbers as cd.policy.json). */ export type RateGatePolicy = { /** The limiter every real request must run (RATE_MODE). A deliberate RATE_MODE rollback edits this too. */ readonly expectMode: 'batched' | 'memo' | 'legacy' /** Pinned viewer requests the gate sends (load token, no mode header) so the version has default-mode checks. */ readonly probes: number readonly probeGapMs: number readonly probePath: string /** Warm default-mode checks needed before the fail_open share is judged. Fewer after the wait is a harness fault. */ readonly minChecks: number /** Warm (not the isolate's first) default-mode fail_open share above this fails the version. */ readonly maxFailOpenRate: number /** Flushes dropped (deadline, overflow) without an injected fault, above this fails the version. */ readonly maxDroppedFlushes: number readonly calibration: RateCalibration } export type RateCalibration = { readonly source: string readonly date: string readonly n: string readonly observed: string readonly headroom: string } export const DEFAULT_RATE_GATE: RateGatePolicy = { expectMode: 'memo', probes: 30, probeGapMs: 300, probePath: '/view?remote=https%3A%2F%2F5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net%2Fgit%2Fpublic-v0%2Fply.git', minChecks: 20, maxFailOpenRate: 0.1, maxDroppedFlushes: 0, calibration: { source: 'default for an omitted rate block; see cd.policy.json rate.calibration', date: '2026-11-07', n: 'see cd.policy.json', observed: 'see cd.policy.json', headroom: 'see cd.policy.json', }, } export type RolloutPolicy = { readonly steps: readonly RolloutStep[] readonly ingestWaitMs: number /** When > 0, the post-dwell ingest wait is polled at this period instead of one fixed sleep; `ingestWaitMs` is the ceiling. */ readonly ingestPollMs: number readonly warmupMs: number readonly probe: { readonly rps: number readonly calls: readonly ProbeCall[] /** Fraction of issued probes in (0, 1] that may be lost before the step is a harness fault. */ readonly maxLossRate: number readonly onHarnessFault: ProbeFaultAction readonly calibration: ProbeCalibration /** Per-request deadline. A probe that hits it is `timed_out`, not a transport error. */ readonly timeoutMs: number /** Outstanding probes. The next tick is `shed` once another batch would pass this. */ readonly maxInFlight: number /** Issued probes required before the loss-rate gate can fail the step. */ readonly minSamples: number /** A response at or above this, on both versions, is the same stall. */ readonly stallLatencyMs: number /** How many dwells a harness stall may run, including the first. */ readonly windowAttempts: number /** Wait between a stalled dwell and its re-run. */ readonly windowBackoffMs: number readonly schedule: ProbeScheduleCalibration } readonly gates: RolloutGates readonly burn: { readonly fastBurn: number readonly minSamples: number } readonly split: SplitPolicy readonly telemetry: TelemetryPolicy readonly cleanup: CleanupPolicy readonly rate: RateGatePolicy /** Evidence for the schedule's numbers (steps, ingest), keyed by field, like `probe.calibration`. Empty when omitted. */ readonly calibration: Readonly> } /** Citation for a schedule number: the runs it was read from, what they showed, and the headroom chosen. */ export type ScheduleCalibration = { readonly source: string readonly date: string readonly window: string readonly n: number readonly observed: string readonly headroom: string } const SCHEDULE_FIELDS: readonly string[] = ['steps[*].percent', 'steps[*].dwellMs', 'ingestWaitMs', 'ingestPollMs', 'warmupMs'] function scheduleCalibrationOf(value: unknown): Readonly> { const rec = record(value, 'calibration') const out: Record = {} for (const [key, entry] of Object.entries(rec)) { const path = `calibration.${key}` if (!SCHEDULE_FIELDS.includes(key)) reject(path, `names no schedule field (${SCHEDULE_FIELDS.join(', ')})`) const row = record(entry, path) exactKeys(row, path, ['source', 'date', 'window', 'n', 'observed', 'headroom']) out[key] = { source: textOf(row.source, `${path}.source`), date: textOf(row.date, `${path}.date`), window: textOf(row.window, `${path}.window`), n: integer(row.n, `${path}.n`, 1), observed: textOf(row.observed, `${path}.observed`), headroom: textOf(row.headroom, `${path}.headroom`), } } return out } export type LoadedPolicy = { readonly policy: RolloutPolicy readonly sha256: string readonly body: Json } function reject(path: string, message: string): never { throw new Error(`rollout policy ${path}: ${message}`) } function record(value: unknown, path: string): Record { if (value === null || typeof value !== 'object' || Array.isArray(value)) reject(path, 'must be an object') return value as Record } function exactKeys(rec: Record, path: string, keys: readonly string[], optional: readonly string[] = []): void { const allowed = new Set([...keys, ...optional]) for (const key of Object.keys(rec)) { if (!allowed.has(key)) reject(`${path}.${key}`, 'unknown field') } for (const key of keys) { if (!(key in rec)) reject(`${path}.${key}`, 'missing') } } function integer(value: unknown, path: string, min: number): number { if (typeof value !== 'number' || !Number.isInteger(value) || value < min) reject(path, `must be an integer >= ${min}`) return value } function positive(value: unknown, path: string): number { if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) reject(path, 'must be a number > 0') return value } function aboveOne(value: unknown, path: string): number { if (typeof value !== 'number' || !Number.isFinite(value) || value <= 1) reject(path, 'must be a number > 1') return value } function signal(value: unknown, path: string): SignalMode { if (value !== 'hard' && value !== 'informational') reject(path, 'must be hard or informational') return value } function oneOf(value: unknown, path: string, allowed: readonly T[]): T { if (typeof value === 'string' && (allowed as readonly string[]).includes(value)) return value as T reject(path, `must be ${allowed.join(' or ')}`) } function stepsOf(value: unknown): readonly RolloutStep[] { if (!Array.isArray(value) || value.length === 0) reject('steps', 'must be a non-empty list') const steps: RolloutStep[] = [] for (let index = 0; index < value.length; index++) { const path = `steps[${index}]` const rec = record(value[index], path) exactKeys(rec, path, ['percent', 'dwellMs']) const percent = integer(rec.percent, `${path}.percent`, 1) if (percent > 100) reject(`${path}.percent`, 'must be <= 100') const dwellMs = integer(rec.dwellMs, `${path}.dwellMs`, 1) const previous = steps[steps.length - 1] if (previous && percent <= previous.percent) reject(`${path}.percent`, 'steps must be strictly increasing') steps.push({ percent, dwellMs }) } const last = steps[steps.length - 1] if (!last || last.percent !== 100) reject('steps', 'the last step must be 100') // Ramp-only (Ivar, 2026-11-08): a lone 100 step is the removed direct promote, 0% straight to 100%. if (steps.length < 2) reject('steps', 'must ramp: at least one step below 100 before the last (a single 0 to 100 step is a direct promote)') return steps } /** `/path` plus an optional `?query`. The engine sends this string unchanged. */ const PROBE_PATH = /^\/[^\s?#]*(\?[^\s#]*)?$/ function probePath(value: unknown, path: string): string { if (typeof value !== 'string' || !PROBE_PATH.test(value)) { reject(path, 'must be a path starting with /, plus an optional query') } return value } function textOf(value: unknown, path: string): string { if (typeof value !== 'string' || value.length === 0) reject(path, 'must be a non-empty string') return value } function calibrationOf(value: unknown): ProbeCalibration { const rec = record(value, 'probe.calibration') exactKeys(rec, 'probe.calibration', ['source', 'date', 'window', 'n', 'lost', 'web', 'ply', 'observedRate', 'percentile', 'headroom']) return { source: textOf(rec.source, 'probe.calibration.source'), date: textOf(rec.date, 'probe.calibration.date'), window: textOf(rec.window, 'probe.calibration.window'), n: integer(rec.n, 'probe.calibration.n', 1), lost: integer(rec.lost, 'probe.calibration.lost', 0), web: textOf(rec.web, 'probe.calibration.web'), ply: textOf(rec.ply, 'probe.calibration.ply'), observedRate: textOf(rec.observedRate, 'probe.calibration.observedRate'), percentile: textOf(rec.percentile, 'probe.calibration.percentile'), headroom: textOf(rec.headroom, 'probe.calibration.headroom'), } } function scheduleOf(value: unknown): ProbeScheduleCalibration { const rec = record(value, 'probe.schedule') exactKeys(rec, 'probe.schedule', [ 'source', 'date', 'window', 'n', 'responded', 'lost', 'healthyN', 'web', 'oldVersion', 'newVersion', 'healthyP50Ms', 'observedStallMs', 'dwellMs', 'observedRate', 'percentile', 'headroom', ]) return { source: textOf(rec.source, 'probe.schedule.source'), date: textOf(rec.date, 'probe.schedule.date'), window: textOf(rec.window, 'probe.schedule.window'), n: integer(rec.n, 'probe.schedule.n', 1), responded: integer(rec.responded, 'probe.schedule.responded', 0), lost: integer(rec.lost, 'probe.schedule.lost', 0), healthyN: integer(rec.healthyN, 'probe.schedule.healthyN', 1), web: textOf(rec.web, 'probe.schedule.web'), oldVersion: textOf(rec.oldVersion, 'probe.schedule.oldVersion'), newVersion: textOf(rec.newVersion, 'probe.schedule.newVersion'), healthyP50Ms: textOf(rec.healthyP50Ms, 'probe.schedule.healthyP50Ms'), observedStallMs: integer(rec.observedStallMs, 'probe.schedule.observedStallMs', 0), dwellMs: integer(rec.dwellMs, 'probe.schedule.dwellMs', 1), observedRate: textOf(rec.observedRate, 'probe.schedule.observedRate'), percentile: textOf(rec.percentile, 'probe.schedule.percentile'), headroom: textOf(rec.headroom, 'probe.schedule.headroom'), } } function callsOf(value: unknown): readonly ProbeCall[] { if (!Array.isArray(value)) reject('probe.calls', 'must be a list') return value.map((item, index) => { const path = `probe.calls[${index}]` const rec = record(item, path) exactKeys(rec, path, ['method', 'path', 'auth']) if (rec.method !== 'GET' && rec.method !== 'POST') reject(`${path}.method`, 'must be GET or POST') const callPath = probePath(rec.path, `${path}.path`) if (typeof rec.auth !== 'boolean') reject(`${path}.auth`, 'must be a boolean') return { method: rec.method, path: callPath, auth: rec.auth } }) } function latencyOf(value: unknown): LatencyPolicy { const rec = record(value, 'gates.latency') const mode = rec.mode if (mode === 'off' || mode === 'informational') { exactKeys(rec, 'gates.latency', ['mode']) return { mode } } if (mode !== 'gate') reject('gates.latency.mode', 'must be off, informational, or gate') if (rec.minSamples === undefined || rec.p99Ratio === undefined || rec.effectFloorMs === undefined) { reject('gates.latency', 'latency=gate needs minSamples, p99Ratio, and effectFloorMs') } exactKeys(rec, 'gates.latency', ['mode', 'minSamples', 'p99Ratio', 'effectFloorMs']) return { mode: 'gate', minSamples: integer(rec.minSamples, 'gates.latency.minSamples', 1), p99Ratio: aboveOne(rec.p99Ratio, 'gates.latency.p99Ratio'), effectFloorMs: positive(rec.effectFloorMs, 'gates.latency.effectFloorMs'), } } function gatesOf(value: unknown): RolloutGates { const rec = record(value, 'gates') exactKeys(rec, 'gates', ['smoke', 'fivexx', 'exceptions', 'errorLogs', 'nonOk', 'burn', 'latency']) return { smoke: signal(rec.smoke, 'gates.smoke'), fivexx: signal(rec.fivexx, 'gates.fivexx'), exceptions: signal(rec.exceptions, 'gates.exceptions'), errorLogs: signal(rec.errorLogs, 'gates.errorLogs'), nonOk: signal(rec.nonOk, 'gates.nonOk'), burn: signal(rec.burn, 'gates.burn'), latency: latencyOf(rec.latency), } } function splitOf(value: unknown): SplitPolicy { const rec = record(value, 'split') exactKeys(rec, 'split', ['z', 'minNewRequests', 'onMismatch', 'onInsufficient']) return { z: positive(rec.z, 'split.z'), minNewRequests: integer(rec.minNewRequests, 'split.minNewRequests', 1), onMismatch: oneOf(rec.onMismatch, 'split.onMismatch', ['hold', 'rollback']), onInsufficient: oneOf(rec.onInsufficient, 'split.onInsufficient', ['advance', 'hold']), } } function rate(value: unknown, path: string): number { if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 1) reject(path, 'must be a number in (0, 1]') return value } function cleanupCalibrationOf(value: unknown): CleanupCalibration { const rec = record(value, 'cleanup.calibration') exactKeys(rec, 'cleanup.calibration', ['source', 'date', 'window', 'n', 'latencyMs', 'web', 'namespace', 'observed', 'percentile', 'headroom']) return { source: textOf(rec.source, 'cleanup.calibration.source'), date: textOf(rec.date, 'cleanup.calibration.date'), window: textOf(rec.window, 'cleanup.calibration.window'), n: integer(rec.n, 'cleanup.calibration.n', 1), latencyMs: integer(rec.latencyMs, 'cleanup.calibration.latencyMs', 0), web: textOf(rec.web, 'cleanup.calibration.web'), namespace: textOf(rec.namespace, 'cleanup.calibration.namespace'), observed: textOf(rec.observed, 'cleanup.calibration.observed'), percentile: textOf(rec.percentile, 'cleanup.calibration.percentile'), headroom: textOf(rec.headroom, 'cleanup.calibration.headroom'), } } function cleanupOf(value: unknown): CleanupPolicy { const rec = record(value, 'cleanup') exactKeys(rec, 'cleanup', ['attempts', 'backoffMs', 'staleMinutes', 'calibration']) return { attempts: integer(rec.attempts, 'cleanup.attempts', 1), backoffMs: integer(rec.backoffMs, 'cleanup.backoffMs', 0), staleMinutes: integer(rec.staleMinutes, 'cleanup.staleMinutes', 1), calibration: cleanupCalibrationOf(rec.calibration), } } function queryCalibrationOf(value: unknown): QueryCalibration { const rec = record(value, 'telemetry.query.calibration') exactKeys(rec, 'telemetry.query.calibration', ['source', 'date', 'window', 'n', 'web', 'ply', 'observed', 'percentile', 'headroom']) return { source: textOf(rec.source, 'telemetry.query.calibration.source'), date: textOf(rec.date, 'telemetry.query.calibration.date'), window: textOf(rec.window, 'telemetry.query.calibration.window'), n: integer(rec.n, 'telemetry.query.calibration.n', 1), web: textOf(rec.web, 'telemetry.query.calibration.web'), ply: textOf(rec.ply, 'telemetry.query.calibration.ply'), observed: textOf(rec.observed, 'telemetry.query.calibration.observed'), percentile: textOf(rec.percentile, 'telemetry.query.calibration.percentile'), headroom: textOf(rec.headroom, 'telemetry.query.calibration.headroom'), } } function queryPolicyOf(value: unknown): TelemetryQueryPolicy { const rec = record(value, 'telemetry.query') exactKeys(rec, 'telemetry.query', ['attempts', 'backoffMs', 'calibration']) return { attempts: integer(rec.attempts, 'telemetry.query.attempts', 1), backoffMs: integer(rec.backoffMs, 'telemetry.query.backoffMs', 0), calibration: queryCalibrationOf(rec.calibration), } } /** Used only when the policy file omits `telemetry`. The numbers match the checked-in block. */ function defaultTelemetry(): TelemetryPolicy { return { maxLossRate: DEFAULT_MAX_LOSS_RATE, query: { attempts: 3, backoffMs: 1000, calibration: { source: 'run 2026-11-01T19-17-18-170Z', date: '2026-11-01', window: '100% ramp step', n: 1, web: '07568e0', ply: '1743461', observed: 'cf o11y telemetry query --body APIError timeout Envelope Error, exit 1', percentile: 'one measured query, not a percentile', headroom: 'default for an omitted telemetry block. attempts is 3. backoffMs 1000 is PRIOR: the run did not retry.', }, }, } } function telemetryOf(value: unknown): TelemetryPolicy { if (value === undefined) return defaultTelemetry() const rec = record(value, 'telemetry') exactKeys(rec, 'telemetry', ['query'], ['maxLossRate']) return { maxLossRate: rec.maxLossRate === undefined ? DEFAULT_MAX_LOSS_RATE : rate(rec.maxLossRate, 'telemetry.maxLossRate'), query: queryPolicyOf(rec.query), } } function unitRate(value: unknown, path: string): number { if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) reject(path, 'must be a number in [0, 1]') return value } function rateGateOf(parent: Record): RateGatePolicy { if (!('rate' in parent)) return DEFAULT_RATE_GATE const rec = record(parent.rate, 'rate') exactKeys(rec, 'rate', ['expectMode', 'probes', 'probeGapMs', 'probePath', 'minChecks', 'maxFailOpenRate', 'maxDroppedFlushes', 'calibration']) const cal = record(rec.calibration, 'rate.calibration') exactKeys(cal, 'rate.calibration', ['source', 'date', 'n', 'observed', 'headroom']) const probes = integer(rec.probes, 'rate.probes', 0) const minChecks = integer(rec.minChecks, 'rate.minChecks', 1) if (probes > 0 && minChecks > probes) reject('rate.minChecks', 'must be <= rate.probes (the probes are what fills it)') return { expectMode: oneOf(rec.expectMode, 'rate.expectMode', ['batched', 'memo', 'legacy']), probes, probeGapMs: integer(rec.probeGapMs, 'rate.probeGapMs', 0), probePath: probePath(rec.probePath, 'rate.probePath'), minChecks, maxFailOpenRate: unitRate(rec.maxFailOpenRate, 'rate.maxFailOpenRate'), maxDroppedFlushes: integer(rec.maxDroppedFlushes, 'rate.maxDroppedFlushes', 0), calibration: { source: textOf(cal.source, 'rate.calibration.source'), date: textOf(cal.date, 'rate.calibration.date'), n: textOf(cal.n, 'rate.calibration.n'), observed: textOf(cal.observed, 'rate.calibration.observed'), headroom: textOf(cal.headroom, 'rate.calibration.headroom'), }, } } function validate(value: unknown): RolloutPolicy { const rec = record(value, 'policy') // The direct promote (one write to 100%, `promote.watchMs` watch) was removed 2026-11-08 (Ivar: "Ramp should be the // only option."). Name it, so an old policy file is not just an unknown key. if ('promote' in rec) reject('promote', 'was removed 2026-11-08: the stepped ramp in steps is the only promotion path') exactKeys(rec, 'policy', ['steps', 'ingestWaitMs', 'probe', 'gates', 'burn', 'split', 'cleanup'], ['warmupMs', 'telemetry', 'ingestPollMs', 'rate', 'calibration']) const probe = record(rec.probe, 'probe') exactKeys(probe, 'probe', [ 'rps', 'calls', 'maxLossRate', 'onHarnessFault', 'calibration', 'timeoutMs', 'maxInFlight', 'minSamples', 'stallLatencyMs', 'windowAttempts', 'windowBackoffMs', 'schedule', ]) const rps = probe.rps if (typeof rps !== 'number' || !Number.isFinite(rps) || rps < 0) reject('probe.rps', 'must be a number >= 0') const calls = callsOf(probe.calls) if (rps > 0 && calls.length === 0) reject('probe.calls', 'probe rps needs at least one call') const onHarnessFault = oneOf(probe.onHarnessFault, 'probe.onHarnessFault', ['rollback', 'hold', 'telemetry']) const burn = record(rec.burn, 'burn') exactKeys(burn, 'burn', ['fastBurn', 'minSamples']) return { steps: stepsOf(rec.steps), ingestWaitMs: integer(rec.ingestWaitMs, 'ingestWaitMs', 0), ingestPollMs: 'ingestPollMs' in rec ? integer(rec.ingestPollMs, 'ingestPollMs', 0) : 0, warmupMs: rec.warmupMs === undefined ? 0 : integer(rec.warmupMs, 'warmupMs', 0), probe: { rps, calls, maxLossRate: rate(probe.maxLossRate, 'probe.maxLossRate'), onHarnessFault, calibration: calibrationOf(probe.calibration), timeoutMs: integer(probe.timeoutMs, 'probe.timeoutMs', 1), maxInFlight: integer(probe.maxInFlight, 'probe.maxInFlight', 1), minSamples: integer(probe.minSamples, 'probe.minSamples', 1), stallLatencyMs: integer(probe.stallLatencyMs, 'probe.stallLatencyMs', 1), windowAttempts: integer(probe.windowAttempts, 'probe.windowAttempts', 1), windowBackoffMs: integer(probe.windowBackoffMs, 'probe.windowBackoffMs', 0), schedule: scheduleOf(probe.schedule), }, gates: gatesOf(rec.gates), burn: { fastBurn: positive(burn.fastBurn, 'burn.fastBurn'), minSamples: integer(burn.minSamples, 'burn.minSamples', 1), }, split: splitOf(rec.split), telemetry: telemetryOf(rec.telemetry), cleanup: cleanupOf(rec.cleanup), rate: rateGateOf(rec), calibration: 'calibration' in rec ? scheduleCalibrationOf(rec.calibration) : {}, } } function policyBody(policy: RolloutPolicy): Json { const latency: Json = policy.gates.latency.mode === 'gate' ? { mode: 'gate', minSamples: policy.gates.latency.minSamples, p99Ratio: policy.gates.latency.p99Ratio, effectFloorMs: policy.gates.latency.effectFloorMs, } : { mode: policy.gates.latency.mode } return { steps: policy.steps.map(step => ({ percent: step.percent, dwellMs: step.dwellMs })), ingestWaitMs: policy.ingestWaitMs, ingestPollMs: policy.ingestPollMs, warmupMs: policy.warmupMs, probe: { rps: policy.probe.rps, maxLossRate: policy.probe.maxLossRate, onHarnessFault: policy.probe.onHarnessFault, calibration: { source: policy.probe.calibration.source, date: policy.probe.calibration.date, window: policy.probe.calibration.window, n: policy.probe.calibration.n, lost: policy.probe.calibration.lost, web: policy.probe.calibration.web, ply: policy.probe.calibration.ply, observedRate: policy.probe.calibration.observedRate, percentile: policy.probe.calibration.percentile, headroom: policy.probe.calibration.headroom, }, calls: policy.probe.calls.map(call => ({ method: call.method, path: call.path, auth: call.auth })), timeoutMs: policy.probe.timeoutMs, maxInFlight: policy.probe.maxInFlight, minSamples: policy.probe.minSamples, stallLatencyMs: policy.probe.stallLatencyMs, windowAttempts: policy.probe.windowAttempts, windowBackoffMs: policy.probe.windowBackoffMs, schedule: { source: policy.probe.schedule.source, date: policy.probe.schedule.date, window: policy.probe.schedule.window, n: policy.probe.schedule.n, responded: policy.probe.schedule.responded, lost: policy.probe.schedule.lost, healthyN: policy.probe.schedule.healthyN, web: policy.probe.schedule.web, oldVersion: policy.probe.schedule.oldVersion, newVersion: policy.probe.schedule.newVersion, healthyP50Ms: policy.probe.schedule.healthyP50Ms, observedStallMs: policy.probe.schedule.observedStallMs, dwellMs: policy.probe.schedule.dwellMs, observedRate: policy.probe.schedule.observedRate, percentile: policy.probe.schedule.percentile, headroom: policy.probe.schedule.headroom, }, }, gates: { smoke: policy.gates.smoke, fivexx: policy.gates.fivexx, exceptions: policy.gates.exceptions, errorLogs: policy.gates.errorLogs, nonOk: policy.gates.nonOk, burn: policy.gates.burn, latency, }, burn: { fastBurn: policy.burn.fastBurn, minSamples: policy.burn.minSamples }, split: { z: policy.split.z, minNewRequests: policy.split.minNewRequests, onMismatch: policy.split.onMismatch, onInsufficient: policy.split.onInsufficient, }, telemetry: { maxLossRate: policy.telemetry.maxLossRate, query: { attempts: policy.telemetry.query.attempts, backoffMs: policy.telemetry.query.backoffMs, calibration: { source: policy.telemetry.query.calibration.source, date: policy.telemetry.query.calibration.date, window: policy.telemetry.query.calibration.window, n: policy.telemetry.query.calibration.n, web: policy.telemetry.query.calibration.web, ply: policy.telemetry.query.calibration.ply, observed: policy.telemetry.query.calibration.observed, percentile: policy.telemetry.query.calibration.percentile, headroom: policy.telemetry.query.calibration.headroom, }, }, }, calibration: Object.fromEntries(Object.entries(policy.calibration).map(([key, row]) => [key, { source: row.source, date: row.date, window: row.window, n: row.n, observed: row.observed, headroom: row.headroom, }])), rate: { expectMode: policy.rate.expectMode, probes: policy.rate.probes, probeGapMs: policy.rate.probeGapMs, probePath: policy.rate.probePath, minChecks: policy.rate.minChecks, maxFailOpenRate: policy.rate.maxFailOpenRate, maxDroppedFlushes: policy.rate.maxDroppedFlushes, calibration: { ...policy.rate.calibration }, }, cleanup: { attempts: policy.cleanup.attempts, backoffMs: policy.cleanup.backoffMs, staleMinutes: policy.cleanup.staleMinutes, calibration: { source: policy.cleanup.calibration.source, date: policy.cleanup.calibration.date, window: policy.cleanup.calibration.window, n: policy.cleanup.calibration.n, latencyMs: policy.cleanup.calibration.latencyMs, web: policy.cleanup.calibration.web, namespace: policy.cleanup.calibration.namespace, observed: policy.cleanup.calibration.observed, percentile: policy.cleanup.calibration.percentile, headroom: policy.cleanup.calibration.headroom, }, }, } } /** Parse and validate. The hash is the raw file bytes, so two spellings of the same rules do not share a hash. */ export function parsePolicy(text: string): LoadedPolicy { let value: unknown try { value = JSON.parse(text) as unknown } catch { throw new Error('rollout policy is not JSON') } const policy = validate(value) return { policy, sha256: createHash('sha256').update(text).digest('hex'), body: policyBody(policy) } } export function loadPolicy(path: string): LoadedPolicy { let text: string try { text = readFileSync(path, 'utf8') } catch { throw new Error(`cannot read rollout policy ${path}`) } return parsePolicy(text) } /** `--policy` is removed before command parsing. A missing or repeated value is an error. */ export function splitPolicy(argv: readonly string[]): { readonly argv: readonly string[]; readonly policyPath: string | null } | { readonly error: string } { const kept: string[] = [] let policyPath: string | null = null for (let index = 0; index < argv.length; index++) { const arg = argv[index] ?? '' if (arg !== '--policy') { kept.push(arg) continue } const value = argv[index + 1] if (!value || value.startsWith('--')) return { error: '--policy needs a path' } if (policyPath) return { error: '--policy was given twice' } policyPath = value index += 1 } return { argv: kept, policyPath } }