diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 097dd091c..104e9729d 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -1624,6 +1624,7 @@ impl DebugManager { // DAP: a response without the flag continued every thread. let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true); session.suspended.resumed(ticket, thread_id, all); + stream_trace::release_done(&session); session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all }); Ok(()) } @@ -1672,6 +1673,7 @@ impl DebugManager { step_settled(&session, sent)?; // A step runs its thread; other threads stopped by their own events stay stopped. session.suspended.resumed(ticket, thread_id, false); + stream_trace::release_done(&session); session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true }); Ok(()) } @@ -1783,6 +1785,7 @@ impl DebugManager { .await; step_settled(&session, sent)?; session.suspended.resumed(ticket, thread_id, false); + stream_trace::release_done(&session); session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true }); Ok(()) } diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index 1238b2d64..a62a74f35 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -116,6 +116,8 @@ pub(crate) struct Session { pub jvm_memory: tokio::sync::Mutex, pub stream_tracer: parking_lot::Mutex>>, pub(crate) stream_trace: parking_lot::Mutex>, + /// The last trace that finished, until the stop its records were read in ends. + pub(crate) stream_trace_done: parking_lot::Mutex>, /// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`]. pub(crate) quirks: kotlin_lsp::Quirks, pub(crate) unity_startup_activity: Mutex, @@ -281,6 +283,7 @@ impl Session { jvm_memory: tokio::sync::Mutex::default(), stream_tracer: parking_lot::Mutex::new(None), stream_trace: parking_lot::Mutex::new(None), + stream_trace_done: parking_lot::Mutex::new(None), quirks: kotlin_lsp::Quirks::default(), unity_startup_activity: Mutex::new(Instant::now()), } @@ -774,6 +777,7 @@ async fn on_event(mgr: &Arc, s: &Arc, event: &str, mut bo // DAP: an event without the flag continues its thread alone. The UI keeps treating // it as all threads; the suspension, which holds only threads that stopped, need not. s.suspended.continued(int("threadId"), all.unwrap_or(false)); + crate::stream_trace::release_done(s); s.emit(DebugEvent::Continued { thread_id: int("threadId").unwrap_or(0), all_threads_continued: all.unwrap_or(true), diff --git a/crates/ide-dap/src/stream_trace.rs b/crates/ide-dap/src/stream_trace.rs index df05a87a3..5f199e702 100644 --- a/crates/ide-dap/src/stream_trace.rs +++ b/crates/ide-dap/src/stream_trace.rs @@ -88,6 +88,32 @@ pub enum TraceUnavailable { }, } +/// A trace that finished. Its records keep their objects from being collected until the stop they +/// were read in ends; then the UI no longer shows them and [`release_done`] lets them go. +pub(crate) struct DoneTrace { + tracer: Arc, + target: VmTarget, + id: TraceId, +} + +/// The stop a finished trace was read in ended (a resume, a step, a `continued` event). +pub(crate) fn release_done(s: &Session) { + let Some(done) = s.stream_trace_done.lock().take() else { return }; + let ended = s.ended.clone(); + let session = s.id.0; + tokio::spawn(async move { + tokio::select! { + biased; + () = ended.cancelled() => {} + result = done.tracer.release(&done.target, done.id) => { + if let Err(e) = result { + tracing::debug!(session, trace = done.id, "releasing a finished stream trace: {e}"); + } + } + } + }); +} + /// The session's running trace; `id` is `None` until `arm` answers. pub(crate) struct ActiveTrace { tracer: Arc, @@ -181,10 +207,30 @@ pub(crate) async fn run( if !s.suspended.get() { return unavailable(TraceUnavailable::NotSuspended); } - let mut trace = - Trace { mgr, s, tracer: &*tracer, target: &target, thread_id, progress, id: None, last: Counts::default() }; + // The bundle releases the previous trace itself when this one arms. + s.stream_trace_done.lock().take(); + static TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let token = + format!("{}-{}-{}", std::process::id(), s.id.0, TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)); + let mut trace = Trace { + mgr, + s, + tracer: &*tracer, + target: &target, + thread_id, + progress, + token, + arm_sent: false, + id: None, + last: Counts::default(), + }; match trace.drive(plan, cancel).await { - Ok(run) => run, + Ok(run) => { + if let (TraceRun::Done { .. }, Some(id)) = (&run, trace.id) { + *s.stream_trace_done.lock() = Some(DoneTrace { tracer: tracer.clone(), target: target.clone(), id }); + } + run + } Err(run) => { // A stop from now on is the user's to see. set_running(s, false); @@ -231,6 +277,9 @@ struct Trace<'a, P> { target: &'a VmTarget, thread_id: i64, progress: &'a P, + /// Names the trace to the bundle before `arm` answers (see [`StreamTracer::release_armed`]). + token: String, + arm_sent: bool, /// Set once `arm` answers. id: Option, last: Counts, @@ -241,8 +290,9 @@ impl Trace<'_, P> { async fn drive(&mut self, plan: &Value, cancel: &CancellationToken) -> Result { let (s, tracer, target) = (self.s, self.tracer, self.target); self.report(TracePhase::Arming); + self.arm_sent = true; let id = self - .until_ended(tracer.arm(target, self.thread_id, plan, BUDGET)) + .until_ended(tracer.arm(target, self.thread_id, plan, BUDGET, &self.token)) .await? .map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?; self.id = Some(id); @@ -313,14 +363,20 @@ impl Trace<'_, P> { /// After a trace that ended early. Left to the bundle, an armed trace would keep every /// breakpoint off and a parked one its thread suspended behind java-debug's back; the bundle /// undoes either, or does so once a terminal still running returns. Not after a finished - /// trace: the records it unpins are the values the result shows. + /// trace: the records it unpins are the values the result shows ([`release_done`] does, once + /// that stop ends). An `arm` that never answered (it timed out) may still have armed: released + /// by its token. async fn release(&self) { - let Some(id) = self.id else { return }; if self.s.ended.is_cancelled() { return; } - if let Ok(Err(e)) = self.until_ended(self.tracer.release(self.target, id)).await { - tracing::debug!(session = self.s.id.0, trace = id, "stream trace release: {e}"); + let work = match self.id { + Some(id) => self.tracer.release(self.target, id), + None if self.arm_sent => self.tracer.release_armed(self.target, &self.token), + None => return, + }; + if let Ok(Err(e)) = self.until_ended(work).await { + tracing::debug!(session = self.s.id.0, trace = ?self.id, "stream trace release: {e}"); } } diff --git a/crates/ide-dap/src/tests/stream_trace.rs b/crates/ide-dap/src/tests/stream_trace.rs index 5cec0852c..99a1ed160 100644 --- a/crates/ide-dap/src/tests/stream_trace.rs +++ b/crates/ide-dap/src/tests/stream_trace.rs @@ -55,6 +55,7 @@ impl StreamTracer for FakeTracer { _thread_id: i64, _plan: &'a Value, _budget: u32, + _token: &'a str, ) -> InspectFuture<'a, TraceId> { self.record("arm", target); let error = self.arm_error.lock().clone(); @@ -96,6 +97,11 @@ impl StreamTracer for FakeTracer { self.record("release", target); Box::pin(async { Ok(()) }) } + + fn release_armed<'a>(&'a self, target: &'a VmTarget, _token: &'a str) -> InspectFuture<'a, ()> { + self.record("releaseArmed", target); + Box::pin(async { Ok(()) }) + } } fn collected() -> TraceCollected { @@ -443,6 +449,36 @@ async fn a_finished_trace_is_not_released() { assert!(!tracer.names().contains(&"release"), "{:?}", tracer.names()); } +#[tokio::test] +async fn a_finished_trace_is_released_once_the_program_runs_on() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([parked()]); + let id = stopped_java(&h, &tracer).await; + assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Done { .. })); + + h.manager.resume(id, 1).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while !tracer.names().contains(&"release") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the finished trace was not released"); + assert_eq!(tracer.names().iter().filter(|n| **n == "release").count(), 1); +} + +#[tokio::test] +async fn an_arm_without_a_reply_is_released_by_its_token() { + // The bundle may still finish arming after the reply timed out: its breakpoints would stay off. + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + *tracer.arm_error.lock() = Some(InspectError::TimedOut); + + assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Failed { .. })); + assert_eq!(tracer.names(), ["arm", "releaseArmed"]); +} + #[tokio::test] async fn refused_stop_leaves_the_outcome_to_wait() { let h = harness(java_debug()); diff --git a/crates/ide-host/src/ops/stream_trace.rs b/crates/ide-host/src/ops/stream_trace.rs index 4015c63d8..0eded7c05 100644 --- a/crates/ide-host/src/ops/stream_trace.rs +++ b/crates/ide-host/src/ops/stream_trace.rs @@ -379,6 +379,10 @@ fn ready( }, }; let mut linked = link_trace(plan, &recording, collected.skipped_breakpoints); + // A stream made parallel before the chain's statement, which the bundle found so at run time. + if collected.sequentialized && !plan.sequentialize { + linked.banners.push(TraceBanner::Sequentialized); + } if resumed_stops > 0 { linked.banners.push(TraceBanner::BreakpointsResumed { count: resumed_stops }); } diff --git a/crates/ide-host/src/ops/stream_trace/tests.rs b/crates/ide-host/src/ops/stream_trace/tests.rs index cf0e63b63..550426094 100644 --- a/crates/ide-host/src/ops/stream_trace/tests.rs +++ b/crates/ide-host/src/ops/stream_trace/tests.rs @@ -442,3 +442,20 @@ fn chain_info_steps_keep_modifiers() { let found = chains_at(service(), &snap, &frame(1), true, true, &CancellationToken::new()).unwrap(); assert_eq!(found[0].info.steps, ["filter", "unordered", "map"]); } + +#[test] +fn ready_says_a_stream_found_parallel_at_run_time_ran_sequentially() { + let java = LanguageId::new("java"); + let snap = Snapshot::text(&java, SOURCE); + let found = chains_at(service(), &snap, &frame(line_of("C_SPIKE")), true, true, &CancellationToken::new()).unwrap(); + let Candidate { info, chain } = found.into_iter().next().unwrap(); + let chain = chain.unwrap(); + let plan = real_run_plan(&chain).unwrap(); + assert!(!plan.sequentialize); + + let collected = TraceCollected { sequentialized: true, ..spike_collected() }; + let StreamTraceResult::Ready { banners, .. } = ready(info, &chain, &plan, collected, 9, 0) else { + panic!("not ready"); + }; + assert!(banners.contains(&TraceBanner::Sequentialized), "{banners:?}"); +} diff --git a/crates/ide-jvm-inspect/src/stream.rs b/crates/ide-jvm-inspect/src/stream.rs index 975d102a2..751501f6d 100644 --- a/crates/ide-jvm-inspect/src/stream.rs +++ b/crates/ide-jvm-inspect/src/stream.rs @@ -64,13 +64,15 @@ pub struct TraceCollected { } pub trait StreamTracer: Send + Sync { - /// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. + /// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. `token` + /// names the trace for [`release_armed`](Self::release_armed) when no reply arrives. fn arm<'a>( &'a self, target: &'a VmTarget, thread_id: i64, plan: &'a serde_json::Value, budget: u32, + token: &'a str, ) -> InspectFuture<'a, TraceId>; /// Blocks up to `ms` milliseconds for the trace to leave `Running`. fn wait<'a>(&'a self, target: &'a VmTarget, trace: TraceId, ms: u32) -> InspectFuture<'a, TraceState>; @@ -81,4 +83,7 @@ pub trait StreamTracer: Send + Sync { /// with; reading each takes a round trip to the JVM, so the time allowed grows with them. fn collect<'a>(&'a self, target: &'a VmTarget, trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected>; fn release<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, ()>; + /// Releases the trace armed with `token` whose `arm` reply never came (it timed out); nothing + /// when there is none. + fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()>; } diff --git a/crates/ide-lsp/src/jdtls/stream_trace.rs b/crates/ide-lsp/src/jdtls/stream_trace.rs index 6eceb36ba..dbd5a7d20 100644 --- a/crates/ide-lsp/src/jdtls/stream_trace.rs +++ b/crates/ide-lsp/src/jdtls/stream_trace.rs @@ -182,9 +182,10 @@ impl StreamTracer for JdtStreamTracer { thread_id: i64, plan: &'a Value, budget: u32, + token: &'a str, ) -> InspectFuture<'a, TraceId> { Box::pin(async move { - let args = json!({"threadId": thread_id, "plan": plan, "budget": budget}); + let args = json!({"threadId": thread_id, "plan": plan, "budget": budget, "token": token}); Ok(self.call::("arm", target, args, COMMAND_TIMEOUT).await?.trace_id) }) } @@ -223,6 +224,13 @@ impl StreamTracer for JdtStreamTracer { self.call::("release", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await.map(drop) }) } + + fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()> { + Box::pin(async move { + // Waits for an arm still setting up: as long as an arm may take. + self.call::("release", target, json!({"token": token}), COMMAND_TIMEOUT).await.map(drop) + }) + } } #[cfg(test)] diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index c5aee23ea..a3eba2875 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3193,7 +3193,7 @@ async fn stream_commands_send_target_then_named_fields() { let plan = json!({"root": {"line": 14}}); s.respond("workspace/executeCommand", json!({"ok": {"traceId": 3}})); - assert_eq!(tracer.arm(&target, 7, &plan, 500).await.unwrap(), 3); + assert_eq!(tracer.arm(&target, 7, &plan, 500, "t1").await.unwrap(), 3); s.respond( "workspace/executeCommand", json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}), @@ -3211,18 +3211,24 @@ async fn stream_commands_send_target_then_named_fields() { tracer.collect(&target, 3, 2).await.unwrap(); s.respond("workspace/executeCommand", json!({"ok": {}})); tracer.release(&target, 3).await.unwrap(); + s.respond("workspace/executeCommand", json!({"ok": {}})); + tracer.release_armed(&target, "t1").await.unwrap(); let asked = s.requested("workspace/executeCommand"); let seen: Vec<_> = asked.iter().map(|p| (p["command"].clone(), p["arguments"].clone())).collect(); assert_eq!( seen, vec![ - (json!("openidea.jvm.stream.arm"), json!([target_json, {"threadId": 7, "plan": plan, "budget": 500}])), + ( + json!("openidea.jvm.stream.arm"), + json!([target_json, {"threadId": 7, "plan": plan, "budget": 500, "token": "t1"}]) + ), (json!("openidea.jvm.stream.wait"), json!([target_json, {"traceId": 3, "ms": 250}])), (json!("openidea.jvm.stream.stop"), json!([target_json, {"traceId": 3}])), (json!("openidea.jvm.stream.abort"), json!([target_json, {"traceId": 3}])), (json!("openidea.jvm.stream.collect"), json!([target_json, {"traceId": 3}])), (json!("openidea.jvm.stream.release"), json!([target_json, {"traceId": 3}])), + (json!("openidea.jvm.stream.release"), json!([target_json, {"token": "t1"}])), ] ); } @@ -3303,7 +3309,7 @@ async fn stream_errors_map() { ]; for (reply, expected) in cases { s.respond("workspace/executeCommand", reply.clone()); - assert_eq!(tracer.arm(&target, 1, &json!({}), 10).await.unwrap_err(), expected, "{reply}"); + assert_eq!(tracer.arm(&target, 1, &json!({}), 10, "t").await.unwrap_err(), expected, "{reply}"); } } diff --git a/crates/ide-streams/src/chain/search.rs b/crates/ide-streams/src/chain/search.rs index 54706d75d..77186cbc3 100644 --- a/crates/ide-streams/src/chain/search.rs +++ b/crates/ide-streams/src/chain/search.rs @@ -332,9 +332,10 @@ impl<'t> Finder<'_, 't> { /// Subtrees where calls that exit before the root can be: the statement holding /// the chain, or, for a chain in a compound statement's header, that statement. - /// For an `else if` also the conditions of the `if`s before it, which all ran; - /// their branch bodies did not, since the later condition is only reached when - /// they were skipped. + /// For an `else if` also the conditions of the `if`s before it that start on the + /// line the trace starts from (`} else if` on a line of its own stops after they + /// ran); their branch bodies never count, since the later condition is only + /// reached when they were skipped. fn skip_regions(&self, anchor: Node<'t>, scope: Node<'t>) -> Vec> { let is_statement = |n: Node| n.kind().ends_with("_statement") || n.kind() == "switch_expression"; if anchor.kind() != "method_invocation" { @@ -344,12 +345,13 @@ impl<'t> Finder<'_, 't> { .take_while(|n| *n != scope) .find(|n| is_statement(*n)) .unwrap_or(anchor); + let stop_row = anchor.start_position().row; let mut regions = vec![region]; while let Some(outer) = region .parent() .filter(|p| p.kind() == "if_statement" && p.child_by_field_name("alternative") == Some(region)) { - regions.extend(outer.child_by_field_name("condition")); + regions.extend(outer.child_by_field_name("condition").filter(|c| c.start_position().row >= stop_row)); region = outer; } regions diff --git a/crates/ide-streams/tests/fixtures/Chains.java b/crates/ide-streams/tests/fixtures/Chains.java index 8a2a448fc..6b08ae95e 100644 --- a/crates/ide-streams/tests/fixtures/Chains.java +++ b/crates/ide-streams/tests/fixtures/Chains.java @@ -125,6 +125,7 @@ public class Chains { } else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF_BODY base--; } + if (names.stream().anyMatch(x -> x.isEmpty())) base++; else if (list.stream().noneMatch(x -> x.isEmpty())) base--; // C_PLAN_ELSE_IF_ONE_LINE List out = nums.stream() // C_PLAN_FIRST_LINE .filter(x -> x > 0) .map(x -> x * 2) diff --git a/crates/ide-streams/tests/real_run.rs b/crates/ide-streams/tests/real_run.rs index 740f22724..f105eb6ab 100644 --- a/crates/ide-streams/tests/real_run.rs +++ b/crates/ide-streams/tests/real_run.rs @@ -172,9 +172,17 @@ fn root_skip_counts_sibling_chain_in_if_header() { } #[test] -fn root_skip_counts_earlier_condition_of_else_if() { +fn root_skip_leaves_out_an_earlier_condition_that_ran_before_the_stop() { + // Stopped on the `} else if` line, the first condition has already returned. let root = plan_of("C_PLAN_ELSE_IF").root.unwrap(); - assert_eq!(root, spec("stream", 0, 1)); + assert_eq!(root, spec("stream", 0, 0)); +} + +#[test] +fn root_skip_counts_an_earlier_condition_on_the_same_line() { + let chains = chains_at("C_PLAN_ELSE_IF_ONE_LINE"); + let later = chains.iter().find(|c| c.terminal.name == "noneMatch").expect("else-if chain"); + assert_eq!(real_run_plan(later).unwrap().root, Some(spec("stream", 0, 1))); } #[test] diff --git a/java/jvm-inspect/openidea-jvm-inspect.jar b/java/jvm-inspect/openidea-jvm-inspect.jar index 120759006..f67c5e2aa 100644 Binary files a/java/jvm-inspect/openidea-jvm-inspect.jar and b/java/jvm-inspect/openidea-jvm-inspect.jar differ diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java index f6896a2dc..60cd077a9 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java @@ -6,6 +6,7 @@ import ai.openidea.jvminspect.JavaDebugSessions.HubEvent; import ai.openidea.jvminspect.RealRunPlan.StepSpec; import com.sun.jdi.AbsentInformationException; import com.sun.jdi.ArrayReference; +import com.sun.jdi.BooleanValue; import com.sun.jdi.ClassType; import com.sun.jdi.Field; import com.sun.jdi.IncompatibleThreadStateException; @@ -162,6 +163,8 @@ final class RealRunTrace { /** Recorder number of the next wrapped op; modifiers take none. */ private int nextStep; private ObjectReference lastWrapped; + /** Whether the stream was made sequential: the plan asked, or the stream the chain starts from was parallel. */ + private volatile boolean sequentialized; /** {@code forceEarlyReturn} at a method exit makes that frame exit once more, returning the forced value. */ private Method echoMethod; private Value echoValue; @@ -240,11 +243,14 @@ final class RealRunTrace { subscription = hub.subscribe(this::onEvent, e -> errors.add("event listener: " + e)); if (held != null) { // Not put back: the program consumes the stream right after. - lastWrapped = wrap(held, nextStep++, plan.sequentialize()); + // A stream made parallel before this statement shows no `parallel` in the chain. + sequentialized = plan.sequentialize() || isParallel(held); + lastWrapped = wrap(held, nextStep++, sequentialized); // The invokes resumed the thread, which invalidated the frame read before them. thread.frame(0).setValue(local, lastWrapped); } else { rootSkip = plan.root().skip(); + sequentialized = plan.sequentialize(); } // Last: with these on, an invoke into the thread would raise the trace's own events inside it. // The step out of the frame never fires inside an invoke, which runs above it. @@ -402,7 +408,8 @@ final class RealRunTrace { } ObjectReference stream = returned(exit, root); setEnabled(false); - replace(exit, wrap(stream, nextStep++, plan.sequentialize())); + if (!sequentialized && isParallel(stream)) sequentialized = true; + replace(exit, wrap(stream, nextStep++, sequentialized)); return; } if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return; @@ -597,6 +604,11 @@ final class RealRunTrace { return sequentialize ? invoke(wrapped, "sequential") : wrapped; } + private boolean isParallel(ObjectReference stream) throws Exception { + Method method = streamMethod(stream.referenceType(), "isParallel", 0); + return stream.invokeMethod(thread, method, List.of(), INVOKE) instanceof BooleanValue b && b.value(); + } + private ObjectReference invoke(ObjectReference stream, String name, Value... arguments) throws Exception { Method method = streamMethod(stream.referenceType(), name, arguments.length); return keep(RecorderLoader.pin(() -> (ObjectReference) stream.invokeMethod(thread, method, List.of(arguments), INVOKE))); @@ -1008,7 +1020,7 @@ final class RealRunTrace { }; int skipped = silencers.stream().mapToInt(Silencer::silencedBreakpoints).sum(); return Values.json("records", records, "dropped", longOf(fields.get(field("dropped"))), "terminal", terminal, - "skippedBreakpoints", skipped, "sequentialized", plan.sequentialize()); + "skippedBreakpoints", skipped, "sequentialized", sequentialized); } /** diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java index 7913a7c2e..d1f8d3dbd 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java @@ -40,6 +40,8 @@ public final class StreamCommand implements IDelegateCommandHandler { private static final int GONE_KEPT = 16; private static final AtomicLong IDS = new AtomicLong(); private static final Map TRACES = new IdentityHashMap<>(); + /** The {@code token} each trace was armed with: a client whose {@code arm} timed out releases by it. */ + private static final Map TOKENS = new IdentityHashMap<>(); /** By trace id, the answer {@link RealRunTrace#ended} gave: the trace itself would keep its dead VM's mirrors. */ private static final Map> GONE = new LinkedHashMap<>() { private static final long serialVersionUID = 1L; @@ -64,6 +66,7 @@ public final class StreamCommand implements IDelegateCommandHandler { } catch (Failure e) { Map gone = name.equals("arm") ? null : gone(args); if (gone == null) throw e; + if (name.equals("release") && args.get("token") instanceof String) return InspectCommand.ok(Map.of()); return InspectCommand.ok(switch (name) { case "wait" -> gone; case "release" -> Map.of(); @@ -76,7 +79,9 @@ public final class StreamCommand implements IDelegateCommandHandler { case "stop" -> Values.json("records", trace(vm, args).stopRecording()); case "abort" -> trace(vm, args).abort(); case "collect" -> collect(vm, target, trace(vm, args)); - case "release" -> release(vm, trace(vm, args)); + case "release" -> args.get("token") instanceof String token && !(args.get("traceId") instanceof Number) + ? releaseArmed(vm, token) + : release(vm, trace(vm, args)); default -> throw new IllegalArgumentException("unknown command " + command); }); } catch (Failure e) { @@ -131,6 +136,7 @@ public final class StreamCommand implements IDelegateCommandHandler { RealRunTrace trace = RealRunTrace.arm(IDS.incrementAndGet(), vm, thread, plan, budget, target.generation(), hub); synchronized (TRACES) { TRACES.put(vm, trace); + if (args.get("token") instanceof String token) TOKENS.put(trace, token); } return trace.id; } @@ -166,11 +172,27 @@ public final class StreamCommand implements IDelegateCommandHandler { if (!trace.state().wire.equals("running")) { synchronized (TRACES) { TRACES.remove(vm, trace); + TOKENS.remove(trace); } } return Map.of(); } + /** + * The trace armed with {@code token}, whose {@code arm} reply the client gave up on: released, + * so its breakpoints come back on. Under the arm lock, so an arm still setting up finishes first. + */ + private static Map releaseArmed(VirtualMachine vm, String token) { + synchronized (InspectCommand.handlesFor(vm)) { + RealRunTrace current; + synchronized (TRACES) { + current = TRACES.get(vm); + if (current == null || !token.equals(TOKENS.get(current))) return Map.of(); + } + return release(vm, current); + } + } + /** Releases the traces of VMs java-debug no longer has; their requests and objects went with the VM. */ private static void forgetGone(List vms) { Set live = Collections.newSetFromMap(new IdentityHashMap<>()); @@ -182,6 +204,7 @@ public final class StreamCommand implements IDelegateCommandHandler { if (live.contains(e.getKey())) continue; RealRunTrace trace = e.getValue(); trace.vmGone(); + TOKENS.remove(trace); GONE.put(trace.id, trace.ended()); gone.add(trace); i.remove(); diff --git a/java/jvm-inspect/tests/stream.py b/java/jvm-inspect/tests/stream.py index a6d81dce3..e17727589 100644 --- a/java/jvm-inspect/tests/stream.py +++ b/java/jvm-inspect/tests/stream.py @@ -91,6 +91,8 @@ public class Real { case "H": h(); break; case "local": local(); break; case "parallel": parallel(); break; + case "plocal": parallelLocal(); break; + case "elif": elseIf(); break; case "nested": nested(); break; case "hostile": hostile(); break; case "sr": stopRecording(Integer.parseInt(a[1])); break; @@ -167,6 +169,20 @@ public class Real { System.out.println("P " + p + " " + q); } + static void parallelLocal() { + Stream s = nums.parallelStream(); + List r = s.map(x -> x + 1).collect(Collectors.toList()); // @plocal + System.out.println("PL " + r); + } + + static void elseIf() { + if (nums.stream().anyMatch(x -> x > 100)) { + System.out.println("ELIF no"); + } else if (nums.stream().anyMatch(x -> x == 8)) { // @elif + System.out.println("ELIF yes"); + } + } + static void nested() { long n = nums.stream().flatMap(x -> Stream.of(x, x)).count(); // @nested System.out.println("NESTED " + n); @@ -833,6 +849,61 @@ def real_run_parallel(): dbg.end() +@case +def real_run_parallel_local(): + dbg = real('plocal') + try: + # No `parallel` in the chain: the stream was made parallel before the statement. + trace, state, _ = run_until_parked(dbg, 'plocal', root=None, local='s', steps=(spec('map', 1),), step_kinds=('sync',), + class_filters=('java.util.stream.*',)) + c = step_out_and_collect(dbg, trace) + collected_ok('parallel local', c, records='0=5 1=6 0=3 1=4 0=8 1=9 0=1 1=2 0=4 1=5 0=2 1=3 0=9 1=10 0=6 1=7'.split()) + check('parallel local: sequentialized', c['sequentialized'] is True, c['sequentialized']) + resume(dbg) + check('parallel local: program output', output_line(dbg, 'PL ') == 'PL [6, 4, 9, 2, 5, 3, 10, 7]') + finally: + dbg.end() + + +@case +def real_run_else_if(): + dbg = real('elif') + try: + # Stopped on the `else if` line, the first condition's `stream()` has already returned. + trace, state, _ = run_until_parked(dbg, 'elif', steps=(), terminal=spec('anyMatch', 1), step_kinds=(), timeout=20) + check('else if: the trace parks with nothing skipped', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + collected_ok('else if', c, terminal='true') + resume(dbg) + check('else if: program output', output_line(dbg, 'ELIF ') == 'ELIF yes') + finally: + dbg.end() + + +@case +def release_by_arm_token(): + dbg = launch() + try: + def arm_with(token): + return stream('arm', dbg, threadId=dbg.thread, plan=plan('loop'), budget=50_000, token=token) + + ok(arm_with('first')) + check('release by another token leaves the trace', ok(stream('release', dbg, token='other')) == {}) + check('so the next arm is busy', error(arm_with('second')) == 'busy') + check('release by the arm\'s token answers {}', ok(stream('release', dbg, token='first')) == {}) + trace = ok(arm_with('third'))['traceId'] + check('arm works again after it', trace is not None, trace) + ok(stream('release', dbg, traceId=trace)) + resume(dbg) + try: + body = expect_stop(dbg, 10, 'stop after release') + check('breakpoints are back after a release by token', body.get('reason') == 'breakpoint', body) + except TimeoutError: + check('breakpoints are back after a release by token', False, 'no stop within 10 s') + finally: + dbg.end() + + @case def real_run_nested(): dbg = real('nested')