-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAdaptiveSamplingController.ts
More file actions
293 lines (254 loc) · 9.36 KB
/
Copy pathAdaptiveSamplingController.ts
File metadata and controls
293 lines (254 loc) · 9.36 KB
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
import { logger } from "../utils/logger";
export type SamplingMode = "fixed" | "adaptive";
export type AdaptiveSamplingState = "fixed" | "healthy" | "warm" | "hot" | "critical_pause";
export type RootSamplingDecisionReason =
| "pre_app_start"
| "sampled"
| "not_sampled"
| "load_shed"
| "critical_pause";
export interface ResolvedSamplingConfig {
mode: SamplingMode;
baseRate: number;
minRate: number;
}
export interface AdaptiveSamplingHealthSnapshot {
queueFillRatio?: number | null;
droppedSpanCount?: number;
exportFailureCount?: number;
exportTimeoutCount?: number;
exportCircuitOpen?: boolean;
eventLoopLagP95Ms?: number | null;
memoryPressureRatio?: number | null;
}
export interface RootSamplingDecision {
shouldRecord: boolean;
reason: RootSamplingDecisionReason;
mode: SamplingMode;
state: AdaptiveSamplingState;
baseRate: number;
minRate: number;
effectiveRate: number;
admissionMultiplier: number;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
function clamp01(value: number): number {
return clamp(value, 0, 1);
}
function normalizeBetween(value: number | null | undefined, zeroPoint: number, onePoint: number): number {
if (value === null || value === undefined || Number.isNaN(value)) {
return 0;
}
if (onePoint <= zeroPoint) {
return 0;
}
return clamp01((value - zeroPoint) / (onePoint - zeroPoint));
}
export class AdaptiveSamplingController {
private readonly config: ResolvedSamplingConfig;
private readonly randomFn: () => number;
private readonly nowFn: () => number;
private readonly logTransitions: boolean;
private admissionMultiplier = 1;
private state: AdaptiveSamplingState;
private pausedUntilMs = 0;
private lastUpdatedAtMs = 0;
private lastDecreaseAtMs = 0;
private prevDroppedSpanCount = 0;
private prevExportFailureCount = 0;
private prevExportTimeoutCount = 0;
private queueFillEwma: number | null = null;
private recentDropSignal = 0;
private recentFailureSignal = 0;
private recentTimeoutSignal = 0;
constructor(
config: ResolvedSamplingConfig,
{
logTransitions = true,
randomFn = Math.random,
nowFn = Date.now,
}: {
logTransitions?: boolean;
randomFn?: () => number;
nowFn?: () => number;
} = {},
) {
this.config = config;
this.logTransitions = logTransitions;
this.randomFn = randomFn;
this.nowFn = nowFn;
this.state = config.mode === "fixed" ? "fixed" : "healthy";
}
update(snapshot: AdaptiveSamplingHealthSnapshot): void {
if (this.config.mode !== "adaptive") {
this.state = "fixed";
this.admissionMultiplier = 1;
return;
}
const now = this.nowFn();
const elapsedMs = this.lastUpdatedAtMs === 0 ? 2000 : Math.max(1, now - this.lastUpdatedAtMs);
this.lastUpdatedAtMs = now;
const decay = Math.exp(-elapsedMs / 30000);
this.recentDropSignal *= decay;
this.recentFailureSignal *= decay;
this.recentTimeoutSignal *= decay;
const droppedSpanCount = Math.max(0, snapshot.droppedSpanCount ?? 0);
const exportFailureCount = Math.max(0, snapshot.exportFailureCount ?? 0);
const exportTimeoutCount = Math.max(0, snapshot.exportTimeoutCount ?? 0);
const droppedDelta = Math.max(0, droppedSpanCount - this.prevDroppedSpanCount);
const exportFailureDelta = Math.max(0, exportFailureCount - this.prevExportFailureCount);
const exportTimeoutDelta = Math.max(0, exportTimeoutCount - this.prevExportTimeoutCount);
this.prevDroppedSpanCount = droppedSpanCount;
this.prevExportFailureCount = exportFailureCount;
this.prevExportTimeoutCount = exportTimeoutCount;
this.recentDropSignal += droppedDelta;
this.recentFailureSignal += exportFailureDelta;
this.recentTimeoutSignal += exportTimeoutDelta;
const queueFillRatio =
snapshot.queueFillRatio === null || snapshot.queueFillRatio === undefined
? null
: clamp01(snapshot.queueFillRatio);
if (queueFillRatio !== null) {
this.queueFillEwma = this.queueFillEwma === null ? queueFillRatio : 0.25 * queueFillRatio + 0.75 * this.queueFillEwma;
}
const queuePressure = normalizeBetween(this.queueFillEwma, 0.2, 0.85);
const eventLoopPressure = normalizeBetween(snapshot.eventLoopLagP95Ms ?? null, 20, 150);
const memoryPressure = normalizeBetween(snapshot.memoryPressureRatio ?? null, 0.8, 0.92);
const exportFailurePressure = clamp01(this.recentFailureSignal / 5);
const pressure = Math.max(queuePressure, eventLoopPressure, memoryPressure, exportFailurePressure);
const hardBrake =
droppedDelta > 0 ||
exportTimeoutDelta > 0 ||
Boolean(snapshot.exportCircuitOpen) ||
(snapshot.eventLoopLagP95Ms ?? 0) >= 150 ||
(snapshot.memoryPressureRatio ?? 0) >= 0.92;
const previousState = this.state;
const previousMultiplier = this.admissionMultiplier;
if (hardBrake) {
this.pausedUntilMs = now + 15000;
this.admissionMultiplier = 0;
this.state = "critical_pause";
this.lastDecreaseAtMs = now;
this.logTransition(previousState, previousMultiplier, pressure, snapshot);
return;
}
if (now < this.pausedUntilMs) {
this.state = "critical_pause";
this.logTransition(previousState, previousMultiplier, pressure, snapshot);
return;
}
const minMultiplier = this.getMinMultiplier();
if (pressure >= 0.7) {
this.admissionMultiplier = Math.max(minMultiplier, this.admissionMultiplier * 0.4);
this.state = "hot";
this.lastDecreaseAtMs = now;
} else if (pressure >= 0.45) {
this.admissionMultiplier = Math.max(minMultiplier, this.admissionMultiplier * 0.7);
this.state = "warm";
this.lastDecreaseAtMs = now;
} else {
if (pressure <= 0.2 && now - this.lastDecreaseAtMs >= 10000) {
this.admissionMultiplier = Math.min(1, this.admissionMultiplier + 0.05);
}
this.state = "healthy";
}
this.logTransition(previousState, previousMultiplier, pressure, snapshot);
}
getDecision({ isPreAppStart }: { isPreAppStart: boolean }): RootSamplingDecision {
if (isPreAppStart) {
return {
shouldRecord: true,
reason: "pre_app_start",
mode: this.config.mode,
state: this.state,
baseRate: this.config.baseRate,
minRate: this.config.minRate,
effectiveRate: 1,
admissionMultiplier: 1,
};
}
const effectiveRate =
this.config.mode === "adaptive" ? this.getEffectiveSamplingRate() : clamp01(this.config.baseRate);
const loadShed =
this.config.mode === "adaptive" && effectiveRate < this.config.baseRate;
if (effectiveRate <= 0) {
return {
shouldRecord: false,
reason: this.state === "critical_pause" ? "critical_pause" : loadShed ? "load_shed" : "not_sampled",
mode: this.config.mode,
state: this.state,
baseRate: this.config.baseRate,
minRate: this.config.minRate,
effectiveRate,
admissionMultiplier: this.admissionMultiplier,
};
}
const shouldRecord = this.randomFn() < effectiveRate;
return {
shouldRecord,
reason: shouldRecord
? "sampled"
: loadShed
? "load_shed"
: "not_sampled",
mode: this.config.mode,
state: this.state,
baseRate: this.config.baseRate,
minRate: this.config.minRate,
effectiveRate,
admissionMultiplier: this.config.mode === "adaptive" ? this.admissionMultiplier : 1,
};
}
getEffectiveSamplingRate(): number {
if (this.config.mode !== "adaptive") {
return clamp01(this.config.baseRate);
}
if (this.nowFn() < this.pausedUntilMs || this.state === "critical_pause") {
return 0;
}
const effectiveRate = this.config.baseRate * this.admissionMultiplier;
return clamp(
effectiveRate,
Math.min(this.config.baseRate, this.config.minRate),
this.config.baseRate,
);
}
getSnapshot(): Omit<RootSamplingDecision, "shouldRecord" | "reason"> {
return {
mode: this.config.mode,
state: this.state,
baseRate: this.config.baseRate,
minRate: this.config.minRate,
effectiveRate:
this.config.mode === "adaptive" ? this.getEffectiveSamplingRate() : clamp01(this.config.baseRate),
admissionMultiplier: this.config.mode === "adaptive" ? this.admissionMultiplier : 1,
};
}
private getMinMultiplier(): number {
if (this.config.baseRate <= 0 || this.config.minRate <= 0) {
return 0;
}
return clamp01(this.config.minRate / this.config.baseRate);
}
private logTransition(
previousState: AdaptiveSamplingState,
previousMultiplier: number,
pressure: number,
snapshot: AdaptiveSamplingHealthSnapshot,
): void {
if (!this.logTransitions) {
return;
}
if (
previousState === this.state &&
Math.abs(previousMultiplier - this.admissionMultiplier) < 0.05
) {
return;
}
logger.info(
`Adaptive sampling updated (state=${this.state}, multiplier=${this.admissionMultiplier.toFixed(2)}, effectiveRate=${this.getEffectiveSamplingRate().toFixed(4)}, pressure=${pressure.toFixed(2)}, queueFill=${this.queueFillEwma?.toFixed(2) ?? "n/a"}, eventLoopLagP95Ms=${snapshot.eventLoopLagP95Ms ?? "n/a"}, memoryPressureRatio=${snapshot.memoryPressureRatio ?? "n/a"}, exportCircuitOpen=${snapshot.exportCircuitOpen ? "true" : "false"}).`,
);
}
}