From 842298e84ada803bfd572df6aebef56866efbe98 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:47:45 +0100 Subject: [PATCH] fix: clear editor diagnostics and in-memory findings with the cache Clear Analysis Cache cleared the sidebar, the saved snapshot and the stack data, but left the Problems panel and the last results in memory, which the ignore-list listener republished and saved again. - The command also clears the diagnostics and the last results. - It is refused while an analysis runs, whose results would be written back right after. - clearCache() waits for the cache load at startup and for writes still in flight, and writes are queued, so neither can restore what it deletes. Tests run Run Analysis with a stubbed ctrace in a workspace: the Problems panel is empty after clearing, stays empty after an ignore-list change, and clearing during a run is refused. Fixes #36 --- src/ctrace/WorkspaceScanner.ts | 21 +++++- src/extension.ts | 10 +++ src/test-workspace/clearCache.test.ts | 103 ++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 src/test-workspace/clearCache.test.ts diff --git a/src/ctrace/WorkspaceScanner.ts b/src/ctrace/WorkspaceScanner.ts index bf58c8f..550b74d 100755 --- a/src/ctrace/WorkspaceScanner.ts +++ b/src/ctrace/WorkspaceScanner.ts @@ -59,7 +59,17 @@ let _cacheFile: string | undefined; * Loads the analysis cache persisted by a previous session. Call once on * activation; without a storage directory the cache stays in memory only. */ -export async function initAnalysisCache(storageDir: string | undefined): Promise { +// The load and the writes in flight: clearCache() waits for them, so that +// none of them can bring back what it deletes. +let _loading: Promise = Promise.resolve(); +let _persisting: Promise = Promise.resolve(); + +export function initAnalysisCache(storageDir: string | undefined): Promise { + _loading = loadAnalysisCache(storageDir); + return _loading; +} + +async function loadAnalysisCache(storageDir: string | undefined): Promise { _cacheFile = storageDir ? path.join(storageDir, CACHE_FILE_NAME) : undefined; if (!_cacheFile) { return; } try { @@ -77,7 +87,12 @@ export async function initAnalysisCache(storageDir: string | undefined): Promise } /** Writes the analysis cache to disk, dropping entries for files that no longer exist. */ -export async function persistAnalysisCache(): Promise { +export function persistAnalysisCache(): Promise { + _persisting = _persisting.then(writeAnalysisCache); + return _persisting; +} + +async function writeAnalysisCache(): Promise { if (!_cacheFile) { return; } for (const fsPath of [..._analysisCache.keys()]) { if (!await fileExists(fsPath)) { _analysisCache.delete(fsPath); } @@ -95,6 +110,8 @@ export function cacheFileAnalysis(file: WorkspaceFile, contextKey: string, analy } export async function clearCache(): Promise { + await _loading; + await _persisting; _fileCache.clear(); _analysisCache.clear(); if (_cacheFile) { diff --git a/src/extension.ts b/src/extension.ts index a498c0d..3b76845 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -679,8 +679,18 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand('ctrace.clearAnalysisCache', async () => { + // A running scan would write its results back right after. + if (isRunning) { + vscode.window.showWarningMessage('An analysis is running: cancel it or wait for it to finish, then clear the cache.'); + return; + } + // Waits for the cache load at startup and for writes still in flight. await clearCache(); StackManager.instance.clear(); + // The ignore-list listener republishes these: they must go too. + lastSarifByFile = new Map(); + republishPending = false; + clearDiagnostics(diagnosticCollection); await findingsStore.clear(); sidebarProvider.postMessage({ type: 'clear-results' }); vscode.window.showInformationMessage('Ctrace analysis cache and saved results cleared.'); diff --git a/src/test-workspace/clearCache.test.ts b/src/test-workspace/clearCache.test.ts new file mode 100644 index 0000000..e14d75b --- /dev/null +++ b/src/test-workspace/clearCache.test.ts @@ -0,0 +1,103 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import * as AnalysisRunner from '../ctrace/AnalysisRunner'; +import * as BinaryUpdater from '../ctrace/BinaryUpdater'; +import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder'; +import { IGNORE_FILE_NAME } from '../ctrace/FindingIgnoreList'; +import { setScanDirectoryForTesting } from '../ctraceRunner'; + +/** Clear Analysis Cache, after a real Run Analysis whose ctrace reports one finding. */ +suite('Clear Analysis Cache', function () { + this.timeout(60000); + + const runner = AnalysisRunner as { runCommand: typeof AnalysisRunner.runCommand }; + const updater = BinaryUpdater as { ensureBinary: typeof BinaryUpdater.ensureBinary }; + const originalRunCommand = runner.runCommand; + const originalEnsureBinary = updater.ensureBinary; + let work = ''; + let root = ''; + let sample = ''; + let ignoreFile = ''; + let gate: Promise | undefined; + + const sarif = () => JSON.stringify({ + $schema: 'https://json.schemastore.org/sarif-2.1.0.json', + version: '2.1.0', + runs: [{ + tool: { driver: { name: 'cppcheck' } }, + results: [{ + ruleId: 'testRule', level: 'warning', message: { text: 'a finding to clear' }, + locations: [{ physicalLocation: { artifactLocation: { uri: sample }, region: { startLine: 1 } } }], + }], + }], + }); + + const diagnostics = () => vscode.languages.getDiagnostics(vscode.Uri.file(sample)) + .filter(d => d.source?.startsWith('CoreTrace')); + const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + const run = () => vscode.commands.executeCommand('ctrace.runAnalysis', { + filePath: sample, + uiState: { staticEnabled: false, staticTools: [], dynamicEnabled: false, dynamicTools: [] }, + }); + + suiteSetup(async () => { + root = vscode.workspace.workspaceFolders![0].uri.fsPath; + sample = path.join(root, 'sample.c'); + ignoreFile = path.join(root, IGNORE_FILE_NAME); + work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-clear-')); + const fakeBinary = path.join(work, 'ctrace'); + fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 }); + updater.ensureBinary = async () => fakeBinary; + runner.runCommand = async (command: string) => { + if (gate) { await gate; } + // The stack pass gets nothing; the SARIF pass reports the finding. + return { stdout: command.includes('--sarif-format') ? sarif() : '', stderr: '', exitCode: 0 }; + }; + setMockWslAvailableForTesting(true); + setScanDirectoryForTesting(path.join(work, 'scan')); + await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate(); + }); + + suiteTeardown(() => { + runner.runCommand = originalRunCommand; + updater.ensureBinary = originalEnsureBinary; + setMockWslAvailableForTesting(null); + setScanDirectoryForTesting(undefined); + fs.rmSync(ignoreFile, { force: true }); + fs.rmSync(work, { recursive: true, force: true }); + }); + + test('the Problems panel is cleared, and an ignore-list change does not bring the findings back', async function () { + if (process.platform === 'win32') { this.skip(); } + await run(); + assert.strictEqual(diagnostics().length, 1, 'the run should publish its finding'); + + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + assert.strictEqual(diagnostics().length, 0, 'Clear Analysis Cache must clear the Problems panel'); + + // Changing the ignore list republishes the last results: there must be none left. + fs.writeFileSync(ignoreFile, JSON.stringify({ version: 1, ignored: [{ fingerprint: 'abcdef123456' }] })); + await sleep(1500); + assert.strictEqual(diagnostics().length, 0, 'cleared findings came back after an ignore-list change'); + }); + + test('clearing is refused while an analysis runs, so it cannot write its results back', async function () { + if (process.platform === 'win32') { this.skip(); } + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + let release!: () => void; + gate = new Promise(resolve => { release = resolve; }); + const running = run(); + await sleep(300); + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + release(); + gate = undefined; + await running; + assert.strictEqual(diagnostics().length, 1, 'the run finished with its finding, the clear was refused'); + + await vscode.commands.executeCommand('ctrace.clearAnalysisCache'); + assert.strictEqual(diagnostics().length, 0); + }); +});