@x-otto/residency 0.0.0-stage → 0.3.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-revision.json +4 -0
- package/dist/host-BodXpY7B.d.ts +603 -0
- package/dist/host.d.ts +2 -0
- package/dist/host.js +3 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/src-v8Ohv9dn.js +1953 -0
- package/package.json +27 -4
- package/README.md +0 -3
|
@@ -0,0 +1,1953 @@
|
|
|
1
|
+
import { DEFAULT_SHRINK_POLICY, PROCESS_TREE_BUDGET_DEFAULT, PROCESS_TREE_BUDGET_SETTING_ENV, SLOTS, SURFACE_KEEP_BYTES_DEFAULT, SURFACE_KEEP_BYTES_SETTING_ENV, SURFACE_KEEP_LAST_DEFAULT, SURFACE_KEEP_LAST_SETTING_ENV, TIMINGS, createSessionResidencyPorts, decideShrink, effectiveMinGrowth, isSessionResidencyManager } from "@x-otto/kernel";
|
|
2
|
+
import { totalmem } from "node:os";
|
|
3
|
+
import { getHeapStatistics } from "node:v8";
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { defineComponent } from "@x-otto/universal";
|
|
6
|
+
import { performance } from "node:perf_hooks";
|
|
7
|
+
|
|
8
|
+
//#region src/joint-calculator.ts
|
|
9
|
+
const LEVEL_DIVISOR = {
|
|
10
|
+
healthy: 1,
|
|
11
|
+
warning: 2,
|
|
12
|
+
critical: 4
|
|
13
|
+
};
|
|
14
|
+
function divisorFor(level) {
|
|
15
|
+
return LEVEL_DIVISOR[level];
|
|
16
|
+
}
|
|
17
|
+
function gradeByPct(usedPct, warnThresholdPct, hardThresholdPct) {
|
|
18
|
+
if (!Number.isFinite(usedPct)) return "healthy";
|
|
19
|
+
if (usedPct >= hardThresholdPct) return "critical";
|
|
20
|
+
if (usedPct >= warnThresholdPct) return "warning";
|
|
21
|
+
return "healthy";
|
|
22
|
+
}
|
|
23
|
+
function pctOf(usedBytes, budgetBytes) {
|
|
24
|
+
if (!Number.isFinite(usedBytes) || !Number.isFinite(budgetBytes) || budgetBytes <= 0) return NaN;
|
|
25
|
+
return usedBytes / budgetBytes * 100;
|
|
26
|
+
}
|
|
27
|
+
function unavailableDomain(domain) {
|
|
28
|
+
return {
|
|
29
|
+
domain,
|
|
30
|
+
level: "healthy",
|
|
31
|
+
usedPct: NaN,
|
|
32
|
+
sampling: "unavailable"
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function okDomain(domain, usedPct, warnThresholdPct, hardThresholdPct) {
|
|
36
|
+
if (!Number.isFinite(usedPct)) return unavailableDomain(domain);
|
|
37
|
+
return {
|
|
38
|
+
domain,
|
|
39
|
+
level: gradeByPct(usedPct, warnThresholdPct, hardThresholdPct),
|
|
40
|
+
usedPct,
|
|
41
|
+
sampling: "ok",
|
|
42
|
+
warnPct: warnThresholdPct,
|
|
43
|
+
hardPct: hardThresholdPct
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function heapDomainLevel(sample, warnThresholdPct, hardThresholdPct) {
|
|
47
|
+
return okDomain("heap", pctOf(sample.heapUsedBytes, sample.heapLimitBytes), warnThresholdPct, hardThresholdPct);
|
|
48
|
+
}
|
|
49
|
+
function systemDomainLevel(sample, warnThresholdPct, hardThresholdPct) {
|
|
50
|
+
const totalBytes = sample.systemTotalBytes;
|
|
51
|
+
if (totalBytes === void 0) return unavailableDomain("system");
|
|
52
|
+
return okDomain("system", pctOf(sample.rssBytes, totalBytes), warnThresholdPct, hardThresholdPct);
|
|
53
|
+
}
|
|
54
|
+
function tokenDomainLevel(sample, warnThresholdPct, hardThresholdPct) {
|
|
55
|
+
if (sample === void 0) return unavailableDomain("tokens");
|
|
56
|
+
return okDomain("tokens", pctOf(sample.totalTokens, sample.contextWindow), warnThresholdPct, hardThresholdPct);
|
|
57
|
+
}
|
|
58
|
+
function processTreeDomainLevel(sample, budgetBytes, weight, warnThresholdPct, hardThresholdPct) {
|
|
59
|
+
if (sample === void 0) return unavailableDomain("processTree");
|
|
60
|
+
return okDomain("processTree", pctOf(sample.totalRssBytes * weight, budgetBytes), warnThresholdPct, hardThresholdPct);
|
|
61
|
+
}
|
|
62
|
+
function aggregateLevel(domains) {
|
|
63
|
+
let level = "healthy";
|
|
64
|
+
for (const domain of domains) {
|
|
65
|
+
if (domain.sampling !== "ok") continue;
|
|
66
|
+
if (domain.level === "critical") return "critical";
|
|
67
|
+
if (domain.level === "warning") level = "warning";
|
|
68
|
+
}
|
|
69
|
+
return level;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/env-readers.ts
|
|
74
|
+
function resolvePositiveEnv(env, envVar, fallback) {
|
|
75
|
+
const raw = env?.get(envVar);
|
|
76
|
+
if (!raw) return fallback;
|
|
77
|
+
const parsed = Number(raw);
|
|
78
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
79
|
+
}
|
|
80
|
+
function resolvePositiveIntEnv(env, envVar, fallback) {
|
|
81
|
+
const raw = env?.get(envVar);
|
|
82
|
+
if (!raw) return fallback;
|
|
83
|
+
const parsed = Number(raw);
|
|
84
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
|
|
85
|
+
}
|
|
86
|
+
function resolvePctEnv(env, envVar, fallback) {
|
|
87
|
+
const raw = env?.get(envVar);
|
|
88
|
+
if (!raw) return fallback;
|
|
89
|
+
const parsed = Number(raw);
|
|
90
|
+
return Number.isFinite(parsed) && parsed > 0 && parsed <= 100 ? parsed : fallback;
|
|
91
|
+
}
|
|
92
|
+
const resolveMsEnv = resolvePositiveEnv;
|
|
93
|
+
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/types.ts
|
|
96
|
+
const OBSERVATION_ONLY_DOMAINS = ["tokens", "processTree"];
|
|
97
|
+
function isObservationOnlyDomain(domain) {
|
|
98
|
+
return OBSERVATION_ONLY_DOMAINS.includes(domain);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/action-policy.ts
|
|
103
|
+
const DEFAULT_BASE_IDLE_EVICT_MS = 30 * 6e4;
|
|
104
|
+
const DEFAULT_BASE_SURFACE_KEEP_LAST = SURFACE_KEEP_LAST_DEFAULT;
|
|
105
|
+
const DEFAULT_BASE_SURFACE_KEEP_BYTES = SURFACE_KEEP_BYTES_DEFAULT;
|
|
106
|
+
const DEFAULT_ACTION_MIN_LEVEL = "warning";
|
|
107
|
+
const DEFAULT_ACTION_DOMAINS = ["heap", "system"];
|
|
108
|
+
const LEVEL_RANK = {
|
|
109
|
+
healthy: 0,
|
|
110
|
+
warning: 1,
|
|
111
|
+
critical: 2
|
|
112
|
+
};
|
|
113
|
+
function atLeastLevel(level, minLevel) {
|
|
114
|
+
return LEVEL_RANK[level] >= LEVEL_RANK[minLevel];
|
|
115
|
+
}
|
|
116
|
+
function tightenThreshold(base, divisor) {
|
|
117
|
+
return Math.max(1, Math.floor(base / (Number.isFinite(divisor) && divisor > 0 ? Math.trunc(divisor) : 1)));
|
|
118
|
+
}
|
|
119
|
+
function triggeredDomainsOf(pressure, actionDomains, minLevel) {
|
|
120
|
+
const triggered = [];
|
|
121
|
+
for (const entry of pressure.domains) {
|
|
122
|
+
if (entry.sampling !== "ok") continue;
|
|
123
|
+
if (!actionDomains.includes(entry.domain)) continue;
|
|
124
|
+
if (!atLeastLevel(entry.level, minLevel)) continue;
|
|
125
|
+
triggered.push(entry.domain);
|
|
126
|
+
}
|
|
127
|
+
return triggered;
|
|
128
|
+
}
|
|
129
|
+
function resolveActionThresholds(pressure, options = {}) {
|
|
130
|
+
const baseIdleEvictMs = options.baseIdleEvictMs ?? resolvePositiveEnv(options.env, "OTTO_RESIDENCY_IDLE_EVICT_MS", 18e5);
|
|
131
|
+
const baseSurfaceKeepLast = resolveTunableNumber(options.baseSurfaceKeepLast) ?? resolvePositiveIntEnv(options.env, SURFACE_KEEP_LAST_SETTING_ENV, DEFAULT_BASE_SURFACE_KEEP_LAST);
|
|
132
|
+
const baseSurfaceKeepBytes = resolveTunableNumber(options.baseSurfaceKeepBytes) ?? resolvePositiveIntEnv(options.env, SURFACE_KEEP_BYTES_SETTING_ENV, DEFAULT_BASE_SURFACE_KEEP_BYTES);
|
|
133
|
+
const divisor = pressure.budgetDivisor;
|
|
134
|
+
return {
|
|
135
|
+
level: pressure.level,
|
|
136
|
+
divisor,
|
|
137
|
+
idleEvictMs: tightenThreshold(baseIdleEvictMs, divisor),
|
|
138
|
+
surfaceKeepLast: baseSurfaceKeepLast,
|
|
139
|
+
surfaceKeepBytes: tightenThreshold(baseSurfaceKeepBytes, divisor)
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function resolveTunableNumber(value) {
|
|
143
|
+
if (typeof value !== "function") return value;
|
|
144
|
+
try {
|
|
145
|
+
const next = value();
|
|
146
|
+
return typeof next === "number" && Number.isFinite(next) && next > 0 ? next : void 0;
|
|
147
|
+
} catch {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function selectResidencyActions(pressure, options = {}) {
|
|
152
|
+
const actionDomains = (options.actionDomains ?? DEFAULT_ACTION_DOMAINS).filter((domain) => !isObservationOnlyDomain(domain));
|
|
153
|
+
const minLevel = options.minLevel ?? "warning";
|
|
154
|
+
const triggeredDomains = triggeredDomainsOf(pressure, actionDomains, minLevel);
|
|
155
|
+
const thresholds = resolveActionThresholds(pressure, options);
|
|
156
|
+
if (triggeredDomains.length === 0) return {
|
|
157
|
+
reason: "no-targeted-domain",
|
|
158
|
+
triggeredDomains,
|
|
159
|
+
thresholds
|
|
160
|
+
};
|
|
161
|
+
if (!atLeastLevel(pressure.level, minLevel)) return {
|
|
162
|
+
reason: "below-threshold",
|
|
163
|
+
triggeredDomains,
|
|
164
|
+
thresholds
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
reason: "ok",
|
|
168
|
+
triggeredDomains,
|
|
169
|
+
thresholds
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/residency-action-coordinator.ts
|
|
175
|
+
const DEFAULT_MAX_EVICTIONS_PER_PASS = 1;
|
|
176
|
+
const DEFAULT_MAX_BOUND_SURFACES_PER_PASS = 4;
|
|
177
|
+
const DEFAULT_MAX_RELEASES_PER_PASS = 1;
|
|
178
|
+
const DEFAULT_FUTILE_TRIM_COOLDOWN_MS = 5 * 6e4;
|
|
179
|
+
const DEFAULT_RELEASE_DOMAINS = ["processTree"];
|
|
180
|
+
const RELEASE_RESOURCE_REASON = "process-tree-pressure";
|
|
181
|
+
function messageOf$2(error) {
|
|
182
|
+
return error instanceof Error ? error.message : String(error);
|
|
183
|
+
}
|
|
184
|
+
function selectCandidates(candidates, keep, compare, limit) {
|
|
185
|
+
return candidates.filter(keep).sort(compare).slice(0, Math.max(0, limit));
|
|
186
|
+
}
|
|
187
|
+
function selectOwners(owners, limit) {
|
|
188
|
+
return owners.map((owner) => {
|
|
189
|
+
let pressure;
|
|
190
|
+
try {
|
|
191
|
+
pressure = owner.pressure();
|
|
192
|
+
} catch {
|
|
193
|
+
pressure = void 0;
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
owner,
|
|
197
|
+
pressure
|
|
198
|
+
};
|
|
199
|
+
}).map((entry) => {
|
|
200
|
+
let busy;
|
|
201
|
+
try {
|
|
202
|
+
busy = entry.owner.busy?.();
|
|
203
|
+
} catch {
|
|
204
|
+
busy = void 0;
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
...entry,
|
|
208
|
+
busy
|
|
209
|
+
};
|
|
210
|
+
}).sort((a, b) => {
|
|
211
|
+
const idleFirst = Number(a.busy === true) - Number(b.busy === true);
|
|
212
|
+
if (idleFirst !== 0) return idleFirst;
|
|
213
|
+
const left = a.pressure !== void 0 && Number.isFinite(a.pressure) ? a.pressure : void 0;
|
|
214
|
+
const right = b.pressure !== void 0 && Number.isFinite(b.pressure) ? b.pressure : void 0;
|
|
215
|
+
if (left === void 0 && right === void 0) return 0;
|
|
216
|
+
if (left === void 0) return 1;
|
|
217
|
+
if (right === void 0) return -1;
|
|
218
|
+
return right - left;
|
|
219
|
+
}).slice(0, Math.max(0, limit)).map((entry) => entry.owner);
|
|
220
|
+
}
|
|
221
|
+
var ResidencyActionCoordinator = class {
|
|
222
|
+
options;
|
|
223
|
+
now;
|
|
224
|
+
maxEvictionsPerPass;
|
|
225
|
+
maxBoundSurfacesPerPass;
|
|
226
|
+
maxReleasesPerPass;
|
|
227
|
+
futileTrimCooldownMs;
|
|
228
|
+
futileByteTrims = /* @__PURE__ */ new Map();
|
|
229
|
+
enabled;
|
|
230
|
+
onReport;
|
|
231
|
+
last;
|
|
232
|
+
inflight;
|
|
233
|
+
accepting = true;
|
|
234
|
+
stopped = false;
|
|
235
|
+
constructor(options) {
|
|
236
|
+
this.options = options;
|
|
237
|
+
this.now = options.now ?? (() => Date.now());
|
|
238
|
+
this.maxEvictionsPerPass = options.maxEvictionsPerPass ?? 1;
|
|
239
|
+
this.maxBoundSurfacesPerPass = options.maxBoundSurfacesPerPass ?? 4;
|
|
240
|
+
this.maxReleasesPerPass = options.maxReleasesPerPass ?? 1;
|
|
241
|
+
this.futileTrimCooldownMs = options.futileTrimCooldownMs ?? 3e5;
|
|
242
|
+
this.enabled = options.enabled ?? true;
|
|
243
|
+
this.onReport = options.onReport;
|
|
244
|
+
}
|
|
245
|
+
onSample = (pressure, candidates) => {
|
|
246
|
+
this.apply(pressure, candidates).catch(() => void 0);
|
|
247
|
+
};
|
|
248
|
+
lastReport() {
|
|
249
|
+
return this.last;
|
|
250
|
+
}
|
|
251
|
+
async settled() {
|
|
252
|
+
const pending = this.inflight;
|
|
253
|
+
if (pending === void 0) return;
|
|
254
|
+
try {
|
|
255
|
+
await pending;
|
|
256
|
+
} catch {
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async stop() {
|
|
261
|
+
this.accepting = false;
|
|
262
|
+
const pending = this.inflight;
|
|
263
|
+
if (pending !== void 0) try {
|
|
264
|
+
await pending;
|
|
265
|
+
} catch {}
|
|
266
|
+
}
|
|
267
|
+
start() {
|
|
268
|
+
if (this.stopped) return;
|
|
269
|
+
this.accepting = true;
|
|
270
|
+
}
|
|
271
|
+
async dispose() {
|
|
272
|
+
await this.stop();
|
|
273
|
+
this.stopped = true;
|
|
274
|
+
}
|
|
275
|
+
async apply(pressure, candidates) {
|
|
276
|
+
if (this.stopped) return this.publish(this.buildReport(pressure, "stopped", [], void 0, [], []));
|
|
277
|
+
if (!this.accepting) {
|
|
278
|
+
const reason = this.inflight !== void 0 ? "draining" : "stopped";
|
|
279
|
+
return this.publish(this.buildReport(pressure, reason, [], void 0, [], []));
|
|
280
|
+
}
|
|
281
|
+
if (this.inflight !== void 0) return this.publish(this.buildReport(pressure, "busy", [], void 0, [], []));
|
|
282
|
+
const run = this.startPass(pressure, candidates);
|
|
283
|
+
this.inflight = run;
|
|
284
|
+
try {
|
|
285
|
+
return await run;
|
|
286
|
+
} finally {
|
|
287
|
+
this.inflight = void 0;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
async startPass(pressure, candidates) {
|
|
291
|
+
if (!this.enabled) return this.publish(this.buildReport(pressure, "disabled", [], void 0, [], []));
|
|
292
|
+
return this.runPass(pressure, candidates);
|
|
293
|
+
}
|
|
294
|
+
async runPass(pressure, providedCandidates) {
|
|
295
|
+
const decision = selectResidencyActions(pressure, this.options);
|
|
296
|
+
const releaseDomains = this.releaseDomainsOf(pressure);
|
|
297
|
+
let candidates;
|
|
298
|
+
try {
|
|
299
|
+
candidates = providedCandidates ?? this.options.ports.listResidencyCandidates();
|
|
300
|
+
} catch (error) {
|
|
301
|
+
return this.publish(this.buildReport(pressure, "error", decision.triggeredDomains, decision.thresholds, [], [], messageOf$2(error)));
|
|
302
|
+
}
|
|
303
|
+
const thresholds = decision.thresholds;
|
|
304
|
+
const exceedsBytes = (candidate) => thresholds.surfaceKeepBytes > 0 && (candidate.surfaceBytes ?? 0) > thresholds.surfaceKeepBytes && !this.isFutileByteTrim(candidate.sessionId, candidate.surfaceBytes ?? 0);
|
|
305
|
+
const budgetExceeded = candidates.some((candidate) => exceedsBytes(candidate));
|
|
306
|
+
if (decision.reason !== "ok" && !budgetExceeded && releaseDomains.length === 0) return this.publish(this.buildReport(pressure, decision.reason, decision.triggeredDomains, decision.thresholds, [], []));
|
|
307
|
+
const actions = [];
|
|
308
|
+
const receipts = [];
|
|
309
|
+
let released = 0;
|
|
310
|
+
if (releaseDomains.length > 0) {
|
|
311
|
+
const outcome = await this.releaseOwnersOf(releaseDomains);
|
|
312
|
+
actions.push(...outcome.actions);
|
|
313
|
+
receipts.push(...outcome.receipts);
|
|
314
|
+
released = outcome.released;
|
|
315
|
+
}
|
|
316
|
+
const triggeredDomains = [...decision.triggeredDomains, ...releaseDomains.filter((domain) => !decision.triggeredDomains.includes(domain))];
|
|
317
|
+
if (decision.reason !== "ok" && !budgetExceeded) {
|
|
318
|
+
const reason = released > 0 ? "ok" : "no-owned-target";
|
|
319
|
+
return this.publish(this.buildReport(pressure, reason, triggeredDomains, decision.thresholds, actions, receipts));
|
|
320
|
+
}
|
|
321
|
+
const nowMs = this.now();
|
|
322
|
+
const evicted = /* @__PURE__ */ new Set();
|
|
323
|
+
const isBusy = this.options.ports.isBusy;
|
|
324
|
+
const idleOf = (candidate) => isBusy?.(candidate.sessionId) !== true;
|
|
325
|
+
const idle = selectCandidates(candidates, (candidate) => idleOf(candidate) && candidate.activeSubscribers === 0 && nowMs - candidate.lastActiveAtMs >= thresholds.idleEvictMs, (a, b) => a.lastActiveAtMs - b.lastActiveAtMs, this.maxEvictionsPerPass);
|
|
326
|
+
for (const candidate of idle) try {
|
|
327
|
+
const applied = await this.options.ports.evictSession(candidate.sessionId);
|
|
328
|
+
actions.push({
|
|
329
|
+
action: "evict",
|
|
330
|
+
sessionId: candidate.sessionId,
|
|
331
|
+
applied
|
|
332
|
+
});
|
|
333
|
+
if (applied) evicted.add(candidate.sessionId);
|
|
334
|
+
} catch (error) {
|
|
335
|
+
actions.push({
|
|
336
|
+
action: "evict",
|
|
337
|
+
sessionId: candidate.sessionId,
|
|
338
|
+
applied: false,
|
|
339
|
+
error: messageOf$2(error)
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
const exceedsCount = (candidate) => candidate.surfaceLength > thresholds.surfaceKeepLast;
|
|
343
|
+
const overageOf = (candidate) => {
|
|
344
|
+
const countRatio = thresholds.surfaceKeepLast > 0 ? candidate.surfaceLength / thresholds.surfaceKeepLast : 0;
|
|
345
|
+
const bytesRatio = thresholds.surfaceKeepBytes > 0 ? (candidate.surfaceBytes ?? 0) / thresholds.surfaceKeepBytes : 0;
|
|
346
|
+
return Math.max(countRatio, bytesRatio);
|
|
347
|
+
};
|
|
348
|
+
const bloated = selectCandidates(candidates, (candidate) => idleOf(candidate) && !evicted.has(candidate.sessionId) && (exceedsCount(candidate) || exceedsBytes(candidate)), (a, b) => overageOf(b) - overageOf(a), this.maxBoundSurfacesPerPass);
|
|
349
|
+
for (const candidate of bloated) {
|
|
350
|
+
const fit = async (target) => {
|
|
351
|
+
try {
|
|
352
|
+
const outcome = await this.options.ports.fitSurface(candidate.sessionId, target);
|
|
353
|
+
const applied = outcome.kind === "reduced";
|
|
354
|
+
actions.push({
|
|
355
|
+
action: "fitSurface",
|
|
356
|
+
sessionId: candidate.sessionId,
|
|
357
|
+
applied,
|
|
358
|
+
dimension: target.dimension,
|
|
359
|
+
...outcome.kind === "reduced" ? { by: outcome.by } : {},
|
|
360
|
+
...outcome.kind === "failed" ? { error: outcome.cause } : {}
|
|
361
|
+
});
|
|
362
|
+
if (target.dimension !== "bytes") return;
|
|
363
|
+
if (applied) {
|
|
364
|
+
this.futileByteTrims.delete(candidate.sessionId);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
this.futileByteTrims.set(candidate.sessionId, {
|
|
368
|
+
bytes: candidate.surfaceBytes ?? 0,
|
|
369
|
+
at: this.now()
|
|
370
|
+
});
|
|
371
|
+
} catch (error) {
|
|
372
|
+
actions.push({
|
|
373
|
+
action: "fitSurface",
|
|
374
|
+
sessionId: candidate.sessionId,
|
|
375
|
+
applied: false,
|
|
376
|
+
dimension: target.dimension,
|
|
377
|
+
error: messageOf$2(error)
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
if (exceedsCount(candidate)) await fit({
|
|
382
|
+
dimension: "count",
|
|
383
|
+
keepLast: thresholds.surfaceKeepLast
|
|
384
|
+
});
|
|
385
|
+
if (exceedsBytes(candidate)) await fit({
|
|
386
|
+
dimension: "bytes",
|
|
387
|
+
keepBytes: thresholds.surfaceKeepBytes
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
return this.publish(this.buildReport(pressure, "ok", triggeredDomains, thresholds, actions, receipts));
|
|
391
|
+
}
|
|
392
|
+
isFutileByteTrim(sessionId, bytes) {
|
|
393
|
+
const futile = this.futileByteTrims.get(sessionId);
|
|
394
|
+
if (futile === void 0) return false;
|
|
395
|
+
if (bytes > futile.bytes * 1.05) {
|
|
396
|
+
this.futileByteTrims.delete(sessionId);
|
|
397
|
+
return false;
|
|
398
|
+
}
|
|
399
|
+
if (this.now() - futile.at < this.futileTrimCooldownMs) return true;
|
|
400
|
+
this.futileByteTrims.delete(sessionId);
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
releaseDomainsOf(pressure) {
|
|
404
|
+
if (this.options.owners === void 0) return [];
|
|
405
|
+
const minLevel = this.options.minLevel ?? "warning";
|
|
406
|
+
if (!atLeastLevel(pressure.level, minLevel)) return [];
|
|
407
|
+
return triggeredDomainsOf(pressure, DEFAULT_RELEASE_DOMAINS, minLevel);
|
|
408
|
+
}
|
|
409
|
+
async releaseOwnersOf(domains) {
|
|
410
|
+
const owners = this.options.owners;
|
|
411
|
+
const actions = [];
|
|
412
|
+
const receipts = [];
|
|
413
|
+
let released = 0;
|
|
414
|
+
if (owners === void 0) return {
|
|
415
|
+
actions,
|
|
416
|
+
receipts,
|
|
417
|
+
released
|
|
418
|
+
};
|
|
419
|
+
const candidates = [];
|
|
420
|
+
try {
|
|
421
|
+
for (const domain of domains) candidates.push(...owners.ownersOf(domain));
|
|
422
|
+
} catch {
|
|
423
|
+
return {
|
|
424
|
+
actions,
|
|
425
|
+
receipts,
|
|
426
|
+
released
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
for (const owner of selectOwners(candidates, this.maxReleasesPerPass)) try {
|
|
430
|
+
const receipt = await owner.release(RELEASE_RESOURCE_REASON);
|
|
431
|
+
actions.push({
|
|
432
|
+
action: "releaseResource",
|
|
433
|
+
ownerId: owner.id,
|
|
434
|
+
domain: owner.domain,
|
|
435
|
+
receipt
|
|
436
|
+
});
|
|
437
|
+
receipts.push(receipt);
|
|
438
|
+
if (receipt.released) released += 1;
|
|
439
|
+
} catch (error) {
|
|
440
|
+
const receipt = {
|
|
441
|
+
ownerId: owner.id,
|
|
442
|
+
domain: owner.domain,
|
|
443
|
+
released: false,
|
|
444
|
+
reason: messageOf$2(error)
|
|
445
|
+
};
|
|
446
|
+
actions.push({
|
|
447
|
+
action: "releaseResource",
|
|
448
|
+
ownerId: owner.id,
|
|
449
|
+
domain: owner.domain,
|
|
450
|
+
receipt,
|
|
451
|
+
error: messageOf$2(error)
|
|
452
|
+
});
|
|
453
|
+
receipts.push(receipt);
|
|
454
|
+
}
|
|
455
|
+
return {
|
|
456
|
+
actions,
|
|
457
|
+
receipts,
|
|
458
|
+
released
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
buildReport(pressure, reason, triggeredDomains, thresholds, actions, receipts, error) {
|
|
462
|
+
const resolved = thresholds ?? resolveActionThresholds(pressure, this.options);
|
|
463
|
+
return {
|
|
464
|
+
ts: this.now(),
|
|
465
|
+
level: pressure.level,
|
|
466
|
+
divisor: pressure.budgetDivisor,
|
|
467
|
+
reason,
|
|
468
|
+
triggeredDomains,
|
|
469
|
+
thresholds: resolved,
|
|
470
|
+
actions,
|
|
471
|
+
receipts,
|
|
472
|
+
releaseFailures: receipts.filter((receipt) => !receipt.released),
|
|
473
|
+
...error === void 0 ? {} : { error }
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
publish(report) {
|
|
477
|
+
this.last = report;
|
|
478
|
+
try {
|
|
479
|
+
this.onReport?.(report);
|
|
480
|
+
} catch {
|
|
481
|
+
return report;
|
|
482
|
+
}
|
|
483
|
+
return report;
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
function createResidencyActionCoordinator(options) {
|
|
487
|
+
return new ResidencyActionCoordinator(options);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
//#endregion
|
|
491
|
+
//#region src/owner-registry.ts
|
|
492
|
+
function messageOf$1(error) {
|
|
493
|
+
return error instanceof Error ? error.message : String(error);
|
|
494
|
+
}
|
|
495
|
+
function createOwnerFacade(spec, cell, isLive) {
|
|
496
|
+
let inflight;
|
|
497
|
+
return {
|
|
498
|
+
id: spec.ownerId,
|
|
499
|
+
domain: spec.domain,
|
|
500
|
+
pressure() {
|
|
501
|
+
try {
|
|
502
|
+
return spec.pressure?.();
|
|
503
|
+
} catch {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
busy() {
|
|
508
|
+
try {
|
|
509
|
+
return spec.busy?.();
|
|
510
|
+
} catch {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
release(reason) {
|
|
515
|
+
const settled = cell.settled;
|
|
516
|
+
if (settled !== void 0) return Promise.resolve({
|
|
517
|
+
...settled,
|
|
518
|
+
reason: "already-released"
|
|
519
|
+
});
|
|
520
|
+
if (!isLive()) return Promise.resolve({
|
|
521
|
+
ownerId: spec.ownerId,
|
|
522
|
+
domain: spec.domain,
|
|
523
|
+
released: false,
|
|
524
|
+
reason: "no-owner"
|
|
525
|
+
});
|
|
526
|
+
if (inflight !== void 0) return inflight;
|
|
527
|
+
const attempt = spec.release(reason).then((receipt) => {
|
|
528
|
+
cell.settled = receipt.released ? receipt : void 0;
|
|
529
|
+
inflight = void 0;
|
|
530
|
+
return receipt;
|
|
531
|
+
}, (error) => {
|
|
532
|
+
inflight = void 0;
|
|
533
|
+
return {
|
|
534
|
+
ownerId: spec.ownerId,
|
|
535
|
+
domain: spec.domain,
|
|
536
|
+
released: false,
|
|
537
|
+
reason: messageOf$1(error)
|
|
538
|
+
};
|
|
539
|
+
});
|
|
540
|
+
inflight = attempt;
|
|
541
|
+
return attempt;
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
function createResourceOwnerRegistry(options = {}) {
|
|
546
|
+
const now = options.now ?? (() => Date.now());
|
|
547
|
+
const entries = /* @__PURE__ */ new Map();
|
|
548
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
549
|
+
function notify(change) {
|
|
550
|
+
for (const listener of listeners) try {
|
|
551
|
+
listener(change);
|
|
552
|
+
} catch {
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function unregister(ownerId) {
|
|
557
|
+
const entry = entries.get(ownerId);
|
|
558
|
+
if (entry === void 0) return false;
|
|
559
|
+
entries.delete(ownerId);
|
|
560
|
+
entry.retireProbe?.();
|
|
561
|
+
notify({
|
|
562
|
+
type: "unregistered",
|
|
563
|
+
ownerId,
|
|
564
|
+
domain: entry.spec.domain,
|
|
565
|
+
kind: entry.spec.kind,
|
|
566
|
+
label: entry.spec.label,
|
|
567
|
+
pid: entry.spec.pid
|
|
568
|
+
});
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
register(spec) {
|
|
573
|
+
unregister(spec.ownerId);
|
|
574
|
+
const cell = { settled: void 0 };
|
|
575
|
+
const retireProbe = spec.pid !== void 0 && options.probe !== void 0 ? options.probe.registerSubprocess(spec.pid, spec.label) : void 0;
|
|
576
|
+
const entry = {
|
|
577
|
+
spec,
|
|
578
|
+
registeredAtMs: now(),
|
|
579
|
+
cell,
|
|
580
|
+
owner: createOwnerFacade(spec, cell, () => entries.get(spec.ownerId) === entry),
|
|
581
|
+
retireProbe
|
|
582
|
+
};
|
|
583
|
+
entries.set(spec.ownerId, entry);
|
|
584
|
+
notify({
|
|
585
|
+
type: "registered",
|
|
586
|
+
ownerId: spec.ownerId,
|
|
587
|
+
domain: spec.domain,
|
|
588
|
+
kind: spec.kind,
|
|
589
|
+
label: spec.label,
|
|
590
|
+
pid: spec.pid
|
|
591
|
+
});
|
|
592
|
+
return () => {
|
|
593
|
+
if (entries.get(spec.ownerId) === entry) unregister(spec.ownerId);
|
|
594
|
+
};
|
|
595
|
+
},
|
|
596
|
+
unregister,
|
|
597
|
+
ownersOf(domain) {
|
|
598
|
+
const owners = [];
|
|
599
|
+
for (const entry of entries.values()) if (entry.spec.domain === domain) owners.push(entry.owner);
|
|
600
|
+
return owners;
|
|
601
|
+
},
|
|
602
|
+
snapshot() {
|
|
603
|
+
const snapshots = [];
|
|
604
|
+
for (const entry of entries.values()) {
|
|
605
|
+
const pressure = entry.owner.pressure();
|
|
606
|
+
snapshots.push({
|
|
607
|
+
ownerId: entry.spec.ownerId,
|
|
608
|
+
domain: entry.spec.domain,
|
|
609
|
+
kind: entry.spec.kind,
|
|
610
|
+
label: entry.spec.label,
|
|
611
|
+
registeredAtMs: entry.registeredAtMs,
|
|
612
|
+
...entry.spec.pid === void 0 ? {} : { pid: entry.spec.pid },
|
|
613
|
+
...pressure === void 0 ? {} : { pressure }
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
return snapshots;
|
|
617
|
+
},
|
|
618
|
+
observe(listener) {
|
|
619
|
+
listeners.add(listener);
|
|
620
|
+
return () => {
|
|
621
|
+
listeners.delete(listener);
|
|
622
|
+
};
|
|
623
|
+
},
|
|
624
|
+
size() {
|
|
625
|
+
return entries.size;
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/trace.ts
|
|
632
|
+
const DEFAULT_RESIDENCY_TRACE_CAPACITY = 256;
|
|
633
|
+
function snapshotsOf(pressure) {
|
|
634
|
+
return pressure.domains.map((entry) => ({
|
|
635
|
+
domain: entry.domain,
|
|
636
|
+
level: entry.level,
|
|
637
|
+
usedPct: entry.usedPct,
|
|
638
|
+
sampling: entry.sampling,
|
|
639
|
+
...entry.warnPct === void 0 ? {} : { warnPct: entry.warnPct },
|
|
640
|
+
...entry.hardPct === void 0 ? {} : { hardPct: entry.hardPct }
|
|
641
|
+
}));
|
|
642
|
+
}
|
|
643
|
+
function resolveCapacity(capacity) {
|
|
644
|
+
if (capacity === void 0) return 256;
|
|
645
|
+
if (!Number.isFinite(capacity)) return 256;
|
|
646
|
+
const truncated = Math.trunc(capacity);
|
|
647
|
+
return truncated > 0 ? truncated : 256;
|
|
648
|
+
}
|
|
649
|
+
function createResidencyTrace(options = {}) {
|
|
650
|
+
const limit = resolveCapacity(options.capacity);
|
|
651
|
+
const ticks = [];
|
|
652
|
+
let seq = 0;
|
|
653
|
+
const push = (pressure, shadow) => {
|
|
654
|
+
seq += 1;
|
|
655
|
+
const tick = {
|
|
656
|
+
seq,
|
|
657
|
+
ts: shadow.ts,
|
|
658
|
+
level: pressure.level,
|
|
659
|
+
budgetDivisor: pressure.budgetDivisor,
|
|
660
|
+
domains: snapshotsOf(pressure),
|
|
661
|
+
shadow
|
|
662
|
+
};
|
|
663
|
+
ticks.push(tick);
|
|
664
|
+
if (ticks.length > limit) ticks.splice(0, ticks.length - limit);
|
|
665
|
+
return tick;
|
|
666
|
+
};
|
|
667
|
+
return {
|
|
668
|
+
record: push,
|
|
669
|
+
attachReport(report) {
|
|
670
|
+
for (let index = ticks.length - 1; index >= 0; index -= 1) {
|
|
671
|
+
const tick = ticks[index];
|
|
672
|
+
if (tick === void 0) continue;
|
|
673
|
+
if (tick.action !== void 0) continue;
|
|
674
|
+
if (tick.ts !== report.ts) continue;
|
|
675
|
+
tick.action = report;
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
for (let index = ticks.length - 1; index >= 0; index -= 1) {
|
|
679
|
+
const tick = ticks[index];
|
|
680
|
+
if (tick === void 0) continue;
|
|
681
|
+
if (tick.action !== void 0) continue;
|
|
682
|
+
tick.action = report;
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
},
|
|
686
|
+
recent(limit2) {
|
|
687
|
+
if (limit2 === void 0) return ticks.slice();
|
|
688
|
+
if (!Number.isFinite(limit2) || limit2 <= 0) return [];
|
|
689
|
+
return ticks.slice(Math.max(0, ticks.length - Math.trunc(limit2)));
|
|
690
|
+
},
|
|
691
|
+
latest() {
|
|
692
|
+
return ticks.at(-1);
|
|
693
|
+
},
|
|
694
|
+
seriesOf(domain) {
|
|
695
|
+
const points = [];
|
|
696
|
+
for (const tick of ticks) {
|
|
697
|
+
const entry = tick.domains.find((candidate) => candidate.domain === domain);
|
|
698
|
+
if (entry === void 0) continue;
|
|
699
|
+
points.push({
|
|
700
|
+
seq: tick.seq,
|
|
701
|
+
ts: tick.ts,
|
|
702
|
+
level: entry.level,
|
|
703
|
+
usedPct: entry.usedPct,
|
|
704
|
+
sampling: entry.sampling
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
return points;
|
|
708
|
+
},
|
|
709
|
+
size() {
|
|
710
|
+
return ticks.length;
|
|
711
|
+
},
|
|
712
|
+
capacity() {
|
|
713
|
+
return limit;
|
|
714
|
+
},
|
|
715
|
+
clear() {
|
|
716
|
+
ticks.splice(0, ticks.length);
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
//#endregion
|
|
722
|
+
//#region src/shadow.ts
|
|
723
|
+
const SHADOW_MIN_LEVEL = "warning";
|
|
724
|
+
function suggestionForDomain(domain) {
|
|
725
|
+
if (domain === "processTree") return [];
|
|
726
|
+
if (domain === "heap" || domain === "system") return ["evict", "fitSurface"];
|
|
727
|
+
if (domain === "tokens") return ["compaction"];
|
|
728
|
+
return [];
|
|
729
|
+
}
|
|
730
|
+
function attributionOf(pressure, samplingReason) {
|
|
731
|
+
return {
|
|
732
|
+
domain: "processTree",
|
|
733
|
+
confidence: pressure.domains.find((domain) => domain.domain === "processTree")?.sampling === "ok" ? "measured" : "unavailable",
|
|
734
|
+
processCount: pressure.subprocess?.processes.length ?? 0,
|
|
735
|
+
attributedRssBytes: pressure.subprocess?.totalRssBytes ?? 0,
|
|
736
|
+
...samplingReason === void 0 ? {} : { samplingReason }
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
function suggestFromPressure(pressure, ts, samplingReason) {
|
|
740
|
+
const suggested = [];
|
|
741
|
+
const sources = [];
|
|
742
|
+
for (const entry of pressure.domains) {
|
|
743
|
+
if (entry.sampling !== "ok") continue;
|
|
744
|
+
if (!atLeastLevel(entry.level, "warning")) continue;
|
|
745
|
+
sources.push(entry.domain);
|
|
746
|
+
for (const action of suggestionForDomain(entry.domain)) suggested.push(action);
|
|
747
|
+
}
|
|
748
|
+
return {
|
|
749
|
+
ts,
|
|
750
|
+
mode: "shadow",
|
|
751
|
+
autoTriggered: false,
|
|
752
|
+
suggested,
|
|
753
|
+
sources,
|
|
754
|
+
attribution: attributionOf(pressure, samplingReason)
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
//#endregion
|
|
759
|
+
//#region src/threshold-spec.ts
|
|
760
|
+
const DEFAULT_WARN_THRESHOLD_PCT = 70;
|
|
761
|
+
const DEFAULT_HARD_THRESHOLD_PCT = 85;
|
|
762
|
+
const DEFAULT_SYSTEM_WARN_THRESHOLD_PCT = 2;
|
|
763
|
+
const DEFAULT_SYSTEM_HARD_THRESHOLD_PCT = 5;
|
|
764
|
+
const DEFAULT_SAMPLE_INTERVAL_MS = 3e4;
|
|
765
|
+
const DEFAULT_WARNING_INTERVAL_MS = 1e4;
|
|
766
|
+
const DEFAULT_CRITICAL_INTERVAL_MS = 5e3;
|
|
767
|
+
const DEFAULT_WARN_COOLDOWN_MS = 3e5;
|
|
768
|
+
const DEFAULT_PROCESS_TREE_BUDGET_BYTES = PROCESS_TREE_BUDGET_DEFAULT;
|
|
769
|
+
const DEFAULT_SUBPROCESS_WEIGHT = .85;
|
|
770
|
+
const THRESHOLD_ENV_KEYS = {
|
|
771
|
+
warnThresholdPct: "OTTO_MEMORY_WARN_PCT",
|
|
772
|
+
hardThresholdPct: "OTTO_MEMORY_HARD_PCT",
|
|
773
|
+
systemWarnThresholdPct: "OTTO_MEMORY_SYSTEM_WARN_PCT",
|
|
774
|
+
systemHardThresholdPct: "OTTO_MEMORY_SYSTEM_HARD_PCT",
|
|
775
|
+
sampleIntervalMs: "OTTO_MEMORY_SAMPLE_INTERVAL_MS",
|
|
776
|
+
warningIntervalMs: "OTTO_MEMORY_WARNING_INTERVAL_MS",
|
|
777
|
+
criticalIntervalMs: "OTTO_MEMORY_CRITICAL_INTERVAL_MS",
|
|
778
|
+
processTreeBudgetBytes: PROCESS_TREE_BUDGET_SETTING_ENV,
|
|
779
|
+
subprocessWeight: "OTTO_RESIDENCY_SUBPROCESS_WEIGHT"
|
|
780
|
+
};
|
|
781
|
+
function resolveResidencyThresholds(env, overrides = {}) {
|
|
782
|
+
return {
|
|
783
|
+
warnThresholdPct: overrides.warnThresholdPct ?? resolvePctEnv(env, THRESHOLD_ENV_KEYS.warnThresholdPct, 70),
|
|
784
|
+
hardThresholdPct: overrides.hardThresholdPct ?? resolvePctEnv(env, THRESHOLD_ENV_KEYS.hardThresholdPct, 85),
|
|
785
|
+
systemWarnThresholdPct: overrides.systemWarnThresholdPct ?? resolvePctEnv(env, THRESHOLD_ENV_KEYS.systemWarnThresholdPct, 2),
|
|
786
|
+
systemHardThresholdPct: overrides.systemHardThresholdPct ?? resolvePctEnv(env, THRESHOLD_ENV_KEYS.systemHardThresholdPct, 5),
|
|
787
|
+
sampleIntervalMs: overrides.sampleIntervalMs ?? resolveMsEnv(env, THRESHOLD_ENV_KEYS.sampleIntervalMs, 3e4),
|
|
788
|
+
warningIntervalMs: overrides.warningIntervalMs ?? resolveMsEnv(env, THRESHOLD_ENV_KEYS.warningIntervalMs, 1e4),
|
|
789
|
+
criticalIntervalMs: overrides.criticalIntervalMs ?? resolveMsEnv(env, THRESHOLD_ENV_KEYS.criticalIntervalMs, 5e3),
|
|
790
|
+
warnCooldownMs: overrides.warnCooldownMs ?? 3e5,
|
|
791
|
+
processTreeBudgetBytes: overrides.processTreeBudgetBytes ?? resolvePositiveEnv(env, THRESHOLD_ENV_KEYS.processTreeBudgetBytes, DEFAULT_PROCESS_TREE_BUDGET_BYTES),
|
|
792
|
+
subprocessWeight: overrides.subprocessWeight ?? resolvePositiveEnv(env, THRESHOLD_ENV_KEYS.subprocessWeight, .85)
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
const DEFAULT_SYSTEM_WARN_FLOOR_BYTES = 512 * 1024 * 1024;
|
|
796
|
+
function systemThresholdPcts(baseWarnPct, baseHardPct, floorBytes, totalBytes) {
|
|
797
|
+
const warnPct = totalBytes !== void 0 && Number.isFinite(totalBytes) && totalBytes > 0 ? Math.max(baseWarnPct, floorBytes / totalBytes * 100) : baseWarnPct;
|
|
798
|
+
return {
|
|
799
|
+
warnPct,
|
|
800
|
+
hardPct: Math.max(baseHardPct, warnPct + 3)
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
//#endregion
|
|
805
|
+
//#region src/memory-governor.ts
|
|
806
|
+
function readHeapSample(now) {
|
|
807
|
+
const { heapUsed, external, rss } = process.memoryUsage();
|
|
808
|
+
const { heap_size_limit: heapLimitBytes } = getHeapStatistics();
|
|
809
|
+
return {
|
|
810
|
+
heapUsedBytes: heapUsed,
|
|
811
|
+
heapLimitBytes,
|
|
812
|
+
externalBytes: external,
|
|
813
|
+
rssBytes: rss,
|
|
814
|
+
systemTotalBytes: totalmem(),
|
|
815
|
+
usedPct: pctOf(heapUsed, heapLimitBytes),
|
|
816
|
+
ts: now()
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
var MemoryGovernor = class {
|
|
820
|
+
warnThresholdPct;
|
|
821
|
+
hardThresholdPct;
|
|
822
|
+
postRestartGraceMs;
|
|
823
|
+
now;
|
|
824
|
+
sampleHeap;
|
|
825
|
+
onSample;
|
|
826
|
+
disposed = false;
|
|
827
|
+
lastLevel = "healthy";
|
|
828
|
+
graceStartedAt;
|
|
829
|
+
lastSample;
|
|
830
|
+
onObserverError;
|
|
831
|
+
constructor(options) {
|
|
832
|
+
this.warnThresholdPct = options.warnThresholdPct;
|
|
833
|
+
this.hardThresholdPct = options.hardThresholdPct;
|
|
834
|
+
this.postRestartGraceMs = options.postRestartGraceMs ?? 0;
|
|
835
|
+
this.now = options.now ?? (() => Date.now());
|
|
836
|
+
this.sampleHeap = options.sampleHeap ?? (() => readHeapSample(this.now));
|
|
837
|
+
this.onSample = options.onSample;
|
|
838
|
+
this.onObserverError = options.onObserverError;
|
|
839
|
+
}
|
|
840
|
+
level() {
|
|
841
|
+
return this.lastLevel;
|
|
842
|
+
}
|
|
843
|
+
get inPostRestartGrace() {
|
|
844
|
+
if (this.graceStartedAt === void 0) return false;
|
|
845
|
+
return this.now() - this.graceStartedAt < this.postRestartGraceMs;
|
|
846
|
+
}
|
|
847
|
+
markRestarted() {
|
|
848
|
+
this.graceStartedAt = this.now();
|
|
849
|
+
}
|
|
850
|
+
sample() {
|
|
851
|
+
const raw = this.sampleHeap();
|
|
852
|
+
const sample = {
|
|
853
|
+
...raw,
|
|
854
|
+
usedPct: pctOf(raw.heapUsedBytes, raw.heapLimitBytes)
|
|
855
|
+
};
|
|
856
|
+
this.lastSample = sample;
|
|
857
|
+
this.lastLevel = gradeByPct(sample.usedPct, this.warnThresholdPct, this.hardThresholdPct);
|
|
858
|
+
return sample;
|
|
859
|
+
}
|
|
860
|
+
lastSampled() {
|
|
861
|
+
return this.lastSample;
|
|
862
|
+
}
|
|
863
|
+
poll() {
|
|
864
|
+
const previous = this.lastLevel;
|
|
865
|
+
const sample = this.sample();
|
|
866
|
+
this.notify(sample, previous);
|
|
867
|
+
return sample;
|
|
868
|
+
}
|
|
869
|
+
dispose() {
|
|
870
|
+
this.disposed = true;
|
|
871
|
+
}
|
|
872
|
+
notify(sample, previous) {
|
|
873
|
+
if (this.disposed) return;
|
|
874
|
+
this.safe(() => this.onSample?.(sample));
|
|
875
|
+
if (this.lastLevel === previous) return;
|
|
876
|
+
}
|
|
877
|
+
safe(callback) {
|
|
878
|
+
try {
|
|
879
|
+
callback();
|
|
880
|
+
} catch (error) {
|
|
881
|
+
try {
|
|
882
|
+
this.onObserverError?.(error);
|
|
883
|
+
} catch {}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
function createMemoryGovernor(options) {
|
|
888
|
+
return new MemoryGovernor(options);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
//#endregion
|
|
892
|
+
//#region src/subprocess-probe.ts
|
|
893
|
+
const DEFAULT_MIN_SUBPROCESS_LIFETIME_MS = 8e3;
|
|
894
|
+
const DEFAULT_PID_REUSE_TOLERANCE_MS = 2e3;
|
|
895
|
+
const PS_TIMEOUT_MS = 2e3;
|
|
896
|
+
const PS_MAX_BUFFER_BYTES = 32 * 1024 * 1024;
|
|
897
|
+
function parseEtimeSeconds(raw) {
|
|
898
|
+
const matched = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(raw.trim());
|
|
899
|
+
if (matched === null) return void 0;
|
|
900
|
+
const days = matched[1] === void 0 ? 0 : Number(matched[1]);
|
|
901
|
+
const hours = matched[2] === void 0 ? 0 : Number(matched[2]);
|
|
902
|
+
const minutes = Number(matched[3]);
|
|
903
|
+
const seconds = Number(matched[4]);
|
|
904
|
+
return days * 86400 + hours * 3600 + minutes * 60 + seconds;
|
|
905
|
+
}
|
|
906
|
+
function parseProcessList(stdout, nowMs) {
|
|
907
|
+
const processes = [];
|
|
908
|
+
for (const line of stdout.split("\n")) {
|
|
909
|
+
const matched = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
910
|
+
if (matched === null) continue;
|
|
911
|
+
const command = (matched[5] ?? "").trim();
|
|
912
|
+
if (command.length === 0) continue;
|
|
913
|
+
const pid = Number(matched[1]);
|
|
914
|
+
const ppid = Number(matched[2]);
|
|
915
|
+
const rssBytes = Number(matched[3]) * 1024;
|
|
916
|
+
const etimeSeconds = parseEtimeSeconds(matched[4] ?? "");
|
|
917
|
+
processes.push({
|
|
918
|
+
pid,
|
|
919
|
+
ppid,
|
|
920
|
+
rssBytes,
|
|
921
|
+
command,
|
|
922
|
+
...etimeSeconds === void 0 ? {} : { startedAtMs: nowMs - etimeSeconds * 1e3 }
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
return processes;
|
|
926
|
+
}
|
|
927
|
+
async function defaultListProcessesAsync(now) {
|
|
928
|
+
const { execFile } = await import("node:child_process");
|
|
929
|
+
return parseProcessList(await new Promise((resolve, reject) => {
|
|
930
|
+
execFile("ps", ["-axo", "pid=,ppid=,rss=,etime=,command="], {
|
|
931
|
+
encoding: "utf8",
|
|
932
|
+
timeout: PS_TIMEOUT_MS,
|
|
933
|
+
maxBuffer: PS_MAX_BUFFER_BYTES
|
|
934
|
+
}, (error, output) => {
|
|
935
|
+
if (error) reject(error);
|
|
936
|
+
else resolve(output);
|
|
937
|
+
});
|
|
938
|
+
}), now());
|
|
939
|
+
}
|
|
940
|
+
function defaultListProcesses(now) {
|
|
941
|
+
return parseProcessList(execFileSync("ps", ["-axo", "pid=,ppid=,rss=,etime=,command="], {
|
|
942
|
+
encoding: "utf8",
|
|
943
|
+
timeout: PS_TIMEOUT_MS,
|
|
944
|
+
maxBuffer: PS_MAX_BUFFER_BYTES
|
|
945
|
+
}), now());
|
|
946
|
+
}
|
|
947
|
+
function createSubprocessProbe(options = {}) {
|
|
948
|
+
const now = options.now ?? (() => Date.now());
|
|
949
|
+
const list = options.listProcesses;
|
|
950
|
+
const rootPid = options.rootPid ?? process.pid;
|
|
951
|
+
const minLifetimeMs = options.minLifetimeMs ?? 8e3;
|
|
952
|
+
const pidReuseToleranceMs = options.pidReuseToleranceMs ?? 2e3;
|
|
953
|
+
const registered = /* @__PURE__ */ new Map();
|
|
954
|
+
const inProcessSubagents = /* @__PURE__ */ new Set();
|
|
955
|
+
const seenStartedAt = /* @__PURE__ */ new Map();
|
|
956
|
+
let unavailable;
|
|
957
|
+
let cache = null;
|
|
958
|
+
let refreshInFlight = false;
|
|
959
|
+
function resolveStartedAt(info) {
|
|
960
|
+
if (info.startedAtMs !== void 0) return info.startedAtMs;
|
|
961
|
+
return registered.get(info.pid)?.registeredAtMs;
|
|
962
|
+
}
|
|
963
|
+
function collectReusedPids(listing) {
|
|
964
|
+
const reusedPids = /* @__PURE__ */ new Set();
|
|
965
|
+
const alivePids = /* @__PURE__ */ new Set();
|
|
966
|
+
for (const info of listing) {
|
|
967
|
+
alivePids.add(info.pid);
|
|
968
|
+
const startedAtMs = resolveStartedAt(info);
|
|
969
|
+
if (startedAtMs === void 0) continue;
|
|
970
|
+
const previous = seenStartedAt.get(info.pid);
|
|
971
|
+
if (previous !== void 0 && Math.abs(previous - startedAtMs) > pidReuseToleranceMs) reusedPids.add(info.pid);
|
|
972
|
+
seenStartedAt.set(info.pid, startedAtMs);
|
|
973
|
+
}
|
|
974
|
+
for (const pid of [...seenStartedAt.keys()]) if (!alivePids.has(pid)) seenStartedAt.delete(pid);
|
|
975
|
+
return reusedPids;
|
|
976
|
+
}
|
|
977
|
+
function collectTree(listing, reusedPids) {
|
|
978
|
+
const byPid = /* @__PURE__ */ new Map();
|
|
979
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
980
|
+
for (const info of listing) {
|
|
981
|
+
byPid.set(info.pid, info);
|
|
982
|
+
const siblings = childrenOf.get(info.ppid);
|
|
983
|
+
if (siblings === void 0) childrenOf.set(info.ppid, [info.pid]);
|
|
984
|
+
else siblings.push(info.pid);
|
|
985
|
+
}
|
|
986
|
+
const selected = /* @__PURE__ */ new Map();
|
|
987
|
+
const visited = new Set([rootPid]);
|
|
988
|
+
const stack = [...[rootPid, ...registered.keys()]];
|
|
989
|
+
while (stack.length > 0) {
|
|
990
|
+
const pid = stack.pop();
|
|
991
|
+
if (pid === void 0) continue;
|
|
992
|
+
if (reusedPids.has(pid)) continue;
|
|
993
|
+
for (const childPid of childrenOf.get(pid) ?? []) {
|
|
994
|
+
if (visited.has(childPid) || reusedPids.has(childPid)) continue;
|
|
995
|
+
visited.add(childPid);
|
|
996
|
+
const info = byPid.get(childPid);
|
|
997
|
+
if (info !== void 0 && childPid !== rootPid) selected.set(childPid, {
|
|
998
|
+
pid: info.pid,
|
|
999
|
+
command: info.command,
|
|
1000
|
+
rssBytes: info.rssBytes,
|
|
1001
|
+
role: "descendant"
|
|
1002
|
+
});
|
|
1003
|
+
stack.push(childPid);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
for (const pid of registered.keys()) {
|
|
1007
|
+
if (reusedPids.has(pid) || pid === rootPid) continue;
|
|
1008
|
+
const info = byPid.get(pid);
|
|
1009
|
+
if (info !== void 0) selected.set(pid, {
|
|
1010
|
+
pid: info.pid,
|
|
1011
|
+
command: info.command,
|
|
1012
|
+
rssBytes: info.rssBytes,
|
|
1013
|
+
role: "registered"
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
return selected;
|
|
1017
|
+
}
|
|
1018
|
+
function sampleFromListing(listing, ts) {
|
|
1019
|
+
const selected = collectTree(listing, collectReusedPids(listing));
|
|
1020
|
+
const byPid = new Map(listing.map((candidate) => [candidate.pid, candidate]));
|
|
1021
|
+
const processes = [];
|
|
1022
|
+
let totalRssBytes = 0;
|
|
1023
|
+
for (const entry of selected.values()) {
|
|
1024
|
+
const info = byPid.get(entry.pid);
|
|
1025
|
+
const startedAtMs = info === void 0 ? void 0 : resolveStartedAt(info);
|
|
1026
|
+
if ((startedAtMs === void 0 ? Number.POSITIVE_INFINITY : ts - startedAtMs) < minLifetimeMs) continue;
|
|
1027
|
+
processes.push(entry);
|
|
1028
|
+
totalRssBytes += entry.rssBytes;
|
|
1029
|
+
}
|
|
1030
|
+
processes.sort((a, b) => a.pid - b.pid);
|
|
1031
|
+
return {
|
|
1032
|
+
processes,
|
|
1033
|
+
totalRssBytes,
|
|
1034
|
+
ts
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
return {
|
|
1038
|
+
register(pid, command) {
|
|
1039
|
+
registered.set(pid, {
|
|
1040
|
+
command,
|
|
1041
|
+
registeredAtMs: now()
|
|
1042
|
+
});
|
|
1043
|
+
return () => {
|
|
1044
|
+
registered.delete(pid);
|
|
1045
|
+
};
|
|
1046
|
+
},
|
|
1047
|
+
registerInProcessSubagent(id) {
|
|
1048
|
+
inProcessSubagents.add(id);
|
|
1049
|
+
return () => {
|
|
1050
|
+
inProcessSubagents.delete(id);
|
|
1051
|
+
};
|
|
1052
|
+
},
|
|
1053
|
+
registeredPids() {
|
|
1054
|
+
return [...registered.keys()];
|
|
1055
|
+
},
|
|
1056
|
+
inProcessSubagentIds() {
|
|
1057
|
+
return [...inProcessSubagents];
|
|
1058
|
+
},
|
|
1059
|
+
unavailableReason() {
|
|
1060
|
+
return unavailable;
|
|
1061
|
+
},
|
|
1062
|
+
sample() {
|
|
1063
|
+
if (list !== void 0) try {
|
|
1064
|
+
const listing = list();
|
|
1065
|
+
unavailable = void 0;
|
|
1066
|
+
cache = {
|
|
1067
|
+
listing,
|
|
1068
|
+
sampledAtMs: now()
|
|
1069
|
+
};
|
|
1070
|
+
return sampleFromListing(listing, now());
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
unavailable = error instanceof Error ? error.message : String(error);
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
if (!refreshInFlight) {
|
|
1076
|
+
refreshInFlight = true;
|
|
1077
|
+
defaultListProcessesAsync(now).then((listing) => {
|
|
1078
|
+
cache = {
|
|
1079
|
+
listing,
|
|
1080
|
+
sampledAtMs: now()
|
|
1081
|
+
};
|
|
1082
|
+
}).catch(() => void 0).finally(() => {
|
|
1083
|
+
refreshInFlight = false;
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
if (cache === null || cache.sampledAtMs === 0) return;
|
|
1087
|
+
unavailable = void 0;
|
|
1088
|
+
return sampleFromListing(cache.listing, cache.sampledAtMs);
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region src/residency-governor.ts
|
|
1095
|
+
function staticProcessTreeBudget(value) {
|
|
1096
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return;
|
|
1097
|
+
return value;
|
|
1098
|
+
}
|
|
1099
|
+
var ResidencyGovernor = class {
|
|
1100
|
+
heap;
|
|
1101
|
+
probe;
|
|
1102
|
+
sampleTokens;
|
|
1103
|
+
now;
|
|
1104
|
+
warnThresholdPct;
|
|
1105
|
+
hardThresholdPct;
|
|
1106
|
+
systemWarnThresholdPct;
|
|
1107
|
+
systemHardThresholdPct;
|
|
1108
|
+
systemWarnFloorBytes;
|
|
1109
|
+
processTreeBudgetBytes;
|
|
1110
|
+
readProcessTreeBudget;
|
|
1111
|
+
subprocessWeight;
|
|
1112
|
+
onSample;
|
|
1113
|
+
sampleIntervalMs;
|
|
1114
|
+
warningIntervalMs;
|
|
1115
|
+
criticalIntervalMs;
|
|
1116
|
+
ticker = null;
|
|
1117
|
+
running = false;
|
|
1118
|
+
disposed = false;
|
|
1119
|
+
lastLevel = "healthy";
|
|
1120
|
+
lastSample;
|
|
1121
|
+
current;
|
|
1122
|
+
onObserverError;
|
|
1123
|
+
constructor(options = {}) {
|
|
1124
|
+
this.now = options.now ?? (() => Date.now());
|
|
1125
|
+
const configuredBudget = options.processTreeBudgetBytes;
|
|
1126
|
+
const staticBudget = staticProcessTreeBudget(configuredBudget);
|
|
1127
|
+
this.readProcessTreeBudget = typeof configuredBudget === "function" ? configuredBudget : void 0;
|
|
1128
|
+
const thresholds = resolveResidencyThresholds(options.env, {
|
|
1129
|
+
...options.warnThresholdPct === void 0 ? {} : { warnThresholdPct: options.warnThresholdPct },
|
|
1130
|
+
...options.hardThresholdPct === void 0 ? {} : { hardThresholdPct: options.hardThresholdPct },
|
|
1131
|
+
...options.systemWarnThresholdPct === void 0 ? {} : { systemWarnThresholdPct: options.systemWarnThresholdPct },
|
|
1132
|
+
...options.systemHardThresholdPct === void 0 ? {} : { systemHardThresholdPct: options.systemHardThresholdPct },
|
|
1133
|
+
...options.sampleIntervalMs === void 0 ? {} : { sampleIntervalMs: options.sampleIntervalMs },
|
|
1134
|
+
...options.warningIntervalMs === void 0 ? {} : { warningIntervalMs: options.warningIntervalMs },
|
|
1135
|
+
...options.criticalIntervalMs === void 0 ? {} : { criticalIntervalMs: options.criticalIntervalMs },
|
|
1136
|
+
...options.warnCooldownMs === void 0 ? {} : { warnCooldownMs: options.warnCooldownMs },
|
|
1137
|
+
...staticBudget === void 0 ? {} : { processTreeBudgetBytes: staticBudget },
|
|
1138
|
+
...options.subprocessWeight === void 0 ? {} : { subprocessWeight: options.subprocessWeight }
|
|
1139
|
+
});
|
|
1140
|
+
this.warnThresholdPct = thresholds.warnThresholdPct;
|
|
1141
|
+
this.hardThresholdPct = thresholds.hardThresholdPct;
|
|
1142
|
+
this.systemWarnThresholdPct = thresholds.systemWarnThresholdPct;
|
|
1143
|
+
this.systemHardThresholdPct = thresholds.systemHardThresholdPct;
|
|
1144
|
+
this.systemWarnFloorBytes = options.systemWarnFloorBytes ?? 536870912;
|
|
1145
|
+
this.sampleIntervalMs = thresholds.sampleIntervalMs;
|
|
1146
|
+
this.warningIntervalMs = thresholds.warningIntervalMs;
|
|
1147
|
+
this.criticalIntervalMs = thresholds.criticalIntervalMs;
|
|
1148
|
+
this.processTreeBudgetBytes = thresholds.processTreeBudgetBytes;
|
|
1149
|
+
this.subprocessWeight = thresholds.subprocessWeight;
|
|
1150
|
+
this.sampleTokens = options.sampleTokens;
|
|
1151
|
+
this.onSample = options.onSample;
|
|
1152
|
+
this.onObserverError = options.onObserverError;
|
|
1153
|
+
this.probe = options.probe ?? createSubprocessProbe({ now: this.now });
|
|
1154
|
+
this.heap = createMemoryGovernor({
|
|
1155
|
+
warnThresholdPct: thresholds.warnThresholdPct,
|
|
1156
|
+
hardThresholdPct: thresholds.hardThresholdPct,
|
|
1157
|
+
...options.postRestartGraceMs === void 0 ? {} : { postRestartGraceMs: options.postRestartGraceMs },
|
|
1158
|
+
...options.sampleHeap === void 0 ? {} : { sampleHeap: options.sampleHeap },
|
|
1159
|
+
...options.onObserverError === void 0 ? {} : { onObserverError: options.onObserverError },
|
|
1160
|
+
now: this.now
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
level() {
|
|
1164
|
+
return this.lastLevel;
|
|
1165
|
+
}
|
|
1166
|
+
budgetDivisor() {
|
|
1167
|
+
return divisorFor(this.lastLevel);
|
|
1168
|
+
}
|
|
1169
|
+
currentPressure() {
|
|
1170
|
+
return this.current;
|
|
1171
|
+
}
|
|
1172
|
+
markRestarted() {
|
|
1173
|
+
this.heap.markRestarted();
|
|
1174
|
+
}
|
|
1175
|
+
registerSubprocess(pid, command) {
|
|
1176
|
+
return this.probe.register(pid, command);
|
|
1177
|
+
}
|
|
1178
|
+
get inPostRestartGrace() {
|
|
1179
|
+
return this.heap.inPostRestartGrace;
|
|
1180
|
+
}
|
|
1181
|
+
pressure() {
|
|
1182
|
+
let sample;
|
|
1183
|
+
let heapDomain;
|
|
1184
|
+
let systemDomain;
|
|
1185
|
+
try {
|
|
1186
|
+
sample = this.heap.poll();
|
|
1187
|
+
heapDomain = heapDomainLevel(sample, this.warnThresholdPct, this.hardThresholdPct);
|
|
1188
|
+
const systemPcts = systemThresholdPcts(this.systemWarnThresholdPct, this.systemHardThresholdPct, this.systemWarnFloorBytes, sample.systemTotalBytes);
|
|
1189
|
+
systemDomain = systemDomainLevel(sample, systemPcts.warnPct, systemPcts.hardPct);
|
|
1190
|
+
} catch {
|
|
1191
|
+
sample = this.lastSample ?? {
|
|
1192
|
+
heapUsedBytes: 0,
|
|
1193
|
+
heapLimitBytes: 0,
|
|
1194
|
+
externalBytes: 0,
|
|
1195
|
+
rssBytes: 0,
|
|
1196
|
+
usedPct: NaN,
|
|
1197
|
+
ts: this.now()
|
|
1198
|
+
};
|
|
1199
|
+
heapDomain = unavailableDomain("heap");
|
|
1200
|
+
systemDomain = unavailableDomain("system");
|
|
1201
|
+
}
|
|
1202
|
+
let tokensDomain;
|
|
1203
|
+
const tokens = this.sampleTokens;
|
|
1204
|
+
if (tokens === void 0) tokensDomain = unavailableDomain("tokens");
|
|
1205
|
+
else try {
|
|
1206
|
+
tokensDomain = tokenDomainLevel(tokens(), this.warnThresholdPct, this.hardThresholdPct);
|
|
1207
|
+
} catch {
|
|
1208
|
+
tokensDomain = unavailableDomain("tokens");
|
|
1209
|
+
}
|
|
1210
|
+
let subprocess;
|
|
1211
|
+
try {
|
|
1212
|
+
subprocess = this.probe.sample();
|
|
1213
|
+
} catch {
|
|
1214
|
+
subprocess = void 0;
|
|
1215
|
+
}
|
|
1216
|
+
const processTreeDomain = processTreeDomainLevel(subprocess, this.currentProcessTreeBudgetBytes(), this.subprocessWeight, this.warnThresholdPct, this.hardThresholdPct);
|
|
1217
|
+
const domains = [
|
|
1218
|
+
tokensDomain,
|
|
1219
|
+
heapDomain,
|
|
1220
|
+
systemDomain,
|
|
1221
|
+
processTreeDomain
|
|
1222
|
+
];
|
|
1223
|
+
const level = aggregateLevel(domains);
|
|
1224
|
+
const pressure = {
|
|
1225
|
+
level,
|
|
1226
|
+
domains,
|
|
1227
|
+
budgetDivisor: divisorFor(level),
|
|
1228
|
+
sample,
|
|
1229
|
+
...subprocess === void 0 ? {} : { subprocess }
|
|
1230
|
+
};
|
|
1231
|
+
this.lastSample = sample;
|
|
1232
|
+
this.lastLevel = level;
|
|
1233
|
+
this.current = pressure;
|
|
1234
|
+
if (this.disposed) return pressure;
|
|
1235
|
+
this.safe(() => this.onSample?.(pressure));
|
|
1236
|
+
return pressure;
|
|
1237
|
+
}
|
|
1238
|
+
currentProcessTreeBudgetBytes() {
|
|
1239
|
+
const read = this.readProcessTreeBudget;
|
|
1240
|
+
if (read === void 0) return this.processTreeBudgetBytes;
|
|
1241
|
+
try {
|
|
1242
|
+
const next = read();
|
|
1243
|
+
if (typeof next === "number" && Number.isFinite(next) && next > 0) return next;
|
|
1244
|
+
} catch {
|
|
1245
|
+
return this.processTreeBudgetBytes;
|
|
1246
|
+
}
|
|
1247
|
+
return this.processTreeBudgetBytes;
|
|
1248
|
+
}
|
|
1249
|
+
safe(callback) {
|
|
1250
|
+
try {
|
|
1251
|
+
callback();
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
try {
|
|
1254
|
+
this.onObserverError?.(error);
|
|
1255
|
+
} catch {}
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
start() {
|
|
1259
|
+
if (this.disposed || this.running) return;
|
|
1260
|
+
this.running = true;
|
|
1261
|
+
this.armNext();
|
|
1262
|
+
}
|
|
1263
|
+
stop() {
|
|
1264
|
+
this.running = false;
|
|
1265
|
+
if (this.ticker !== null) {
|
|
1266
|
+
clearTimeout(this.ticker);
|
|
1267
|
+
this.ticker = null;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
dispose() {
|
|
1271
|
+
this.disposed = true;
|
|
1272
|
+
this.running = false;
|
|
1273
|
+
if (this.ticker !== null) {
|
|
1274
|
+
clearTimeout(this.ticker);
|
|
1275
|
+
this.ticker = null;
|
|
1276
|
+
}
|
|
1277
|
+
this.heap.dispose();
|
|
1278
|
+
}
|
|
1279
|
+
intervalForLevel() {
|
|
1280
|
+
if (this.lastLevel === "critical") return this.criticalIntervalMs;
|
|
1281
|
+
if (this.lastLevel === "warning") return this.warningIntervalMs;
|
|
1282
|
+
return this.sampleIntervalMs;
|
|
1283
|
+
}
|
|
1284
|
+
armNext() {
|
|
1285
|
+
if (!this.running || this.ticker !== null) return;
|
|
1286
|
+
const timer = setTimeout(() => {
|
|
1287
|
+
this.tick();
|
|
1288
|
+
}, this.intervalForLevel());
|
|
1289
|
+
timer.unref?.();
|
|
1290
|
+
this.ticker = timer;
|
|
1291
|
+
}
|
|
1292
|
+
tick() {
|
|
1293
|
+
this.ticker = null;
|
|
1294
|
+
if (this.disposed) return;
|
|
1295
|
+
try {
|
|
1296
|
+
this.pressure();
|
|
1297
|
+
} catch {}
|
|
1298
|
+
this.armNext();
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
function createResidencyGovernor(options = {}) {
|
|
1302
|
+
return new ResidencyGovernor(options);
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
//#endregion
|
|
1306
|
+
//#region src/footprint.ts
|
|
1307
|
+
const DEFAULT_FOOTPRINT_TOP_PROCESSES = 5;
|
|
1308
|
+
function findDomain(pressure, domain) {
|
|
1309
|
+
return pressure.domains.find((entry) => entry.domain === domain);
|
|
1310
|
+
}
|
|
1311
|
+
function footprintDomain(pressure, domain, usedBytes, budgetBytes) {
|
|
1312
|
+
const entry = findDomain(pressure, domain);
|
|
1313
|
+
return {
|
|
1314
|
+
domain,
|
|
1315
|
+
usedBytes,
|
|
1316
|
+
budgetBytes,
|
|
1317
|
+
usedPct: entry?.usedPct ?? NaN,
|
|
1318
|
+
level: entry?.level ?? "healthy",
|
|
1319
|
+
sampling: entry?.sampling ?? "unavailable",
|
|
1320
|
+
...entry?.warnPct === void 0 ? {} : { warnPct: entry.warnPct },
|
|
1321
|
+
...entry?.hardPct === void 0 ? {} : { hardPct: entry.hardPct }
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
function buildResidencyFootprint(pressure, topProcesses = 5, sessionLedger = []) {
|
|
1325
|
+
const sample = pressure.sample;
|
|
1326
|
+
const processTreeBudget = pressure.subprocess !== void 0 && pressure.subprocess.totalRssBytes > 0 ? deriveProcessTreeBudget(pressure) : 0;
|
|
1327
|
+
const domains = [
|
|
1328
|
+
footprintDomain(pressure, "heap", sample.heapUsedBytes, sample.heapLimitBytes),
|
|
1329
|
+
footprintDomain(pressure, "system", sample.rssBytes, sample.systemTotalBytes ?? 0),
|
|
1330
|
+
footprintDomain(pressure, "processTree", pressure.subprocess?.totalRssBytes ?? 0, processTreeBudget)
|
|
1331
|
+
];
|
|
1332
|
+
const processes = [...pressure.subprocess?.processes ?? []];
|
|
1333
|
+
processes.sort((a, b) => b.rssBytes - a.rssBytes);
|
|
1334
|
+
const keep = Math.max(0, Math.trunc(topProcesses));
|
|
1335
|
+
const budget = processTreeBudget > 0 ? processTreeBudget : 1;
|
|
1336
|
+
const top = processes.slice(0, keep).map((entry) => ({
|
|
1337
|
+
pid: entry.pid,
|
|
1338
|
+
command: entry.command,
|
|
1339
|
+
rssBytes: entry.rssBytes,
|
|
1340
|
+
pctOfBudget: entry.rssBytes / budget * 100
|
|
1341
|
+
}));
|
|
1342
|
+
return {
|
|
1343
|
+
ts: sample.ts,
|
|
1344
|
+
level: pressure.level,
|
|
1345
|
+
domains,
|
|
1346
|
+
topProcesses: top,
|
|
1347
|
+
ledger: [...buildLedger(pressure), ...sessionLedger]
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
function buildLedger(pressure) {
|
|
1351
|
+
const sample = pressure.sample;
|
|
1352
|
+
const processes = pressure.subprocess?.processes ?? [];
|
|
1353
|
+
const supervisor = processes.find((entry) => entry.role === "registered");
|
|
1354
|
+
const supervisorBytes = supervisor?.rssBytes ?? 0;
|
|
1355
|
+
const childrenBytes = processes.filter((entry) => entry.role !== "registered").reduce((sum, entry) => sum + entry.rssBytes, 0);
|
|
1356
|
+
const processTotal = sample.rssBytes + supervisorBytes + childrenBytes;
|
|
1357
|
+
const share = (bytes) => processTotal > 0 ? bytes / processTotal * 100 : void 0;
|
|
1358
|
+
const entries = [{
|
|
1359
|
+
key: "self",
|
|
1360
|
+
kind: "process",
|
|
1361
|
+
bytes: sample.rssBytes,
|
|
1362
|
+
...share(sample.rssBytes) === void 0 ? {} : { sharePct: share(sample.rssBytes) }
|
|
1363
|
+
}];
|
|
1364
|
+
if (supervisor !== void 0) entries.push({
|
|
1365
|
+
key: "supervisor",
|
|
1366
|
+
kind: "process",
|
|
1367
|
+
bytes: supervisor.rssBytes,
|
|
1368
|
+
...share(supervisor.rssBytes) === void 0 ? {} : { sharePct: share(supervisor.rssBytes) }
|
|
1369
|
+
});
|
|
1370
|
+
entries.push({
|
|
1371
|
+
key: "children",
|
|
1372
|
+
kind: "process",
|
|
1373
|
+
bytes: childrenBytes,
|
|
1374
|
+
...share(childrenBytes) === void 0 ? {} : { sharePct: share(childrenBytes) }
|
|
1375
|
+
});
|
|
1376
|
+
entries.push({
|
|
1377
|
+
key: "jsHeap",
|
|
1378
|
+
kind: "memory",
|
|
1379
|
+
bytes: sample.heapUsedBytes
|
|
1380
|
+
}, {
|
|
1381
|
+
key: "external",
|
|
1382
|
+
kind: "memory",
|
|
1383
|
+
bytes: sample.externalBytes
|
|
1384
|
+
});
|
|
1385
|
+
return entries;
|
|
1386
|
+
}
|
|
1387
|
+
function deriveProcessTreeBudget(pressure) {
|
|
1388
|
+
const entry = findDomain(pressure, "processTree");
|
|
1389
|
+
if (entry === void 0 || !Number.isFinite(entry.usedPct) || entry.usedPct <= 0) return 0;
|
|
1390
|
+
return (pressure.subprocess?.totalRssBytes ?? 0) / (entry.usedPct / 100);
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
//#endregion
|
|
1394
|
+
//#region src/fleet-monitor.ts
|
|
1395
|
+
const DEFAULT_FLEET_SAMPLE_INTERVAL_MS = 6e5;
|
|
1396
|
+
const DEFAULT_FLEET_MAX_PROCESSES = 8;
|
|
1397
|
+
const DEFAULT_FLEET_MAX_TOTAL_RSS_BYTES = 8 * 1024 * 1024 * 1024;
|
|
1398
|
+
function filterFleetProcesses(processes, matchPattern) {
|
|
1399
|
+
const out = [];
|
|
1400
|
+
for (const info of processes) {
|
|
1401
|
+
if (!info.command.includes(matchPattern)) continue;
|
|
1402
|
+
out.push(info);
|
|
1403
|
+
}
|
|
1404
|
+
return out;
|
|
1405
|
+
}
|
|
1406
|
+
function buildFleetSample(processes, nowMs) {
|
|
1407
|
+
let totalRssBytes = 0;
|
|
1408
|
+
let suspectedOrphanCount = 0;
|
|
1409
|
+
for (const info of processes) {
|
|
1410
|
+
totalRssBytes += info.rssBytes;
|
|
1411
|
+
if (info.ppid === 1 && info.command.length > 0) suspectedOrphanCount += 1;
|
|
1412
|
+
}
|
|
1413
|
+
return {
|
|
1414
|
+
processCount: processes.length,
|
|
1415
|
+
totalRssBytes,
|
|
1416
|
+
suspectedOrphanCount,
|
|
1417
|
+
ts: nowMs
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
var FleetMonitor = class {
|
|
1421
|
+
matchPattern;
|
|
1422
|
+
sampleIntervalMs;
|
|
1423
|
+
maxProcesses;
|
|
1424
|
+
maxTotalRssBytes;
|
|
1425
|
+
now;
|
|
1426
|
+
listProcesses;
|
|
1427
|
+
onSample;
|
|
1428
|
+
onBudgetExceeded;
|
|
1429
|
+
onObserverError;
|
|
1430
|
+
ticker = null;
|
|
1431
|
+
disposed = false;
|
|
1432
|
+
budgetExceededNotified = false;
|
|
1433
|
+
constructor(options = {}) {
|
|
1434
|
+
this.matchPattern = options.matchPattern ?? "bin/otto";
|
|
1435
|
+
this.sampleIntervalMs = options.sampleIntervalMs ?? 6e5;
|
|
1436
|
+
this.maxProcesses = options.maxProcesses ?? 8;
|
|
1437
|
+
this.maxTotalRssBytes = options.maxTotalRssBytes ?? 8589934592;
|
|
1438
|
+
this.now = options.now ?? (() => Date.now());
|
|
1439
|
+
this.listProcesses = options.listProcesses ?? defaultListFleetProcesses;
|
|
1440
|
+
this.onSample = options.onSample;
|
|
1441
|
+
this.onBudgetExceeded = options.onBudgetExceeded;
|
|
1442
|
+
this.onObserverError = options.onObserverError;
|
|
1443
|
+
}
|
|
1444
|
+
setCallbacks(callbacks) {
|
|
1445
|
+
if ("onSample" in callbacks) this.onSample = callbacks.onSample;
|
|
1446
|
+
if ("onBudgetExceeded" in callbacks) this.onBudgetExceeded = callbacks.onBudgetExceeded;
|
|
1447
|
+
}
|
|
1448
|
+
sample() {
|
|
1449
|
+
let listing;
|
|
1450
|
+
try {
|
|
1451
|
+
listing = this.listProcesses();
|
|
1452
|
+
} catch {
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (listing === void 0 || listing.length === 0) return void 0;
|
|
1456
|
+
const fleet = filterFleetProcesses(listing, this.matchPattern);
|
|
1457
|
+
if (fleet.length === 0) return void 0;
|
|
1458
|
+
return buildFleetSample(fleet, this.now());
|
|
1459
|
+
}
|
|
1460
|
+
tick() {
|
|
1461
|
+
if (this.disposed) return;
|
|
1462
|
+
try {
|
|
1463
|
+
this.safe(() => this.collectSample());
|
|
1464
|
+
} finally {
|
|
1465
|
+
if (!this.disposed) {
|
|
1466
|
+
this.ticker = setTimeout(() => this.tick(), this.sampleIntervalMs);
|
|
1467
|
+
this.ticker.unref?.();
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
collectSample() {
|
|
1472
|
+
const sample = this.sample();
|
|
1473
|
+
if (sample === void 0) return;
|
|
1474
|
+
this.onSample?.(sample);
|
|
1475
|
+
const overCount = sample.processCount > this.maxProcesses;
|
|
1476
|
+
const overRss = sample.totalRssBytes > this.maxTotalRssBytes;
|
|
1477
|
+
if (overCount || overRss) {
|
|
1478
|
+
if (!this.budgetExceededNotified) {
|
|
1479
|
+
this.budgetExceededNotified = true;
|
|
1480
|
+
this.onBudgetExceeded?.(sample, overCount ? "process-count" : "total-rss");
|
|
1481
|
+
}
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
this.budgetExceededNotified = false;
|
|
1485
|
+
}
|
|
1486
|
+
safe(callback) {
|
|
1487
|
+
try {
|
|
1488
|
+
callback();
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
try {
|
|
1491
|
+
this.onObserverError?.(error);
|
|
1492
|
+
} catch {}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
start() {
|
|
1496
|
+
if (this.ticker !== null || this.disposed) return;
|
|
1497
|
+
this.ticker = setTimeout(() => this.tick(), this.sampleIntervalMs);
|
|
1498
|
+
this.ticker.unref?.();
|
|
1499
|
+
}
|
|
1500
|
+
get running() {
|
|
1501
|
+
return this.ticker !== null;
|
|
1502
|
+
}
|
|
1503
|
+
stop() {
|
|
1504
|
+
if (this.ticker !== null) {
|
|
1505
|
+
clearTimeout(this.ticker);
|
|
1506
|
+
this.ticker = null;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
dispose() {
|
|
1510
|
+
this.disposed = true;
|
|
1511
|
+
this.stop();
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
function defaultListFleetProcesses() {
|
|
1515
|
+
try {
|
|
1516
|
+
return defaultListProcesses(Date.now);
|
|
1517
|
+
} catch {
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
//#endregion
|
|
1523
|
+
//#region src/session-ledger.ts
|
|
1524
|
+
const DEFAULT_SESSION_LEDGER_LIMIT = 5;
|
|
1525
|
+
function buildSessionLedger(candidates, budgetBytes, limit = 5) {
|
|
1526
|
+
return candidates.map((candidate) => ({
|
|
1527
|
+
candidate,
|
|
1528
|
+
bytes: candidate.surfaceBytes ?? 0
|
|
1529
|
+
})).filter((entry) => entry.bytes > 0).sort((left, right) => right.bytes - left.bytes).slice(0, Math.max(0, limit)).map(({ candidate, bytes }) => {
|
|
1530
|
+
if (budgetBytes <= 0) return {
|
|
1531
|
+
key: "session",
|
|
1532
|
+
kind: "session",
|
|
1533
|
+
id: candidate.sessionId,
|
|
1534
|
+
bytes
|
|
1535
|
+
};
|
|
1536
|
+
const budgetPct = bytes / budgetBytes * 100;
|
|
1537
|
+
return {
|
|
1538
|
+
key: "session",
|
|
1539
|
+
kind: "session",
|
|
1540
|
+
id: candidate.sessionId,
|
|
1541
|
+
bytes,
|
|
1542
|
+
budgetBytes,
|
|
1543
|
+
budgetPct,
|
|
1544
|
+
overBudget: budgetPct > 100
|
|
1545
|
+
};
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
//#endregion
|
|
1550
|
+
//#region src/load-window-trims.ts
|
|
1551
|
+
function scheduleLoadWindowTrims(input) {
|
|
1552
|
+
const scheduled = [];
|
|
1553
|
+
for (const candidate of input.candidates) {
|
|
1554
|
+
const sessionId = candidate.sessionId;
|
|
1555
|
+
if (input.inFlight.has(sessionId) || input.isBusy?.(sessionId) === true) continue;
|
|
1556
|
+
const dropped = input.retain(sessionId, input.loadWindowBytes);
|
|
1557
|
+
if (dropped === void 0 || dropped <= 0) continue;
|
|
1558
|
+
input.inFlight.add(sessionId);
|
|
1559
|
+
scheduled.push(sessionId);
|
|
1560
|
+
const release = () => {
|
|
1561
|
+
input.inFlight.delete(sessionId);
|
|
1562
|
+
};
|
|
1563
|
+
input.trim(sessionId).then(release, (error) => {
|
|
1564
|
+
release();
|
|
1565
|
+
input.onError?.(error);
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
return scheduled;
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
//#endregion
|
|
1572
|
+
//#region src/host.ts
|
|
1573
|
+
const RESIDENCY_DISABLED_ENV = "OTTO_RESIDENCY_DISABLED";
|
|
1574
|
+
function messageOf(error) {
|
|
1575
|
+
return error instanceof Error ? error.message : String(error);
|
|
1576
|
+
}
|
|
1577
|
+
function residencyEnabledFromEnv(env) {
|
|
1578
|
+
return env?.get(RESIDENCY_DISABLED_ENV) !== "1";
|
|
1579
|
+
}
|
|
1580
|
+
function processTreeSamplingReason(pressure) {
|
|
1581
|
+
const entry = pressure.domains.find((domain) => domain.domain === "processTree");
|
|
1582
|
+
if (entry === void 0) return "process-tree-domain-missing";
|
|
1583
|
+
if (entry.sampling === "ok") return void 0;
|
|
1584
|
+
return "process-tree-sampling-unavailable";
|
|
1585
|
+
}
|
|
1586
|
+
function domainReport(domain) {
|
|
1587
|
+
const pct = Number.isFinite(domain.usedPct) ? `${domain.usedPct.toFixed(1)}%` : "n/a";
|
|
1588
|
+
return `${domain.domain}=${domain.level}/${pct}`;
|
|
1589
|
+
}
|
|
1590
|
+
function pressureDiagnosticMessage(pressure, thresholds) {
|
|
1591
|
+
const domains = pressure.domains.map(domainReport).join(", ");
|
|
1592
|
+
return `residency pressure level=${pressure.level} divisor=${pressure.budgetDivisor} (${domains}) derived keepLast=${thresholds.surfaceKeepLast} keepBytes=${thresholds.surfaceKeepBytes} idleEvictMs=${thresholds.idleEvictMs}`;
|
|
1593
|
+
}
|
|
1594
|
+
function createResidencyHost(options) {
|
|
1595
|
+
const enabled = options.enabled ?? residencyEnabledFromEnv(options.env);
|
|
1596
|
+
const now = options.ports.clock.now;
|
|
1597
|
+
const processOwners = options.processOwners ?? createResourceOwnerRegistry({ now });
|
|
1598
|
+
const trace = createResidencyTrace({ ...options.traceCapacity === void 0 ? {} : { capacity: options.traceCapacity } });
|
|
1599
|
+
let managerAccessor;
|
|
1600
|
+
let memoryReportersAccessor;
|
|
1601
|
+
let diagnose = options.onDiagnostic;
|
|
1602
|
+
let cachedManager;
|
|
1603
|
+
let cachedPorts;
|
|
1604
|
+
let status = "stopped";
|
|
1605
|
+
let ticks = 0;
|
|
1606
|
+
let decisions = 0;
|
|
1607
|
+
let lastError;
|
|
1608
|
+
let lastPressure;
|
|
1609
|
+
let lastDiagnosedLevel;
|
|
1610
|
+
let lastTick;
|
|
1611
|
+
let lastReport;
|
|
1612
|
+
let budgetAccessor;
|
|
1613
|
+
let tickCandidates;
|
|
1614
|
+
let lastSessionLedger = [];
|
|
1615
|
+
const fitAborts = /* @__PURE__ */ new Map();
|
|
1616
|
+
const loadWindowTrimsInFlight = /* @__PURE__ */ new Set();
|
|
1617
|
+
function portsOf() {
|
|
1618
|
+
let manager;
|
|
1619
|
+
try {
|
|
1620
|
+
manager = managerAccessor?.();
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
lastError = messageOf(error);
|
|
1623
|
+
return;
|
|
1624
|
+
}
|
|
1625
|
+
if (manager === void 0 || manager === null) return void 0;
|
|
1626
|
+
if (manager === cachedManager) return cachedPorts;
|
|
1627
|
+
cachedManager = manager;
|
|
1628
|
+
cachedPorts = isSessionResidencyManager(manager) ? createSessionResidencyPorts(manager) : void 0;
|
|
1629
|
+
return cachedPorts;
|
|
1630
|
+
}
|
|
1631
|
+
function reportSurfaceDiagnostic(sessionId, code, message) {
|
|
1632
|
+
try {
|
|
1633
|
+
diagnose?.({
|
|
1634
|
+
source: "persistence",
|
|
1635
|
+
severity: "warning",
|
|
1636
|
+
sessionId,
|
|
1637
|
+
code,
|
|
1638
|
+
message
|
|
1639
|
+
});
|
|
1640
|
+
} catch (error) {
|
|
1641
|
+
lastError = messageOf(error);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
async function fitSurface(sessionId, target) {
|
|
1645
|
+
if (portsOf() === void 0) return {
|
|
1646
|
+
kind: "failed",
|
|
1647
|
+
cause: "no-progress"
|
|
1648
|
+
};
|
|
1649
|
+
const budget = budgetAccessor?.();
|
|
1650
|
+
if (budget === void 0) {
|
|
1651
|
+
reportSurfaceDiagnostic(sessionId, "SESSION_SURFACE_SHRINK_UNAVAILABLE", `session surface shrink requested but no context budget is attached${target.dimension === "bytes" ? ` (keepBytes ${target.keepBytes})` : ` (keepLast ${target.keepLast})`}: residency only requests fitting; message deletion is owned by memory`);
|
|
1652
|
+
return {
|
|
1653
|
+
kind: "failed",
|
|
1654
|
+
cause: "no-progress"
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
const abort = new AbortController();
|
|
1658
|
+
fitAborts.set(sessionId, abort);
|
|
1659
|
+
try {
|
|
1660
|
+
return await budget.fit(sessionId, "residency", abort.signal, { surfaceTarget: target });
|
|
1661
|
+
} finally {
|
|
1662
|
+
if (fitAborts.get(sessionId) === abort) fitAborts.delete(sessionId);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
function abortFit(sessionId, reason) {
|
|
1666
|
+
fitAborts.get(sessionId)?.abort(reason);
|
|
1667
|
+
fitAborts.delete(sessionId);
|
|
1668
|
+
}
|
|
1669
|
+
const evictWithCleanup = async (sessionId) => {
|
|
1670
|
+
const ports = portsOf();
|
|
1671
|
+
if (ports === void 0) return false;
|
|
1672
|
+
const applied = await ports.evictSession(sessionId);
|
|
1673
|
+
if (applied) {
|
|
1674
|
+
abortFit(sessionId, "evicted");
|
|
1675
|
+
budgetAccessor?.()?.forget(sessionId);
|
|
1676
|
+
options.cleanupSpillOf?.(sessionId);
|
|
1677
|
+
}
|
|
1678
|
+
return applied;
|
|
1679
|
+
};
|
|
1680
|
+
const coordinator = createResidencyActionCoordinator({
|
|
1681
|
+
owners: processOwners,
|
|
1682
|
+
ports: {
|
|
1683
|
+
listResidencyCandidates: () => portsOf()?.listResidencyCandidates() ?? [],
|
|
1684
|
+
...options.isBusy === void 0 ? {} : { isBusy: options.isBusy },
|
|
1685
|
+
evictSession: evictWithCleanup,
|
|
1686
|
+
fitSurface
|
|
1687
|
+
},
|
|
1688
|
+
now,
|
|
1689
|
+
enabled,
|
|
1690
|
+
...options.env === void 0 ? {} : { env: options.env },
|
|
1691
|
+
...options.minLevel === void 0 ? {} : { minLevel: options.minLevel },
|
|
1692
|
+
...options.baseIdleEvictMs === void 0 ? {} : { baseIdleEvictMs: options.baseIdleEvictMs },
|
|
1693
|
+
...options.baseSurfaceKeepLast === void 0 ? {} : { baseSurfaceKeepLast: options.baseSurfaceKeepLast },
|
|
1694
|
+
...options.baseSurfaceKeepBytes === void 0 ? {} : { baseSurfaceKeepBytes: options.baseSurfaceKeepBytes },
|
|
1695
|
+
onReport: (report) => {
|
|
1696
|
+
decisions += 1;
|
|
1697
|
+
lastReport = report;
|
|
1698
|
+
try {
|
|
1699
|
+
trace.attachReport(report);
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
lastError = messageOf(error);
|
|
1702
|
+
}
|
|
1703
|
+
try {
|
|
1704
|
+
options.onReport?.(report);
|
|
1705
|
+
} catch (error) {
|
|
1706
|
+
lastError = messageOf(error);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
});
|
|
1710
|
+
function emitPressureDiagnostic(pressure) {
|
|
1711
|
+
if (diagnose === void 0 || lastDiagnosedLevel === pressure.level) return;
|
|
1712
|
+
lastDiagnosedLevel = pressure.level;
|
|
1713
|
+
const thresholds = resolveActionThresholds(pressure, {
|
|
1714
|
+
...options.baseSurfaceKeepLast === void 0 ? {} : { baseSurfaceKeepLast: options.baseSurfaceKeepLast },
|
|
1715
|
+
...options.baseSurfaceKeepBytes === void 0 ? {} : { baseSurfaceKeepBytes: options.baseSurfaceKeepBytes },
|
|
1716
|
+
...options.env === void 0 ? {} : { env: options.env }
|
|
1717
|
+
});
|
|
1718
|
+
diagnose({
|
|
1719
|
+
source: "residency",
|
|
1720
|
+
severity: pressure.level === "healthy" ? "info" : "warning",
|
|
1721
|
+
code: "RESIDENCY_PRESSURE",
|
|
1722
|
+
message: pressureDiagnosticMessage(pressure, thresholds),
|
|
1723
|
+
detail: {
|
|
1724
|
+
level: pressure.level,
|
|
1725
|
+
budgetDivisor: pressure.budgetDivisor,
|
|
1726
|
+
keepLast: thresholds.surfaceKeepLast,
|
|
1727
|
+
keepBytes: thresholds.surfaceKeepBytes
|
|
1728
|
+
}
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
function onPressure(pressure) {
|
|
1732
|
+
const measureCount = performance.getEntriesByType("measure").length;
|
|
1733
|
+
if (measureCount > 5e4) {
|
|
1734
|
+
performance.clearMeasures();
|
|
1735
|
+
performance.clearMarks();
|
|
1736
|
+
console.warn(`[residency] user-timing buffer exceeded guard threshold (${measureCount} entries) — cleared`);
|
|
1737
|
+
}
|
|
1738
|
+
try {
|
|
1739
|
+
const record = trace.record(pressure, suggestFromPressure(pressure, now(), processTreeSamplingReason(pressure)));
|
|
1740
|
+
ticks += 1;
|
|
1741
|
+
lastTick = record;
|
|
1742
|
+
lastPressure = pressure;
|
|
1743
|
+
options.onTick?.(record);
|
|
1744
|
+
} catch (error) {
|
|
1745
|
+
lastError = messageOf(error);
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
emitPressureDiagnostic(pressure);
|
|
1749
|
+
try {
|
|
1750
|
+
coordinator.onSample(pressure, tickCandidates);
|
|
1751
|
+
} catch (error) {
|
|
1752
|
+
lastError = messageOf(error);
|
|
1753
|
+
}
|
|
1754
|
+
try {
|
|
1755
|
+
const thresholds = resolveActionThresholds(pressure, {
|
|
1756
|
+
...options.baseSurfaceKeepLast === void 0 ? {} : { baseSurfaceKeepLast: options.baseSurfaceKeepLast },
|
|
1757
|
+
...options.baseSurfaceKeepBytes === void 0 ? {} : { baseSurfaceKeepBytes: options.baseSurfaceKeepBytes },
|
|
1758
|
+
...options.env === void 0 ? {} : { env: options.env }
|
|
1759
|
+
});
|
|
1760
|
+
const loadWindowBytes = options.loadWindowBytes?.();
|
|
1761
|
+
const trim = options.trimLoadWindow;
|
|
1762
|
+
if (loadWindowBytes !== void 0 && trim !== void 0) {
|
|
1763
|
+
const sessions = portsOf();
|
|
1764
|
+
scheduleLoadWindowTrims({
|
|
1765
|
+
candidates: tickCandidates ?? [],
|
|
1766
|
+
loadWindowBytes,
|
|
1767
|
+
inFlight: loadWindowTrimsInFlight,
|
|
1768
|
+
retain: (sessionId, keepBytes) => sessions?.retainOnlyLatestWindow?.(sessionId, keepBytes),
|
|
1769
|
+
trim,
|
|
1770
|
+
...options.isBusy === void 0 ? {} : { isBusy: options.isBusy },
|
|
1771
|
+
onError: (error) => {
|
|
1772
|
+
lastError = messageOf(error);
|
|
1773
|
+
}
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
const sessionEntries = buildSessionLedger(tickCandidates ?? [], thresholds.surfaceKeepBytes);
|
|
1777
|
+
const memoryEntries = [...memoryReportersAccessor?.() ?? /* @__PURE__ */ new Map()].map(([key, reporter]) => ({
|
|
1778
|
+
key,
|
|
1779
|
+
kind: "memory",
|
|
1780
|
+
bytes: reporter.bytes()
|
|
1781
|
+
}));
|
|
1782
|
+
const jobsBytes = options.jobsOutputBytes?.() ?? 0;
|
|
1783
|
+
lastSessionLedger = [
|
|
1784
|
+
...sessionEntries,
|
|
1785
|
+
...memoryEntries.filter((entry) => entry.bytes > 0),
|
|
1786
|
+
...jobsBytes > 0 ? [{
|
|
1787
|
+
key: "jobsOutput",
|
|
1788
|
+
kind: "memory",
|
|
1789
|
+
bytes: jobsBytes
|
|
1790
|
+
}] : []
|
|
1791
|
+
];
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
lastError = messageOf(error);
|
|
1794
|
+
}
|
|
1795
|
+
tickCandidates = void 0;
|
|
1796
|
+
}
|
|
1797
|
+
const governorEnv = options.governorOptions?.env ?? (options.env !== void 0 ? { env: options.env } : {});
|
|
1798
|
+
const sampleTokensFromPorts = () => {
|
|
1799
|
+
const candidates = portsOf()?.listResidencyCandidates() ?? [];
|
|
1800
|
+
tickCandidates = candidates;
|
|
1801
|
+
let totalTokens = 0;
|
|
1802
|
+
for (const candidate of candidates) {
|
|
1803
|
+
const tokens = candidate.surfaceTokens ?? 0;
|
|
1804
|
+
if (tokens > totalTokens) totalTokens = tokens;
|
|
1805
|
+
}
|
|
1806
|
+
const contextWindow = options.contextWindowTokens?.() ?? 0;
|
|
1807
|
+
if (contextWindow <= 0) throw new Error("residency: context window unavailable");
|
|
1808
|
+
return {
|
|
1809
|
+
totalTokens,
|
|
1810
|
+
contextWindow
|
|
1811
|
+
};
|
|
1812
|
+
};
|
|
1813
|
+
const governor = createResidencyGovernor({
|
|
1814
|
+
...options.governorOptions,
|
|
1815
|
+
...governorEnv,
|
|
1816
|
+
sampleTokens: options.governorOptions?.sampleTokens ?? sampleTokensFromPorts,
|
|
1817
|
+
now,
|
|
1818
|
+
onSample: onPressure
|
|
1819
|
+
});
|
|
1820
|
+
async function sample() {
|
|
1821
|
+
if (!enabled) return lastTick;
|
|
1822
|
+
try {
|
|
1823
|
+
governor.pressure();
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
lastError = messageOf(error);
|
|
1826
|
+
}
|
|
1827
|
+
await coordinator.settled();
|
|
1828
|
+
return lastTick;
|
|
1829
|
+
}
|
|
1830
|
+
const fleetMonitor = options.fleet?.enabled === true ? new FleetMonitor({
|
|
1831
|
+
onBudgetExceeded: (sample) => {
|
|
1832
|
+
options.fleet?.onBudgetExceeded?.(sample.processCount, sample.totalRssBytes);
|
|
1833
|
+
},
|
|
1834
|
+
onObserverError: (error) => {
|
|
1835
|
+
diagnose?.({
|
|
1836
|
+
source: "persistence",
|
|
1837
|
+
severity: "warning",
|
|
1838
|
+
code: "RESIDENCY_FLEET_OBSERVER_ERROR",
|
|
1839
|
+
message: messageOf(error)
|
|
1840
|
+
});
|
|
1841
|
+
}
|
|
1842
|
+
}) : void 0;
|
|
1843
|
+
let supervisorRelease;
|
|
1844
|
+
function start() {
|
|
1845
|
+
if (status === "running") return;
|
|
1846
|
+
status = "running";
|
|
1847
|
+
if (!enabled) return;
|
|
1848
|
+
if (supervisorRelease === void 0 && options.supervisorPid !== void 0) supervisorRelease = governor.registerSubprocess(options.supervisorPid, "supervisor");
|
|
1849
|
+
governor.start();
|
|
1850
|
+
coordinator.start();
|
|
1851
|
+
fleetMonitor?.start();
|
|
1852
|
+
}
|
|
1853
|
+
async function stop() {
|
|
1854
|
+
if (status === "stopped") return;
|
|
1855
|
+
status = "draining";
|
|
1856
|
+
for (const sessionId of [...fitAborts.keys()]) abortFit(sessionId, "stopped");
|
|
1857
|
+
try {
|
|
1858
|
+
governor.stop();
|
|
1859
|
+
} catch (error) {
|
|
1860
|
+
lastError = messageOf(error);
|
|
1861
|
+
}
|
|
1862
|
+
supervisorRelease?.();
|
|
1863
|
+
supervisorRelease = void 0;
|
|
1864
|
+
fleetMonitor?.stop();
|
|
1865
|
+
try {
|
|
1866
|
+
await coordinator.stop();
|
|
1867
|
+
} catch (error) {
|
|
1868
|
+
lastError = messageOf(error);
|
|
1869
|
+
}
|
|
1870
|
+
status = "stopped";
|
|
1871
|
+
}
|
|
1872
|
+
const component = (ctx) => {
|
|
1873
|
+
const sessions = ctx.consume(SLOTS.sessions);
|
|
1874
|
+
const hooks = ctx.maybe(SLOTS.hooks);
|
|
1875
|
+
const budget = ctx.maybe(SLOTS.contextBudget);
|
|
1876
|
+
const memoryReporters = ctx.consumeAll(SLOTS.residencyMemoryReporters);
|
|
1877
|
+
managerAccessor = () => sessions();
|
|
1878
|
+
memoryReportersAccessor = () => memoryReporters();
|
|
1879
|
+
budgetAccessor = () => budget();
|
|
1880
|
+
diagnose = (input) => {
|
|
1881
|
+
const sink = options.onDiagnostic;
|
|
1882
|
+
if (sink !== void 0) {
|
|
1883
|
+
sink(input);
|
|
1884
|
+
return;
|
|
1885
|
+
}
|
|
1886
|
+
hooks()?.emitAndWait(TIMINGS.runtimeDiagnostic, input).catch(() => void 0);
|
|
1887
|
+
};
|
|
1888
|
+
ctx.effect(() => {
|
|
1889
|
+
start();
|
|
1890
|
+
return async () => {
|
|
1891
|
+
await stop();
|
|
1892
|
+
managerAccessor = void 0;
|
|
1893
|
+
budgetAccessor = void 0;
|
|
1894
|
+
diagnose = void 0;
|
|
1895
|
+
lastDiagnosedLevel = void 0;
|
|
1896
|
+
cachedManager = void 0;
|
|
1897
|
+
cachedPorts = void 0;
|
|
1898
|
+
};
|
|
1899
|
+
});
|
|
1900
|
+
};
|
|
1901
|
+
return {
|
|
1902
|
+
component,
|
|
1903
|
+
trace,
|
|
1904
|
+
processOwners,
|
|
1905
|
+
start,
|
|
1906
|
+
stop,
|
|
1907
|
+
sample,
|
|
1908
|
+
diagnostics() {
|
|
1909
|
+
return {
|
|
1910
|
+
enabled,
|
|
1911
|
+
running: status === "running",
|
|
1912
|
+
status,
|
|
1913
|
+
portsAttached: cachedPorts !== void 0,
|
|
1914
|
+
...fleetMonitor === void 0 ? {} : { fleetRunning: fleetMonitor.running },
|
|
1915
|
+
ticks,
|
|
1916
|
+
decisions,
|
|
1917
|
+
traceSize: trace.size(),
|
|
1918
|
+
...lastError === void 0 ? {} : { lastError },
|
|
1919
|
+
...lastPressure === void 0 ? {} : { lastPressure },
|
|
1920
|
+
...lastTick === void 0 ? {} : { lastTick },
|
|
1921
|
+
...lastReport === void 0 ? {} : { lastReport }
|
|
1922
|
+
};
|
|
1923
|
+
},
|
|
1924
|
+
lastPressure() {
|
|
1925
|
+
return lastPressure;
|
|
1926
|
+
},
|
|
1927
|
+
lastReport() {
|
|
1928
|
+
return lastReport;
|
|
1929
|
+
},
|
|
1930
|
+
evictSession: evictWithCleanup,
|
|
1931
|
+
footprint() {
|
|
1932
|
+
if (lastPressure === void 0) return void 0;
|
|
1933
|
+
return buildResidencyFootprint(lastPressure, void 0, lastSessionLedger);
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
//#endregion
|
|
1939
|
+
//#region src/family.ts
|
|
1940
|
+
const ResidencyHost = defineComponent("ResidencyHost", (ctx, options) => {
|
|
1941
|
+
const { cell, ...hostOptions } = options;
|
|
1942
|
+
const processOwners = cell.host?.processOwners ?? hostOptions.processOwners;
|
|
1943
|
+
const host = createResidencyHost({
|
|
1944
|
+
...hostOptions,
|
|
1945
|
+
...processOwners === void 0 ? {} : { processOwners }
|
|
1946
|
+
});
|
|
1947
|
+
cell.host = host;
|
|
1948
|
+
ctx.provide(SLOTS.residencyHost, () => host);
|
|
1949
|
+
ctx.mount(host.component);
|
|
1950
|
+
});
|
|
1951
|
+
|
|
1952
|
+
//#endregion
|
|
1953
|
+
export { DEFAULT_ACTION_DOMAINS as $, DEFAULT_SUBPROCESS_WEIGHT as A, attributionOf as B, parseEtimeSeconds as C, DEFAULT_HARD_THRESHOLD_PCT as D, DEFAULT_CRITICAL_INTERVAL_MS as E, DEFAULT_WARN_COOLDOWN_MS as F, createResourceOwnerRegistry as G, suggestionForDomain as H, DEFAULT_WARN_THRESHOLD_PCT as I, DEFAULT_MAX_RELEASES_PER_PASS as J, DEFAULT_MAX_BOUND_SURFACES_PER_PASS as K, resolveResidencyThresholds as L, DEFAULT_SYSTEM_WARN_FLOOR_BYTES as M, DEFAULT_SYSTEM_WARN_THRESHOLD_PCT as N, DEFAULT_PROCESS_TREE_BUDGET_BYTES as O, DEFAULT_WARNING_INTERVAL_MS as P, createResidencyActionCoordinator as Q, systemThresholdPcts as R, createSubprocessProbe as S, readHeapSample as T, DEFAULT_RESIDENCY_TRACE_CAPACITY as U, suggestFromPressure as V, createResidencyTrace as W, RELEASE_RESOURCE_REASON as X, DEFAULT_RELEASE_DOMAINS as Y, ResidencyActionCoordinator as Z, buildResidencyFootprint as _, pctOf as _t, RESIDENCY_DISABLED_ENV as a, resolveActionThresholds as at, DEFAULT_MIN_SUBPROCESS_LIFETIME_MS as b, tokenDomainLevel as bt, processTreeSamplingReason as c, triggeredDomainsOf as ct, DEFAULT_FLEET_MAX_TOTAL_RSS_BYTES as d, LEVEL_DIVISOR as dt, DEFAULT_ACTION_MIN_LEVEL as et, DEFAULT_FLEET_SAMPLE_INTERVAL_MS as f, aggregateLevel as ft, DEFAULT_FOOTPRINT_TOP_PROCESSES as g, okDomain as gt, filterFleetProcesses as h, heapDomainLevel as ht, ResidencyHost as i, atLeastLevel as it, DEFAULT_SYSTEM_HARD_THRESHOLD_PCT as j, DEFAULT_SAMPLE_INTERVAL_MS as k, residencyEnabledFromEnv as l, OBSERVATION_ONLY_DOMAINS as lt, buildFleetSample as m, gradeByPct as mt, decideShrink as n, DEFAULT_BASE_SURFACE_KEEP_BYTES as nt, createResidencyHost as o, selectResidencyActions as ot, FleetMonitor as p, divisorFor as pt, DEFAULT_MAX_EVICTIONS_PER_PASS as q, effectiveMinGrowth as r, DEFAULT_BASE_SURFACE_KEEP_LAST as rt, pressureDiagnosticMessage as s, tightenThreshold as st, DEFAULT_SHRINK_POLICY as t, DEFAULT_BASE_IDLE_EVICT_MS as tt, DEFAULT_FLEET_MAX_PROCESSES as u, isObservationOnlyDomain as ut, ResidencyGovernor as v, processTreeDomainLevel as vt, parseProcessList as w, DEFAULT_PID_REUSE_TOLERANCE_MS as x, unavailableDomain as xt, createResidencyGovernor as y, systemDomainLevel as yt, SHADOW_MIN_LEVEL as z };
|