fix(lsp): r3 review folds (refs #4320)

Round 3 of the #4344 review (verify r2, G1 to G6).

- G1: bounded-cache joins the declared client leaves, and a leaf may
  import another leaf, so workspace-diagnostics-session keeps its
  bounded marker map without breaking #2504.
- G6: dependency-boundaries.test.ts now reds on any violation the
  known-violations baseline does not cover (JSON mode exits 0, so it
  reads the summary), and lane:check runs depcruise:check.
- G2: a two-server batch test pins the per-server filter in
  announceCreatedFiles through a wire trace of the stale-lookup server.
- G3: a test pins the onDisk guard (an unsaved buffer's Created is not
  remembered, so the file's real creation is still Created).
- G4: fix-run-restore carries the path birth across its atomic
  rewrite, so a restored file stays Changed for language servers.
- G5: announceCreated is required and announceCreatedFiles is called
  unconditionally; the shared and hand-rolled doubles gain both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Apostolos MantzarisandClaude Opus 5.5 committed 2026-10-14 00:27:02 +03:00
1 parent 5baf9680c2
commit cb2aa317c0
53 files changed
+367 -39

No files matched your search

+14 -3
View File
@@ -10,6 +10,13 @@ const eagerClientPattern = `^(?:\\./)?(?:${eagerClients
)
.join("|")})$`;
// #2504: leaves import no clients/ module except another leaf, so a
// heavyweight importer reaching one never drags an owner's graph along.
// #4344 r2 adds bounded-cache (it imports nothing) so the
// workspace-diagnostics-session leaf can hold a bounded map.
const clientLeaves =
"(ledger-bounds|spawn-output-cap|map-with-concurrency|deferred-lsp-work|lsp/workspace-diagnostics-session|bounded-cache)";
module.exports = {
forbidden: [
{
@@ -30,16 +37,20 @@ module.exports = {
{
name: "declared-client-leaf",
severity: "error",
comment: "Declared leaf modules must not import another clients/ module.",
comment:
"Declared leaf modules must not import a clients/ module other than another declared leaf.",
from: {
// #2504 adds the two leaves it introduced. Both exist precisely so
// a heavyweight importer (runtime-turn, lsp/index) can reach a
// small shared primitive without dragging that primitive's owner's
// import graph along — a claim each module's own doc comment makes
// and which only this rule can actually hold.
path: "^(?:\\./)?clients/(ledger-bounds|spawn-output-cap|map-with-concurrency|deferred-lsp-work|lsp/workspace-diagnostics-session)\\.js$",
path: `^(?:\\./)?clients/${clientLeaves}\\.js$`,
},
to: {
path: "^(?:\\./)?clients/",
pathNot: `^(?:\\./)?clients/${clientLeaves}\\.js$`,
},
to: { path: "^(?:\\./)?clients/" },
},
{
name: "session-start-eager-allowlist-config-dependency-cruiser-eager-allowlist-json",
+16
View File
@@ -169,6 +169,7 @@ import { createHash } from "node:crypto";
import * as fs from "node:fs";
import { writeFileAtomicAsync } from "./atomic-write.js";
import { noteAtomicReplace } from "./path-birth.js";
import {
incrementDegradationCount,
recordDegradationOnce,
@@ -745,9 +746,24 @@ async function restoreFile(
skipped.push(file.filePath);
return;
}
let before: fs.Stats | undefined;
try {
before = fs.statSync(file.filePath);
} catch {
// Gone since the re-read: the write below recreates it, a new path.
}
await writeFileAtomicAsync(file.filePath, capture.bytes, {
bestEffort: false,
});
// #4320: the rewrite installs a new inode; the path is as old as it was,
// so its next first open must tell a language server Changed, not Created.
if (before) {
try {
noteAtomicReplace(before, fs.statSync(file.filePath));
} catch {
// Gone again: no path left to describe.
}
}
report.restored.push(file.filePath);
}
+1 -3
View File
@@ -374,10 +374,8 @@ export interface LSPClientInfo {
* #4320: queue Created for each existing path that is new to this server
* and not yet announced to it, then send any waiting Created now. A read
* that follows is then answered by a server that has heard of the path.
* Optional so client doubles that predate it need no update; a caller
* treats a missing implementation as "nothing to announce".
*/
announceCreated?(
announceCreated(
entries: ReadonlyArray<{ filePath: string; stat: BirthStat }>,
): void;
};
+1 -1
View File
@@ -3921,7 +3921,7 @@ export class LSPService {
key.startsWith(`${serverId}:`) ? list : [],
);
// Called with no entries too: the client still sends a waiting Created.
client.notify.announceCreated?.(entries);
client.notify.announceCreated(entries);
}
}
+3
View File
@@ -295,6 +295,9 @@ export function main(argv = process.argv.slice(2)) {
])
: null,
astgrep: run(root, "npm", ["run", "astgrep:self-scan"]),
// #4344 r2: CI's Dependency boundaries job, so a boundary violation
// reds the lane before the push rather than after it.
depcruise: run(root, "npm", ["run", "depcruise:check"]),
};
for (const [name, result] of Object.entries(checks)) {
record.checks[name] = result ? result.status : null;
+32
View File
@@ -54,6 +54,7 @@ import {
setHostFileMutationQueueLoader,
withHostFileMutationQueues,
} from "../../clients/file-mutation-queue.js";
import { pathBirthtimeMs } from "../../clients/path-birth.js";
import { getProcessSingleton } from "../../clients/process-singletons.js";
import { beginScope } from "../../clients/session-scope.js";
import {
@@ -381,6 +382,37 @@ describe("whole-package fixer restores agent edits (#3598)", () => {
expect(overwrittenCount()).toBe(1);
}, 10000);
// #4320 r3 (G4): the restore rewrites the agent's file through a temp file
// and a rename, so the file gets a new inode born now. Without the carried
// birth its next first open told the language server Created, and every
// cached finding of that server under the root was dropped and re-checked.
it("keeps the restored file's path birth across its atomic rewrite", async (ctx) => {
const aRs = path.join(srcDir, "a.rs");
const born = fs.statSync(aRs);
if (!(born.birthtimeMs > 0)) ctx.skip("filesystem reports no birth time");
const started = gate();
const proceed = gate();
fake.clippy = async () => {
started.open();
await proceed.p;
fs.writeFileSync(aRs, TOOL_FIXED);
return 0;
};
const run = runPipelineSettled(pipelineContext(mainRs), pipelineDeps());
await started.p;
const edit = agentEdit(aRs, "let AGENT = 1;");
edit.write();
await edit.deliver();
proceed.open();
await run;
const restored = fs.statSync(aRs);
expect(fs.readFileSync(aRs, "utf-8")).toBe("let AGENT = 1;\n");
expect(restored.ino).not.toBe(born.ino);
expect(pathBirthtimeMs(restored)).toBe(born.birthtimeMs);
}, 10000);
it("leaves the tool's fix on a sibling the agent did not edit", async () => {
const aRs = path.join(srcDir, "a.rs");
const bRs = path.join(srcDir, "b.rs");
@@ -959,6 +959,7 @@ describe("#3529: the drain's LSP sync ends on the bytes on disk", () => {
getAllDiagnostics: vi.fn(() => new Map()),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open: (
fp: string,
content: string,
@@ -105,6 +105,7 @@ async function setup() {
getAllDiagnostics: vi.fn(() => new Map()),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open: (
filePath: string,
content: string,
@@ -75,6 +75,7 @@ function makeClient(delayMs: number, serverId: string) {
getDiagnosticsVersionForPath: vi.fn((p: string) => stamps.get(p) ?? 0),
getDiagnostics: vi.fn(() => []),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -188,6 +188,7 @@ function makeClient(
// matching real client behaviour (server pushes → client caches → wait resolves).
getDiagnostics: vi.fn(() => (waitSettled ? diags : [])),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -228,6 +229,7 @@ function makeLateBoundClient(content: string, serverId = "opengrep") {
published ? { contentHash: hashDiagnosticContent(content) } : undefined,
),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {
published = false;
}),
@@ -306,6 +308,7 @@ function makeVersionlessLateClient(serverId = "opengrep") {
getDiagnostics: vi.fn(() => (published ? [diagnostic] : [])),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {
published = false;
}),
@@ -341,6 +344,7 @@ function makeWedgeableAux(
const client = {
...makeClient(delayMs, diags, { serverId }),
notify: {
announceCreated: () => undefined,
open: vi.fn((filePath: string) =>
filePath === wedgePath
? new Promise<void>((resolve) => {
@@ -2819,6 +2823,7 @@ describe('#1533 — silent auxiliary honesty on clientScope "all"', () => {
const auxClient = {
...makeClient(9000, [], { serverId: "opengrep" }),
notify: {
announceCreated: () => undefined,
open: vi.fn(() => new Promise<void>(() => {})),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -3060,6 +3065,7 @@ describe('#1533 — silent auxiliary honesty on clientScope "all"', () => {
getOperationSupport: () => ({}),
getDiagnostics: vi.fn(() => []),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -104,6 +104,7 @@ function makeClient(serverId: string, root: string) {
getRawCapabilityKeys: () => [],
getLaunchVariant: () => undefined,
notify: {
announceCreated: () => undefined,
open: vi.fn(
(
filePath: string,
@@ -80,6 +80,7 @@ function makeClient(serverId: string, open: ReturnType<typeof vi.fn>) {
getAllDiagnostics: vi.fn(() => new Map()),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open,
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -97,6 +97,7 @@ function makeClient(
diagnosticsVersion: 0,
getDiagnostics: vi.fn(() => []),
notify: {
announceCreated: () => undefined,
open: vi.fn(async (filePath: string, content: string) => {
await behaviour.onOpen?.(filePath, content);
openDocuments.add(path.resolve(filePath));
@@ -177,6 +177,7 @@ function makeClient(
return contentHash === undefined ? undefined : { contentHash };
}),
notify: {
announceCreated: () => undefined,
open: vi.fn((filePath: string, content: string) => {
writeCount += 1;
if (
@@ -58,6 +58,7 @@ function makeClient() {
diagnosticsVersion: 0,
getDiagnostics: vi.fn(() => []),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
watchedFileChange: vi.fn(),
@@ -155,6 +155,7 @@ function makeScanner(
return true;
}),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {
stats.opens += 1;
if (stats.wedged) return new Promise<void>(() => {});
@@ -202,6 +203,7 @@ function makePrimary(serverId: string) {
getDiagnostics: vi.fn(() => []),
pingLiveness: vi.fn(async () => true),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -94,6 +94,7 @@ function makeClient(
diagnosticsVersion: 0,
getDiagnostics: vi.fn(() => diags),
notify: {
announceCreated: () => undefined,
open: vi.fn(() =>
stallWrite ? new Promise<void>(() => {}) : Promise.resolve(),
),
@@ -245,6 +246,7 @@ describe("#743 — per-server notify-write deadlines", () => {
diagnosticsVersion: 0,
getDiagnostics: vi.fn(() => []),
notify: {
announceCreated: () => undefined,
open: vi.fn(() =>
stall ? new Promise<void>(() => {}) : Promise.resolve(),
),
+12 -3
View File
@@ -148,7 +148,10 @@ describe("LSPService race hardening", () => {
}),
getAdvertisedCommands: () => [],
getRawCapabilityKeys: () => [],
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
};
const initialize = suspendAt(createLSPClient, async () => client);
const spawn = vi.fn(async () => ({
@@ -243,7 +246,10 @@ describe("LSPService race hardening", () => {
}),
getAdvertisedCommands: () => [],
getRawCapabilityKeys: () => [],
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
};
const initialize = suspendAt(createLSPClient, async () => client);
getServersForFileWithConfig.mockReturnValue([
@@ -309,7 +315,10 @@ describe("LSPService race hardening", () => {
}),
getAdvertisedCommands: () => [],
getRawCapabilityKeys: () => [],
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
};
const initialize = suspendAt(createLSPClient, async () => client);
const internal = service as unknown as {
@@ -70,6 +70,7 @@ function makeFakeClient(serverId: string) {
fake.intentional = true; // mirrors clientShutdown() setting shutdownRequested
}),
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
change: vi.fn().mockResolvedValue(undefined),
},
@@ -155,6 +155,7 @@ function makeClient(
getDiagnostics: vi.fn(() => diags),
getAllDiagnostics: vi.fn(() => new Map()),
notify: {
announceCreated: () => undefined,
open: vi.fn(() => {
inFlight += 1;
stats.maxInFlight = Math.max(stats.maxInFlight, inFlight);
@@ -123,7 +123,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
getOperationSupport: () => ({}),
getAdvertisedCommands: () => [],
getRawCapabilityKeys: () => ["diagnosticProvider"],
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
};
@@ -187,6 +190,7 @@ describe("LSPService.touchFile collectDiagnostics", () => {
}),
getOperationSupport: () => ({}),
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
@@ -236,6 +240,7 @@ describe("LSPService.touchFile collectDiagnostics", () => {
}),
getOperationSupport: () => ({}),
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
@@ -289,7 +294,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
};
@@ -337,7 +345,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
};
@@ -679,7 +690,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
// notify.open never resolves = a server whose stdin backpressures
// (wedged/CPU-bound). Unbounded, this parked the dispatch LSP runner
// until its 30s dispatcher timeout. It must now bail at the budget.
notify: { open: vi.fn(() => new Promise(() => {})) },
notify: {
announceCreated: () => undefined,
open: vi.fn(() => new Promise(() => {})),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
};
@@ -721,7 +735,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
};
@@ -772,7 +789,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => diagnosticsToReturn),
};
@@ -843,7 +863,10 @@ describe("LSPService.touchFile collectDiagnostics", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn().mockResolvedValue(undefined) },
notify: {
announceCreated: () => undefined,
open: vi.fn().mockResolvedValue(undefined),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => diagnosticsToReturn),
};
@@ -128,6 +128,7 @@ function makeClient(serverId: string, root: string) {
recentStderr: () => "",
checkAlive: () => undefined,
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => undefined),
change: vi.fn(async () => undefined),
},
+8 -2
View File
@@ -72,7 +72,10 @@ function makeFakeClient(root: string, serverId = "typescript") {
getRawCapabilityKeys: () => [],
serverId,
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (filePath: string, ms: number) => {
waitCalls.push({ filePath, ms });
return undefined;
@@ -327,7 +330,10 @@ function makeControlledClient(
getOperationSupport: () => ({}),
serverId,
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (filePath: string, ms: number) => {
const outcome = plan[Math.min(call, plan.length - 1)] ?? "warm";
call += 1;
@@ -75,6 +75,7 @@ async function setup() {
getAllDiagnostics: vi.fn(() => new Map()),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open: (
filePath: string,
content: string,
@@ -96,6 +96,7 @@ function makeSilentClient(serverId: string, budgets: number[]) {
getAllDiagnostics: vi.fn(() => new Map()),
getDiagnosticBinding: vi.fn(() => undefined),
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
change: vi.fn(async () => {}),
close: vi.fn(async () => {}),
@@ -299,6 +299,25 @@ describe("didChangeWatchedFiles type for an opened file (#4320)", () => {
]);
});
// #4320 r3 (G3): a Created for an unsaved document tells the server of a
// buffer, not a file. Remembering it would turn the file's real creation
// on disk into Changed, and Pyrefly would keep the failed lookup.
it("announces Created when an unsaved document's file is later written", async (ctx) => {
requireBirthtime(ctx);
await startClient();
const file = path.join(dir, "saved-later.ts");
await client!.notify.open(file, "export const s = 1;\n", "typescript");
await framesReceived(1);
await client!.closeDocument(file);
fs.writeFileSync(file, "export const s = 1;\n");
await client!.notify.open(file, "export const s = 1;\n", "typescript");
expect((await framesReceived(2))[1]).toEqual([
{ uri: pathToFileURL(file).href, type: 1 },
]);
});
it("sends nothing for a silent open of a new file", async (ctx) => {
requireBirthtime(ctx);
await startClient();
@@ -1038,7 +1038,10 @@ function makeFakeClient(
getOperationSupport: () => ({}),
serverId,
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (filePath: string, ms: number) => {
waitCalls.push({ filePath, ms });
return undefined;
@@ -83,7 +83,10 @@ describe("#2052 sweep over a foreign root does not report or cache a clean", ()
root: foreignDir,
getWorkspaceDiagnosticsSupport: () => ({ advertised: false }),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
});
@@ -69,6 +69,7 @@ describe("runWorkspaceDiagnostics — per-server serialization (#387)", () => {
getOperationSupport: () => ({}),
serverId,
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {
const n = (live.get(serverId) ?? 0) + 1;
live.set(serverId, n);
@@ -140,7 +141,10 @@ describe("runWorkspaceDiagnostics — per-server serialization (#387)", () => {
diagnosticProviderKind: "object",
}),
getOperationSupport: () => ({}),
notify: { open: notifyOpen },
notify: {
announceCreated: () => undefined,
open: notifyOpen,
},
requestWorkspaceDiagnostics,
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
@@ -183,7 +187,10 @@ describe("runWorkspaceDiagnostics — per-server serialization (#387)", () => {
diagnosticProviderKind: "object",
}),
getOperationSupport: () => ({}),
notify: { open: notifyOpen },
notify: {
announceCreated: () => undefined,
open: notifyOpen,
},
requestWorkspaceDiagnostics,
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
@@ -89,7 +89,10 @@ describe("runWorkspaceDiagnostics pull-sweep content binding (#1104)", () => {
diagnosticProviderKind: "object",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
requestWorkspaceDiagnostics: vi.fn(async () => [
{
filePath: file,
@@ -139,7 +142,10 @@ describe("runWorkspaceDiagnostics pull-sweep content binding (#1104)", () => {
diagnosticProviderKind: "object",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
requestWorkspaceDiagnostics,
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
getDiagnostics: vi.fn(() => []),
@@ -198,7 +204,10 @@ describe("runWorkspaceDiagnostics pull-sweep content binding (#1104)", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn().mockResolvedValue(undefined),
// touchFile's real merge logic (index.ts, not mocked) composes each
// spawned client's `getDiagnosticBinding` into the non-enumerable
@@ -84,7 +84,10 @@ describe("runWorkspaceDiagnostics — service destroyed mid-sweep (#1618)", () =
getRawCapabilityKeys: () => [],
serverId: "typescript",
root: tmp,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async () => {
waitCalls += 1;
if (waitCalls === DESTROY_AFTER_CALLS) {
@@ -112,7 +112,10 @@ function makeClient(root: string) {
getOperationSupport: () => ({}),
serverId: "typescript",
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (filePath: string) => {
waits.push(filePath);
return undefined;
@@ -114,7 +114,10 @@ describe(
root: sessionDir,
getWorkspaceDiagnosticsSupport: () => ({ advertised: false }),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async () => {
touchedCount += 1;
duringTouch?.(touchedCount);
@@ -110,6 +110,7 @@ describe("runWorkspaceDiagnostics — batch-open restores #271 coalescing for a
getOperationSupport: () => ({}),
serverId: "typescript",
notify: {
announceCreated: () => undefined,
// Mirrors `handleNotifyOpen`'s real branch structure closely enough
// to reproduce the bug/fix: first open of a path enqueues a
// watched-files change; a later call for an already-open path is
@@ -250,6 +251,7 @@ describe("runWorkspaceDiagnostics — pre-open is bounded, not just fast (#615)"
getOperationSupport: () => ({}),
serverId: "typescript",
notify: {
announceCreated: () => undefined,
// Deliberately never resolves — reproduces a stuck notification
// write / hung server. Before #615 this hung `preOpenGroupFiles`
// forever, with no heartbeat and no way for the sweep to move on.
@@ -292,6 +294,7 @@ describe("runWorkspaceDiagnostics — pre-open is bounded, not just fast (#615)"
getOperationSupport: () => ({}),
serverId: "typescript",
notify: {
announceCreated: () => undefined,
open: vi.fn(() => new Promise<void>(() => {})),
},
waitForDiagnostics: vi.fn(async () => []),
@@ -78,7 +78,10 @@ describe("runWorkspaceDiagnostics — sweep-scoped index gate for workspaceIndex
}),
getOperationSupport: () => ({}),
serverId: "marksman",
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (filePath: string, ms: number) => {
waitCalls.push({ filePath, ms });
fileIndex += 1;
@@ -166,7 +169,10 @@ describe("runWorkspaceDiagnostics — sweep-scoped index gate for workspaceIndex
}),
getOperationSupport: () => ({}),
serverId: "python",
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (_filePath: string, ms: number) => {
waitCalls.push(ms);
return undefined;
@@ -110,6 +110,7 @@ describe("runWorkspaceDiagnostics — pre-open is chunked, not whole-group (#621
getOperationSupport: () => ({}),
serverId: "typescript",
notify: {
announceCreated: () => undefined,
open: vi.fn(async (filePath: string) => {
if (openDocuments.has(filePath)) return;
openDocuments.add(filePath);
@@ -182,6 +183,7 @@ describe("runWorkspaceDiagnostics — pre-open is chunked, not whole-group (#621
getOperationSupport: () => ({}),
serverId: "typescript",
notify: {
announceCreated: () => undefined,
open: vi.fn(async (filePath: string) => {
if (openDocuments.has(filePath)) return;
openDocuments.add(filePath);
@@ -184,7 +184,10 @@ describe("runWorkspaceDiagnostics warm attach sweeps (#822)", () => {
diagnosticProviderKind: "none",
}),
getOperationSupport: () => ({}),
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async () => undefined),
getDiagnostics: vi.fn(() => [localDiagnostic]),
};
@@ -79,6 +79,7 @@ function diag(
function makeService(diags: Array<Record<string, unknown>>) {
return {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => ({ diags })),
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -82,6 +82,7 @@ function diag(
function makeService(diags: Array<Record<string, unknown>>) {
return {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => ({ diags })),
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -32,6 +32,13 @@ function cruiseBuiltGraph(): {
dynamic?: boolean;
}>;
}>;
summary: {
violations: Array<{
from: string;
to: string;
rule: { name: string; severity: string };
}>;
};
} {
const output = execFileSync(
process.execPath,
@@ -51,7 +58,42 @@ function cruiseBuiltGraph(): {
return JSON.parse(output) as ReturnType<typeof cruiseBuiltGraph>;
}
/**
* The violations CI's Dependency boundaries job (`npm run depcruise:check`)
* would fail on: every violation in the cruise that the known-violations
* baseline does not list. JSON mode exits 0 whatever it finds, so the
* caller must read the summary.
*/
function unexpectedViolations(): string[] {
const key = (violation: {
from: string;
to: string;
rule: { name: string };
}) => `${violation.rule.name}: ${violation.from} -> ${violation.to}`;
const known = new Set(
(
parseJson5(
readFileSync(
resolve(repoRoot, ".dependency-cruiser-known-violations.json"),
"utf8",
),
) as Array<{ from: string; to: string; rule: { name: string } }>
).map(key),
);
return cruiseBuiltGraph()
.summary.violations.filter((violation) => !known.has(key(violation)))
.map((violation) => `${violation.rule.severity} ${key(violation)}`);
}
describe("dependency boundary governance", () => {
// #4344 r2: `workspace-diagnostics-session.js -> bounded-cache.js` broke
// the declared-client-leaf rule. CI's Dependency boundaries job went red,
// but this suite stayed green: it cruised in JSON mode, which exits 0 with
// errors, and asserted only rule names and counts.
it("finds no boundary violation outside the known-violations baseline", () => {
expect(unexpectedViolations()).toEqual([]);
}, 60_000);
it("keeps the configured boundary rules present", () => {
const config = require(resolve(repoRoot, ".dependency-cruiser.cjs")) as {
forbidden: Array<{ name?: string }>;
+6
View File
@@ -418,6 +418,12 @@ function handle(raw) {
trace(
`recv ${data.method ?? "<response>"} ${data.params?.textDocument?.uri ?? ""}`.trim(),
);
// #4320 r3: which watched-files changes reached this server.
if (data.method === "workspace/didChangeWatchedFiles") {
for (const change of data.params?.changes ?? []) {
trace(`watched ${change.uri} ${change.type}`);
}
}
if (
process.env.FAKE_LSP_ECHO_NOTIFY_METHODS === "1" &&
data.id === undefined
+22 -1
View File
@@ -42,7 +42,7 @@ type LaneSpec = {
detach?: boolean;
};
const packageJson = (buildExit = 0, distBuildExit = 0) =>
const packageJson = (buildExit = 0, distBuildExit = 0, depcruiseExit = 0) =>
JSON.stringify({
name: "lane-fixture",
private: true,
@@ -52,6 +52,7 @@ const packageJson = (buildExit = 0, distBuildExit = 0) =>
"build:dist": `node -e "process.env.BUILD_LOG && require('fs').appendFileSync(process.env.BUILD_LOG, 'd\\n'); if (${distBuildExit}) process.exit(${distBuildExit}); require('fs').mkdirSync('dist/clients/lsp', {recursive:true}); require('fs').writeFileSync('dist/clients/lsp/server-traits.js', '')"`,
"test:targeted": "node scripts/with-test-lock.mjs --shared -- vitest run",
"astgrep:self-scan": 'node -e ""',
"depcruise:check": `node -e "process.exit(${depcruiseExit})"`,
},
});
const GREEN = 'import { it } from "vitest";\nit("green", () => {});\n';
@@ -581,6 +582,26 @@ describe("lane-check verdict table (#4047 round 2)", () => {
TIMEOUT,
);
// #4344 r2: a declared-client-leaf violation redded CI's Dependency
// boundaries job after a lane:check that never ran the cruise.
it(
"a failed dependency-boundary check is unproven, exit 3, with every test green",
() => {
const lane = makeLane({
base: BASE_FILES,
head: { "package.json": packageJson(0, 0, 1) },
});
const run = runLane(lane);
expect(run.status).toBe(3);
expect(run.record.checks.depcruise).toBe(1);
expect(run.record.findings).toContainEqual({
kind: "unproven",
reason: "check depcruise failed (exit 1)",
});
},
TIMEOUT,
);
it(
"an unformatted untracked file is checked too: unproven, exit 3",
() => {
+1
View File
@@ -62,6 +62,7 @@ export function makeLspServiceDouble(
getOperationSupport: vi.fn(() => undefined),
isDocumentOpen: vi.fn(() => false),
notifyExternalFileChange: vi.fn(async () => undefined),
announceCreatedFiles: vi.fn(() => undefined),
getBrokenStatus: vi.fn(() => undefined),
};
@@ -71,6 +71,7 @@ function makeService(severity = 2) {
],
}));
return {
announceCreatedFiles: vi.fn(),
touchFile,
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -84,6 +85,7 @@ const OTHER_MESSAGE = "Cannot find name 'other'.";
function makeTwoFindingService(severity = 2, otherSeverity = severity) {
return {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => ({
diags: [
{
@@ -831,6 +833,7 @@ describe("the source=lsp footer reconcile respects mark-time demotion (#3088)",
describe("lens_diagnostics source=lsp scope=paths / legacy lsp_diagnostics paths-mode batch widget-state key parity (#3160/#3182)", () => {
function makeBadCallService() {
return {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => ({
diags: [
{
@@ -41,6 +41,7 @@ describe("lens_diagnostics source=lsp observability (#2860 F11)", () => {
const file = path.join(cwd, "bad.ts");
fs.writeFileSync(file, "const value: number = 'bad';\n");
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => [
{
@@ -51,6 +51,7 @@ afterEach(() => {
describe("source=lsp finding policy fails open (#3088)", () => {
it("still reports the finding, and records one bounded degradation, when the filter throws", async () => {
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => ({
diags: [
{
@@ -117,7 +117,10 @@ function makeClient(root: string, file: string) {
getOperationSupport: () => ({}),
serverId: "typescript",
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async () => undefined),
getDiagnostics: vi.fn((fp: string) =>
fp === file
+8
View File
@@ -219,6 +219,7 @@ describe("lens_diagnostics compact filename", () => {
const file = path.join(cwd, "app.ts");
fs.writeFileSync(file, "const app = 1;\n");
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -247,6 +248,7 @@ describe("lens_diagnostics compact filename", () => {
fs.writeFileSync(diagnosed, "const diagnosed = 1;\n");
fs.writeFileSync(unrelated, "const unrelated = 1;\n");
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -319,6 +321,7 @@ describe("lens_diagnostics source and scope routing", () => {
),
);
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () =>
tiers.map(([_, message, severity]) => ({
@@ -398,6 +401,7 @@ describe("lens_diagnostics source and scope routing", () => {
),
);
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => [
{
@@ -443,6 +447,7 @@ describe("lens_diagnostics source and scope routing", () => {
const file = path.join(cwd, "bad.ts");
fs.writeFileSync(file, "const value: number = 'bad';\n");
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => [
{
@@ -479,6 +484,7 @@ describe("lens_diagnostics source and scope routing", () => {
fs.writeFileSync(path.join(cwd, "one.ts"), "const one = 1;\n");
const service = {
runWorkspaceDiagnostics: vi.fn(async () => []),
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async () => undefined),
getDiagnostics: vi.fn(async () => []),
getCapabilitySnapshots: vi.fn(async () => []),
@@ -509,6 +515,7 @@ describe("lens_diagnostics source and scope routing", () => {
fs.writeFileSync(path.join(cwd, "outside.ts"), "const b = 1;\n");
const touched: string[] = [];
const service = {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async (file: string) => {
touched.push(file);
return undefined;
@@ -542,6 +549,7 @@ describe("lens_diagnostics source and scope routing", () => {
const touchedByScope = new Map<string, string[]>();
function makeService(key: string) {
return {
announceCreatedFiles: vi.fn(),
touchFile: vi.fn(async (f: string) => {
touchedByScope.set(key, [...(touchedByScope.get(key) ?? []), f]);
return undefined;
@@ -36,6 +36,8 @@ const fakeServer = fileURLToPath(
const env = setupTestEnvironment("pi-lens-4320-svc-");
const workspace = env.tmpDir;
// The stale-lookup server's record of every watched-files change it heard.
const luaTrace = path.join(workspace, "lua-server.trace");
const IMPORTER = 'import "./new_module"\nlocal value = 1\n';
async function diagnose(paths: string[]): Promise<{
@@ -74,6 +76,17 @@ describe("a module created after the server started (#4320)", () => {
// A push-only server, Pyrefly's measured shape here.
'process.env.FAKE_LSP_NO_DIAGNOSTIC_PROVIDER = "1";',
'process.env.FAKE_LSP_STALE_MODULE_LOOKUP = "1";',
`process.env.FAKE_LSP_TRACE_FILE = ${JSON.stringify(luaTrace)};`,
`import(${JSON.stringify(pathToFileURL(fakeServer).href)});`,
"",
].join("\n"),
);
// A second server, for `.tl` files only.
const otherShim = path.join(workspace, "other-server.mjs");
fs.writeFileSync(
otherShim,
[
'process.env.FAKE_LSP_NO_DIAGNOSTIC_PROVIDER = "1";',
`import(${JSON.stringify(pathToFileURL(fakeServer).href)});`,
"",
].join("\n"),
@@ -94,6 +107,13 @@ describe("a module created after the server started (#4320)", () => {
args: [shim],
rootMarkers: [".luarc.json"],
},
"other-fake": {
name: "other server",
extensions: [".tl"],
command: process.execPath,
args: [otherShim],
rootMarkers: [".luarc.json"],
},
},
// ast-grep and typos never confirm here, and a sweep persists no
// entry with an unconfirmed server, so the sweep case would never
@@ -226,6 +246,36 @@ describe("a module created after the server started (#4320)", () => {
expect(after.details.primaryDiagnosticsCount).toBe(0);
}, 30_000);
// #4320 r3 (G2): a batch tells each client only the files of its own
// server. Without the per-server filter in `announceCreatedFiles` the
// stale-lookup (`.lua`) server heard Created for a `.tl` file, and every
// cached finding of that server was dropped and re-checked (probe4 with
// Pyrefly: replay 8 ms -> 629 ms).
it("announces a new file only to its own server's clients", async () => {
const luaFile = path.join(workspace, "own_server.lua");
fs.writeFileSync(luaFile, "return {}\n");
const seed = path.join(workspace, "seed.tl");
fs.writeFileSync(seed, "local s = 1\n");
await diagnose([luaFile, seed]);
const fresh = path.join(workspace, "fresh_other.tl");
fs.writeFileSync(fresh, "local f = 1\n");
await diagnose([fresh, luaFile]);
// a sentinel the stale-lookup server must hear, so its trace is current
const sentinel = path.join(workspace, "sentinel_module.lua");
fs.writeFileSync(sentinel, "return {}\n");
await diagnose([sentinel]);
const watched = fs
.readFileSync(luaTrace, "utf8")
.split("\n")
.filter((line) => line.startsWith("watched "));
expect(watched).toContain(`watched ${pathToFileURL(sentinel).href} 1`);
expect(watched.filter((line) => line.includes("fresh_other.tl"))).toEqual(
[],
);
}, 30_000);
// #4320 r2 (F2): `rename_file` moves a module into the missing path. The
// moved inode keeps its old birth, so its first open read as Changed, and
// a server without didRenameFiles (Pyrefly) kept the failed lookup.
@@ -121,6 +121,7 @@ describe("#3405 M3406-1 — didSave payload from the explicit lsp_diagnostics qu
getDiagnosticBinding: vi.fn(() => undefined),
// The REAL notify path, against the mock transport on `state`.
notify: {
announceCreated: () => undefined,
open: (
filePath: string,
content: string,
@@ -112,7 +112,10 @@ function makeSilentClient(serverId: string, root: string) {
getLaunchVariant: () => undefined,
serverId,
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (_filePath: string, ms: number) => {
await new Promise<void>((resolve) => {
const t = setTimeout(resolve, ms);
@@ -119,7 +119,10 @@ function makeSilentClient(serverId: string, root: string) {
getLaunchVariant: () => undefined,
serverId,
root,
notify: { open: vi.fn(async () => {}) },
notify: {
announceCreated: () => undefined,
open: vi.fn(async () => {}),
},
waitForDiagnostics: vi.fn(async (_filePath: string, ms: number) => {
await new Promise<void>((resolve) => {
const t = setTimeout(resolve, ms);
+1 -3
View File
@@ -1977,9 +1977,7 @@ async function collectBatchDiagnostics(
});
// #4320: a module created since a file was cached must reach its servers
// before any lookup below, whatever the order of `files`.
if (typeof lspService.announceCreatedFiles === "function") {
lspService.announceCreatedFiles(files);
}
lspService.announceCreatedFiles(files);
const groups = groupFilesByPrimaryServer(files);
await runPerServerGroups(
groups,