{"record":{"id":"491f290f0a4d28a9","repo":"mastra-ai/mastra","slug":"this-latesterror","errorCode":null,"errorMessage":"${this.latestError}","messagePattern":"\\$\\{this\\.latestError\\}","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/process-memory-diagnostics.ts","lineNumber":590,"sourceCode":"    return result;\n  }\n\n  private async captureEpoch(\n    reason: ProcessMemoryDiagnosticsCapture['reason'],\n    final: boolean,\n  ): Promise<ProcessMemoryDiagnosticsCapture> {\n    if (!this.inspector || !this.samplingActive || !this.outputDirectory) {\n      throw new Error(this.latestError ?? 'Allocation sampling is not active.');\n    }\n\n    let response: Record<string, unknown>;\n    try {\n      response = await this.inspector.post('HeapProfiler.stopSampling');\n      this.samplingActive = false;\n    } catch (error) {\n      this.latestError = `Allocation capture failed: ${errorMessage(error)}`;\n      if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();\n      throw new Error(this.latestError, { cause: error });\n    }\n\n    const profile = response.profile;\n    if (!profile || typeof profile !== 'object') {\n      this.latestError = 'Allocation capture failed: inspector returned no profile.';\n      if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();\n      throw new Error(this.latestError);\n    }\n\n    const sequence = this.captureCount + 1;\n    const timestamp = this.now().toISOString();\n    const filename = `allocation-${String(sequence).padStart(6, '0')}-${safeTimestamp(new Date(timestamp))}.heapprofile`;\n    const finalPath = join(this.outputDirectory, filename);\n    const temporaryPath = join(this.outputDirectory, `.${filename}.${this.randomId()}.tmp`);\n\n    try {\n      await writeFile(temporaryPath, `${JSON.stringify(profile)}\\n`, { flag: 'wx', mode: 0o600 });\n      await chmod(temporaryPath, 0o600);","sourceCodeStart":572,"sourceCodeEnd":608,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/process-memory-diagnostics.ts#L572-L608","documentation":"When captureEpoch() posts 'HeapProfiler.stopSampling' to the inspector session and the call rejects, the library records 'Allocation capture failed: <reason>' as latestError and rethrows it as an Error with the original attached as cause. This is the library's wrapper around CDP/inspector protocol failures during profile collection.","triggerScenarios":"this.inspector.post('HeapProfiler.stopSampling') rejects: the inspector WebSocket/session died mid-capture, the debugger disconnected, the CDP target crashed, or the protocol command errored.","commonSituations":"Node process under memory pressure killed the inspector session; another debugger (Chrome DevTools, IDE) grabbed or closed the session; long-running runs where the inspector times out; forked/worker threads whose inspector session ended; Node version quirks with HeapProfiler domain.","solutions":["Inspect error.cause for the underlying inspector failure and fix that (reconnect session, update Node).","Check getStatus().state — after this failure the instance attempts restartSamplingAfterFailure; if it lands in 'error', restart diagnostics with a fresh start().","Ensure no external debugger is attached to or disconnecting the same inspector session.","Update to a recent Node.js LTS; older versions had HeapProfiler stability issues.","Reduce capture frequency if captures are timing out under load."],"exampleFix":"// before\ntry {\n  await diagnostics.capture('manual');\n} catch (e) { /* opaque */ }\n// after\ntry {\n  await diagnostics.capture('manual');\n} catch (e) {\n  console.error('capture failed:', e.message, 'cause:', e.cause);\n  if ((await diagnostics.getStatus()).state === 'error') await restartDiagnostics();\n}","handlingStrategy":"try-catch","validationCode":"// Heuristic pre-check: inspector domains are unavailable in restricted runtimes.\nif (typeof process === 'undefined' || !process.features?.inspector) {\n  throw new Error('Inspector unavailable; memory diagnostics not supported in this runtime.');\n}","typeGuard":"function isCaptureErrorWithCause(e: unknown): e is Error & { cause: unknown } {\n  return e instanceof Error && 'cause' in e;\n}","tryCatchPattern":"try {\n  await diagnostics.capture('manual');\n} catch (e) {\n  const cause = isCaptureErrorWithCause(e) ? e.cause : undefined;\n  logger.error('allocation capture failed', { cause });\n  const s = await diagnostics.getStatus();\n  if (s.state === 'error') await restartDiagnostics();\n}","preventionTips":["Don't attach a competing debugger to the same process while diagnostics run.","Pin a supported Node.js LTS and test inspector stability on long-running processes.","Wrap periodic capture callbacks so failures restart diagnostics instead of accumulating errors.","Monitor for state === 'error' and alert/restart proactively."],"tags":["inspector","cdp","heap-profiler","network"],"backgroundTag":"inspector-session-disconnected","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}