Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions packages/core/src/services/memoryDiagnosticsDumper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import { MemoryDiagnosticsDumper } from './memoryDiagnosticsDumper.js';
import type { Config } from '../config/config.js';

vi.mock('node:fs', () => ({
mkdirSync: vi.fn(),
writeFileSync: vi.fn(),
}));

vi.mock('../utils/memoryDiagnostics.js', () => ({
collectMemoryDiagnostics: vi.fn().mockResolvedValue({
timestamp: '2026-05-31T00:00:00.000Z',
memoryUsage: {
rss: 2_000_000_000,
heapUsed: 1_800_000_000,
heapTotal: 2_048_000_000,
external: 50_000_000,
arrayBuffers: 10_000_000,
},
v8HeapStats: {
heapSizeLimit: 4_096_000_000,
totalHeapSize: 2_048_000_000,
usedHeapSize: 1_800_000_000,
},
}),
}));

function createMockConfig(overrides: Partial<Record<string, unknown>> = {}) {
return {
getSessionId: vi.fn().mockReturnValue('test-session-id-12345678'),
getCliVersion: vi.fn().mockReturnValue('0.17.0'),
getGeminiClient: vi.fn().mockReturnValue({
getChat: () => ({
getHistoryLength: () => 500,
}),
}),
storage: {
getProjectDir: vi.fn().mockReturnValue('/tmp/test-project'),
},
...overrides,
} as unknown as Config;
}

describe('MemoryDiagnosticsDumper', () => {
beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
vi.restoreAllMocks();
});

it('writes diagnostics JSON on first dump', async () => {
const config = createMockConfig();
const dumper = new MemoryDiagnosticsDumper(config);

const result = await dumper.dump('hard');

expect(result).toBeDefined();
expect(result!.trigger).toBe('hard');
expect(result!.filePath).toContain('/tmp/test-project/diagnostics/');
expect(result!.filePath).toContain('memory-test-ses');
expect(fs.mkdirSync).toHaveBeenCalledWith(
expect.stringContaining('diagnostics'),
{ recursive: true },
);
expect(fs.writeFileSync).toHaveBeenCalledOnce();

const writtenContent = JSON.parse(
vi.mocked(fs.writeFileSync).mock.calls[0][1] as string,
);
expect(writtenContent.trigger).toBe('hard');
expect(writtenContent.dumpNumber).toBe(1);
expect(writtenContent.memoryUsage.rss).toBe(2_000_000_000);
expect(writtenContent.session.historyEntries).toBe(500);
expect(writtenContent.suggestion).toContain('/compact');
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
});

it('respects per-session cap of 3 dumps', async () => {
const config = createMockConfig();
const dumper = new MemoryDiagnosticsDumper(config);

// Bypass cooldown by mocking Date.now
let mockNow = 1000000;
vi.spyOn(Date, 'now').mockImplementation(() => {
mockNow += 60_000;
return mockNow;
});

const r1 = await dumper.dump('hard');
const r2 = await dumper.dump('critical');
const r3 = await dumper.dump('hard');
const r4 = await dumper.dump('critical');

expect(r1).toBeDefined();
expect(r2).toBeDefined();
expect(r3).toBeDefined();
expect(r4).toBeUndefined();
expect(fs.writeFileSync).toHaveBeenCalledTimes(3);
});

it('respects cooldown between dumps', async () => {
const config = createMockConfig();
const dumper = new MemoryDiagnosticsDumper(config);

const mockNow = 1000000;
vi.spyOn(Date, 'now').mockReturnValue(mockNow);

const r1 = await dumper.dump('hard');
const r2 = await dumper.dump('hard');

expect(r1).toBeDefined();
expect(r2).toBeUndefined();
expect(fs.writeFileSync).toHaveBeenCalledTimes(1);
});

it('resets state on new session', async () => {
const config = createMockConfig();
const dumper = new MemoryDiagnosticsDumper(config);

let mockNow = 1000000;
vi.spyOn(Date, 'now').mockImplementation(() => {
mockNow += 60_000;
return mockNow;
});

await dumper.dump('hard');
await dumper.dump('hard');
await dumper.dump('hard');

// Cap reached
const r4 = await dumper.dump('hard');
expect(r4).toBeUndefined();

// Reset
dumper.resetForNewSession();

const r5 = await dumper.dump('critical');
expect(r5).toBeDefined();
expect(r5!.trigger).toBe('critical');
});

it('includes critical suggestion for critical pressure', async () => {
const config = createMockConfig();
const dumper = new MemoryDiagnosticsDumper(config);

await dumper.dump('critical');

const writtenContent = JSON.parse(
vi.mocked(fs.writeFileSync).mock.calls[0][1] as string,
);
expect(writtenContent.suggestion).toContain('critically high');
});

it('handles missing geminiClient gracefully', async () => {
const config = createMockConfig({
getGeminiClient: vi.fn().mockReturnValue(null),
});
const dumper = new MemoryDiagnosticsDumper(config);

const result = await dumper.dump('hard');

expect(result).toBeDefined();
const writtenContent = JSON.parse(
vi.mocked(fs.writeFileSync).mock.calls[0][1] as string,
);
expect(writtenContent.session.available).toBe(false);
});
});
139 changes: 139 additions & 0 deletions packages/core/src/services/memoryDiagnosticsDumper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

/**
* Writes a lightweight memory diagnostics JSON to disk when the memory
* pressure monitor detects hard or critical pressure. The file survives
* a subsequent OOM crash, giving maintainers actionable data from bug
* reports without requiring the user to manually run `/doctor memory`.
*
* Design: diagnostics JSON is written BEFORE any expensive operation
* (like heap snapshots) so it lands on disk even if the process crashes
* during the heavier step.
*/

import * as fs from 'node:fs';
import * as path from 'node:path';
import { collectMemoryDiagnostics } from '../utils/memoryDiagnostics.js';
import { createDebugLogger } from '../utils/debugLogger.js';
import { getErrorMessage } from '../utils/errors.js';
import type { Config } from '../config/config.js';

const debugLogger = createDebugLogger('MEMORY_DUMP');

/** Maximum dumps per session to avoid disk flooding. */
const MAX_DUMPS_PER_SESSION = 3;

/** Minimum interval between dumps (ms). */
const MIN_DUMP_INTERVAL_MS = 30_000;

export interface MemoryDumpResult {
filePath: string;
trigger: string;
}

export class MemoryDiagnosticsDumper {
private dumpCount = 0;
private lastDumpTime = 0;

constructor(private readonly config: Config) {}

/**
* Resets session-scoped state. Called when a new session starts.
*/
resetForNewSession(): void {
this.dumpCount = 0;
this.lastDumpTime = 0;
}

/**
* Writes a diagnostics snapshot to disk if within per-session limits.
* Returns the file path on success, or undefined if skipped/failed.
*/
async dump(
trigger: 'hard' | 'critical',
): Promise<MemoryDumpResult | undefined> {
if (this.dumpCount >= MAX_DUMPS_PER_SESSION) {
debugLogger.debug(
`Skipping dump: session cap reached (${MAX_DUMPS_PER_SESSION})`,
);
return undefined;
}

const now = Date.now();
if (now - this.lastDumpTime < MIN_DUMP_INTERVAL_MS) {
debugLogger.debug('Skipping dump: cooldown not elapsed');
return undefined;
}

try {
const diagnosticsDir = this.ensureDiagnosticsDir();
const sessionId = this.config.getSessionId();
const timestamp = new Date()
.toISOString()
.replace(/:/g, '-')
.replace(/\./g, '_');
const fileName = `memory-${sessionId.slice(0, 8)}-${timestamp}.json`;
const filePath = path.join(diagnosticsDir, fileName);

const diagnostics = await collectMemoryDiagnostics({
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
sessionId,
qwenVersion: this.config.getCliVersion(),
});

const payload = {
trigger,
dumpNumber: this.dumpCount + 1,
...diagnostics,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Phase 2's fullPayload spreads ...diagnostics which includes memoryUsage from collectMemoryDiagnostics(). Since void dump() fires before executeCleanup() in the caller, Phase 2's async collection may capture post-cleanup (cleaner) memory state — overwriting Phase 1's accurate crisis-state memoryUsage with misleading "healthy" numbers.

Consider preserving Phase 1's memory snapshot in the full payload:

Suggested change
...diagnostics,
const fullPayload = {
trigger,
dumpNumber,
...diagnostics,
memoryUsage: process.memoryUsage(),
session: this.collectSessionStats(),
suggestion: this.getSuggestion(trigger),
collectionComplete: true,
};

Or place dumper-specific memory fields after the spread so they take precedence.

— qwen3.7-max via Qwen Code /review

session: this.collectSessionStats(),
suggestion: this.getSuggestion(trigger),
};

fs.writeFileSync(filePath, JSON.stringify(payload, null, 2), 'utf8');

this.dumpCount++;
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
this.lastDumpTime = now;

debugLogger.info(
`Memory diagnostics written to ${filePath} (trigger=${trigger}, dump #${this.dumpCount})`,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The catch block contains a deliberate design decision ("slot stays consumed on failure") but is entirely untested. No test mocks mkdirSync or writeFileSync to throw.

Suggested test:

it('catch block keeps slot consumed on write failure', async () => {
  const config = createMockConfig();
  const dumper = new MemoryDiagnosticsDumper(config);

  let mockNow = 1000000;
  vi.spyOn(Date, 'now').mockImplementation(() => {
    mockNow += 60_000;
    return mockNow;
  });

  vi.mocked(fs.writeFileSync).mockImplementationOnce(() => {
    throw new Error('EACCES');
  });

  const r1 = await dumper.dump('hard'); // fails, slot consumed
  expect(r1).toBeUndefined();

  // Slots 2 and 3 succeed
  await dumper.dump('hard');
  await dumper.dump('hard');

  // Slot 4 hits cap (not cooldown), proving failed attempt consumed slot 1
  const r4 = await dumper.dump('hard');
  expect(r4).toBeUndefined();
});

— qwen3.7-max via Qwen Code /review


return { filePath, trigger };
} catch (err) {
debugLogger.error(
`Failed to write memory diagnostics: ${getErrorMessage(err)}`,
);
return undefined;
}
}

private ensureDiagnosticsDir(): string {
const projectDir = this.config.storage.getProjectDir();
const diagnosticsDir = path.join(projectDir, 'diagnostics');
fs.mkdirSync(diagnosticsDir, { recursive: true });
return diagnosticsDir;
}

private collectSessionStats(): Record<string, unknown> {
try {
const geminiClient = this.config.getGeminiClient?.();
if (!geminiClient) return { available: false };
const historyLength = geminiClient.getChat?.()?.getHistoryLength?.() ?? 0;
return {
historyEntries: historyLength,
};
} catch {
return { available: false };
}
}

private getSuggestion(trigger: 'hard' | 'critical'): string {
if (trigger === 'critical') {
return 'Memory is critically high. Consider running /compact or starting a fresh session to avoid OOM.';
}
return 'Memory pressure detected. Running /compact may help reduce memory usage.';
}
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}
10 changes: 10 additions & 0 deletions packages/core/src/services/memoryPressureMonitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getHeapStatistics } from 'node:v8';
import { createDebugLogger } from '../utils/debugLogger.js';
import { getErrorMessage } from '../utils/errors.js';
import type { Config } from '../config/config.js';
import { MemoryDiagnosticsDumper } from './memoryDiagnosticsDumper.js';

// Types

Expand Down Expand Up @@ -104,13 +105,15 @@ export class MemoryPressureMonitor extends EventEmitter {
private consecutiveIneffectiveAggressiveCleanups = 0;
private cleanupGeneration = 0;
private readonly effectiveMemoryLimit: number;
private readonly diagnosticsDumper: MemoryDiagnosticsDumper;

constructor(coreConfig: Config, pressureConfig?: MemoryPressureConfig) {
super();
this.coreConfig = coreConfig;
this.config = { ...(pressureConfig ?? DEFAULT_PRESSURE_CONFIG) };
validateMemoryPressureConfig(this.config);
this.effectiveMemoryLimit = this.computeEffectiveMemoryLimit();
this.diagnosticsDumper = new MemoryDiagnosticsDumper(coreConfig);
const heapSizeLimit = getHeapStatistics().heap_size_limit;
debugLogger.info(
`Effective memory limit: ${formatMiB(this.effectiveMemoryLimit)} MiB; ` +
Expand Down Expand Up @@ -142,6 +145,7 @@ export class MemoryPressureMonitor extends EventEmitter {
resetForNewSession(): void {
this.cleanupGeneration++;
this.resetConsecutiveFailures();
this.diagnosticsDumper.resetForNewSession();
this.cleanupInProgress = false;
this.activeCleanupAction = 'none';
this.queuedCleanupRecommendation = undefined;
Expand Down Expand Up @@ -196,6 +200,12 @@ export class MemoryPressureMonitor extends EventEmitter {
return;
}

// Write diagnostics to disk before cleanup — the JSON is cheap and survives
// even if a subsequent heap snapshot or cleanup triggers OOM.
if (pressure === 'hard' || pressure === 'critical') {
void this.diagnosticsDumper.dump(pressure);
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}

this.executeCleanup(recommendation);
}

Expand Down
Loading