mastra-ai/mastra · error

${this.latestError}

Error message

${this.latestError}

What it means

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.

Source

Thrown at mastracode/sdk/src/process-memory-diagnostics.ts:590

    return result;
  }

  private async captureEpoch(
    reason: ProcessMemoryDiagnosticsCapture['reason'],
    final: boolean,
  ): Promise<ProcessMemoryDiagnosticsCapture> {
    if (!this.inspector || !this.samplingActive || !this.outputDirectory) {
      throw new Error(this.latestError ?? 'Allocation sampling is not active.');
    }

    let response: Record<string, unknown>;
    try {
      response = await this.inspector.post('HeapProfiler.stopSampling');
      this.samplingActive = false;
    } catch (error) {
      this.latestError = `Allocation capture failed: ${errorMessage(error)}`;
      if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();
      throw new Error(this.latestError, { cause: error });
    }

    const profile = response.profile;
    if (!profile || typeof profile !== 'object') {
      this.latestError = 'Allocation capture failed: inspector returned no profile.';
      if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();
      throw new Error(this.latestError);
    }

    const sequence = this.captureCount + 1;
    const timestamp = this.now().toISOString();
    const filename = `allocation-${String(sequence).padStart(6, '0')}-${safeTimestamp(new Date(timestamp))}.heapprofile`;
    const finalPath = join(this.outputDirectory, filename);
    const temporaryPath = join(this.outputDirectory, `.${filename}.${this.randomId()}.tmp`);

    try {
      await writeFile(temporaryPath, `${JSON.stringify(profile)}\n`, { flag: 'wx', mode: 0o600 });
      await chmod(temporaryPath, 0o600);

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Inspect error.cause for the underlying inspector failure and fix that (reconnect session, update Node).
  2. Check getStatus().state — after this failure the instance attempts restartSamplingAfterFailure; if it lands in 'error', restart diagnostics with a fresh start().
  3. Ensure no external debugger is attached to or disconnecting the same inspector session.
  4. Update to a recent Node.js LTS; older versions had HeapProfiler stability issues.
  5. Reduce capture frequency if captures are timing out under load.

Example fix

// before
try {
  await diagnostics.capture('manual');
} catch (e) { /* opaque */ }
// after
try {
  await diagnostics.capture('manual');
} catch (e) {
  console.error('capture failed:', e.message, 'cause:', e.cause);
  if ((await diagnostics.getStatus()).state === 'error') await restartDiagnostics();
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Heuristic pre-check: inspector domains are unavailable in restricted runtimes.
if (typeof process === 'undefined' || !process.features?.inspector) {
  throw new Error('Inspector unavailable; memory diagnostics not supported in this runtime.');
}

Type guard

function isCaptureErrorWithCause(e: unknown): e is Error & { cause: unknown } {
  return e instanceof Error && 'cause' in e;
}

Try / catch

try {
  await diagnostics.capture('manual');
} catch (e) {
  const cause = isCaptureErrorWithCause(e) ? e.cause : undefined;
  logger.error('allocation capture failed', { cause });
  const s = await diagnostics.getStatus();
  if (s.state === 'error') await restartDiagnostics();
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/491f290f0a4d28a9. Report an issue: GitHub.