diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 49362c41..10dcc609 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -79,6 +79,14 @@ - Bubble charts rested their smallest bubble on the table and sank their axes up to 0.6 m into it. The lowest of the bubbles and the axes now rests on the table. - Pie and donut charts stand up to 2 m tall (they were about 1.3 m), so their sectors and labels are readable from the controller position. - A live re-analysis no longer undoes a remap you made while the charts were refreshing, and a second chart change made in project evolution while the first is applied is no longer ignored. +- **Long analyses can be cancelled, time out, and no longer block a mode for the rest of the session.** Project evolution, historical comparison and the dependency graph now run as jobs that can be stopped: + - A movie or a comparison that is generating can be stopped with **Cancel** (the Clear movie / Compare button while it runs). The Git and Python processes it started are killed, its result is discarded, and the previous movie or comparison is kept. + - **Clear movie** no longer races a generation: a running generation is cancelled and waited for, so a movie can no longer reappear right after it was cleared. + - **Leaving project evolution no longer deletes the movie** or stops a generation started by someone else in the room; only Cancel does. + - A revision whose analysis hangs is stopped after 5 minutes and left out of the movie; a single Git command is stopped after 3 minutes; a whole movie after 30 minutes, a comparison after 15 and a dependency analysis after 10. Before, one stuck revision kept the mode "already running" until VS Code was reloaded. + - A double click on Generate or Compare, or two participants starting at once, no longer shows an error to everyone while the first job runs: "already running" goes only to the person who asked. A participant who joins mid-job sees it running. + - A cancelled analysis is no longer recorded as "this revision has no data", which hid that commit from both Git pickers until the session ended. + - Git-history exports no longer wait forever on one file: a file analysis is stopped after 2 minutes and retried once, and a Python worker that is slow to start (antivirus on Windows) reduces the number of workers instead of failing the export. - A source file of the XR chart-mapping runtime contained a raw control character typed into a string. Behaviour was correct, but the file was invisible to code search and review tools. It now uses the equivalent escape sequence; the runtime value is identical. ## [1.2.0] - 2026-07-30 diff --git a/apps/vscode-extension/docs/features/HISTORICAL_COMPARISON_XR.md b/apps/vscode-extension/docs/features/HISTORICAL_COMPARISON_XR.md index 5dc9b862..c65485be 100644 --- a/apps/vscode-extension/docs/features/HISTORICAL_COMPARISON_XR.md +++ b/apps/vscode-extension/docs/features/HISTORICAL_COMPARISON_XR.md @@ -285,6 +285,13 @@ Closing a comparison removes datasources, charts, listeners, controllers and comparison geometry. The service deletes its temporary snapshots on disposal and clears its in-memory cache. +A comparison is a job on the extension host (1.2.1) with a 15-minute deadline, +a 5-minute watchdog per side and a 3-minute one per Git command. While it runs, +the `Compare` button reads `Cancel`: it stops the comparison for the whole room, +kills its Git and Python processes and keeps the previous comparison. A second +start is answered `busy` to that participant only, and the live-refresh flag +follows the request that succeeded, not the one that was asked. + ## Testing performed Automated coverage checks: diff --git a/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md b/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md index f4040076..fbfe211f 100644 --- a/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md +++ b/apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md @@ -53,6 +53,27 @@ Project Evolution entity, hides the movie chart, and resets every connected client to the empty Project Evolution panel. It does not delete the normal analysis `data.json`. +### Cancel, Clear and leaving the mode (1.2.1) + +Generating a movie is a job on the extension host with an id, a state +(`queued`, `running`, `cancelled`, `failed`, `done`) and a 30-minute deadline; +each revision's analysis also has its own 5-minute watchdog, and each Git +command a 3-minute one. While a movie is being generated the `Clear movie` +button reads `Cancel`: + +- **Cancel** stops the generation for the whole room: it kills the running Git + and Python processes, discards anything the job would still produce, and + keeps the movie generated before it. +- **Clear movie** deletes the current movie. If a generation is running, it is + cancelled and waited for first, so no late movie can appear after the clear. +- **Leaving the mode** changes nothing on the server: the generation goes on + for the room and its movie appears when it is ready. + +A second Generate while one runs is answered `busy` to that participant only. +A participant who opens the panel mid-generation sees the room's job (the +references reply carries its state). A revision whose analysis times out is +discarded like any other unusable revision; the movie is built from the rest. + ## Architecture `ProjectEvolutionService` reuses the local Git snapshot materialization used by diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 9c017c96..77819fa2 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 155", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 154", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/core/analysis/launch/jobRunner.ts b/apps/vscode-extension/src/core/analysis/launch/jobRunner.ts new file mode 100644 index 00000000..aa2177aa --- /dev/null +++ b/apps/vscode-extension/src/core/analysis/launch/jobRunner.ts @@ -0,0 +1,338 @@ +/** + * One long job at a time per service (a historical comparison, a project + * evolution movie, a dependency graph), with an id, a state, a deadline and a + * cancel that reaches the child processes. + * + * It replaces `SingleJobGate`, which had none of that (S6, issue #78): + * + * - **Atomic start.** `tryReserve()` takes the slot synchronously, so a + * bridge reserves BEFORE its first `await` and two starts can never both + * pass a check-then-act `isBusy()` (LAUNCHER-11, HIST-9). + * - **Cancel kills.** The work runs under `runWithLaunchSignal`, so the + * Python spawner (`executePython.ts`) and the Git runner + * (`gitRepositoryService.ts`) see the job's signal and kill their child on + * abort, on Windows, macOS and Linux alike (EVO-2, HIST-7, DEPGRAPH-9). + * - **Deadline.** A job past `timeoutMs` is aborted the same way (EVO-3). + * - **Late results are discarded.** A job aborted while its work was + * finishing rejects with `JobCancelledError`; its result is never returned + * to be published (EVO-4). + * - **The slot is held until the work really ends**, so a new job never runs + * beside the orphans of a cancelled one; after an abort it is released + * anyway once `graceMs` passes, so a step that ignores the signal cannot + * block the service for the rest of the session. + * + * Deliberately free of vscode imports, so it is unit-testable from `out/`. + */ +import { runWithLaunchSignal } from './launchControl'; + +export type JobState = 'queued' | 'running' | 'cancelled' | 'failed' | 'done'; + +export interface JobStatus { + id: string; + state: JobState; + startedAt: string; + endedAt?: string; + /** For a failed job: its error message; for a cancelled one: the reason. */ + error?: string; +} + +export type JobCancelReason = 'cancelled' | 'timeout' | 'disposed'; + +export class JobCancelledError extends Error { + constructor(public readonly reason: JobCancelReason, code: string) { + super(code); + this.name = 'JobCancelledError'; + } +} + +export interface JobTicket { + readonly id: string; + readonly signal: AbortSignal; + /** Runs the reserved job; call it once. */ + execute(work: (signal: AbortSignal) => Promise): Promise; + /** Gives the slot back when the job is abandoned before `execute`. */ + release(): void; +} + +export interface JobRunnerOptions { + /** Error message of a refused start. */ + busyCode: string; + /** Error message of a job that was cancelled (or disposed). */ + cancelledCode: string; + /** Error message of a job that ran past its deadline. */ + timeoutCode: string; + /** Deadline of one job; 0 disables it. */ + timeoutMs: number; + /** How long an aborted job may keep the slot while its work unwinds. */ + graceMs?: number; + /** Called on every state change (to share it with the room). */ + onStateChange?: (status: JobStatus) => void; +} + +const DEFAULT_GRACE_MS = 5_000; + +interface ActiveJob { + status: JobStatus; + controller: AbortController; + timer: ReturnType | null; + promise: Promise | null; + executed: boolean; + /** Releases the slot; idempotent. */ + free: () => void; +} + +let nextJobNumber = 0; + +function newJobId(): string { + nextJobNumber += 1; + return `job-${Date.now().toString(36)}-${nextJobNumber}`; +} + +export class JobRunner { + private active: ActiveJob | null = null; + private completedRequest: TRequest | null = null; + private latestStatus: JobStatus | null = null; + /** Settles when the active job's slot is released. */ + private released: Promise = Promise.resolve(); + + public constructor(private readonly options: JobRunnerOptions) {} + + public isBusy(): boolean { + return this.active !== null; + } + + /** The current job's status, or the last one's once it ended. */ + public get status(): JobStatus | null { + return this.latestStatus ? { ...this.latestStatus } : null; + } + + /** The request of the last job that finished successfully, or null. */ + public get lastRequest(): TRequest | null { + return this.completedRequest; + } + + public forgetLastRequest(): void { + this.completedRequest = null; + } + + /** The running job's result promise (for callers that join it), or null. */ + public current(): Promise | null { + return this.active?.promise ?? null; + } + + /** + * Takes the slot synchronously, or returns null when a job holds it. + * The returned ticket must be executed or released. + */ + public tryReserve(request: TRequest): JobTicket | null { + if (this.active) { + return null; + } + const job: ActiveJob = { + status: { id: newJobId(), state: 'queued', startedAt: new Date().toISOString() }, + controller: new AbortController(), + timer: null, + promise: null, + executed: false, + free: () => undefined, + }; + let releaseSlot!: () => void; + this.released = new Promise((resolve) => { + releaseSlot = resolve; + }); + const free = () => { + if (job.timer) { + clearTimeout(job.timer); + job.timer = null; + } + if (this.active === job) { + this.active = null; + } + releaseSlot(); + }; + job.free = free; + this.active = job; + this.publish(job.status); + + return { + id: job.status.id, + signal: job.controller.signal, + release: () => { + if (!job.executed && this.active === job) { + this.finish(job, 'cancelled', 'released'); + free(); + } + }, + execute: (work) => { + if (job.executed) { + return Promise.reject(new Error('job-already-executed')); + } + job.executed = true; + job.promise = this.runJob(job, request, work, free); + return job.promise; + }, + }; + } + + /** Takes the slot and runs `work`, or throws the busy code. */ + public run(request: TRequest, work: (signal: AbortSignal) => Promise): Promise { + const ticket = this.tryReserve(request); + if (!ticket) { + return Promise.reject(new Error(this.options.busyCode)); + } + return ticket.execute(work); + } + + /** Aborts the running job, if any. Returns whether there was one. */ + public cancel(reason: JobCancelReason = 'cancelled'): boolean { + const job = this.active; + if (!job || job.controller.signal.aborted) { + return false; + } + job.controller.abort(reason); + if (!job.executed) { + this.finish(job, 'cancelled', reason); + job.free(); + } + return true; + } + + /** Cancels the running job and waits until its slot is free. */ + public async cancelAndWait(reason: JobCancelReason = 'cancelled'): Promise { + this.cancel(reason); + await this.released; + } + + private async runJob( + job: ActiveJob, + request: TRequest, + work: (signal: AbortSignal) => Promise, + free: () => void, + ): Promise { + const signal = job.controller.signal; + if (signal.aborted) { + free(); + throw this.cancelledError(signal); + } + job.status = { ...job.status, state: 'running' }; + this.publish(job.status); + if (this.options.timeoutMs > 0) { + job.timer = setTimeout(() => { + if (!signal.aborted) { + job.controller.abort('timeout'); + } + }, this.options.timeoutMs); + (job.timer as { unref?: () => void }).unref?.(); + } + + const workPromise = runWithLaunchSignal(signal, () => work(signal)); + const settled = workPromise.then(() => undefined, () => undefined); + // The slot is freed when the work ends; after an abort, at the latest + // once the grace period has passed. + void settled.then(free); + const onAbort = () => { + const grace = setTimeout(free, this.options.graceMs ?? DEFAULT_GRACE_MS); + (grace as { unref?: () => void }).unref?.(); + void settled.then(() => clearTimeout(grace)); + }; + signal.addEventListener('abort', onAbort, { once: true }); + + try { + const result = await raceAbort(workPromise, signal, () => this.cancelledError(signal)); + if (signal.aborted) { + // The work finished after it was cancelled: discard the result. + throw this.cancelledError(signal); + } + this.completedRequest = { ...request }; + this.finish(job, 'done'); + return result; + } catch (error) { + if (signal.aborted) { + const cancelled = error instanceof JobCancelledError ? error : this.cancelledError(signal); + this.finish(job, 'cancelled', cancelled.reason); + throw cancelled; + } + this.finish(job, 'failed', error instanceof Error ? error.message : String(error)); + throw error; + } finally { + signal.removeEventListener('abort', onAbort); + if (job.timer) { + clearTimeout(job.timer); + job.timer = null; + } + } + } + + private cancelledError(signal: AbortSignal): JobCancelledError { + const reason = (signal.reason as JobCancelReason) || 'cancelled'; + return new JobCancelledError( + reason, + reason === 'timeout' ? this.options.timeoutCode : this.options.cancelledCode, + ); + } + + private finish(job: ActiveJob, state: JobState, error?: string): void { + if (job.status.state === 'done' || job.status.state === 'failed' || job.status.state === 'cancelled') { + return; + } + job.status = { ...job.status, state, endedAt: new Date().toISOString(), ...(error ? { error } : {}) }; + this.publish(job.status); + } + + private publish(status: JobStatus): void { + this.latestStatus = { ...status }; + try { + this.options.onStateChange?.({ ...status }); + } catch { + // A listener must never break the job. + } + } +} + +/** Settles with `work`, or rejects as soon as `signal` aborts. */ +function raceAbort(work: Promise, signal: AbortSignal, onAbort: () => Error): Promise { + if (signal.aborted) { + work.catch(() => undefined); + return Promise.reject(onAbort()); + } + return new Promise((resolve, reject) => { + const abort = () => reject(onAbort()); + signal.addEventListener('abort', abort, { once: true }); + work.then( + (value) => { signal.removeEventListener('abort', abort); resolve(value); }, + (error) => { signal.removeEventListener('abort', abort); reject(error); }, + ); + }); +} + +/** + * A signal that aborts when `parent` does or after `timeoutMs`, whichever + * comes first; `dispose()` clears the timer. Used for per-step watchdogs + * inside a job (one revision's analysis, one Git command). + */ +export function withTimeout( + parent: AbortSignal | undefined, + timeoutMs: number, + reason = 'timeout', +): { signal: AbortSignal; dispose: () => void } { + const controller = new AbortController(); + const onParentAbort = () => controller.abort(parent?.reason); + if (parent?.aborted) { + controller.abort(parent.reason); + } else { + parent?.addEventListener('abort', onParentAbort, { once: true }); + } + const timer = timeoutMs > 0 + ? setTimeout(() => controller.abort(reason), timeoutMs) + : null; + (timer as { unref?: () => void } | null)?.unref?.(); + return { + signal: controller.signal, + dispose: () => { + if (timer) { + clearTimeout(timer); + } + parent?.removeEventListener('abort', onParentAbort); + }, + }; +} diff --git a/apps/vscode-extension/src/core/dependencies/dependencyGraphService.ts b/apps/vscode-extension/src/core/dependencies/dependencyGraphService.ts index 59e753f4..eae8d620 100644 --- a/apps/vscode-extension/src/core/dependencies/dependencyGraphService.ts +++ b/apps/vscode-extension/src/core/dependencies/dependencyGraphService.ts @@ -5,9 +5,21 @@ import * as vscode from 'vscode'; import { UnifiedSessionRegistry } from '../analysis/session/sessionRegistry'; import { ExecutePython } from '../analysis/python/executePython'; import { DependencyGraphDataset, DependencyRefreshRequest } from './dependencyGraphModels'; +import { JobRunner } from '../analysis/launch/jobRunner'; +import { runWithLaunchSignal } from '../analysis/launch/launchControl'; + +/** A dependency analysis longer than this is killed and reported (DEPGRAPH-9). */ +export const DEPENDENCY_GRAPH_JOB_TIMEOUT_MS = 10 * 60 * 1000; export class DependencyGraphService { - private activeJob: Promise | null = null; + private readonly jobs = new JobRunner({ + busyCode: 'dependency-graph-busy', + cancelledCode: 'dependency-graph-cancelled', + timeoutCode: 'dependency-graph-timeout', + timeoutMs: DEPENDENCY_GRAPH_JOB_TIMEOUT_MS, + }); + /** Cancels the file-scope analysis in flight when the service is disposed. */ + private readonly disposal = new AbortController(); private revision = 0; private generated = false; private readonly extractionCachePath: string; @@ -40,7 +52,7 @@ export class DependencyGraphService { } public isBusy(): boolean { - return this.activeJob !== null; + return this.jobs.isBusy(); } public getInitialScope(): { kind: 'file' | 'directory'; relativePath: string } { @@ -54,22 +66,27 @@ export class DependencyGraphService { request?: DependencyRefreshRequest, onProgress?: (message: string) => void, ): Promise { - if (this.activeJob) { - return this.activeJob; + // A start while one runs joins it rather than being refused. + const running = this.jobs.current(); + if (running) { + return running; } - const job = this.executeAnalysis(request, onProgress); - this.activeJob = job; - const clearActiveJob = () => { - if (this.activeJob === job) { - this.activeJob = null; - } - }; - void job.then(clearActiveJob, clearActiveJob); - return job; + const ticket = this.jobs.tryReserve({}); + if (!ticket) { + // Reserved but not executing yet: impossible here (reserve and + // execute are synchronous together), kept as a typed guard. + return Promise.reject(new Error('dependency-graph-busy')); + } + return ticket.execute(() => this.executeAnalysis(request, onProgress)); } + /** + * Disposing (the session ends) kills the Python analysis in flight + * instead of leaving it running with nobody to read it (DEPGRAPH-9). + */ public async dispose(): Promise { - this.activeJob = null; + this.disposal.abort('disposed'); + await this.jobs.cancelAndWait('disposed'); this.fileScopeCache.clear(); } @@ -93,14 +110,14 @@ export class DependencyGraphService { return dataset; } onProgress?.('Analyzing symbols and calls in the selected file...'); - const result = await new ExecutePython(this.context).executeDependencyAnalysis( + const result = await runWithLaunchSignal(this.disposal.signal, () => new ExecutePython(this.context).executeDependencyAnalysis( targetPath, 'file', false, undefined, undefined, this.resolveProjectRoot(targetPath), - ); + )); if (!result || result.error === true || !Array.isArray(result.nodes) || !Array.isArray(result.edges)) { throw new Error(String(result?.message || 'File dependency analysis returned an invalid dataset.')); } diff --git a/apps/vscode-extension/src/core/export/gitExportPythonWorkerPool.ts b/apps/vscode-extension/src/core/export/gitExportPythonWorkerPool.ts index 9d8ce181..85f233e3 100644 --- a/apps/vscode-extension/src/core/export/gitExportPythonWorkerPool.ts +++ b/apps/vscode-extension/src/core/export/gitExportPythonWorkerPool.ts @@ -4,7 +4,15 @@ import * as path from 'path'; const WORKER_PROTOCOL_VERSION = 1; const MAX_TASKS_PER_WORKER = 500; -const WORKER_READY_TIMEOUT_MS = 10_000; +// A cold interpreter importing lizard under antivirus on Windows can take +// well over 10 s, and the Maximum profile starts up to 32 at once (EVO-17). +const WORKER_READY_TIMEOUT_MS = 30_000; +/** + * One file analysis that takes longer than this is treated as a failure: + * the worker is killed and the job retried once on a fresh worker, then + * recorded as failed, instead of waiting forever (EVO-17). + */ +export const WORKER_JOB_TIMEOUT_MS = 120_000; export interface WorkerPoolCancelSignal { readonly isCancellationRequested: boolean; @@ -121,7 +129,7 @@ class PersistentPythonWorker { } } - public async analyze(job: GitExportAnalysisJob): Promise { + public async analyze(job: GitExportAnalysisJob, timeoutMs = WORKER_JOB_TIMEOUT_MS): Promise { await this.ready(); if (this.stopped || this.child.exitCode !== null) { throw new Error('python-export-worker-not-running'); @@ -130,13 +138,25 @@ class PersistentPythonWorker { throw new Error('python-export-worker-busy'); } return new Promise((resolve, reject) => { + const timer = timeoutMs > 0 + ? setTimeout(() => { + if (this.pending?.jobId === job.id) { + this.pending = undefined; + reject(new Error(`python-export-worker-job-timeout: ${job.id} took more than ${Math.round(timeoutMs / 1000)} s`)); + } + }, timeoutMs) + : undefined; this.pending = { jobId: job.id, resolve: () => { + clearTimeout(timer); this.completedTasks += 1; resolve(); }, - reject, + reject: (reason: Error) => { + clearTimeout(timer); + reject(reason); + }, }; this.child.stdin.write(`${JSON.stringify({ type: 'analyze', @@ -251,6 +271,7 @@ export class GitExportPythonWorkerPool { private readonly workerScriptPath: string, private readonly workerCount: number, private readonly token?: WorkerPoolCancelSignal, + private readonly jobTimeoutMs = WORKER_JOB_TIMEOUT_MS, ) {} public async run( @@ -280,8 +301,22 @@ export class GitExportPythonWorkerPool { jobs.length, ); - const loops = Array.from({ length: actualWorkers }, async () => { - let worker = await this.createWorker(); + // A worker that cannot start degrades the pool instead of failing the + // export, as long as one other worker runs; the job queue is shared, + // so the running loops take its share (EVO-17). + const started = await Promise.allSettled( + Array.from({ length: actualWorkers }, () => this.createWorker()), + ); + this.throwIfCancelled(); + const initialWorkers = started + .filter((entry): entry is PromiseFulfilledResult => entry.status === 'fulfilled') + .map((entry) => entry.value); + if (!initialWorkers.length) { + throw (started[0] as PromiseRejectedResult).reason; + } + + const loops = initialWorkers.map(async (initialWorker) => { + let worker = initialWorker; try { while (true) { this.throwIfCancelled(); @@ -296,7 +331,7 @@ export class GitExportPythonWorkerPool { this.throwIfCancelled(); try { await job.prepareInput(); - await worker.analyze(job); + await worker.analyze(job, this.jobTimeoutMs); finished = true; } catch (error) { const attempt = (attempts.get(job.id) || 0) + 1; @@ -323,7 +358,7 @@ export class GitExportPythonWorkerPool { onProgress?.({ completed, total: jobs.length, - workerCount: actualWorkers, + workerCount: initialWorkers.length, filesPerSecond, etaSeconds: Math.max(0, (jobs.length - completed) / filesPerSecond), }); diff --git a/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts b/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts index 4f95cfe3..f38a3fc1 100644 --- a/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts +++ b/apps/vscode-extension/src/core/history/gitAnalysisSessionContext.ts @@ -3,6 +3,8 @@ import * as path from 'path'; import * as vscode from 'vscode'; import { UnifiedAnalysisSession } from '../analysis/session/analysisSession'; import { ExecutePython } from '../analysis/python/executePython'; +import { currentLaunchSignal, runWithLaunchSignal } from '../analysis/launch/launchControl'; +import { withTimeout } from '../analysis/launch/jobRunner'; import { GitAnalysisSourceCatalog, GitAnalysisSourceError, @@ -13,6 +15,13 @@ import { buildAnalyzerCacheKey } from './gitAnalysisShared'; import { GitRepositoryService } from './gitRepositoryService'; import { ComparisonSource, GitAnalysisExclusionCode } from './historicalComparisonModels'; +/** + * One revision's analysis longer than this is killed: in a movie the frame + * is discarded, in a comparison the comparison fails with a clear message, + * and in both the job is free again (EVO-3, HIST-7). + */ +export const REVISION_ANALYSIS_TIMEOUT_MS = 5 * 60 * 1000; + /** One analyzed revision as both Git services cache it. */ export interface CachedPayload { payload: Record[]; @@ -62,6 +71,8 @@ export class GitAnalysisSessionContext { public readonly sourceCatalog: GitAnalysisSourceCatalog; public readonly cache = new Map(); private readonly ownsSourceCatalog: boolean; + /** Test seam: the per-revision watchdog. */ + public revisionTimeoutMs = REVISION_ANALYSIS_TIMEOUT_MS; public constructor( session: UnifiedAnalysisSession, @@ -128,10 +139,49 @@ export class GitAnalysisSessionContext { templatePaths: new Map(), metadata: { [this.policy.metadataKey]: source }, }; + const analysisResult = await this.runRevisionAnalysis(source, revisionSession); + const result = { + payload: this.policy.decorate( + this.requireUsablePayload(source, analysisResult), + session, + materialized.targetPath, + ), + missingTarget: false, + warnings: materialized.warnings, + }; + this.cache.set(cacheKey, result); + return result; + } + + /** + * Runs one revision's Python analysis under the job's signal plus a + * per-revision watchdog. A cancelled job's analysis is never classified + * (nor cached) as a fact about the revision. + */ + private async runRevisionAnalysis( + source: ComparisonSource, + revisionSession: UnifiedAnalysisSession, + ): Promise { let analysisResult: unknown; + const jobSignal = currentLaunchSignal(); + const watchdog = withTimeout(jobSignal, this.revisionTimeoutMs, 'revision-timeout'); try { - analysisResult = await new ExecutePython(this.extensionContext).executeAnalysis(revisionSession); + analysisResult = await runWithLaunchSignal( + watchdog.signal, + () => new ExecutePython(this.extensionContext).executeAnalysis(revisionSession), + ); } catch (error) { + if (jobSignal?.aborted) { + // A killed analysis is not a fact about the revision: never + // record it as a deterministic exclusion (EVO-2). + throw new Error('revision-analysis-cancelled'); + } + if (watchdog.signal.aborted) { + throw new Error( + `revision-analysis-timeout: the analysis of "${source.label}" took more than ` + + `${Math.round(this.revisionTimeoutMs / 1000)} s and was stopped.`, + ); + } if (isDeterministicNoDataError(error)) { throw this.excludeSource( source, @@ -140,18 +190,14 @@ export class GitAnalysisSessionContext { ); } throw error; + } finally { + watchdog.dispose(); } - const result = { - payload: this.policy.decorate( - this.requireUsablePayload(source, analysisResult), - session, - materialized.targetPath, - ), - missingTarget: false, - warnings: materialized.warnings, - }; - this.cache.set(cacheKey, result); - return result; + if (jobSignal?.aborted) { + // A cancelled job never caches what its last analysis returned. + throw new Error('revision-analysis-cancelled'); + } + return analysisResult; } /** The working copy is never cached: its data.json is the live analysis. */ @@ -227,43 +273,3 @@ export class GitAnalysisSessionContext { this.cache.clear(); } } - -/** - * At most one job at a time. A second start while one runs is refused with - * the caller's busy code; the request of the last job that SUCCEEDED is kept - * (a copy), so a failed run never replaces what the room is showing. - */ -export class SingleJobGate { - private activeJob: Promise | null = null; - private completedRequest: TRequest | null = null; - - public constructor(private readonly busyCode: string) {} - - public isBusy(): boolean { - return this.activeJob !== null; - } - - /** The request of the last successful job, or null. */ - public get lastRequest(): TRequest | null { - return this.completedRequest; - } - - public forgetLastRequest(): void { - this.completedRequest = null; - } - - public async run(request: TRequest, execute: () => Promise): Promise { - if (this.activeJob) { - throw new Error(this.busyCode); - } - const job = execute(); - this.activeJob = job; - try { - const result = await job; - this.completedRequest = { ...request }; - return result; - } finally { - this.activeJob = null; - } - } -} diff --git a/apps/vscode-extension/src/core/history/gitRepositoryService.ts b/apps/vscode-extension/src/core/history/gitRepositoryService.ts index 52ff5a95..d5fb3145 100644 --- a/apps/vscode-extension/src/core/history/gitRepositoryService.ts +++ b/apps/vscode-extension/src/core/history/gitRepositoryService.ts @@ -7,6 +7,7 @@ import { isDirectoryAnalysisFile, shouldIgnoreDirectoryName, } from '../analysis/watchers/analysisFilePolicy'; +import { currentLaunchSignal } from '../analysis/launch/launchControl'; import type { ComparisonSource, GitReferenceType, @@ -18,6 +19,21 @@ const execFile = promisify(childProcess.execFile); const MAX_SNAPSHOT_FILES = 5000; const MAX_SNAPSHOT_BYTES = 100 * 1024 * 1024; const MAX_SINGLE_FILE_BYTES = 8 * 1024 * 1024; +/** One git command longer than this is killed and reported (HIST-7, EVO-3). */ +export const GIT_COMMAND_TIMEOUT_MS = 180_000; + +/** The error a failed git command is reported with: timeout and cancel get their own codes. */ +function describeGitFailure(error: unknown): Error { + const failure = error as { name?: string; killed?: boolean; code?: unknown; message?: string } | null; + if (failure?.name === 'AbortError' || failure?.code === 'ABORT_ERR') { + return new Error('git-command-cancelled'); + } + if (failure?.killed) { + return new Error(`git-command-timeout: a git command took more than ${GIT_COMMAND_TIMEOUT_MS / 1000} s`); + } + const message = error instanceof Error ? error.message : String(error); + return new Error(`git-command-failed: ${message}`); +} interface GitCommandResult { stdout: string; @@ -527,18 +543,22 @@ export class GitRepositoryService { private async runGit(cwd: string, args: string[]): Promise { try { + // The job's signal (if this runs inside one) kills git on Cancel; + // the timeout stops a command that hangs on a network drive or a + // lazy fetch (HIST-7, EVO-3). const result = await execFile('git', ['-C', cwd, ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024, encoding: 'utf8', + timeout: GIT_COMMAND_TIMEOUT_MS, + signal: currentLaunchSignal(), }); return { stdout: result.stdout, stderr: result.stderr, }; } catch (error) { - const message = error instanceof Error ? error.message : String(error); - throw new Error(`git-command-failed: ${message}`); + throw describeGitFailure(error); } } @@ -559,10 +579,12 @@ export class GitRepositoryService { windowsHide: true, maxBuffer: MAX_SNAPSHOT_BYTES + (16 * 1024 * 1024), encoding: 'buffer', + timeout: GIT_COMMAND_TIMEOUT_MS, + signal: currentLaunchSignal(), }, (error, stdout) => { if (error) { - reject(new Error(`git-command-failed: ${error.message}`)); + reject(describeGitFailure(error)); return; } resolve(Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout)); diff --git a/apps/vscode-extension/src/core/history/historicalComparisonModels.ts b/apps/vscode-extension/src/core/history/historicalComparisonModels.ts index a1c10772..071d1869 100644 --- a/apps/vscode-extension/src/core/history/historicalComparisonModels.ts +++ b/apps/vscode-extension/src/core/history/historicalComparisonModels.ts @@ -107,12 +107,28 @@ export interface HistoricalComparisonReferences { pageSize: number; activeRequest?: HistoricalComparisonRequest | null; eligibility?: GitAnalysisEligibility; + /** + * The job running (or last run) for this mode, so a client that joins + * mid-job shows the same state as everyone else (S6). + */ + job?: AnalysisJobSnapshot | null; +} + +/** What the room sees of a long analysis job (JobRunner's JobStatus). */ +export interface AnalysisJobSnapshot { + id: string; + state: 'queued' | 'running' | 'cancelled' | 'failed' | 'done'; + startedAt: string; + endedAt?: string; + error?: string; } export interface HistoricalComparisonProgress { state: 'idle' | 'analyzing' | 'ready' | 'error'; message: string; revision?: number; + /** The job this progress belongs to. */ + jobId?: string; } export interface ProjectEvolutionRequest { @@ -156,6 +172,8 @@ export interface ProjectEvolutionProgress { revision?: number; frameIndex?: number; frameCount?: number; + /** The job this progress belongs to. */ + jobId?: string; } /** diff --git a/apps/vscode-extension/src/core/history/historicalComparisonService.ts b/apps/vscode-extension/src/core/history/historicalComparisonService.ts index 89bacb76..1123f180 100644 --- a/apps/vscode-extension/src/core/history/historicalComparisonService.ts +++ b/apps/vscode-extension/src/core/history/historicalComparisonService.ts @@ -5,7 +5,8 @@ import { AnalysisConfigurationStorage } from '../analysis/configuration/analysis import { UnifiedAnalysisSession } from '../analysis/session/analysisSession'; import { UnifiedSessionRegistry } from '../analysis/session/sessionRegistry'; import { decorateDirectoryEntries } from './gitAnalysisShared'; -import { CachedPayload, GitAnalysisSessionContext, SingleJobGate } from './gitAnalysisSessionContext'; +import { CachedPayload, GitAnalysisSessionContext } from './gitAnalysisSessionContext'; +import { JobRunner, JobTicket } from '../analysis/launch/jobRunner'; import { GitRepositoryService } from './gitRepositoryService'; import { GitAnalysisSourceCatalog } from './gitAnalysisEligibility'; import { @@ -20,10 +21,18 @@ import { const ANALYZER_CACHE_VERSION = 'historical-v1'; +/** A comparison (two revisions) longer than this is cancelled and reported (HIST-7). */ +export const HISTORICAL_COMPARISON_JOB_TIMEOUT_MS = 15 * 60 * 1000; + export class HistoricalComparisonService { private readonly gitService: GitRepositoryService; private readonly analysis: GitAnalysisSessionContext; - private readonly jobs = new SingleJobGate('comparison-busy'); + private readonly jobs = new JobRunner({ + busyCode: 'comparison-busy', + cancelledCode: 'comparison-cancelled', + timeoutCode: 'comparison-timeout', + timeoutMs: HISTORICAL_COMPARISON_JOB_TIMEOUT_MS, + }); private revision = 0; public constructor( @@ -72,6 +81,7 @@ export class HistoricalComparisonService { sources: filtered.sources, eligibility: filtered.eligibility, activeRequest: this.activeRequest ? { ...this.activeRequest } : null, + job: this.jobs.status, }; } @@ -81,11 +91,44 @@ export class HistoricalComparisonService { ); } - public async compare( + /** + * Takes the job slot synchronously (before the caller's first await), or + * returns null when a comparison is already running (HIST-9). + */ + public reserveComparison(request: HistoricalComparisonRequest): JobTicket | null { + return this.jobs.tryReserve(request); + } + + /** Runs a reserved comparison. Rejects with comparison-cancelled/-timeout when stopped. */ + public runComparison( + ticket: JobTicket, request: HistoricalComparisonRequest, onProgress?: (progress: HistoricalComparisonProgress) => void, ): Promise { - return this.jobs.run(request, () => this.executeComparison(request, onProgress)); + const tagged = onProgress + ? (progress: HistoricalComparisonProgress) => onProgress({ ...progress, jobId: ticket.id }) + : undefined; + return ticket.execute(() => this.executeComparison(request, tagged)); + } + + public compare( + request: HistoricalComparisonRequest, + onProgress?: (progress: HistoricalComparisonProgress) => void, + ): Promise { + const ticket = this.reserveComparison(request); + if (!ticket) { + return Promise.reject(new Error('comparison-busy')); + } + return this.runComparison(ticket, request, onProgress); + } + + /** Stops the running comparison and kills its children. Returns whether one ran. */ + public cancelComparison(): boolean { + return this.jobs.cancel('cancelled'); + } + + public getJobStatus() { + return this.jobs.status; } public isBusy(): boolean { @@ -106,8 +149,9 @@ export class HistoricalComparisonService { return this.compare({ ...this.activeRequest }, onProgress); } - public dispose(): Promise { - return this.analysis.dispose(); + public async dispose(): Promise { + await this.jobs.cancelAndWait('disposed'); + await this.analysis.dispose(); } private async executeComparison( diff --git a/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts b/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts new file mode 100644 index 00000000..7ed550af --- /dev/null +++ b/apps/vscode-extension/src/core/history/projectEvolutionArtifacts.ts @@ -0,0 +1,110 @@ +/** + * The files of one generated project-evolution movie: `dataN.json` per frame, + * the `data.json` bridge the scene reads, and the manifest. + * + * Pure helpers split out of ProjectEvolutionService: the service owns WHEN a + * revision becomes current (only once these files are written and the job is + * still wanted), this module owns WHAT a revision folder contains, plus two + * pure source helpers. + */ +import * as fs from 'fs'; +import * as path from 'path'; +import { CachedPayload } from './gitAnalysisSessionContext'; +import { + ComparisonSource, + GitAnalysisExclusion, + ProjectEvolutionResult, +} from './historicalComparisonModels'; + +export interface EvolutionFrameInput { + payload: CachedPayload; + source: ComparisonSource; +} + +/** Phase 4: a fresh revision folder with dataN.json per frame, the data.json bridge and the manifest. */ +export async function writeEvolutionRevision( + revision: number, + revisionDirectory: string, + valid: EvolutionFrameInput[], + excludedSources: GitAnalysisExclusion[], +): Promise { + await fs.promises.rm(revisionDirectory, { recursive: true, force: true }); + await fs.promises.mkdir(revisionDirectory, { recursive: true }); + const frames: ProjectEvolutionResult['frames'] = []; + for (let index = 0; index < valid.length; index += 1) { + const entry = valid[index]; + const fileName = `data${index + 1}.json`; + await fs.promises.writeFile( + path.join(revisionDirectory, fileName), + JSON.stringify(entry.payload.payload, null, 2), + 'utf8', + ); + frames.push({ + index, + source: entry.source, + label: entry.source.label, + date: extractSourceDate(entry.source) || '', + url: `/evolution/revision-${revision}/${fileName}`, + itemCount: entry.payload.payload.length, + missingTarget: false, + warnings: entry.payload.warnings, + }); + } + + const result: ProjectEvolutionResult = { + revision, + mode: 'project-evolution', + frames, + generatedAt: new Date().toISOString(), + manifestUrl: `/evolution/revision-${revision}/manifest.json`, + bridgeUrl: `/evolution/revision-${revision}/data.json`, + excludedSources, + }; + await copyFileAtomically( + path.join(revisionDirectory, 'data1.json'), + path.join(revisionDirectory, 'data.json'), + ); + await fs.promises.writeFile( + path.join(revisionDirectory, 'manifest.json'), + JSON.stringify(result, null, 2), + 'utf8', + ); + return result; +} + +/** The YYYY-MM-DD a Git source's description starts with, if any. */ +export function extractSourceDate(source: ComparisonSource): string | undefined { + const description = source.kind === 'gitRef' ? source.description : ''; + const match = String(description || '').match(/^(\d{4}-\d{2}-\d{2})/); + return match ? match[1] : undefined; +} + +/** Copy through a temp file + rename, so a reader never sees half a file. */ +export async function copyFileAtomically(sourcePath: string, destinationPath: string): Promise { + const tempPath = `${destinationPath}.${process.pid}.${Date.now()}.tmp`; + await fs.promises.copyFile(sourcePath, tempPath); + await fs.promises.rename(tempPath, destinationPath); +} + +/** How a frame's revision is named in progress messages. */ +export function describeRevisionType(source: ComparisonSource): string { + if (source.kind === 'workingCopy') { + return 'working copy'; + } + if (source.revisionType === 'merge') { + return 'merge'; + } + return source.revisionType || source.refType || 'commit'; +} + +/** The picker's sources plus the timeline's, one per id (the timeline wins). */ +export function mergeEvolutionSources(primary: ComparisonSource[], timeline: ComparisonSource[]): ComparisonSource[] { + const merged = new Map(); + for (const source of primary) { + merged.set(source.id, source); + } + for (const source of timeline) { + merged.set(source.id, source); + } + return Array.from(merged.values()); +} diff --git a/apps/vscode-extension/src/core/history/projectEvolutionService.ts b/apps/vscode-extension/src/core/history/projectEvolutionService.ts index dc8d62b6..cf781cd4 100644 --- a/apps/vscode-extension/src/core/history/projectEvolutionService.ts +++ b/apps/vscode-extension/src/core/history/projectEvolutionService.ts @@ -4,7 +4,8 @@ import * as vscode from 'vscode'; import { UnifiedAnalysisSession } from '../analysis/session/analysisSession'; import { UnifiedSessionRegistry } from '../analysis/session/sessionRegistry'; import { decorateDirectoryEntries } from './gitAnalysisShared'; -import { CachedPayload, GitAnalysisSessionContext, SingleJobGate } from './gitAnalysisSessionContext'; +import { CachedPayload, GitAnalysisSessionContext } from './gitAnalysisSessionContext'; +import { JobRunner, JobTicket } from '../analysis/launch/jobRunner'; import { GitRepositoryService } from './gitRepositoryService'; import { GitAnalysisSourceCatalog, @@ -12,6 +13,12 @@ import { createGitAnalysisExclusion, } from './gitAnalysisEligibility'; import { sampleTimeline } from './gitTimelineSampler'; +import { + copyFileAtomically, + describeRevisionType, + mergeEvolutionSources, + writeEvolutionRevision, +} from './projectEvolutionArtifacts'; import { ComparisonSource, GitAnalysisExclusion, @@ -25,6 +32,8 @@ const ANALYZER_CACHE_VERSION = 'project-evolution-v1'; const DEFAULT_MAX_FRAMES = 24; const DEFAULT_ANALYSIS_CONCURRENCY = 4; const TIMELINE_SCAN_LIMIT = 240; +/** A whole movie longer than this is cancelled and reported (EVO-3). */ +export const PROJECT_EVOLUTION_JOB_TIMEOUT_MS = 30 * 60 * 1000; interface ResolvedEvolutionSources { sources: ComparisonSource[]; @@ -34,9 +43,13 @@ interface ResolvedEvolutionSources { export class ProjectEvolutionService { private readonly gitService: GitRepositoryService; private readonly analysis: GitAnalysisSessionContext; - private readonly jobs = new SingleJobGate('project-evolution-busy'); + private readonly jobs = new JobRunner({ + busyCode: 'project-evolution-busy', + cancelledCode: 'project-evolution-cancelled', + timeoutCode: 'project-evolution-timeout', + timeoutMs: PROJECT_EVOLUTION_JOB_TIMEOUT_MS, + }); private revision = 0; - private cancellationRevision = 0; public constructor( private readonly context: vscode.ExtensionContext, @@ -69,7 +82,7 @@ export class ProjectEvolutionService { public async getReferences(): Promise { const references = await this.gitService.listReferences(); const timeline = await this.buildAutomaticTimeline(references); - const mergedSources = this.mergeSources(references.sources, timeline); + const mergedSources = mergeEvolutionSources(references.sources, timeline); const filtered = await this.analysis.sourceCatalog.filterSources({ repositoryRoot: references.repositoryRoot, targetRelativePath: references.targetRelativePath, @@ -84,6 +97,7 @@ export class ProjectEvolutionService { sources: filtered.sources, eligibility: filtered.eligibility, activeRequest: this.jobs.lastRequest ? { ...this.jobs.lastRequest } : null, + job: this.jobs.status, suggestedSourceIds: suggested, maxFrames: DEFAULT_MAX_FRAMES, }; @@ -93,19 +107,59 @@ export class ProjectEvolutionService { return this.jobs.isBusy(); } - public async generate( + /** + * Takes the job slot synchronously (before the caller's first await), or + * returns null when a movie is already being generated. + */ + public reserveGeneration(request: ProjectEvolutionRequest): JobTicket | null { + return this.jobs.tryReserve(request); + } + + /** Runs a reserved generation. Rejects with project-evolution-cancelled/-timeout when stopped. */ + public runGeneration( + ticket: JobTicket, request: ProjectEvolutionRequest, onProgress: (progress: ProjectEvolutionProgress) => void, ): Promise { - return this.jobs.run(request, () => this.executeEvolution(request, onProgress)); + const tagged = (progress: ProjectEvolutionProgress) => onProgress?.({ ...progress, jobId: ticket.id }); + return ticket.execute((signal) => this.executeEvolution(request, tagged, signal)); + } + + public generate( + request: ProjectEvolutionRequest, + onProgress: (progress: ProjectEvolutionProgress) => void, + ): Promise { + const ticket = this.reserveGeneration(request); + if (!ticket) { + return Promise.reject(new Error('project-evolution-busy')); + } + return this.runGeneration(ticket, request, onProgress); } - public dispose(): Promise { - return this.analysis.dispose(); + /** + * Stops the generation in flight: kills its Git and Python children and + * discards its result. The movie already generated is kept. Returns + * whether a generation was running. + */ + public cancelGeneration(): boolean { + return this.jobs.cancel('cancelled'); + } + + public getJobStatus() { + return this.jobs.status; + } + + public async dispose(): Promise { + await this.jobs.cancelAndWait('disposed'); + await this.analysis.dispose(); } + /** + * Deletes the generated movie. A generation in flight is cancelled and + * waited for first, so its late files can never land after the clear. + */ public async clearGeneratedMovie(): Promise { - this.cancellationRevision += 1; + await this.jobs.cancelAndWait('cancelled'); this.jobs.forgetLastRequest(); this.analysis.cache.clear(); if (this.revision < 1) { @@ -136,7 +190,7 @@ export class ProjectEvolutionService { const sourcePath = path.join(revisionDirectory, `data${safeFrameIndex + 1}.json`); const bridgePath = path.join(revisionDirectory, 'data.json'); await fs.promises.access(sourcePath, fs.constants.R_OK); - await this.copyFileAtomically(sourcePath, bridgePath); + await copyFileAtomically(sourcePath, bridgePath); return { revision: safeRevision, frameIndex: safeFrameIndex, @@ -147,9 +201,9 @@ export class ProjectEvolutionService { private async executeEvolution( request: ProjectEvolutionRequest, onProgress: (progress: ProjectEvolutionProgress) => void, + signal: AbortSignal, ): Promise { onProgress?.({ state: 'analyzing', message: 'Resolving project timeline...' }); - const cancellationToken = this.cancellationRevision; const resolved = await this.resolveTimelineSources(request); const sources = resolved.sources; if (sources.length < 2) { @@ -160,7 +214,7 @@ export class ProjectEvolutionService { ); } - const { analyzed, exclusionsByIndex } = await this.analyzeSources(sources, cancellationToken, onProgress); + const { analyzed, exclusionsByIndex } = await this.analyzeSources(sources, signal, onProgress); const valid = analyzed .map((payload, index) => payload ? { payload, source: sources[index] } : undefined) .filter((entry): entry is { payload: CachedPayload; source: ComparisonSource } => !!entry); @@ -178,7 +232,7 @@ export class ProjectEvolutionService { ); } - const result = await this.writeEvolutionArtifacts(valid, excludedSources); + const result = await this.writeEvolutionArtifacts(valid, excludedSources, signal); onProgress?.({ state: 'ready', message: excludedSources.length @@ -193,7 +247,7 @@ export class ProjectEvolutionService { /** Phase 2: a worker pool analyzes every source; a failure becomes that frame's exclusion. */ private async analyzeSources( sources: ComparisonSource[], - cancellationToken: number, + signal: AbortSignal, onProgress: (progress: ProjectEvolutionProgress) => void, ): Promise<{ analyzed: (CachedPayload | undefined)[]; exclusionsByIndex: (GitAnalysisExclusion | undefined)[] }> { const analyzed = new Array(sources.length); @@ -210,13 +264,13 @@ export class ProjectEvolutionService { }); const workers = Array.from({ length: concurrency }, async () => { - while (nextIndex < sources.length && cancellationToken === this.cancellationRevision) { + while (nextIndex < sources.length && !signal.aborted) { const index = nextIndex; nextIndex += 1; const source = sources[index]; onProgress?.({ state: 'analyzing', - message: `Analyzing frame ${index + 1} / ${sources.length} (${this.describeRevisionType(source)}): ${source.label}`, + message: `Analyzing frame ${index + 1} / ${sources.length} (${describeRevisionType(source)}): ${source.label}`, frameIndex: index, frameCount: sources.length, }); @@ -243,8 +297,8 @@ export class ProjectEvolutionService { error instanceof Error ? error.message : String(error), ); } - if (cancellationToken !== this.cancellationRevision) { - throw new Error('project-evolution-cleared'); + if (signal.aborted) { + return; } completed += 1; const exclusion = exclusionsByIndex[index]; @@ -252,15 +306,18 @@ export class ProjectEvolutionService { state: 'analyzing', message: exclusion ? `Discarded ${source.label}: ${exclusion.reason}` - : `Analyzed ${completed} / ${sources.length} project revisions. Last completed: ${this.describeRevisionType(source)} ${source.label}`, + : `Analyzed ${completed} / ${sources.length} project revisions. Last completed: ${describeRevisionType(source)} ${source.label}`, frameIndex: index, frameCount: sources.length, }); } }); - await Promise.all(workers); - if (cancellationToken !== this.cancellationRevision) { - throw new Error('project-evolution-cleared'); + // Every worker ends before the job does: a cancelled job leaves no + // orphan analysis writing into the cache (EVO-2). The children are + // killed by the job signal, so this returns promptly. + await Promise.allSettled(workers); + if (signal.aborted) { + throw new Error('project-evolution-cancelled'); } return { analyzed, exclusionsByIndex }; } @@ -269,52 +326,28 @@ export class ProjectEvolutionService { private async writeEvolutionArtifacts( valid: Array<{ payload: CachedPayload; source: ComparisonSource }>, excludedSources: GitAnalysisExclusion[], + signal: AbortSignal, ): Promise { - const revision = ++this.revision; + // The revision becomes current only once every file is written and + // the job is still wanted; a cancelled write leaves the previous + // movie current and removes its own folder (EVO-4). + if (signal.aborted) { + throw new Error('project-evolution-cancelled'); + } + const revision = this.revision + 1; const evolutionDirectory = path.join(this.staticRoot, 'evolution'); const revisionDirectory = path.join(evolutionDirectory, `revision-${revision}`); - await fs.promises.rm(revisionDirectory, { recursive: true, force: true }); - await fs.promises.mkdir(revisionDirectory, { recursive: true }); - const frames: ProjectEvolutionResult['frames'] = []; - for (let index = 0; index < valid.length; index += 1) { - const entry = valid[index]; - const fileName = `data${index + 1}.json`; - await fs.promises.writeFile( - path.join(revisionDirectory, fileName), - JSON.stringify(entry.payload.payload, null, 2), - 'utf8', - ); - frames.push({ - index, - source: entry.source, - label: entry.source.label, - date: this.extractDate(entry.source) || '', - url: `/evolution/revision-${revision}/${fileName}`, - itemCount: entry.payload.payload.length, - missingTarget: false, - warnings: entry.payload.warnings, - }); + try { + const result = await writeEvolutionRevision(revision, revisionDirectory, valid, excludedSources); + if (signal.aborted) { + throw new Error('project-evolution-cancelled'); + } + this.revision = revision; + return result; + } catch (error) { + await fs.promises.rm(revisionDirectory, { recursive: true, force: true }).catch(() => undefined); + throw error; } - - const result: ProjectEvolutionResult = { - revision, - mode: 'project-evolution', - frames, - generatedAt: new Date().toISOString(), - manifestUrl: `/evolution/revision-${revision}/manifest.json`, - bridgeUrl: `/evolution/revision-${revision}/data.json`, - excludedSources, - }; - await this.copyFileAtomically( - path.join(revisionDirectory, 'data1.json'), - path.join(revisionDirectory, 'data.json'), - ); - await fs.promises.writeFile( - path.join(revisionDirectory, 'manifest.json'), - JSON.stringify(result, null, 2), - 'utf8', - ); - return result; } private async resolveTimelineSources(request: ProjectEvolutionRequest): Promise { @@ -427,20 +460,6 @@ export class ProjectEvolutionService { return sampleTimeline(sources, maxFrames, sources[sources.length - 1] || null); } - private mergeSources(primary: ComparisonSource[], timeline: ComparisonSource[]): ComparisonSource[] { - const merged = new Map(); - for (const source of primary) { - merged.set(source.id, source); - } - for (const source of timeline) { - merged.set(source.id, source); - } - return Array.from(merged.values()); - } - - - - private decoratePayload( payload: Record[], session: UnifiedAnalysisSession, @@ -457,22 +476,6 @@ export class ProjectEvolutionService { })); } - private extractDate(source: ComparisonSource): string | undefined { - const description = source.kind === 'gitRef' ? source.description : ''; - const match = String(description || '').match(/^(\d{4}-\d{2}-\d{2})/); - return match ? match[1] : undefined; - } - - private describeRevisionType(source: ComparisonSource): string { - if (source.kind === 'workingCopy') { - return 'working copy'; - } - if (source.revisionType === 'merge') { - return 'merge'; - } - return source.revisionType || source.refType || 'commit'; - } - private resolveRevisionDirectory(revision: number): string { const evolutionDirectory = path.resolve(this.staticRoot, 'evolution'); const revisionDirectory = path.resolve(evolutionDirectory, `revision-${revision}`); @@ -483,12 +486,6 @@ export class ProjectEvolutionService { return revisionDirectory; } - private async copyFileAtomically(sourcePath: string, destinationPath: string): Promise { - const tempPath = `${destinationPath}.${process.pid}.${Date.now()}.tmp`; - await fs.promises.copyFile(sourcePath, tempPath); - await fs.promises.rename(tempPath, destinationPath); - } - private getSession(): UnifiedAnalysisSession { const session = UnifiedSessionRegistry.getInstance(this.context).getSession(this.sessionId); if (!session || session.analysisMode !== 'XR') { diff --git a/apps/vscode-extension/src/core/server/analysis/analysisBridgeReplies.ts b/apps/vscode-extension/src/core/server/analysis/analysisBridgeReplies.ts index cd0c7777..24fa9cb6 100644 --- a/apps/vscode-extension/src/core/server/analysis/analysisBridgeReplies.ts +++ b/apps/vscode-extension/src/core/server/analysis/analysisBridgeReplies.ts @@ -1,4 +1,5 @@ import { CollaborationApplicationMessageContext } from '../collaboration/collaborationRoomServer'; +import { JobCancelledError } from '../../analysis/launch/jobRunner'; import { GitAnalysisSourceError } from '../../history/gitAnalysisEligibility'; import { AnalysisFeatureHost } from './analysisFeatureHost'; @@ -67,10 +68,23 @@ export async function replyWithReferences( * The error payload of a failed start: a Git source error reports its own * code, any other Error its message, anything else the fallback code. */ +/** What the room reads when a job is stopped by its deadline. */ +const JOB_TIMEOUT_MESSAGES: Readonly> = Object.freeze({ + 'project-evolution-timeout': 'Generating the project evolution movie took more than 30 minutes and was stopped.', + 'comparison-timeout': 'The historical comparison took more than 15 minutes and was stopped.', + 'dependency-graph-timeout': 'The dependency analysis took more than 10 minutes and was stopped.', +}); + export function describeBridgeError( error: unknown, fallbackCode: string, ): { code: string; message: string } { + if (error instanceof JobCancelledError) { + return { + code: error.message, + message: JOB_TIMEOUT_MESSAGES[error.message] || 'The analysis was stopped.', + }; + } return { code: error instanceof GitAnalysisSourceError ? error.code diff --git a/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts b/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts index c3e61eb4..051e3826 100644 --- a/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts +++ b/apps/vscode-extension/src/core/server/analysis/analysisMessageRouter.ts @@ -87,9 +87,15 @@ export class AnalysisMessageRouter { if (message.type === 'historical-comparison-start') { return this.historicalComparison.handleHistoricalComparisonStartMessage(messageContext, message); } + if (message.type === 'historical-comparison-cancel') { + return this.historicalComparison.handleHistoricalComparisonCancelMessage(messageContext); + } if (this.projectEvolutionService && message.type === 'project-evolution-references-request') { return this.projectEvolution.handleProjectEvolutionReferencesMessage(messageContext); } + if (this.projectEvolutionService && message.type === 'project-evolution-cancel') { + return this.projectEvolution.handleProjectEvolutionCancelMessage(messageContext); + } if (this.projectEvolutionService && message.type === 'project-evolution-clear') { return this.projectEvolution.handleProjectEvolutionClearMessage(messageContext); } diff --git a/apps/vscode-extension/src/core/server/analysis/historicalComparisonBridge.ts b/apps/vscode-extension/src/core/server/analysis/historicalComparisonBridge.ts index 51744ba6..83e646e3 100644 --- a/apps/vscode-extension/src/core/server/analysis/historicalComparisonBridge.ts +++ b/apps/vscode-extension/src/core/server/analysis/historicalComparisonBridge.ts @@ -4,7 +4,8 @@ import { CollaborationMessage, } from '../collaboration/collaborationRoomServer'; import { GitAnalysisSourceError } from '../../history/gitAnalysisEligibility'; -import { HistoricalComparisonRequest } from '../../history/historicalComparisonModels'; +import { JobCancelledError, JobTicket } from '../../analysis/launch/jobRunner'; +import { HistoricalComparisonRequest, HistoricalComparisonResult } from '../../history/historicalComparisonModels'; import { analysisRefreshCoordinator } from '../../analysis/refresh/analysisRefreshCoordinator'; import { SessionWatcherManager } from '../../analysis/watchers/sessionWatcherManager'; import { readJsonBody, sendErrorResponse, sendJsonResponse } from '../http/httpRespond'; @@ -82,10 +83,6 @@ export class HistoricalComparisonBridge { sendErrorResponse(res, 404, 'Historical comparison is not available for this session.'); return; } - if (this.historicalComparisonService.isBusy()) { - sendErrorResponse(res, 409, 'A historical comparison is already running.'); - return; - } let request: HistoricalComparisonRequest; try { const payload = await readJsonBody(req); @@ -97,11 +94,23 @@ export class HistoricalComparisonBridge { sendErrorResponse(res, 400, 'Invalid request body'); return; } - sendJsonResponse(res, 202, { accepted: true }); + // Reserved with no await between the check and the take (HIST-9). + const service = this.historicalComparisonService; + const ticket = service.reserveComparison(request); + if (!ticket) { + sendErrorResponse(res, 409, 'A historical comparison is already running.'); + return; + } + sendJsonResponse(res, 202, { accepted: true, jobId: ticket.id }); void (async () => { try { - await SessionWatcherManager.reconcileSession(this.host.sessionId); - const result = await this.historicalComparisonService!.compare(request, (progress) => { + try { + await SessionWatcherManager.reconcileSession(this.host.sessionId); + } catch (error) { + ticket.release(); + throw error; + } + const result = await service.runComparison(ticket, request, (progress) => { this.host.notifyLivePanelHistoricalProgress(progress); }); this.host.notifyLivePanelHistoricalUpdated(result.revision); @@ -129,6 +138,28 @@ export class HistoricalComparisonBridge { return true; } + /** Stops the running comparison for the whole room; the previous result stays. */ + public handleHistoricalComparisonCancelMessage( + messageContext: CollaborationApplicationMessageContext, + ): boolean { + if (!this.historicalComparisonService) { + return false; + } + const job = this.historicalComparisonService.getJobStatus(); + if (!this.historicalComparisonService.cancelComparison()) { + messageContext.send({ + type: 'historical-comparison-cancelled', + payload: { message: 'No historical comparison is running.', jobId: job?.id ?? null }, + }); + return true; + } + messageContext.broadcast({ + type: 'historical-comparison-cancelled', + payload: { message: 'Historical comparison cancelled.', jobId: job?.id ?? null }, + }); + return true; + } + public handleHistoricalComparisonStartMessage( messageContext: CollaborationApplicationMessageContext, message: CollaborationMessage, @@ -136,7 +167,15 @@ export class HistoricalComparisonBridge { if (!this.historicalComparisonService) { return false; } - if (this.historicalComparisonService.isBusy()) { + const request: HistoricalComparisonRequest = { + leftSourceId: String(message.payload?.leftSourceId || ''), + rightSourceId: String(message.payload?.rightSourceId || ''), + }; + // Reserve BEFORE the first await: two starts can never both pass, and + // the loser hears "busy" alone (HIST-9, LAUNCHER-11). + const service = this.historicalComparisonService; + const ticket = service.reserveComparison(request); + if (!ticket) { messageContext.send({ type: 'historical-comparison-error', payload: { @@ -146,15 +185,6 @@ export class HistoricalComparisonBridge { }); return true; } - const request: HistoricalComparisonRequest = { - leftSourceId: String(message.payload?.leftSourceId || ''), - rightSourceId: String(message.payload?.rightSourceId || ''), - }; - analysisRefreshCoordinator.setRefreshEnabled( - this.host.sessionId, - 'historical-compare', - request.leftSourceId === 'working-copy' || request.rightSourceId === 'working-copy', - ); const currentView = this.host.getAnalysisViewState(); if (currentView?.mode !== 'historical-compare') { this.host.changeAnalysisViewMode('historical-compare', 'historical.selection'); @@ -163,7 +193,19 @@ export class HistoricalComparisonBridge { ? currentView : this.host.getAnalysisViewState(); const operationViewRevision = operationView?.viewRevision; - void (async () => { + void this.runComparisonJob(messageContext, ticket, request, operationViewRevision); + return true; + } + + /** Runs a reserved comparison and publishes its result, or its error, to the room. */ + private async runComparisonJob( + messageContext: CollaborationApplicationMessageContext, + ticket: JobTicket, + request: HistoricalComparisonRequest, + operationViewRevision: number | undefined, + ): Promise { + const service = this.historicalComparisonService!; + try { try { await SessionWatcherManager.reconcileSession( this.host.sessionId, @@ -172,40 +214,54 @@ export class HistoricalComparisonBridge { this.host.sessionId, 'historical-compare', ); - const result = await this.historicalComparisonService!.compare(request, (progress) => { - messageContext.broadcast({ - type: 'historical-comparison-progress', - payload: progress, - }); - }); - messageContext.upsertSharedEntity({ - entityKind: 'historical-comparison', - entityId: 'main', - mode: 'historical-compare', - result, - }); - analysisRefreshCoordinator.setSnapshotAvailable( - this.host.sessionId, - 'historical-compare', - true, - ); - if (operationViewRevision !== undefined) { - this.host.updateAnalysisViewIfCurrent( - 'historical-compare', - operationViewRevision, - 'historical.mapping', - ); - } } catch (error) { - if (error instanceof GitAnalysisSourceError) { - await broadcastFilteredGitReferences(this.host, messageContext); - } + ticket.release(); + throw error; + } + const result = await service.runComparison(ticket, request, (progress) => { messageContext.broadcast({ - type: 'historical-comparison-error', - payload: describeBridgeError(error, 'comparison-failed'), + type: 'historical-comparison-progress', + payload: progress, }); + }); + // The live-refresh flag describes the request that SUCCEEDED; + // a failed request no longer leaves it describing itself + // while the room still shows the previous one (HIST-9). + analysisRefreshCoordinator.setRefreshEnabled( + this.host.sessionId, + 'historical-compare', + request.leftSourceId === 'working-copy' || request.rightSourceId === 'working-copy', + ); + messageContext.upsertSharedEntity({ + entityKind: 'historical-comparison', + entityId: 'main', + mode: 'historical-compare', + result, + }); + analysisRefreshCoordinator.setSnapshotAvailable( + this.host.sessionId, + 'historical-compare', + true, + ); + if (operationViewRevision !== undefined) { + this.host.updateAnalysisViewIfCurrent( + 'historical-compare', + operationViewRevision, + 'historical.mapping', + ); } - })(); - return true; + } catch (error) { + if (error instanceof JobCancelledError && error.reason !== 'timeout') { + // The cancel handler tells the room itself. + return; + } + if (error instanceof GitAnalysisSourceError) { + await broadcastFilteredGitReferences(this.host, messageContext); + } + messageContext.broadcast({ + type: 'historical-comparison-error', + payload: describeBridgeError(error, 'comparison-failed'), + }); + } } } diff --git a/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts b/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts index 2b5fed97..012d61df 100644 --- a/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts +++ b/apps/vscode-extension/src/core/server/analysis/projectEvolutionBridge.ts @@ -3,7 +3,8 @@ import { CollaborationMessage, } from '../collaboration/collaborationRoomServer'; import { GitAnalysisSourceError } from '../../history/gitAnalysisEligibility'; -import { ProjectEvolutionRequest } from '../../history/historicalComparisonModels'; +import { JobCancelledError, JobTicket } from '../../analysis/launch/jobRunner'; +import { ProjectEvolutionRequest, ProjectEvolutionResult } from '../../history/historicalComparisonModels'; import { analysisRefreshCoordinator } from '../../analysis/refresh/analysisRefreshCoordinator'; import { SessionWatcherManager } from '../../analysis/watchers/sessionWatcherManager'; import { AnalysisFeatureHost } from './analysisFeatureHost'; @@ -40,6 +41,33 @@ export class ProjectEvolutionBridge { return true; } + /** + * Cancel is not Clear (EVO-2): it stops the generation in flight, kills + * its Git and Python children and discards its result, and keeps the + * movie already generated. Every client is told, so the whole room stops + * showing progress. + */ + public handleProjectEvolutionCancelMessage( + messageContext: CollaborationApplicationMessageContext, + ): boolean { + if (!this.projectEvolutionService) { + return false; + } + const job = this.projectEvolutionService.getJobStatus(); + if (!this.projectEvolutionService.cancelGeneration()) { + messageContext.send({ + type: 'project-evolution-cancelled', + payload: { message: 'No project evolution movie is being generated.', jobId: job?.id ?? null }, + }); + return true; + } + messageContext.broadcast({ + type: 'project-evolution-cancelled', + payload: { message: 'Project evolution generation cancelled.', jobId: job?.id ?? null }, + }); + return true; + } + public async handleProjectEvolutionClearMessage( messageContext: CollaborationApplicationMessageContext, ): Promise { @@ -134,7 +162,14 @@ export class ProjectEvolutionBridge { if (!this.projectEvolutionService) { return false; } - if (this.projectEvolutionService.isBusy()) { + const payload = message.payload || {}; + const request = parseEvolutionRequest(payload); + // Reserve the job slot BEFORE the first await, so two starts (a + // double tap, two collaborators) can never both pass; the loser hears + // "busy" alone, the room keeps following the running job (LAUNCHER-11). + const service = this.projectEvolutionService; + const ticket = service.reserveGeneration(request); + if (!ticket) { messageContext.send({ type: 'project-evolution-error', payload: { @@ -144,24 +179,6 @@ export class ProjectEvolutionBridge { }); return true; } - const payload = message.payload || {}; - const request: ProjectEvolutionRequest = { - mode: payload.mode === 'range' || payload.mode === 'manual' - ? payload.mode - : 'auto', - startSourceId: typeof payload.startSourceId === 'string' - ? payload.startSourceId - : undefined, - endSourceId: typeof payload.endSourceId === 'string' - ? payload.endSourceId - : undefined, - sourceIds: Array.isArray(payload.sourceIds) - ? payload.sourceIds.map((value: unknown) => String(value)).filter(Boolean) - : undefined, - maxFrames: Number.isFinite(Number(payload.maxFrames)) - ? Number(payload.maxFrames) - : undefined, - }; analysisRefreshCoordinator.setRefreshEnabled( this.host.sessionId, 'project-evolution', @@ -175,48 +192,84 @@ export class ProjectEvolutionBridge { ? currentView : this.host.getAnalysisViewState(); const operationViewRevision = operationView?.viewRevision; - void (async () => { + void this.runGenerationJob(messageContext, ticket, request, operationViewRevision); + return true; + } + + /** Runs a reserved generation and publishes its movie, or its error, to the room. */ + private async runGenerationJob( + messageContext: CollaborationApplicationMessageContext, + ticket: JobTicket, + request: ProjectEvolutionRequest, + operationViewRevision: number | undefined, + ): Promise { + const service = this.projectEvolutionService!; + try { try { await SessionWatcherManager.reconcileSession( this.host.sessionId, ); - const result = await this.projectEvolutionService!.generate(request, (progress) => { - messageContext.broadcast({ - type: 'project-evolution-progress', - payload: progress, - }); - }); - messageContext.upsertSharedEntity({ - entityKind: 'project-evolution', - entityId: 'main', - mode: 'project-evolution', - result, - }); - analysisRefreshCoordinator.setSnapshotAvailable( - this.host.sessionId, - 'project-evolution', - true, - ); - if (operationViewRevision !== undefined) { - this.host.updateAnalysisViewIfCurrent( - 'project-evolution', - operationViewRevision, - 'project-evolution', - ); - } } catch (error) { - if (error instanceof Error && error.message === 'project-evolution-cleared') { - return; - } - if (error instanceof GitAnalysisSourceError) { - await broadcastFilteredGitReferences(this.host, messageContext); - } + ticket.release(); + throw error; + } + const result = await service.runGeneration(ticket, request, (progress) => { messageContext.broadcast({ - type: 'project-evolution-error', - payload: describeBridgeError(error, 'project-evolution-failed'), + type: 'project-evolution-progress', + payload: progress, }); + }); + messageContext.upsertSharedEntity({ + entityKind: 'project-evolution', + entityId: 'main', + mode: 'project-evolution', + result, + }); + analysisRefreshCoordinator.setSnapshotAvailable( + this.host.sessionId, + 'project-evolution', + true, + ); + if (operationViewRevision !== undefined) { + this.host.updateAnalysisViewIfCurrent( + 'project-evolution', + operationViewRevision, + 'project-evolution', + ); } - })(); - return true; + } catch (error) { + if (error instanceof JobCancelledError && error.reason !== 'timeout') { + // Cancel and Clear tell the room themselves. + return; + } + if (error instanceof GitAnalysisSourceError) { + await broadcastFilteredGitReferences(this.host, messageContext); + } + messageContext.broadcast({ + type: 'project-evolution-error', + payload: describeBridgeError(error, 'project-evolution-failed'), + }); + } } } + +/** The request a start message describes, with every field validated. */ +function parseEvolutionRequest(payload: Record): ProjectEvolutionRequest { + return { + mode: payload.mode === 'range' || payload.mode === 'manual' + ? payload.mode + : 'auto', + startSourceId: typeof payload.startSourceId === 'string' + ? payload.startSourceId + : undefined, + endSourceId: typeof payload.endSourceId === 'string' + ? payload.endSourceId + : undefined, + sourceIds: Array.isArray(payload.sourceIds) + ? payload.sourceIds.map((value: unknown) => String(value)).filter(Boolean) + : undefined, + maxFrames: Number.isFinite(Number(payload.maxFrames)) + ? Number(payload.maxFrames) + : undefined, + }; +} diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js index 17644706..66f70989 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/compareFlowAndMessages.js @@ -40,6 +40,27 @@ } } + function setComparisonJobRunning(running) { + state.jobRunning = !!running; + refs.compareButton?.querySelector?.('a-text')?.setAttribute?.('value', state.jobRunning ? 'Cancel' : 'Compare'); + } + + function compareOrCancel() { + if (state.jobRunning && !getClient()?.isOfflineExport?.()) { + setStatus('Cancelling the historical comparison...', 'info'); + if (!getClient()?.sendMessage?.('historical-comparison-cancel', {})) { + setStatus('Could not reach VS Code to cancel the comparison.', 'error'); + } + return; + } + startComparison(); + } + + function handleCancelled(message) { + setComparisonJobRunning(false); + setStatus(message?.payload?.message || 'Historical comparison cancelled.', 'info'); + } + function startComparison() { // Offline with exported git payloads, Compare works for real: validate // the selection like online and compose the comparison locally. Without @@ -121,6 +142,12 @@ // Category/paging now live inside the shared picker; the panel only feeds // it the references and keeps the selection detail. renderReferences(); + var job = state.references?.job; + if (job && (job.state === 'running' || job.state === 'queued')) { + setComparisonJobRunning(true); + setStatus('A historical comparison is running for the room...', 'info'); + return; + } var excludedCount = Number(state.references?.eligibility?.excludedSources?.length || 0); setStatus( excludedCount @@ -131,18 +158,25 @@ } function handleProgress(message) { + setComparisonJobRunning(message?.payload?.state === 'analyzing'); setStatus(message?.payload?.message || 'Analyzing...', 'info'); } function handleError(message) { var code = String(message?.payload?.code || ''); var rawMessage = String(message?.payload?.message || ''); + // "Busy" answers only this participant: the room's comparison runs on. + if (code !== 'comparison-busy') { + setComparisonJobRunning(false); + } var friendlyMessage = code === 'references-unavailable' || /not a git repository|git-command-failed/i.test(rawMessage) ? 'History compare requires an analysis inside a local Git repository.' : code === 'comparison-busy' ? 'Another comparison is already being generated.' - : code === 'comparison-source-no-data' + : code === 'comparison-source-no-data' || code === 'comparison-timeout' ? rawMessage + : /git-command-timeout|revision-analysis-timeout/i.test(rawMessage) + ? 'A Git or analysis step took too long and was stopped. Please try again.' : 'Historical comparison failed. Please try again.'; setStatus(friendlyMessage, 'error'); } @@ -153,6 +187,7 @@ if (!snapshot || !snapshot.result) { return; } + setComparisonJobRunning(false); if (!isHistoricalModeActiveOrActivating()) { state.result = snapshot.result; return; diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js index 71160140..959619c7 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/liveRefreshAndRegistration.js @@ -153,6 +153,7 @@ state.disposables.push(client.onMessage?.('historical-comparison-references', handleReferences)); state.disposables.push(client.onMessage?.('historical-comparison-progress', handleProgress)); state.disposables.push(client.onMessage?.('historical-comparison-error', handleError)); + state.disposables.push(client.onMessage?.('historical-comparison-cancelled', handleCancelled)); client.registerEntityRuntime?.({ entityKind: ENTITY_KIND, entityId: ENTITY_ID, diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/selectionPanel.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/selectionPanel.js index 972acd2b..6bf4ceb6 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/selectionPanel.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/selectionPanel.js @@ -61,7 +61,10 @@ refs.sourceRoot.appendChild(buildButton('Back', '-0.75 -2.4 0.02', 1.3, 0.38, function () { root.CodeXRAnalysisModeRuntime?.openSelector?.(); }, '#475569')); - refs.sourceRoot.appendChild(buildButton('Compare', '0.75 -2.4 0.02', 1.3, 0.38, startComparison, '#be123c')); + // Reads "Cancel" while a comparison runs for the room (S6): the same + // place, a separate action, the previous comparison is kept. + refs.compareButton = buildButton('Compare', '0.75 -2.4 0.02', 1.3, 0.38, compareOrCancel, '#be123c'); + refs.sourceRoot.appendChild(refs.compareButton); refs.panel.appendChild(refs.sourceRoot); refs.panel.appendChild(refs.status); diff --git a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/stateAndInteractionGuards.js b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/stateAndInteractionGuards.js index de524e49..aef36e75 100644 --- a/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/stateAndInteractionGuards.js +++ b/apps/vscode-extension/templates/components/codexr/historical-comparison/historicalComparisonRuntime/stateAndInteractionGuards.js @@ -7,6 +7,8 @@ var state = { initialized: false, panelVisible: false, + // A comparison job is running for the room: Compare reads "Cancel". + jobRunning: false, references: null, activeSide: 'left', availability: 'loading', diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js index c2957c57..4ac4b868 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/frameApplication.js @@ -68,6 +68,7 @@ } var previousRevision = Number(state.result?.revision || 0); state.result = shared.result; + state.jobRunning = false; state.frameIndex = 0; if (previousRevision && previousRevision !== Number(shared.result.revision || 0)) { releaseEvolutionVisualization(); @@ -149,6 +150,9 @@ function applyClearedState(message) { invalidateEvolutionView('project-evolution-cleared'); + state.jobRunning = false; + state.generating = false; + renderGenerationProgress({ state: 'idle' }); stop(); state.result = null; state.frameIndex = 0; diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js index 975c3a0c..4db3ba27 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/overlayAndPanel.js @@ -120,7 +120,7 @@ refs.panel.appendChild(refs.progressRoot); refs.generateButton = primaryActionButton('Generate movie', '0 0 0.02', startSelectedTimeline); refs.panel.appendChild(refs.generateButton); - refs.clearButton = button('Clear movie', '0 0 0.02', 1.5, clearMovie, '#7f1d1d', { + refs.clearButton = button('Clear movie', '0 0 0.02', 1.5, clearOrCancel, '#7f1d1d', { height: 0.4, textWidth: 1.9, wrapCount: 14 diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js index aa72e719..a55ca26d 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js @@ -19,6 +19,10 @@ // render() runs before the panel exists (activate with no movie) and during // deactivate, so every node here is optional all the way down. refs.playButton?.querySelector?.('a-text')?.setAttribute?.('value', state.playing ? 'Pause' : 'Play'); + // One button, two separate actions (EVO-2): while a movie is being + // generated it cancels the generation (the previous movie is kept); + // otherwise it clears the movie. + refs.clearButton?.querySelector?.('a-text')?.setAttribute?.('value', state.jobRunning ? 'Cancel' : 'Clear movie'); } function updateNowShowing(frame, frameCount) { @@ -245,6 +249,36 @@ client()?.sendMessage?.('project-evolution-start', request); } + function clearOrCancel() { + if (state.jobRunning) { + cancelGeneration(); + return; + } + clearMovie(); + } + + function cancelGeneration() { + setStatus('Cancelling the project evolution generation...', 'info'); + if (!client()?.sendMessage?.('project-evolution-cancel', {})) { + setStatus('Could not reach VS Code to cancel the generation.', 'error'); + } + } + + // The server stopped the generation (any participant pressed Cancel). The + // movie generated before it, if any, is still the current one: show it again. + function handleCancelled(message) { + var payload = unwrapPayload(message) || {}; + var wasGenerating = state.jobRunning; + state.generating = false; + state.jobRunning = false; + renderGenerationProgress({ state: 'idle' }); + setStatus(payload.message || 'Project evolution generation cancelled.', 'info'); + render(); + if (wasGenerating && state.result && isEvolutionModeActiveOrActivating()) { + void Promise.resolve(seek(state.frameIndex)).catch(function () {}); + } + } + function clearMovie() { // Clearing deletes server-side files; offline it would only wipe the // replay this export exists to provide. With exported git payloads, @@ -268,6 +302,16 @@ function handleReferences(message) { var payload = unwrapPayload(message); state.references = payload || null; + // A participant who opens the panel mid-generation sees the room's job, + // not an idle panel with a Generate button that would only answer "busy". + var job = payload && payload.job; + if (job && (job.state === 'running' || job.state === 'queued')) { + state.jobRunning = true; + refs.picker?.setReferences(state.references); + setStatus('A project evolution movie is being generated for the room...', 'info'); + render(); + return; + } refs.picker?.setReferences(state.references); var count = (refs.picker?.getVisibleSources?.() || []).filter(function (source) { return source && source.kind === 'gitRef'; @@ -289,12 +333,22 @@ setStatus(payload.message || '', payload.state === 'error' ? 'error' : 'info'); // Drives both the progress bar and whether the panel reserves room for it. state.generating = payload.state === 'analyzing' && Number(payload.frameCount) > 0; + // Any analyzing step, the timeline resolution included, is a job the + // room can cancel. + state.jobRunning = payload.state === 'analyzing'; renderGenerationProgress(payload); render(); } function handleError(message) { var payload = unwrapPayload(message); + // "Busy" answers only this participant; the room's job is still running. + if (payload && payload.code !== 'project-evolution-busy') { + state.jobRunning = false; + state.generating = false; + renderGenerationProgress({ state: 'idle' }); + render(); + } state.pendingFrameApply?.reject?.(new Error(payload.message || 'Project evolution failed.')); state.pendingFrameApply = null; stop(); diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js index 5fd9ba35..2e6272ee 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/stateAndUiAtoms.js @@ -41,6 +41,9 @@ // True while the server is building the movie: shows the progress bar and // makes the panel reserve room for it. generating: false, + // A generation job (any phase) is running for the room: the Clear button + // then reads "Cancel" and stops the job instead of deleting the movie. + jobRunning: false, // True while a confirmed chart/axis change is being applied to the current // frame: playback and seeking stay locked until it settles. applyingMapping: false, diff --git a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js index 57790767..d52573b6 100644 --- a/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/project-evolution/projectEvolutionRuntime/transportAndRegistration.js @@ -145,17 +145,13 @@ } } - // Leaving the mode, per scenario: a generation in flight is CANCELLED and - // everything cleaned (the server aborts its workers on project-evolution-clear - // and broadcasts -cleared, which resets the local state too); a generated - // movie is paused, remembering whether it was playing so re-entry resumes it. + // Leaving the mode never changes the server's state (EVO-2): a generation + // in flight keeps running for the room (only Cancel stops it) and its movie + // arrives as the shared entity; a generated movie is paused, remembering + // whether it was playing so re-entry resumes it. function releaseEvolutionOnLeave() { invalidateEvolutionView('project-evolution-view-released'); - if (state.generating) { - state.generating = false; - renderGenerationProgress({ state: 'idle' }); - clearMovie(); - } else { + if (!state.generating) { state.resumePlayback = state.resumePlayback || state.playing; } stop(); @@ -177,6 +173,7 @@ state.disposables.push(runtimeClient?.onMessage?.('project-evolution-references', handleReferences)); state.disposables.push(runtimeClient?.onMessage?.('project-evolution-progress', handleProgress)); state.disposables.push(runtimeClient?.onMessage?.('project-evolution-error', handleError)); + state.disposables.push(runtimeClient?.onMessage?.('project-evolution-cancelled', handleCancelled)); state.disposables.push(runtimeClient?.onMessage?.('project-evolution-frame-applied', handleFrameApplied)); state.disposables.push(runtimeClient?.onMessage?.('project-evolution-cleared', function (message) { applyClearedState(unwrapPayload(message).message || 'Project evolution movie cleared.'); diff --git a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs index de36bab3..8c259522 100644 --- a/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs +++ b/apps/vscode-extension/test/analysis/dependencyGraph.test.cjs @@ -596,7 +596,8 @@ test('dependency server preserves cached datasets and no longer accepts granular assert.doesNotMatch(server, /allowedGranularity/); assert.doesNotMatch(models, /DependencyGraphGranularity/); assert.doesNotMatch(service, /void job\.finally/); - assert.match(service, /void job\.then\(clearActiveJob, clearActiveJob\)/); + // A start while one runs joins it (S6: the job runner owns the slot). + assert.match(service, /this\.jobs\.current\(\)/); }); test('python dependency packages are pinned centrally', () => { diff --git a/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs b/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs index 44605bd8e..4af39cb5 100644 --- a/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs +++ b/apps/vscode-extension/test/analysis/gitHistoryServices.test.cjs @@ -100,6 +100,7 @@ function walkFiles(directory) { function createAnalyzer() { const analyzer = { calls: [], + killed: [], respond: null, async run(session) { analyzer.calls.push({ @@ -196,11 +197,33 @@ async function withServices(options, body) { const sessions = new Map((options.sessions || []).map((session) => [session.id, session])); try { await withFakeVscode(fake, async ({ requireOut }) => { + // Loaded first, so every service shares this signal context and + // this JobCancelledError class. + const launch = requireOut('core/analysis/launch/launchControl.js'); + const { JobCancelledError } = requireOut('core/analysis/launch/jobRunner.js'); const { UnifiedSessionRegistry } = requireOut('core/analysis/session/sessionRegistry.js'); UnifiedSessionRegistry.getInstance = () => ({ getSession: (id) => sessions.get(id) }); const { ExecutePython } = requireOut('core/analysis/python/executePython.js'); + // Like the real spawner, the stub "kills" its analysis when the + // job (or revision watchdog) signal it runs under aborts. ExecutePython.prototype.executeAnalysis = function stubbedAnalysis(session) { - return analyzer.run(session); + const work = analyzer.run(session); + const signal = launch.currentLaunchSignal(); + if (!signal) { + return work; + } + return new Promise((resolve, reject) => { + const kill = () => { + analyzer.killed.push(session.id); + reject(new Error('python-process-killed')); + }; + if (signal.aborted) { + kill(); + return; + } + signal.addEventListener('abort', kill, { once: true }); + work.then(resolve, reject); + }); }; const { AnalysisConfigurationStorage } = requireOut('core/analysis/configuration/analysisConfigurationStorage.js'); AnalysisConfigurationStorage.getInstance = () => ({ @@ -226,6 +249,7 @@ async function withServices(options, body) { analyzer, materialized, requireOut, + JobCancelledError, }); }); } finally { @@ -406,7 +430,10 @@ test('historical compare (directory): decorated payloads, delta, artifacts and t `Analyzing ${result.right.source.label}...`, 'Historical comparison ready.', ]); - assert.deepEqual(progress.at(-1), { state: 'ready', message: 'Historical comparison ready.', revision: 1 }); + // Every progress names the job it belongs to (S6). + assert.match(progress.at(-1).jobId, /^job-/); + assert.ok(progress.every((entry) => entry.jobId === progress.at(-1).jobId)); + assert.deepEqual({ ...progress.at(-1), jobId: undefined }, { state: 'ready', message: 'Historical comparison ready.', revision: 1, jobId: undefined }); // Second run: same commit, cached analysis (no analyzer call, no // materialization); the working copy is re-read every time. @@ -603,6 +630,126 @@ test('busy codes: one job per service; a second start is refused until the first }); }); +async function waitFor(predicate, timeoutMs = 5000) { + const started = Date.now(); + while (!predicate()) { + if (Date.now() - started > timeoutMs) { + throw new Error('waitFor timed out'); + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} + +test('S6: cancelling a movie kills its analyses, discards it, frees the job and keeps the previous movie', async () => { + const session = makeSession(); + writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); + await withServices({ sessions: [session] }, async ({ ProjectEvolutionService, JobCancelledError, context, analyzer }) => { + const evolution = new ProjectEvolutionService(context, session.id, session.staticRoot, createCatalog()); + const refs = await evolution.getReferences(); + const commitId = (sha) => refs.sources.find((s) => s.kind === 'gitRef' && s.commitSha === sha && s.refType === 'commit').id; + const first = await evolution.generate({ mode: 'manual', sourceIds: [commitId(fixture.shas.c1), 'working-copy'] }, () => {}); + assert.equal(first.revision, 1); + + analyzer.respond = () => new Promise(() => {}); // hangs until killed + const progress = []; + const callsBefore = analyzer.calls.length; + const movie = evolution.generate({ mode: 'manual', sourceIds: [commitId(fixture.shas.c2), commitId(fixture.shas.c3)] }, (entry) => progress.push(entry)); + await waitFor(() => analyzer.calls.length > callsBefore); + assert.equal(evolution.getJobStatus().state, 'running'); + assert.equal(evolution.cancelGeneration(), true); + await assert.rejects(movie, (error) => error instanceof JobCancelledError && error.reason === 'cancelled' && error.message === 'project-evolution-cancelled'); + assert.ok(analyzer.killed.length >= 1, 'the running analyses were killed'); + await waitFor(() => !evolution.isBusy()); + assert.equal(evolution.getJobStatus().state, 'cancelled'); + assert.equal(evolution.cancelGeneration(), false, 'nothing left to cancel'); + + // No second revision was written; the first movie is still current. + assert.deepEqual(fs.readdirSync(path.join(session.staticRoot, 'evolution')), ['revision-1']); + const applied = await evolution.applyFrameToBridge(1, 0); + assert.equal(applied.revision, 1); + // A killed analysis is never recorded as a fact about the revision. + assert.deepEqual((await evolution.getReferences()).eligibility?.excludedSources || [], []); + + analyzer.respond = null; + const again = await evolution.generate({ mode: 'manual', sourceIds: [commitId(fixture.shas.c2), 'working-copy'] }, () => {}); + assert.equal(again.revision, 2); + await evolution.dispose(); + }); +}); + +test('S6: Clear during a generation cancels it and waits, so no late movie lands after the clear', async () => { + const session = makeSession(); + writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); + await withServices({ sessions: [session] }, async ({ ProjectEvolutionService, JobCancelledError, context, analyzer }) => { + const evolution = new ProjectEvolutionService(context, session.id, session.staticRoot, createCatalog()); + const refs = await evolution.getReferences(); + const c2 = refs.sources.find((s) => s.kind === 'gitRef' && s.commitSha === fixture.shas.c2 && s.refType === 'commit').id; + analyzer.respond = () => new Promise(() => {}); + const movie = evolution.generate({ mode: 'manual', sourceIds: [c2, 'working-copy'] }, () => {}); + await waitFor(() => analyzer.calls.length > 0); + await evolution.clearGeneratedMovie(); + assert.equal(evolution.isBusy(), false, 'Clear returned only once the job had ended'); + await assert.rejects(movie, JobCancelledError); + const evolutionDirectory = path.join(session.staticRoot, 'evolution'); + assert.deepEqual(fs.existsSync(evolutionDirectory) ? fs.readdirSync(evolutionDirectory) : [], []); + await evolution.dispose(); + }); +}); + +test('S6: a revision whose analysis hangs is killed by its watchdog and discarded; the movie still finishes', async () => { + const session = makeSession(); + writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); + await withServices({ sessions: [session] }, async ({ ProjectEvolutionService, context, analyzer }) => { + const evolution = new ProjectEvolutionService(context, session.id, session.staticRoot, createCatalog()); + evolution.analysis.revisionTimeoutMs = 40; + const refs = await evolution.getReferences(); + const commitId = (sha) => refs.sources.find((s) => s.kind === 'gitRef' && s.commitSha === sha && s.refType === 'commit').id; + const hungSha = fixture.shas.c2.slice(0, 8); + analyzer.respond = (revisionSession) => (revisionSession.id.endsWith(hungSha) + ? new Promise(() => {}) + : Promise.resolve([{ filePath: 'main.js', totalLines: 1 }])); + const result = await evolution.generate({ + mode: 'manual', + sourceIds: [commitId(fixture.shas.c1), commitId(fixture.shas.c2), commitId(fixture.shas.c3)], + }, () => {}); + assert.equal(result.frames.length, 2); + const excluded = result.excludedSources.find((entry) => String(entry.reason).includes('revision-analysis-timeout')); + assert.ok(excluded, JSON.stringify(result.excludedSources)); + assert.deepEqual(analyzer.killed, [`${session.id}-evolution-${hungSha}`]); + assert.equal(evolution.isBusy(), false); + await evolution.dispose(); + }); +}); + +test('S6: a historical comparison can be reserved synchronously, cancelled, and its late result is never returned', async () => { + const session = makeSession(); + writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); + await withServices({ sessions: [session] }, async ({ HistoricalComparisonService, JobCancelledError, context, analyzer }) => { + const historical = new HistoricalComparisonService(context, session.id, session.staticRoot, createCatalog()); + const { bySha } = await sourcesBySha(historical); + const request = { leftSourceId: bySha[fixture.shas.c1].id, rightSourceId: 'working-copy' }; + const ticket = historical.reserveComparison(request); + assert.ok(ticket); + assert.equal(historical.reserveComparison(request), null, 'the slot is taken before any await'); + assert.equal(historical.getJobStatus().state, 'queued'); + ticket.release(); + assert.equal(historical.isBusy(), false); + + let finish; + analyzer.respond = () => new Promise((resolve) => { + finish = () => resolve([{ filePath: 'main.js', totalLines: 1 }]); + }); + const running = historical.compare(request); + await waitFor(() => typeof finish === 'function'); + assert.equal(historical.cancelComparison(), true); + await assert.rejects(running, (error) => error instanceof JobCancelledError && error.message === 'comparison-cancelled'); + finish(); + await waitFor(() => !historical.isBusy()); + assert.equal((await historical.getReferences()).activeRequest, null, 'a cancelled request never becomes the active one'); + await historical.dispose(); + }); +}); + test('historical refreshActiveComparison re-runs only a comparison with a live side', async () => { const session = makeSession(); writeWorkingCopy(session, [{ filePath: 'main.js', totalLines: 1 }]); @@ -667,11 +814,13 @@ test('evolution generate (file): missing target cached and excluded per frame, p assert.equal(progress[0].message, 'Resolving project timeline...'); assert.equal(progress[1].message, 'Analyzing 4 project revisions with 4 workers...'); assert.ok(progress.some((entry) => entry.message === `Discarded ${commit(fixture.shas.c1).label}: The analyzed target does not exist in this revision.`)); - assert.deepEqual(progress.at(-1), { + assert.match(progress.at(-1).jobId, /^job-/); + assert.deepEqual({ ...progress.at(-1), jobId: undefined }, { state: 'ready', message: 'Project evolution ready. 1 revision(s) were discarded because they had no usable data.', revision: 1, frameCount: 3, + jobId: undefined, }); assert.equal(analyzer.calls.length, 2); @@ -900,6 +1049,21 @@ function fakeService(overrides = {}) { async getReferences() { return { kind: 'references', from: this.name }; }, + // The bridges reserve the job slot synchronously, then run it (S6); + // the fake maps that pair onto compare()/generate(). + released: 0, + reserveComparison(request) { + return this.busy ? null : { id: 'job-h', request, release: () => { this.released += 1; } }; + }, + runComparison(ticket, request, onProgress) { + return this.compare(request, onProgress); + }, + reserveGeneration(request) { + return this.busy ? null : { id: 'job-e', request, release: () => { this.released += 1; } }; + }, + runGeneration(ticket, request, onProgress) { + return this.generate(request, onProgress); + }, ...overrides, }; } @@ -922,9 +1086,11 @@ async function withBridges(body) { coordinatorCalls.push(['refreshMode', ...args]); }; const { GitAnalysisSourceError } = requireOut('core/history/gitAnalysisEligibility.js'); + // Loaded before the bridges, so they share this very class. + const { JobCancelledError } = requireOut('core/analysis/launch/jobRunner.js'); const { HistoricalComparisonBridge } = requireOut(HISTORICAL_BRIDGE_MODULE); const { ProjectEvolutionBridge } = requireOut(EVOLUTION_BRIDGE_MODULE); - await body({ HistoricalComparisonBridge, ProjectEvolutionBridge, GitAnalysisSourceError, coordinatorCalls }); + await body({ HistoricalComparisonBridge, ProjectEvolutionBridge, GitAnalysisSourceError, JobCancelledError, coordinatorCalls }); }); } @@ -1011,9 +1177,10 @@ test('historical bridge start: switches the view, broadcasts progress, shares th ['change', 'historical-compare', 'historical.selection'], ['update', 'historical-compare', 2, 'historical.mapping'], ]); + // The refresh flag is set only once the request succeeded (HIST-9). assert.deepEqual(coordinatorCalls, [ - ['setRefreshEnabled', 'sess-1', 'historical-compare', true], ['refreshMode', 'sess-1', 'historical-compare'], + ['setRefreshEnabled', 'sess-1', 'historical-compare', true], ['setSnapshotAvailable', 'sess-1', 'historical-compare', true], ]); assert.deepEqual(messageContext.log, [ @@ -1121,12 +1288,12 @@ test('bridges: a source error re-broadcasts only the reference lists whose servi }); }); -test('evolution bridge: a cleared movie is silent; clear and apply-frame report their own outcomes', async () => { - await withBridges(async ({ ProjectEvolutionBridge, coordinatorCalls }) => { +test('evolution bridge: a cancelled movie is silent; clear and apply-frame report their own outcomes', async () => { + await withBridges(async ({ ProjectEvolutionBridge, JobCancelledError, coordinatorCalls }) => { const host = createHost({ evolution: fakeService({ async generate() { - throw new Error('project-evolution-cleared'); + throw new JobCancelledError('cancelled', 'project-evolution-cancelled'); }, async clearGeneratedMovie() {}, async applyFrameToBridge(revision, frameIndex) { @@ -1169,3 +1336,28 @@ test('evolution bridge: a cleared movie is silent; clear and apply-frame report assert.deepEqual(host.calls, [['update', 'project-evolution', 4, 'project-evolution']]); }); }); + +test('S6 bridges: Cancel stops the job for the whole room, or tells only the requester there is none', async () => { + await withBridges(async ({ HistoricalComparisonBridge, ProjectEvolutionBridge }) => { + let running = true; + const cancelOnce = () => { + const was = running; + running = false; + return was; + }; + const host = createHost({ + historical: fakeService({ getJobStatus: () => ({ id: 'job-h' }), cancelComparison: cancelOnce }), + evolution: fakeService({ getJobStatus: () => ({ id: 'job-e' }), cancelGeneration: cancelOnce }), + }); + const evolution = new ProjectEvolutionBridge(host); + const historical = new HistoricalComparisonBridge(host); + const room = createMessageContext(); + assert.equal(evolution.handleProjectEvolutionCancelMessage(room), true); + assert.equal(historical.handleHistoricalComparisonCancelMessage(room), true); + assert.deepEqual(room.log, [ + ['broadcast', { type: 'project-evolution-cancelled', payload: { message: 'Project evolution generation cancelled.', jobId: 'job-e' } }], + ['send', { type: 'historical-comparison-cancelled', payload: { message: 'No historical comparison is running.', jobId: 'job-h' } }], + ]); + assert.equal(new ProjectEvolutionBridge(createHost({})).handleProjectEvolutionCancelMessage(room), false); + }); +}); diff --git a/apps/vscode-extension/test/analysis/historicalComparison.test.cjs b/apps/vscode-extension/test/analysis/historicalComparison.test.cjs index fb4fbeec..3f90add9 100644 --- a/apps/vscode-extension/test/analysis/historicalComparison.test.cjs +++ b/apps/vscode-extension/test/analysis/historicalComparison.test.cjs @@ -380,7 +380,9 @@ test('historical comparison is authoritative, shared per room, and rejects concu assert.match(server, /changeAnalysisViewMode\('historical-compare', 'historical.selection'\);/); assert.match(server, /updateAnalysisViewIfCurrent\([\s\S]*'historical.mapping'/); assert.doesNotMatch(server, /message\.type === 'historical-comparison-reset'/); - assert.match(server, /historicalComparisonService\.isBusy\(\)/); + // The job slot is reserved synchronously, before the first await (S6). + assert.match(server, /service\.reserveComparison\(request\)/); + assert.match(server, /message\.type === 'historical-comparison-cancel'/); assert.match(server, /await this\.historicalComparisonService\.getAvailability\(\)/); // The capability payload is built by the extracted CollaborationSessionApi. assert.match( @@ -401,12 +403,9 @@ test('project evolution builds a chronological Git movie and publishes shared XR + readProjectFile('src', 'core', 'server', 'analysis', 'historicalComparisonBridge.ts') + readProjectFile('src', 'core', 'server', 'analysis', 'projectEvolutionBridge.ts') + readProjectFile('src', 'core', 'server', 'analysis', 'analysisFeatureHost.ts'); - const service = readProjectFile( - 'src', - 'core', - 'history', - 'projectEvolutionService.ts', - ); + // The revision writer was split out of the service (S6); same assertions. + const service = readProjectFile('src', 'core', 'history', 'projectEvolutionService.ts') + + readProjectFile('src', 'core', 'history', 'projectEvolutionArtifacts.ts'); const models = readProjectFile( 'src', 'core', @@ -442,7 +441,8 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(service, /DEFAULT_MAX_FRAMES = 24/); assert.match(service, /DEFAULT_ANALYSIS_CONCURRENCY = 4/); assert.match(service, /sampleSources/); - assert.match(service, /Promise\.all\(workers\)/); + // Every worker ends before the job does: no orphan after a cancel (S6). + assert.match(service, /Promise\.allSettled\(workers\)/); assert.match(service, /Analyzing \$\{sources\.length\} project revisions with \$\{concurrency\} workers/); assert.match(service, /references\.sources\.filter\(\(source\) => source\.kind === 'gitRef'\)/); assert.match(service, /'project-evolution'/); @@ -457,7 +457,7 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(service, /Project evolution ready\./); assert.match(service, /clearGeneratedMovie/); assert.match(service, /fs\.promises\.rm\(revisionDirectory, \{ recursive: true, force: true \}\)/); - assert.match(service, /project-evolution-cleared/); + assert.match(service, /cancelAndWait/); // Frame selection is the shared sampler (even spacing in time, milestones // preferred), and the movie always ends on the current state of the branch — // the `--all` timeline's last entry can belong to another branch. @@ -493,7 +493,9 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(server, /type: 'project-evolution-frame-applied'/); assert.match(server, /message\.type === 'project-evolution-start'/); assert.match(server, /changeAnalysisViewMode\('project-evolution', 'project-evolution'\);/); - assert.match(server, /projectEvolutionService\.isBusy\(\)/); + assert.match(server, /service\.reserveGeneration\(request\)/); + assert.match(server, /message\.type === 'project-evolution-cancel'/); + assert.match(server, /type: 'project-evolution-cancelled'/); assert.match(server, /entityKind: 'project-evolution'/); assert.match(server, /mode: 'project-evolution'/); assert.match(runtime, /CodeXRProjectEvolutionRuntime/); @@ -501,6 +503,7 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(runtime, /project-evolution-references-request/); assert.match(runtime, /project-evolution-clear/); assert.match(runtime, /project-evolution-cleared/); + assert.match(runtime, /project-evolution-cancel'/); assert.match(runtime, /project-evolution-start/); assert.match(runtime, /function unwrapPayload\(message\)/); assert.match(runtime, /Object\.prototype\.hasOwnProperty\.call\(message, 'payload'\)/); @@ -690,7 +693,9 @@ test('project evolution builds a chronological Git movie and publishes shared XR assert.match(runtime, /if \(!state\.applyingMapping\) \{[\s\S]{0,120}tryResumePlayback\(\);/); // A deliberate pause cancels any pending auto-resume. assert.match(runtime, /state\.resumePlayback = false;\s*stop\(\);/); - assert.match(runtime, /state\.generating\) \{[\s\S]{0,200}clearMovie\(\);/); + // Leaving the mode never clears the movie or stops the room's job (S6, EVO-2). + assert.doesNotMatch(runtime, /state\.generating\) \{[\s\S]{0,200}clearMovie\(\);/); + assert.match(runtime, /function clearOrCancel\(\)/); assert.match(runtime, /function setTimelineMode/); assert.match(runtime, /function selectSourceForTimeline/); assert.match(runtime, /refs\.picker\?\.getVisibleSources\?\.\(\)/); @@ -874,7 +879,8 @@ test('XR historical runtime renders two contained charts and restores the single assert.match(runtime, /function restoreOriginalChartMapping\(config\)/); assert.match(runtime, /mappingRuntime\.switchMappingContext\?\.\('normal-analysis'/); assert.match(runtime, /setStatus\('Analyzing historical comparison\. Please wait\.\.\.', 'info'\)/); - assert.match(runtime, /function handleProgress\(message\) \{\s*setStatus\(message\?\.payload\?\.message \|\| 'Analyzing\.\.\.', 'info'\);/); + assert.match(runtime, /function handleProgress\(message\) \{\s*setComparisonJobRunning\(message\?\.payload\?\.state === 'analyzing'\);\s*setStatus\(message\?\.payload\?\.message \|\| 'Analyzing\.\.\.', 'info'\);/); + assert.match(runtime, /historical-comparison-cancel'/); assert.match(runtime, /parkOriginalChart\(original\)/); assert.match(runtime, /restoreOriginalChart\(\)/); assert.match(runtime, /CodeXRAnalysisModeRuntime/); diff --git a/apps/vscode-extension/test/analysis/jobRunner.test.cjs b/apps/vscode-extension/test/analysis/jobRunner.test.cjs new file mode 100644 index 00000000..1109aa54 --- /dev/null +++ b/apps/vscode-extension/test/analysis/jobRunner.test.cjs @@ -0,0 +1,160 @@ +'use strict'; + +/** + * The shared job runner (S6, issue #78), from out/: atomic reservation, the + * job states, the deadline, cancel reaching the work's signal, late results + * discarded, the slot held while the work unwinds (with a grace limit), and + * the per-step watchdog signal. + */ + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { createFakeVscode, withFakeVscode } = require('../helpers/fakeVscode.cjs'); + +async function withRunner(body) { + await withFakeVscode(createFakeVscode(), async ({ requireOut }) => { + const launch = requireOut('core/analysis/launch/launchControl.js'); + const jobs = requireOut('core/analysis/launch/jobRunner.js'); + await body({ ...jobs, launch }); + }); +} + +const options = (overrides = {}) => ({ + busyCode: 'x-busy', + cancelledCode: 'x-cancelled', + timeoutCode: 'x-timeout', + timeoutMs: 0, + graceMs: 50, + ...overrides, +}); +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +test('tryReserve takes the slot synchronously; a second start is refused until the job ends', async () => { + await withRunner(async ({ JobRunner }) => { + const states = []; + const runner = new JobRunner(options({ onStateChange: (status) => states.push(status.state) })); + const ticket = runner.tryReserve({ n: 1 }); + assert.ok(ticket && /^job-/.test(ticket.id)); + assert.equal(runner.tryReserve({ n: 2 }), null); + await assert.rejects(runner.run({ n: 3 }, async () => 'never'), /^Error: x-busy$/); + assert.equal(await ticket.execute(async () => 'done'), 'done'); + assert.equal(runner.isBusy(), false); + assert.deepEqual(runner.lastRequest, { n: 1 }); + assert.deepEqual(states, ['queued', 'running', 'done']); + assert.equal(runner.status.state, 'done'); + assert.ok(runner.status.endedAt); + }); +}); + +test('a failed job keeps the previous successful request and reports its error', async () => { + await withRunner(async ({ JobRunner }) => { + const runner = new JobRunner(options()); + await runner.run({ n: 1 }, async () => 'ok'); + await assert.rejects(runner.run({ n: 2 }, async () => { + throw new Error('boom'); + }), /boom/); + assert.deepEqual(runner.lastRequest, { n: 1 }); + assert.deepEqual([runner.status.state, runner.status.error], ['failed', 'boom']); + }); +}); + +test('release() gives back a reservation that never ran; cancel() of a queued job frees it too', async () => { + await withRunner(async ({ JobRunner, JobCancelledError }) => { + const runner = new JobRunner(options()); + runner.tryReserve({}).release(); + assert.equal(runner.isBusy(), false); + assert.equal(runner.status.state, 'cancelled'); + + const queued = runner.tryReserve({}); + assert.equal(runner.cancel(), true); + assert.equal(runner.isBusy(), false); + await runner.cancelAndWait(); // resolves: the slot is already free + await assert.rejects(queued.execute(async () => 'late'), JobCancelledError); + }); +}); + +test('cancel aborts the signal the work runs under, and the job rejects at once with the cancelled code', async () => { + await withRunner(async ({ JobRunner, JobCancelledError, launch }) => { + const runner = new JobRunner(options()); + let seen = null; + const job = runner.run({}, (signal) => new Promise((resolve, reject) => { + seen = launch.currentLaunchSignal(); + assert.equal(seen, signal, 'the work sees the job signal through the async context'); + signal.addEventListener('abort', () => reject(new Error('child killed'))); + })); + await delay(5); + assert.equal(runner.cancel(), true); + await assert.rejects(job, (error) => error instanceof JobCancelledError + && error.reason === 'cancelled' && error.message === 'x-cancelled'); + assert.equal(seen.aborted, true); + await delay(0); + assert.equal(runner.isBusy(), false); + assert.equal(runner.status.state, 'cancelled'); + assert.equal(runner.lastRequest, null); + }); +}); + +test('a job past its deadline is aborted with the timeout code', async () => { + await withRunner(async ({ JobRunner, JobCancelledError }) => { + const runner = new JobRunner(options({ timeoutMs: 20 })); + const job = runner.run({}, (signal) => new Promise((resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('killed'))); + })); + await assert.rejects(job, (error) => error instanceof JobCancelledError + && error.reason === 'timeout' && error.message === 'x-timeout'); + await delay(0); + assert.equal(runner.isBusy(), false); + }); +}); + +test('a result that arrives after the cancel is discarded, and the slot waits for the work to end', async () => { + await withRunner(async ({ JobRunner, JobCancelledError }) => { + const runner = new JobRunner(options({ graceMs: 10_000 })); + let finish; + const job = runner.run({}, () => new Promise((resolve) => { + finish = resolve; // ignores the signal, like a step that cannot be killed + })); + await delay(5); + runner.cancel(); + await assert.rejects(job, JobCancelledError); + assert.equal(runner.isBusy(), true, 'the work is still unwinding: no new job beside it'); + finish('late result'); + await delay(0); + assert.equal(runner.isBusy(), false); + assert.equal(runner.lastRequest, null); + }); +}); + +test('work that ignores the abort frees the slot after the grace period, so the service is never stuck', async () => { + await withRunner(async ({ JobRunner }) => { + const runner = new JobRunner(options({ graceMs: 30 })); + const job = runner.run({}, () => new Promise(() => {})); + job.catch(() => undefined); + await delay(5); + const waited = runner.cancelAndWait(); + assert.equal(runner.isBusy(), true); + await waited; + assert.equal(runner.isBusy(), false); + assert.ok(runner.tryReserve({}), 'a new job can start'); + }); +}); + +test('withTimeout aborts on its deadline or with its parent, and dispose clears the timer', async () => { + await withRunner(async ({ withTimeout }) => { + const timed = withTimeout(undefined, 10, 'step-timeout'); + await delay(30); + assert.equal(timed.signal.reason, 'step-timeout'); + + const parent = new AbortController(); + const child = withTimeout(parent.signal, 10_000); + parent.abort('cancelled'); + assert.equal(child.signal.reason, 'cancelled'); + child.dispose(); + + const disposed = withTimeout(undefined, 10); + disposed.dispose(); + await delay(30); + assert.equal(disposed.signal.aborted, false); + }); +}); diff --git a/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs b/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs index 09dbe9d4..2a21f16f 100644 --- a/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs +++ b/apps/vscode-extension/test/analysis/livePanelHistorical.test.cjs @@ -49,7 +49,7 @@ test('HttpServer exposes LivePanel REST endpoints for references and async compa // References report availability instead of failing on non-Git targets. assert.match(server, /sendJsonResponse\(res, 200, \{ enabled: false, reason: availability\.reason \}\)/); // Compare answers 202 and runs the comparison in the background. - assert.match(server, /sendJsonResponse\(res, 202, \{ accepted: true \}\)/); + assert.match(server, /sendJsonResponse\(res, 202, \{ accepted: true, jobId: ticket\.id \}\)/); assert.match(server, /A historical comparison is already running\./); }); diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index b44e0d95..5451b76e 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -56,14 +56,14 @@ "src/features/active-servers/views/handleServerActions.ts", "src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts" ], - "functions.over80Lines": 35, - "complexity.over10": 51, + "functions.over80Lines": 34, + "complexity.over10": 50, "complexity.over15": 8, "complexity.over20": 0, "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 155, + "eslint.maxWarnings": 154, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -71,9 +71,9 @@ } }, "informational": { - "src.files": 294, - "src.lines": 49299, - "src.functions": 3360, + "src.files": 296, + "src.lines": 50017, + "src.functions": 3417, "src.unreachableLines": 0, "console.byFile": { "src/platform/logging/sink.ts": 2 @@ -196,6 +196,12 @@ "function": "sampleTimeline", "file": "src/core/history/gitTimelineSampler.ts" }, + { + "ccn": 20, + "lines": 50, + "function": "handleCollaborationMessage", + "file": "src/core/server/analysis/analysisMessageRouter.ts" + }, { "ccn": 19, "lines": 50, @@ -214,12 +220,6 @@ "function": "recalculateLivePanelSummary", "file": "src/core/analysis/watchers/directoryReanalysisData.ts" }, - { - "ccn": 17, - "lines": 44, - "function": "handleCollaborationMessage", - "file": "src/core/server/analysis/analysisMessageRouter.ts" - }, { "ccn": 17, "lines": 98, @@ -264,6 +264,10 @@ "file": "src/core/export/exportManifest.ts", "lines": 746 }, + { + "file": "src/core/history/gitRepositoryService.ts", + "lines": 639 + }, { "file": "src/core/remote-access/remoteSessionAuthority.ts", "lines": 632 @@ -272,10 +276,6 @@ "file": "src/features/active-servers/views/handleServerActions.ts", "lines": 628 }, - { - "file": "src/core/history/gitRepositoryService.ts", - "lines": 617 - }, { "file": "src/core/server/httpServer.ts", "lines": 596