From 029611ddc7bd69ec10cf88a80465f570c376dc66 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 16:01:58 -0500 Subject: [PATCH 1/2] fix(java): one stopped event per JDI event set (#1383) A step that lands on a line with a breakpoint arrives from JDI as a StepEvent and a BreakpointEvent in one event set. The bridge sent a DAP stopped event for each, so one suspension became two stops in the core (measured: 49 of 300 step_over calls on a loop with one breakpoint line). The event loop now collects one stop per set and sends it after every event of the set has been handled. A stopping breakpoint takes precedence over a step, as debugpy and js-debug report that step; an exception takes precedence over both. Conditions, the one-shot step request, class-prepare handling and the resume decision are unchanged. Test: an integration case steps onto a breakpoint line and asserts one stopped event with reason breakpoint. It fails on the previous bridge with [step, breakpoint]. The change and the test were written by a GPT worker. The manager session verified the failing-first run and wrote the changelog entry. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1383.fixed.md | 1 + packages/adapter-java/java/JdiDapServer.java | 24 +++- .../integration/java-event-set-stop.test.ts | 134 ++++++++++++++++++ 3 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 changelog.d/1383.fixed.md create mode 100644 tests/adapters/java/integration/java-event-set-stop.test.ts diff --git a/changelog.d/1383.fixed.md b/changelog.d/1383.fixed.md new file mode 100644 index 00000000..b81d498a --- /dev/null +++ b/changelog.d/1383.fixed.md @@ -0,0 +1 @@ +**A Java step that lands on a line with a breakpoint is announced as one stop** — JDI delivers the step's completion and the breakpoint hit as two events in one event set, and the bridge sent a `stopped` event for each: `step`, then `breakpoint` a millisecond later, for one suspension (49 of 300 `step_over` calls in a loop with one breakpoint line). The bridge now sends one `stopped` per event set. When a set holds both, the stop is reported as `breakpoint`, which is what debugpy and js-debug report for the same step; an exception in the set takes precedence over both (#1383) diff --git a/packages/adapter-java/java/JdiDapServer.java b/packages/adapter-java/java/JdiDapServer.java index 7234d8db..d374a55f 100644 --- a/packages/adapter-java/java/JdiDapServer.java +++ b/packages/adapter-java/java/JdiDapServer.java @@ -1867,6 +1867,7 @@ private void startEventLoop() { boolean resume = true; boolean stopped = false; // true once a stopping event (breakpoint/step/exception) is seen + Map stoppedBody = null; for (Event event : eventSet) { if (event instanceof BreakpointEvent) { @@ -1888,7 +1889,14 @@ private void startEventLoop() { boolean allStopped = bpr == null || bpr.suspendPolicy() == EventRequest.SUSPEND_ALL; // Function breakpoints report their own DAP stop reason boolean isFnBp = bpr != null && bpr.getProperty("jdi-fnbp-name") != null; - sendStoppedEvent(isFnBp ? "function breakpoint" : "breakpoint", bpe.thread().uniqueID(), allStopped); + // One suspension can contain both step and breakpoint events, + // in either order. A stopping breakpoint takes precedence. + if (stoppedBody == null || "step".equals(stoppedBody.get("reason"))) { + stoppedBody = new HashMap<>(); + stoppedBody.put("reason", isFnBp ? "function breakpoint" : "breakpoint"); + stoppedBody.put("threadId", bpe.thread().uniqueID()); + stoppedBody.put("allThreadsStopped", allStopped); + } resume = false; stopped = true; @@ -1897,7 +1905,12 @@ private void startEventLoop() { // Delete the step request (one-shot) vm.eventRequestManager().deleteEventRequest(se.request()); log("Step completed: " + se.location()); - sendStoppedEvent("step", se.thread().uniqueID()); + if (stoppedBody == null) { + stoppedBody = new HashMap<>(); + stoppedBody.put("reason", "step"); + stoppedBody.put("threadId", se.thread().uniqueID()); + stoppedBody.put("allThreadsStopped", true); + } resume = false; stopped = true; @@ -1947,19 +1960,22 @@ private void startEventLoop() { log("Exception: " + fqcn + " at " + ee.location()); lastException = new ExceptionStop(exObj, ee.thread().uniqueID(), ee.catchLocation() != null); String message = throwableMessage(exObj); - lastStopAllThreads = true; // exception requests are SUSPEND_ALL Map body = new HashMap<>(); body.put("reason", "exception"); body.put("threadId", ee.thread().uniqueID()); body.put("text", fqcn); body.put("description", message != null ? fqcn + ": " + message : fqcn); body.put("allThreadsStopped", true); - sendEvent("stopped", body); + stoppedBody = body; resume = false; stopped = true; } } + if (stoppedBody != null) { + lastStopAllThreads = Boolean.TRUE.equals(stoppedBody.get("allThreadsStopped")); + sendEvent("stopped", stoppedBody); + } if (resume) { eventSet.resume(); } diff --git a/tests/adapters/java/integration/java-event-set-stop.test.ts b/tests/adapters/java/integration/java-event-set-stop.test.ts new file mode 100644 index 00000000..cbb9a89f --- /dev/null +++ b/tests/adapters/java/integration/java-event-set-stop.test.ts @@ -0,0 +1,134 @@ +/** A step landing on a breakpoint is one JDI suspension (issue #1383). */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { execFileSync, spawn, type ChildProcess } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import net from 'node:net'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { setTimeout as settle } from 'node:timers/promises'; +import type { DebugProtocol } from '@vscode/debugprotocol'; +import { TcpDapClient } from '../../../test-utils/helpers/dap-test-client.js'; + +const ROOT = fileURLToPath(new URL('../../../../', import.meta.url)); +const FIXTURE = [ + 'public class EventSetStop {', + ' public static void main(String[] args) {', + ' int n = 1;', + ' n++;', + ' System.out.println(n);', + ' }', + '}', + '' +].join('\n'); + +/** Wait on this child's output, without probing the bridge's single-client socket. */ +function announced(child: ChildProcess, pattern: RegExp): Promise { + return new Promise((resolve, reject) => { + let output = ''; + const cleanup = (): void => { + clearTimeout(timer); + child.stdout?.off('data', read); + child.stderr?.off('data', read); + child.off('error', fail); + child.off('exit', exited); + }; + const fail = (error: Error): void => { cleanup(); reject(error); }; + const exited = (code: number | null): void => fail(new Error(`Child exited (${code}): ${output}`)); + const read = (chunk: Buffer): void => { + output += chunk.toString(); + const match = pattern.exec(output); + if (match) { cleanup(); resolve(match); } + }; + const timer = setTimeout(() => fail(new Error(`Child startup timed out: ${output}`)), 10_000); + child.stdout?.on('data', read); + child.stderr?.on('data', read); + child.once('error', fail); + child.once('exit', exited); + }); +} + +/** Only the retained handle of a child we started may be terminated. */ +async function stopChild(child: ChildProcess | undefined): Promise { + if (!child || child.exitCode !== null || child.signalCode !== null) return; + const exited = once(child, 'exit'); + child.kill(); + await exited; +} + +describe('One Java stopped event per event set @requires-java', () => { + let work: string; + let source: string; + + beforeAll(() => { + const cache = path.join(ROOT, 'node_modules', '.cache'); + fs.mkdirSync(cache, { recursive: true }); + work = fs.mkdtempSync(path.join(cache, 'java-event-set-')); + source = path.join(work, 'EventSetStop.java'); + fs.writeFileSync(source, FIXTURE); + execFileSync('javac', [ + '-g', '-d', work, + path.join(ROOT, 'packages', 'adapter-java', 'java', 'JdiDapServer.java'), source + ], { windowsHide: true }); + }, 30_000); + + afterAll(() => { + if (work) fs.rmSync(work, { recursive: true, force: true }); + }); + + it('next onto a breakpoint emits exactly one stopped event with reason breakpoint', async () => { + const client = new TcpDapClient(); + let bridge: ChildProcess | undefined; + let jvm: ChildProcess | undefined; + try { + const reservation = net.createServer(); + reservation.listen(0, '127.0.0.1'); + await once(reservation, 'listening'); + const port = (reservation.address() as net.AddressInfo).port; + await new Promise((resolve, reject) => reservation.close(error => error ? reject(error) : resolve())); + + bridge = spawn('java', [ + '-Djava.net.preferIPv4Stack=true', '-cp', work, 'JdiDapServer', '--port', String(port), '--debug' + ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + await announced(bridge, /JdiDapServer listening on port/); + await client.connect(port); + expect(await client.request('initialize', { adapterID: 'java' })).toMatchObject({ success: true }); + expect(await client.request('setBreakpoints', { + source: { path: source }, breakpoints: [{ line: 3 }, { line: 4 }] + })).toMatchObject({ success: true }); + + jvm = spawn('java', [ + '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0', + '-cp', work, 'EventSetStop' + ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + const jdwp = await announced(jvm, /Listening for transport dt_socket at address: (\d+)/); + expect(await client.request('attach', { host: '127.0.0.1', port: Number(jdwp[1]) })).toMatchObject({ success: true }); + expect(await client.request('configurationDone')).toMatchObject({ success: true }); + expect(await client.request('continue', { threadId: 1 })).toMatchObject({ success: true }); + const initial = await client.waitForEvent('stopped') as DebugProtocol.StoppedEvent; + expect(initial.body.reason).toBe('breakpoint'); + const stack = await client.request('stackTrace', { threadId: initial.body.threadId }) as DebugProtocol.StackTraceResponse; + expect(stack.body.stackFrames[0].line).toBe(3); + + const firstFrame = client.frames.length; + expect(await client.request('next', { threadId: initial.body.threadId })).toMatchObject({ success: true }); + // waitForEvent retains history: start at the saved frame index to wait + // for a fresh stop, then collect all stops during a short settle window. + await expect.poll(() => client.frames.slice(firstFrame).some(message => + message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped' + ), { timeout: 10_000 }).toBe(true); + await settle(200); + const stops = client.frames.slice(firstFrame).filter((message): message is DebugProtocol.StoppedEvent => + message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped' + ); + expect(stops.map(stop => stop.body.reason)).toEqual(['breakpoint']); + expect(stops[0].body).toMatchObject({ threadId: initial.body.threadId, allThreadsStopped: true }); + const landed = await client.request('stackTrace', { threadId: initial.body.threadId }) as DebugProtocol.StackTraceResponse; + expect(landed.body.stackFrames[0].line).toBe(4); + } finally { + client.close(); + await stopChild(bridge); + await stopChild(jvm); + } + }, 30_000); +}); From f70ff96e327185a2f6323a938143d5f6da2278d9 Mon Sep 17 00:00:00 2001 From: JF Date: Sun, 29 Nov 2026 16:27:42 -0500 Subject: [PATCH 2/2] fix(java): take allThreadsStopped from the event set (#1383) Review finding on the previous commit. A step request suspends all threads; a line breakpoint with suspendPolicy "thread" suspends one. When a step lands on such a breakpoint JDI suspends by the set's most restrictive policy, so every thread is suspended, but the bridge took allThreadsStopped from the breakpoint request alone and reported false. The next continue then resumed that one thread and left every other thread suspended. With the order HotSpot delivers the two events this predates the previous commit. The one stopped event of a set, and lastStopAllThreads, now take the value from eventSet.suspendPolicy(). Tests: the integration file grows from one case to four. A second plain step (the step branch must stop by itself), a false-condition breakpoint together with a step (reason step), stepIn onto a function breakpoint (reason function breakpoint), and a two-thread program stepped onto a thread-policy breakpoint and continued to its end. The last fails on the previous commit. The test also retries the bridge's start when its reserved port is lost, keeps draining the bridge's pipes, and ends its two children independently. Found by a Gemini review with a mutation pass; written by the GPT worker that wrote the previous commit; verified by the manager session, which also extended the changelog entry. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1383.fixed.md | 2 +- packages/adapter-java/java/JdiDapServer.java | 8 +- .../integration/java-event-set-stop.test.ts | 240 +++++++++++++----- 3 files changed, 184 insertions(+), 66 deletions(-) diff --git a/changelog.d/1383.fixed.md b/changelog.d/1383.fixed.md index b81d498a..a579f0c1 100644 --- a/changelog.d/1383.fixed.md +++ b/changelog.d/1383.fixed.md @@ -1 +1 @@ -**A Java step that lands on a line with a breakpoint is announced as one stop** — JDI delivers the step's completion and the breakpoint hit as two events in one event set, and the bridge sent a `stopped` event for each: `step`, then `breakpoint` a millisecond later, for one suspension (49 of 300 `step_over` calls in a loop with one breakpoint line). The bridge now sends one `stopped` per event set. When a set holds both, the stop is reported as `breakpoint`, which is what debugpy and js-debug report for the same step; an exception in the set takes precedence over both (#1383) +**A Java step that lands on a line with a breakpoint is announced as one stop** — JDI delivers the step's completion and the breakpoint hit as two events in one event set, and the bridge sent a `stopped` event for each: `step`, then `breakpoint` a millisecond later, for one suspension (49 of 300 `step_over` calls in a loop with one breakpoint line). The bridge now sends one `stopped` per event set. When a set holds both, the stop is reported as `breakpoint`, which is what debugpy and js-debug report for the same step; an exception in the set takes precedence over both. The stop's `allThreadsStopped` now comes from the event set as well: stepping onto a breakpoint with `suspendPolicy: "thread"` reported that one thread had stopped while the JVM had suspended all of them, and the next `continue_execution` then left every other thread suspended (#1383) diff --git a/packages/adapter-java/java/JdiDapServer.java b/packages/adapter-java/java/JdiDapServer.java index d374a55f..1feeffac 100644 --- a/packages/adapter-java/java/JdiDapServer.java +++ b/packages/adapter-java/java/JdiDapServer.java @@ -1886,7 +1886,6 @@ private void startEventLoop() { } log("Breakpoint hit: " + bpe.location()); - boolean allStopped = bpr == null || bpr.suspendPolicy() == EventRequest.SUSPEND_ALL; // Function breakpoints report their own DAP stop reason boolean isFnBp = bpr != null && bpr.getProperty("jdi-fnbp-name") != null; // One suspension can contain both step and breakpoint events, @@ -1895,7 +1894,6 @@ private void startEventLoop() { stoppedBody = new HashMap<>(); stoppedBody.put("reason", isFnBp ? "function breakpoint" : "breakpoint"); stoppedBody.put("threadId", bpe.thread().uniqueID()); - stoppedBody.put("allThreadsStopped", allStopped); } resume = false; stopped = true; @@ -1909,7 +1907,6 @@ private void startEventLoop() { stoppedBody = new HashMap<>(); stoppedBody.put("reason", "step"); stoppedBody.put("threadId", se.thread().uniqueID()); - stoppedBody.put("allThreadsStopped", true); } resume = false; stopped = true; @@ -1965,7 +1962,6 @@ private void startEventLoop() { body.put("threadId", ee.thread().uniqueID()); body.put("text", fqcn); body.put("description", message != null ? fqcn + ": " + message : fqcn); - body.put("allThreadsStopped", true); stoppedBody = body; resume = false; stopped = true; @@ -1973,7 +1969,9 @@ private void startEventLoop() { } if (stoppedBody != null) { - lastStopAllThreads = Boolean.TRUE.equals(stoppedBody.get("allThreadsStopped")); + boolean allStopped = eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL; + stoppedBody.put("allThreadsStopped", allStopped); + lastStopAllThreads = allStopped; sendEvent("stopped", stoppedBody); } if (resume) { diff --git a/tests/adapters/java/integration/java-event-set-stop.test.ts b/tests/adapters/java/integration/java-event-set-stop.test.ts index cbb9a89f..bb102248 100644 --- a/tests/adapters/java/integration/java-event-set-stop.test.ts +++ b/tests/adapters/java/integration/java-event-set-stop.test.ts @@ -1,5 +1,5 @@ /** A step landing on a breakpoint is one JDI suspension (issue #1383). */ -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { execFileSync, spawn, type ChildProcess } from 'node:child_process'; import { once } from 'node:events'; import fs from 'node:fs'; @@ -21,6 +21,41 @@ const FIXTURE = [ '}', '' ].join('\n'); +const FUNCTION_FIXTURE = [ + 'public class EventSetFunction {', + ' public static void main(String[] args) {', + ' int n = compute(1);', + ' System.out.println(n);', + ' }', + ' static int compute(int n) {', + ' return n + 1;', + ' }', + '}', + '' +].join('\n'); +const THREAD_FIXTURE = [ + 'import java.util.concurrent.CountDownLatch;', + 'public class EventSetThreads {', + ' static final CountDownLatch ready = new CountDownLatch(1);', + ' static final CountDownLatch release = new CountDownLatch(1);', + ' public static void main(String[] args) throws InterruptedException {', + ' Thread worker = new Thread(EventSetThreads::work);', + ' worker.start();', + ' ready.await();', + ' int n = 1;', + ' release.countDown();', + ' worker.join();', + ' System.out.println(n);', + ' }', + ' static void work() {', + ' ready.countDown();', + ' try { release.await(); } catch (InterruptedException e) { throw new RuntimeException(e); }', + ' }', + '}', + '' +].join('\n'); + +class StartupExitError extends Error {} /** Wait on this child's output, without probing the bridge's single-client socket. */ function announced(child: ChildProcess, pattern: RegExp): Promise { @@ -30,11 +65,14 @@ function announced(child: ChildProcess, pattern: RegExp): Promise { cleanup(); reject(error); }; - const exited = (code: number | null): void => fail(new Error(`Child exited (${code}): ${output}`)); + const exited = (code: number | null): void => fail(new StartupExitError(`Child exited (${code}): ${output}`)); const read = (chunk: Buffer): void => { output += chunk.toString(); const match = pattern.exec(output); @@ -56,79 +94,161 @@ async function stopChild(child: ChildProcess | undefined): Promise { await exited; } +/** Retry a lost port reservation if the bridge exits before announcing readiness. */ +async function startBridge(work: string): Promise<{ child: ChildProcess; port: number }> { + for (let attempt = 0; attempt < 3; attempt++) { + const reservation = net.createServer(); + reservation.listen(0, '127.0.0.1'); + await once(reservation, 'listening'); + const port = (reservation.address() as net.AddressInfo).port; + await new Promise((resolve, reject) => reservation.close(error => error ? reject(error) : resolve())); + const child = spawn('java', [ + '-Djava.net.preferIPv4Stack=true', '-cp', work, 'JdiDapServer', '--port', String(port), '--debug' + ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + try { + await announced(child, /JdiDapServer listening on port/); + return { child, port }; + } catch (error) { + await stopChild(child); + if (!(error instanceof StartupExitError) || attempt === 2) throw error; + } + } + throw new Error('Bridge startup attempts exhausted'); +} + +/** History stays in TcpDapClient, so collect only frames after this command. */ +async function stoppedAfter(client: TcpDapClient, command: string, threadId: number): Promise { + const firstFrame = client.frames.length; + expect(await client.request(command, { threadId })).toMatchObject({ success: true }); + const stops = (): DebugProtocol.StoppedEvent[] => client.frames.slice(firstFrame).filter( + (message): message is DebugProtocol.StoppedEvent => + message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped' + ); + await expect.poll(() => stops().length, { timeout: 10_000 }).toBeGreaterThan(0); + await settle(200); + expect(stops()).toHaveLength(1); + return stops()[0]; +} + +async function expectLine(client: TcpDapClient, threadId: number, line: number): Promise { + const stack = await client.request('stackTrace', { threadId }) as DebugProtocol.StackTraceResponse; + expect(stack.success).toBe(true); + expect(stack.body.stackFrames[0].line).toBe(line); +} + describe('One Java stopped event per event set @requires-java', () => { let work: string; - let source: string; + let client: TcpDapClient; + let bridge: ChildProcess | undefined; + let jvm: ChildProcess | undefined; beforeAll(() => { const cache = path.join(ROOT, 'node_modules', '.cache'); fs.mkdirSync(cache, { recursive: true }); work = fs.mkdtempSync(path.join(cache, 'java-event-set-')); - source = path.join(work, 'EventSetStop.java'); - fs.writeFileSync(source, FIXTURE); + const sources = Object.entries({ EventSetStop: FIXTURE, EventSetFunction: FUNCTION_FIXTURE, EventSetThreads: THREAD_FIXTURE }) + .map(([name, text]) => { + const source = path.join(work, `${name}.java`); + fs.writeFileSync(source, text); + return source; + }); execFileSync('javac', [ '-g', '-d', work, - path.join(ROOT, 'packages', 'adapter-java', 'java', 'JdiDapServer.java'), source + path.join(ROOT, 'packages', 'adapter-java', 'java', 'JdiDapServer.java'), ...sources ], { windowsHide: true }); }, 30_000); + afterEach(async () => { + client?.close(); + const results = await Promise.allSettled([stopChild(bridge), stopChild(jvm)]); + bridge = undefined; + jvm = undefined; + const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Child cleanup failed'); + }); + afterAll(() => { - if (work) fs.rmSync(work, { recursive: true, force: true }); + if (work) fs.rmSync(work, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); }); - it('next onto a breakpoint emits exactly one stopped event with reason breakpoint', async () => { - const client = new TcpDapClient(); - let bridge: ChildProcess | undefined; - let jvm: ChildProcess | undefined; - try { - const reservation = net.createServer(); - reservation.listen(0, '127.0.0.1'); - await once(reservation, 'listening'); - const port = (reservation.address() as net.AddressInfo).port; - await new Promise((resolve, reject) => reservation.close(error => error ? reject(error) : resolve())); - - bridge = spawn('java', [ - '-Djava.net.preferIPv4Stack=true', '-cp', work, 'JdiDapServer', '--port', String(port), '--debug' - ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); - await announced(bridge, /JdiDapServer listening on port/); - await client.connect(port); - expect(await client.request('initialize', { adapterID: 'java' })).toMatchObject({ success: true }); - expect(await client.request('setBreakpoints', { - source: { path: source }, breakpoints: [{ line: 3 }, { line: 4 }] - })).toMatchObject({ success: true }); - - jvm = spawn('java', [ - '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0', - '-cp', work, 'EventSetStop' - ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); - const jdwp = await announced(jvm, /Listening for transport dt_socket at address: (\d+)/); - expect(await client.request('attach', { host: '127.0.0.1', port: Number(jdwp[1]) })).toMatchObject({ success: true }); - expect(await client.request('configurationDone')).toMatchObject({ success: true }); - expect(await client.request('continue', { threadId: 1 })).toMatchObject({ success: true }); - const initial = await client.waitForEvent('stopped') as DebugProtocol.StoppedEvent; - expect(initial.body.reason).toBe('breakpoint'); - const stack = await client.request('stackTrace', { threadId: initial.body.threadId }) as DebugProtocol.StackTraceResponse; - expect(stack.body.stackFrames[0].line).toBe(3); - - const firstFrame = client.frames.length; - expect(await client.request('next', { threadId: initial.body.threadId })).toMatchObject({ success: true }); - // waitForEvent retains history: start at the saved frame index to wait - // for a fresh stop, then collect all stops during a short settle window. - await expect.poll(() => client.frames.slice(firstFrame).some(message => - message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped' - ), { timeout: 10_000 }).toBe(true); - await settle(200); - const stops = client.frames.slice(firstFrame).filter((message): message is DebugProtocol.StoppedEvent => - message.type === 'event' && (message as DebugProtocol.Event).event === 'stopped' - ); - expect(stops.map(stop => stop.body.reason)).toEqual(['breakpoint']); - expect(stops[0].body).toMatchObject({ threadId: initial.body.threadId, allThreadsStopped: true }); - const landed = await client.request('stackTrace', { threadId: initial.body.threadId }) as DebugProtocol.StackTraceResponse; - expect(landed.body.stackFrames[0].line).toBe(4); - } finally { - client.close(); - await stopChild(bridge); - await stopChild(jvm); + async function attach( + mainClass: string, + breakpoints: Array<{ line: number; condition?: string; suspendPolicy?: string }>, + functionBreakpoints: Array<{ name: string }> = [] + ): Promise { + client = new TcpDapClient(); + const started = await startBridge(work); + bridge = started.child; + await client.connect(started.port); + expect(await client.request('initialize', { adapterID: 'java' })).toMatchObject({ success: true }); + expect(await client.request('setBreakpoints', { + source: { path: path.join(work, `${mainClass}.java`) }, breakpoints + })).toMatchObject({ success: true }); + if (functionBreakpoints.length) { + expect(await client.request('setFunctionBreakpoints', { breakpoints: functionBreakpoints })).toMatchObject({ success: true }); } + jvm = spawn('java', [ + '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0', + '-cp', work, mainClass + ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + const jdwp = await announced(jvm, /Listening for transport dt_socket at address: (\d+)/); + expect(await client.request('attach', { host: '127.0.0.1', port: Number(jdwp[1]) })).toMatchObject({ success: true }); + expect(await client.request('configurationDone')).toMatchObject({ success: true }); + expect(await client.request('continue', { threadId: 1 })).toMatchObject({ success: true }); + const initial = await client.waitForEvent('stopped') as DebugProtocol.StoppedEvent; + expect(initial.body.reason).toBe('breakpoint'); + await expectLine(client, initial.body.threadId!, breakpoints[0].line); + return initial; + } + + it('next onto a breakpoint emits one breakpoint stop, then next emits one plain step', async () => { + const initial = await attach('EventSetStop', [{ line: 3 }, { line: 4 }]); + const threadId = initial.body.threadId!; + const breakpoint = await stoppedAfter(client, 'next', threadId); + expect(breakpoint.body).toMatchObject({ reason: 'breakpoint', threadId, allThreadsStopped: true }); + await expectLine(client, threadId, 4); + + const step = await stoppedAfter(client, 'next', threadId); + expect(step.body).toMatchObject({ reason: 'step', threadId, allThreadsStopped: true }); + await expectLine(client, threadId, 5); + }, 30_000); + + it('next onto a false conditional breakpoint emits exactly one step stop', async () => { + const initial = await attach('EventSetStop', [{ line: 3 }, { line: 4, condition: 'n < 0' }]); + const threadId = initial.body.threadId!; + const step = await stoppedAfter(client, 'next', threadId); + expect(step.body).toMatchObject({ reason: 'step', threadId, allThreadsStopped: true }); + await expectLine(client, threadId, 4); + }, 30_000); + + it('stepIn onto a function breakpoint emits exactly one function breakpoint stop', async () => { + const initial = await attach('EventSetFunction', [{ line: 3 }], [{ name: 'EventSetFunction.compute' }]); + const threadId = initial.body.threadId!; + const step = await stoppedAfter(client, 'stepIn', threadId); + expect(step.body).toMatchObject({ reason: 'function breakpoint', threadId, allThreadsStopped: true }); + await expectLine(client, threadId, 7); + }, 30_000); + + it('next onto a thread-policy breakpoint reports all threads stopped and continue finishes both threads', async () => { + const initial = await attach('EventSetThreads', [ + { line: 9, suspendPolicy: 'thread' }, { line: 10, suspendPolicy: 'thread' } + ]); + const threadId = initial.body.threadId!; + expect(initial.body.allThreadsStopped).toBe(false); + // Idempotent thread pause seeds lastStopAllThreads=false through a separate + // path, so omitting the event-set bookkeeping update is observable too. + const paused = await stoppedAfter(client, 'pause', threadId); + expect(paused.body).toMatchObject({ reason: 'pause', allThreadsStopped: false }); + + const step = await stoppedAfter(client, 'next', threadId); + expect(step.body.reason).toBe('breakpoint'); + await expectLine(client, threadId, 10); + expect.soft(step.body.allThreadsStopped).toBe(true); + const continued = await client.request('continue', { threadId }); + expect(continued.success).toBe(true); + expect.soft(continued.body.allThreadsContinued).toBe(true); + // main releases the worker and joins it. Resuming only main leaves the + // worker suspended forever, so the VM cannot terminate. + await client.waitForEvent('terminated', 3_000); }, 30_000); });