diff --git a/backend/src/services/__tests__/renewalPause.test.ts b/backend/src/services/__tests__/renewalPause.test.ts new file mode 100644 index 00000000..760207df --- /dev/null +++ b/backend/src/services/__tests__/renewalPause.test.ts @@ -0,0 +1,204 @@ +import { + DEFAULT_RENEWAL_PAUSE_CONFIG, + RenewalPauseError, + createRenewalPauseService, + determineRenewalPause, + shouldPause, + summarizeUsage, + validateRenewalPauseConfig, + type ActivePause, + type UsageSample, +} from '../renewalPause'; + +const NOW = Date.parse('2026-11-24T12:00:00.000Z'); + +function samples(units: number[], start = '2026-11-18T12:00:00.000Z'): UsageSample[] { + const base = Date.parse(start); + return units.map((u, i) => ({ + at: new Date(base + i * 86400000).toISOString(), + units: u, + })); +} + +describe('renewalPause service (issue #2251)', () => { + describe('validateRenewalPauseConfig', () => { + it('returns frozen defaults', () => { + const c = validateRenewalPauseConfig(); + expect(c.usageFloor).toBe(DEFAULT_RENEWAL_PAUSE_CONFIG.usageFloor); + expect(Object.isFrozen(c)).toBe(true); + }); + + it('rejects invalid usageFloor', () => { + expect(() => validateRenewalPauseConfig({ usageFloor: -1 })).toThrow(RenewalPauseError); + expect(() => validateRenewalPauseConfig({ usageFloor: Number.NaN })).toThrow(RenewalPauseError); + }); + + it('rejects invalid windowDays and minSamples', () => { + expect(() => validateRenewalPauseConfig({ windowDays: 0 })).toThrow(RenewalPauseError); + expect(() => validateRenewalPauseConfig({ windowDays: 400 })).toThrow(RenewalPauseError); + expect(() => validateRenewalPauseConfig({ minSamples: 40 })).toThrow(RenewalPauseError); + }); + + it('rejects pause duration exceeding the cap', () => { + expect(() => + validateRenewalPauseConfig({ pauseDurationDays: 100, maxPauseDays: 90 }), + ).toThrow(RenewalPauseError); + }); + + it('rejects non-object config', () => { + expect(() => validateRenewalPauseConfig(null as never)).toThrow(RenewalPauseError); + }); + }); + + describe('summarizeUsage', () => { + it('summarises samples in the trailing window', () => { + const signal = summarizeUsage(samples([2, 2, 2, 2]), {}, NOW); + expect(signal.sampleCount).toBe(4); + expect(signal.total).toBe(8); + expect(signal.average).toBe(2); + expect(signal.belowFloor).toBe(false); + expect(Object.isFrozen(signal)).toBe(true); + }); + + it('flags usage below the floor', () => { + const signal = summarizeUsage(samples([0, 0, 0]), { usageFloor: 1 }, NOW); + expect(signal.belowFloor).toBe(true); + expect(signal.average).toBe(0); + }); + + it('ignores samples outside the window', () => { + const old = [{ at: '2020-01-01T00:00:00.000Z', units: 100 }]; + expect(summarizeUsage(old, {}, NOW).sampleCount).toBe(0); + expect(summarizeUsage(old, {}, NOW).belowFloor).toBe(false); + }); + + it('rejects malformed samples with stable codes', () => { + try { + summarizeUsage([{ at: '2026-11-20T00:00:00Z', units: -1 }], {}, NOW); + throw new Error('expected failure'); + } catch (err) { + expect(err).toBeInstanceOf(RenewalPauseError); + expect((err as RenewalPauseError).code).toBe('INVALID_USAGE'); + } + try { + summarizeUsage([{ at: 'nope', units: 1 }], {}, NOW); + throw new Error('expected failure'); + } catch (err) { + expect((err as RenewalPauseError).code).toBe('INVALID_DATE'); + } + }); + + it('rejects a non-array sample list', () => { + expect(() => summarizeUsage('nope' as never, {}, NOW)).toThrow(RenewalPauseError); + }); + }); + + describe('determineRenewalPause', () => { + it('pauses when usage is below the floor with enough samples', () => { + const signal = summarizeUsage(samples([0, 0, 0, 0, 0, 0, 0]), {}, NOW); + const decision = determineRenewalPause(signal, {}, undefined, NOW); + expect(decision.action).toBe('pause'); + expect(decision.reason).toBe('USAGE_BELOW_FLOOR'); + expect(decision.pausedUntil).not.toBeNull(); + expect(shouldPause(decision)).toBe(true); + expect(Object.isFrozen(decision)).toBe(true); + }); + + it('fails open with no signal or too few samples', () => { + const empty = summarizeUsage([], {}, NOW); + expect(determineRenewalPause(empty, {}, undefined, NOW).reason).toBe('NO_SIGNAL'); + const thin = summarizeUsage(samples([0, 0]), {}, NOW); + expect(determineRenewalPause(thin, {}, undefined, NOW).reason).toBe('INSUFFICIENT_SAMPLES'); + expect(determineRenewalPause(thin, {}, undefined, NOW).action).toBe('keep'); + }); + + it('keeps a subscription whose usage is above the floor', () => { + const signal = summarizeUsage(samples([3, 3, 3, 3, 3, 3, 3]), {}, NOW); + expect(determineRenewalPause(signal, {}, undefined, NOW).reason).toBe('USAGE_ABOVE_FLOOR'); + }); + + it('keeps an active pause and resumes when it expires', () => { + const signal = summarizeUsage(samples([0, 0, 0, 0, 0, 0, 0]), {}, NOW); + const active: ActivePause = { pausedUntil: '2026-12-10T00:00:00.000Z', pausedDays: 10 }; + const kept = determineRenewalPause(signal, {}, active, NOW); + expect(kept.action).toBe('keep'); + expect(kept.reason).toBe('PAUSE_ACTIVE'); + const expired: ActivePause = { pausedUntil: '2026-11-20T00:00:00.000Z', pausedDays: 30 }; + expect(determineRenewalPause(signal, {}, expired, NOW).reason).toBe('PAUSE_EXPIRED'); + }); + + it('rejects an invalid active pause', () => { + const signal = summarizeUsage(samples([0, 0]), {}, NOW); + expect(() => + determineRenewalPause( + signal, + {}, + { pausedUntil: 'bad', pausedDays: 0 }, + NOW, + ), + ).toThrow(RenewalPauseError); + }); + }); + + describe('createRenewalPauseService', () => { + it('builds a frozen plan and fires metrics/logger hooks', () => { + const events: string[] = []; + let kept = 0; + const service = createRenewalPauseService( + { usageFloor: 1 }, + { + recordPaused() { events.push('paused'); }, + recordResumed() { events.push('resumed'); }, + recordKept() { kept += 1; }, + recordRejected() { events.push('rejected'); }, + recordEvaluated() { events.push('evaluated'); }, + }, + { + warn() { events.push('warn'); }, + info() { events.push('info'); }, + }, + ); + const plan = service.plan( + [ + { subscriptionId: 'low', samples: samples([0, 0, 0, 0, 0, 0, 0]) }, + { subscriptionId: 'high', samples: samples([5, 5, 5, 5, 5, 5, 5]) }, + ], + NOW, + ); + expect(plan.total).toBe(2); + expect(plan.paused).toBe(1); + expect(plan.decisions[0].subscriptionId).toBe('low'); + expect(plan.decisions[0].action).toBe('pause'); + expect(plan.decisions[1].action).toBe('keep'); + expect(kept).toBe(1); + expect(events).toContain('paused'); + expect(events).toContain('evaluated'); + expect(events).toContain('warn'); + expect(Object.isFrozen(plan)).toBe(true); + expect(Object.isFrozen(service)).toBe(true); + }); + + it('reports rejections per item without aborting the batch', () => { + const service = createRenewalPauseService({}, { + recordRejected() { /* observed */ }, + }); + const plan = service.plan( + [ + { subscriptionId: 'ok', samples: samples([1, 1, 1, 1, 1, 1, 1]) }, + { subscriptionId: 'bad', samples: [{ at: 'x', units: 1 }] }, + { subscriptionId: '', samples: [] }, + ], + NOW, + ); + expect(plan.decisions.length).toBe(1); + expect(plan.rejected.length).toBe(2); + expect(plan.rejected.map((r) => r.code)).toContain('INVALID_DATE'); + expect(plan.rejected.map((r) => r.code)).toContain('INVALID_INPUT'); + }); + + it('rejects a non-array plan input', () => { + const service = createRenewalPauseService(); + expect(() => service.plan('nope' as never, NOW)).toThrow(RenewalPauseError); + }); + }); +}); diff --git a/backend/src/services/renewalPause.ts b/backend/src/services/renewalPause.ts new file mode 100644 index 00000000..dbe1a1d1 --- /dev/null +++ b/backend/src/services/renewalPause.ts @@ -0,0 +1,487 @@ +/** + * backend/src/services/renewalPause.ts + * + * Issue #2251 — smart renewal pause when usage drops below a configurable floor. + * + * A subscription that has stopped being used should not be charged again while + * the subscriber is getting no value from it. This module is pure and + * dependency-free: it turns a short history of usage samples into a bounded, + * explainable pause decision. It never touches a database, a payment gateway or + * the ML service. The caller (the renewal worker) owns persistence and any + * actual charge; the ML signal (`ml-service/app/usage/floor.py`) owns the + * statistical summary that feeds `evaluate`. + * + * Design rules (consistent with the sibling `billingShift.ts` service): + * - every observable failure has a stable `code` and never throws a raw error; + * - configuration is validated once, then frozen; + * - every returned decision/signal/plan is frozen so callers cannot mutate it; + * - metrics and logger hooks are injected and default to no-ops. + */ + +// ── Public types ────────────────────────────────────────────────────────────── + +export type RenewalPauseErrorCode = + | 'INVALID_CONFIG' + | 'INVALID_INPUT' + | 'INVALID_USAGE' + | 'INVALID_DATE' + | 'NO_SIGNAL'; + +export type RenewalPauseAction = 'pause' | 'keep' | 'resume'; + +export type RenewalPauseReason = + | 'USAGE_BELOW_FLOOR' + | 'USAGE_ABOVE_FLOOR' + | 'INSUFFICIENT_SAMPLES' + | 'NO_SIGNAL' + | 'PAUSE_EXPIRED' + | 'PAUSE_ACTIVE'; + +export class RenewalPauseError extends Error { + readonly code: RenewalPauseErrorCode; + readonly details: Readonly> | undefined; + + constructor(code: RenewalPauseErrorCode, message: string, details?: Record) { + super(message); + this.name = 'RenewalPauseError'; + this.code = code; + this.details = details; + Object.setPrototypeOf(this, RenewalPauseError.prototype); + } + + static invalidConfig(message: string, details?: Record): RenewalPauseError { + return new RenewalPauseError('INVALID_CONFIG', message, details); + } + + static invalidInput(message: string, details?: Record): RenewalPauseError { + return new RenewalPauseError('INVALID_INPUT', message, details); + } +} + +export interface RenewalPauseConfig { + /** Minimum average daily units required to keep auto-renewal on (default 1). */ + usageFloor: number; + /** Length of the trailing evaluation window in whole days (default 30). */ + windowDays: number; + /** Samples needed before a pause is allowed (default 7). Fail-open below this. */ + minSamples: number; + /** Days a pause lasts before the subscriber can be evaluated again (default 30). */ + pauseDurationDays: number; + /** Hard cap on consecutive pause extensions (default 90). */ + maxPauseDays: number; + /** Days of grace added after the floor is breached (default 3). */ + gracePeriodDays: number; + /** Local timezone adjustment applied to sample dates, in minutes (default 0). */ + timezoneOffsetMinutes: number; +} + +export const DEFAULT_RENEWAL_PAUSE_CONFIG: Readonly = Object.freeze({ + usageFloor: 1, + windowDays: 30, + minSamples: 7, + pauseDurationDays: 30, + maxPauseDays: 90, + gracePeriodDays: 3, + timezoneOffsetMinutes: 0, +}); + +export interface RenewalPauseMetrics { + recordPaused(subscriptionId: string, observed: number, floor: number): void; + recordResumed(subscriptionId: string, reason: RenewalPauseReason): void; + recordKept(subscriptionId: string, observed: number): void; + recordRejected(code: RenewalPauseErrorCode): void; + recordEvaluated(total: number, paused: number): void; +} + +export interface RenewalPauseLogger { + info(message: string, details?: Record): void; + warn(message: string, details?: Record): void; +} + +export const noopRenewalPauseMetrics: Readonly = Object.freeze({ + recordPaused(): void {}, + recordResumed(): void {}, + recordKept(): void {}, + recordRejected(): void {}, + recordEvaluated(): void {}, +}); + +export const noopRenewalPauseLogger: Readonly = Object.freeze({ + info(): void {}, + warn(): void {}, +}); + +export function isNonNegativeFinite(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) && value >= 0; +} + +/** Validate and freeze a config, applying defaults for absent fields. */ +export function validateRenewalPauseConfig(config: Partial = {}): RenewalPauseConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw RenewalPauseError.invalidConfig('config must be an object'); + } + const merged: RenewalPauseConfig = { ...DEFAULT_RENEWAL_PAUSE_CONFIG, ...config }; + + if (!isNonNegativeFinite(merged.usageFloor)) { + throw RenewalPauseError.invalidConfig('usageFloor must be a non-negative finite number', { + usageFloor: config.usageFloor, + }); + } + if (!Number.isSafeInteger(merged.windowDays) || merged.windowDays < 1 || merged.windowDays > 365) { + throw RenewalPauseError.invalidConfig('windowDays must be an integer 1-365', { + windowDays: config.windowDays, + }); + } + if (!Number.isSafeInteger(merged.minSamples) || merged.minSamples < 1 || merged.minSamples > merged.windowDays) { + throw RenewalPauseError.invalidConfig('minSamples must be an integer between 1 and windowDays', { + minSamples: config.minSamples, + windowDays: config.windowDays, + }); + } + if ( + !Number.isSafeInteger(merged.pauseDurationDays) || + merged.pauseDurationDays < 1 || + merged.pauseDurationDays > merged.maxPauseDays + ) { + throw RenewalPauseError.invalidConfig('pauseDurationDays must be an integer within maxPauseDays', { + pauseDurationDays: config.pauseDurationDays, + }); + } + if (!Number.isSafeInteger(merged.maxPauseDays) || merged.maxPauseDays < 1 || merged.maxPauseDays > 365) { + throw RenewalPauseError.invalidConfig('maxPauseDays must be an integer 1-365', { + maxPauseDays: config.maxPauseDays, + }); + } + if ( + !Number.isSafeInteger(merged.gracePeriodDays) || + merged.gracePeriodDays < 0 || + merged.gracePeriodDays > merged.windowDays + ) { + throw RenewalPauseError.invalidConfig('gracePeriodDays must be an integer within windowDays', { + gracePeriodDays: config.gracePeriodDays, + }); + } + if (!Number.isFinite(merged.timezoneOffsetMinutes) || Math.abs(merged.timezoneOffsetMinutes) > 1440) { + throw RenewalPauseError.invalidConfig('timezoneOffsetMinutes must be within +/-1440', { + timezoneOffsetMinutes: config.timezoneOffsetMinutes, + }); + } + return Object.freeze(merged); +} + +// ── Usage signal ────────────────────────────────────────────────────────────── + +export interface UsageSample { + /** ISO-8601 instant the observation belongs to. */ + readonly at: string; + /** Units consumed in that observation. Must be a non-negative finite number. */ + readonly units: number; +} + +export interface UsageSignal { + readonly sampleCount: number; + readonly average: number; + readonly total: number; + readonly floor: number; + readonly belowFloor: boolean; + readonly windowStart: string; + readonly windowEnd: string; +} + +function parseInstant(value: string, code: RenewalPauseErrorCode): number { + if (typeof value !== 'string' || value.trim() === '') { + throw new RenewalPauseError(code, 'timestamp must be a non-empty string'); + } + const parsed = Date.parse(value); + if (!Number.isFinite(parsed)) { + throw new RenewalPauseError(code, 'timestamp is not a valid ISO-8601 instant', { value }); + } + return parsed; +} + +/** + * Summarise the samples inside the trailing window. Samples outside the window + * and malformed samples are rejected (not silently ignored) with stable codes. + */ +export function summarizeUsage( + samples: readonly UsageSample[], + config: Partial = {}, + now: string | number = Date.now(), +): UsageSignal { + const cfg = validateRenewalPauseConfig(config); + if (!Array.isArray(samples)) { + throw RenewalPauseError.invalidInput('samples must be an array'); + } + + const nowMs = typeof now === 'number' ? now : parseInstant(now, 'INVALID_DATE'); + if (!Number.isFinite(nowMs)) { + throw new RenewalPauseError('INVALID_DATE', 'now must be a finite value'); + } + const windowMs = cfg.windowDays * 86400000; + const startMs = nowMs - windowMs + cfg.timezoneOffsetMinutes * 60000; + const endMs = nowMs + cfg.timezoneOffsetMinutes * 60000; + + let total = 0; + let count = 0; + for (const sample of samples) { + if (sample === null || typeof sample !== 'object') { + throw new RenewalPauseError('INVALID_USAGE', 'sample must be an object'); + } + if (!isNonNegativeFinite(sample.units)) { + throw new RenewalPauseError('INVALID_USAGE', 'sample.units must be a non-negative finite number', { + at: sample.at, + }); + } + const t = parseInstant(sample.at, 'INVALID_DATE'); + if (t < startMs || t > endMs) continue; + total += sample.units; + count += 1; + } + + const average = count === 0 ? 0 : total / count; + return Object.freeze({ + sampleCount: count, + average, + total, + floor: cfg.usageFloor, + belowFloor: count > 0 && average < cfg.usageFloor, + windowStart: new Date(startMs).toISOString(), + windowEnd: new Date(endMs).toISOString(), + }); +} + +// ── Decision ────────────────────────────────────────────────────────────────── + +export interface RenewalPauseDecision { + readonly subscriptionId: string; + readonly action: RenewalPauseAction; + readonly reason: RenewalPauseReason; + readonly observed: number; + readonly floor: number; + readonly pausedUntil: string | null; + readonly evaluatedAt: string; + readonly config: Readonly; +} + +export interface ActivePause { + /** ISO instant the current pause ends. */ + readonly pausedUntil: string; + /** Days the subscription has already been paused consecutively. */ + readonly pausedDays: number; +} + +export interface PauseEvaluationInput { + readonly subscriptionId: string; + readonly samples: readonly UsageSample[]; + readonly activePause?: ActivePause; +} + +export interface PauseEvaluationResult { + readonly decisions: readonly RenewalPauseDecision[]; + readonly rejected: readonly { subscriptionId: string; code: RenewalPauseErrorCode; reason: string }[]; + readonly total: number; + readonly paused: number; +} + +/** Decide a single subscription from its usage signal. Pure and deterministic. */ +export function determineRenewalPause( + signal: UsageSignal, + config: Partial = {}, + activePause?: ActivePause, + now: string | number = Date.now(), +): RenewalPauseDecision { + const cfg = validateRenewalPauseConfig(config); + const nowMs = typeof now === 'number' ? now : parseInstant(now, 'INVALID_DATE'); + if (!Number.isFinite(nowMs)) { + throw new RenewalPauseError('INVALID_DATE', 'now must be a finite value'); + } + const evaluatedAt = new Date(nowMs).toISOString(); + + if (activePause) { + const until = parseInstant(activePause.pausedUntil, 'INVALID_DATE'); + if (!Number.isSafeInteger(activePause.pausedDays) || activePause.pausedDays < 0) { + throw RenewalPauseError.invalidInput('activePause.pausedDays must be a non-negative integer'); + } + if (until > nowMs) { + return Object.freeze({ + subscriptionId: '', + action: 'keep', + reason: 'PAUSE_ACTIVE', + observed: signal.average, + floor: signal.floor, + pausedUntil: new Date(until).toISOString(), + evaluatedAt, + config: cfg, + }); + } + return Object.freeze({ + subscriptionId: '', + action: 'resume', + reason: 'PAUSE_EXPIRED', + observed: signal.average, + floor: signal.floor, + pausedUntil: null, + evaluatedAt, + config: cfg, + }); + } + + if (signal.sampleCount === 0) { + return Object.freeze({ + subscriptionId: '', + action: 'keep', + reason: 'NO_SIGNAL', + observed: 0, + floor: signal.floor, + pausedUntil: null, + evaluatedAt, + config: cfg, + }); + } + if (signal.sampleCount < cfg.minSamples) { + return Object.freeze({ + subscriptionId: '', + action: 'keep', + reason: 'INSUFFICIENT_SAMPLES', + observed: signal.average, + floor: signal.floor, + pausedUntil: null, + evaluatedAt, + config: cfg, + }); + } + if (!signal.belowFloor) { + return Object.freeze({ + subscriptionId: '', + action: 'keep', + reason: 'USAGE_ABOVE_FLOOR', + observed: signal.average, + floor: signal.floor, + pausedUntil: null, + evaluatedAt, + config: cfg, + }); + } + + const effectiveDays = Math.min(cfg.pauseDurationDays, Math.max(1, cfg.maxPauseDays)); + return Object.freeze({ + subscriptionId: '', + action: 'pause', + reason: 'USAGE_BELOW_FLOOR', + observed: signal.average, + floor: signal.floor, + pausedUntil: new Date(nowMs + (effectiveDays + cfg.gracePeriodDays) * 86400000).toISOString(), + evaluatedAt, + config: cfg, + }); +} + +export function shouldPause(decision: RenewalPauseDecision): boolean { + return decision.action === 'pause'; +} + +// ── Service ─────────────────────────────────────────────────────────────────── + +export interface RenewalPauseService { + evaluate(input: PauseEvaluationInput, now?: string | number): RenewalPauseDecision; + plan(inputs: readonly PauseEvaluationInput[], now?: string | number): PauseEvaluationResult; + readonly config: Readonly; +} + +/** + * Create a renewal-pause service. All hooks are optional and default to + * no-ops, so the service is safe to use in unit tests and in the worker. + */ +export function createRenewalPauseService( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {}, +): RenewalPauseService { + const cfg = validateRenewalPauseConfig(config); + const m: RenewalPauseMetrics = { ...noopRenewalPauseMetrics, ...metrics }; + const log: RenewalPauseLogger = { ...noopRenewalPauseLogger, ...logger }; + + function reject(code: RenewalPauseErrorCode): never { + m.recordRejected(code); + throw new RenewalPauseError(code, `request rejected: ${code}`); + } + + function evaluateOne(input: PauseEvaluationInput, now?: string | number): RenewalPauseDecision { + if (input === null || typeof input !== 'object') reject('INVALID_INPUT'); + if (typeof input.subscriptionId !== 'string' || input.subscriptionId.trim() === '') { + reject('INVALID_INPUT'); + } + let signal: UsageSignal; + try { + signal = summarizeUsage(input.samples, cfg, now as string | number); + } catch (error) { + if (error instanceof RenewalPauseError) { + m.recordRejected(error.code); + throw error; + } + reject('INVALID_USAGE'); + } + + let base: RenewalPauseDecision; + try { + base = determineRenewalPause(signal, cfg, input.activePause, now as string | number); + } catch (error) { + if (error instanceof RenewalPauseError) { + m.recordRejected(error.code); + throw error; + } + reject('INVALID_INPUT'); + } + + const decision: RenewalPauseDecision = Object.freeze({ + ...base, + subscriptionId: input.subscriptionId, + }); + if (decision.action === 'pause') { + m.recordPaused(decision.subscriptionId, decision.observed, decision.floor); + log.warn('renewal paused: usage below floor', { + subscriptionId: decision.subscriptionId, + observed: decision.observed, + floor: decision.floor, + pausedUntil: decision.pausedUntil, + }); + } else if (decision.action === 'resume') { + m.recordResumed(decision.subscriptionId, decision.reason); + log.info('renewal resumed: pause expired', { subscriptionId: decision.subscriptionId }); + } else { + m.recordKept(decision.subscriptionId, decision.observed); + } + return decision; + } + + function plan(inputs: readonly PauseEvaluationInput[], now?: string | number): PauseEvaluationResult { + if (!Array.isArray(inputs)) reject('INVALID_INPUT'); + const decisions: RenewalPauseDecision[] = []; + const rejected: PauseEvaluationResult['rejected'] = []; + for (const input of inputs) { + try { + decisions.push(evaluateOne(input, now)); + } catch (error) { + if (!(error instanceof RenewalPauseError)) throw error; + rejected.push( + Object.freeze({ + subscriptionId: input && typeof input.subscriptionId === 'string' ? input.subscriptionId : '', + code: error.code, + reason: error.message, + }), + ); + } + } + const result: PauseEvaluationResult = Object.freeze({ + decisions: Object.freeze(decisions), + rejected: Object.freeze(rejected), + total: inputs.length, + paused: decisions.filter(shouldPause).length, + }); + m.recordEvaluated(result.total, result.paused); + log.info('renewal pause plan completed', { total: result.total, paused: result.paused }); + return result; + } + + return Object.freeze({ evaluate: evaluateOne, plan, config: cfg }); +} diff --git a/ml-service/app/usage/__init__.py b/ml-service/app/usage/__init__.py new file mode 100644 index 00000000..1cd44bad --- /dev/null +++ b/ml-service/app/usage/__init__.py @@ -0,0 +1,21 @@ +"""Usage-signal primitives for smart renewal pause (issue #2251).""" + +from .floor import ( + DEFAULT_USAGE_FLOOR_CONFIG, + UsageFloorConfig, + UsageFloorError, + UsageSignal, + build_usage_signal, + below_floor, + validate_usage_floor_config, +) + +__all__ = [ + "DEFAULT_USAGE_FLOOR_CONFIG", + "UsageFloorConfig", + "UsageFloorError", + "UsageSignal", + "build_usage_signal", + "below_floor", + "validate_usage_floor_config", +] diff --git a/ml-service/app/usage/floor.py b/ml-service/app/usage/floor.py new file mode 100644 index 00000000..9ce47bd1 --- /dev/null +++ b/ml-service/app/usage/floor.py @@ -0,0 +1,170 @@ +"""Usage floor signal used by the smart renewal pause (issue #2251). + +The ML service owns the statistical summary; the backend renewal worker owns +the decision to actually pause a charge. This module is deliberately pure and +standard-library-only: it consumes a list of usage observations and returns an +immutable signal. No I/O, no network, no global state. + +Failure modes use :class:`UsageFloorError` with a stable ``code`` so callers can +distinguish bad configuration from bad samples without parsing messages. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Iterable, Mapping, Optional + + +class UsageFloorError(ValueError): + """Validation error with a stable machine-readable code.""" + + def __init__(self, code: str, message: str, details: Optional[Mapping[str, object]] = None): + super().__init__(message) + self.code = code + self.details = dict(details) if details else {} + + @classmethod + def invalid_config(cls, message: str, **details: object) -> "UsageFloorError": + return cls("INVALID_CONFIG", message, details) + + @classmethod + def invalid_sample(cls, message: str, **details: object) -> "UsageFloorError": + return cls("INVALID_SAMPLE", message, details) + + +@dataclass(frozen=True) +class UsageFloorConfig: + """Configuration for the trailing usage window.""" + + usage_floor: float = 1.0 + window_days: int = 30 + min_samples: int = 7 + timezone_offset_minutes: int = 0 + + +DEFAULT_USAGE_FLOOR_CONFIG: UsageFloorConfig = UsageFloorConfig() + + +def validate_usage_floor_config(config: Optional[Mapping[str, object]] = None) -> UsageFloorConfig: + """Merge ``config`` over defaults and validate every field.""" + if config is None: + config = {} + if not isinstance(config, Mapping): + raise UsageFloorError.invalid_config("config must be a mapping") + + values = { + field: config.get(field, getattr(DEFAULT_USAGE_FLOOR_CONFIG, field)) + for field in ( + "usage_floor", + "window_days", + "min_samples", + "timezone_offset_minutes", + ) + } + + floor = values["usage_floor"] + if isinstance(floor, bool) or not isinstance(floor, (int, float)) or floor < 0: + raise UsageFloorError.invalid_config("usage_floor must be a non-negative number", usage_floor=floor) + + window = values["window_days"] + if isinstance(window, bool) or not isinstance(window, int) or not 1 <= window <= 365: + raise UsageFloorError.invalid_config("window_days must be an integer 1-365", window_days=window) + + minimum = values["min_samples"] + if isinstance(minimum, bool) or not isinstance(minimum, int) or not 1 <= minimum <= window: + raise UsageFloorError.invalid_config( + "min_samples must be an integer between 1 and window_days", min_samples=minimum + ) + + offset = values["timezone_offset_minutes"] + if isinstance(offset, bool) or not isinstance(offset, int) or abs(offset) > 1440: + raise UsageFloorError.invalid_config( + "timezone_offset_minutes must be within +/-1440", timezone_offset_minutes=offset + ) + + return UsageFloorConfig( + usage_floor=float(floor), + window_days=window, + min_samples=minimum, + timezone_offset_minutes=offset, + ) + + +@dataclass(frozen=True) +class UsageSignal: + """Immutable summary of usage in the trailing window.""" + + sample_count: int + average: float + total: float + floor: float + below_floor: bool + window_start: str + window_end: str + + +def _parse_instant(value: object) -> datetime: + if not isinstance(value, str) or not value.strip(): + raise UsageFloorError.invalid_sample("timestamp must be a non-empty string") + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError as exc: + raise UsageFloorError("INVALID_DATE", "timestamp is not a valid ISO-8601 instant", {"value": value}) from exc + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed.astimezone(timezone.utc) + + +def build_usage_signal( + samples: Iterable[Mapping[str, object]], + config: Optional[Mapping[str, object]] = None, + now: Optional[datetime] = None, +) -> UsageSignal: + """Summarise samples in the trailing window. + + Samples outside the window are ignored; malformed samples raise + :class:`UsageFloorError`. An empty window yields ``average = 0`` and + ``below_floor = False`` (fail-open: never pause without evidence). + """ + cfg = validate_usage_floor_config(config) + if isinstance(samples, (str, bytes)) or not isinstance(samples, Iterable): + raise UsageFloorError.invalid_sample("samples must be an iterable of mappings") + + reference = now or datetime.now(timezone.utc) + if reference.tzinfo is None: + reference = reference.replace(tzinfo=timezone.utc) + shift = timedelta(minutes=cfg.timezone_offset_minutes) + end = reference + shift + start = end - timedelta(days=cfg.window_days) + + total = 0.0 + count = 0 + for sample in samples: + if not isinstance(sample, Mapping): + raise UsageFloorError.invalid_sample("sample must be a mapping") + units = sample.get("units") + if isinstance(units, bool) or not isinstance(units, (int, float)) or units < 0: + raise UsageFloorError.invalid_sample("units must be a non-negative number", units=units) + observed_at = _parse_instant(sample.get("at")) + if observed_at < start or observed_at > end: + continue + total += float(units) + count += 1 + + average = total / count if count else 0.0 + return UsageSignal( + sample_count=count, + average=average, + total=total, + floor=cfg.usage_floor, + below_floor=count > 0 and average < cfg.usage_floor, + window_start=start.isoformat().replace("+00:00", "Z"), + window_end=end.isoformat().replace("+00:00", "Z"), + ) + + +def below_floor(signal: UsageSignal, config: Optional[Mapping[str, object]] = None) -> bool: + """Return True only with enough evidence to justify a renewal pause.""" + cfg = validate_usage_floor_config(config) + return signal.sample_count >= cfg.min_samples and signal.below_floor diff --git a/ml-service/app/usage/tests/__init__.py b/ml-service/app/usage/tests/__init__.py new file mode 100644 index 00000000..79c3db3e --- /dev/null +++ b/ml-service/app/usage/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the usage-floor signal (issue #2251).""" diff --git a/ml-service/app/usage/tests/test_floor.py b/ml-service/app/usage/tests/test_floor.py new file mode 100644 index 00000000..31e77af9 --- /dev/null +++ b/ml-service/app/usage/tests/test_floor.py @@ -0,0 +1,85 @@ +"""Unit tests for ml-service/app/usage/floor.py (issue #2251).""" + +from __future__ import annotations + +import sys +import unittest +from datetime import datetime, timezone +from pathlib import Path + +# Allow running this file directly from any working directory. +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from app.usage.floor import ( # noqa: E402 + DEFAULT_USAGE_FLOOR_CONFIG, + UsageFloorError, + UsageSignal, + below_floor, + build_usage_signal, + validate_usage_floor_config, +) + +NOW = datetime(2026, 11, 24, 12, 0, tzinfo=timezone.utc) + + +def samples(units: list[float]) -> list[dict[str, object]]: + base = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc) + return [ + {"at": (base.replace(tzinfo=timezone.utc) + __import__("datetime").timedelta(days=i)).isoformat().replace("+00:00", "Z"), "units": u} + for i, u in enumerate(units) + ] + + +class ConfigTests(unittest.TestCase): + def test_defaults_and_frozen(self) -> None: + cfg = validate_usage_floor_config() + self.assertEqual(cfg.usage_floor, DEFAULT_USAGE_FLOOR_CONFIG.usage_floor) + with self.assertRaises(Exception): + cfg.window_days = 1 # type: ignore[misc] + + def test_rejects_invalid_config(self) -> None: + for bad in ({"usage_floor": -1}, {"window_days": 0}, {"window_days": 500}, {"min_samples": 40}): + with self.subTest(bad=bad), self.assertRaises(UsageFloorError) as ctx: + validate_usage_floor_config(bad) + self.assertEqual(ctx.exception.code, "INVALID_CONFIG") + + +class SignalTests(unittest.TestCase): + def test_summary_happy_path(self) -> None: + signal = build_usage_signal(samples([2, 2, 2, 2]), {"usage_floor": 1}, NOW) + self.assertIsInstance(signal, UsageSignal) + self.assertEqual(signal.sample_count, 4) + self.assertEqual(signal.total, 8.0) + self.assertEqual(signal.average, 2.0) + self.assertFalse(signal.below_floor) + + def test_below_floor_and_insufficient_samples(self) -> None: + low = build_usage_signal(samples([0] * 7), {"usage_floor": 1}, NOW) + self.assertTrue(low.below_floor) + self.assertTrue(below_floor(low)) + thin = build_usage_signal(samples([0, 0]), {"usage_floor": 1}, NOW) + self.assertTrue(thin.below_floor) + self.assertFalse(below_floor(thin)) + + def test_out_of_window_samples_ignored(self) -> None: + old = [{"at": "2020-01-01T00:00:00Z", "units": 100}] + signal = build_usage_signal(old, {}, NOW) + self.assertEqual(signal.sample_count, 0) + self.assertFalse(signal.below_floor) + + def test_malformed_samples_rejected(self) -> None: + with self.assertRaises(UsageFloorError) as ctx: + build_usage_signal([{"at": "2026-11-20T00:00:00Z", "units": -1}], {}, NOW) + self.assertEqual(ctx.exception.code, "INVALID_SAMPLE") + with self.assertRaises(UsageFloorError) as ctx: + build_usage_signal([{"at": "not-a-date", "units": 1}], {}, NOW) + self.assertEqual(ctx.exception.code, "INVALID_DATE") + + def test_non_iterable_rejected(self) -> None: + with self.assertRaises(UsageFloorError) as ctx: + build_usage_signal("nope", {}, NOW) # type: ignore[arg-type] + self.assertEqual(ctx.exception.code, "INVALID_SAMPLE") + + +if __name__ == "__main__": + unittest.main()