Repository navigation
feat(core): auto-dump memory diagnostics to disk on pressure detection #4654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
5a87473
4aa1584
8f776f7
33de27e
b3a6fba
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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'); | ||
| }); | ||
|
|
||
| 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); | ||
| }); | ||
| }); | ||
| 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({ | ||||||||||||||||||||||
|
yiliang114 marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||
| sessionId, | ||||||||||||||||||||||
| qwenVersion: this.config.getCliVersion(), | ||||||||||||||||||||||
| }); | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| const payload = { | ||||||||||||||||||||||
| trigger, | ||||||||||||||||||||||
| dumpNumber: this.dumpCount + 1, | ||||||||||||||||||||||
| ...diagnostics, | ||||||||||||||||||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] Phase 2's Consider preserving Phase 1's memory snapshot in the full payload:
Suggested change
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++; | ||||||||||||||||||||||
|
yiliang114 marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||
| this.lastDumpTime = now; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| debugLogger.info( | ||||||||||||||||||||||
| `Memory diagnostics written to ${filePath} (trigger=${trigger}, dump #${this.dumpCount})`, | ||||||||||||||||||||||
| ); | ||||||||||||||||||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] The 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.'; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
yiliang114 marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||
| } | ||||||||||||||||||||||
Uh oh!
There was an error while loading. Please reload this page.