/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @oncall memory_lab */ import {jobsActiveBetween} from './tools/jobs.js'; /** * Background jobs run in this process, and a snapshot parse or a whole-heap * scan is one synchronous block: every call that arrives meanwhile waits, * even one that reads no snapshot. The client then times the wait as the * call's own, and a 0 s lookup reads as a 104 s one. A heartbeat timer finds * those blocks so the delayed call can say what it waited for. */ const BEAT_MS = 250; /** A gap this long between beats is a block worth naming. */ const STALL_MS = 2000; /** A block that ended this recently may have held the call just read. */ const JUST_ENDED_MS = 1000; const MAX_KEPT = 16; let lastBeat = Date.now(); /** When the server last answered a call. */ let lastAnswerAt = 0; const stalls: Array<{start: number; end: number}> = []; /** * Timer heartbeats on a free loop since the last block ended. Calls sent * during the block are read in the same loop turn as the beat that closes it; * one read after a further timer beat arrived once the loop was free again. * A beat taken by a call does not count: several calls queued behind one * block are read back to back, and each was held. */ let freeBeats = 0; let timer: ReturnType | null = null; /** Calls read and not yet answered, by the id `noteCallStarted` returned. */ const inFlight = new Map(); let lastCallId = 0; function beat(now: number = Date.now(), fromTimer = false): void { if (now - lastBeat >= STALL_MS) { stalls.push({start: lastBeat, end: now}); if (stalls.length > MAX_KEPT) stalls.shift(); freeBeats = 0; } else if (fromTimer) { freeBeats++; } lastBeat = now; } /** Start the heartbeat once per process; it never keeps the process alive. */ export function startStallWatch(): void { if (timer != null) return; lastBeat = Date.now(); timer = setInterval(() => beat(Date.now(), true), BEAT_MS); timer.unref(); } /** * Called as each call is read, after `stallBefore`. A call still running when * a later one is read may have run the block itself, between two awaits. */ export function noteCallStarted( tool: string, now: number = Date.now(), ): number { const id = ++lastCallId; inFlight.set(id, {tool, startedAt: now}); return id; } /** * Called as each call is answered. A block that ended before this answer * did not hold a call sent after it. */ export function noteAnswered( now: number = Date.now(), callId: number | null = null, ): void { if (callId != null) inFlight.delete(callId); if (timer == null) return; beat(now); lastAnswerAt = now; } /** * The block the call being read now waited behind: one that ended at most a * second ago (this beat closes one still open, whose timers have not run * yet) with no answer sent and no free heartbeat since. Null when the loop * was free. */ export function stallBefore( now: number = Date.now(), ): {start: number; end: number} | null { if (timer == null) return null; const freeSince = freeBeats > 0; beat(now); const last = stalls[stalls.length - 1]; return last != null && (now === last.end || !freeSince) && now - last.end <= JUST_ENDED_MS && last.end > lastAnswerAt ? last : null; } /** * "_Waited up to ~98 s before it ran …_" when this call was held by a * background job's synchronous work, or by an earlier call still running, * or null. A stall with neither is the previous call's own work, already * answered. Either may have run the block (a job idle on I/O was alive but * did not), so both are named when both were running. The block's length is * an upper bound: the call may have been sent at any point during it, and * the server reads it only once the block ends. */ export function waitNote( stall: {start: number; end: number} | null, ): string | null { if (stall == null) return null; const held = jobsActiveBetween(stall.start, stall.end); const calls = [...inFlight.values()].filter(c => c.startedAt < stall.end); if (held.length === 0 && calls.length === 0) return null; const secs = Math.round((stall.end - stall.start) / 1000); const behind: string[] = []; if (calls.length > 0) { const tools = calls .slice(0, 3) .map(c => `\`${c.tool}\``) .join(', '); behind.push( `the earlier call${calls.length > 1 ? 's' : ''} ${tools} still running`, ); } if (held.length > 0) { const names = held .slice(0, 3) .map(j => `\`${j.id}\` (\`${j.tool}\`)`) .join(', '); behind.push(`background job${held.length > 1 ? 's' : ''} ${names}`); } const runs = calls.length === 0 ? "jobs run in this server's process" : held.length === 0 ? "calls run in this server's process" : "calls and jobs run in this server's process"; return `_Waited up to ~${secs} s before it ran (the server sees when a call runs, not when it was sent), behind ${behind.join(' or ')}: ${runs}, and a snapshot parse or heap scan holds every call until it returns, including calls that read no snapshot._`; }