diff --git a/Cargo.lock b/Cargo.lock index 312dbf2010..a5943383ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4435,6 +4435,7 @@ dependencies = [ "ide-index", "ide-jsonrpc", "ide-jvm-attach", + "ide-jvm-inspect", "ide-language", "ide-lsp", "ide-mcp", @@ -4447,6 +4448,7 @@ dependencies = [ "ide-search", "ide-spell", "ide-ssh", + "ide-streams", "ide-syntax", "ide-terminal", "ide-text", @@ -4876,6 +4878,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "ide-streams" +version = "0.1.46" +dependencies = [ + "ide-core", + "ide-language", + "ide-syntax", + "serde", + "serde_json", + "specta", + "tree-sitter", +] + [[package]] name = "ide-syntax" version = "0.1.46" diff --git a/Cargo.toml b/Cargo.toml index 4924a8ac14..b3cb2fe0a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ ide-jvm-attach = { path = "crates/ide-jvm-attach" } ide-jvm-inspect = { path = "crates/ide-jvm-inspect" } ide-jdwp = { path = "crates/ide-jdwp" } ide-heap = { path = "crates/ide-heap" } +ide-streams = { path = "crates/ide-streams" } # serialization & IPC typing serde = { version = "1", features = ["derive"] } diff --git a/crates/ide-dap/src/jvm_memory/inspect.rs b/crates/ide-dap/src/jvm_memory/inspect.rs index ed9ab9af83..19a20e0e74 100644 --- a/crates/ide-dap/src/jvm_memory/inspect.rs +++ b/crates/ide-dap/src/jvm_memory/inspect.rs @@ -216,6 +216,11 @@ fn settle(result: Result) -> IdeResult U::TimedOut, InspectError::Closed => U::BackendClosed, InspectError::Failed(message) => return Err(IdeError::internal(format!("JVM inspector: {message}"))), + // Only the stream trace commands answer these, never the memory view's. + other @ (InspectError::NoSession + | InspectError::NotAtChainStart(_) + | InspectError::Busy + | InspectError::NoTrace) => return Err(IdeError::internal(format!("JVM inspector: {other}"))), })) } diff --git a/crates/ide-dap/src/jvm_memory/mod.rs b/crates/ide-dap/src/jvm_memory/mod.rs index 7b6a97984f..ce710d6f97 100644 --- a/crates/ide-dap/src/jvm_memory/mod.rs +++ b/crates/ide-dap/src/jvm_memory/mod.rs @@ -23,7 +23,7 @@ use std::time::Duration; pub use heap::*; pub use inspect::{JvmFieldsResult, JvmInspectUnavailable, JvmInstancesResult, JvmObjectRef, JvmReferrersResult}; -pub(crate) use inspect::{fields, instances, referrers, set_inspector, watch_link}; +pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target, watch_link}; #[cfg(all(test, unix))] pub(crate) use scan::watch_for_attached_jvm; pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port}; diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index c436cb6166..097dd091c9 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -19,6 +19,7 @@ mod jvm_memory; pub mod kotlin; pub mod kotlin_lsp; mod session; +mod stream_trace; pub mod unity; use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher}; @@ -39,6 +40,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; use std::sync::{Arc, Weak}; use std::time::Duration; +pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable}; #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -146,6 +148,9 @@ pub struct DebugCapabilities { pub js_page: bool, /// The adapter evaluates expressions while the program runs, without a stack frame. pub live_evaluate: bool, + /// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]). + /// Can change during the session, like `jvm_instances`. + pub stream_trace: bool, } /// Result of [`DebugManager::redefine_classes`]. @@ -602,6 +607,7 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities { jvm_heap: false, js_page: false, live_evaluate: false, + stream_trace: false, } } @@ -613,6 +619,7 @@ pub(crate) fn session_capabilities(session: &Session) -> DebugCapabilities { caps.jvm_heap = JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str()); caps.js_page = js_debug::is_page(session); caps.live_evaluate = session.adapter == js_debug::ADAPTER; + caps.stream_trace = stream_trace::available(session); caps } @@ -1873,6 +1880,42 @@ impl DebugManager { jvm_memory::referrers(&*self.session(s)?, object, limit).await } + /// Gives the session the backend for [`Self::stream_trace`] (used by java-debug sessions + /// only); the UI is told to reload the session's capabilities. + pub fn set_stream_tracer( + &self, + s: DebugSessionId, + tracer: Arc, + ) -> IdeResult<()> { + let session = self.session(s)?; + if session.ended.is_cancelled() { + return Err(no_session(s)); + } + stream_trace::set_tracer(&session, tracer); + Ok(()) + } + + /// Traces the stream chain `plan` (the JSON of `ide_streams::RealRunPlan`) while the program + /// runs it, from `thread_id` stopped where the chain starts. Leaves the thread stopped right + /// after the chain's terminal operation. `cancel` stops keeping records; the program runs on. + pub async fn stream_trace( + &self, + s: DebugSessionId, + thread_id: i64, + plan: Value, + cancel: ide_core::CancellationToken, + progress: impl Fn(TraceProgress) + Send + Sync, + ) -> IdeResult { + let session = self.session(s)?; + Ok(stream_trace::run(self, &session, thread_id, &plan, &cancel, &progress).await) + } + + /// Ends the running terminal operation by interrupting its thread, then by throwing into it. + /// `None` when no trace runs. + pub async fn stream_trace_abort(&self, s: DebugSessionId) -> IdeResult> { + stream_trace::abort(&*self.session(s)?).await + } + /// HotSwap: reloads the classes compiled since the session started (or since the /// last reload) into the debuggee (java-debug `redefineClasses`). pub async fn redefine_classes(&self, s: DebugSessionId) -> IdeResult { diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index 52d028b2dd..1238b2d647 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -114,6 +114,8 @@ pub(crate) struct Session { pub jvm_located: watch::Sender, pub kotlin_mirror: Mutex>, pub jvm_memory: tokio::sync::Mutex, + pub stream_tracer: parking_lot::Mutex>>, + pub(crate) stream_trace: 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, @@ -195,6 +197,13 @@ impl Suspension { self.0.lock().ticket } + /// The ticket of a stop of `thread` (its own or every thread's) taken after ticket `after`. + pub fn stopped_since(&self, thread: i64, after: u64) -> Option { + let stops = self.0.lock(); + let own = stops.threads.iter().find(|&&(id, _)| id == thread).map(|&(_, ticket)| ticket); + own.max(stops.all).filter(|&ticket| ticket > after) + } + /// After a successful resume-like request for `thread`; `all`: every thread ran. pub fn resumed(&self, ticket: u64, thread: i64, all: bool) { self.0.lock().release(Some(thread), all, ticket); @@ -270,6 +279,8 @@ impl Session { jvm_located: watch::channel(false).0, kotlin_mirror: Mutex::new(None), jvm_memory: tokio::sync::Mutex::default(), + stream_tracer: parking_lot::Mutex::new(None), + stream_trace: parking_lot::Mutex::new(None), quirks: kotlin_lsp::Quirks::default(), unity_startup_activity: Mutex::new(Instant::now()), } @@ -741,6 +752,9 @@ async fn on_event(mgr: &Arc, s: &Arc, event: &str, mut bo } "stopped" => { let all = body.get("allThreadsStopped").and_then(Value::as_bool).unwrap_or(false); + if crate::stream_trace::resume_traced_stop(s, int("threadId"), all) { + return; + } s.suspended.stopped(int("threadId"), all); let mut reason = str_("reason").unwrap_or_else(|| "pause".into()); if let Some(quirks) = s.kotlin_lsp_quirks() { diff --git a/crates/ide-dap/src/stream_trace.rs b/crates/ide-dap/src/stream_trace.rs new file mode 100644 index 0000000000..df05a87a38 --- /dev/null +++ b/crates/ide-dap/src/stream_trace.rs @@ -0,0 +1,377 @@ +//! A stream chain traced while the program itself runs it. The JDT LS bundle arms the trace with +//! the thread stopped where the chain starts; the program runs on `continue`, and the bundle holds +//! the thread inside the terminal operation once it has run, until a `stepOut` brings java-debug +//! to a stop of its own in which the records are read. + +use crate::jvm_memory::vm_target; +use crate::session::Session; +use crate::{DebugManager, StepKind}; +use ide_core::event::DebugEvent; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use ide_jvm_inspect::{ + AbortState, InspectError, InspectFuture, StreamTracer, TraceCollected, TraceId, TraceState, VmTarget, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use specta::Type; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +/// Records the bundle keeps; later ones are only counted. +const BUDGET: u32 = 50_000; +const WAIT_MS: u32 = 500; +const STOP_POLL: Duration = Duration::from_millis(20); +const STOP_WAIT: Duration = Duration::from_secs(30); +const RESUME_TIMEOUT: Duration = Duration::from_secs(30); +/// The bundle reaches the JVM through java-debug's own session. +const ADAPTER: &str = "java-debug"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct TraceProgress { + pub phase: TracePhase, + pub records: u64, + pub dropped: u64, + /// Since the program started running the chain, as the bundle measures it. + pub elapsed_ms: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum TracePhase { + Arming, + Running, + /// The terminal operation runs on, keeping no more records. + RecordingStopped, + Aborting, + /// The terminal operation finished: stepping out of it and reading the records. + Collecting, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TraceRun { + /// `generation`: the stop the records were read in, the only one their objects are valid in. + Done { + collected: TraceCollected, + generation: u64, + /// Stops of the traced thread while the program ran the chain, resumed unseen. + resumed_stops: u32, + }, + Unavailable { + reason: TraceUnavailable, + }, + Failed { + detail: String, + }, + /// Stop Recording or Abort Operation came before the terminal operation ran. + Cancelled { + detail: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TraceUnavailable { + /// Not a java-debug session, or no JDT LS bundle behind it. + NoBackend, + NotSuspended, + NotAtChainStart { + detail: String, + }, + /// A trace already runs in this session or its JVM. + Busy, + /// java-debug has no debug session for the JVM. + NoSession, + Unsupported { + detail: String, + }, +} + +/// The session's running trace; `id` is `None` until `arm` answers. +pub(crate) struct ActiveTrace { + tracer: Arc, + target: VmTarget, + id: Option, + aborting: bool, + thread_id: i64, + /// From the `continue` that runs the chain until the bundle holds the thread after it. + running: bool, + resumed_stops: u32, +} + +/// A stop of the traced thread while the program runs the chain is resumed instead of shown, as +/// IntelliJ does (spec G5): the UI keeps Resume locked meanwhile, and a breakpoint java-debug set +/// since the bundle last switched them off, hit inside the terminal's invoke, would hold that +/// invoke forever. java-debug stops a breakpoint's thread alone; a stop of every thread is shown. +/// `true` when the stop was taken. +pub(crate) fn resume_traced_stop(s: &Arc, thread_id: Option, all: bool) -> bool { + let Some(thread_id) = thread_id.filter(|_| !all) else { return false }; + { + let mut slot = s.stream_trace.lock(); + let Some(active) = slot.as_mut().filter(|a| a.running && a.thread_id == thread_id) else { return false }; + active.resumed_stops += 1; + } + let s = s.clone(); + tokio::spawn(async move { + let sent = + s.conn.request_timeout("continue", serde_json::json!({ "threadId": thread_id }), RESUME_TIMEOUT).await; + if let Err(e) = sent { + tracing::warn!(session = s.id.0, thread_id, "resuming a stop inside a stream trace: {e}"); + } + }); + true +} + +fn set_running(s: &Session, running: bool) { + if let Some(active) = s.stream_trace.lock().as_mut() { + active.running = running; + } +} + +/// Frees the session for the next trace however this one ends, a dropped future included. +struct Claim<'s>(&'s Session); + +impl Drop for Claim<'_> { + fn drop(&mut self) { + self.0.stream_trace.lock().take(); + } +} + +pub(crate) fn set_tracer(s: &Session, tracer: Arc) { + *s.stream_tracer.lock() = Some(tracer); + s.emit(DebugEvent::Capabilities); +} + +fn tracer(s: &Session) -> Option> { + s.stream_tracer.lock().clone().filter(|_| s.adapter == ADAPTER) +} + +pub(crate) fn available(s: &Session) -> bool { + tracer(s).is_some() +} + +pub(crate) async fn run( + mgr: &DebugManager, + s: &Session, + thread_id: i64, + plan: &Value, + cancel: &CancellationToken, + progress: &(impl Fn(TraceProgress) + Send + Sync), +) -> TraceRun { + let unavailable = |reason| TraceRun::Unavailable { reason }; + let Some(tracer) = tracer(s) else { return unavailable(TraceUnavailable::NoBackend) }; + let target = vm_target(s); + let _claim = { + let mut slot = s.stream_trace.lock(); + if slot.is_some() { + return unavailable(TraceUnavailable::Busy); + } + *slot = Some(ActiveTrace { + tracer: tracer.clone(), + target: target.clone(), + id: None, + aborting: false, + thread_id, + running: false, + resumed_stops: 0, + }); + Claim(s) + }; + 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() }; + match trace.drive(plan, cancel).await { + Ok(run) => run, + Err(run) => { + // A stop from now on is the user's to see. + set_running(s, false); + trace.release().await; + run + } + } +} + +/// `None` when no trace runs or it is still arming. The trace itself goes on to report how the +/// abort ended it. +pub(crate) async fn abort(s: &Session) -> IdeResult> { + let (tracer, target, id) = { + let mut slot = s.stream_trace.lock(); + let Some(active) = slot.as_mut() else { return Ok(None) }; + let Some(id) = active.id else { return Ok(None) }; + active.aborting = true; + (active.tracer.clone(), active.target.clone(), id) + }; + let result = tokio::select! { + biased; + () = s.ended.cancelled() => return Ok(None), + result = tracer.abort(&target, id) => result, + }; + match result { + Ok(state) => Ok(Some(state)), + Err(InspectError::NoTrace) => Ok(None), + Err(e) => Err(IdeError::internal(format!("cannot abort the stream trace: {e}"))), + } +} + +#[derive(Default)] +struct Counts { + records: u64, + dropped: u64, + elapsed_ms: u64, +} + +struct Trace<'a, P> { + mgr: &'a DebugManager, + s: &'a Session, + tracer: &'a dyn StreamTracer, + /// The stop the trace was armed in. + target: &'a VmTarget, + thread_id: i64, + progress: &'a P, + /// Set once `arm` answers. + id: Option, + last: Counts, +} + +impl Trace<'_, P> { + /// `Err` ends the trace early. + async fn drive(&mut self, plan: &Value, cancel: &CancellationToken) -> Result { + let (s, tracer, target) = (self.s, self.tracer, self.target); + self.report(TracePhase::Arming); + let id = self + .until_ended(tracer.arm(target, self.thread_id, plan, BUDGET)) + .await? + .map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?; + self.id = Some(id); + if let Some(active) = s.stream_trace.lock().as_mut() { + active.id = Some(id); + } + // Before the request: the thread can stop again before its reply arrives. + set_running(s, true); + self.dap(self.mgr.resume(s.id, self.thread_id)).await?; + let mut stopped = false; + loop { + if cancel.is_cancelled() && !stopped { + stopped = true; + // Refused when the trace parked or failed just before: `wait` reports that. + match self.until_ended(tracer.stop(target, id)).await? { + Ok(records) => { + self.last.records = records; + self.report(TracePhase::RecordingStopped); + } + Err(e) => tracing::debug!(session = s.id.0, trace = id, "stream trace stop: {e}"), + } + } + match self.inspect(tracer.wait(target, id, WAIT_MS)).await? { + TraceState::Running { records, dropped, elapsed_ms } => { + self.last = Counts { records, dropped, elapsed_ms }; + let aborting = s.stream_trace.lock().as_ref().is_some_and(|a| a.aborting); + self.report(if aborting { + TracePhase::Aborting + } else if stopped { + TracePhase::RecordingStopped + } else { + TracePhase::Running + }); + } + TraceState::Parked { records, dropped } => { + set_running(s, false); + self.last.records = records; + self.last.dropped = dropped; + break; + } + TraceState::Failed { detail } => return Err(TraceRun::Failed { detail }), + TraceState::Cancelled { detail } => return Err(TraceRun::Cancelled { detail }), + } + } + self.report(TracePhase::Collecting); + let before = s.suspended.ticket(); + self.dap(self.mgr.step(s.id, self.thread_id, StepKind::Out)).await?; + // Another thread's stop meanwhile is not this one: the traced thread would still be + // inside the terminal operation. + let stop = async { + loop { + if let Some(ticket) = s.suspended.stopped_since(self.thread_id, before) { + return ticket; + } + tokio::time::sleep(STOP_POLL).await; + } + }; + let Ok(generation) = self.until_ended(tokio::time::timeout(STOP_WAIT, stop)).await? else { + // Collecting in the old stop would only be refused as stale. + return Err(TraceRun::Failed { detail: step_out_timeout() }); + }; + let stopped_in = VmTarget { generation, ..vm_target(s) }; + let collected = self.inspect(tracer.collect(&stopped_in, id, self.last.records)).await?; + let resumed_stops = s.stream_trace.lock().as_ref().map_or(0, |a| a.resumed_stops); + Ok(TraceRun::Done { collected, generation, resumed_stops }) + } + + /// 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. + 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}"); + } + } + + fn report(&self, phase: TracePhase) { + let Counts { records, dropped, elapsed_ms } = self.last; + (self.progress)(TraceProgress { phase, records, dropped, elapsed_ms }); + } + + /// A reply may never come once the session ends. + async fn until_ended(&self, work: impl Future) -> Result { + tokio::select! { + biased; + () = self.s.ended.cancelled() => Err(ended()), + value = work => Ok(value), + } + } + + async fn inspect(&self, work: InspectFuture<'_, T>) -> Result { + self.until_ended(work).await?.map_err(|e| self.failed(e.to_string())) + } + + async fn dap(&self, work: impl Future>) -> Result<(), TraceRun> { + self.until_ended(work).await?.map_err(|e| self.failed(e.message)) + } + + /// A request that failed because the session was ending says so. + fn failed(&self, detail: String) -> TraceRun { + if self.s.ended.is_cancelled() { ended() } else { TraceRun::Failed { detail } } + } +} + +fn step_out_timeout() -> String { + format!( + "java-debug reported no stop within {} s of stepping out of the stream's terminal operation", + STOP_WAIT.as_secs() + ) +} + +fn ended() -> TraceRun { + TraceRun::Failed { detail: "the debug session ended".into() } +} + +fn refused(e: InspectError) -> TraceRun { + use TraceUnavailable as U; + let reason = match e { + InspectError::NotSuspended => U::NotSuspended, + InspectError::Busy => U::Busy, + InspectError::NoSession => U::NoSession, + InspectError::Unsupported(detail) => U::Unsupported { detail }, + InspectError::NotAtChainStart(detail) => U::NotAtChainStart { detail }, + other => return TraceRun::Failed { detail: other.to_string() }, + }; + TraceRun::Unavailable { reason } +} diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index ec578d4d53..fa6baf64ac 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -1,6 +1,7 @@ //! Protocol flow against an in-memory fake adapter. mod jvm_inspect; +mod stream_trace; use super::*; use crate::adapter::{AdapterIo, LaunchFuture}; @@ -132,6 +133,16 @@ struct Script { continue_reply: Option, /// Answer `continue` and stop at a breakpoint again, instead of letting the program exit. stop_after_continue: bool, + /// Answer `stepOut` and stop these threads one after the other, 100 ms apart (java-debug + /// stops the stepping thread right after the call returns). + step_out_stops: &'static [i64], + /// Refuse `stepOut`. + refuse_step_out: bool, + /// Refuse `continue`. + refuse_continue: bool, + /// Stop thread 1 alone at a breakpoint right after each of the first this many `continue`s + /// that `continue_reply` answers. + breakpoints_after_continue: usize, /// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`). step_reason: Option<&'static str>, /// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile). @@ -185,6 +196,10 @@ impl Default for Script { hang_up_after_stop: false, continue_reply: None, stop_after_continue: false, + step_out_stops: &[], + refuse_step_out: false, + refuse_continue: false, + breakpoints_after_continue: 0, step_reason: None, refuse_next: false, invalidated_after_stop: false, @@ -248,6 +263,7 @@ async fn fake_adapter(stream let mut running = false; let mut thread_requests = 0; let mut unity = false; + let mut breakpoints_left = script.breakpoints_after_continue; macro_rules! send { ($v:expr) => {{ let mut v: Value = $v; @@ -494,7 +510,21 @@ async fn fake_adapter(stream {"label": ""}, ]}) ), - "continue" if script.continue_reply.is_some() => ok!(msg, script.continue_reply.clone().unwrap()), + "continue" if script.refuse_continue => send!( + json!({"type": "response", "request_seq": msg["seq"], "command": "continue", "success": false, "message": "Thread is not suspended"}) + ), + "continue" if script.continue_reply.is_some() => { + ok!(msg, script.continue_reply.clone().unwrap()); + if breakpoints_left > 0 { + breakpoints_left -= 1; + send!( + json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}) + ); + } + } + "stepOut" if script.refuse_step_out => send!( + json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"}) + ), "continue" if script.stop_after_continue => { ok!(msg, json!({"allThreadsContinued": true})); send!( @@ -507,6 +537,16 @@ async fn fake_adapter(stream send!(json!({"type": "event", "event": "terminated"})); } "pause" if script.hang_up_on_pause => break, + "stepOut" if !script.step_out_stops.is_empty() => { + ok!(msg, Value::Null); + for (i, thread) in script.step_out_stops.iter().enumerate() { + if i > 0 { + tokio::time::sleep(Duration::from_millis(100)).await; + } + let reason = if i + 1 == script.step_out_stops.len() { "step" } else { "breakpoint" }; + send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}})); + } + } "stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null), "redefineClasses" => { send!( diff --git a/crates/ide-dap/src/tests/stream_trace.rs b/crates/ide-dap/src/tests/stream_trace.rs new file mode 100644 index 0000000000..5cec0852ce --- /dev/null +++ b/crates/ide-dap/src/tests/stream_trace.rs @@ -0,0 +1,522 @@ +//! A stream chain traced while the program runs it, through a session's stream tracer. + +use super::*; +use ide_core::CancellationToken; +use ide_jvm_inspect::{ + AbortState, CollectedTerminal, InspectError, InspectFuture, JvmValue, StreamTracer, TraceCollected, TraceId, + TraceState, VmTarget, +}; +use std::collections::VecDeque; +use tokio::sync::Notify; + +const TRACE: TraceId = 7; + +#[derive(Default)] +struct FakeTracer { + /// Answers to `wait`, in order. Once they run out, `wait` signals `waiting` and answers only + /// after more are pushed and `more` is notified. + waits: Mutex>>, + arm_error: Mutex>, + stop_error: Mutex>, + collect_error: Mutex>, + /// The record count each `collect` was given. + collect_records: Mutex>, + calls: Mutex>, + waiting: Notify, + more: Notify, +} + +impl FakeTracer { + fn scripted(waits: impl IntoIterator) -> Arc { + Self::answering(waits.into_iter().map(Ok)) + } + + fn answering(waits: impl IntoIterator>) -> Arc { + Arc::new(Self { waits: Mutex::new(waits.into_iter().collect()), ..Self::default() }) + } + + fn record(&self, name: &'static str, target: &VmTarget) { + self.calls.lock().push((name, target.clone())); + } + + fn names(&self) -> Vec<&'static str> { + self.calls.lock().iter().map(|(name, _)| *name).collect() + } + + fn target_of(&self, name: &str) -> VmTarget { + self.calls.lock().iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()).unwrap() + } +} + +impl StreamTracer for FakeTracer { + fn arm<'a>( + &'a self, + target: &'a VmTarget, + _thread_id: i64, + _plan: &'a Value, + _budget: u32, + ) -> InspectFuture<'a, TraceId> { + self.record("arm", target); + let error = self.arm_error.lock().clone(); + Box::pin(async move { error.map_or(Ok(TRACE), Err) }) + } + + fn wait<'a>(&'a self, target: &'a VmTarget, _trace: TraceId, _ms: u32) -> InspectFuture<'a, TraceState> { + self.record("wait", target); + Box::pin(async move { + loop { + if let Some(state) = self.waits.lock().pop_front() { + return state; + } + self.waiting.notify_one(); + self.more.notified().await; + } + }) + } + + fn stop<'a>(&'a self, target: &'a VmTarget, _trace: TraceId) -> InspectFuture<'a, u64> { + self.record("stop", target); + let error = self.stop_error.lock().clone(); + Box::pin(async move { error.map_or(Ok(3), Err) }) + } + + fn abort<'a>(&'a self, target: &'a VmTarget, _trace: TraceId) -> InspectFuture<'a, AbortState> { + self.record("abort", target); + Box::pin(async { Ok(AbortState::Interrupted) }) + } + + fn collect<'a>(&'a self, target: &'a VmTarget, _trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected> { + self.record("collect", target); + self.collect_records.lock().push(records); + let error = self.collect_error.lock().clone(); + Box::pin(async move { error.map_or_else(|| Ok(collected()), Err) }) + } + + fn release<'a>(&'a self, target: &'a VmTarget, _trace: TraceId) -> InspectFuture<'a, ()> { + self.record("release", target); + Box::pin(async { Ok(()) }) + } +} + +fn collected() -> TraceCollected { + TraceCollected { + records: vec![(0, JvmValue::Primitive { type_name: "int".into(), text: "1".into() })], + dropped: 0, + terminal: CollectedTerminal::Void, + skipped_breakpoints: 0, + sequentialized: false, + } +} + +fn running(records: u64) -> TraceState { + TraceState::Running { records, dropped: 0, elapsed_ms: 5 } +} + +fn parked() -> TraceState { + TraceState::Parked { records: 10, dropped: 0 } +} + +/// java-debug keeps the program running after `continue` and stops right after a `stepOut`. +fn java_debug() -> Script { + Script { continue_reply: Some(json!({"allThreadsContinued": true})), step_out_stops: &[1], ..Script::default() } +} + +async fn stopped_java(h: &Harness, tracer: &Arc) -> DebugSessionId { + let id = h.start(java_config("launch")).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + h.manager.set_stream_tracer(id, tracer.clone()).unwrap(); + id +} + +async fn trace(h: &Harness, id: DebugSessionId) -> IdeResult { + let run = h.manager.stream_trace(id, 1, json!({"steps": []}), CancellationToken::new(), |_| {}); + tokio::time::timeout(Duration::from_secs(10), run).await.expect("the trace did not end") +} + +/// A trace in its own task, returned once it waits for the answers its tracer has not got. +async fn hanging_trace( + h: &Harness, + id: DebugSessionId, + tracer: &FakeTracer, +) -> tokio::task::JoinHandle> { + hanging_trace_with(h, id, tracer, |_| {}).await +} + +async fn hanging_trace_with( + h: &Harness, + id: DebugSessionId, + tracer: &FakeTracer, + progress: impl Fn(TraceProgress) + Send + Sync + 'static, +) -> tokio::task::JoinHandle> { + let manager = h.manager.clone(); + let task = tokio::spawn(async move { + manager.stream_trace(id, 1, json!({"steps": []}), CancellationToken::new(), progress).await + }); + tokio::time::timeout(Duration::from_secs(5), tracer.waiting.notified()).await.expect("the trace did not wait"); + task +} + +fn phases(seen: &Mutex>) -> Vec { + seen.lock().iter().map(|p| p.phase).collect() +} + +fn progress(phase: TracePhase, records: u64, elapsed_ms: u64) -> TraceProgress { + TraceProgress { phase, records, dropped: 0, elapsed_ms } +} + +#[tokio::test] +async fn trace_runs_continue_then_step_out() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([running(10), parked()]); + let id = stopped_java(&h, &tracer).await; + let start = h.manager.session(id).unwrap().suspended.ticket(); + + let run = trace(&h, id).await.unwrap(); + + let TraceRun::Done { collected: got, generation, resumed_stops } = run else { panic!("not done: {run:?}") }; + assert_eq!(got, collected()); + assert_eq!(resumed_stops, 0); + assert!(generation > start, "collected in the stop of the trace ({start}), not after it ({generation})"); + let commands = h.commands(); + let resumed = commands.iter().position(|c| c == "continue").expect("no continue"); + let stepped = commands.iter().position(|c| c == "stepOut").expect("no stepOut"); + assert!(resumed < stepped, "{commands:?}"); + assert_eq!(h.request("continue")["arguments"]["threadId"], 1); + assert_eq!(h.request("stepOut")["arguments"]["threadId"], 1); + assert_eq!(tracer.names(), ["arm", "wait", "wait", "collect"]); + assert_eq!(*tracer.collect_records.lock(), [10], "collect is told how many records the trace parked with"); + assert_eq!(tracer.target_of("arm").generation, start); + assert_eq!(tracer.target_of("collect").generation, generation); + assert!(h.manager.session(id).unwrap().suspended.get()); +} + +#[tokio::test] +async fn trace_reports_progress() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([running(10), parked()]); + let id = stopped_java(&h, &tracer).await; + let seen: Arc>> = Arc::default(); + let sink = seen.clone(); + + let run = h.manager.stream_trace(id, 1, json!({}), CancellationToken::new(), move |p| sink.lock().push(p)).await; + + assert!(matches!(run, Ok(TraceRun::Done { .. })), "{run:?}"); + assert_eq!( + *seen.lock(), + [ + progress(TracePhase::Arming, 0, 0), + progress(TracePhase::Running, 10, 5), + progress(TracePhase::Collecting, 10, 5), + ] + ); +} + +#[tokio::test] +async fn cancel_stops_recording_once() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([running(10), running(12), parked()]); + let id = stopped_java(&h, &tracer).await; + let cancel = CancellationToken::new(); + let on_running = cancel.clone(); + let seen: Arc>> = Arc::default(); + let sink = seen.clone(); + + let run = h + .manager + .stream_trace(id, 1, json!({}), cancel, move |p| { + if p.phase == TracePhase::Running { + on_running.cancel(); + } + sink.lock().push(p.phase); + }) + .await; + + assert!(matches!(run, Ok(TraceRun::Done { .. })), "{run:?}"); + assert_eq!(tracer.names(), ["arm", "wait", "stop", "wait", "wait", "collect"]); + assert_eq!( + *seen.lock(), + [ + TracePhase::Arming, + TracePhase::Running, + TracePhase::RecordingStopped, + TracePhase::RecordingStopped, + TracePhase::Collecting + ] + ); +} + +#[tokio::test] +async fn second_trace_is_busy() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + let first = hanging_trace(&h, id, &tracer).await; + + let second = trace(&h, id).await.unwrap(); + + assert_eq!(second, TraceRun::Unavailable { reason: TraceUnavailable::Busy }); + assert_eq!(tracer.names().iter().filter(|n| **n == "arm").count(), 1); + first.abort(); +} + +#[tokio::test] +async fn trace_ends_when_session_ends() { + // The fake adapter lets the program exit on `continue`. + let h = harness(Script::default()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + let session = h.manager.session(id).unwrap(); + + let run = trace(&h, id).await.unwrap(); + + assert_eq!(run, TraceRun::Failed { detail: "the debug session ended".into() }); + assert!(session.stream_trace.lock().is_none()); + let next = trace(&h, id).await; + assert!(!matches!(next, Ok(TraceRun::Unavailable { reason: TraceUnavailable::Busy })), "{next:?}"); +} + +#[tokio::test] +async fn dropping_the_trace_frees_the_session() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + let first = hanging_trace(&h, id, &tracer).await; + + first.abort(); + assert!(first.await.unwrap_err().is_cancelled()); + + let session = h.manager.session(id).unwrap(); + assert!(session.stream_trace.lock().is_none()); + // The first trace resumed the thread. + session.suspended.stopped(Some(1), false); + let again = hanging_trace(&h, id, &tracer).await; + assert_eq!(tracer.names().iter().filter(|n| **n == "arm").count(), 2); + again.abort(); +} + +#[tokio::test] +async fn arm_errors_map_to_unavailable_or_failed() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + + *tracer.arm_error.lock() = Some(InspectError::NotAtChainStart("the stop is on line 4".into())); + assert_eq!( + trace(&h, id).await.unwrap(), + TraceRun::Unavailable { reason: TraceUnavailable::NotAtChainStart { detail: "the stop is on line 4".into() } } + ); + *tracer.arm_error.lock() = Some(InspectError::TimedOut); + assert_eq!(trace(&h, id).await.unwrap(), TraceRun::Failed { detail: InspectError::TimedOut.to_string() }); + assert!(!h.commands().iter().any(|c| c == "continue")); +} + +#[tokio::test] +async fn abort_reaches_the_running_trace() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + assert_eq!(h.manager.stream_trace_abort(id).await.unwrap(), None); + let seen: Arc>> = Arc::default(); + let sink = seen.clone(); + let task = hanging_trace_with(&h, id, &tracer, move |p| sink.lock().push(p)).await; + + assert_eq!(h.manager.stream_trace_abort(id).await.unwrap(), Some(AbortState::Interrupted)); + assert_eq!(tracer.target_of("abort"), tracer.target_of("arm")); + + let thrown = "java.lang.RuntimeException: oi-cancel:1"; + tracer.waits.lock().extend([Ok(running(4)), Ok(TraceState::Failed { detail: thrown.into() })]); + tracer.more.notify_one(); + let run = tokio::time::timeout(Duration::from_secs(5), task).await.unwrap().unwrap().unwrap(); + assert_eq!(run, TraceRun::Failed { detail: thrown.into() }); + assert_eq!(phases(&seen), [TracePhase::Arming, TracePhase::Aborting]); + assert_eq!(tracer.names().last(), Some(&"release")); +} + +#[tokio::test] +async fn failed_wait_passes_its_detail_through() { + let h = harness(java_debug()); + let detail = "the program began to exit while the stream ran: stop the debug session"; + let tracer = FakeTracer::scripted([running(1), TraceState::Failed { detail: detail.into() }]); + let id = stopped_java(&h, &tracer).await; + + assert_eq!(trace(&h, id).await.unwrap(), TraceRun::Failed { detail: detail.into() }); + assert_eq!(tracer.names(), ["arm", "wait", "wait", "release"]); + assert!(!h.commands().iter().any(|c| c == "stepOut")); +} + +#[tokio::test] +async fn a_trace_cancelled_before_its_terminal_says_so() { + let detail = "cancelled before the terminal ran"; + let tracer = FakeTracer::scripted([TraceState::Cancelled { detail: detail.into() }]); + let h = harness(java_debug()); + let id = stopped_java(&h, &tracer).await; + + assert_eq!(trace(&h, id).await.unwrap(), TraceRun::Cancelled { detail: detail.into() }); + assert!(!h.commands().iter().any(|c| c == "stepOut")); +} + +#[tokio::test] +async fn a_wait_that_errs_releases_the_trace() { + let h = harness(java_debug()); + let tracer = FakeTracer::answering([Ok(running(1)), Err(InspectError::TimedOut)]); + let id = stopped_java(&h, &tracer).await; + + assert_eq!(trace(&h, id).await.unwrap(), TraceRun::Failed { detail: InspectError::TimedOut.to_string() }); + assert_eq!(tracer.names(), ["arm", "wait", "wait", "release"]); + assert_eq!(tracer.target_of("release"), tracer.target_of("arm")); +} + +#[tokio::test] +async fn a_refused_step_out_releases_the_trace() { + let h = harness(Script { refuse_step_out: true, ..java_debug() }); + let tracer = FakeTracer::scripted([parked()]); + let id = stopped_java(&h, &tracer).await; + + let run = trace(&h, id).await.unwrap(); + + assert!(matches!(&run, TraceRun::Failed { detail } if detail.contains("not suspended")), "{run:?}"); + assert_eq!(tracer.names(), ["arm", "wait", "release"]); +} + +#[tokio::test] +async fn a_refused_continue_releases_the_trace() { + let h = harness(Script { refuse_continue: true, ..java_debug() }); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + + let run = trace(&h, id).await.unwrap(); + + assert!(matches!(&run, TraceRun::Failed { .. }), "{run:?}"); + assert_eq!(tracer.names(), ["arm", "release"]); +} + +#[tokio::test] +async fn a_failed_collect_releases_the_trace() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([parked()]); + *tracer.collect_error.lock() = Some(InspectError::Stale); + let id = stopped_java(&h, &tracer).await; + + assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Failed { .. })); + assert_eq!(tracer.names(), ["arm", "wait", "collect", "release"]); +} + +fn stops(h: &Harness) -> usize { + h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Stopped { .. }, .. })).count() +} + +#[tokio::test] +async fn a_stop_of_the_traced_thread_while_the_chain_runs_is_resumed_unseen() { + // A breakpoint java-debug set meanwhile, hit inside the terminal's invoke before the bundle + // switched it off: held there, the invoke would never return. + let h = harness(Script { breakpoints_after_continue: 1, ..java_debug() }); + let tracer = FakeTracer::scripted([]); + let id = stopped_java(&h, &tracer).await; + let shown = stops(&h); + let task = hanging_trace(&h, id, &tracer).await; + + for _ in 0..200 { + if h.commands().iter().filter(|c| *c == "continue").count() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(h.commands().iter().filter(|c| *c == "continue").count(), 2, "{:?}", h.commands()); + assert_eq!(h.log.lock().iter().rfind(|m| m["command"] == "continue").unwrap()["arguments"]["threadId"], 1); + tracer.waits.lock().push_back(Ok(parked())); + tracer.more.notify_one(); + let run = tokio::time::timeout(Duration::from_secs(5), task).await.unwrap().unwrap().unwrap(); + + let TraceRun::Done { resumed_stops, .. } = run else { panic!("not done: {run:?}") }; + assert_eq!(resumed_stops, 1); + assert_eq!(stops(&h), shown + 1, "only the step-out stop is shown, after the trace parked"); +} + +#[tokio::test] +async fn a_finished_trace_is_not_released() { + // Releasing unpins the records, which the result's values still show until 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 { .. })); + assert!(!tracer.names().contains(&"release"), "{:?}", tracer.names()); +} + +#[tokio::test] +async fn refused_stop_leaves_the_outcome_to_wait() { + let h = harness(java_debug()); + let tracer = FakeTracer::scripted([running(10), parked()]); + *tracer.stop_error.lock() = Some(InspectError::NoTrace); + let id = stopped_java(&h, &tracer).await; + let cancel = CancellationToken::new(); + let on_running = cancel.clone(); + let seen: Arc>> = Arc::default(); + let sink = seen.clone(); + + let run = h + .manager + .stream_trace(id, 1, json!({}), cancel, move |p| { + if p.phase == TracePhase::Running { + on_running.cancel(); + } + sink.lock().push(p); + }) + .await; + + assert!(matches!(run, Ok(TraceRun::Done { .. })), "{run:?}"); + assert_eq!(tracer.names(), ["arm", "wait", "stop", "wait", "collect"]); + assert_eq!(phases(&seen), [TracePhase::Arming, TracePhase::Running, TracePhase::Collecting]); +} + +#[tokio::test] +async fn another_threads_stop_is_not_the_step_out() { + // Thread 2 stops at a breakpoint 100 ms before the traced thread's step out ends. + let h = harness(Script { step_out_stops: &[2, 1], ..java_debug() }); + let tracer = FakeTracer::scripted([parked()]); + let id = stopped_java(&h, &tracer).await; + let start = h.manager.session(id).unwrap().suspended.ticket(); + + let run = trace(&h, id).await.unwrap(); + + let TraceRun::Done { generation, .. } = run else { panic!("not done: {run:?}") }; + assert_eq!( + generation, + start + 2, + "collected in thread 2's stop, not in the traced thread's step-out stop after it" + ); + assert_eq!(tracer.target_of("collect").generation, generation); +} + +#[tokio::test] +async fn step_out_without_a_stop_times_out() { + let h = harness(Script { step_out_stops: &[], ..java_debug() }); + let tracer = FakeTracer::scripted([parked()]); + let id = stopped_java(&h, &tracer).await; + tokio::time::pause(); + + let run = h.manager.stream_trace(id, 1, json!({}), CancellationToken::new(), |_| {}).await.unwrap(); + + assert_eq!( + run, + TraceRun::Failed { + detail: "java-debug reported no stop within 30 s of stepping out of the stream's terminal operation".into() + } + ); + assert!(h.commands().iter().any(|c| c == "stepOut")); + assert_eq!(tracer.names(), ["arm", "wait", "release"]); +} + +#[tokio::test] +async fn capability_only_for_java_debug() { + let h = harness(Script::default()); + let tracer = FakeTracer::scripted([]); + let java = h.start(java_config("launch")).await.unwrap(); + assert!(!h.manager.capabilities(java).unwrap().stream_trace); + h.manager.set_stream_tracer(java, tracer.clone()).unwrap(); + assert!(h.manager.capabilities(java).unwrap().stream_trace); + + let other = h.start(config()).await.unwrap(); + h.manager.set_stream_tracer(other, tracer.clone()).unwrap(); + assert!(!h.manager.capabilities(other).unwrap().stream_trace); +} diff --git a/crates/ide-host/Cargo.toml b/crates/ide-host/Cargo.toml index e3ed8d24cd..28c967640e 100644 --- a/crates/ide-host/Cargo.toml +++ b/crates/ide-host/Cargo.toml @@ -30,6 +30,8 @@ ide-vcs.workspace = true ide-dap.workspace = true ide-heap.workspace = true ide-jvm-attach.workspace = true +ide-jvm-inspect.workspace = true +ide-streams.workspace = true ide-build.workspace = true ide-analysis.workspace = true ide-coverage.workspace = true diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 0b2e22f3c1..bc080c96f3 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -154,9 +154,14 @@ fn debug_server_port(config: &LaunchConfig) -> Option { fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port: u16) { let Ok(project) = host.project(window) else { return }; let Some(module) = project.lsp.java_debug_server_module(port) else { return }; - let inspector = std::sync::Arc::new(ide_lsp::JdtJvmInspector::new(project.lsp.clone(), module)); + let inspector = std::sync::Arc::new(ide_lsp::JdtJvmInspector::new(project.lsp.clone(), module.clone())); if let Err(e) = host.debugger.set_jvm_inspector(session, inspector) { tracing::debug!("jvm inspector for session {session:?}: {e}"); + return; + } + let tracer = std::sync::Arc::new(ide_lsp::JdtStreamTracer::new(project.lsp.clone(), module)); + if let Err(e) = host.debugger.set_stream_tracer(session, tracer) { + tracing::debug!("stream tracer for session {session:?}: {e}"); } } diff --git a/crates/ide-host/src/ops/mod.rs b/crates/ide-host/src/ops/mod.rs index 2e1d41fe5e..47a48d2b74 100644 --- a/crates/ide-host/src/ops/mod.rs +++ b/crates/ide-host/src/ops/mod.rs @@ -33,6 +33,7 @@ pub mod sdk; pub mod search; pub mod spell; mod ssh; +pub mod stream_trace; pub mod syntax; pub mod term; pub mod tools; @@ -88,6 +89,7 @@ pub fn register_all(d: &mut crate::rpc::Dispatcher) { java::register(d); debug::register(d); heap::register(d); + stream_trace::register(d); bytes::register(d); vcs::register(d); doc::register(d); diff --git a/crates/ide-host/src/ops/stream_trace.rs b/crates/ide-host/src/ops/stream_trace.rs new file mode 100644 index 0000000000..4015c63d8f --- /dev/null +++ b/crates/ide-host/src/ops/stream_trace.rs @@ -0,0 +1,462 @@ +//! Java Stream Debugger: the stream chains around a debugger stop, and traces of a chain's real run. +//! `ide_streams` finds the chains and links what the run recorded; `ide_dap` runs the trace. + +use crate::Host; +use crate::ops::Channel; +use crate::rpc::Dispatcher; +use ide_core::{CancellationToken, DebugSessionId, IdeError, IdeResult, LanguageId, Range, RequestId}; +use ide_dap::{StackFrame, TraceRun}; +pub use ide_dap::{TracePhase, TraceProgress, TraceUnavailable}; +pub use ide_jvm_inspect::{AbortState, JvmValue}; +use ide_jvm_inspect::{CollectedTerminal, TraceCollected}; +use ide_streams::{ + BoxKind, RealRunPlan, RealRunRefusal, Record, Rejection, StopContext, StreamChain, TerminalOutcome, TraceRecording, + TraceValue, find_chains, link_trace, real_run_plan, recorded_steps, +}; +pub use ide_streams::{Link, TraceBanner}; +use ide_syntax::{Snapshot, StructureService}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::path::Path; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StreamChainInfo { + /// The `chain_index` [`debug_stream_trace`] takes for the same frame. + pub index: u32, + pub range: Range, + pub text: String, + /// Intermediate operations in call order, modifiers included. Empty, like `terminal`, for a + /// chain the search rejected. + pub steps: Vec, + pub terminal: String, + pub available: bool, + /// Set exactly when `available` is false. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub reason: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum ChainUnavailable { + NotTopFrame, + NotAtChainStart, + InsideChainLambda, + NotJavaStreamRoot { + root: String, + }, + LazyTerminal { + op: String, + }, + NoTerminal, + UnknownOperation { + op: String, + }, + SyntaxError, + /// The session has no stream tracer: not java-debug, or its jdtls has no inspector bundle. + NoBackend, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum StreamTraceResult { + Ready { + chain: Box, + /// Column titles by recorded step: `steps[0]` is the root call's name (empty for a stream + /// held in a local), then each operation that records, modifiers left out. + steps: Vec, + /// In recording order. + records: Vec, + /// Parallel to `records`. + links: Vec, + terminal: TerminalView, + banners: Vec, + /// The stop the values belong to, for `debug_jvm_memory_fields`. + generation: u64, + }, + Unavailable { + reason: TraceUnavailable, + }, + Failed { + detail: String, + }, + /// Recording was stopped, or the operation aborted, before the chain ran: nothing went wrong. + Cancelled { + detail: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct TraceRecordView { + pub step: u16, + pub value: JvmValue, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TerminalView { + Value { value: JvmValue }, + Void, + Threw { exception: JvmValue }, +} + +/// The stream chains around `frame`'s line, in source order, with why each cannot be traced. +/// `top`: `frame` is the thread's top frame, the only one a trace can run from. +pub async fn debug_stream_chains( + host: &Host, + window: &str, + session: DebugSessionId, + frame: StackFrame, + top: bool, +) -> IdeResult> { + host.require_trust(window)?; + let backend = host.debugger.capabilities(session)?.stream_trace; + Ok(candidates(host, window, frame, top, backend).await?.into_iter().map(|c| c.info).collect()) +} + +/// Runs the program from `thread_id`, stopped in `frame`, through the chain `chain_index` of +/// [`debug_stream_chains`], recording each element, and leaves it stopped after the chain's +/// terminal operation. `range` is that chain's [`StreamChainInfo::range`]: an edit in between +/// can move another chain to the same index. Cancelling `request` stops recording while the +/// program runs on. +#[allow(clippy::too_many_arguments)] +pub async fn debug_stream_trace( + host: &Host, + window: &str, + session: DebugSessionId, + request: RequestId, + thread_id: i64, + frame: StackFrame, + chain_index: u32, + range: Range, + on_progress: Channel, +) -> IdeResult { + host.require_trust(window)?; + let cancel = host.begin_project_request(window, request); + let chain = ChainRef { frame, index: chain_index, range }; + let result = trace(host, window, session, thread_id, chain, &cancel, &on_progress).await; + host.end_request(request); + result +} + +/// The chain the UI chose, as [`debug_stream_chains`] listed it. +struct ChainRef { + frame: StackFrame, + index: u32, + range: Range, +} + +async fn trace( + host: &Host, + window: &str, + session: DebugSessionId, + thread_id: i64, + chosen: ChainRef, + cancel: &CancellationToken, + on_progress: &Channel, +) -> IdeResult { + let line = chosen.frame.line; + // `stream_trace` decides whether the session can trace, so the backend is assumed here. + let candidate = candidates(host, window, chosen.frame, true, true) + .await? + .into_iter() + .nth(chosen.index as usize) + .filter(|c| c.info.range == chosen.range); + let Some(candidate) = candidate else { + return Ok(StreamTraceResult::Failed { detail: "the chain changed; trace it again".into() }); + }; + if let Some(reason) = candidate.info.reason.clone() { + let reason = trace_unavailable(reason, line, candidate.chain.as_ref()); + return Ok(StreamTraceResult::Unavailable { reason }); + } + let Some(chain) = candidate.chain else { + return Err(IdeError::internal("an available stream chain has no parsed chain")); + }; + let plan = real_run_plan(&chain).map_err(|e| IdeError::internal(format!("stream chain plan: {e:?}")))?; + let plan_json = serde_json::to_value(&plan).map_err(|e| IdeError::internal(e.to_string()))?; + // `stream_trace` resumes the program before it looks at `cancel`. + if cancel.is_cancelled() { + return Ok(StreamTraceResult::Cancelled { detail: "cancelled before the trace started".into() }); + } + let progress = |p| { + let _ = on_progress.send(p); + }; + let run = host.debugger.stream_trace(session, thread_id, plan_json, cancel.clone(), progress).await?; + Ok(match run { + TraceRun::Done { collected, generation, resumed_stops } => { + let info = candidate.info; + host.blocking(move || Ok(ready(info, &chain, &plan, collected, generation, resumed_stops))).await? + } + TraceRun::Unavailable { reason } => StreamTraceResult::Unavailable { reason }, + TraceRun::Failed { detail } => StreamTraceResult::Failed { detail }, + TraceRun::Cancelled { detail } => StreamTraceResult::Cancelled { detail }, + }) +} + +/// Ends the running trace's terminal operation (Abort Operation); `None` when no trace runs. +pub async fn debug_stream_trace_abort( + host: &Host, + window: &str, + session: DebugSessionId, +) -> IdeResult> { + host.require_trust(window)?; + host.debugger.stream_trace_abort(session).await +} + +struct Candidate { + info: StreamChainInfo, + /// `None` for a chain the search rejected. + chain: Option, +} + +/// The file's current text (the open buffer, else the disk) searched off the command thread. +/// Frames outside readable Java sources have no chains: java-debug gives library frames +/// `jdt://contents/…` paths. +async fn candidates( + host: &Host, + window: &str, + frame: StackFrame, + top: bool, + backend: bool, +) -> IdeResult> { + let Some(path) = frame.path.clone() else { return Ok(Vec::new()) }; + let project = host.project(window)?; + host.blocking(move || { + let path = path.into_path_buf(); + let cancel = CancellationToken::new(); + let search = |snap: &Snapshot| { + if snap.language.as_str() != "java" { + return Ok(Vec::new()); + } + chains_at(&project.structure, snap, &frame, top, backend, &cancel) + }; + if let Some(doc) = project.documents.by_path(&path) { + let snap = project.documents.text_snapshot(doc)?; + if snap.large { + return Err(IdeError::unavailable("file is too large for syntax analysis")); + } + return search(&Snapshot::doc(doc, snap.version, &snap.language, &snap.text)); + } + let language: LanguageId = project.languages.detect(&path, None); + if language.as_str() != "java" { + return Ok(Vec::new()); + } + let Ok(text) = project.text_of(&path) else { return Ok(Vec::new()) }; + search(&Snapshot::text(&language, &text)) + }) + .await +} + +fn chains_at( + service: &StructureService, + snap: &Snapshot, + frame: &StackFrame, + top: bool, + backend: bool, + cancel: &CancellationToken, +) -> IdeResult> { + let path = frame.path.as_ref().map(|p| p.0.as_path()); + let file_stem = path.and_then(Path::file_stem).and_then(|s| s.to_str()).unwrap_or_default(); + let stop = StopContext { line: frame.line, in_lambda: frame.name.contains("lambda$"), file_stem }; + let found = find_chains(service, snap, &stop, cancel)?; + let mut candidates: Vec = found + .chains + .into_iter() + .map(|chain| { + let reason = refusal(&chain, frame.line, top, backend); + let info = StreamChainInfo { + index: 0, + range: chain.range, + text: chain.text.clone(), + steps: chain.ops.iter().map(|op| op.name.clone()).collect(), + terminal: chain.terminal.name.clone(), + available: reason.is_none(), + reason, + }; + Candidate { info, chain: Some(chain) } + }) + .collect(); + candidates.extend(found.rejected.into_iter().map(|rejected| { + let reason = if top { rejection(rejected.reason) } else { ChainUnavailable::NotTopFrame }; + let info = StreamChainInfo { + index: 0, + range: rejected.range, + text: rejected.text, + steps: Vec::new(), + terminal: String::new(), + available: false, + reason: Some(reason), + }; + Candidate { info, chain: None } + })); + candidates.sort_by_key(|c| c.info.range); + for (i, c) in candidates.iter_mut().enumerate() { + c.info.index = i as u32; + } + Ok(candidates) +} + +fn refusal(chain: &StreamChain, line: u32, top: bool, backend: bool) -> Option { + if !top { + return Some(ChainUnavailable::NotTopFrame); + } + // ECJ puts the first instruction of `T x =\n root…` on the root's line, not the + // statement's; the bundle makes the final call from the line table. + if line < chain.first_line || line > root_line(chain) { + return Some(ChainUnavailable::NotAtChainStart); + } + if let Err(refused) = real_run_plan(chain) { + return Some(refusal_reason(refused)); + } + (!backend).then_some(ChainUnavailable::NoBackend) +} + +fn root_line(chain: &StreamChain) -> u32 { + let before_root = chain.text.get(..chain.root.span.0).unwrap_or_default(); + chain.range.start.line + before_root.matches('\n').count() as u32 +} + +fn refusal_reason(refused: RealRunRefusal) -> ChainUnavailable { + match refused { + RealRunRefusal::NotJavaStreamRoot { root } => ChainUnavailable::NotJavaStreamRoot { root }, + RealRunRefusal::LazyTerminal { op } => ChainUnavailable::LazyTerminal { op }, + RealRunRefusal::NoTerminal => ChainUnavailable::NoTerminal, + RealRunRefusal::UnknownOperation { op } => ChainUnavailable::UnknownOperation { op }, + RealRunRefusal::InsideChainLambda => ChainUnavailable::InsideChainLambda, + RealRunRefusal::SyntaxError => ChainUnavailable::SyntaxError, + } +} + +fn rejection(rejected: Rejection) -> ChainUnavailable { + match rejected { + Rejection::LazyTerminal { op } => ChainUnavailable::LazyTerminal { op }, + Rejection::NoTerminal => ChainUnavailable::NoTerminal, + Rejection::UnknownOperation { op } => ChainUnavailable::UnknownOperation { op }, + Rejection::InsideChainLambda => ChainUnavailable::InsideChainLambda, + Rejection::SyntaxError => ChainUnavailable::SyntaxError, + } +} + +/// The same reasons as the bundle's refusals, for a chain that stopped being traceable between +/// [`debug_stream_chains`] and [`debug_stream_trace`]. +fn trace_unavailable(reason: ChainUnavailable, line: u32, chain: Option<&StreamChain>) -> TraceUnavailable { + let unsupported = |detail: String| TraceUnavailable::Unsupported { detail }; + match reason { + ChainUnavailable::NotAtChainStart => { + let start = chain.map_or(String::new(), |c| format!(", the chain starts on line {}", c.first_line + 1)); + TraceUnavailable::NotAtChainStart { detail: format!("the stop is on line {}{start}", line + 1) } + } + ChainUnavailable::NoBackend => TraceUnavailable::NoBackend, + ChainUnavailable::NotTopFrame => unsupported("only the top frame can be traced".into()), + ChainUnavailable::InsideChainLambda => unsupported("the chain is already running".into()), + ChainUnavailable::NotJavaStreamRoot { root } => { + unsupported(format!("the stream {root} does not start in this statement")) + } + ChainUnavailable::LazyTerminal { op } => unsupported(format!("{op}() does not run the pipeline")), + ChainUnavailable::NoTerminal => unsupported("the chain has no terminal operation".into()), + ChainUnavailable::UnknownOperation { op } => unsupported(format!("unknown stream operation {op}()")), + ChainUnavailable::SyntaxError => unsupported("the statement does not parse".into()), + } +} + +fn ready( + chain_info: StreamChainInfo, + chain: &StreamChain, + plan: &RealRunPlan, + collected: TraceCollected, + generation: u64, + resumed_stops: u32, +) -> StreamTraceResult { + let recording = TraceRecording { + records: collected.records.iter().map(|(step, v)| Record { step: *step, value: trace_value(v) }).collect(), + dropped: collected.dropped, + terminal: match &collected.terminal { + CollectedTerminal::Value(v) => TerminalOutcome::Value { value: trace_value(v) }, + CollectedTerminal::Void => TerminalOutcome::Void, + CollectedTerminal::Threw(e) => TerminalOutcome::Threw { exception: trace_value(e) }, + }, + }; + let mut linked = link_trace(plan, &recording, collected.skipped_breakpoints); + if resumed_stops > 0 { + linked.banners.push(TraceBanner::BreakpointsResumed { count: resumed_stops }); + } + StreamTraceResult::Ready { + chain: Box::new(chain_info), + steps: recorded_steps(chain), + records: collected.records.into_iter().map(|(step, value)| TraceRecordView { step, value }).collect(), + links: linked.links, + terminal: match collected.terminal { + CollectedTerminal::Value(value) => TerminalView::Value { value }, + CollectedTerminal::Void => TerminalView::Void, + CollectedTerminal::Threw(exception) => TerminalView::Threw { exception }, + }, + banners: linked.banners, + generation, + } +} + +fn trace_value(value: &JvmValue) -> TraceValue { + match value { + JvmValue::Null => TraceValue::Null, + JvmValue::Boxed { id, type_name, text } => match box_kind(type_name) { + Some(class) => TraceValue::Boxed { id: *id, class, value: text.clone() }, + None => TraceValue::Object { id: *id, class: type_name.clone() }, + }, + JvmValue::Str { id, text, .. } => { + TraceValue::Str { id: *id, value: text.clone().unwrap_or_default(), truncated: text.is_none() } + } + JvmValue::Object { id, type_name } | JvmValue::Array { id, type_name, .. } => { + TraceValue::Object { id: *id, class: type_name.clone() } + } + // The recorder boxes every element, so only a terminal's result is primitive, and linking + // never reads that. + JvmValue::Primitive { type_name, text } => match box_kind(type_name) { + Some(class) => TraceValue::Boxed { id: 0, class, value: text.clone() }, + None => TraceValue::Null, + }, + } +} + +/// Wrapper class names (boxed values) and primitive type names (primitive values) alike. +fn box_kind(type_name: &str) -> Option { + Some(match type_name { + "java.lang.Boolean" | "boolean" => BoxKind::Boolean, + "java.lang.Byte" | "byte" => BoxKind::Byte, + "java.lang.Character" | "char" => BoxKind::Char, + "java.lang.Short" | "short" => BoxKind::Short, + "java.lang.Integer" | "int" => BoxKind::Int, + "java.lang.Long" | "long" => BoxKind::Long, + "java.lang.Float" | "float" => BoxKind::Float, + "java.lang.Double" | "double" => BoxKind::Double, + _ => return None, + }) +} + +/// Commands of this module the remote server answers. +pub(crate) fn register(d: &mut Dispatcher) { + d.add("debug_stream_chains", |c| async move { + debug_stream_chains(&c.host, &c.window, c.arg("session")?, c.arg("frame")?, c.arg("top")?).await + }); + d.add("debug_stream_trace", |c| async move { + debug_stream_trace( + &c.host, + &c.window, + c.arg("session")?, + c.arg("request")?, + c.arg("threadId")?, + c.arg("frame")?, + c.arg("chainIndex")?, + c.arg("range")?, + c.sender("onProgress")?, + ) + .await + }); + d.add("debug_stream_trace_abort", |c| async move { + debug_stream_trace_abort(&c.host, &c.window, c.arg("session")?).await + }); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ide-host/src/ops/stream_trace/tests.rs b/crates/ide-host/src/ops/stream_trace/tests.rs new file mode 100644 index 0000000000..cf0e63b63d --- /dev/null +++ b/crates/ide-host/src/ops/stream_trace/tests.rs @@ -0,0 +1,444 @@ +use super::*; +use ide_core::{CancellationToken, LanguageId}; +use ide_language::{Syntax, SyntaxCache}; +use ide_streams::BoxKind; +use serde_json::json; +use std::sync::{Arc, OnceLock}; + +const SOURCE: &str = r#"import java.util.*; +import java.util.stream.*; + +class Chains { + Stream items; + + void run(List nums) { + List evens = nums.stream() // C_EVENS + .filter(x -> x % 2 == 0) // C_EVENS_FILTER + .collect(Collectors.toList()); + List out = // C_DECL + nums.stream() // C_ROOT + .map(x -> x + 1) // C_ROOT_MAP + .collect(Collectors.toList()); + long n = this.items.filter(x -> x > 0).count(); // C_FIELD + Iterator it = nums.stream().map(x -> x).iterator(); // C_LAZY + List a = nums.stream().filter(x -> x % 2 == 0).map(x -> x * 10 + 1).sorted().map(String::valueOf).collect(Collectors.toList()); // C_SPIKE + } +} +"#; + +fn service() -> &'static StructureService { + static S: OnceLock = OnceLock::new(); + S.get_or_init(|| StructureService::new(Arc::new(SyntaxCache::new(Arc::new(Syntax::new()))))) +} + +fn line_of(marker: &str) -> u32 { + let tag = format!("// {marker}"); + let found = SOURCE.lines().position(|l| l.trim_end().ends_with(&tag)); + found.unwrap_or_else(|| panic!("no line marked {marker}")) as u32 +} + +fn frame(line: u32) -> StackFrame { + StackFrame { + id: 1, + name: "Chains.run(List)".into(), + path: Some("/project/src/Chains.java".into()), + line, + column: 8, + presentation_hint: None, + } +} + +fn chains_on(line: u32, top: bool, backend: bool) -> Vec { + let java = LanguageId::new("java"); + let snap = Snapshot::text(&java, SOURCE); + let found = chains_at(service(), &snap, &frame(line), top, backend, &CancellationToken::new()).expect("search"); + found.into_iter().map(|c| c.info).collect() +} + +fn availability(info: &StreamChainInfo) -> serde_json::Value { + let mut v = serde_json::to_value(info).unwrap(); + let map = v.as_object_mut().unwrap(); + json!({ "available": map.remove("available"), "reason": map.remove("reason") }) +} + +#[test] +fn chains_refuse_non_top_frame() { + let infos = chains_on(line_of("C_EVENS"), false, true); + assert!(!infos.is_empty()); + for info in &infos { + assert_eq!(availability(info), json!({"available": false, "reason": {"kind": "notTopFrame"}}), "{info:?}"); + } +} + +#[test] +fn chains_need_first_line() { + let infos = chains_on(line_of("C_EVENS_FILTER"), true, true); + assert_eq!(infos.len(), 1, "{infos:?}"); + assert_eq!(availability(&infos[0]), json!({"available": false, "reason": {"kind": "notAtChainStart"}})); + let mid = chains_on(line_of("C_ROOT_MAP"), true, true); + assert_eq!(availability(&mid[0]), json!({"available": false, "reason": {"kind": "notAtChainStart"}})); +} + +/// ECJ puts a declaration's first instruction on the line of its initializer's root call. +#[test] +fn chains_accept_the_root_line_of_a_declaration() { + let at_root = chains_on(line_of("C_ROOT"), true, true); + assert_eq!(at_root.len(), 1, "{at_root:?}"); + assert_eq!(availability(&at_root[0]), json!({"available": true, "reason": null})); + let at_head = chains_on(line_of("C_DECL"), true, true); + assert_eq!(availability(&at_head[0]), json!({"available": true, "reason": null})); +} + +#[test] +fn chains_list_rejections() { + let field = chains_on(line_of("C_FIELD"), true, true); + assert_eq!(field.len(), 1, "{field:?}"); + assert_eq!( + availability(&field[0]), + json!({"available": false, "reason": {"kind": "notJavaStreamRoot", "root": "this.items"}}) + ); + let lazy = chains_on(line_of("C_LAZY"), true, true); + assert_eq!(lazy.len(), 1, "{lazy:?}"); + assert_eq!( + availability(&lazy[0]), + json!({"available": false, "reason": {"kind": "lazyTerminal", "op": "iterator"}}) + ); +} + +#[test] +fn chains_without_a_tracer_have_no_backend() { + let infos = chains_on(line_of("C_EVENS"), true, false); + assert_eq!(availability(&infos[0]), json!({"available": false, "reason": {"kind": "noBackend"}})); +} + +#[test] +fn chain_info_json_shape() { + let infos = chains_on(line_of("C_EVENS"), true, true); + let v = serde_json::to_value(&infos[0]).unwrap(); + assert_eq!(v["index"], 0); + assert_eq!(v["steps"], json!(["filter"])); + assert_eq!(v["terminal"], "collect"); + assert_eq!(v["range"]["start"]["line"], line_of("C_EVENS")); + assert_eq!(v["available"], true); + assert!(v.get("reason").is_none(), "{v}"); +} + +#[test] +fn jvm_value_to_trace_value() { + let boxed = JvmValue::Boxed { id: 4, type_name: "java.lang.Integer".into(), text: "8".into() }; + assert_eq!(trace_value(&boxed), TraceValue::Boxed { id: 4, class: BoxKind::Int, value: "8".into() }); + let long_text = JvmValue::Str { id: 5, text: None, length: 50_000 }; + assert_eq!(trace_value(&long_text), TraceValue::Str { id: 5, value: String::new(), truncated: true }); + let short_text = JvmValue::Str { id: 6, text: Some("81".into()), length: 2 }; + assert_eq!(trace_value(&short_text), TraceValue::Str { id: 6, value: "81".into(), truncated: false }); + let object = JvmValue::Object { id: 7, type_name: "com.x.Order".into() }; + assert_eq!(trace_value(&object), TraceValue::Object { id: 7, class: "com.x.Order".into() }); + let array = JvmValue::Array { id: 8, type_name: "int[]".into(), length: 3 }; + assert_eq!(trace_value(&array), TraceValue::Object { id: 8, class: "int[]".into() }); + assert_eq!(trace_value(&JvmValue::Null), TraceValue::Null); + let odd_box = JvmValue::Boxed { id: 9, type_name: "java.math.BigInteger".into(), text: "1".into() }; + assert_eq!(trace_value(&odd_box), TraceValue::Object { id: 9, class: "java.math.BigInteger".into() }); + let count = JvmValue::Primitive { type_name: "long".into(), text: "4".into() }; + assert_eq!(trace_value(&count), TraceValue::Boxed { id: 0, class: BoxKind::Long, value: "4".into() }); + let odd_primitive = JvmValue::Primitive { type_name: "void".into(), text: String::new() }; + assert_eq!(trace_value(&odd_primitive), TraceValue::Null); +} + +/// The log measured on `source -> filter -> map -> sorted -> map` (see ide-streams' spike test), +/// as the bundle reports it: every `peek` re-boxes, so no two boxes share an id. +fn spike_collected() -> TraceCollected { + let steps_values: [(u16, &str); 24] = [ + (0, "5"), + (0, "3"), + (0, "8"), + (1, "8"), + (2, "81"), + (0, "1"), + (0, "4"), + (1, "4"), + (2, "41"), + (0, "2"), + (1, "2"), + (2, "21"), + (0, "9"), + (0, "6"), + (1, "6"), + (2, "61"), + (3, "21"), + (4, "21"), + (3, "41"), + (4, "41"), + (3, "61"), + (4, "61"), + (3, "81"), + (4, "81"), + ]; + let records = steps_values + .iter() + .enumerate() + .map(|(i, &(step, text))| { + let id = 100 + i as u64; + let value = if step == 4 { + JvmValue::Str { id, text: Some(text.into()), length: text.len() as u32 } + } else { + JvmValue::Boxed { id, type_name: "java.lang.Integer".into(), text: text.into() } + }; + (step, value) + }) + .collect(); + TraceCollected { + records, + dropped: 3, + terminal: CollectedTerminal::Value(JvmValue::Object { id: 7, type_name: "java.util.ArrayList".into() }), + skipped_breakpoints: 2, + sequentialized: false, + } +} + +#[test] +fn ready_links_the_collected_records() { + 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(); + let collected = spike_collected(); + let expected_records: Vec = + collected.records.iter().map(|(step, value)| TraceRecordView { step: *step, value: value.clone() }).collect(); + + let StreamTraceResult::Ready { chain: shown, steps, records, links, terminal, banners, generation } = + ready(info.clone(), &chain, &plan, collected, 9, 0) + else { + panic!("not ready"); + }; + assert_eq!(*shown, info); + assert_eq!(steps, ["stream", "filter", "map", "sorted", "map"]); + assert_eq!(records, expected_records); + assert_eq!(links.len(), records.len()); + assert_eq!(links[0], Link { parent: None, ambiguous: false }); + // `1=8` comes from the `0=8` just before it, and `2=81` from that. + assert_eq!(links[3].parent, Some(2)); + assert_eq!(links[4].parent, Some(3)); + // `sorted` emits `3=21` after the whole upstream ran: it is the `2=21` of record 11, linked by + // value although the box was re-made. + assert_eq!(links[16], Link { parent: Some(11), ambiguous: false }); + assert_eq!(links[17].parent, Some(16)); + assert_eq!(links[22].parent, Some(4)); + assert_eq!( + terminal, + TerminalView::Value { value: JvmValue::Object { id: 7, type_name: "java.util.ArrayList".into() } } + ); + assert_eq!(banners, [TraceBanner::Truncated { dropped: 3 }, TraceBanner::BreakpointsSkipped { count: 2 }]); + assert_eq!(generation, 9); +} + +#[test] +fn ready_says_how_many_stops_were_resumed() { + 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(); + + let StreamTraceResult::Ready { banners, .. } = ready(info, &chain, &plan, spike_collected(), 9, 3) else { + panic!("not ready"); + }; + assert_eq!( + banners, + [ + TraceBanner::Truncated { dropped: 3 }, + TraceBanner::BreakpointsSkipped { count: 2 }, + TraceBanner::BreakpointsResumed { count: 3 } + ] + ); +} + +const WINDOW: &str = "main"; + +/// A real `Host` with a trusted project holding `src/Chains.java` (= [`SOURCE`]). +struct Fixture { + host: Host, + source: std::path::PathBuf, + _temp: tempfile::TempDir, +} + +impl Fixture { + async fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + std::fs::create_dir_all(root.join("src")).unwrap(); + let source = root.join("src/Chains.java"); + std::fs::write(&source, SOURCE).unwrap(); + let host = Host::new(crate::HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(|_| {})), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + host.open_project(WINDOW, &root).unwrap(); + host.set_project_trust(&root, true, false).await.unwrap(); + Self { host, source, _temp: temp } + } + + fn frame(&self, line: u32) -> StackFrame { + StackFrame { path: Some(self.source.as_path().into()), ..frame(line) } + } + + async fn chains(&self, frame: StackFrame) -> Vec { + candidates(&self.host, WINDOW, frame, true, true).await.unwrap().into_iter().map(|c| c.info).collect() + } + + async fn trace(&self, request: u32, frame: StackFrame, index: u32, range: Range) -> StreamTraceResult { + let request = RequestId(request); + debug_stream_trace( + &self.host, + WINDOW, + DebugSessionId(404), + request, + 1, + frame, + index, + range, + Channel::new(|_| {}), + ) + .await + .unwrap() + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn chains_skip_frames_without_a_readable_java_source() { + let f = Fixture::new().await; + assert_eq!(f.chains(f.frame(line_of("C_EVENS"))).await.len(), 1, "the file on disk is read"); + let library = StackFrame { + path: Some("jdt://contents/rt.jar/java.util.stream/ReferencePipeline.class?=java/rt.jar".into()), + ..frame(120) + }; + assert_eq!(f.chains(library).await, []); + let missing = StackFrame { path: Some(f.source.with_file_name("Missing.java").as_path().into()), ..frame(3) }; + assert_eq!(f.chains(missing).await, []); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn trace_refuses_a_chain_that_changed() { + let f = Fixture::new().await; + let at = f.frame(line_of("C_EVENS")); + let listed = f.chains(at.clone()).await.remove(0); + let changed = StreamTraceResult::Failed { detail: "the chain changed; trace it again".into() }; + let mut moved = listed.range; + moved.end.col += 1; + assert_eq!(f.trace(1, at.clone(), listed.index, moved).await, changed); + assert_eq!(f.trace(2, at, listed.index + 1, listed.range).await, changed); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn trace_reports_an_unavailable_chain_like_the_bundle() { + let f = Fixture::new().await; + let mid = f.frame(line_of("C_EVENS_FILTER")); + let listed = f.chains(mid.clone()).await.remove(0); + let detail = format!( + "the stop is on line {}, the chain starts on line {}", + line_of("C_EVENS_FILTER") + 1, + line_of("C_EVENS") + 1 + ); + assert_eq!( + f.trace(1, mid, listed.index, listed.range).await, + StreamTraceResult::Unavailable { reason: TraceUnavailable::NotAtChainStart { detail } } + ); + let field = f.frame(line_of("C_FIELD")); + let listed = f.chains(field.clone()).await.remove(0); + let detail = "the stream this.items does not start in this statement".to_string(); + assert_eq!( + f.trace(2, field, listed.index, listed.range).await, + StreamTraceResult::Unavailable { reason: TraceUnavailable::Unsupported { detail } } + ); +} + +/// The session id names no session: reaching `stream_trace` would fail the call. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn trace_cancelled_before_it_starts_does_not_run() { + let f = Fixture::new().await; + let at = f.frame(line_of("C_EVENS")); + let listed = f.chains(at.clone()).await.remove(0); + f.host.cancel_request(RequestId(7)); + assert_eq!( + f.trace(7, at, listed.index, listed.range).await, + StreamTraceResult::Cancelled { detail: "cancelled before the trace started".into() } + ); + assert_eq!( + serde_json::to_value(StreamTraceResult::Cancelled { detail: "x".into() }).unwrap(), + json!({"status": "cancelled", "detail": "x"}) + ); +} + +#[test] +fn ready_result_json_shape() { + let info = chains_on(line_of("C_EVENS"), true, true).remove(0); + let value = JvmValue::Boxed { id: 4, type_name: "java.lang.Integer".into(), text: "8".into() }; + let ready = StreamTraceResult::Ready { + chain: Box::new(info), + steps: vec!["stream".into(), "filter".into()], + records: vec![TraceRecordView { step: 0, value: value.clone() }], + links: vec![Link { parent: None, ambiguous: false }], + terminal: TerminalView::Threw { exception: JvmValue::Object { id: 9, type_name: "java.lang.X".into() } }, + banners: vec![TraceBanner::Truncated { dropped: 2 }, TraceBanner::BreakpointsSkipped { count: 1 }], + generation: 3, + }; + let v = serde_json::to_value(&ready).unwrap(); + assert_eq!(v["status"], "ready"); + assert_eq!(v["chain"]["available"], true); + assert_eq!(v["steps"], json!(["stream", "filter"])); + assert_eq!( + v["records"], + json!([{"step": 0, "value": {"kind": "boxed", "id": 4, "typeName": "java.lang.Integer", "text": "8"}}]) + ); + assert_eq!(v["links"], json!([{"parent": null, "ambiguous": false}])); + assert_eq!( + v["terminal"], + json!({"kind": "threw", "exception": {"kind": "object", "id": 9, "typeName": "java.lang.X"}}) + ); + assert_eq!(v["banners"], json!([{"kind": "truncated", "dropped": 2}, {"kind": "breakpointsSkipped", "count": 1}])); + assert_eq!(v["generation"], 3); + assert_eq!(serde_json::to_value(TerminalView::Value { value }).unwrap()["kind"], "value"); + assert_eq!(serde_json::to_value(TerminalView::Void).unwrap(), json!({"kind": "void"})); +} + +#[test] +fn other_results_json_shape() { + let unavailable = + StreamTraceResult::Unavailable { reason: TraceUnavailable::NotAtChainStart { detail: "line 4".into() } }; + assert_eq!( + serde_json::to_value(&unavailable).unwrap(), + json!({"status": "unavailable", "reason": {"kind": "notAtChainStart", "detail": "line 4"}}) + ); + assert_eq!( + serde_json::to_value(StreamTraceResult::Failed { detail: "boom".into() }).unwrap(), + json!({"status": "failed", "detail": "boom"}) + ); + let progress = TraceProgress { phase: TracePhase::RecordingStopped, records: 5, dropped: 0, elapsed_ms: 40 }; + assert_eq!( + serde_json::to_value(&progress).unwrap(), + json!({"phase": "recordingStopped", "records": 5, "dropped": 0, "elapsedMs": 40}) + ); + let stuck = AbortState::Stuck { holders: vec![(3, "main".into())] }; + assert_eq!(serde_json::to_value(&stuck).unwrap(), json!({"kind": "stuck", "holders": [[3, "main"]]})); + assert_eq!(serde_json::to_value(AbortState::Interrupted).unwrap(), json!({"kind": "interrupted"})); +} + +#[test] +fn chain_info_steps_keep_modifiers() { + let java = LanguageId::new("java"); + let source = "class Chains { void run(java.util.List nums) {\n\ + long n = nums.parallelStream().filter(x -> x > 0).unordered().map(x -> x).count();\n} }"; + let snap = Snapshot::text(&java, source); + let found = chains_at(service(), &snap, &frame(1), true, true, &CancellationToken::new()).unwrap(); + assert_eq!(found[0].info.steps, ["filter", "unordered", "map"]); +} diff --git a/crates/ide-jvm-inspect/Cargo.toml b/crates/ide-jvm-inspect/Cargo.toml index 7d7630dffe..c0f961087c 100644 --- a/crates/ide-jvm-inspect/Cargo.toml +++ b/crates/ide-jvm-inspect/Cargo.toml @@ -8,8 +8,6 @@ license.workspace = true [dependencies] futures.workspace = true serde.workspace = true +serde_json.workspace = true specta.workspace = true thiserror.workspace = true - -[dev-dependencies] -serde_json.workspace = true diff --git a/crates/ide-jvm-inspect/src/lib.rs b/crates/ide-jvm-inspect/src/lib.rs index 71a4031608..f7c7cbf0e6 100644 --- a/crates/ide-jvm-inspect/src/lib.rs +++ b/crates/ide-jvm-inspect/src/lib.rs @@ -2,8 +2,10 @@ //! suspended. Implementations live elsewhere (jdtls bundle for Java, JDWP link for Kotlin). mod names; +mod stream; pub use names::{is_boxed, name_to_signature, signature_to_name, string_length}; +pub use stream::{AbortState, CollectedTerminal, StreamTracer, TraceCollected, TraceId, TraceState}; use futures::future::BoxFuture; use serde::{Deserialize, Serialize}; @@ -112,6 +114,15 @@ pub enum InspectError { VmNotFound, #[error("not supported by this debug adapter: {0}")] Unsupported(String), + #[error("java-debug has no debug session for this JVM")] + NoSession, + /// The bundle's reason, e.g. which line the chain starts on. + #[error("the debuggee is not stopped where the stream chain starts: {0}")] + NotAtChainStart(String), + #[error("a stream trace is already running in this JVM")] + Busy, + #[error("there is no such stream trace in this JVM")] + NoTrace, #[error("the request timed out")] TimedOut, #[error("the connection was closed")] diff --git a/crates/ide-jvm-inspect/src/stream.rs b/crates/ide-jvm-inspect/src/stream.rs new file mode 100644 index 0000000000..975d102a29 --- /dev/null +++ b/crates/ide-jvm-inspect/src/stream.rs @@ -0,0 +1,84 @@ +//! Tracing a stream chain while the program itself runs it. One trace per VM; the trace's records +//! are read back once the debuggee is suspended again. + +use crate::{InspectFuture, JvmValue, VmTarget}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +/// Assigned by the debuggee-side bundle; valid for one VM. +pub type TraceId = u64; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TraceState { + Running { + records: u64, + dropped: u64, + elapsed_ms: u64, + }, + /// The terminal operation finished and the thread is suspended again, ready to `collect`. + Parked { + records: u64, + dropped: u64, + }, + Failed { + detail: String, + }, + /// Stopped or aborted before the terminal operation ran: taken down, the program untouched. + Cancelled { + detail: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum AbortState { + Interrupted, + Stopped, + /// Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. + Stuck { + holders: Vec<(i64, String)>, + }, + /// The terminal had not started. + Cancelled, + /// The trace had already parked or failed. + Finished, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CollectedTerminal { + Value(JvmValue), + Void, + Threw(JvmValue), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TraceCollected { + /// `(step, value)`: step counts the wrapped ops from 0 (the source). + pub records: Vec<(u16, JvmValue)>, + /// Records past the arm-time budget; counted, not kept. + pub dropped: u64, + pub terminal: CollectedTerminal, + pub skipped_breakpoints: u32, + /// A parallel chain was forced to run sequentially so that records keep their order. + pub sequentialized: bool, +} + +pub trait StreamTracer: Send + Sync { + /// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. + fn arm<'a>( + &'a self, + target: &'a VmTarget, + thread_id: i64, + plan: &'a serde_json::Value, + budget: u32, + ) -> 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>; + /// Stops keeping records while the terminal keeps running; returns the records kept so far. + fn stop<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, u64>; + fn abort<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, AbortState>; + /// `target.generation` must be a stop after the trace parked. `records`: how many it parked + /// 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, ()>; +} diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 6c256e8b6f..22ad93dda9 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -26,6 +26,7 @@ pub(crate) mod jvm_inspect; mod move_refactoring; pub(crate) mod reserved_names; mod signature; +pub(crate) mod stream_trace; pub use formatter::configure_formatter; /// First start imports the Maven / Gradle model, which can take minutes. const READY_TIMEOUT: Duration = Duration::from_secs(240); diff --git a/crates/ide-lsp/src/jdtls/jvm_inspect.rs b/crates/ide-lsp/src/jdtls/jvm_inspect.rs index 6a6b675865..ad9f48024c 100644 --- a/crates/ide-lsp/src/jdtls/jvm_inspect.rs +++ b/crates/ide-lsp/src/jdtls/jvm_inspect.rs @@ -63,7 +63,7 @@ impl JdtJvmInspector { } /// `VmTarget` is not `Serialize`: the field names here are the bundle's. -fn target_json(target: &VmTarget) -> Value { +pub(super) fn target_json(target: &VmTarget) -> Value { json!({ "pid": target.pid, "host": target.attach_host, @@ -72,7 +72,7 @@ fn target_json(target: &VmTarget) -> Value { }) } -fn command_error(e: IdeError) -> InspectError { +pub(super) fn command_error(e: IdeError) -> InspectError { if missing_bundle(&e) { InspectError::Unsupported("the JVM inspector bundle is not loaded".to_owned()) } else { @@ -81,7 +81,7 @@ fn command_error(e: IdeError) -> InspectError { } /// `{"ok": payload}` or `{"error": code, "detail": text}`. -fn decode(mut reply: Value) -> Result { +pub(super) fn decode(mut reply: Value) -> Result { if let Some(code) = reply.get("error").and_then(Value::as_str) { let detail = reply.get("detail").and_then(Value::as_str); return Err(match code { @@ -94,6 +94,11 @@ fn decode(mut reply: Value) -> Result { "classNotLoaded" => InspectError::ClassNotLoaded, "notSuspended" => InspectError::NotSuspended, "timedOut" => InspectError::TimedOut, + "noSession" => InspectError::NoSession, + "notAtChainStart" => InspectError::NotAtChainStart(detail.unwrap_or_default().to_owned()), + "busy" => InspectError::Busy, + "noTrace" => InspectError::NoTrace, + "failed" | "badArgument" => InspectError::Failed(detail.unwrap_or(code).to_owned()), other => InspectError::Failed(match detail { Some(detail) => format!("{other}: {detail}"), None => other.to_owned(), diff --git a/crates/ide-lsp/src/jdtls/stream_trace.rs b/crates/ide-lsp/src/jdtls/stream_trace.rs new file mode 100644 index 0000000000..6eceb36baa --- /dev/null +++ b/crates/ide-lsp/src/jdtls/stream_trace.rs @@ -0,0 +1,238 @@ +//! [`StreamTracer`] over the `openidea.jvm.stream.*` commands of the JVM inspector bundle that runs +//! inside jdtls (`java/jvm-inspect`). + +use super::jvm_inspect::{command_error, decode, target_json}; +use crate::LspManager; +use ide_jvm_inspect::{ + AbortState, CollectedTerminal, InspectError, InspectFuture, JvmValue, StreamTracer, TraceCollected, TraceId, + TraceState, VmTarget, +}; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use tokio::time::timeout; + +/// `wait` is held by the bundle for the `ms` it is given; the command times out this long after. +const WAIT_SLACK: Duration = Duration::from_secs(10); +const ABORT_TIMEOUT: Duration = Duration::from_secs(15); +const COMMAND_TIMEOUT: Duration = Duration::from_secs(15); + +/// Each record is previewed with at least one JDWP round trip (about 0.1 ms locally, far more +/// over a remote attach). +fn collect_timeout(records: u64) -> Duration { + Duration::from_secs(60) + .saturating_add(Duration::from_millis(5).saturating_mul(records.try_into().unwrap_or(u32::MAX))) +} + +pub struct JdtStreamTracer { + lsp: Arc, + /// A path inside the module whose jdtls runs the debug session. + server: PathBuf, +} + +impl JdtStreamTracer { + /// Deliberately without `JdtJvmInspector`'s turn: a `wait` that holds a JDT LS thread for + /// seconds must not keep the memory view from reading while the trace runs. + pub fn new(lsp: Arc, server: PathBuf) -> Self { + Self { lsp, server } + } + + async fn call( + &self, + op: &str, + target: &VmTarget, + args: Value, + limit: Duration, + ) -> Result { + let command = format!("openidea.jvm.stream.{op}"); + let arguments = vec![target_json(target), args]; + let reply = timeout(limit, self.lsp.jdtls_command(&self.server, &command, arguments)) + .await + .map_err(|_| InspectError::TimedOut)? + .map_err(command_error)?; + decode(reply) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Armed { + trace_id: TraceId, +} + +#[derive(Deserialize)] +#[serde(tag = "state", rename_all = "camelCase", rename_all_fields = "camelCase")] +enum WireState { + Running { + records: u64, + dropped: u64, + elapsed_ms: u64, + }, + Parked { + records: u64, + dropped: u64, + }, + Failed { + #[serde(default)] + detail: String, + }, + Cancelled { + #[serde(default)] + detail: String, + }, +} + +impl From for TraceState { + fn from(state: WireState) -> Self { + match state { + WireState::Running { records, dropped, elapsed_ms } => Self::Running { records, dropped, elapsed_ms }, + WireState::Parked { records, dropped } => Self::Parked { records, dropped }, + WireState::Failed { detail } => Self::Failed { detail }, + WireState::Cancelled { detail } => Self::Cancelled { detail }, + } + } +} + +#[derive(Deserialize)] +struct Stopped { + records: u64, +} + +#[derive(Deserialize)] +#[serde(tag = "state", rename_all = "camelCase")] +enum WireAbort { + Interrupted, + Stopped, + Stuck { + #[serde(default)] + holders: Vec, + }, + Cancelled, + Finished, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Holder { + thread_id: i64, + name: String, +} + +impl From for AbortState { + fn from(state: WireAbort) -> Self { + match state { + WireAbort::Interrupted => Self::Interrupted, + WireAbort::Stopped => Self::Stopped, + WireAbort::Stuck { holders } => { + Self::Stuck { holders: holders.into_iter().map(|h| (h.thread_id, h.name)).collect() } + } + WireAbort::Cancelled => Self::Cancelled, + WireAbort::Finished => Self::Finished, + } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WireCollected { + records: Vec, + dropped: u64, + terminal: WireTerminal, + skipped_breakpoints: u32, + sequentialized: bool, +} + +#[derive(Deserialize)] +struct WireRecord { + step: u16, + value: JvmValue, +} + +#[derive(Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +enum WireTerminal { + Value { value: JvmValue }, + Void, + Threw { exception: JvmValue }, +} + +impl From for TraceCollected { + fn from(wire: WireCollected) -> Self { + Self { + records: wire.records.into_iter().map(|r| (r.step, r.value)).collect(), + dropped: wire.dropped, + terminal: match wire.terminal { + WireTerminal::Value { value } => CollectedTerminal::Value(value), + WireTerminal::Void => CollectedTerminal::Void, + WireTerminal::Threw { exception } => CollectedTerminal::Threw(exception), + }, + skipped_breakpoints: wire.skipped_breakpoints, + sequentialized: wire.sequentialized, + } + } +} + +impl StreamTracer for JdtStreamTracer { + fn arm<'a>( + &'a self, + target: &'a VmTarget, + thread_id: i64, + plan: &'a Value, + budget: u32, + ) -> InspectFuture<'a, TraceId> { + Box::pin(async move { + let args = json!({"threadId": thread_id, "plan": plan, "budget": budget}); + Ok(self.call::("arm", target, args, COMMAND_TIMEOUT).await?.trace_id) + }) + } + + fn wait<'a>(&'a self, target: &'a VmTarget, trace: TraceId, ms: u32) -> InspectFuture<'a, TraceState> { + Box::pin(async move { + let limit = Duration::from_millis(u64::from(ms)) + WAIT_SLACK; + let state: WireState = self.call("wait", target, json!({"traceId": trace, "ms": ms}), limit).await?; + Ok(state.into()) + }) + } + + fn stop<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, u64> { + Box::pin(async move { + Ok(self.call::("stop", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await?.records) + }) + } + + fn abort<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, AbortState> { + Box::pin(async move { + let state: WireAbort = self.call("abort", target, json!({"traceId": trace}), ABORT_TIMEOUT).await?; + Ok(state.into()) + }) + } + + fn collect<'a>(&'a self, target: &'a VmTarget, trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected> { + Box::pin(async move { + let limit = collect_timeout(records); + let collected: WireCollected = self.call("collect", target, json!({"traceId": trace}), limit).await?; + Ok(collected.into()) + }) + } + + fn release<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, ()> { + Box::pin(async move { + self.call::("release", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await.map(drop) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn collect_timeout_grows_with_the_records() { + assert_eq!(collect_timeout(0), Duration::from_secs(60)); + assert_eq!(collect_timeout(50_000), Duration::from_secs(60 + 250)); + assert!(collect_timeout(u64::MAX) >= collect_timeout(50_000)); + } +} diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index bb72e4c5c6..a1e2d327ff 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -44,6 +44,7 @@ mod vue_refs; pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES}; pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions}; pub use jdtls::jvm_inspect::JdtJvmInspector; +pub use jdtls::stream_trace::JdtStreamTracer; pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable}; pub use launch::{LaunchError, Launcher, ProcessLauncher}; pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri}; diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 1a78dcf2e0..6807cdc452 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3170,6 +3170,222 @@ async fn jvm_inspect_sends_one_command_at_a_time() { assert_eq!(most.load(Ordering::SeqCst), 1); } +async fn stream_harness() -> (Harness, Arc, ide_lsp::JdtStreamTracer) { + let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); + let (_, path) = h.open("Sample.java", "class Sample {}"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let tracer = ide_lsp::JdtStreamTracer::new(h.mgr.clone(), path); + let state = h.launcher.state("jdtls"); + (h, state, tracer) +} + +fn stream_launch_target() -> ide_jvm_inspect::VmTarget { + ide_jvm_inspect::VmTarget { pid: Some(42), attach_host: None, attach_port: None, generation: 3 } +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_commands_send_target_then_named_fields() { + use ide_jvm_inspect::StreamTracer; + let (_h, s, tracer) = stream_harness().await; + let target = stream_launch_target(); + let target_json = json!({"pid": 42, "host": null, "port": null, "generation": 3}); + 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); + s.respond( + "workspace/executeCommand", + json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}), + ); + tracer.wait(&target, 3, 250).await.unwrap(); + s.respond("workspace/executeCommand", json!({"ok": {"records": 9}})); + assert_eq!(tracer.stop(&target, 3).await.unwrap(), 9); + s.respond("workspace/executeCommand", json!({"ok": {"state": "stopped"}})); + tracer.abort(&target, 3).await.unwrap(); + s.respond( + "workspace/executeCommand", + json!({"ok": {"records": [], "dropped": 0, "terminal": {"kind": "void"}, "skippedBreakpoints": 0, + "sequentialized": false}}), + ); + tracer.collect(&target, 3, 2).await.unwrap(); + s.respond("workspace/executeCommand", json!({"ok": {}})); + tracer.release(&target, 3).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.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}])), + ] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_wait_decodes_states() { + use ide_jvm_inspect::{StreamTracer, TraceState}; + let (_h, s, tracer) = stream_harness().await; + let target = stream_launch_target(); + let cases = [ + ( + json!({"state": "running", "records": 10, "dropped": 0, "elapsedMs": 5}), + TraceState::Running { records: 10, dropped: 0, elapsed_ms: 5 }, + ), + ( + json!({"state": "parked", "records": 50000, "dropped": 950000, "elapsedMs": 96}), + TraceState::Parked { records: 50000, dropped: 950000 }, + ), + ( + json!({"state": "failed", "records": 4, "dropped": 0, "elapsedMs": 12, "detail": "missed map"}), + TraceState::Failed { detail: "missed map".into() }, + ), + ( + json!({"state": "cancelled", "records": 0, "dropped": 0, "elapsedMs": 12, + "detail": "cancelled before the terminal ran"}), + TraceState::Cancelled { detail: "cancelled before the terminal ran".into() }, + ), + ]; + for (ok, expected) in cases { + s.respond("workspace/executeCommand", json!({"ok": ok})); + assert_eq!(tracer.wait(&target, 1, 10).await.unwrap(), expected, "{ok}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_abort_decodes_every_state() { + use ide_jvm_inspect::{AbortState, StreamTracer}; + let (_h, s, tracer) = stream_harness().await; + let target = stream_launch_target(); + let cases = [ + (json!({"state": "interrupted"}), AbortState::Interrupted), + (json!({"state": "stopped"}), AbortState::Stopped), + ( + json!({"state": "stuck", "holders": [{"threadId": 42, "name": "worker-1"}]}), + AbortState::Stuck { holders: vec![(42, "worker-1".into())] }, + ), + (json!({"state": "cancelled"}), AbortState::Cancelled), + (json!({"state": "finished"}), AbortState::Finished), + ]; + for (ok, expected) in cases { + s.respond("workspace/executeCommand", json!({"ok": ok})); + assert_eq!(tracer.abort(&target, 1).await.unwrap(), expected, "{ok}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_errors_map() { + use ide_jvm_inspect::{InspectError, StreamTracer}; + let (_h, s, tracer) = stream_harness().await; + let target = stream_launch_target(); + let cases = [ + ( + json!({"error": "notAtChainStart", "detail": "line 14 is not where the statement starts"}), + InspectError::NotAtChainStart("line 14 is not where the statement starts".into()), + ), + (json!({"error": "busy", "detail": "trace 2 is running"}), InspectError::Busy), + (json!({"error": "noTrace", "detail": "no trace 9 on this VM"}), InspectError::NoTrace), + (json!({"error": "noSession", "detail": "x"}), InspectError::NoSession), + (json!({"error": "stale", "detail": "no thread 77"}), InspectError::Stale), + (json!({"error": "notSuspended", "detail": "thread 1 is running"}), InspectError::NotSuspended), + (json!({"error": "unsupported", "detail": "xs is a List"}), InspectError::Unsupported("xs is a List".into())), + ( + json!({"error": "badArgument", "detail": "budget must be 1 or more"}), + InspectError::Failed("budget must be 1 or more".into()), + ), + (json!({"error": "failed", "detail": "missed filter"}), InspectError::Failed("missed filter".into())), + (json!({"error": "surprise", "detail": "d"}), InspectError::Failed("surprise: d".into())), + ]; + for (reply, expected) in cases { + s.respond("workspace/executeCommand", reply.clone()); + assert_eq!(tracer.arm(&target, 1, &json!({}), 10).await.unwrap_err(), expected, "{reply}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_missing_bundle_is_unsupported() { + use ide_jvm_inspect::{InspectError, StreamTracer}; + let (_h, s, tracer) = stream_harness().await; + s.errors.lock().insert( + "workspace/executeCommand".into(), + (-32603, "No delegateCommandHandler for openidea.jvm.stream.wait".into()), + ); + assert_eq!( + tracer.wait(&stream_launch_target(), 1, 10).await.unwrap_err(), + InspectError::Unsupported("the JVM inspector bundle is not loaded".into()) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_collect_decodes() { + use ide_jvm_inspect::{CollectedTerminal, JvmValue, StreamTracer}; + let (_h, s, tracer) = stream_harness().await; + let target = stream_launch_target(); + s.respond( + "workspace/executeCommand", + json!({"ok": { + "records": [ + {"step": 0, "value": {"kind": "boxed", "id": 1, "typeName": "java.lang.Integer", "text": "5"}}, + {"step": 1, "value": {"kind": "string", "id": 2, "text": "5", "length": 1}}, + ], + "dropped": 4, + "terminal": {"kind": "threw", + "exception": {"kind": "object", "id": 9, "typeName": "java.lang.ArithmeticException"}}, + "skippedBreakpoints": 1, + "sequentialized": true, + }}), + ); + let collected = tracer.collect(&target, 3, 2).await.unwrap(); + assert_eq!( + collected.records, + vec![ + (0, JvmValue::Boxed { id: 1, type_name: "java.lang.Integer".into(), text: "5".into() }), + (1, JvmValue::Str { id: 2, text: Some("5".into()), length: 1 }), + ] + ); + assert_eq!(collected.dropped, 4); + assert_eq!( + collected.terminal, + CollectedTerminal::Threw(JvmValue::Object { id: 9, type_name: "java.lang.ArithmeticException".into() }) + ); + assert_eq!(collected.skipped_breakpoints, 1); + assert!(collected.sequentialized); + + s.respond( + "workspace/executeCommand", + json!({"ok": {"records": [], "dropped": 0, + "terminal": {"kind": "value", "value": {"kind": "object", "id": 19, "typeName": "java.util.ArrayList"}}, + "skippedBreakpoints": 0, "sequentialized": false}}), + ); + assert_eq!( + tracer.collect(&target, 3, 2).await.unwrap().terminal, + CollectedTerminal::Value(JvmValue::Object { id: 19, type_name: "java.util.ArrayList".into() }) + ); + s.respond( + "workspace/executeCommand", + json!({"ok": {"records": [], "dropped": 0, "terminal": {"kind": "void"}, + "skippedBreakpoints": 0, "sequentialized": false}}), + ); + assert_eq!(tracer.collect(&target, 3, 2).await.unwrap().terminal, CollectedTerminal::Void); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stream_collect_fails_cleanly_on_a_step_beyond_u16() { + use ide_jvm_inspect::{InspectError, StreamTracer}; + let (_h, s, tracer) = stream_harness().await; + s.respond( + "workspace/executeCommand", + json!({"ok": {"records": [{"step": 70000, "value": {"kind": "null"}}], "dropped": 0, + "terminal": {"kind": "void"}, "skippedBreakpoints": 0, "sequentialized": false}}), + ); + let error = tracer.collect(&stream_launch_target(), 3, 2).await.unwrap_err(); + assert!(matches!(error, InspectError::Failed(ref m) if m.contains("malformed")), "{error:?}"); +} + #[tokio::test(flavor = "multi_thread")] async fn debug_server_port_maps_to_module() { let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 84f1a6f129..a06cdd0870 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1598,7 +1598,7 @@ pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "jvm-inspect", - "1.0.0", + "1.1.0", include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"), ) } @@ -1694,7 +1694,7 @@ mod usages_bundle_tests { std::fs::write(dir.path().join(name), b"old").unwrap(); } let jar = super::jvm_inspect_bundle(dir.path()).unwrap(); - assert_eq!(jar, dir.path().join("jvm-inspect-1.0.0.jar")); + assert_eq!(jar, dir.path().join("jvm-inspect-1.1.0.jar")); assert_eq!(std::fs::read(&jar).unwrap(), include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar")); assert!(!dir.path().join("jvm-inspect-0.9.0.jar").exists()); assert_eq!(std::fs::read(dir.path().join("java-usages-1.7.0.jar")).unwrap(), b"old"); diff --git a/crates/ide-streams/Cargo.toml b/crates/ide-streams/Cargo.toml new file mode 100644 index 0000000000..f80c871675 --- /dev/null +++ b/crates/ide-streams/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ide-streams" +description = "Java Stream Debugger engine: finds stream chains and links the recorded elements" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +ide-core.workspace = true +ide-syntax.workspace = true +serde.workspace = true +specta.workspace = true +tree-sitter.workspace = true + +[dev-dependencies] +ide-language.workspace = true +serde_json.workspace = true diff --git a/crates/ide-streams/src/catalog.rs b/crates/ide-streams/src/catalog.rs new file mode 100644 index 0000000000..7717440346 --- /dev/null +++ b/crates/ide-streams/src/catalog.rs @@ -0,0 +1,188 @@ +use crate::StepKind; +use serde::{Deserialize, Serialize}; +use specta::Type; + +/// What a method name means when it appears in a stream chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum OpRole { + /// Intermediate operation whose elements are recorded. + Step { link: StepKind }, + /// Intermediate operation that changes no elements (execution-mode flags). + Modifier, + /// Ends the chain; `void` terminals produce no result value. + Terminal { void: bool }, + /// Terminal that hands out a lazy handle, so nothing runs inside the chain. + LazyTerminal, +} + +pub(crate) fn op_role(name: &str) -> Option { + use OpRole::*; + Some(match name { + "filter" | "map" | "mapToInt" | "mapToLong" | "mapToDouble" | "mapToObj" | "flatMap" | "flatMapToInt" + | "flatMapToLong" | "flatMapToDouble" | "flatMapToObj" | "mapMulti" | "mapMultiToInt" | "mapMultiToLong" + | "mapMultiToDouble" | "mapMultiToObj" | "boxed" | "asLongStream" | "asDoubleStream" | "peek" | "distinct" + | "skip" | "limit" | "takeWhile" | "dropWhile" => Step { link: StepKind::Sync }, + "sorted" => Step { link: StepKind::Reorder }, + "gather" => Step { link: StepKind::Unlinked }, + "parallel" | "sequential" | "unordered" | "onClose" => Modifier, + "collect" | "toList" | "reduce" | "count" | "sum" | "average" | "min" | "max" | "summaryStatistics" + | "anyMatch" | "allMatch" | "noneMatch" | "findFirst" | "findAny" | "toArray" => Terminal { void: false }, + "forEach" | "forEachOrdered" => Terminal { void: true }, + "iterator" | "spliterator" => LazyTerminal, + _ => return None, + }) +} + +/// `None` for names that are not intermediate steps (modifiers, terminals, unknown calls). +pub fn step_kind(op: &str) -> Option { + match op_role(op)? { + OpRole::Step { link } => Some(link), + _ => None, + } +} + +/// The class declaring a stream-producing method, which decides what the +/// debugger must watch to catch the stream when it is created. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SourceFamily { + /// Factories in `java.util.stream`, already covered by the stream filter. + StreamPackage, + /// `Collection.stream()`, `Random.ints()`, `Scanner.tokens()`. + Util, + Arrays, + /// `chars()` / `codePoints()`: `String`, `StringBuilder` and the `CharSequence` default methods. + Chars, + /// `lines()`: `String` and `BufferedReader`; the receiver's type is not known here. + Lines, + Files, + Pattern, +} + +impl SourceFamily { + /// Class filters beyond `java.util.stream.*` that see the source call exit: + /// every class that can declare the method. + pub fn class_filters(self) -> &'static [&'static str] { + match self { + Self::StreamPackage => &[], + Self::Util => &["java.util.*"], + Self::Arrays => &["java.util.Arrays"], + Self::Chars => &["java.lang.String", "java.lang.AbstractStringBuilder", "java.lang.CharSequence"], + Self::Lines => &["java.lang.String", "java.io.BufferedReader"], + Self::Files => &["java.nio.file.Files"], + Self::Pattern => &["java.util.regex.Pattern"], + } + } +} + +const STREAM: &[&str] = &["of", "ofNullable", "iterate", "concat", "empty", "generate"]; +const PRIMITIVE_RANGE: &[&str] = &["range", "rangeClosed", "of", "iterate", "concat", "empty", "generate"]; +const DOUBLE_STREAM: &[&str] = &["of", "iterate", "concat", "empty", "generate"]; +const STREAM_SUPPORT: &[&str] = &["stream", "intStream", "longStream", "doubleStream"]; + +use SourceFamily::{Arrays, Files, StreamPackage}; + +const STATIC_SOURCES: &[(&str, SourceFamily, &[&str])] = &[ + ("Stream", StreamPackage, STREAM), + ("IntStream", StreamPackage, PRIMITIVE_RANGE), + ("LongStream", StreamPackage, PRIMITIVE_RANGE), + ("DoubleStream", StreamPackage, DOUBLE_STREAM), + ("Arrays", Arrays, &["stream"]), + ("StreamSupport", StreamPackage, STREAM_SUPPORT), + ("Files", Files, &["lines", "list", "walk", "find"]), +]; + +fn names_class(receiver: &str, class: &str) -> bool { + receiver.strip_suffix(class).is_some_and(|rest| rest.is_empty() || rest.ends_with('.')) +} + +/// The parameter count the JVM sees, which differs from the written arguments +/// for the varargs `of` of the stream interfaces: it takes one array. +pub(crate) fn jvm_arg_count(receiver: Option<&str>, method: &str, written: usize) -> usize { + let stream_interface = + |r: &str| ["Stream", "IntStream", "LongStream", "DoubleStream"].iter().any(|c| names_class(r, c)); + if method == "of" && receiver.is_some_and(stream_interface) { 1 } else { written } +} + +/// `None` means `method` does not start a stream here. A receiver naming one +/// of the known factory classes only matches that class's own factories. +pub(crate) fn classify_source(receiver: Option<&str>, method: &str) -> Option { + let receiver = receiver?; + if let Some((_, family, methods)) = STATIC_SOURCES.iter().find(|(class, ..)| names_class(receiver, class)) { + return methods.contains(&method).then_some(*family); + } + match method { + "stream" | "parallelStream" | "tokens" | "ints" | "longs" | "doubles" => Some(SourceFamily::Util), + "chars" | "codePoints" => Some(SourceFamily::Chars), + "splitAsStream" => Some(SourceFamily::Pattern), + "lines" => Some(SourceFamily::Lines), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn op_roles() { + assert_eq!(op_role("filter"), Some(OpRole::Step { link: StepKind::Sync })); + assert_eq!(op_role("sorted"), Some(OpRole::Step { link: StepKind::Reorder })); + assert_eq!(op_role("gather"), Some(OpRole::Step { link: StepKind::Unlinked })); + assert_eq!(op_role("parallel"), Some(OpRole::Modifier)); + assert_eq!(op_role("forEach"), Some(OpRole::Terminal { void: true })); + assert_eq!(op_role("collect"), Some(OpRole::Terminal { void: false })); + assert_eq!(op_role("iterator"), Some(OpRole::LazyTerminal)); + assert_eq!(op_role("orElse"), None); + } + + #[test] + fn step_kinds() { + assert_eq!(step_kind("mapMulti"), Some(StepKind::Sync)); + assert_eq!(step_kind("sorted"), Some(StepKind::Reorder)); + assert_eq!(step_kind("parallel"), None); + assert_eq!(step_kind("collect"), None); + } + + #[test] + fn sources() { + use SourceFamily::*; + let family = |receiver, method| classify_source(Some(receiver), method); + assert_eq!(family("nums", "stream"), Some(Util)); + assert_eq!(family("myStream", "stream"), Some(Util)); + assert_eq!(family("rnd", "ints"), Some(Util)); + assert_eq!(family("java.util.stream.Stream", "generate"), Some(StreamPackage)); + assert_eq!(family("IntStream", "range"), Some(StreamPackage)); + assert_eq!(family("Arrays", "stream"), Some(Arrays)); + assert_eq!(family("Files", "walk"), Some(Files)); + assert_eq!(family("reader", "lines"), Some(Lines)); + assert_eq!(family("\"a\\nb\"", "lines"), Some(Lines)); + assert_eq!(family("text", "chars"), Some(Chars)); + assert_eq!(family("pattern", "splitAsStream"), Some(Pattern)); + assert_eq!(classify_source(None, "stream"), None); + assert_eq!(family("repo", "findAll"), None); + assert_eq!(family("Stream", "builder"), None); + assert_eq!(family("Files", "readAllLines"), None); + } + + #[test] + fn class_filters() { + assert!(SourceFamily::StreamPackage.class_filters().is_empty()); + assert_eq!(SourceFamily::Util.class_filters(), ["java.util.*"]); + assert_eq!(SourceFamily::Lines.class_filters(), ["java.lang.String", "java.io.BufferedReader"]); + assert_eq!( + SourceFamily::Chars.class_filters(), + ["java.lang.String", "java.lang.AbstractStringBuilder", "java.lang.CharSequence"] + ); + } + + #[test] + fn varargs_of_takes_one_parameter() { + assert_eq!(jvm_arg_count(Some("Stream"), "of", 3), 1); + assert_eq!(jvm_arg_count(Some("java.util.stream.IntStream"), "of", 2), 1); + assert_eq!(jvm_arg_count(Some("List"), "of", 3), 3); + assert_eq!(jvm_arg_count(Some("Stream"), "iterate", 2), 2); + assert_eq!(jvm_arg_count(None, "of", 2), 2); + } +} diff --git a/crates/ide-streams/src/chain/frame.rs b/crates/ide-streams/src/chain/frame.rs new file mode 100644 index 0000000000..00674e94b1 --- /dev/null +++ b/crates/ide-streams/src/chain/frame.rs @@ -0,0 +1,94 @@ +use super::search::{Finder, TYPE_BODIES, TYPE_DECLARATIONS}; +use super::{FrameKind, FrameShape}; +use tree_sitter::Node; + +impl Finder<'_, '_> { + /// Frame shape from the scope outwards; `Err` for frames a lambda cannot + /// be compiled into. + pub(super) fn frame(&self, scope: Node) -> Result { + let mut shape = FrameShape::default(); + let mut past_method = false; + // A static member or static nested type cannot see the type + // parameters of the types around it. + let mut sees_outer_params = true; + let mut cur = Some(scope); + while let Some(n) = cur { + let kind = n.kind(); + if matches!(kind, "method_declaration" | "constructor_declaration") && !past_method { + self.push_type_params(n, &mut shape.type_params); + past_method = true; + sees_outer_params = !self.is_static(n); + } else if matches!(kind, "field_declaration" | "constant_declaration" | "static_initializer") + && !past_method + { + past_method = true; + sees_outer_params = kind == "field_declaration" && !self.is_static(n); + } else if kind == "class_body" + && n.parent().is_some_and(|p| matches!(p.kind(), "object_creation_expression" | "enum_constant")) + { + return Err(FrameKind::Anonymous); + } else if TYPE_DECLARATIONS.contains(&kind) { + let parent = n.parent().map_or("program", |p| p.kind()); + let name = n.child_by_field_name("name").map_or("", |c| self.text(c)); + if parent != "program" && !TYPE_BODIES.contains(&parent) { + return Err(FrameKind::Local); + } + if parent == "program" && name != self.file_stem { + return Err(FrameKind::SecondaryTopLevel); + } + if shape.class_path.is_empty() { + shape.record = kind == "record_declaration"; + } + shape.class_path.push(name.into()); + if sees_outer_params { + self.push_type_params(n, &mut shape.type_params); + } + // Nested records, enums and interfaces, and types nested in an interface, are implicitly static. + sees_outer_params &= kind == "class_declaration" && parent != "interface_body" && !self.is_static(n); + past_method = true; + } else if kind == "program" { + let mut cursor = n.walk(); + shape.package = + n.named_children(&mut cursor).find(|c| c.kind() == "package_declaration").and_then(|p| { + let mut cursor = p.walk(); + let name = p + .named_children(&mut cursor) + .find(|c| matches!(c.kind(), "scoped_identifier" | "identifier")); + name.map(|c| self.text(c).to_string()) + }); + } + cur = n.parent(); + } + shape.class_path.reverse(); + Ok(shape) + } + + fn push_type_params(&self, decl: Node, out: &mut Vec<(String, Option)>) { + let Some(params) = decl.child_by_field_name("type_parameters") else { return }; + let mut cursor = params.walk(); + for param in params.named_children(&mut cursor).filter(|p| p.kind() == "type_parameter") { + let mut cursor = param.walk(); + let mut children = param.named_children(&mut cursor); + let Some(name) = children.find(|c| c.kind() == "type_identifier") else { continue }; + let bound = children.find(|c| c.kind() == "type_bound").and_then(|b| { + let mut cursor = b.walk(); + let first = + b.named_children(&mut cursor).find(|c| c.kind() != "annotation" && c.kind() != "marker_annotation"); + first.map(|ty| self.erasure(ty)) + }); + out.push((self.text(name).into(), bound)); + } + } + + fn is_static(&self, decl: Node) -> bool { + let mut cursor = decl.walk(); + let Some(mods) = decl.children(&mut cursor).find(|c| c.kind() == "modifiers") else { return false }; + let mut cursor = mods.walk(); + mods.children(&mut cursor).any(|c| self.text(c) == "static") + } + + fn erasure(&self, ty: Node) -> String { + let raw = if ty.kind() == "generic_type" { ty.named_child(0).unwrap_or(ty) } else { ty }; + self.text(raw).into() + } +} diff --git a/crates/ide-streams/src/chain/locals.rs b/crates/ide-streams/src/chain/locals.rs new file mode 100644 index 0000000000..98a1d5ab2d --- /dev/null +++ b/crates/ide-streams/src/chain/locals.rs @@ -0,0 +1,66 @@ +use ide_syntax::SyntaxTree; +use tree_sitter::Node; + +/// Whether `name`, used at `from`, is a local variable or parameter, looking no +/// further out than `member`: declarations before `from` in each enclosing +/// block, then loop, catch, resource and lambda / method parameters. +pub(crate) fn is_visible_local<'t>(t: &SyntaxTree<'t>, from: Node<'t>, member: Node<'t>, name: &str) -> bool { + let named = |n: Node| t.text[n.byte_range()] == *name; + let mut child = from; + while let Some(p) = child.parent() { + let mut cursor = p.walk(); + let found = match p.kind() { + "block" | "switch_block_statement_group" | "resource_specification" => p + .named_children(&mut cursor) + .take_while(|c| c.end_byte() <= child.start_byte()) + .any(|c| declares(c, named) || is_resource(c, named)), + "for_statement" => p.child_by_field_name("init").is_some_and(|init| declares(init, named)), + "enhanced_for_statement" if p.child_by_field_name("body") == Some(child) => { + p.child_by_field_name("name").is_some_and(named) + } + "try_with_resources_statement" if p.child_by_field_name("body") == Some(child) => { + p.child_by_field_name("resources").is_some_and(|resources| { + let mut cursor = resources.walk(); + resources.named_children(&mut cursor).any(|r| is_resource(r, named)) + }) + } + "catch_clause" => p + .named_children(&mut cursor) + .find(|c| c.kind() == "catch_formal_parameter") + .and_then(|c| c.child_by_field_name("name")) + .is_some_and(named), + "method_declaration" | "constructor_declaration" | "lambda_expression" => has_parameter(p, named), + _ => false, + }; + if found || p == member { + return found; + } + child = p; + } + false +} + +fn is_resource(r: Node, named: impl Fn(Node) -> bool) -> bool { + r.kind() == "resource" && r.child_by_field_name("name").is_some_and(named) +} + +fn declares(decl: Node, named: impl Fn(Node) -> bool) -> bool { + if decl.kind() != "local_variable_declaration" { + return false; + } + let mut cursor = decl.walk(); + decl.children_by_field_name("declarator", &mut cursor).any(|d| d.child_by_field_name("name").is_some_and(&named)) +} + +fn has_parameter(decl: Node, named: impl Fn(Node) -> bool) -> bool { + let Some(params) = decl.child_by_field_name("parameters") else { return false }; + if params.kind() == "identifier" { + return named(params); + } + let mut cursor = params.walk(); + params.named_children(&mut cursor).any(|p| match p.kind() { + "identifier" => named(p), + "formal_parameter" => p.child_by_field_name("name").is_some_and(&named), + _ => false, + }) +} diff --git a/crates/ide-streams/src/chain/mod.rs b/crates/ide-streams/src/chain/mod.rs new file mode 100644 index 0000000000..c95e5eaac2 --- /dev/null +++ b/crates/ide-streams/src/chain/mod.rs @@ -0,0 +1,165 @@ +mod frame; +mod locals; +mod search; +mod warnings; + +use crate::{OpRole, SourceFamily}; +use ide_core::{CancellationToken, Range}; +use ide_syntax::{Snapshot, StructureResult, StructureService}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +/// Where the debuggee stopped. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StopContext<'a> { + pub line: u32, + /// The DAP frame is a lambda body (`lambda$…`); the line alone cannot tell. + pub in_lambda: bool, + /// File name without extension: the top-level class the file is named after. + pub file_stem: &'a str, +} + +/// Chains around the stopped line; both lists in source order. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ChainSearch { + pub chains: Vec, + pub rejected: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RejectedChain { + pub range: Range, + pub text: String, + pub reason: Rejection, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StreamChain { + pub range: Range, + pub text: String, + pub root: ChainRoot, + pub root_kind: RootKind, + /// 0-based line of the first token of the statement holding the chain. + pub first_line: u32, + /// Intermediate operations in call order. + pub ops: Vec, + pub terminal: ChainOp, + pub frame: FrameShape, + pub warnings: Vec, +} + +/// What the chain's first expression is. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum RootKind { + /// A call that creates a new stream ([`ChainRoot::call`] is set). + Call, + /// A local variable or parameter holding a stream. + Local { name: String }, + /// A field or the result of another method. + Other, +} + +/// The expression the chain's operations are applied to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ChainRoot { + pub text: String, + /// Byte range in [`StreamChain::text`]. + pub span: (usize, usize), + /// Set when [`StreamChain::root_kind`] is `Call`. + pub call: Option, +} + +/// The call that creates the stream. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RootCall { + pub name: String, + /// Parameter count the JVM sees: always 1 for the stream interfaces' varargs `of`. + pub args: u8, + /// Calls with the same name and parameter count that return earlier in the + /// statement, which the root must not be mistaken for. Calls inside lambda + /// and class bodies do not count: they only run with the terminal. + pub skip: u8, + pub family: SourceFamily, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ChainOp { + pub name: String, + pub role: OpRole, + /// Byte range in [`StreamChain::text`], from the `.` to the call's `)`. + pub span: (usize, usize), + pub args: u8, +} + +/// The class context the chain's frame runs in. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct FrameShape { + /// Set when the frame is of a kind a lambda cannot be compiled into; the chain is still reported. + /// The other fields are unset then. + pub kind: Option, + /// The innermost enclosing type is a record. + pub record: bool, + /// Enclosing type names, outermost first. + pub class_path: Vec, + /// Type parameters in scope with the erasure of their first bound: the + /// method's, then each enclosing type's from the inside out, stopping at + /// the first static member or static nested type. + pub type_params: Vec<(String, Option)>, + pub package: Option, +} + +/// Frames whose class cannot host a compiled lambda. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum FrameKind { + Anonymous, + Local, + /// A top-level type not named after the file. + SecondaryTopLevel, +} + +/// Tracing still works, but its result may differ from the program's own run. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum ChainWarning { + /// The chain is parallel; the trace adds `.sequential()`. + Sequentialized, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum Rejection { + LazyTerminal { + op: String, + }, + /// A new stream with operations but no terminal, so nothing would run. + NoTerminal, + UnknownOperation { + op: String, + }, + /// Stopped inside a lambda of a chain: the chain is already running. + InsideChainLambda, + SyntaxError, +} + +/// Calls that only share a terminal's name (`Collectors.toList()`, the +/// `forEach` in `s.toList().forEach(..)`) appear in neither list. +pub fn find_chains( + service: &StructureService, + snap: &Snapshot, + stop: &StopContext, + cancel: &CancellationToken, +) -> StructureResult { + service.with_tree(snap, cancel, |t| { + search::Finder { t, line: stop.line as usize, file_stem: stop.file_stem }.run(stop) + }) +} diff --git a/crates/ide-streams/src/chain/search.rs b/crates/ide-streams/src/chain/search.rs new file mode 100644 index 0000000000..54706d75dc --- /dev/null +++ b/crates/ide-streams/src/chain/search.rs @@ -0,0 +1,418 @@ +use super::locals::is_visible_local; +use super::{ + ChainOp, ChainRoot, ChainSearch, FrameShape, RejectedChain, Rejection, RootCall, RootKind, StopContext, StreamChain, +}; +use crate::OpRole; +use crate::catalog::{SourceFamily, classify_source, jvm_arg_count, op_role}; +use ide_syntax::SyntaxTree; +use tree_sitter::Node; + +const METHOD_SCOPES: &[&str] = &[ + "method_declaration", + "constructor_declaration", + "compact_constructor_declaration", + "static_initializer", + // Field initialisers run in `` / ``. + "field_declaration", + "constant_declaration", +]; +pub(crate) const TYPE_BODIES: &[&str] = + &["class_body", "interface_body", "enum_body", "enum_body_declarations", "annotation_type_body"]; +pub(crate) const TYPE_DECLARATIONS: &[&str] = &[ + "class_declaration", + "record_declaration", + "enum_declaration", + "interface_declaration", + "annotation_type_declaration", +]; +const SIMPLE_STATEMENTS: &[&str] = &[ + "expression_statement", + "local_variable_declaration", + "return_statement", + "throw_statement", + "yield_statement", + "assert_statement", + "explicit_constructor_invocation", +]; + +fn is_method_scope(n: Node) -> bool { + // A bare block in a type body is an instance initializer. + METHOD_SCOPES.contains(&n.kind()) + || (n.kind() == "block" && n.parent().is_some_and(|p| TYPE_BODIES.contains(&p.kind()))) +} + +fn is_scope(n: Node) -> bool { + n.kind() == "lambda_expression" || is_method_scope(n) +} + +fn is_intermediate(name: &str) -> bool { + matches!(op_role(name), Some(OpRole::Step { .. } | OpRole::Modifier)) +} + +fn saturate(n: usize) -> u8 { + u8::try_from(n).unwrap_or(u8::MAX) +} + +pub(super) fn object_of<'t>(call: Node<'t>) -> Option> { + call.child_by_field_name("object") +} + +/// The call whose `object` is `n`. +fn called_on<'t>(n: Node<'t>) -> Option> { + n.parent().filter(|p| p.kind() == "method_invocation" && object_of(*p) == Some(n)) +} + +/// The pieces of a chain that passed the structural checks. +struct Parts<'t> { + terminal: Node<'t>, + root: Node<'t>, + /// Set when `root` is a call that creates a new stream. + family: Option, + ops: Vec>, +} + +/// Calls met walking `object` links down to a stream's source. +struct Descent<'t> { + /// Calls above the source, nearest to the start first. + above: Vec>, + source: Option<(Node<'t>, SourceFamily)>, +} + +pub(super) struct Finder<'a, 't> { + pub(super) t: &'a SyntaxTree<'t>, + pub(super) line: usize, + pub(super) file_stem: &'a str, +} + +impl<'t> Finder<'_, 't> { + pub(super) fn text(&self, n: Node) -> &'t str { + &self.t.text[n.byte_range()] + } + + pub(super) fn name(&self, call: Node) -> &'t str { + call.child_by_field_name("name").map_or("", |n| self.text(n)) + } + + fn covers(&self, n: Node) -> bool { + n.start_position().row <= self.line && self.line <= n.end_position().row + } + + fn is_terminal(&self, call: Node) -> bool { + matches!(op_role(self.name(call)), Some(OpRole::Terminal { .. } | OpRole::LazyTerminal)) + } + + pub(super) fn run(&self, stop: &StopContext) -> ChainSearch { + let mut search = ChainSearch::default(); + let scopes = self.frame_scopes(stop.in_lambda); + let mut scopes_with_chains = Vec::new(); + for &scope in &scopes { + let mut calls = Vec::new(); + collect_calls(scope, &mut calls); + let mut any = false; + for call in calls.into_iter().filter(|&c| self.covers(self.anchor(c, scope))) { + any |= self.judge(call, scope, &mut search); + } + if any { + scopes_with_chains.push(scope); + } + } + if stop.in_lambda { + for &lambda in scopes.iter().filter(|s| !scopes_with_chains.contains(s)) { + let Some(outer) = self.enclosing_chain(lambda) else { continue }; + let range = self.t.range(&outer); + if search.chains.iter().any(|c| c.range == range) || search.rejected.iter().any(|r| r.range == range) { + continue; + } + let text = self.text(outer).to_string(); + search.rejected.push(RejectedChain { range, text, reason: Rejection::InsideChainLambda }); + } + } + search.chains.sort_by_key(|c| c.range); + search.rejected.sort_by_key(|r| r.range); + search + } + + /// The innermost method-like scope around the line, or, for a lambda + /// frame, every lambda inside it whose body covers the line: the frame + /// name does not say which of several nested lambdas it is. + fn frame_scopes(&self, in_lambda: bool) -> Vec> { + let mut covering = Vec::new(); + self.collect_covering(self.t.tree.root_node(), &mut covering); + // Nested scopes start later than the ones around them. + let method = covering.iter().copied().filter(|n| is_method_scope(*n)).max_by_key(|n| n.start_byte()); + if !in_lambda { + return method.into_iter().collect(); + } + let inside_method = + |n: &Node| method.is_none_or(|m| m.start_byte() <= n.start_byte() && n.end_byte() <= m.end_byte()); + let lambda_frame = + |n: &Node| n.kind() == "lambda_expression" && n.child_by_field_name("body").is_some_and(|b| self.covers(b)); + covering.into_iter().filter(|n| lambda_frame(n) && inside_method(n)).collect() + } + + fn collect_covering(&self, node: Node<'t>, out: &mut Vec>) { + let mut cursor = node.walk(); + for child in node.children(&mut cursor).filter(|c| self.covers(*c)) { + out.push(child); + self.collect_covering(child, out); + } + } + + /// The first terminal-named call at or above `call` along `object` links. + fn nearest_terminal(&self, call: Node<'t>) -> Option> { + let mut cur = Some(call); + while let Some(c) = cur { + if self.is_terminal(c) { + return Some(c); + } + cur = called_on(c); + } + None + } + + /// The statement the line must fall in: the simple statement holding the + /// call, an expression lambda's body, a field declaration, or the call + /// itself when it sits in a compound statement's header (`if (s.anyMatch(..)) {`). + fn anchor(&self, call: Node<'t>, scope: Node<'t>) -> Node<'t> { + let mut cur = call; + while let Some(p) = cur.parent() { + if p == scope { + return match scope.kind() { + "lambda_expression" => scope.child_by_field_name("body").unwrap_or(call), + "field_declaration" | "constant_declaration" => scope, + _ => call, + }; + } + if SIMPLE_STATEMENTS.contains(&p.kind()) { + return p; + } + if p.kind().ends_with("_statement") { + return call; + } + cur = p; + } + call + } + + /// Records the verdict on one call around the line; `false` when it is no chain at all. + fn judge(&self, call: Node<'t>, scope: Node<'t>, search: &mut ChainSearch) -> bool { + let shape = if self.is_terminal(call) { + self.shape(call) + } else if self.is_unterminated(call) { + Some(Err(Rejection::NoTerminal)) + } else { + None + }; + let Some(shape) = shape else { return false }; + let reject = |reason| RejectedChain { range: self.t.range(&call), text: self.text(call).into(), reason }; + if self.anchor(call, scope).has_error() { + search.rejected.push(reject(Rejection::SyntaxError)); + return true; + } + match shape { + Err(reason) => search.rejected.push(reject(reason)), + Ok(parts) => { + let frame = + self.frame(scope).unwrap_or_else(|kind| FrameShape { kind: Some(kind), ..Default::default() }); + let statement = self.anchor(call, scope); + search.chains.push(self.chain(parts, frame, scope, statement)); + } + } + true + } + + /// Walks `object` links down from `from`. `None` when a terminal-named + /// call comes first: what is above it works on a collection, not a stream. + fn descend(&self, from: Option>) -> Option> { + let mut above = Vec::new(); + let mut cur = from; + while let Some(call) = cur.filter(|n| n.kind() == "method_invocation") { + if let Some(family) = self.source_family(call) { + return Some(Descent { above, source: Some((call, family)) }); + } + if self.is_terminal(call) { + return None; + } + above.push(call); + cur = object_of(call); + } + Some(Descent { above, source: None }) + } + + /// `None`: the call only shares a terminal's name (`Collectors.toList()`), + /// or works on what an earlier terminal returned (`s.toList().forEach(..)`). + fn shape(&self, terminal: Node<'t>) -> Option, Rejection>> { + let Descent { above, source } = self.descend(object_of(terminal))?; + let mut ops: Vec<_> = above.into_iter().rev().collect(); + let (root, family) = match source { + Some((root, family)) => (root, Some(family)), + // The stream was made elsewhere: the root is what the lowest operation is called on. + None => { + let lowest = ops.iter().position(|c| object_of(*c).is_some() && is_intermediate(self.name(*c)))?; + ops.drain(..lowest); + (object_of(ops[0])?, None) + } + }; + if let Some(op) = ops.iter().find(|c| !is_intermediate(self.name(**c))) { + return Some(Err(Rejection::UnknownOperation { op: self.name(*op).into() })); + } + if op_role(self.name(terminal)) == Some(OpRole::LazyTerminal) { + return Some(Err(Rejection::LazyTerminal { op: self.name(terminal).into() })); + } + Some(Ok(Parts { terminal, root, family, ops })) + } + + /// A new stream with intermediate operations but no terminal, standing + /// on its own (`var s = xs.stream().map(f);`); a stream passed as an + /// argument or returned from a lambda is someone else's to finish. + fn is_unterminated(&self, call: Node<'t>) -> bool { + let standalone = called_on(call).is_none() + && call.parent().is_some_and(|p| !matches!(p.kind(), "argument_list" | "lambda_expression")); + if !standalone || object_of(call).is_none() || !is_intermediate(self.name(call)) { + return false; + } + self.descend(Some(call)) + .is_some_and(|d| d.source.is_some() && d.above.iter().all(|c| is_intermediate(self.name(*c)))) + } + + fn source_family(&self, call: Node) -> Option { + classify_source(object_of(call).map(|r| self.text(r).trim()), self.name(call)) + } + + fn chain(&self, parts: Parts<'t>, frame: FrameShape, scope: Node<'t>, statement: Node<'t>) -> StreamChain { + let Parts { terminal, root, family, ops } = parts; + let start = terminal.start_byte(); + let op = |call: Node| { + let mut cursor = call.walk(); + let dot = + call.children(&mut cursor).find(|c| c.kind() == ".").map_or(call.start_byte(), |d| d.start_byte()); + let name = self.name(call); + let role = op_role(name).expect("checked by shape"); + let args = saturate(self.jvm_args(call)); + ChainOp { name: name.into(), role, span: (dot - start, call.end_byte() - start), args } + }; + let (root_kind, call) = match family { + Some(family) => { + let args = saturate(self.jvm_args(root)); + let skip: usize = self + .skip_regions(statement, scope) + .into_iter() + .map(|region| self.earlier_exits(region, root, family)) + .sum(); + let skip = saturate(skip); + (RootKind::Call, Some(RootCall { name: self.name(root).into(), args, skip, family })) + } + None => (self.value_root_kind(root, scope), None), + }; + StreamChain { + range: self.t.range(&terminal), + text: self.text(terminal).into(), + root: ChainRoot { + text: self.text(root).into(), + span: (root.start_byte() - start, root.end_byte() - start), + call, + }, + root_kind, + first_line: statement.start_position().row as u32, + ops: ops.iter().map(|c| op(*c)).collect(), + terminal: op(terminal), + warnings: self.warnings(root, &ops), + frame, + } + } + + /// Parameter count of the method the JVM runs for `call`. + fn jvm_args(&self, call: Node) -> usize { + let written = call.child_by_field_name("arguments").map_or(0, |a| { + let mut cursor = a.walk(); + a.named_children(&mut cursor).filter(|c| !c.kind().ends_with("comment")).count() + }); + jvm_arg_count(object_of(call).map(|r| self.text(r).trim()), self.name(call), written) + } + + /// 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. + 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" { + return vec![anchor]; + } + let mut region = std::iter::successors(anchor.parent(), |n| n.parent()) + .take_while(|n| *n != scope) + .find(|n| is_statement(*n)) + .unwrap_or(anchor); + 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")); + region = outer; + } + regions + } + + /// Calls in `region` that the debugger would take for `root`: same name, parameter + /// count and source family, returning before `root` does (in its receiver, its + /// arguments and earlier chains). Lambda and class bodies do not count, as they + /// run only once a terminal does. + fn earlier_exits(&self, region: Node, root: Node, family: SourceFamily) -> usize { + if matches!(region.kind(), "lambda_expression" | "class_body") { + return 0; + } + let mut cursor = region.walk(); + let inside: usize = region.children(&mut cursor).map(|c| self.earlier_exits(c, root, family)).sum(); + let same = region.kind() == "method_invocation" + && region.id() != root.id() + && region.end_byte() <= root.end_byte() + && self.name(region) == self.name(root) + && self.jvm_args(region) == self.jvm_args(root) + && self.source_family(region) == Some(family); + inside + usize::from(same) + } + + /// `Local` for a variable or parameter the member declares; anything else + /// (a field, `this.items`, another method's result) is `Other`. + fn value_root_kind(&self, root: Node<'t>, scope: Node<'t>) -> RootKind { + let name = self.text(root); + let member = std::iter::successors(Some(scope), |n| n.parent()).find(|n| is_method_scope(*n)).unwrap_or(scope); + if root.kind() == "identifier" && is_visible_local(self.t, root, member, name) { + RootKind::Local { name: name.into() } + } else { + RootKind::Other + } + } + + /// The chain a lambda frame runs inside of, when the lambda is an + /// argument somewhere in a chain's calls. + fn enclosing_chain(&self, lambda: Node<'t>) -> Option> { + let mut cur = lambda.parent(); + while let Some(n) = cur.filter(|n| !is_scope(*n) && !TYPE_BODIES.contains(&n.kind())) { + if n.kind() == "method_invocation" + && let Some(end) = self.nearest_terminal(n) + && self.shape(end).is_some() + { + return Some(end); + } + cur = n.parent(); + } + None + } +} + +/// Method invocations owned by `scope`, not by a nested lambda, method or type body. +fn collect_calls<'t>(scope: Node<'t>, out: &mut Vec>) { + let mut cursor = scope.walk(); + for child in scope.children(&mut cursor) { + if is_scope(child) || TYPE_BODIES.contains(&child.kind()) { + continue; + } + if child.kind() == "method_invocation" { + out.push(child); + } + collect_calls(child, out); + } +} diff --git a/crates/ide-streams/src/chain/warnings.rs b/crates/ide-streams/src/chain/warnings.rs new file mode 100644 index 0000000000..8dec2ed44a --- /dev/null +++ b/crates/ide-streams/src/chain/warnings.rs @@ -0,0 +1,10 @@ +use super::ChainWarning; +use super::search::Finder; +use tree_sitter::Node; + +impl Finder<'_, '_> { + pub(super) fn warnings(&self, root: Node, ops: &[Node]) -> Vec { + let parallel = self.name(root) == "parallelStream" || ops.iter().any(|op| self.name(*op) == "parallel"); + if parallel { vec![ChainWarning::Sequentialized] } else { Vec::new() } + } +} diff --git a/crates/ide-streams/src/lib.rs b/crates/ide-streams/src/lib.rs new file mode 100644 index 0000000000..f36afb4efd --- /dev/null +++ b/crates/ide-streams/src/lib.rs @@ -0,0 +1,13 @@ +//! Java Stream Debugger engine. Pure computation: no IO, no debugger transport. + +mod catalog; +mod chain; +mod model; +mod real_run; +mod resolve; + +pub use catalog::{OpRole, SourceFamily, step_kind}; +pub use chain::*; +pub use model::*; +pub use real_run::*; +pub use resolve::{distinct_drops, resolve, sorted_pass_through}; diff --git a/crates/ide-streams/src/model.rs b/crates/ide-streams/src/model.rs new file mode 100644 index 0000000000..006318bc9f --- /dev/null +++ b/crates/ide-streams/src/model.rs @@ -0,0 +1,86 @@ +use serde::{Deserialize, Serialize}; +use specta::Type; + +/// Wrapper class of a boxed primitive; serialises as the primitive name. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)] +#[serde(rename_all = "lowercase")] +pub enum BoxKind { + Boolean, + Byte, + Char, + Short, + Int, + Long, + Float, + Double, +} + +/// An element as the debuggee reported it. `id` is the JDI unique object id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TraceValue { + Null, + Object { + id: u64, + /// Binary class name. + class: String, + }, + Boxed { + id: u64, + class: BoxKind, + /// The primitive's textual form. + value: String, + }, + Str { + id: u64, + value: String, + truncated: bool, + }, +} + +/// One recorded element. Time order is the position in the owning `Vec`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Record { + pub step: u16, + pub value: TraceValue, +} + +/// How a step's output elements relate to its input elements. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum StepKind { + /// Output order follows input order, so elements can be linked by position. + Sync, + /// Output is reordered; elements are linked by identity. + Reorder, + /// No usable relation between input and output. + Unlinked, +} + +/// Link from an output element to the input element it came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Link { + pub parent: Option, + pub ambiguous: bool, +} + +/// An element `distinct` discarded, with the kept element equal to it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DistinctDrop { + pub dropped: u32, + pub same_as: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trace_value_json_shape() { + let v = TraceValue::Boxed { id: 7, class: BoxKind::Int, value: "5".into() }; + assert_eq!(serde_json::to_string(&v).unwrap(), r#"{"kind":"boxed","id":7,"class":"int","value":"5"}"#); + } +} diff --git a/crates/ide-streams/src/real_run.rs b/crates/ide-streams/src/real_run.rs new file mode 100644 index 0000000000..679fb96fe1 --- /dev/null +++ b/crates/ide-streams/src/real_run.rs @@ -0,0 +1,197 @@ +//! Plan for tracing a chain by running the program itself, and linking what the run recorded. + +use crate::OpRole; +use crate::chain::{ChainOp, ChainWarning, RootKind, StreamChain}; +use crate::model::{Link, Record, StepKind, TraceValue}; +use crate::resolve::{resolve, sorted_pass_through}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +/// A call to find among the method exits of the statement's execution. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StepSpec { + pub name: String, + /// Parameter count of the JVM method, not the arguments as written. + pub args: u8, + /// Only the root uses `skip`: later steps are matched by receiver identity. + pub skip: u8, +} + +/// Sent as JSON to the debugger-side bundle, which wraps each step's return in a recorder. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RealRunPlan { + /// `None` when the stream is already held in [`Self::local`]. + pub root: Option, + pub local: Option, + /// Intermediate operations in call order, modifiers included. + pub steps: Vec, + pub terminal: StepSpec, + /// Class filters for catching the stream's construction, ANDed within one request by JDI. + pub class_filters: Vec, + /// `step_kinds[i]` relates recorded step `i` to `i + 1`. Step 0 is the source; + /// modifiers record nothing. + pub step_kinds: Vec, + /// The chain is parallel, so the trace forces it sequential. + pub sequentialize: bool, + /// 0-based line of the statement's first token. + pub first_line: u32, + /// 0-based line the chain ends on. Before the terminal runs, the thread is on these lines; once + /// it is elsewhere, an exception skipped the rest of the chain. + pub last_line: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum RealRunRefusal { + NotJavaStreamRoot { root: String }, + LazyTerminal { op: String }, + NoTerminal, + UnknownOperation { op: String }, + InsideChainLambda, + SyntaxError, +} + +const STREAM_PACKAGE: &str = "java.util.stream.*"; + +pub fn real_run_plan(chain: &StreamChain) -> Result { + let spec = |op: &ChainOp| StepSpec { name: op.name.clone(), args: op.args, skip: 0 }; + + let mut class_filters = vec![STREAM_PACKAGE.to_string()]; + let (root, local) = match (&chain.root_kind, &chain.root.call) { + (RootKind::Call, Some(call)) => { + class_filters.extend(call.family.class_filters().iter().map(|f| f.to_string())); + (Some(StepSpec { name: call.name.clone(), args: call.args, skip: call.skip }), None) + } + (RootKind::Local { name }, _) => (None, Some(name.clone())), + _ => return Err(RealRunRefusal::NotJavaStreamRoot { root: chain.root.text.clone() }), + }; + + let mut step_kinds = Vec::new(); + for op in &chain.ops { + match op.role { + OpRole::Step { link } => step_kinds.push(link), + OpRole::Modifier => {} + _ => return Err(RealRunRefusal::UnknownOperation { op: op.name.clone() }), + } + } + match chain.terminal.role { + OpRole::Terminal { .. } => {} + OpRole::LazyTerminal => return Err(RealRunRefusal::LazyTerminal { op: chain.terminal.name.clone() }), + _ => return Err(RealRunRefusal::NoTerminal), + } + + Ok(RealRunPlan { + root, + local, + steps: chain.ops.iter().map(spec).collect(), + terminal: spec(&chain.terminal), + class_filters: without_overlaps(class_filters), + step_kinds, + sequentialize: chain.warnings.contains(&ChainWarning::Sequentialized), + first_line: chain.first_line, + last_line: chain.range.end.line, + }) +} + +/// Drops each filter another one covers. A method exit that two requests match arrives as two +/// events of one held event set, and the bundle handles (and resumes) each, so the trace fails. +fn without_overlaps(filters: Vec) -> Vec { + let covered = + |f: &String| filters.iter().any(|w| w != f && w.strip_suffix('*').is_some_and(|prefix| f.starts_with(prefix))); + let mut kept: Vec = Vec::new(); + for f in &filters { + if !covered(f) && !kept.contains(f) { + kept.push(f.clone()); + } + } + kept +} + +/// Names of the recorded steps, indexed like [`Record::step`]: the root call's name (empty for a +/// stream held in a local), then each operation [`real_run_plan`] gives a step kind. +pub fn recorded_steps(chain: &StreamChain) -> Vec { + let source = match (&chain.root_kind, &chain.root.call) { + (RootKind::Call, Some(call)) => call.name.clone(), + _ => String::new(), + }; + let recording = chain.ops.iter().filter(|op| matches!(op.role, OpRole::Step { .. })); + std::iter::once(source).chain(recording.map(|op| op.name.clone())).collect() +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct TraceRecording { + pub records: Vec, + /// Records the recorder discarded after its budget ran out. + pub dropped: u64, + pub terminal: TerminalOutcome, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TerminalOutcome { + Value { value: TraceValue }, + Void, + Threw { exception: TraceValue }, +} + +/// Something the user must know to read the trace correctly. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TraceBanner { + Truncated { + dropped: u64, + }, + /// `count()` on a sized source skips the pipeline, so nothing was recorded. + CountFromSize, + SortedPassThrough { + step: u16, + }, + Sequentialized, + BreakpointsSkipped { + count: u32, + }, + /// Breakpoint stops of the chain's thread while it ran, resumed without being shown. + BreakpointsResumed { + count: u32, + }, + Threw, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct LinkedTrace { + pub records: Vec, + /// Parallel to `records`. + pub links: Vec, + pub banners: Vec, +} + +pub fn link_trace(plan: &RealRunPlan, recording: &TraceRecording, skipped_breakpoints: u32) -> LinkedTrace { + let records = &recording.records; + let mut banners = Vec::new(); + if recording.dropped > 0 { + banners.push(TraceBanner::Truncated { dropped: recording.dropped }); + } + if plan.terminal.name == "count" && records.is_empty() { + banners.push(TraceBanner::CountFromSize); + } + for (i, kind) in plan.step_kinds.iter().enumerate() { + let step = i as u16 + 1; + if *kind == StepKind::Reorder && sorted_pass_through(records, step) { + banners.push(TraceBanner::SortedPassThrough { step }); + } + } + if plan.sequentialize { + banners.push(TraceBanner::Sequentialized); + } + if skipped_breakpoints > 0 { + banners.push(TraceBanner::BreakpointsSkipped { count: skipped_breakpoints }); + } + if matches!(recording.terminal, TerminalOutcome::Threw { .. }) { + banners.push(TraceBanner::Threw); + } + LinkedTrace { links: resolve(&plan.step_kinds, records), records: records.clone(), banners } +} diff --git a/crates/ide-streams/src/resolve.rs b/crates/ide-streams/src/resolve.rs new file mode 100644 index 0000000000..fb63aab040 --- /dev/null +++ b/crates/ide-streams/src/resolve.rs @@ -0,0 +1,220 @@ +//! Links recorded elements across steps by time order and identity (spec §10.4). + +use std::collections::HashMap; + +use crate::model::{BoxKind, DistinctDrop, Link, Record, StepKind, TraceValue}; + +/// What a reordering step preserves: the primitive's value for boxes (each `peek` +/// re-boxes, so their ids say nothing), the object id otherwise. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Key<'a> { + Null, + Boxed(BoxKind, &'a str), + Id(u64), +} + +fn identity_key(value: &TraceValue) -> Key<'_> { + match value { + TraceValue::Null => Key::Null, + TraceValue::Boxed { class, value, .. } => Key::Boxed(*class, value), + TraceValue::Object { id, .. } | TraceValue::Str { id, .. } => Key::Id(*id), + } +} + +/// Value equality that needs no debuggee call; `None` when only `equals` can tell. +fn equality_key(value: &TraceValue) -> Option> { + match value { + TraceValue::Null => Some(EqKey::Null), + TraceValue::Boxed { class, value, .. } => Some(EqKey::Boxed(*class, value)), + TraceValue::Str { value, truncated: false, .. } => Some(EqKey::Text(value)), + TraceValue::Str { truncated: true, .. } | TraceValue::Object { .. } => None, + } +} + +#[derive(PartialEq, Eq, Hash)] +enum EqKey<'a> { + Null, + Boxed(BoxKind, &'a str), + Text(&'a str), +} + +/// Records of one step with the same key, handed out in recording order. +#[derive(Default)] +struct Bucket { + indices: Vec, + next: usize, +} + +/// `kinds[i]` is the operation between steps `i` and `i + 1`; the result runs parallel to `records`. +pub fn resolve(kinds: &[StepKind], records: &[Record]) -> Vec { + let mut buckets: HashMap<(u16, Key), Bucket> = HashMap::new(); + for (i, rec) in records.iter().enumerate() { + if kinds.get(usize::from(rec.step)) == Some(&StepKind::Reorder) { + buckets.entry((rec.step, identity_key(&rec.value))).or_default().indices.push(i as u32); + } + } + + let mut latest: HashMap = HashMap::new(); + let mut links = Vec::with_capacity(records.len()); + for (i, rec) in records.iter().enumerate() { + let previous = rec.step.checked_sub(1); + let kind = previous.and_then(|p| kinds.get(usize::from(p))); + links.push(match (previous, kind) { + (Some(p), Some(StepKind::Sync)) => Link { parent: latest.get(&p).copied(), ambiguous: false }, + (Some(p), Some(StepKind::Reorder)) => match buckets.get_mut(&(p, identity_key(&rec.value))) { + Some(b) => { + let parent = b.indices.get(b.next).copied(); + b.next += 1; + Link { parent, ambiguous: b.indices.len() > 1 } + } + None => Link { parent: None, ambiguous: false }, + }, + _ => Link { parent: None, ambiguous: false }, + }); + latest.insert(rec.step, i as u32); + } + links +} + +/// True when `step` started emitting before `step - 1` finished, which a real sort +/// cannot do: the source was already sorted and `sorted` passed elements through. +pub fn sorted_pass_through(records: &[Record], step: u16) -> bool { + let Some(previous) = step.checked_sub(1) else { + return false; + }; + let last_previous = records.iter().rposition(|r| r.step == previous); + let first_current = records.iter().position(|r| r.step == step); + matches!((first_current, last_previous), (Some(c), Some(p)) if c < p) +} + +/// Elements of `step - 1` that produced nothing at `step`, each with the earliest kept +/// element of that step it equals. Objects and truncated strings get `None`: only the +/// user's `equals` can compare them. +pub fn distinct_drops(records: &[Record], links: &[Link], step: u16) -> Vec { + let Some(previous) = step.checked_sub(1) else { + return Vec::new(); + }; + let mut kept = vec![false; records.len()]; + for (rec, link) in records.iter().zip(links) { + if let (true, Some(parent)) = (rec.step == step, link.parent) { + kept[parent as usize] = true; + } + } + + let mut first_kept: HashMap = HashMap::new(); + let mut drops = Vec::new(); + for (i, rec) in records.iter().enumerate().filter(|(_, r)| r.step == previous) { + let key = equality_key(&rec.value); + if kept[i] { + if let Some(key) = key { + first_kept.entry(key).or_insert(i as u32); + } + } else { + let same_as = key.and_then(|k| first_kept.get(&k).copied()); + drops.push(DistinctDrop { dropped: i as u32, same_as }); + } + } + drops +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{BoxKind, TraceValue}; + + fn o(id: u64) -> TraceValue { + TraceValue::Object { id, class: "Foo".into() } + } + fn int(id: u64, v: i32) -> TraceValue { + TraceValue::Boxed { id, class: BoxKind::Int, value: v.to_string() } + } + fn s(id: u64, text: &str) -> TraceValue { + TraceValue::Str { id, value: text.into(), truncated: false } + } + fn r(step: u16, value: TraceValue) -> Record { + Record { step, value } + } + fn parents(links: &[Link]) -> Vec> { + links.iter().map(|l| l.parent).collect() + } + use StepKind::{Reorder, Sync, Unlinked}; + + #[test] + fn sync_links_to_the_nearest_earlier_record() { + let records = [r(0, o(1)), r(0, o(2)), r(1, o(2)), r(2, o(3)), r(0, o(4))]; + let links = resolve(&[Sync, Sync], &records); + assert_eq!(parents(&links), [None, None, Some(1), Some(2), None]); + } + + #[test] + fn flat_map_children_link_to_their_element() { + let records = [r(0, o(1)), r(1, o(5)), r(1, o(6)), r(0, o(2)), r(1, o(7))]; + let links = resolve(&[Sync], &records); + assert_eq!(parents(&links), [None, Some(0), Some(0), None, Some(3)]); + } + + #[test] + fn skip_with_shared_cached_integers() { + let records = [r(0, int(7, 1)), r(0, int(7, 1)), r(0, int(7, 1)), r(1, int(7, 1))]; + let links = resolve(&[Sync], &records); + assert_eq!(links[3].parent, Some(2)); + } + + #[test] + fn sorted_matches_objects_by_identity() { + let records = [r(0, o(1)), r(0, o(2)), r(0, o(3)), r(1, o(3)), r(1, o(1)), r(1, o(2))]; + let links = resolve(&[Reorder], &records); + assert_eq!(parents(&links), [None, None, None, Some(2), Some(0), Some(1)]); + assert!(links.iter().all(|l| !l.ambiguous)); + } + + #[test] + fn sorted_matches_boxes_by_value_in_order() { + let records = [ + r(0, int(11, 300)), + r(0, int(12, 1)), + r(0, int(13, 300)), + r(1, int(14, 1)), + r(1, int(15, 300)), + r(1, int(16, 300)), + ]; + let links = resolve(&[Reorder], &records); + assert_eq!(links[3], Link { parent: Some(1), ambiguous: false }); + assert_eq!(links[4], Link { parent: Some(0), ambiguous: true }); + assert_eq!(links[5], Link { parent: Some(2), ambiguous: true }); + } + + #[test] + fn sorted_then_limit() { + let records = [r(0, o(5)), r(0, o(3)), r(0, o(8)), r(0, o(1)), r(1, o(1)), r(2, o(1)), r(1, o(3)), r(2, o(3))]; + let links = resolve(&[Reorder, Sync], &records); + assert_eq!(parents(&links), [None, None, None, None, Some(3), Some(4), Some(1), Some(6)]); + } + + #[test] + fn unlinked_ops_have_no_parents() { + let records = [r(0, o(1)), r(1, o(1)), r(1, o(2))]; + let links = resolve(&[Unlinked], &records); + assert_eq!(parents(&links), [None, None, None]); + } + + #[test] + fn pass_through_sort_is_detected() { + let (a, b) = (o(1), o(2)); + let sorted = [r(0, a.clone()), r(1, a.clone()), r(0, b.clone()), r(1, b.clone())]; + assert!(sorted_pass_through(&sorted, 1)); + let real = [r(0, a.clone()), r(0, b.clone()), r(1, b), r(1, a)]; + assert!(!sorted_pass_through(&real, 1)); + } + + #[test] + fn distinct_drops_find_equal_values() { + let records = [r(0, s(1, "a")), r(1, s(1, "a")), r(0, s(2, "b")), r(1, s(2, "b")), r(0, s(3, "a"))]; + let links = resolve(&[Sync], &records); + assert_eq!(distinct_drops(&records, &links, 1), [DistinctDrop { dropped: 4, same_as: Some(0) }]); + + let records = [r(0, o(1)), r(1, o(1)), r(0, o(2))]; + let links = resolve(&[Sync], &records); + assert_eq!(distinct_drops(&records, &links, 1), [DistinctDrop { dropped: 2, same_as: None }]); + } +} diff --git a/crates/ide-streams/tests/chains.rs b/crates/ide-streams/tests/chains.rs new file mode 100644 index 0000000000..3e6b7e3a6c --- /dev/null +++ b/crates/ide-streams/tests/chains.rs @@ -0,0 +1,272 @@ +use ide_core::{CancellationToken, LanguageId}; +use ide_language::{Syntax, SyntaxCache}; +use ide_streams::{ + ChainSearch, ChainWarning, FrameKind, OpRole, Rejection, RootKind, StepKind, StopContext, StreamChain, find_chains, +}; +use ide_syntax::{Snapshot, StructureService}; +use std::sync::{Arc, OnceLock}; + +const FIXTURE: &str = include_str!("fixtures/Chains.java"); + +fn service() -> &'static StructureService { + static S: OnceLock = OnceLock::new(); + S.get_or_init(|| StructureService::new(Arc::new(SyntaxCache::new(Arc::new(Syntax::new()))))) +} + +fn line_of(marker: &str) -> u32 { + let tag = format!("// {marker}"); + let found = FIXTURE.lines().position(|l| l.trim_end().ends_with(&tag)); + found.unwrap_or_else(|| panic!("no line marked {marker}")) as u32 +} + +fn search(marker: &str, in_lambda: bool) -> ChainSearch { + let java = LanguageId::new("java"); + let stop = StopContext { line: line_of(marker), in_lambda, file_stem: "Chains" }; + find_chains(service(), &Snapshot::text(&java, FIXTURE), &stop, &CancellationToken::new()).expect("search") +} + +/// The single chain on the marked line, with nothing rejected. +#[track_caller] +fn only_chain(marker: &str) -> StreamChain { + let mut found = search(marker, false); + assert!(found.rejected.is_empty(), "{marker}: unexpected rejections {:?}", found.rejected); + assert_eq!(found.chains.len(), 1, "{marker}: {:?}", found.chains); + found.chains.remove(0) +} + +#[track_caller] +fn only_rejection(marker: &str, in_lambda: bool) -> Rejection { + let found = search(marker, in_lambda); + assert!(found.chains.is_empty(), "{marker}: unexpected chains {:?}", found.chains); + assert_eq!(found.rejected.len(), 1, "{marker}: {:?}", found.rejected); + found.rejected[0].reason.clone() +} + +fn op_names(chain: &StreamChain) -> Vec<&str> { + chain.ops.iter().map(|op| op.name.as_str()).collect() +} + +#[test] +fn collector_calls_are_not_chains() { + assert_eq!(only_chain("C_NEW").terminal.name, "collect"); + assert_eq!(op_names(&only_chain("C_STATIC_IMPORT")), ["map"]); + let optional = search("C_OPTIONAL", false); + assert!(optional.chains.is_empty() && optional.rejected.is_empty(), "{optional:?}"); +} + +#[test] +fn new_stream_chain_has_root_ops_and_terminal() { + let chain = only_chain("C_NEW"); + assert_eq!(chain.root.text, "nums.stream()"); + assert_eq!(&chain.text[chain.root.span.0..chain.root.span.1], "nums.stream()"); + assert_eq!(op_names(&chain), ["filter", "map"]); + assert_eq!(&chain.text[chain.ops[0].span.0..chain.ops[0].span.1], ".filter(x -> x % 2 == 0)"); + assert_eq!(chain.ops[1].role, OpRole::Step { link: StepKind::Sync }); + assert_eq!(chain.terminal.role, OpRole::Terminal { void: false }); + assert_eq!(&chain.text[chain.terminal.span.0..chain.terminal.span.1], ".collect(Collectors.toList())"); + assert!(chain.text.starts_with("nums.stream()") && chain.text.ends_with(".collect(Collectors.toList())")); + assert!(chain.warnings.is_empty()); +} + +#[test] +fn stream_held_in_a_variable_is_a_local_root() { + let chain = only_chain("C_VARIABLE"); + assert_eq!(chain.root.text, "given"); + assert_eq!(chain.root_kind, RootKind::Local { name: "given".into() }); + assert_eq!(chain.root.call, None); +} + +#[test] +fn stream_from_an_unknown_method_is_an_other_root() { + let chain = only_chain("C_FOREIGN_ROOT"); + assert_eq!(chain.root.text, "repo.findAll()"); + assert_eq!(chain.root_kind, RootKind::Other); + assert_eq!(op_names(&chain), ["filter"]); +} + +#[test] +fn new_stream_call_is_a_call_root() { + let chain = only_chain("C_NEW"); + assert_eq!(chain.root_kind, RootKind::Call); + let call = chain.root.call.expect("call root"); + assert_eq!((call.name.as_str(), call.args, call.skip), ("stream", 0, 0)); +} + +#[test] +fn unknown_operation_is_rejected() { + assert_eq!(only_rejection("C_UNKNOWN_OP", false), Rejection::UnknownOperation { op: "mapToEntry".into() }); +} + +#[test] +fn primitive_stream_chain() { + let chain = only_chain("C_INT"); + assert_eq!(chain.root.text, "IntStream.range(0, 10)"); + assert_eq!(op_names(&chain), ["map"]); + assert_eq!(chain.terminal.name, "sum"); +} + +#[test] +fn lazy_terminal_is_rejected() { + assert_eq!(only_rejection("C_ITERATOR", false), Rejection::LazyTerminal { op: "iterator".into() }); +} + +#[test] +fn parallel_modifiers_are_kept_with_a_warning() { + let chain = only_chain("C_PARALLEL"); + assert_eq!(op_names(&chain), ["sequential", "map", "parallel"]); + let roles: Vec<_> = chain.ops.iter().map(|op| op.role).collect(); + assert_eq!(roles, [OpRole::Modifier, OpRole::Step { link: StepKind::Sync }, OpRole::Modifier]); + assert_eq!(chain.warnings, [ChainWarning::Sequentialized]); +} + +#[test] +fn multi_line_chain_found_from_a_middle_line() { + let chain = only_chain("C_MULTI"); + assert_eq!(chain.root.text, "nums.stream()"); + assert_eq!(op_names(&chain), ["map", "filter"]); + assert_eq!(chain.terminal.name, "collect"); + assert_eq!(chain.range.start.line + 3, chain.range.end.line); +} + +#[test] +fn line_inside_a_chain_lambda_is_rejected() { + assert_eq!(only_rejection("C_IN_LAMBDA", true), Rejection::InsideChainLambda); +} + +#[test] +fn nested_chain_belongs_to_the_frame() { + let outer = only_chain("C_INNER"); + assert_eq!(outer.root.text, "xs.stream()"); + assert_eq!(outer.terminal.name, "toList"); + + let mut in_lambda = search("C_INNER", true); + assert!(in_lambda.rejected.is_empty(), "{:?}", in_lambda.rejected); + assert_eq!(in_lambda.chains.len(), 1); + let inner = in_lambda.chains.remove(0); + assert_eq!(inner.text, "ys.stream().filter(y -> y < x).count()"); +} + +#[test] +fn two_chains_in_one_statement_in_source_order() { + let found = search("C_TWO", false); + assert!(found.rejected.is_empty()); + let texts: Vec<_> = found.chains.iter().map(|c| c.text.as_str()).collect(); + assert_eq!(texts, ["xs.stream().count()", "ys.stream().filter(y -> y > 0).count()"]); +} + +#[test] +fn for_each_is_a_void_terminal() { + assert_eq!(only_chain("C_FOREACH").terminal.role, OpRole::Terminal { void: true }); +} + +#[test] +fn chain_without_terminal_is_rejected() { + assert_eq!(only_rejection("C_NO_TERMINAL", false), Rejection::NoTerminal); +} + +#[test] +fn terminal_on_a_collected_result_keeps_the_stream_chain() { + for (marker, terminal) in + [("C_COLLECT_FOREACH", "collect"), ("C_TOLIST_FOREACH", "toList"), ("C_GROUPING_FOREACH", "collect")] + { + let chain = only_chain(marker); + assert_eq!(chain.terminal.name, terminal, "{marker}"); + assert!(chain.text.starts_with("nums.stream()"), "{marker}: {}", chain.text); + } +} + +#[test] +fn lambda_of_a_collection_call_is_not_inside_a_chain() { + let found = search("C_LIST_FOREACH_BODY", true); + assert!(found.chains.is_empty() && found.rejected.is_empty(), "{found:?}"); + + let grouping = search("C_GROUPING_FOREACH", true); + assert!(grouping.chains.is_empty(), "{:?}", grouping.chains); + let reasons: Vec<_> = grouping.rejected.iter().map(|r| (&r.reason, r.text.as_str())).collect(); + let chain = "nums.stream().collect(Collectors.groupingBy(x -> x % 2))"; + assert_eq!(reasons, [(&Rejection::InsideChainLambda, chain)]); +} + +#[test] +fn outermost_stream_terminal_is_the_chain_end() { + assert_eq!(only_chain("C_FIND_FIRST").terminal.name, "findFirst"); + assert_eq!(only_chain("C_COLLECT_SIZE").terminal.name, "collect"); +} + +#[test] +fn chain_in_a_statement_header_is_found_only_from_the_header() { + assert_eq!(only_chain("C_IF_HEADER").terminal.name, "anyMatch"); + let body = search("C_IF_BODY", false); + assert!(body.chains.is_empty() && body.rejected.is_empty(), "{body:?}"); +} + +#[test] +fn initializers_are_frames() { + for marker in ["C_STATIC_INIT", "C_INSTANCE_INIT", "C_FIELD_INIT", "C_INSTANCE_FIELD"] { + let chain = only_chain(marker); + assert!(chain.text.starts_with("NUMS.stream()"), "{marker}: {}", chain.text); + } + assert_eq!(only_rejection("C_FIELD_INIT", true), Rejection::InsideChainLambda); +} + +#[test] +fn syntax_error_rejects_only_the_broken_chain() { + assert_eq!(only_rejection("C_BROKEN", false), Rejection::SyntaxError); + assert_eq!(only_chain("C_BROKEN_NEXT").text, "nums.stream().count()"); +} + +#[test] +fn chains_in_unsupported_frames_are_reported_with_the_frame_kind() { + for (marker, frame) in [ + ("C_ANON", FrameKind::Anonymous), + ("C_ENUM_BODY", FrameKind::Anonymous), + ("C_LOCAL", FrameKind::Local), + ("C_SECONDARY", FrameKind::SecondaryTopLevel), + ] { + assert_eq!(only_chain(marker).frame.kind, Some(frame), "{marker}"); + } + assert_eq!(only_chain("C_NEW").frame.kind, None); +} + +#[test] +fn frame_shape_lists_classes_type_params_and_package() { + let plain = only_chain("C_NEW").frame; + assert_eq!(plain.class_path, ["Chains"]); + assert_eq!(plain.package.as_deref(), Some("demo")); + assert!(!plain.record && plain.type_params.is_empty()); + + let generic = only_chain("C_GENERIC").frame; + assert_eq!(generic.class_path, ["Chains", "Inner"]); + assert_eq!(generic.type_params, [("T".to_string(), Some("Comparable".to_string())), ("K".to_string(), None)]); + assert!(!generic.record); + + let record = only_chain("C_RECORD").frame; + assert_eq!(record.class_path, ["Chains", "Point"]); + assert!(record.record); +} + +#[test] +fn enclosing_type_params_stop_at_static_boundaries() { + let params = |marker| only_chain(marker).frame.type_params; + assert_eq!(params("C_STATIC_GENERIC"), [("S".to_string(), None)]); + assert_eq!(params("C_INNER_GENERIC"), [("K".to_string(), None)]); + assert_eq!(params("C_STATIC_NESTED"), [("F".to_string(), None)]); + // A nested record is implicitly static. + assert_eq!(params("C_RECORD_GENERIC"), [("P".to_string(), None)]); +} + +#[test] +fn columns_are_utf16() { + let chain = only_chain("C_UTF16"); + let line = FIXTURE.lines().nth(line_of("C_UTF16") as usize).unwrap(); + let before = &line[..line.find("nums").unwrap()]; + assert_eq!(chain.range.start.col as usize, before.encode_utf16().count()); +} + +#[test] +fn rejection_json_shape() { + let r = Rejection::UnknownOperation { op: "mapToEntry".into() }; + assert_eq!(serde_json::to_string(&r).unwrap(), r#"{"kind":"unknownOperation","op":"mapToEntry"}"#); + let role = OpRole::Step { link: StepKind::Reorder }; + assert_eq!(serde_json::to_string(&role).unwrap(), r#"{"kind":"step","link":"reorder"}"#); +} diff --git a/crates/ide-streams/tests/fixtures/Chains.java b/crates/ide-streams/tests/fixtures/Chains.java new file mode 100644 index 0000000000..8a2a448fc5 --- /dev/null +++ b/crates/ide-streams/tests/fixtures/Chains.java @@ -0,0 +1,214 @@ +package demo; + +import java.util.*; +import java.util.stream.*; +import static java.util.stream.Collectors.toList; + +public class Chains { + private static final int LIMIT = 3; + static final List NUMS = List.of(1, 2, 3); + static final List DOUBLED = NUMS.stream().map(x -> x * 2).toList(); // C_FIELD_INIT + final long countAll = NUMS.stream().count(); // C_INSTANCE_FIELD + int stride = 2; + + static { + long c = NUMS.stream().count(); // C_STATIC_INIT + } + + { + long c = NUMS.stream().filter(x -> x > 1).count(); // C_INSTANCE_INIT + } + + List collectors(List nums) { + List a = nums.stream().filter(x -> x % 2 == 0).map(x -> x * LIMIT).collect(Collectors.toList()); // C_NEW + List b = nums.stream().map(x -> x + 1).collect(toList()); // C_STATIC_IMPORT + int o = Optional.of(1).map(x -> x + 1).filter(x -> x > 0).orElse(0); // C_OPTIONAL + a.addAll(b); + return a; + } + + long roots(Stream given, List nums, Repository repo) { + long n = given.filter(s -> !s.isEmpty()).count(); // C_VARIABLE + int sq = IntStream.range(0, 10).map(i -> i * i).sum(); // C_INT + Iterator it = nums.stream().map(x -> x + 1).iterator(); // C_ITERATOR + long r = repo.findAll().filter(x -> x > 0).count(); // C_FOREIGN_ROOT + long u = nums.stream().map(x -> x).mapToEntry(x -> x).count(); // C_UNKNOWN_OP + return n + sq + r + u; + } + + static int next(int x) { + return x + 1; + } + + int bump(int x) { + return x + stride; + } + + void sources(List nums, java.io.BufferedReader reader, int step) { + List p = nums.parallelStream().sequential().map(x -> x).parallel().toList(); // C_PARALLEL + List g = Stream.generate(Math::random).limit(3).toList(); // C_GENERATE + List i1 = Stream.iterate(1, Chains::next).limit(3).toList(); // C_ITERATE_REF + List i2 = Stream.iterate(1, x -> x + step).limit(3).toList(); // C_ITERATE_CAPTURE + List i3 = Stream.iterate(1, x -> x * 2).limit(3).toList(); // C_ITERATE_PURE + List i4 = Stream.iterate(1, x -> x + this.stride).limit(3).toList(); // C_ITERATE_THIS_FIELD + List i5 = Stream.iterate(1, x -> this.bump(x)).limit(3).toList(); // C_ITERATE_THIS_CALL + List i6 = Stream.iterate(1, x -> { int y = x * 2; return y; }).limit(3).toList(); // C_ITERATE_BLOCK_LOCAL + long l1 = reader.lines().count(); // C_LINES + long l2 = "a\nb".lines().count(); // C_LINES_LITERAL + } + + void shapes(List nums, List xs, List ys) { + List m = nums.stream() + .map(x -> x * 2) + .filter(y -> y > 0) // C_MULTI + .collect(Collectors.toList()); + List k = nums.stream().map(x -> { + int y = x * 2; + return y + LIMIT; // C_IN_LAMBDA + }).collect(Collectors.toList()); + List inner = xs.stream().map(x -> ys.stream().filter(y -> y < x).count()).toList(); // C_INNER + long a1 = xs.stream().count(), a2 = ys.stream().filter(y -> y > 0).count(); // C_TWO + nums.stream().forEach(x -> System.out.println(x)); // C_FOREACH + var s = nums.stream().map(x -> x); // C_NO_TERMINAL + String t = "é😀"; long c = nums.stream().count(); // C_UTF16 + } + + void idioms(List nums, java.io.BufferedReader reader) { + nums.stream().map(x -> x + 1).collect(Collectors.toList()).forEach(x -> { // C_COLLECT_FOREACH + System.out.println(x); // C_LIST_FOREACH_BODY + }); + nums.stream().filter(x -> x > 1).toList().forEach(System.out::println); // C_TOLIST_FOREACH + nums.stream().collect(Collectors.groupingBy(x -> x % 2)).forEach((k, v) -> System.out.println(k + "=" + v)); // C_GROUPING_FOREACH + long rr = reader.lines().collect(Collectors.toList()).stream().count(); // C_REOPEN_READER + long rg = Stream.generate(Math::random).limit(2).collect(Collectors.toList()).stream().count(); // C_REOPEN_GENERATE + int f = nums.stream().filter(x -> x > 0).findFirst().orElse(0); // C_FIND_FIRST + int z = nums.stream().map(x -> x).collect(Collectors.toList()).size(); // C_COLLECT_SIZE + int total = 0; + if (nums.stream().anyMatch(x -> x > 0)) { // C_IF_HEADER + total += 1; // C_IF_BODY + } + } + + Stream items; + + static void foo(Object a, Object b) {} + + static boolean keep(int x) { + return x > 0; + } + + void plans(List nums, List names, List list, int base, int[] arr) { + List a = nums.stream().filter(Chains::keep).map(x -> x * 10 + base).sorted().map(String::valueOf).collect(Collectors.toList()); // C_PLAN_COLLECTION + int r = IntStream.range(0, 20).filter(i -> i % 3 == 0).map(i -> i * i).sum(); // C_PLAN_RANGE + Stream s = names.stream(); + long n = s.filter(v -> !v.isEmpty()).count(); // C_PLAN_LOCAL + long f = this.items.filter(v -> !v.isEmpty()).count(); // C_PLAN_FIELD + long g = items.filter(v -> !v.isEmpty()).count(); // C_PLAN_FIELD_BARE + List par = list.parallelStream().map(v -> v + "!").toList(); // C_PLAN_PARALLEL + long deep = list.stream().collect(Collectors.toList()).stream().filter(x -> true).count(); // C_PLAN_SKIP + long twice = list.stream().map(v -> v).filter(v -> true).map(v -> v).count(); // C_PLAN_SAME_NAME + long lazy = Math.max(names.stream().map(v -> list.stream().count()).count(), list.stream().map(v -> v).count()); // C_PLAN_LAMBDA_CALLS + boolean same = Objects.equals(names.stream().map(v -> v).toList(), list.stream().map(v -> v).toList()); // C_PLAN_SIBLING + long ar = Arrays.stream(arr).boxed().collect(Collectors.toList()).stream().count(); // C_PLAN_ARRAYS_NESTED + long so = Stream.of(1, 2, 3).map(v -> v).count(); // C_PLAN_STREAM_OF + foo(Optional.of(1), Stream.of(2).map(v -> v).count()); // C_PLAN_OTHER_FAMILY + if (names.stream().anyMatch(x -> x.isEmpty()) || list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_IF_HEADER + base++; + } + if (names.stream().anyMatch(x -> x.isEmpty())) { + base++; + } else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF + base--; + } + if (base > 0) { + names.stream().forEach(x -> x.length()); + } else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF_BODY + base--; + } + List out = nums.stream() // C_PLAN_FIRST_LINE + .filter(x -> x > 0) + .map(x -> x * 2) + .sorted() + .map(String::valueOf) + .collect(Collectors.toList()); + } + + void sourceFamilies(int[] arr, String text, java.nio.file.Path dir, java.util.regex.Pattern pat, Random rnd) throws Exception { + long c1 = Arrays.stream(arr).count(); // C_SRC_ARRAYS + long c2 = text.chars().count(); // C_SRC_CHARS + long c6 = text.lines().count(); // C_SRC_LINES + long c3 = java.nio.file.Files.lines(dir).count(); // C_SRC_FILES + long c4 = pat.splitAsStream(text).count(); // C_SRC_PATTERN + long c5 = rnd.ints(5).count(); // C_SRC_RANDOM + } + + void broken(List nums) { + nums.stream().map(x -> x +).toList(); // C_BROKEN + long ok = nums.stream().count(); // C_BROKEN_NEXT + } + + void frames(List nums) { + Runnable r = new Runnable() { + public void run() { + long c = nums.stream().count(); // C_ANON + } + }; + class Helper { + long go() { + return nums.stream().count(); // C_LOCAL + } + } + } + + static class Inner { + > long sortedCount(List items) { + return items.stream().sorted().count(); // C_GENERIC + } + + static long staticCount(List items) { + return items.stream().count(); // C_STATIC_GENERIC + } + + class Lid { + long count(List items) { + return items.stream().count(); // C_INNER_GENERIC + } + } + + static class Tag { + long count(List items) { + return items.stream().count(); // C_STATIC_NESTED + } + } + + record Pair

(P left) { + long count(List

items) { + return items.stream().count(); // C_RECORD_GENERIC + } + } + } + + record Point(int x, int y) { + long count(List nums) { + return nums.stream().filter(v -> v > x).count(); // C_RECORD + } + } + + enum Mode { + FAST { + long go(List nums) { + return nums.stream().count(); // C_ENUM_BODY + } + }; + } + + interface Repository { + Stream findAll(); + } +} + +class Secondary { + long go(List nums) { + return nums.stream().count(); // C_SECONDARY + } +} diff --git a/crates/ide-streams/tests/fixtures/java/TraceOracle.java b/crates/ide-streams/tests/fixtures/java/TraceOracle.java new file mode 100644 index 0000000000..8a96e427a8 --- /dev/null +++ b/crates/ide-streams/tests/fixtures/java/TraceOracle.java @@ -0,0 +1,184 @@ +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +// Ground truth for the stream resolver: random chains run by this JDK, logged by peek in time +// order, with each element's real parent. Usage: java TraceOracle.java +public class TraceOracle { + static int nextId = 0; + + static final class Item { + final int id = nextId++; + final int v; + final Item from; + + Item(int v, Item from) { + this.v = v; + this.from = from; + } + + // Value equality, so distinct drops equal elements the way it does for boxes. + @Override + public boolean equals(Object o) { + return o instanceof Item && ((Item) o).v == v; + } + + @Override + public int hashCode() { + return v; + } + } + + static final class Rec { + final int stage; + final Item item; + + Rec(int stage, Item item) { + this.stage = stage; + this.item = item; + } + } + + // Stream.mapMulti exists from JDK 16; called reflectively so the file still runs on 11. + static final Method MAP_MULTI = findMapMulti(); + + static Method findMapMulti() { + try { + return Stream.class.getMethod("mapMulti", BiConsumer.class); + } catch (NoSuchMethodException e) { + return null; + } + } + + static final String[] VARIANTS = {"map", "filter", "filterStateful", "flatMap", "mapMulti", "skip", "limit", + "distinct", "sorted", "sortedDesc", "sortedByKey", "takeWhile", "dropWhile", "peek"}; + + static String method(String variant) { + if (variant.startsWith("sorted")) return "sorted"; + if (variant.equals("filterStateful")) return "filter"; + return variant; + } + + static boolean creates(String variant) { + return variant.equals("map") || variant.equals("flatMap") || variant.equals("mapMulti"); + } + + final int low; + final int range; + + TraceOracle(int low, int range) { + this.low = low; + this.range = range; + } + + int wrap(int x) { + return low + Math.floorMod(x - low, range); + } + + @SuppressWarnings("unchecked") + Stream apply(Stream s, String variant, int a) { + switch (variant) { + case "map": + return s.map(t -> new Item(wrap(t.v * 7 + a), t)); + case "filter": + return s.filter(t -> Math.floorMod(t.v, 2) == 0); + case "filterStateful": { + int[] seen = {0}; + return s.filter(t -> seen[0]++ % 2 == 1); + } + case "flatMap": + return s.flatMap(t -> IntStream.range(0, Math.floorMod(t.v, 3)).mapToObj(i -> new Item(wrap(t.v + i), t))); + case "mapMulti": { + BiConsumer> expand = (t, sink) -> { + for (int i = 0; i < Math.floorMod(t.v, 3); i++) sink.accept(new Item(wrap(t.v - i), t)); + }; + try { + return (Stream) MAP_MULTI.invoke(s, expand); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException(e); + } + } + case "skip": + return s.skip(a % 3); + case "limit": + return s.limit(a % 5 + 1); + case "distinct": + return s.distinct(); + case "sorted": + return s.sorted(Comparator.comparingInt(t -> t.v)); + case "sortedDesc": + return s.sorted(Comparator.comparingInt((Item t) -> t.v).reversed()); + case "sortedByKey": + return s.sorted(Comparator.comparingInt(t -> Math.floorMod(t.v, 3))); + case "takeWhile": + return s.takeWhile(t -> t.v < low + range / 2); + case "dropWhile": + return s.dropWhile(t -> t.v < low + range / 3); + default: + return s.peek(t -> {}); + } + } + + public static void main(String[] args) { + Random rnd = new Random(Long.parseLong(args[0])); + int count = Integer.parseInt(args[1]); + List pool = new ArrayList<>(); + for (String v : VARIANTS) { + if (MAP_MULTI != null || !v.equals("mapMulti")) pool.add(v); + } + StringBuilder out = new StringBuilder(); + for (int c = 0; c < count; c++) { + // Small values hit the Integer cache (-128..127), large ones cross its edge. + TraceOracle chain = rnd.nextBoolean() ? new TraceOracle(-1, 7) : new TraceOracle(-150, 601); + int n = rnd.nextInt(10); + List source = new ArrayList<>(); + for (int i = 0; i < n; i++) source.add(new Item(chain.low + rnd.nextInt(chain.range), null)); + String[] ops = new String[1 + rnd.nextInt(4)]; + for (int i = 0; i < ops.length; i++) ops[i] = pool.get(rnd.nextInt(pool.size())); + + List log = new ArrayList<>(); + Stream s = source.stream().peek(t -> log.add(new Rec(0, t))); + for (int i = 0; i < ops.length; i++) { + int stage = i + 1; + s = chain.apply(s, ops[i], rnd.nextInt(10)).peek(t -> log.add(new Rec(stage, t))); + } + s.collect(Collectors.toList()); + + List> seen = new ArrayList<>(); + for (int i = 0; i <= ops.length; i++) seen.add(new IdentityHashMap<>()); + out.append("{\"ops\":["); + for (int i = 0; i < ops.length; i++) out.append(i > 0 ? "," : "").append('"').append(method(ops[i])).append('"'); + out.append("],\"records\":["); + for (int i = 0; i < log.size(); i++) { + Rec r = log.get(i); + out.append(i > 0 ? "," : "").append('[').append(r.stage).append(',').append(r.item.id).append(',') + .append(r.item.v).append(']'); + } + out.append("],\"truth\":["); + for (int i = 0; i < log.size(); i++) { + Rec r = log.get(i); + int parent = -1; + if (r.stage > 0) { + Item want = creates(ops[r.stage - 1]) ? r.item.from : r.item; + Integer found = seen.get(r.stage - 1).get(want); + if (found == null) throw new IllegalStateException("parent not logged before chain " + c); + parent = found; + } + seen.get(r.stage).put(r.item, i); + out.append(i > 0 ? "," : "").append(parent); + } + out.append("]}\n"); + } + System.out.print(out); + } +} diff --git a/crates/ide-streams/tests/fixtures/resolver/oracle-jdk21-seed1.jsonl b/crates/ide-streams/tests/fixtures/resolver/oracle-jdk21-seed1.jsonl new file mode 100644 index 0000000000..47a5717e3b --- /dev/null +++ b/crates/ide-streams/tests/fixtures/resolver/oracle-jdk21-seed1.jsonl @@ -0,0 +1,500 @@ +{"ops":["skip"],"records":[[0,0,0],[0,1,-1],[1,1,-1],[0,2,5],[1,2,5],[0,3,5],[1,3,5],[0,4,-1],[1,4,-1],[0,5,0],[1,5,0],[0,6,2],[1,6,2],[0,7,5],[1,7,5]],"truth":[-1,-1,1,-1,3,-1,5,-1,7,-1,9,-1,11,-1,13]} +{"ops":["map","skip","filter","limit"],"records":[[0,8,82],[1,10,-27],[2,10,-27],[0,9,341],[1,11,-17],[2,11,-17],[3,11,-17],[4,11,-17]],"truth":[-1,0,1,-1,3,4,5,6]} +{"ops":["filter","sorted","takeWhile"],"records":[[0,12,4],[0,13,1],[1,13,1],[0,14,4],[2,13,1],[3,13,1]],"truth":[-1,-1,1,-1,2,4]} +{"ops":["sorted"],"records":[[0,15,-112],[0,16,-3],[0,17,-100],[0,18,449],[1,16,-3],[1,15,-112],[1,17,-100],[1,18,449]],"truth":[-1,-1,-1,-1,1,0,2,3]} +{"ops":["sorted","distinct","sorted"],"records":[],"truth":[]} +{"ops":["flatMap","map"],"records":[[0,19,-1],[1,28,-1],[2,29,-1],[1,30,0],[2,31,-1],[0,20,3],[0,21,0],[0,22,4],[1,32,4],[2,33,-1],[0,23,2],[1,34,2],[2,35,-1],[1,36,3],[2,37,-1],[0,24,1],[1,38,1],[2,39,-1],[0,25,4],[1,40,4],[2,41,-1],[0,26,5],[1,42,5],[2,43,-1],[1,44,-1],[2,45,-1],[0,27,2],[1,46,2],[2,47,-1],[1,48,3],[2,49,-1]],"truth":[-1,0,1,0,3,-1,-1,-1,7,8,-1,10,11,10,13,-1,15,16,-1,18,19,-1,21,22,21,24,-1,26,27,26,29]} +{"ops":["limit"],"records":[[0,50,5],[1,50,5]],"truth":[-1,0]} +{"ops":["flatMap","dropWhile","dropWhile","sorted"],"records":[[0,58,120],[0,59,-71],[1,67,-71],[0,60,131],[1,68,131],[2,68,131],[3,68,131],[1,69,132],[2,69,132],[3,69,132],[0,61,412],[1,70,412],[2,70,412],[3,70,412],[0,62,225],[0,63,418],[1,71,418],[2,71,418],[3,71,418],[0,64,93],[0,65,84],[0,66,102],[4,68,131],[4,69,132],[4,70,412],[4,71,418]],"truth":[-1,-1,1,-1,3,4,5,3,7,8,-1,10,11,12,-1,-1,15,16,17,-1,-1,-1,6,9,13,18]} +{"ops":["sorted","skip"],"records":[[0,72,159],[0,73,-16],[0,74,375],[0,75,75],[0,76,-24],[0,77,249],[0,78,-38],[0,79,-4],[1,74,375],[2,74,375],[1,77,249],[2,77,249],[1,72,159],[2,72,159],[1,75,75],[2,75,75],[1,79,-4],[2,79,-4],[1,73,-16],[2,73,-16],[1,76,-24],[2,76,-24],[1,78,-38],[2,78,-38]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,2,8,5,10,0,12,3,14,7,16,1,18,4,20,6,22]} +{"ops":["distinct","sorted"],"records":[[0,80,268],[1,80,268],[0,81,449],[1,81,449],[0,82,442],[1,82,442],[2,81,449],[2,82,442],[2,80,268]],"truth":[-1,0,-1,2,-1,4,3,5,1]} +{"ops":["skip","map","sorted","flatMap"],"records":[[0,83,92],[1,83,92],[2,84,49],[3,84,49],[4,85,49]],"truth":[-1,0,1,2,3]} +{"ops":["flatMap","sorted","filter","sorted"],"records":[[0,86,75],[0,87,-138]],"truth":[-1,-1]} +{"ops":["map"],"records":[[0,88,323],[1,95,-142],[0,89,262],[1,96,32],[0,90,386],[1,97,299],[0,91,197],[1,98,178],[0,92,222],[1,99,353],[0,93,250],[1,100,-52],[0,94,-146],[1,101,181]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12]} +{"ops":["peek","mapMulti","filter"],"records":[[0,102,-8],[1,102,-8],[2,110,-8],[0,103,-113],[1,103,-113],[2,111,-113],[3,111,-113],[0,104,350],[1,104,350],[2,112,350],[2,113,349],[3,113,349],[0,105,-120],[1,105,-120],[0,106,-75],[1,106,-75],[0,107,249],[1,107,249],[0,108,355],[1,108,355],[2,114,355],[0,109,444],[1,109,444]],"truth":[-1,0,1,-1,3,4,5,-1,7,8,8,10,-1,12,-1,14,-1,16,-1,18,19,-1,21]} +{"ops":["flatMap","dropWhile"],"records":[[0,115,0],[0,116,4],[1,122,4],[2,122,4],[0,117,5],[1,123,5],[2,123,5],[1,124,-1],[2,124,-1],[0,118,1],[1,125,1],[2,125,1],[0,119,4],[1,126,4],[2,126,4],[0,120,0],[0,121,3]],"truth":[-1,-1,1,2,-1,4,5,4,7,-1,9,10,-1,12,13,-1,-1]} +{"ops":["sorted","mapMulti","peek","sorted"],"records":[[0,127,112],[0,128,107],[0,129,36],[0,130,443],[0,131,408],[0,132,-37],[1,130,443],[2,133,443],[3,133,443],[2,134,442],[3,134,442],[1,131,408],[1,127,112],[2,135,112],[3,135,112],[1,128,107],[2,136,107],[3,136,107],[2,137,106],[3,137,106],[1,129,36],[1,132,-37],[2,138,-37],[3,138,-37],[2,139,-38],[3,139,-38],[4,139,-38],[4,138,-37],[4,137,106],[4,136,107],[4,135,112],[4,134,442],[4,133,443]],"truth":[-1,-1,-1,-1,-1,-1,3,6,7,6,9,4,0,12,13,1,15,16,15,18,2,5,21,22,21,24,25,23,19,17,14,10,8]} +{"ops":["takeWhile","sorted"],"records":[[0,140,0],[1,140,0],[0,141,4],[2,140,0]],"truth":[-1,0,-1,1]} +{"ops":["takeWhile","sorted","sorted","skip"],"records":[],"truth":[]} +{"ops":["filter","filter","takeWhile"],"records":[[0,143,3],[0,144,-134],[1,144,-134],[0,145,-60],[0,146,418],[1,146,418],[2,146,418]],"truth":[-1,-1,1,-1,-1,4,5]} +{"ops":["flatMap"],"records":[[0,151,4],[1,159,4],[0,152,-1],[1,160,-1],[1,161,0],[0,153,3],[0,154,3],[0,155,-1],[1,162,-1],[1,163,0],[0,156,2],[1,164,2],[1,165,3],[0,157,0],[0,158,2],[1,166,2],[1,167,3]],"truth":[-1,0,-1,2,2,-1,-1,-1,7,7,-1,10,10,-1,-1,14,14]} +{"ops":["takeWhile"],"records":[[0,168,100],[1,168,100],[0,169,42],[1,169,42],[0,170,369]],"truth":[-1,0,-1,2,-1]} +{"ops":["distinct","filter","sorted"],"records":[[0,175,4],[1,175,4],[0,176,2],[1,176,2],[2,176,2],[0,177,1],[1,177,1],[0,178,-1],[1,178,-1],[2,178,-1],[0,179,4],[0,180,1],[0,181,1],[0,182,3],[1,182,3],[0,183,-1],[3,176,2],[3,178,-1]],"truth":[-1,0,-1,2,3,-1,5,-1,7,8,-1,-1,-1,-1,13,-1,4,9]} +{"ops":["filter","distinct","filter"],"records":[[0,184,5],[0,185,0],[1,185,0],[2,185,0],[3,185,0],[0,186,-1],[0,187,0],[1,187,0],[0,188,5],[0,189,2],[1,189,2],[2,189,2],[3,189,2],[0,190,2],[0,191,3],[1,191,3],[2,191,3],[0,192,1]],"truth":[-1,-1,1,2,3,-1,-1,6,-1,-1,9,10,11,-1,-1,14,15,-1]} +{"ops":["peek","sorted"],"records":[[0,193,315],[1,193,315],[0,194,120],[1,194,120],[0,195,132],[1,195,132],[0,196,-32],[1,196,-32],[0,197,184],[1,197,184],[0,198,-87],[1,198,-87],[0,199,373],[1,199,373],[0,200,199],[1,200,199],[2,199,373],[2,193,315],[2,200,199],[2,197,184],[2,195,132],[2,194,120],[2,196,-32],[2,198,-87]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,13,1,15,9,5,3,7,11]} +{"ops":["filter","distinct","sorted"],"records":[[0,201,3],[0,202,-1]],"truth":[-1,-1]} +{"ops":["skip","filter"],"records":[[0,203,259],[1,203,259],[0,204,442],[1,204,442],[2,204,442],[0,205,35],[1,205,35],[0,206,51],[1,206,51],[0,207,204],[1,207,204],[2,207,204],[0,208,330],[1,208,330],[2,208,330],[0,209,329],[1,209,329]],"truth":[-1,0,-1,2,3,-1,5,-1,7,-1,9,10,-1,12,13,-1,15]} +{"ops":["mapMulti","takeWhile","flatMap"],"records":[[0,210,4],[1,219,4]],"truth":[-1,0]} +{"ops":["sorted","limit"],"records":[[0,220,0],[0,221,5],[0,222,3],[0,223,0],[0,224,-1],[1,221,5],[2,221,5],[1,222,3],[2,222,3],[1,220,0],[2,220,0],[1,223,0],[2,223,0],[1,224,-1],[2,224,-1]],"truth":[-1,-1,-1,-1,-1,1,5,2,7,0,9,3,11,4,13]} +{"ops":["distinct","filter","sorted"],"records":[[0,225,369],[1,225,369],[0,226,446],[1,226,446],[2,226,446],[0,227,158],[1,227,158],[0,228,329],[1,228,329],[2,228,329],[0,229,346],[1,229,346],[0,230,-114],[1,230,-114],[2,230,-114],[3,226,446],[3,228,329],[3,230,-114]],"truth":[-1,0,-1,2,3,-1,5,-1,7,8,-1,10,-1,12,13,4,9,14]} +{"ops":["peek","distinct"],"records":[[0,231,319],[1,231,319],[2,231,319],[0,232,112],[1,232,112],[2,232,112],[0,233,177],[1,233,177],[2,233,177],[0,234,316],[1,234,316],[2,234,316]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10]} +{"ops":["filter"],"records":[[0,235,2],[1,235,2],[0,236,2],[1,236,2],[0,237,3],[0,238,2],[1,238,2]],"truth":[-1,0,-1,2,-1,-1,5]} +{"ops":["mapMulti","peek","skip"],"records":[[0,239,-116],[1,240,-116],[2,240,-116],[3,240,-116]],"truth":[-1,0,1,2]} +{"ops":["mapMulti","map","filter","peek"],"records":[[0,241,1],[1,243,1],[2,244,1],[0,242,1],[1,245,1],[2,246,1]],"truth":[-1,0,1,-1,3,4]} +{"ops":["distinct","sorted","sorted"],"records":[[0,247,-1],[1,247,-1],[0,248,1],[1,248,1],[0,249,3],[1,249,3],[2,249,3],[2,248,1],[2,247,-1],[3,249,3],[3,248,1],[3,247,-1]],"truth":[-1,0,-1,2,-1,4,5,3,1,6,7,8]} +{"ops":["sorted","peek","limit"],"records":[],"truth":[]} +{"ops":["peek","map","skip"],"records":[[0,250,2],[1,250,2],[2,257,1],[3,257,1],[0,251,2],[1,251,2],[2,258,1],[3,258,1],[0,252,-1],[1,252,-1],[2,259,1],[3,259,1],[0,253,5],[1,253,5],[2,260,1],[3,260,1],[0,254,0],[1,254,0],[2,261,1],[3,261,1],[0,255,0],[1,255,0],[2,262,1],[3,262,1],[0,256,5],[1,256,5],[2,263,1],[3,263,1]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,-1,16,17,18,-1,20,21,22,-1,24,25,26]} +{"ops":["sorted","filter","takeWhile"],"records":[[0,264,-33],[0,265,-83],[0,266,-120],[1,264,-33],[1,266,-120],[2,266,-120],[3,266,-120],[1,265,-83]],"truth":[-1,-1,-1,0,2,4,5,1]} +{"ops":["dropWhile","filter","filter","peek"],"records":[[0,267,5],[1,267,5]],"truth":[-1,0]} +{"ops":["dropWhile","skip"],"records":[[0,268,185],[1,268,185],[0,269,-100],[1,269,-100],[0,270,158],[1,270,158],[2,270,158],[0,271,395],[1,271,395],[2,271,395],[0,272,-4],[1,272,-4],[2,272,-4]],"truth":[-1,0,-1,2,-1,4,5,-1,7,8,-1,10,11]} +{"ops":["flatMap","sorted"],"records":[[0,273,1],[1,277,1],[0,274,1],[1,278,1],[0,275,-1],[1,279,-1],[1,280,0],[0,276,3],[2,280,0],[2,277,1],[2,278,1],[2,279,-1]],"truth":[-1,0,-1,2,-1,4,4,-1,6,1,3,5]} +{"ops":["dropWhile","sorted","skip","map"],"records":[],"truth":[]} +{"ops":["flatMap"],"records":[[0,281,1],[1,290,1],[0,282,2],[1,291,2],[1,292,3],[0,283,3],[0,284,3],[0,285,5],[1,293,5],[1,294,-1],[0,286,3],[0,287,4],[1,295,4],[0,288,-1],[1,296,-1],[1,297,0],[0,289,-1],[1,298,-1],[1,299,0]],"truth":[-1,0,-1,2,2,-1,-1,-1,7,7,-1,-1,11,-1,13,13,-1,16,16]} +{"ops":["sorted","takeWhile","filter","filter"],"records":[],"truth":[]} +{"ops":["distinct","dropWhile","distinct"],"records":[[0,300,8],[1,300,8],[0,301,-84],[1,301,-84],[0,302,430],[1,302,430],[2,302,430],[3,302,430],[0,303,-112],[1,303,-112],[2,303,-112],[3,303,-112],[0,304,-62],[1,304,-62],[2,304,-62],[3,304,-62],[0,305,158],[1,305,158],[2,305,158],[3,305,158],[0,306,11],[1,306,11],[2,306,11],[3,306,11],[0,307,22],[1,307,22],[2,307,22],[3,307,22],[0,308,322],[1,308,322],[2,308,322],[3,308,322]],"truth":[-1,0,-1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,-1,16,17,18,-1,20,21,22,-1,24,25,26,-1,28,29,30]} +{"ops":["peek","peek"],"records":[[0,309,-105],[1,309,-105],[2,309,-105],[0,310,144],[1,310,144],[2,310,144],[0,311,370],[1,311,370],[2,311,370]],"truth":[-1,0,1,-1,3,4,-1,6,7]} +{"ops":["takeWhile"],"records":[[0,312,1],[1,312,1],[0,313,0],[1,313,0],[0,314,2]],"truth":[-1,0,-1,2,-1]} +{"ops":["flatMap","dropWhile","mapMulti","mapMulti"],"records":[[0,320,-1],[1,325,-1],[1,326,0],[0,321,0],[0,322,2],[1,327,2],[2,327,2],[3,328,2],[4,329,2],[4,330,1],[3,331,1],[4,332,1],[1,333,3],[2,333,3],[0,323,4],[1,334,4],[2,334,4],[3,335,4],[4,336,4],[0,324,1],[1,337,1],[2,337,1],[3,338,1],[4,339,1]],"truth":[-1,0,0,-1,-1,4,5,6,7,7,6,10,4,12,-1,14,15,16,17,-1,19,20,21,22]} +{"ops":["map"],"records":[[0,340,-1],[1,343,-1],[0,341,2],[1,344,-1],[0,342,5],[1,345,-1]],"truth":[-1,0,-1,2,-1,4]} +{"ops":["distinct"],"records":[[0,346,2],[1,346,2],[0,347,-1],[1,347,-1],[0,348,1],[1,348,1],[0,349,0],[1,349,0],[0,350,4],[1,350,4],[0,351,5],[1,351,5]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["skip"],"records":[[0,352,4],[0,353,1],[0,354,2],[1,354,2],[0,355,2],[1,355,2],[0,356,-1],[1,356,-1],[0,357,5],[1,357,5],[0,358,3],[1,358,3]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["map","sorted"],"records":[],"truth":[]} +{"ops":["sorted","limit"],"records":[[0,359,-115],[0,360,-41],[0,361,163],[0,362,236],[0,363,-107],[0,364,399],[0,365,-97],[0,366,233],[1,364,399],[2,364,399],[1,362,236],[2,362,236]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,5,8,3,10]} +{"ops":["limit"],"records":[[0,367,3],[1,367,3]],"truth":[-1,0]} +{"ops":["sorted"],"records":[[0,368,289],[0,369,-43],[0,370,90],[0,371,414],[0,372,-82],[0,373,402],[0,374,197],[1,372,-82],[1,369,-43],[1,370,90],[1,374,197],[1,368,289],[1,373,402],[1,371,414]],"truth":[-1,-1,-1,-1,-1,-1,-1,4,1,2,6,0,5,3]} +{"ops":["distinct","skip"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,375,145],[0,376,351],[1,376,351],[0,377,315],[0,378,301],[1,378,301],[0,379,430],[0,380,318],[1,380,318],[0,381,178],[0,382,439],[1,382,439]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10]} +{"ops":["limit","takeWhile","sorted","sorted"],"records":[[0,383,2],[1,383,2]],"truth":[-1,0]} +{"ops":["filter","map","limit"],"records":[[0,392,75],[0,393,418],[1,393,418],[2,395,-76],[3,395,-76],[0,394,311]],"truth":[-1,-1,1,2,3,-1]} +{"ops":["skip","dropWhile","filter","distinct"],"records":[[0,396,4],[0,397,2],[1,397,2],[2,397,2],[0,398,-1],[1,398,-1],[2,398,-1],[3,398,-1],[4,398,-1],[0,399,3],[1,399,3],[2,399,3],[0,400,3],[1,400,3],[2,400,3],[3,400,3],[4,400,3]],"truth":[-1,-1,1,2,-1,4,5,6,7,-1,9,10,-1,12,13,14,15]} +{"ops":["sorted"],"records":[[0,401,228],[0,402,-43],[0,403,314],[0,404,193],[1,403,314],[1,401,228],[1,404,193],[1,402,-43]],"truth":[-1,-1,-1,-1,2,0,3,1]} +{"ops":["map","map","map"],"records":[[0,405,3],[1,414,3],[2,415,0],[3,416,5],[0,406,4],[1,417,3],[2,418,0],[3,419,5],[0,407,1],[1,420,3],[2,421,0],[3,422,5],[0,408,1],[1,423,3],[2,424,0],[3,425,5],[0,409,-1],[1,426,3],[2,427,0],[3,428,5],[0,410,1],[1,429,3],[2,430,0],[3,431,5],[0,411,5],[1,432,3],[2,433,0],[3,434,5],[0,412,4],[1,435,3],[2,436,0],[3,437,5],[0,413,1],[1,438,3],[2,439,0],[3,440,5]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,-1,16,17,18,-1,20,21,22,-1,24,25,26,-1,28,29,30,-1,32,33,34]} +{"ops":["peek","filter","sorted","sorted"],"records":[[0,441,1],[1,441,1],[0,442,4],[1,442,4],[2,442,4],[0,443,0],[1,443,0],[2,443,0],[0,444,4],[1,444,4],[2,444,4],[3,442,4],[3,444,4],[3,443,0],[4,442,4],[4,444,4],[4,443,0]],"truth":[-1,0,-1,2,3,-1,5,6,-1,8,9,4,10,7,11,12,13]} +{"ops":["sorted"],"records":[[0,445,-77],[0,446,-75],[0,447,128],[0,448,220],[0,449,232],[0,450,91],[0,451,110],[1,446,-75],[1,445,-77],[1,448,220],[1,449,232],[1,450,91],[1,447,128],[1,451,110]],"truth":[-1,-1,-1,-1,-1,-1,-1,1,0,3,4,5,2,6]} +{"ops":["skip"],"records":[[0,452,330],[0,453,337],[1,453,337],[0,454,82],[1,454,82],[0,455,-88],[1,455,-88],[0,456,74],[1,456,74],[0,457,227],[1,457,227],[0,458,108],[1,458,108],[0,459,5],[1,459,5],[0,460,300],[1,460,300]],"truth":[-1,-1,1,-1,3,-1,5,-1,7,-1,9,-1,11,-1,13,-1,15]} +{"ops":["mapMulti"],"records":[[0,461,420],[0,462,-38],[1,469,-38],[0,463,18],[0,464,-2],[1,470,-2],[0,465,196],[1,471,196],[0,466,234],[0,467,286],[1,472,286],[0,468,225]],"truth":[-1,-1,1,-1,-1,4,-1,6,-1,-1,9,-1]} +{"ops":["sorted","sorted","distinct"],"records":[[0,473,2],[0,474,-1],[0,475,4],[0,476,1],[0,477,5],[0,478,5],[0,479,0],[0,480,-1],[0,481,0],[1,479,0],[1,481,0],[1,475,4],[1,476,1],[1,473,2],[1,474,-1],[1,477,5],[1,478,5],[1,480,-1],[2,477,5],[3,477,5],[2,478,5],[2,475,4],[3,475,4],[2,473,2],[3,473,2],[2,476,1],[3,476,1],[2,479,0],[3,479,0],[2,481,0],[2,474,-1],[3,474,-1],[2,480,-1]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,-1,6,8,2,3,0,1,4,5,7,15,18,16,11,21,13,23,12,25,9,27,10,14,30,17]} +{"ops":["distinct"],"records":[[0,482,36],[1,482,36],[0,483,-91],[1,483,-91]],"truth":[-1,0,-1,2]} +{"ops":["filter","filter"],"records":[[0,484,436],[1,484,436],[2,484,436],[0,485,-1],[0,486,-60],[1,486,-60],[2,486,-60],[0,487,376],[1,487,376],[2,487,376],[0,488,351],[0,489,341]],"truth":[-1,0,1,-1,-1,4,5,-1,7,8,-1,-1]} +{"ops":["filter","skip","distinct","dropWhile"],"records":[[0,490,413],[0,491,-35],[0,492,321],[0,493,171],[0,494,221],[0,495,16],[1,495,16],[0,496,200],[1,496,200],[2,496,200],[3,496,200],[4,496,200]],"truth":[-1,-1,-1,-1,-1,-1,5,-1,7,8,9,10]} +{"ops":["takeWhile"],"records":[[0,497,5]],"truth":[-1]} +{"ops":["filter","sorted"],"records":[[0,500,159],[0,501,299],[0,502,-56],[1,502,-56],[0,503,200],[1,503,200],[0,504,242],[1,504,242],[0,505,156],[1,505,156],[0,506,327],[2,502,-56],[2,505,156],[2,503,200],[2,504,242]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,-1,3,9,5,7]} +{"ops":["flatMap"],"records":[[0,507,3],[0,508,3],[0,509,4],[1,514,4],[0,510,4],[1,515,4],[0,511,1],[1,516,1],[0,512,2],[1,517,2],[1,518,3],[0,513,0]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,8,-1]} +{"ops":["filter"],"records":[[0,519,132],[0,520,6],[1,520,6],[0,521,56],[0,522,-41],[1,522,-41],[0,523,318],[0,524,95],[1,524,95],[0,525,287],[0,526,354],[1,526,354],[0,527,-132]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,-1]} +{"ops":["sorted","flatMap"],"records":[[0,528,-7],[0,529,-131],[0,530,-46],[0,531,50],[0,532,292],[0,533,76],[0,534,13],[0,535,232],[1,529,-131],[2,536,-131],[1,532,292],[2,537,292],[1,533,76],[2,538,76],[1,534,13],[2,539,13],[1,535,232],[2,540,232],[1,528,-7],[2,541,-7],[2,542,-6],[1,530,-46],[2,543,-46],[2,544,-45],[1,531,50],[2,545,50],[2,546,51]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,1,8,4,10,5,12,6,14,7,16,0,18,18,2,21,21,3,24,24]} +{"ops":["takeWhile","dropWhile"],"records":[[0,547,0],[1,547,0],[0,548,4]],"truth":[-1,0,-1]} +{"ops":["distinct"],"records":[[0,550,388],[1,550,388],[0,551,-91],[1,551,-91]],"truth":[-1,0,-1,2]} +{"ops":["limit","mapMulti","filter","sorted"],"records":[[0,552,-134],[1,552,-134],[2,561,-134],[0,553,178],[1,553,178],[2,562,178],[3,562,178],[0,554,-142],[1,554,-142],[2,563,-142],[2,564,-143],[3,564,-143],[0,555,42],[1,555,42],[0,556,193],[1,556,193],[2,565,193],[4,564,-143],[4,562,178]],"truth":[-1,0,1,-1,3,4,5,-1,7,8,8,10,-1,12,-1,14,15,11,6]} +{"ops":["skip","flatMap","flatMap","skip"],"records":[[0,566,136],[1,566,136],[2,571,136],[3,572,136],[0,567,-74],[1,567,-74],[2,573,-74],[3,574,-74],[0,568,328],[1,568,328],[2,575,328],[3,576,328],[4,576,328],[0,569,-130],[1,569,-130],[2,577,-130],[3,578,-130],[4,578,-130],[3,579,-129],[4,579,-129],[2,580,-129],[0,570,415],[1,570,415],[2,581,415],[3,582,415],[4,582,415]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,11,-1,13,14,15,16,15,18,14,-1,21,22,23,24]} +{"ops":["filter"],"records":[[0,583,1],[0,584,3],[1,584,3]],"truth":[-1,-1,1]} +{"ops":["map","distinct","sorted"],"records":[[0,585,2],[1,587,3],[2,587,3],[0,586,5],[1,588,3],[3,587,3]],"truth":[-1,0,1,-1,3,2]} +{"ops":["map","takeWhile","takeWhile"],"records":[[0,589,126],[1,596,289]],"truth":[-1,0]} +{"ops":["skip","peek"],"records":[[0,597,2],[1,597,2],[2,597,2],[0,598,5],[1,598,5],[2,598,5],[0,599,3],[1,599,3],[2,599,3],[0,600,5],[1,600,5],[2,600,5],[0,601,5],[1,601,5],[2,601,5],[0,602,-1],[1,602,-1],[2,602,-1]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16]} +{"ops":["filter","peek","distinct","filter"],"records":[[0,603,343],[0,604,378],[1,604,378],[2,604,378],[3,604,378],[4,604,378],[0,605,-111],[0,606,113],[0,607,228],[1,607,228],[2,607,228],[3,607,228],[4,607,228],[0,608,16],[1,608,16],[2,608,16],[3,608,16],[4,608,16],[0,609,94],[1,609,94],[2,609,94],[3,609,94],[4,609,94]],"truth":[-1,-1,1,2,3,4,-1,-1,-1,8,9,10,11,-1,13,14,15,16,-1,18,19,20,21]} +{"ops":["mapMulti","map","mapMulti"],"records":[[0,610,103],[1,614,103],[2,615,121],[3,616,121],[0,611,307],[1,617,307],[2,618,347],[3,619,347],[3,620,346],[0,612,350],[1,621,350],[2,622,47],[3,623,47],[3,624,46],[1,625,349],[2,626,40],[3,627,40],[0,613,-51]],"truth":[-1,0,1,2,-1,4,5,6,6,-1,9,10,11,11,9,14,15,-1]} +{"ops":["takeWhile","limit","mapMulti","peek"],"records":[[0,628,343]],"truth":[-1]} +{"ops":["skip","peek"],"records":[[0,629,0],[0,630,2],[0,631,2],[1,631,2],[2,631,2],[0,632,0],[1,632,0],[2,632,0]],"truth":[-1,-1,-1,2,3,-1,5,6]} +{"ops":["limit"],"records":[[0,633,447],[1,633,447],[0,634,-50],[1,634,-50]],"truth":[-1,0,-1,2]} +{"ops":["mapMulti","map"],"records":[],"truth":[]} +{"ops":["filter"],"records":[],"truth":[]} +{"ops":["limit"],"records":[],"truth":[]} +{"ops":["dropWhile"],"records":[[0,635,5],[1,635,5],[0,636,-1],[1,636,-1],[0,637,0],[1,637,0],[0,638,2],[1,638,2]],"truth":[-1,0,-1,2,-1,4,-1,6]} +{"ops":["sorted","takeWhile"],"records":[],"truth":[]} +{"ops":["mapMulti"],"records":[[0,639,4],[1,647,4],[0,640,-1],[1,648,-1],[1,649,5],[0,641,5],[1,650,5],[1,651,4],[0,642,5],[1,652,5],[1,653,4],[0,643,-1],[1,654,-1],[1,655,5],[0,644,2],[1,656,2],[1,657,1],[0,645,4],[1,658,4],[0,646,4],[1,659,4]],"truth":[-1,0,-1,2,2,-1,5,5,-1,8,8,-1,11,11,-1,14,14,-1,17,-1,19]} +{"ops":["filter","limit","takeWhile"],"records":[[0,660,3],[0,661,4],[1,661,4],[2,661,4]],"truth":[-1,-1,1,2]} +{"ops":["limit"],"records":[[0,666,0],[1,666,0],[0,667,0],[1,667,0]],"truth":[-1,0,-1,2]} +{"ops":["peek"],"records":[[0,668,2],[1,668,2],[0,669,2],[1,669,2],[0,670,2],[1,670,2]],"truth":[-1,0,-1,2,-1,4]} +{"ops":["sorted","distinct","filter","map"],"records":[[0,671,98],[0,672,13],[1,672,13],[2,672,13],[1,671,98],[2,671,98],[3,671,98],[4,673,85]],"truth":[-1,-1,1,2,0,4,5,6]} +{"ops":["mapMulti","flatMap","sorted"],"records":[[0,674,275],[1,676,275],[2,677,275],[2,678,276],[1,679,274],[2,680,274],[0,675,447],[3,678,276],[3,680,274],[3,677,275]],"truth":[-1,0,1,1,0,4,-1,3,5,2]} +{"ops":["flatMap","sorted"],"records":[[0,681,5],[1,685,5],[1,686,-1],[0,682,3],[0,683,2],[1,687,2],[1,688,3],[0,684,0],[2,688,3],[2,685,5],[2,686,-1],[2,687,2]],"truth":[-1,0,0,-1,-1,4,4,-1,6,1,2,5]} +{"ops":["mapMulti","dropWhile"],"records":[[0,689,-76],[1,690,-76],[1,691,-77]],"truth":[-1,0,0]} +{"ops":["sorted"],"records":[[0,692,70],[0,693,103],[0,694,328],[0,695,92],[0,696,118],[1,692,70],[1,693,103],[1,694,328],[1,696,118],[1,695,92]],"truth":[-1,-1,-1,-1,-1,0,1,2,4,3]} +{"ops":["skip"],"records":[[0,697,5],[1,697,5],[0,698,4],[1,698,4],[0,699,1],[1,699,1],[0,700,3],[1,700,3],[0,701,4],[1,701,4],[0,702,1],[1,702,1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["limit"],"records":[[0,703,3],[1,703,3],[0,704,0],[1,704,0]],"truth":[-1,0,-1,2]} +{"ops":["filter","takeWhile"],"records":[[0,706,247],[0,707,-121],[0,708,-37],[0,709,38],[1,709,38],[2,709,38],[0,710,-51],[0,711,297]],"truth":[-1,-1,-1,-1,3,4,-1,-1]} +{"ops":["peek"],"records":[[0,712,2],[1,712,2],[0,713,4],[1,713,4],[0,714,3],[1,714,3]],"truth":[-1,0,-1,2,-1,4]} +{"ops":["mapMulti","takeWhile"],"records":[[0,715,4],[1,719,4]],"truth":[-1,0]} +{"ops":["filter","takeWhile","sorted"],"records":[[0,720,2],[1,720,2]],"truth":[-1,0]} +{"ops":["sorted","skip","skip","peek"],"records":[[0,723,143],[0,724,61],[0,725,-132],[0,726,286],[0,727,129],[0,728,197],[0,729,209],[1,725,-132],[1,724,61],[1,727,129],[2,727,129],[1,723,143],[2,723,143],[1,728,197],[2,728,197],[3,728,197],[4,728,197],[1,729,209],[2,729,209],[3,729,209],[4,729,209],[1,726,286],[2,726,286],[3,726,286],[4,726,286]],"truth":[-1,-1,-1,-1,-1,-1,-1,2,1,4,9,0,11,5,13,14,15,6,17,18,19,3,21,22,23]} +{"ops":["mapMulti"],"records":[[0,730,349],[1,732,349],[0,731,408]],"truth":[-1,0,-1]} +{"ops":["flatMap","distinct"],"records":[[0,733,-73],[1,735,-73],[2,735,-73],[1,736,-72],[2,736,-72],[0,734,172],[1,737,172],[2,737,172]],"truth":[-1,0,1,0,3,-1,5,6]} +{"ops":["limit","limit","sorted"],"records":[[0,738,404],[1,738,404],[2,738,404],[3,738,404]],"truth":[-1,0,1,2]} +{"ops":["skip","skip","sorted","mapMulti"],"records":[[0,743,140],[0,744,225],[1,744,225],[0,745,51],[1,745,51]],"truth":[-1,-1,1,-1,3]} +{"ops":["takeWhile","map","sorted","peek"],"records":[[0,746,119],[1,746,119],[2,754,234],[0,747,139],[1,747,139],[2,755,374],[0,748,405],[3,755,374],[4,755,374],[3,754,234],[4,754,234]],"truth":[-1,0,1,-1,3,4,-1,5,7,2,9]} +{"ops":["filter","limit","sorted","sorted"],"records":[[0,756,2],[0,757,2],[1,757,2],[2,757,2],[0,758,3],[0,759,3],[1,759,3],[2,759,3],[0,760,-1],[0,761,1],[1,761,1],[2,761,1],[3,761,1],[3,757,2],[3,759,3],[4,759,3],[4,761,1],[4,757,2]],"truth":[-1,-1,1,2,-1,-1,5,6,-1,-1,9,10,11,3,7,14,12,13]} +{"ops":["distinct","filter"],"records":[[0,762,3],[1,762,3]],"truth":[-1,0]} +{"ops":["sorted","takeWhile","dropWhile","skip"],"records":[[0,763,2],[0,764,3],[0,765,2],[0,766,3],[0,767,0],[0,768,5],[0,769,2],[1,768,5]],"truth":[-1,-1,-1,-1,-1,-1,-1,5]} +{"ops":["sorted","mapMulti"],"records":[[0,770,-1],[0,771,-1],[0,772,5],[0,773,1],[0,774,3],[0,775,3],[1,772,5],[2,776,5],[2,777,4],[1,774,3],[1,775,3],[1,773,1],[2,778,1],[1,770,-1],[2,779,-1],[2,780,5],[1,771,-1],[2,781,-1],[2,782,5]],"truth":[-1,-1,-1,-1,-1,-1,2,6,6,4,5,3,11,0,13,13,1,16,16]} +{"ops":["dropWhile"],"records":[[0,783,3],[1,783,3],[0,784,3],[1,784,3],[0,785,0],[1,785,0],[0,786,1],[1,786,1],[0,787,2],[1,787,2],[0,788,-1],[1,788,-1],[0,789,0],[1,789,0],[0,790,2],[1,790,2],[0,791,0],[1,791,0]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["map","limit","dropWhile","dropWhile"],"records":[[0,792,0],[1,797,-1],[2,797,-1],[0,793,0],[1,798,-1],[2,798,-1]],"truth":[-1,0,1,-1,3,4]} +{"ops":["flatMap"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,799,1],[0,800,3],[0,801,4],[1,801,4],[0,802,-1],[0,803,4],[1,803,4],[0,804,5],[0,805,1],[0,806,-1],[0,807,1]],"truth":[-1,-1,-1,2,-1,-1,5,-1,-1,-1,-1]} +{"ops":["distinct","takeWhile","flatMap","mapMulti"],"records":[[0,808,-1],[1,808,-1],[2,808,-1],[3,815,-1],[4,816,-1],[4,817,5],[3,818,0],[0,809,0],[1,809,0],[2,809,0],[0,810,0],[0,811,0],[0,812,-1],[0,813,5],[1,813,5]],"truth":[-1,0,1,2,3,3,2,-1,7,8,-1,-1,-1,-1,13]} +{"ops":["takeWhile","flatMap","peek","sorted"],"records":[[0,819,4]],"truth":[-1]} +{"ops":["filter","skip","map"],"records":[[0,827,174],[1,827,174],[2,827,174],[3,829,18],[0,828,385]],"truth":[-1,0,1,2,-1]} +{"ops":["peek","sorted","distinct","limit"],"records":[],"truth":[]} +{"ops":["skip"],"records":[[0,830,202],[0,831,318],[1,831,318],[0,832,227],[1,832,227],[0,833,-102],[1,833,-102],[0,834,295],[1,834,295],[0,835,57],[1,835,57],[0,836,186],[1,836,186],[0,837,84],[1,837,84],[0,838,183],[1,838,183]],"truth":[-1,-1,1,-1,3,-1,5,-1,7,-1,9,-1,11,-1,13,-1,15]} +{"ops":["limit"],"records":[[0,839,-114],[1,839,-114],[0,840,33],[1,840,33]],"truth":[-1,0,-1,2]} +{"ops":["sorted","limit","sorted","filter"],"records":[[0,841,113],[0,842,230],[0,843,231],[1,843,231],[2,843,231],[1,841,113],[2,841,113],[1,842,230],[2,842,230],[3,843,231],[3,842,230],[4,842,230],[3,841,113]],"truth":[-1,-1,-1,2,3,0,5,1,7,4,8,10,6]} +{"ops":["limit"],"records":[[0,844,4],[1,844,4],[0,845,3],[1,845,3]],"truth":[-1,0,-1,2]} +{"ops":["map","mapMulti","limit","peek"],"records":[[0,846,1],[1,854,2],[2,855,2],[3,855,2],[4,855,2],[2,856,1]],"truth":[-1,0,1,2,3,1]} +{"ops":["skip","sorted","filter"],"records":[[0,857,60],[0,858,77],[0,859,-149],[1,859,-149],[0,860,78],[1,860,78],[0,861,402],[1,861,402],[2,861,402],[3,861,402],[2,860,78],[3,860,78],[2,859,-149]],"truth":[-1,-1,-1,2,-1,4,-1,6,7,8,5,10,3]} +{"ops":["peek"],"records":[],"truth":[]} +{"ops":["filter","mapMulti","mapMulti","distinct"],"records":[[0,862,253],[0,863,-113],[1,863,-113],[2,865,-113],[3,866,-113],[4,866,-113],[0,864,227]],"truth":[-1,-1,1,2,3,4,-1]} +{"ops":["sorted"],"records":[],"truth":[]} +{"ops":["distinct"],"records":[[0,867,4],[1,867,4],[0,868,1],[1,868,1]],"truth":[-1,0,-1,2]} +{"ops":["peek"],"records":[[0,869,0],[1,869,0],[0,870,1],[1,870,1]],"truth":[-1,0,-1,2]} +{"ops":["takeWhile","skip","map"],"records":[[0,871,5]],"truth":[-1]} +{"ops":["takeWhile","sorted"],"records":[[0,873,2]],"truth":[-1]} +{"ops":["skip","sorted","filter"],"records":[[0,874,272],[1,874,272],[0,875,167],[1,875,167],[0,876,99],[1,876,99],[2,876,99],[2,874,272],[3,874,272],[2,875,167]],"truth":[-1,0,-1,2,-1,4,5,1,7,3]} +{"ops":["flatMap","takeWhile","takeWhile","filter"],"records":[[0,877,71],[1,878,71],[2,878,71],[3,878,71],[1,879,72],[2,879,72],[3,879,72],[4,879,72]],"truth":[-1,0,1,2,0,4,5,6]} +{"ops":["skip","distinct","flatMap"],"records":[[0,880,90],[0,881,-4],[0,882,1],[1,882,1],[2,882,1],[3,887,1],[0,883,-34],[1,883,-34],[2,883,-34],[3,888,-34],[3,889,-33],[0,884,-131],[1,884,-131],[2,884,-131],[3,890,-131],[0,885,373],[1,885,373],[2,885,373],[3,891,373],[0,886,34],[1,886,34],[2,886,34],[3,892,34]],"truth":[-1,-1,-1,2,3,4,-1,6,7,8,8,-1,11,12,13,-1,15,16,17,-1,19,20,21]} +{"ops":["takeWhile","skip"],"records":[],"truth":[]} +{"ops":["flatMap","limit","filter","sorted"],"records":[[0,893,-100],[1,897,-100],[2,897,-100],[3,897,-100],[1,898,-99],[2,898,-99],[0,894,318],[0,895,282],[0,896,2],[1,899,2],[2,899,2],[3,899,2],[4,897,-100],[4,899,2]],"truth":[-1,0,1,2,0,4,-1,-1,-1,8,9,10,3,11]} +{"ops":["sorted","mapMulti","distinct","takeWhile"],"records":[[0,900,439],[0,901,280],[0,902,197],[0,903,-104],[0,904,436],[0,905,360],[0,906,180],[0,907,394],[1,903,-104],[2,908,-104],[3,908,-104],[4,908,-104],[1,906,180],[1,902,197],[2,909,197],[3,909,197],[2,910,196],[3,910,196]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,3,8,9,10,6,2,13,14,13,16]} +{"ops":["sorted","mapMulti","limit","dropWhile"],"records":[[0,911,5],[0,912,4],[0,913,5],[1,911,5],[2,914,5],[3,914,5],[4,914,5],[2,915,4],[3,915,4],[4,915,4]],"truth":[-1,-1,-1,0,3,4,5,3,7,8]} +{"ops":["mapMulti"],"records":[[0,916,-1],[1,918,-1],[1,919,5],[0,917,1],[1,920,1]],"truth":[-1,0,0,-1,3]} +{"ops":["filter","flatMap","filter","skip"],"records":[[0,921,5],[0,922,5],[1,922,5],[2,923,5],[2,924,-1],[3,924,-1]],"truth":[-1,-1,1,2,2,4]} +{"ops":["map","mapMulti","dropWhile","mapMulti"],"records":[[0,925,1],[1,933,1],[2,934,1],[3,934,1],[4,935,1],[0,926,4],[1,936,1],[2,937,1],[3,937,1],[4,938,1],[0,927,4],[1,939,1],[2,940,1],[3,940,1],[4,941,1],[0,928,-1],[1,942,1],[2,943,1],[3,943,1],[4,944,1],[0,929,0],[1,945,1],[2,946,1],[3,946,1],[4,947,1],[0,930,3],[1,948,1],[2,949,1],[3,949,1],[4,950,1],[0,931,4],[1,951,1],[2,952,1],[3,952,1],[4,953,1],[0,932,5],[1,954,1],[2,955,1],[3,955,1],[4,956,1]],"truth":[-1,0,1,2,3,-1,5,6,7,8,-1,10,11,12,13,-1,15,16,17,18,-1,20,21,22,23,-1,25,26,27,28,-1,30,31,32,33,-1,35,36,37,38]} +{"ops":["sorted","sorted","filter","filter"],"records":[[0,957,36],[0,958,93],[1,958,93],[1,957,36],[2,958,93],[2,957,36],[3,957,36],[4,957,36]],"truth":[-1,-1,1,0,2,3,5,6]} +{"ops":["sorted","limit","distinct","skip"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,959,448],[1,959,448],[0,960,-95],[0,961,111],[0,962,200],[1,962,200],[0,963,183],[0,964,275],[0,965,405],[0,966,-20],[1,966,-20]],"truth":[-1,0,-1,-1,-1,4,-1,-1,-1,-1,9]} +{"ops":["sorted","filter"],"records":[[0,967,5],[0,968,4],[1,967,5],[1,968,4],[2,968,4]],"truth":[-1,-1,0,1,3]} +{"ops":["peek","map"],"records":[[0,969,115],[1,969,115],[2,975,210],[0,970,310],[1,970,310],[2,976,373],[0,971,-51],[1,971,-51],[2,977,250],[0,972,-65],[1,972,-65],[2,978,152],[0,973,296],[1,973,296],[2,979,275],[0,974,114],[1,974,114],[2,980,203]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16]} +{"ops":["limit","sorted"],"records":[[0,981,136],[1,981,136],[0,982,218],[1,982,218],[2,982,218],[2,981,136]],"truth":[-1,0,-1,2,3,1]} +{"ops":["flatMap","limit","limit","dropWhile"],"records":[[0,990,2],[1,991,2],[2,991,2],[3,991,2],[4,991,2],[1,992,3],[2,992,3],[3,992,3],[4,992,3]],"truth":[-1,0,1,2,3,0,5,6,7]} +{"ops":["skip","takeWhile","skip"],"records":[[0,993,329],[1,993,329]],"truth":[-1,0]} +{"ops":["distinct","flatMap"],"records":[[0,995,4],[1,995,4],[2,999,4],[0,996,5],[1,996,5],[2,1000,5],[2,1001,-1],[0,997,0],[1,997,0],[0,998,-1],[1,998,-1],[2,1002,-1],[2,1003,0]],"truth":[-1,0,1,-1,3,4,4,-1,7,-1,9,10,10]} +{"ops":["map","distinct","dropWhile","flatMap"],"records":[],"truth":[]} +{"ops":["mapMulti","flatMap","skip","dropWhile"],"records":[[0,1004,-120],[0,1005,-63],[0,1006,31],[1,1010,31],[2,1011,31],[3,1011,31],[0,1007,-62],[1,1012,-62],[2,1013,-62],[3,1013,-62],[0,1008,-68],[1,1014,-68],[2,1015,-68],[3,1015,-68],[0,1009,383],[1,1016,383],[2,1017,383],[3,1017,383],[4,1017,383],[2,1018,384],[3,1018,384],[4,1018,384],[1,1019,382],[2,1020,382],[3,1020,382],[4,1020,382]],"truth":[-1,-1,-1,2,3,4,-1,6,7,8,-1,10,11,12,-1,14,15,16,17,15,19,20,14,22,23,24]} +{"ops":["filter","skip","sorted","filter"],"records":[[0,1021,3],[0,1022,2],[1,1022,2],[2,1022,2],[0,1023,4],[1,1023,4],[2,1023,4],[0,1024,2],[1,1024,2],[2,1024,2],[3,1023,4],[4,1023,4],[3,1022,2],[4,1022,2],[3,1024,2],[4,1024,2]],"truth":[-1,-1,1,2,-1,4,5,-1,7,8,6,10,3,12,9,14]} +{"ops":["limit","takeWhile","distinct"],"records":[[0,1025,273],[1,1025,273]],"truth":[-1,0]} +{"ops":["flatMap"],"records":[[0,1031,3],[0,1032,4],[1,1033,4]],"truth":[-1,-1,1]} +{"ops":["dropWhile"],"records":[[0,1034,354],[1,1034,354],[0,1035,257],[1,1035,257],[0,1036,369],[1,1036,369],[0,1037,226],[1,1037,226],[0,1038,98],[1,1038,98]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8]} +{"ops":["dropWhile","flatMap","map","flatMap"],"records":[[0,1039,2],[1,1039,2],[2,1041,2],[3,1042,0],[2,1043,3],[3,1044,0],[0,1040,0],[1,1040,0]],"truth":[-1,0,1,2,1,4,-1,6]} +{"ops":["dropWhile","sorted","sorted","flatMap"],"records":[[0,1045,359],[1,1045,359],[2,1045,359],[3,1045,359],[4,1046,359],[4,1047,360]],"truth":[-1,0,1,2,3,3]} +{"ops":["takeWhile","skip","peek"],"records":[[0,1048,0],[1,1048,0],[0,1049,-1],[1,1049,-1],[0,1050,2]],"truth":[-1,0,-1,2,-1]} +{"ops":["sorted","takeWhile","mapMulti"],"records":[[0,1054,5],[0,1055,0],[0,1056,4],[0,1057,4],[1,1055,0],[2,1055,0],[1,1056,4]],"truth":[-1,-1,-1,-1,1,4,2]} +{"ops":["distinct","sorted","map","sorted"],"records":[[0,1058,26],[1,1058,26],[0,1059,400],[1,1059,400],[0,1060,-126],[1,1060,-126],[0,1061,123],[1,1061,123],[0,1062,14],[1,1062,14],[0,1063,368],[1,1063,368],[0,1064,131],[1,1064,131],[2,1060,-126],[3,1065,329],[2,1061,123],[3,1066,269],[2,1059,400],[3,1067,405],[2,1058,26],[3,1068,191],[2,1062,14],[3,1069,107],[2,1063,368],[3,1070,181],[2,1064,131],[3,1071,325],[4,1069,107],[4,1070,181],[4,1068,191],[4,1066,269],[4,1071,325],[4,1065,329],[4,1067,405]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,5,14,7,16,3,18,1,20,9,22,11,24,13,26,23,25,21,17,27,15,19]} +{"ops":["distinct","sorted","limit","skip"],"records":[[0,1072,5],[1,1072,5],[0,1073,1],[1,1073,1],[0,1074,-1],[1,1074,-1],[0,1075,0],[1,1075,0],[2,1075,0],[3,1075,0],[2,1073,1],[3,1073,1],[4,1073,1],[2,1072,5],[3,1072,5],[4,1072,5],[2,1074,-1],[3,1074,-1],[4,1074,-1]],"truth":[-1,0,-1,2,-1,4,-1,6,7,8,3,10,11,1,13,14,5,16,17]} +{"ops":["filter","map","sorted","sorted"],"records":[[0,1076,87]],"truth":[-1]} +{"ops":["mapMulti","peek","dropWhile","filter"],"records":[[0,1077,5],[1,1080,5],[2,1080,5],[3,1080,5],[1,1081,4],[2,1081,4],[3,1081,4],[4,1081,4],[0,1078,5],[1,1082,5],[2,1082,5],[3,1082,5],[1,1083,4],[2,1083,4],[3,1083,4],[4,1083,4],[0,1079,2],[1,1084,2],[2,1084,2],[3,1084,2],[1,1085,1],[2,1085,1],[3,1085,1],[4,1085,1]],"truth":[-1,0,1,2,0,4,5,6,-1,8,9,10,8,12,13,14,-1,16,17,18,16,20,21,22]} +{"ops":["filter","limit"],"records":[[0,1086,45],[0,1087,-44],[1,1087,-44],[2,1087,-44]],"truth":[-1,-1,1,2]} +{"ops":["filter","map"],"records":[[0,1090,251],[0,1091,138],[1,1091,138],[2,1095,369],[0,1092,419],[0,1093,415],[1,1093,415],[2,1096,-96],[0,1094,264]],"truth":[-1,-1,1,2,-1,-1,5,6,-1]} +{"ops":["filter","filter","sorted"],"records":[[0,1097,3],[0,1098,1],[1,1098,1],[0,1099,0],[0,1100,-1],[1,1100,-1]],"truth":[-1,-1,1,-1,-1,4]} +{"ops":["takeWhile","sorted","takeWhile"],"records":[[0,1101,-116],[1,1101,-116],[0,1102,284],[2,1101,-116],[3,1101,-116]],"truth":[-1,0,-1,1,3]} +{"ops":["sorted"],"records":[[0,1110,114],[0,1111,-40],[0,1112,357],[0,1113,387],[0,1114,-14],[0,1115,31],[0,1116,99],[0,1117,26],[1,1111,-40],[1,1114,-14],[1,1117,26],[1,1115,31],[1,1116,99],[1,1110,114],[1,1112,357],[1,1113,387]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,1,4,7,5,6,0,2,3]} +{"ops":["mapMulti"],"records":[[0,1118,-30],[0,1119,174],[0,1120,314],[1,1121,314],[1,1122,313]],"truth":[-1,-1,-1,2,2]} +{"ops":["distinct","skip","skip"],"records":[[0,1123,1],[1,1123,1],[2,1123,1],[0,1124,1],[0,1125,5],[1,1125,5],[2,1125,5]],"truth":[-1,0,1,-1,-1,4,5]} +{"ops":["sorted","sorted","takeWhile","skip"],"records":[[0,1126,2],[0,1127,1],[0,1128,3],[0,1129,3],[0,1130,-1],[0,1131,0],[0,1132,0],[0,1133,5],[0,1134,0],[1,1133,5],[1,1128,3],[1,1129,3],[1,1126,2],[1,1127,1],[1,1131,0],[1,1132,0],[1,1134,0],[1,1130,-1],[2,1130,-1],[3,1130,-1],[2,1131,0],[3,1131,0],[2,1132,0],[3,1132,0],[4,1132,0],[2,1134,0],[3,1134,0],[4,1134,0],[2,1127,1],[3,1127,1],[4,1127,1],[2,1126,2]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,-1,7,2,3,0,1,5,6,8,4,17,18,14,20,15,22,23,16,25,26,13,28,29,12]} +{"ops":["flatMap","flatMap","peek","takeWhile"],"records":[[0,1135,-22],[1,1138,-22],[2,1139,-22],[3,1139,-22],[4,1139,-22],[2,1140,-21],[3,1140,-21],[4,1140,-21],[1,1141,-21],[0,1136,329],[1,1142,329],[2,1143,329],[3,1143,329]],"truth":[-1,0,1,2,3,1,5,6,0,-1,9,10,11]} +{"ops":["sorted","limit"],"records":[[0,1144,286],[0,1145,-142],[0,1146,378],[0,1147,-24],[0,1148,-49],[0,1149,222],[0,1150,11],[1,1146,378],[2,1146,378],[1,1147,-24],[2,1147,-24],[1,1149,222],[2,1149,222],[1,1144,286],[2,1144,286],[1,1145,-142],[2,1145,-142]],"truth":[-1,-1,-1,-1,-1,-1,-1,2,7,3,9,5,11,0,13,1,15]} +{"ops":["mapMulti","distinct","sorted","peek"],"records":[[0,1151,-38],[1,1156,-38],[2,1156,-38],[0,1152,49],[1,1157,49],[2,1157,49],[0,1153,125],[1,1158,125],[2,1158,125],[1,1159,124],[2,1159,124],[0,1154,-141],[0,1155,292],[1,1160,292],[2,1160,292],[3,1156,-38],[4,1156,-38],[3,1157,49],[4,1157,49],[3,1159,124],[4,1159,124],[3,1158,125],[4,1158,125],[3,1160,292],[4,1160,292]],"truth":[-1,0,1,-1,3,4,-1,6,7,6,9,-1,-1,12,13,2,15,5,17,10,19,8,21,14,23]} +{"ops":["skip","peek"],"records":[[0,1161,60],[0,1162,120],[0,1163,-150],[1,1163,-150],[2,1163,-150],[0,1164,386],[1,1164,386],[2,1164,386],[0,1165,-16],[1,1165,-16],[2,1165,-16],[0,1166,220],[1,1166,220],[2,1166,220],[0,1167,28],[1,1167,28],[2,1167,28],[0,1168,322],[1,1168,322],[2,1168,322],[0,1169,56],[1,1169,56],[2,1169,56]],"truth":[-1,-1,-1,2,3,-1,5,6,-1,8,9,-1,11,12,-1,14,15,-1,17,18,-1,20,21]} +{"ops":["mapMulti","mapMulti","map","filter"],"records":[[0,1170,-54]],"truth":[-1]} +{"ops":["flatMap","filter"],"records":[[0,1171,2],[1,1179,2],[2,1179,2],[1,1180,3],[0,1172,4],[1,1181,4],[2,1181,4],[0,1173,-1],[1,1182,-1],[1,1183,0],[2,1183,0],[0,1174,2],[1,1184,2],[2,1184,2],[1,1185,3],[0,1175,1],[1,1186,1],[0,1176,0],[0,1177,2],[1,1187,2],[2,1187,2],[1,1188,3],[0,1178,5],[1,1189,5],[1,1190,-1]],"truth":[-1,0,1,0,-1,4,5,-1,7,7,9,-1,11,12,11,-1,15,-1,-1,18,19,18,-1,22,22]} +{"ops":["filter","map","skip"],"records":[[0,1191,120],[0,1192,-135],[1,1192,-135],[2,1196,263],[0,1193,304],[0,1194,300],[1,1194,300],[2,1197,303],[3,1197,303],[0,1195,18]],"truth":[-1,-1,1,2,-1,-1,5,6,7,-1]} +{"ops":["limit"],"records":[],"truth":[]} +{"ops":["distinct","peek","map"],"records":[[0,1198,1],[1,1198,1],[2,1198,1],[3,1207,1],[0,1199,1],[0,1200,0],[1,1200,0],[2,1200,0],[3,1208,1],[0,1201,4],[1,1201,4],[2,1201,4],[3,1209,1],[0,1202,-1],[1,1202,-1],[2,1202,-1],[3,1210,1],[0,1203,4],[0,1204,3],[1,1204,3],[2,1204,3],[3,1211,1],[0,1205,5],[1,1205,5],[2,1205,5],[3,1212,1],[0,1206,2],[1,1206,2],[2,1206,2],[3,1213,1]],"truth":[-1,0,1,2,-1,-1,5,6,7,-1,9,10,11,-1,13,14,15,-1,-1,18,19,20,-1,22,23,24,-1,26,27,28]} +{"ops":["distinct","distinct"],"records":[[0,1214,292],[1,1214,292],[2,1214,292],[0,1215,417],[1,1215,417],[2,1215,417],[0,1216,420],[1,1216,420],[2,1216,420]],"truth":[-1,0,1,-1,3,4,-1,6,7]} +{"ops":["sorted"],"records":[[0,1217,1],[0,1218,-1],[0,1219,4],[0,1220,3],[1,1219,4],[1,1220,3],[1,1217,1],[1,1218,-1]],"truth":[-1,-1,-1,-1,2,3,0,1]} +{"ops":["takeWhile"],"records":[[0,1221,378]],"truth":[-1]} +{"ops":["sorted","sorted","mapMulti","sorted"],"records":[[0,1224,2],[0,1225,1],[1,1225,1],[1,1224,2],[2,1225,1],[3,1226,1],[2,1224,2],[3,1227,2],[3,1228,1],[4,1226,1],[4,1228,1],[4,1227,2]],"truth":[-1,-1,1,0,2,4,3,6,6,5,8,7]} +{"ops":["sorted"],"records":[[0,1229,266],[0,1230,-69],[0,1231,6],[0,1232,-76],[1,1229,266],[1,1231,6],[1,1230,-69],[1,1232,-76]],"truth":[-1,-1,-1,-1,0,2,1,3]} +{"ops":["peek"],"records":[[0,1233,4],[1,1233,4],[0,1234,4],[1,1234,4],[0,1235,3],[1,1235,3],[0,1236,3],[1,1236,3],[0,1237,4],[1,1237,4],[0,1238,3],[1,1238,3],[0,1239,3],[1,1239,3],[0,1240,4],[1,1240,4],[0,1241,-1],[1,1241,-1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["distinct","distinct","distinct"],"records":[[0,1242,4],[1,1242,4],[2,1242,4],[3,1242,4]],"truth":[-1,0,1,2]} +{"ops":["filter","map","dropWhile","limit"],"records":[[0,1243,3],[0,1244,-1],[1,1244,-1],[2,1250,3],[3,1250,3],[4,1250,3],[0,1245,4],[0,1246,2],[1,1246,2],[2,1251,3],[3,1251,3],[4,1251,3],[0,1247,2],[0,1248,0],[1,1248,0],[2,1252,3],[3,1252,3],[4,1252,3]],"truth":[-1,-1,1,2,3,4,-1,-1,7,8,9,10,-1,-1,13,14,15,16]} +{"ops":["dropWhile"],"records":[[0,1253,5],[1,1253,5],[0,1254,4],[1,1254,4],[0,1255,3],[1,1255,3],[0,1256,0],[1,1256,0],[0,1257,4],[1,1257,4],[0,1258,2],[1,1258,2],[0,1259,1],[1,1259,1],[0,1260,3],[1,1260,3],[0,1261,1],[1,1261,1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["sorted","dropWhile","sorted"],"records":[[0,1262,0],[0,1263,0],[0,1264,3],[0,1265,3],[1,1262,0],[1,1263,0],[1,1264,3],[2,1264,3],[1,1265,3],[2,1265,3],[3,1264,3],[3,1265,3]],"truth":[-1,-1,-1,-1,0,1,2,6,3,8,7,9]} +{"ops":["peek","limit","mapMulti"],"records":[[0,1266,385],[1,1266,385],[2,1266,385],[3,1269,385],[0,1267,383],[1,1267,383],[2,1267,383],[3,1270,383],[3,1271,382],[0,1268,233],[1,1268,233],[2,1268,233],[3,1272,233],[3,1273,232]],"truth":[-1,0,1,2,-1,4,5,6,6,-1,9,10,11,11]} +{"ops":["filter","sorted","peek"],"records":[],"truth":[]} +{"ops":["peek","map","limit","sorted"],"records":[[0,1274,1],[1,1274,1],[2,1280,-1],[3,1280,-1],[0,1275,4],[1,1275,4],[2,1281,-1],[3,1281,-1],[0,1276,5],[1,1276,5],[2,1282,-1],[3,1282,-1],[0,1277,5],[1,1277,5],[2,1283,-1],[3,1283,-1],[4,1280,-1],[4,1281,-1],[4,1282,-1],[4,1283,-1]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,3,7,11,15]} +{"ops":["peek"],"records":[[0,1284,173],[1,1284,173],[0,1285,145],[1,1285,145],[0,1286,-79],[1,1286,-79],[0,1287,25],[1,1287,25],[0,1288,3],[1,1288,3]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8]} +{"ops":["takeWhile","mapMulti"],"records":[[0,1289,150]],"truth":[-1]} +{"ops":["map","distinct"],"records":[[0,1292,-70],[1,1298,114],[2,1298,114],[0,1293,-102],[1,1299,-110],[2,1299,-110],[0,1294,419],[1,1300,-69],[2,1300,-69],[0,1295,344],[1,1301,7],[2,1301,7],[0,1296,180],[1,1302,61],[2,1302,61],[0,1297,-125],[1,1303,330],[2,1303,330]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16]} +{"ops":["filter","peek","mapMulti","dropWhile"],"records":[[0,1304,321],[0,1305,-76],[1,1305,-76],[2,1305,-76],[3,1308,-76],[3,1309,-77],[0,1306,277],[0,1307,400],[1,1307,400],[2,1307,400],[3,1310,400],[4,1310,400]],"truth":[-1,-1,1,2,3,3,-1,-1,7,8,9,10]} +{"ops":["skip","limit","map"],"records":[[0,1311,3],[1,1311,3],[2,1311,3],[3,1313,1],[0,1312,4],[1,1312,4],[2,1312,4],[3,1314,1]],"truth":[-1,0,1,2,-1,4,5,6]} +{"ops":["sorted"],"records":[[0,1315,2],[0,1316,1],[0,1317,5],[1,1316,1],[1,1315,2],[1,1317,5]],"truth":[-1,-1,-1,1,0,2]} +{"ops":["sorted","sorted"],"records":[],"truth":[]} +{"ops":["peek","sorted","sorted","flatMap"],"records":[[0,1318,1],[1,1318,1],[0,1319,5],[1,1319,5],[0,1320,-1],[1,1320,-1],[0,1321,4],[1,1321,4],[0,1322,5],[1,1322,5],[2,1320,-1],[2,1318,1],[2,1321,4],[2,1319,5],[2,1322,5],[3,1320,-1],[4,1323,-1],[4,1324,0],[3,1318,1],[4,1325,1],[3,1321,4],[4,1326,4],[3,1319,5],[4,1327,5],[4,1328,-1],[3,1322,5],[4,1329,5],[4,1330,-1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,5,1,7,3,9,10,15,15,11,18,12,20,13,22,22,14,25,25]} +{"ops":["filter","skip","peek","skip"],"records":[],"truth":[]} +{"ops":["filter","mapMulti","dropWhile","peek"],"records":[[0,1331,1],[0,1332,1],[0,1333,4],[1,1333,4],[2,1334,4],[3,1334,4],[4,1334,4]],"truth":[-1,-1,-1,2,3,4,5]} +{"ops":["dropWhile"],"records":[[0,1335,1],[1,1335,1],[0,1336,3],[1,1336,3],[0,1337,2],[1,1337,2],[0,1338,-1],[1,1338,-1]],"truth":[-1,0,-1,2,-1,4,-1,6]} +{"ops":["sorted","peek","peek"],"records":[[0,1339,1],[0,1340,2],[0,1341,3],[1,1341,3],[2,1341,3],[3,1341,3],[1,1339,1],[2,1339,1],[3,1339,1],[1,1340,2],[2,1340,2],[3,1340,2]],"truth":[-1,-1,-1,2,3,4,0,6,7,1,9,10]} +{"ops":["sorted","flatMap"],"records":[[0,1342,-36],[0,1343,331],[0,1344,-4],[1,1342,-36],[1,1344,-4],[2,1345,-4],[2,1346,-3],[1,1343,331],[2,1347,331]],"truth":[-1,-1,-1,0,2,4,4,1,7]} +{"ops":["dropWhile","mapMulti"],"records":[[0,1348,5],[1,1348,5],[2,1352,5],[2,1353,4],[0,1349,5],[1,1349,5],[2,1354,5],[2,1355,4],[0,1350,-1],[1,1350,-1],[2,1356,-1],[2,1357,5],[0,1351,0],[1,1351,0]],"truth":[-1,0,1,1,-1,4,5,5,-1,8,9,9,-1,12]} +{"ops":["sorted","filter","flatMap"],"records":[[0,1358,3],[1,1358,3]],"truth":[-1,0]} +{"ops":["distinct","dropWhile","peek","takeWhile"],"records":[[0,1359,181],[1,1359,181],[2,1359,181],[3,1359,181]],"truth":[-1,0,1,2]} +{"ops":["sorted","peek","filter"],"records":[[0,1364,5],[0,1365,2],[0,1366,2],[0,1367,0],[1,1367,0],[2,1367,0],[3,1367,0],[1,1364,5],[2,1364,5],[1,1365,2],[2,1365,2],[3,1365,2],[1,1366,2],[2,1366,2],[3,1366,2]],"truth":[-1,-1,-1,-1,3,4,5,0,7,1,9,10,2,12,13]} +{"ops":["skip"],"records":[[0,1368,5],[0,1369,2],[0,1370,-1],[1,1370,-1],[0,1371,0],[1,1371,0],[0,1372,5],[1,1372,5],[0,1373,4],[1,1373,4],[0,1374,4],[1,1374,4],[0,1375,0],[1,1375,0],[0,1376,4],[1,1376,4]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14]} +{"ops":["sorted","distinct"],"records":[],"truth":[]} +{"ops":["mapMulti","dropWhile"],"records":[[0,1377,328],[1,1380,328],[2,1380,328],[0,1378,6],[0,1379,144]],"truth":[-1,0,1,-1,-1]} +{"ops":["limit","sorted","filter"],"records":[[0,1381,3],[1,1381,3],[0,1382,-1],[1,1382,-1],[0,1383,5],[1,1383,5],[2,1381,3],[2,1382,-1],[2,1383,5]],"truth":[-1,0,-1,2,-1,4,1,3,5]} +{"ops":["mapMulti","peek","flatMap"],"records":[[0,1389,262],[1,1397,262],[2,1397,262],[3,1398,262],[0,1390,222],[0,1391,83],[1,1399,83],[2,1399,83],[3,1400,83],[3,1401,84],[1,1402,82],[2,1402,82],[3,1403,82],[0,1392,162],[0,1393,-81],[0,1394,329],[1,1404,329],[2,1404,329],[3,1405,329],[3,1406,330],[1,1407,328],[2,1407,328],[3,1408,328],[0,1395,-1],[1,1409,-1],[2,1409,-1],[3,1410,-1],[3,1411,0],[1,1412,-2],[2,1412,-2],[3,1413,-2],[0,1396,-16],[1,1414,-16],[2,1414,-16],[3,1415,-16],[3,1416,-15],[1,1417,-17],[2,1417,-17],[3,1418,-17]],"truth":[-1,0,1,2,-1,-1,5,6,7,7,5,10,11,-1,-1,-1,15,16,17,17,15,20,21,-1,23,24,25,25,23,28,29,-1,31,32,33,33,31,36,37]} +{"ops":["sorted"],"records":[[0,1419,1],[0,1420,2],[0,1421,3],[0,1422,5],[1,1421,3],[1,1419,1],[1,1420,2],[1,1422,5]],"truth":[-1,-1,-1,-1,2,0,1,3]} +{"ops":["peek","takeWhile","skip","mapMulti"],"records":[[0,1423,4],[1,1423,4]],"truth":[-1,0]} +{"ops":["distinct"],"records":[[0,1432,5],[1,1432,5],[0,1433,3],[1,1433,3],[0,1434,4],[1,1434,4],[0,1435,3],[0,1436,1],[1,1436,1],[0,1437,3],[0,1438,0],[1,1438,0],[0,1439,2],[1,1439,2],[0,1440,4]],"truth":[-1,0,-1,2,-1,4,-1,-1,7,-1,-1,10,-1,12,-1]} +{"ops":["dropWhile","limit","sorted","map"],"records":[[0,1441,1],[1,1441,1],[2,1441,1],[3,1441,1],[4,1442,-1]],"truth":[-1,0,1,2,3]} +{"ops":["flatMap"],"records":[],"truth":[]} +{"ops":["distinct","distinct"],"records":[[0,1443,1],[1,1443,1],[2,1443,1],[0,1444,0],[1,1444,0],[2,1444,0],[0,1445,1],[0,1446,0],[0,1447,0],[0,1448,-1],[1,1448,-1],[2,1448,-1],[0,1449,3],[1,1449,3],[2,1449,3],[0,1450,3],[0,1451,5],[1,1451,5],[2,1451,5]],"truth":[-1,0,1,-1,3,4,-1,-1,-1,-1,9,10,-1,12,13,-1,-1,16,17]} +{"ops":["takeWhile","skip"],"records":[],"truth":[]} +{"ops":["filter","sorted","filter","limit"],"records":[[0,1452,351],[0,1453,-141]],"truth":[-1,-1]} +{"ops":["filter"],"records":[[0,1454,1],[0,1455,0],[1,1455,0],[0,1456,0],[0,1457,0],[1,1457,0],[0,1458,2],[0,1459,4],[1,1459,4],[0,1460,4],[0,1461,2],[1,1461,2]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10]} +{"ops":["peek","takeWhile"],"records":[[0,1462,5],[1,1462,5]],"truth":[-1,0]} +{"ops":["filter","filter","sorted","limit"],"records":[[0,1467,4],[1,1467,4],[0,1468,3],[0,1469,5],[0,1470,3],[0,1471,2],[1,1471,2],[2,1471,2],[3,1471,2],[4,1471,2]],"truth":[-1,0,-1,-1,-1,-1,5,6,7,8]} +{"ops":["skip"],"records":[[0,1472,169],[0,1473,159],[0,1474,121],[1,1474,121],[0,1475,141],[1,1475,141]],"truth":[-1,-1,-1,2,-1,4]} +{"ops":["skip"],"records":[[0,1476,-65],[0,1477,187],[0,1478,256],[1,1478,256],[0,1479,46],[1,1479,46],[0,1480,64],[1,1480,64]],"truth":[-1,-1,-1,2,-1,4,-1,6]} +{"ops":["sorted"],"records":[[0,1481,338],[1,1481,338]],"truth":[-1,0]} +{"ops":["skip","mapMulti","distinct"],"records":[[0,1482,334],[0,1483,28],[0,1484,349],[1,1484,349],[2,1487,349],[3,1487,349],[0,1485,342],[1,1485,342],[0,1486,432],[1,1486,432]],"truth":[-1,-1,-1,2,3,4,-1,6,-1,8]} +{"ops":["mapMulti","limit"],"records":[[0,1488,4],[1,1489,4],[2,1489,4]],"truth":[-1,0,1]} +{"ops":["sorted","takeWhile","distinct"],"records":[[0,1490,1],[0,1491,1],[0,1492,0],[0,1493,1],[0,1494,4],[1,1492,0],[2,1492,0],[3,1492,0],[1,1490,1],[2,1490,1],[3,1490,1],[1,1491,1],[2,1491,1],[1,1493,1],[2,1493,1],[1,1494,4]],"truth":[-1,-1,-1,-1,-1,2,5,6,0,8,9,1,11,3,13,4]} +{"ops":["dropWhile"],"records":[],"truth":[]} +{"ops":["map","sorted","sorted"],"records":[],"truth":[]} +{"ops":["peek"],"records":[[0,1495,5],[1,1495,5]],"truth":[-1,0]} +{"ops":["distinct","distinct","filter"],"records":[[0,1496,-46],[1,1496,-46],[2,1496,-46],[0,1497,321],[1,1497,321],[2,1497,321],[3,1497,321],[0,1498,409],[1,1498,409],[2,1498,409],[0,1499,-28],[1,1499,-28],[2,1499,-28],[3,1499,-28],[0,1500,45],[1,1500,45],[2,1500,45],[0,1501,-91],[1,1501,-91],[2,1501,-91],[3,1501,-91],[0,1502,-14],[1,1502,-14],[2,1502,-14],[0,1503,215],[1,1503,215],[2,1503,215],[3,1503,215]],"truth":[-1,0,1,-1,3,4,5,-1,7,8,-1,10,11,12,-1,14,15,-1,17,18,19,-1,21,22,-1,24,25,26]} +{"ops":["takeWhile","peek"],"records":[[0,1504,2]],"truth":[-1]} +{"ops":["limit","filter","mapMulti"],"records":[],"truth":[]} +{"ops":["filter","limit","sorted","filter"],"records":[[0,1511,3],[0,1512,1],[0,1513,4],[1,1513,4],[2,1513,4],[3,1513,4]],"truth":[-1,-1,-1,2,3,4]} +{"ops":["map","distinct","map"],"records":[[0,1514,2],[1,1519,1],[2,1519,1],[3,1520,1],[0,1515,3],[1,1521,1],[0,1516,5],[1,1522,1],[0,1517,4],[1,1523,1],[0,1518,3],[1,1524,1]],"truth":[-1,0,1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["distinct","sorted","mapMulti"],"records":[[0,1525,428],[1,1525,428],[0,1526,20],[1,1526,20],[0,1527,4],[1,1527,4],[0,1528,351],[1,1528,351],[0,1529,245],[1,1529,245],[0,1530,397],[1,1530,397],[0,1531,-106],[1,1531,-106],[0,1532,228],[1,1532,228],[2,1528,351],[2,1532,228],[2,1527,4],[3,1533,4],[2,1530,397],[3,1534,397],[2,1525,428],[3,1535,428],[3,1536,427],[2,1526,20],[3,1537,20],[3,1538,19],[2,1529,245],[3,1539,245],[3,1540,244],[2,1531,-106],[3,1541,-106],[3,1542,-107]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,7,15,5,18,11,20,1,22,22,3,25,25,9,28,28,13,31,31]} +{"ops":["mapMulti","sorted","peek","filter"],"records":[[0,1543,5],[1,1548,5],[1,1549,4],[0,1544,-1],[1,1550,-1],[1,1551,5],[0,1545,0],[0,1546,4],[1,1552,4],[0,1547,3],[2,1549,4],[3,1549,4],[4,1549,4],[2,1552,4],[3,1552,4],[4,1552,4],[2,1548,5],[3,1548,5],[2,1550,-1],[3,1550,-1],[2,1551,5],[3,1551,5]],"truth":[-1,0,0,-1,3,3,-1,-1,7,-1,2,10,11,8,13,14,1,16,4,18,5,20]} +{"ops":["filter","mapMulti","filter"],"records":[[0,1553,61]],"truth":[-1]} +{"ops":["takeWhile","limit"],"records":[[0,1554,1],[1,1554,1],[2,1554,1]],"truth":[-1,0,1]} +{"ops":["sorted","peek","filter","sorted"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,1556,423],[0,1557,389],[0,1558,-129]],"truth":[-1,-1,-1]} +{"ops":["limit","peek","flatMap"],"records":[[0,1559,71],[1,1559,71],[2,1559,71],[3,1566,71],[3,1567,72],[0,1560,446],[1,1560,446],[2,1560,446],[3,1568,446],[3,1569,447],[0,1561,438],[1,1561,438],[2,1561,438],[0,1562,-54],[1,1562,-54],[2,1562,-54]],"truth":[-1,0,1,2,2,-1,5,6,7,7,-1,10,11,-1,13,14]} +{"ops":["takeWhile","dropWhile","limit","map"],"records":[],"truth":[]} +{"ops":["peek","skip","mapMulti","peek"],"records":[[0,1570,1],[1,1570,1],[2,1570,1],[3,1576,1],[4,1576,1],[0,1571,2],[1,1571,2],[2,1571,2],[3,1577,2],[4,1577,2],[3,1578,1],[4,1578,1],[0,1572,2],[1,1572,2],[2,1572,2],[3,1579,2],[4,1579,2],[3,1580,1],[4,1580,1],[0,1573,5],[1,1573,5],[2,1573,5],[3,1581,5],[4,1581,5],[3,1582,4],[4,1582,4],[0,1574,2],[1,1574,2],[2,1574,2],[3,1583,2],[4,1583,2],[3,1584,1],[4,1584,1],[0,1575,5],[1,1575,5],[2,1575,5],[3,1585,5],[4,1585,5],[3,1586,4],[4,1586,4]],"truth":[-1,0,1,2,3,-1,5,6,7,8,7,10,-1,12,13,14,15,14,17,-1,19,20,21,22,21,24,-1,26,27,28,29,28,31,-1,33,34,35,36,35,38]} +{"ops":["peek"],"records":[[0,1587,1],[1,1587,1],[0,1588,1],[1,1588,1],[0,1589,-1],[1,1589,-1],[0,1590,5],[1,1590,5],[0,1591,4],[1,1591,4],[0,1592,-1],[1,1592,-1],[0,1593,2],[1,1593,2],[0,1594,-1],[1,1594,-1],[0,1595,2],[1,1595,2]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["skip","sorted","sorted"],"records":[[0,1596,4]],"truth":[-1]} +{"ops":["peek","map","skip"],"records":[[0,1597,4],[1,1597,4],[2,1603,2],[0,1598,3],[1,1598,3],[2,1604,2],[3,1604,2],[0,1599,-1],[1,1599,-1],[2,1605,2],[3,1605,2],[0,1600,1],[1,1600,1],[2,1606,2],[3,1606,2],[0,1601,3],[1,1601,3],[2,1607,2],[3,1607,2],[0,1602,3],[1,1602,3],[2,1608,2],[3,1608,2]],"truth":[-1,0,1,-1,3,4,5,-1,7,8,9,-1,11,12,13,-1,15,16,17,-1,19,20,21]} +{"ops":["takeWhile","filter","map","peek"],"records":[],"truth":[]} +{"ops":["filter","sorted","sorted","peek"],"records":[[0,1609,412],[0,1610,-59],[1,1610,-59],[0,1611,86],[0,1612,110],[1,1612,110],[0,1613,428],[0,1614,372],[1,1614,372],[0,1615,-29],[0,1616,-59],[1,1616,-59],[0,1617,-108],[2,1610,-59],[2,1616,-59],[2,1612,110],[2,1614,372],[3,1614,372],[4,1614,372],[3,1610,-59],[4,1610,-59],[3,1616,-59],[4,1616,-59],[3,1612,110],[4,1612,110]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,-1,2,11,5,8,16,17,13,19,14,21,15,23]} +{"ops":["takeWhile","map","sorted"],"records":[[0,1618,24],[1,1618,24],[2,1623,175],[0,1619,449],[3,1623,175]],"truth":[-1,0,1,-1,2]} +{"ops":["sorted","mapMulti","distinct"],"records":[[0,1624,149],[0,1625,348],[1,1625,348],[1,1624,149],[2,1626,149],[3,1626,149],[2,1627,148],[3,1627,148]],"truth":[-1,-1,1,0,3,4,3,6]} +{"ops":["skip","takeWhile"],"records":[[0,1628,5],[1,1628,5]],"truth":[-1,0]} +{"ops":["skip"],"records":[[0,1636,5],[0,1637,2],[0,1638,5],[1,1638,5]],"truth":[-1,-1,-1,2]} +{"ops":["sorted"],"records":[[0,1639,250],[1,1639,250]],"truth":[-1,0]} +{"ops":["sorted","distinct","sorted"],"records":[[0,1640,1],[0,1641,3],[0,1642,-1],[0,1643,4],[0,1644,3],[0,1645,3],[1,1643,4],[2,1643,4],[1,1641,3],[2,1641,3],[1,1644,3],[1,1645,3],[1,1640,1],[2,1640,1],[1,1642,-1],[2,1642,-1],[3,1641,3],[3,1643,4],[3,1640,1],[3,1642,-1]],"truth":[-1,-1,-1,-1,-1,-1,3,6,1,8,4,5,0,12,2,14,9,7,13,15]} +{"ops":["filter","skip","filter","dropWhile"],"records":[[0,1646,5],[0,1647,5],[0,1648,3]],"truth":[-1,-1,-1]} +{"ops":["dropWhile","map","distinct"],"records":[[0,1649,0],[0,1650,4],[1,1650,4],[2,1658,-1],[3,1658,-1],[0,1651,4],[1,1651,4],[2,1659,-1],[0,1652,1],[1,1652,1],[2,1660,-1],[0,1653,5],[1,1653,5],[2,1661,-1],[0,1654,2],[1,1654,2],[2,1662,-1],[0,1655,-1],[1,1655,-1],[2,1663,-1],[0,1656,-1],[1,1656,-1],[2,1664,-1],[0,1657,2],[1,1657,2],[2,1665,-1]],"truth":[-1,-1,1,2,3,-1,5,6,-1,8,9,-1,11,12,-1,14,15,-1,17,18,-1,20,21,-1,23,24]} +{"ops":["filter","peek","distinct","filter"],"records":[],"truth":[]} +{"ops":["distinct","mapMulti","distinct"],"records":[[0,1666,-87],[1,1666,-87],[0,1667,-109],[1,1667,-109],[2,1673,-109],[3,1673,-109],[2,1674,-110],[3,1674,-110],[0,1668,-35],[1,1668,-35],[2,1675,-35],[3,1675,-35],[0,1669,41],[1,1669,41],[2,1676,41],[3,1676,41],[2,1677,40],[3,1677,40],[0,1670,67],[1,1670,67],[2,1678,67],[3,1678,67],[0,1671,8],[1,1671,8],[2,1679,8],[3,1679,8],[2,1680,7],[3,1680,7],[0,1672,173],[1,1672,173],[2,1681,173],[3,1681,173],[2,1682,172],[3,1682,172]],"truth":[-1,0,-1,2,3,4,3,6,-1,8,9,10,-1,12,13,14,13,16,-1,18,19,20,-1,22,23,24,23,26,-1,28,29,30,29,32]} +{"ops":["dropWhile","flatMap","filter"],"records":[[0,1683,375],[1,1683,375],[0,1684,400],[1,1684,400],[2,1685,400]],"truth":[-1,0,-1,2,3]} +{"ops":["sorted","map"],"records":[[0,1686,5],[0,1687,2],[0,1688,1],[0,1689,-1],[0,1690,0],[0,1691,4],[0,1692,5],[1,1689,-1],[2,1693,0],[1,1690,0],[2,1694,0],[1,1688,1],[2,1695,0],[1,1687,2],[2,1696,0],[1,1691,4],[2,1697,0],[1,1686,5],[2,1698,0],[1,1692,5],[2,1699,0]],"truth":[-1,-1,-1,-1,-1,-1,-1,3,7,4,9,2,11,1,13,5,15,0,17,6,19]} +{"ops":["map","filter","limit","dropWhile"],"records":[[0,1700,1],[1,1707,4],[2,1707,4],[3,1707,4],[4,1707,4],[0,1701,2],[1,1708,4],[2,1708,4],[3,1708,4],[4,1708,4],[0,1702,5],[1,1709,4],[2,1709,4],[3,1709,4],[4,1709,4],[0,1703,5],[1,1710,4],[2,1710,4],[3,1710,4],[4,1710,4],[0,1704,0],[1,1711,4],[2,1711,4],[3,1711,4],[4,1711,4]],"truth":[-1,0,1,2,3,-1,5,6,7,8,-1,10,11,12,13,-1,15,16,17,18,-1,20,21,22,23]} +{"ops":["map"],"records":[[0,1712,107],[1,1717,149],[0,1713,165],[1,1718,-46],[0,1714,405],[1,1719,432],[0,1715,365],[1,1720,152],[0,1716,85],[1,1721,-5]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8]} +{"ops":["filter","dropWhile","sorted","filter"],"records":[],"truth":[]} +{"ops":["mapMulti"],"records":[[0,1722,3],[0,1723,5],[1,1725,5],[1,1726,4],[0,1724,2],[1,1727,2],[1,1728,1]],"truth":[-1,-1,1,1,-1,4,4]} +{"ops":["filter","sorted","filter","flatMap"],"records":[[0,1729,-1],[0,1730,0],[1,1730,0],[0,1731,3],[0,1732,4],[1,1732,4],[0,1733,3],[0,1734,1],[1,1734,1],[0,1735,4],[0,1736,-1],[1,1736,-1],[2,1730,0],[2,1732,4],[3,1732,4],[4,1737,4],[2,1734,1],[2,1736,-1],[3,1736,-1],[4,1738,-1],[4,1739,0]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,2,5,13,14,8,11,17,18,18]} +{"ops":["map","filter","sorted","skip"],"records":[[0,1740,2],[1,1743,-1],[0,1741,0],[1,1744,-1],[0,1742,4],[1,1745,-1]],"truth":[-1,0,-1,2,-1,4]} +{"ops":["sorted","peek","mapMulti"],"records":[[0,1746,-69],[0,1747,394],[0,1748,148],[0,1749,230],[0,1750,302],[0,1751,258],[1,1747,394],[2,1747,394],[3,1752,394],[1,1750,302],[2,1750,302],[3,1753,302],[3,1754,301],[1,1751,258],[2,1751,258],[1,1749,230],[2,1749,230],[3,1755,230],[3,1756,229],[1,1748,148],[2,1748,148],[3,1757,148],[1,1746,-69],[2,1746,-69]],"truth":[-1,-1,-1,-1,-1,-1,1,6,7,4,9,10,10,5,13,3,15,16,16,2,19,20,0,22]} +{"ops":["filter"],"records":[[0,1758,353],[0,1759,198],[1,1759,198],[0,1760,5],[0,1761,239],[1,1761,239],[0,1762,345],[0,1763,350],[1,1763,350],[0,1764,-96],[0,1765,-118],[1,1765,-118],[0,1766,3]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,-1]} +{"ops":["takeWhile","sorted","peek","sorted"],"records":[[0,1767,3]],"truth":[-1]} +{"ops":["map"],"records":[[0,1773,424],[1,1779,-32],[0,1774,351],[1,1780,58],[0,1775,304],[1,1781,330],[0,1776,162],[1,1782,-63],[0,1777,140],[1,1783,384],[0,1778,-14],[1,1784,-93]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["filter","skip","filter"],"records":[[0,1785,1],[0,1786,23],[0,1787,127],[0,1788,386],[1,1788,386],[0,1789,-15],[0,1790,310],[1,1790,310],[0,1791,351],[0,1792,385],[0,1793,99]],"truth":[-1,-1,-1,-1,3,-1,-1,6,-1,-1,-1]} +{"ops":["filter","takeWhile","peek","sorted"],"records":[[0,1794,2],[0,1795,2],[1,1795,2]],"truth":[-1,-1,1]} +{"ops":["map","map","sorted","limit"],"records":[[0,1801,5],[1,1804,5],[2,1805,-1],[0,1802,5],[1,1806,5],[2,1807,-1],[0,1803,3],[1,1808,5],[2,1809,-1],[3,1805,-1],[4,1805,-1],[3,1807,-1],[4,1807,-1],[3,1809,-1],[4,1809,-1]],"truth":[-1,0,1,-1,3,4,-1,6,7,2,9,5,11,8,13]} +{"ops":["dropWhile","sorted"],"records":[[0,1810,-1],[0,1811,0],[0,1812,3],[1,1812,3],[0,1813,3],[1,1813,3],[0,1814,5],[1,1814,5],[0,1815,4],[1,1815,4],[0,1816,-1],[1,1816,-1],[0,1817,2],[1,1817,2],[0,1818,2],[1,1818,2],[2,1816,-1],[2,1817,2],[2,1818,2],[2,1812,3],[2,1813,3],[2,1815,4],[2,1814,5]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,11,13,15,3,5,9,7]} +{"ops":["distinct","distinct"],"records":[[0,1819,-1],[1,1819,-1],[2,1819,-1],[0,1820,5],[1,1820,5],[2,1820,5],[0,1821,0],[1,1821,0],[2,1821,0],[0,1822,4],[1,1822,4],[2,1822,4],[0,1823,0],[0,1824,4],[0,1825,2],[1,1825,2],[2,1825,2]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,-1,-1,14,15]} +{"ops":["filter","takeWhile","map","distinct"],"records":[[0,1826,0],[0,1827,3],[1,1827,3]],"truth":[-1,-1,1]} +{"ops":["sorted","distinct","sorted","takeWhile"],"records":[[0,1835,65],[0,1836,154],[0,1837,45],[0,1838,-61],[0,1839,159],[0,1840,416],[1,1840,416],[2,1840,416],[1,1839,159],[2,1839,159],[1,1836,154],[2,1836,154],[1,1835,65],[2,1835,65],[1,1837,45],[2,1837,45],[1,1838,-61],[2,1838,-61],[3,1839,159]],"truth":[-1,-1,-1,-1,-1,-1,5,6,4,8,1,10,0,12,2,14,3,16,9]} +{"ops":["filter","sorted","peek","peek"],"records":[[0,1841,371],[0,1842,151],[1,1842,151],[0,1843,82],[0,1844,360],[1,1844,360],[0,1845,231],[0,1846,203],[1,1846,203],[0,1847,442],[2,1844,360],[3,1844,360],[4,1844,360],[2,1846,203],[3,1846,203],[4,1846,203],[2,1842,151],[3,1842,151],[4,1842,151]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,5,10,11,8,13,14,2,16,17]} +{"ops":["filter","map","mapMulti","map"],"records":[[0,1848,3],[0,1849,1],[0,1850,0],[1,1850,0],[2,1851,1],[3,1852,1],[4,1853,4]],"truth":[-1,-1,-1,2,3,4,5]} +{"ops":["dropWhile","takeWhile","dropWhile"],"records":[[0,1854,4],[1,1854,4]],"truth":[-1,0]} +{"ops":["distinct","dropWhile"],"records":[[0,1859,369],[1,1859,369],[2,1859,369],[0,1860,397],[1,1860,397],[2,1860,397],[0,1861,-75],[1,1861,-75],[2,1861,-75],[0,1862,194],[1,1862,194],[2,1862,194],[0,1863,-60],[1,1863,-60],[2,1863,-60],[0,1864,428],[1,1864,428],[2,1864,428]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16]} +{"ops":["limit"],"records":[],"truth":[]} +{"ops":["peek","sorted","filter","distinct"],"records":[[0,1865,-1],[1,1865,-1],[2,1865,-1]],"truth":[-1,0,1]} +{"ops":["filter"],"records":[[0,1866,2],[0,1867,4],[1,1867,4],[0,1868,4],[0,1869,3],[1,1869,3],[0,1870,0],[0,1871,5],[1,1871,5],[0,1872,4],[0,1873,3],[1,1873,3],[0,1874,2]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,-1]} +{"ops":["limit","sorted","distinct"],"records":[[0,1875,4],[1,1875,4],[0,1876,0],[1,1876,0],[2,1876,0],[3,1876,0],[2,1875,4],[3,1875,4]],"truth":[-1,0,-1,2,3,4,1,6]} +{"ops":["sorted","limit","map","sorted"],"records":[[0,1881,1],[0,1882,2],[0,1883,0],[0,1884,4],[0,1885,0],[0,1886,2],[0,1887,5],[0,1888,2],[1,1883,0],[2,1883,0],[3,1889,2],[4,1889,2]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,2,8,9,10]} +{"ops":["skip","filter"],"records":[[0,1890,363],[1,1890,363],[0,1891,306],[1,1891,306],[2,1891,306],[0,1892,0],[1,1892,0],[0,1893,34],[1,1893,34],[2,1893,34]],"truth":[-1,0,-1,2,3,-1,5,-1,7,8]} +{"ops":["sorted"],"records":[[0,1894,0],[0,1895,5],[0,1896,0],[0,1897,3],[1,1894,0],[1,1896,0],[1,1897,3],[1,1895,5]],"truth":[-1,-1,-1,-1,0,2,3,1]} +{"ops":["distinct"],"records":[],"truth":[]} +{"ops":["dropWhile","map"],"records":[[0,1898,-79],[0,1899,-53],[0,1900,351],[1,1900,351],[2,1906,53],[0,1901,-14],[1,1901,-14],[2,1907,-98],[0,1902,135],[1,1902,135],[2,1908,344],[0,1903,252],[1,1903,252],[2,1909,-39],[0,1904,366],[1,1904,366],[2,1910,158],[0,1905,35],[1,1905,35],[2,1911,245]],"truth":[-1,-1,-1,2,3,-1,5,6,-1,8,9,-1,11,12,-1,14,15,-1,17,18]} +{"ops":["map","distinct","flatMap","distinct"],"records":[[0,1912,447],[1,1920,126],[2,1920,126],[0,1913,356],[1,1921,90],[2,1921,90],[0,1914,182],[1,1922,74],[2,1922,74],[3,1923,74],[4,1923,74],[3,1924,75],[4,1924,75],[0,1915,-112],[1,1925,420],[2,1925,420],[0,1916,-60],[1,1926,183],[2,1926,183],[0,1917,206],[1,1927,242],[2,1927,242],[3,1928,242],[4,1928,242],[3,1929,243],[4,1929,243],[0,1918,-143],[1,1930,203],[2,1930,203],[3,1931,203],[4,1931,203],[3,1932,204],[4,1932,204],[0,1919,403],[1,1933,419],[2,1933,419],[3,1934,419],[4,1934,419],[3,1935,420],[4,1935,420]],"truth":[-1,0,1,-1,3,4,-1,6,7,8,9,8,11,-1,13,14,-1,16,17,-1,19,20,21,22,21,24,-1,26,27,28,29,28,31,-1,33,34,35,36,35,38]} +{"ops":["takeWhile","skip","peek","flatMap"],"records":[[0,1936,374]],"truth":[-1]} +{"ops":["sorted","filter","sorted"],"records":[[0,1942,1],[1,1942,1]],"truth":[-1,0]} +{"ops":["sorted","sorted","takeWhile","flatMap"],"records":[[0,1943,2],[0,1944,1],[0,1945,-1],[1,1944,1],[1,1943,2],[1,1945,-1],[2,1944,1],[3,1944,1],[4,1946,1],[2,1943,2]],"truth":[-1,-1,-1,1,0,2,3,6,7,4]} +{"ops":["peek","sorted","map"],"records":[[0,1947,55],[1,1947,55],[0,1948,-90],[1,1948,-90],[0,1949,357],[1,1949,357],[0,1950,99],[1,1950,99],[0,1951,287],[1,1951,287],[0,1952,-112],[1,1952,-112],[0,1953,-83],[1,1953,-83],[2,1948,-90],[3,1954,-22],[2,1949,357],[3,1955,102],[2,1950,99],[3,1956,99],[2,1947,55],[3,1957,392],[2,1953,-83],[3,1958,27],[2,1951,287],[3,1959,213],[2,1952,-112],[3,1960,425]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,3,14,5,16,7,18,1,20,13,22,9,24,11,26]} +{"ops":["distinct","filter"],"records":[],"truth":[]} +{"ops":["mapMulti"],"records":[[0,1961,-49],[1,1965,-49],[1,1966,-50],[0,1962,-40],[1,1967,-40],[1,1968,-41],[0,1963,106],[1,1969,106],[0,1964,1],[1,1970,1]],"truth":[-1,0,0,-1,3,3,-1,6,-1,8]} +{"ops":["peek","filter","sorted","sorted"],"records":[[0,1971,3],[1,1971,3],[0,1972,2],[1,1972,2],[2,1972,2],[3,1972,2],[4,1972,2]],"truth":[-1,0,-1,2,3,4,5]} +{"ops":["filter","dropWhile","takeWhile"],"records":[[0,1973,29],[0,1974,161],[0,1975,369],[0,1976,261],[0,1977,6],[1,1977,6]],"truth":[-1,-1,-1,-1,-1,4]} +{"ops":["sorted","distinct"],"records":[[0,1978,-112],[0,1979,-117],[0,1980,209],[0,1981,404],[1,1981,404],[2,1981,404],[1,1980,209],[2,1980,209],[1,1978,-112],[2,1978,-112],[1,1979,-117],[2,1979,-117]],"truth":[-1,-1,-1,-1,3,4,2,6,0,8,1,10]} +{"ops":["skip","limit"],"records":[[0,1982,3],[1,1982,3],[2,1982,3],[0,1983,1],[1,1983,1],[2,1983,1]],"truth":[-1,0,1,-1,3,4]} +{"ops":["map"],"records":[[0,1984,5],[1,1991,38],[0,1985,-149],[1,1992,162],[0,1986,-134],[1,1993,267],[0,1987,-1],[1,1994,-4],[0,1988,216],[1,1995,313],[0,1989,143],[1,1996,403],[0,1990,408],[1,1997,-146]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12]} +{"ops":["flatMap","sorted"],"records":[[0,1998,0],[0,1999,0],[0,2000,4],[1,2003,4],[0,2001,5],[1,2004,5],[1,2005,-1],[0,2002,0],[2,2003,4],[2,2004,5],[2,2005,-1]],"truth":[-1,-1,-1,2,-1,4,4,-1,3,5,6]} +{"ops":["skip","filter"],"records":[],"truth":[]} +{"ops":["mapMulti","sorted","sorted"],"records":[[0,2006,187],[1,2014,187],[0,2007,364],[1,2015,364],[0,2008,269],[1,2016,269],[1,2017,268],[0,2009,181],[1,2018,181],[0,2010,9],[0,2011,-133],[1,2019,-133],[1,2020,-134],[0,2012,214],[1,2021,214],[0,2013,-12],[2,2014,187],[2,2015,364],[2,2017,268],[2,2018,181],[2,2020,-134],[2,2021,214],[2,2016,269],[2,2019,-133],[3,2015,364],[3,2016,269],[3,2017,268],[3,2021,214],[3,2014,187],[3,2018,181],[3,2019,-133],[3,2020,-134]],"truth":[-1,0,-1,2,-1,4,4,-1,7,-1,-1,10,10,-1,13,-1,1,3,6,8,12,14,5,11,17,22,18,21,16,19,23,20]} +{"ops":["filter","mapMulti","distinct"],"records":[[0,2022,289]],"truth":[-1]} +{"ops":["mapMulti","filter","filter"],"records":[[0,2023,4],[1,2026,4],[0,2024,0],[0,2025,2],[1,2027,2],[2,2027,2],[1,2028,1]],"truth":[-1,0,-1,-1,3,4,3]} +{"ops":["sorted","skip","flatMap"],"records":[[0,2029,3],[0,2030,0],[0,2031,4],[0,2032,3],[1,2029,3],[1,2030,0],[2,2030,0],[1,2032,3],[2,2032,3],[1,2031,4],[2,2031,4],[3,2033,4]],"truth":[-1,-1,-1,-1,0,1,5,3,7,2,9,10]} +{"ops":["dropWhile","peek","sorted"],"records":[[0,2034,134],[1,2034,134],[2,2034,134],[0,2035,153],[1,2035,153],[2,2035,153],[0,2036,356],[1,2036,356],[2,2036,356],[0,2037,136],[1,2037,136],[2,2037,136],[0,2038,448],[1,2038,448],[2,2038,448],[0,2039,144],[1,2039,144],[2,2039,144],[0,2040,76],[1,2040,76],[2,2040,76],[0,2041,417],[1,2041,417],[2,2041,417],[3,2040,76],[3,2034,134],[3,2037,136],[3,2039,144],[3,2035,153],[3,2036,356],[3,2041,417],[3,2038,448]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16,-1,18,19,-1,21,22,20,2,11,17,5,8,23,14]} +{"ops":["flatMap","distinct","sorted","filter"],"records":[[0,2042,-1],[1,2046,-1],[2,2046,-1],[1,2047,0],[2,2047,0],[0,2043,4],[1,2048,4],[2,2048,4],[0,2044,-1],[1,2049,-1],[1,2050,0],[0,2045,5],[1,2051,5],[2,2051,5],[1,2052,-1],[3,2051,5],[3,2048,4],[4,2048,4],[3,2047,0],[3,2046,-1],[4,2046,-1]],"truth":[-1,0,1,0,3,-1,5,6,-1,8,8,-1,11,12,11,13,7,16,4,2,19]} +{"ops":["takeWhile","flatMap","filter","sorted"],"records":[[0,2053,310]],"truth":[-1]} +{"ops":["mapMulti","sorted","filter","sorted"],"records":[[0,2056,2],[1,2061,2],[1,2062,1],[0,2057,5],[1,2063,5],[1,2064,4],[0,2058,-1],[1,2065,-1],[1,2066,5],[0,2059,0],[0,2060,5],[1,2067,5],[1,2068,4],[2,2062,1],[2,2064,4],[3,2064,4],[2,2068,4],[3,2068,4],[2,2061,2],[3,2061,2],[2,2063,5],[2,2065,-1],[2,2066,5],[2,2067,5],[4,2064,4],[4,2068,4],[4,2061,2]],"truth":[-1,0,0,-1,3,3,-1,6,6,-1,-1,10,10,2,5,14,12,16,1,18,4,7,8,11,15,17,19]} +{"ops":["peek"],"records":[[0,2069,348],[1,2069,348],[0,2070,35],[1,2070,35],[0,2071,66],[1,2071,66]],"truth":[-1,0,-1,2,-1,4]} +{"ops":["flatMap"],"records":[[0,2072,303],[0,2073,397],[1,2079,397],[0,2074,282],[0,2075,191],[1,2080,191],[1,2081,192],[0,2076,258],[0,2077,282],[0,2078,103],[1,2082,103]],"truth":[-1,-1,1,-1,-1,4,4,-1,-1,-1,9]} +{"ops":["sorted","sorted","map","dropWhile"],"records":[[0,2083,381],[0,2084,397],[0,2085,220],[0,2086,426],[0,2087,103],[0,2088,428],[0,2089,65],[0,2090,-84],[1,2090,-84],[1,2089,65],[1,2087,103],[1,2085,220],[1,2083,381],[1,2084,397],[1,2086,426],[1,2088,428],[2,2090,-84],[3,2091,15],[2,2083,381],[3,2092,265],[4,2092,265],[2,2086,426],[3,2093,-21],[4,2093,-21],[2,2087,103],[3,2094,122],[4,2094,122],[2,2085,220],[3,2095,340],[4,2095,340],[2,2084,397],[3,2096,377],[4,2096,377],[2,2089,65],[3,2097,-144],[4,2097,-144],[2,2088,428],[3,2098,-7],[4,2098,-7]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,7,6,4,2,0,1,3,5,8,16,12,18,19,14,21,22,10,24,25,11,27,28,13,30,31,9,33,34,15,36,37]} +{"ops":["dropWhile","sorted"],"records":[[0,2099,3],[1,2099,3],[0,2100,3],[1,2100,3],[2,2099,3],[2,2100,3]],"truth":[-1,0,-1,2,1,3]} +{"ops":["skip","sorted"],"records":[[0,2101,0],[0,2102,2],[0,2103,4],[1,2103,4],[0,2104,2],[1,2104,2],[2,2104,2],[2,2103,4]],"truth":[-1,-1,-1,2,-1,4,5,3]} +{"ops":["peek","sorted","skip","mapMulti"],"records":[[0,2105,0],[1,2105,0],[0,2106,2],[1,2106,2],[0,2107,0],[1,2107,0],[0,2108,0],[1,2108,0],[2,2106,2],[2,2105,0],[2,2107,0],[3,2107,0],[2,2108,0],[3,2108,0]],"truth":[-1,0,-1,2,-1,4,-1,6,3,1,5,10,7,12]} +{"ops":["distinct","takeWhile","filter","skip"],"records":[[0,2109,299],[1,2109,299]],"truth":[-1,0]} +{"ops":["flatMap"],"records":[[0,2111,-97],[1,2116,-97],[1,2117,-96],[0,2112,385],[1,2118,385],[0,2113,305],[1,2119,305],[1,2120,306],[0,2114,86],[1,2121,86],[1,2122,87],[0,2115,65],[1,2123,65],[1,2124,66]],"truth":[-1,0,0,-1,3,-1,5,5,-1,8,8,-1,11,11]} +{"ops":["mapMulti","distinct","map","distinct"],"records":[[0,2125,299],[1,2127,299],[2,2127,299],[3,2128,297],[4,2128,297],[1,2129,298],[2,2129,298],[3,2130,290],[4,2130,290],[0,2126,-144]],"truth":[-1,0,1,2,3,0,5,6,7,-1]} +{"ops":["distinct","sorted","skip"],"records":[[0,2131,3],[1,2131,3],[0,2132,5],[1,2132,5],[0,2133,2],[1,2133,2],[0,2134,0],[1,2134,0],[0,2135,0],[0,2136,0],[0,2137,2],[2,2134,0],[2,2133,2],[2,2131,3],[3,2131,3],[2,2132,5],[3,2132,5]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,-1,-1,7,5,1,13,3,15]} +{"ops":["mapMulti","filter","distinct"],"records":[[0,2138,431],[1,2145,431],[1,2146,430],[2,2146,430],[3,2146,430],[0,2139,363],[0,2140,221],[1,2147,221],[1,2148,220],[2,2148,220],[3,2148,220],[0,2141,89],[1,2149,89],[1,2150,88],[2,2150,88],[3,2150,88],[0,2142,-114],[0,2143,355],[1,2151,355],[0,2144,317],[1,2152,317],[2,2152,317],[3,2152,317],[1,2153,316]],"truth":[-1,0,0,2,3,-1,-1,6,6,8,9,-1,11,11,13,14,-1,-1,17,-1,19,20,21,19]} +{"ops":["sorted","mapMulti"],"records":[[0,2154,170],[0,2155,48],[0,2156,293],[0,2157,359],[0,2158,373],[0,2159,432],[0,2160,128],[0,2161,-113],[0,2162,4],[1,2161,-113],[2,2163,-113],[1,2162,4],[2,2164,4],[1,2155,48],[1,2160,128],[2,2165,128],[2,2166,127],[1,2154,170],[2,2167,170],[2,2168,169],[1,2156,293],[2,2169,293],[2,2170,292],[1,2157,359],[2,2171,359],[2,2172,358],[1,2158,373],[2,2173,373],[1,2159,432]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,-1,7,9,8,11,1,6,14,14,0,17,17,2,20,20,3,23,23,4,26,5]} +{"ops":["flatMap"],"records":[[0,2174,298],[1,2180,298],[0,2175,295],[1,2181,295],[0,2176,403],[1,2182,403],[0,2177,-75],[0,2178,237],[0,2179,54]],"truth":[-1,0,-1,2,-1,4,-1,-1,-1]} +{"ops":["distinct","filter"],"records":[[0,2183,3],[1,2183,3],[0,2184,-1],[1,2184,-1],[0,2185,5],[1,2185,5],[0,2186,-1],[0,2187,2],[1,2187,2],[2,2187,2]],"truth":[-1,0,-1,2,-1,4,-1,-1,7,8]} +{"ops":["distinct","filter","sorted"],"records":[[0,2188,5],[1,2188,5],[0,2189,-1],[1,2189,-1],[0,2190,2],[1,2190,2],[2,2190,2],[0,2191,0],[1,2191,0],[2,2191,0],[0,2192,3],[1,2192,3],[0,2193,1],[1,2193,1],[0,2194,5],[0,2195,-1],[0,2196,3],[3,2191,0],[3,2190,2]],"truth":[-1,0,-1,2,-1,4,5,-1,7,8,-1,10,-1,12,-1,-1,-1,9,6]} +{"ops":["sorted","mapMulti","sorted"],"records":[[0,2197,403],[1,2197,403],[2,2198,403],[3,2198,403]],"truth":[-1,0,1,2]} +{"ops":["sorted","sorted","filter","sorted"],"records":[[0,2199,2],[0,2200,1],[1,2200,1],[1,2199,2],[2,2200,1],[2,2199,2],[3,2199,2],[4,2199,2]],"truth":[-1,-1,1,0,2,3,5,6]} +{"ops":["sorted","sorted","peek"],"records":[[0,2201,257],[0,2202,389],[0,2203,440],[0,2204,18],[0,2205,-113],[0,2206,407],[0,2207,-141],[0,2208,288],[0,2209,428],[1,2207,-141],[1,2205,-113],[1,2204,18],[1,2201,257],[1,2208,288],[1,2202,389],[1,2206,407],[1,2209,428],[1,2203,440],[2,2207,-141],[3,2207,-141],[2,2205,-113],[3,2205,-113],[2,2204,18],[3,2204,18],[2,2201,257],[3,2201,257],[2,2208,288],[3,2208,288],[2,2202,389],[3,2202,389],[2,2206,407],[3,2206,407],[2,2209,428],[3,2209,428],[2,2203,440],[3,2203,440]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,-1,6,4,3,0,7,1,5,8,2,9,18,10,20,11,22,12,24,13,26,14,28,15,30,16,32,17,34]} +{"ops":["skip","sorted"],"records":[],"truth":[]} +{"ops":["sorted","flatMap"],"records":[[0,2210,224],[0,2211,97],[0,2212,411],[0,2213,-46],[0,2214,312],[0,2215,62],[0,2216,-130],[1,2212,411],[1,2214,312],[1,2211,97],[2,2217,97],[1,2210,224],[2,2218,224],[2,2219,225],[1,2213,-46],[2,2220,-46],[2,2221,-45],[1,2215,62],[2,2222,62],[2,2223,63],[1,2216,-130],[2,2224,-130],[2,2225,-129]],"truth":[-1,-1,-1,-1,-1,-1,-1,2,4,1,9,0,11,11,3,14,14,5,17,17,6,20,20]} +{"ops":["peek","distinct","sorted"],"records":[[0,2226,5],[1,2226,5],[2,2226,5],[0,2227,-1],[1,2227,-1],[2,2227,-1],[0,2228,3],[1,2228,3],[2,2228,3],[0,2229,5],[1,2229,5],[0,2230,3],[1,2230,3],[0,2231,0],[1,2231,0],[2,2231,0],[0,2232,4],[1,2232,4],[2,2232,4],[0,2233,1],[1,2233,1],[2,2233,1],[0,2234,0],[1,2234,0],[3,2226,5],[3,2232,4],[3,2228,3],[3,2233,1],[3,2231,0],[3,2227,-1]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,-1,11,-1,13,14,-1,16,17,-1,19,20,-1,22,2,18,8,21,15,5]} +{"ops":["dropWhile","sorted","skip","mapMulti"],"records":[[0,2235,0],[0,2236,3],[1,2236,3],[0,2237,5],[1,2237,5],[0,2238,2],[1,2238,2],[0,2239,0],[1,2239,0],[2,2237,5],[3,2237,5],[4,2240,5],[4,2241,4],[2,2236,3],[3,2236,3],[2,2238,2],[3,2238,2],[4,2242,2],[4,2243,1],[2,2239,0],[3,2239,0]],"truth":[-1,-1,1,-1,3,-1,5,-1,7,4,9,10,10,2,13,6,15,16,16,8,19]} +{"ops":["map"],"records":[],"truth":[]} +{"ops":["takeWhile"],"records":[[0,2244,-15],[1,2244,-15]],"truth":[-1,0]} +{"ops":["sorted","dropWhile","dropWhile"],"records":[[0,2245,0],[0,2246,1],[0,2247,-1],[0,2248,-1],[1,2245,0],[1,2246,1],[2,2246,1],[3,2246,1],[1,2247,-1],[2,2247,-1],[3,2247,-1],[1,2248,-1],[2,2248,-1],[3,2248,-1]],"truth":[-1,-1,-1,-1,0,1,5,6,2,8,9,3,11,12]} +{"ops":["flatMap"],"records":[[0,2249,-51],[0,2250,88],[1,2252,88],[0,2251,443],[1,2253,443],[1,2254,444]],"truth":[-1,-1,1,-1,3,3]} +{"ops":["filter"],"records":[[0,2255,132],[0,2256,-44],[1,2256,-44],[0,2257,6],[0,2258,-143],[1,2258,-143],[0,2259,89]],"truth":[-1,-1,1,-1,-1,4,-1]} +{"ops":["mapMulti","limit","sorted"],"records":[[0,2260,4],[1,2265,4],[2,2265,4],[3,2265,4]],"truth":[-1,0,1,2]} +{"ops":["skip","peek"],"records":[[0,2266,3],[0,2267,5],[0,2268,4],[1,2268,4],[2,2268,4],[0,2269,-1],[1,2269,-1],[2,2269,-1],[0,2270,-1],[1,2270,-1],[2,2270,-1]],"truth":[-1,-1,-1,2,3,-1,5,6,-1,8,9]} +{"ops":["sorted","sorted","dropWhile"],"records":[[0,2271,0],[0,2272,3],[0,2273,2],[1,2271,0],[1,2272,3],[1,2273,2],[2,2272,3],[3,2272,3],[2,2273,2],[3,2273,2],[2,2271,0],[3,2271,0]],"truth":[-1,-1,-1,0,1,2,4,6,5,8,3,10]} +{"ops":["filter","map","sorted"],"records":[[0,2274,-121],[0,2275,320],[1,2275,320],[2,2278,442],[0,2276,60],[0,2277,137],[1,2277,137],[2,2279,363],[3,2279,363],[3,2278,442]],"truth":[-1,-1,1,2,-1,-1,5,6,7,3]} +{"ops":["takeWhile","peek","skip"],"records":[[0,2280,0],[1,2280,0],[2,2280,0]],"truth":[-1,0,1]} +{"ops":["map","peek"],"records":[[0,2281,-102],[1,2283,-110],[2,2283,-110],[0,2282,181],[1,2284,68],[2,2284,68]],"truth":[-1,0,1,-1,3,4]} +{"ops":["map","sorted"],"records":[[0,2285,-1],[1,2291,0],[0,2286,2],[1,2292,0],[0,2287,2],[1,2293,0],[0,2288,3],[1,2294,0],[0,2289,-1],[1,2295,0],[0,2290,2],[1,2296,0],[2,2291,0],[2,2292,0],[2,2293,0],[2,2294,0],[2,2295,0],[2,2296,0]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,1,3,5,7,9,11]} +{"ops":["dropWhile","map","mapMulti","filter"],"records":[[0,2297,31],[0,2298,50],[1,2298,50],[2,2299,351]],"truth":[-1,-1,1,2]} +{"ops":["skip","sorted","limit"],"records":[[0,2300,172],[0,2301,161],[1,2301,161],[0,2302,2],[1,2302,2],[2,2301,161],[3,2301,161],[2,2302,2],[3,2302,2]],"truth":[-1,-1,1,-1,3,2,5,4,7]} +{"ops":["filter","mapMulti","sorted"],"records":[[0,2303,5],[0,2304,4],[1,2304,4],[2,2312,4],[0,2305,-1],[0,2306,5],[1,2306,5],[2,2313,5],[2,2314,4],[0,2307,1],[0,2308,2],[1,2308,2],[2,2315,2],[2,2316,1],[0,2309,0],[0,2310,5],[1,2310,5],[2,2317,5],[2,2318,4],[0,2311,2],[3,2316,1],[3,2315,2],[3,2312,4],[3,2314,4],[3,2318,4],[3,2313,5],[3,2317,5]],"truth":[-1,-1,1,2,-1,-1,5,6,6,-1,-1,10,11,11,-1,-1,15,16,16,-1,13,12,3,8,18,7,17]} +{"ops":["takeWhile"],"records":[],"truth":[]} +{"ops":["filter","sorted"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,2319,0],[1,2319,0],[0,2320,1],[0,2321,3]],"truth":[-1,0,-1,-1]} +{"ops":["peek","dropWhile","skip"],"records":[[0,2322,317],[1,2322,317],[2,2322,317],[3,2322,317],[0,2323,430],[1,2323,430],[2,2323,430],[3,2323,430],[0,2324,193],[1,2324,193],[2,2324,193],[3,2324,193],[0,2325,256],[1,2325,256],[2,2325,256],[3,2325,256],[0,2326,374],[1,2326,374],[2,2326,374],[3,2326,374],[0,2327,84],[1,2327,84],[2,2327,84],[3,2327,84],[0,2328,119],[1,2328,119],[2,2328,119],[3,2328,119]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,-1,16,17,18,-1,20,21,22,-1,24,25,26]} +{"ops":["takeWhile","peek","sorted","distinct"],"records":[[0,2329,23],[1,2329,23],[2,2329,23],[3,2329,23],[4,2329,23]],"truth":[-1,0,1,2,3]} +{"ops":["mapMulti","filter"],"records":[],"truth":[]} +{"ops":["sorted"],"records":[[0,2330,107],[0,2331,199],[0,2332,428],[0,2333,16],[0,2334,255],[0,2335,-53],[0,2336,384],[0,2337,401],[1,2332,428],[1,2337,401],[1,2336,384],[1,2334,255],[1,2331,199],[1,2330,107],[1,2333,16],[1,2335,-53]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,2,7,6,4,1,0,3,5]} +{"ops":["mapMulti","limit","limit"],"records":[[0,2338,50],[1,2345,50],[2,2345,50],[3,2345,50],[1,2346,49],[2,2346,49],[3,2346,49]],"truth":[-1,0,1,2,0,4,5]} +{"ops":["sorted","skip","limit","takeWhile"],"records":[[0,2347,3],[1,2347,3],[2,2347,3],[3,2347,3]],"truth":[-1,0,1,2]} +{"ops":["filter","mapMulti","filter","flatMap"],"records":[[0,2348,-105],[0,2349,365],[0,2350,237],[0,2351,141],[0,2352,-106],[1,2352,-106],[2,2353,-106],[2,2354,-107],[3,2354,-107],[4,2355,-107]],"truth":[-1,-1,-1,-1,-1,4,5,5,7,8]} +{"ops":["sorted","filter","filter","filter"],"records":[[0,2356,366],[0,2357,112],[0,2358,-25],[0,2359,386],[0,2360,151],[1,2358,-25],[1,2357,112],[2,2357,112],[1,2360,151],[1,2356,366],[2,2356,366],[3,2356,366],[4,2356,366],[1,2359,386],[2,2359,386]],"truth":[-1,-1,-1,-1,-1,2,1,6,4,0,9,10,11,3,13]} +{"ops":["takeWhile"],"records":[],"truth":[]} +{"ops":["sorted"],"records":[[0,2361,3],[0,2362,1],[0,2363,4],[1,2362,1],[1,2361,3],[1,2363,4]],"truth":[-1,-1,-1,1,0,2]} +{"ops":["map"],"records":[[0,2364,1],[1,2365,5]],"truth":[-1,0]} +{"ops":["dropWhile"],"records":[[0,2366,-1],[0,2367,5],[1,2367,5],[0,2368,4],[1,2368,4]],"truth":[-1,-1,1,-1,3]} +{"ops":["filter"],"records":[[0,2369,2],[0,2370,347],[1,2370,347],[0,2371,449]],"truth":[-1,-1,1,-1]} +{"ops":["filter"],"records":[[0,2372,3],[0,2373,2],[1,2373,2],[0,2374,1],[0,2375,1],[0,2376,5],[0,2377,1],[0,2378,0],[1,2378,0]],"truth":[-1,-1,1,-1,-1,-1,-1,-1,7]} +{"ops":["map"],"records":[[0,2379,5],[1,2388,4],[0,2380,4],[1,2389,4],[0,2381,3],[1,2390,4],[0,2382,1],[1,2391,4],[0,2383,3],[1,2392,4],[0,2384,4],[1,2393,4],[0,2385,5],[1,2394,4],[0,2386,3],[1,2395,4],[0,2387,4],[1,2396,4]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["takeWhile","dropWhile"],"records":[[0,2397,5]],"truth":[-1]} +{"ops":["filter","sorted","skip"],"records":[[0,2403,2],[0,2404,-1],[1,2404,-1],[0,2405,-1],[0,2406,2],[1,2406,2],[2,2404,-1],[2,2406,2],[3,2406,2]],"truth":[-1,-1,1,-1,-1,4,2,5,7]} +{"ops":["takeWhile","dropWhile","distinct","peek"],"records":[[0,2407,3]],"truth":[-1]} +{"ops":["skip","peek","distinct"],"records":[[0,2410,2],[1,2410,2],[2,2410,2],[3,2410,2],[0,2411,3],[1,2411,3],[2,2411,3],[3,2411,3],[0,2412,5],[1,2412,5],[2,2412,5],[3,2412,5],[0,2413,4],[1,2413,4],[2,2413,4],[3,2413,4]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14]} +{"ops":["limit"],"records":[[0,2414,2],[1,2414,2],[0,2415,3],[1,2415,3]],"truth":[-1,0,-1,2]} +{"ops":["sorted","sorted","sorted"],"records":[[0,2416,3],[0,2417,3],[0,2418,3],[0,2419,3],[1,2416,3],[1,2417,3],[1,2418,3],[1,2419,3],[2,2416,3],[2,2417,3],[2,2418,3],[2,2419,3],[3,2416,3],[3,2417,3],[3,2418,3],[3,2419,3]],"truth":[-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11]} +{"ops":["takeWhile","sorted"],"records":[[0,2420,4]],"truth":[-1]} +{"ops":["sorted","distinct"],"records":[[0,2422,82],[0,2423,423],[0,2424,146],[0,2425,-1],[0,2426,-107],[0,2427,164],[1,2423,423],[2,2423,423],[1,2427,164],[2,2427,164],[1,2424,146],[2,2424,146],[1,2422,82],[2,2422,82],[1,2425,-1],[2,2425,-1],[1,2426,-107],[2,2426,-107]],"truth":[-1,-1,-1,-1,-1,-1,1,6,5,8,2,10,0,12,3,14,4,16]} +{"ops":["sorted"],"records":[],"truth":[]} +{"ops":["sorted","takeWhile"],"records":[[0,2428,120],[0,2429,185],[0,2430,-78],[0,2431,1],[0,2432,428],[1,2432,428]],"truth":[-1,-1,-1,-1,-1,4]} +{"ops":["filter"],"records":[],"truth":[]} +{"ops":["sorted","mapMulti"],"records":[[0,2433,156],[0,2434,236],[0,2435,242],[0,2436,295],[0,2437,-20],[0,2438,59],[0,2439,237],[1,2436,295],[2,2440,295],[1,2435,242],[2,2441,242],[2,2442,241],[1,2439,237],[1,2434,236],[2,2443,236],[2,2444,235],[1,2433,156],[1,2438,59],[2,2445,59],[2,2446,58],[1,2437,-20],[2,2447,-20]],"truth":[-1,-1,-1,-1,-1,-1,-1,3,7,2,9,9,6,1,13,13,0,5,17,17,4,20]} +{"ops":["map","filter"],"records":[[0,2448,396],[1,2451,368],[0,2449,365],[1,2452,151],[2,2452,151],[0,2450,-46],[1,2453,279]],"truth":[-1,0,-1,2,3,-1,5]} +{"ops":["limit","map"],"records":[[0,2454,409],[1,2454,409],[2,2462,-139],[0,2455,90],[1,2455,90],[2,2463,32],[0,2456,110],[1,2456,110],[2,2464,172],[0,2457,279],[1,2457,279],[2,2465,153],[0,2458,1],[1,2458,1],[2,2466,10]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13]} +{"ops":["filter","takeWhile","takeWhile","peek"],"records":[],"truth":[]} +{"ops":["skip","filter","flatMap"],"records":[[0,2467,242],[0,2468,-75],[0,2469,433],[1,2469,433],[0,2470,242],[1,2470,242],[2,2470,242],[3,2476,242],[3,2477,243],[0,2471,228],[1,2471,228],[2,2471,228],[0,2472,261],[1,2472,261],[0,2473,-147],[1,2473,-147],[0,2474,77],[1,2474,77],[0,2475,-17],[1,2475,-17]],"truth":[-1,-1,-1,2,-1,4,5,6,6,-1,9,10,-1,12,-1,14,-1,16,-1,18]} +{"ops":["filter","filter","mapMulti"],"records":[[0,2478,250],[0,2479,376],[1,2479,376],[2,2479,376],[3,2485,376],[0,2480,199],[0,2481,332],[1,2481,332],[2,2481,332],[3,2486,332],[3,2487,331],[0,2482,233],[0,2483,-14],[1,2483,-14],[2,2483,-14],[3,2488,-14],[0,2484,178]],"truth":[-1,-1,1,2,3,-1,-1,6,7,8,8,-1,-1,12,13,14,-1]} +{"ops":["distinct","flatMap","limit","dropWhile"],"records":[[0,2489,3],[1,2489,3],[0,2490,3],[0,2491,4],[1,2491,4],[2,2497,4],[3,2497,4],[4,2497,4],[0,2492,0],[1,2492,0],[0,2493,5],[1,2493,5],[2,2498,5],[3,2498,5],[4,2498,5]],"truth":[-1,0,-1,-1,3,4,5,6,-1,8,-1,10,11,12,13]} +{"ops":["skip"],"records":[[0,2499,344],[1,2499,344],[0,2500,55],[1,2500,55],[0,2501,113],[1,2501,113],[0,2502,369],[1,2502,369]],"truth":[-1,0,-1,2,-1,4,-1,6]} +{"ops":["takeWhile","sorted","distinct","mapMulti"],"records":[[0,2503,-1],[1,2503,-1],[0,2504,1],[1,2504,1],[0,2505,2],[2,2504,1],[3,2504,1],[4,2507,1],[2,2503,-1],[3,2503,-1],[4,2508,-1],[4,2509,5]],"truth":[-1,0,-1,2,-1,3,5,6,1,8,9,9]} +{"ops":["sorted","sorted"],"records":[[0,2510,112],[0,2511,137],[0,2512,-9],[0,2513,66],[1,2512,-9],[1,2513,66],[1,2510,112],[1,2511,137],[2,2511,137],[2,2510,112],[2,2513,66],[2,2512,-9]],"truth":[-1,-1,-1,-1,2,3,0,1,7,6,5,4]} +{"ops":["limit","flatMap"],"records":[[0,2514,5],[1,2514,5],[2,2522,5],[2,2523,-1],[0,2515,4],[1,2515,4],[2,2524,4]],"truth":[-1,0,1,1,-1,4,5]} +{"ops":["skip","peek"],"records":[[0,2525,-66],[0,2526,345]],"truth":[-1,-1]} +{"ops":["dropWhile","filter","map","map"],"records":[[0,2527,79],[1,2527,79],[0,2528,-106],[1,2528,-106],[2,2528,-106],[3,2533,-132],[4,2534,279],[0,2529,327],[1,2529,327],[0,2530,401],[1,2530,401],[2,2530,401],[3,2535,412],[4,2536,-120],[0,2531,409],[1,2531,409],[0,2532,380],[1,2532,380],[2,2532,380],[3,2537,265],[4,2538,53]],"truth":[-1,0,-1,2,3,4,5,-1,7,-1,9,10,11,12,-1,14,-1,16,17,18,19]} +{"ops":["sorted"],"records":[[0,2539,0],[1,2539,0]],"truth":[-1,0]} +{"ops":["filter"],"records":[[0,2540,4],[1,2540,4]],"truth":[-1,0]} +{"ops":["map","filter","sorted"],"records":[[0,2541,0],[1,2548,2],[2,2548,2],[0,2542,1],[1,2549,2],[2,2549,2],[0,2543,-1],[1,2550,2],[2,2550,2],[0,2544,5],[1,2551,2],[2,2551,2],[0,2545,0],[1,2552,2],[2,2552,2],[0,2546,5],[1,2553,2],[2,2553,2],[0,2547,3],[1,2554,2],[2,2554,2],[3,2548,2],[3,2549,2],[3,2550,2],[3,2551,2],[3,2552,2],[3,2553,2],[3,2554,2]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16,-1,18,19,2,5,8,11,14,17,20]} +{"ops":["peek","limit","filter"],"records":[[0,2555,298],[1,2555,298],[2,2555,298],[3,2555,298]],"truth":[-1,0,1,2]} +{"ops":["dropWhile"],"records":[[0,2556,5],[1,2556,5],[0,2557,3],[1,2557,3],[0,2558,1],[1,2558,1],[0,2559,2],[1,2559,2],[0,2560,4],[1,2560,4],[0,2561,2],[1,2561,2],[0,2562,0],[1,2562,0],[0,2563,-1],[1,2563,-1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14]} +{"ops":["takeWhile"],"records":[[0,2564,0],[1,2564,0]],"truth":[-1,0]} +{"ops":["sorted","takeWhile","map"],"records":[],"truth":[]} +{"ops":["dropWhile","takeWhile","limit","filter"],"records":[[0,2565,1],[1,2565,1],[2,2565,1],[3,2565,1]],"truth":[-1,0,1,2]} +{"ops":["flatMap","takeWhile","limit"],"records":[[0,2571,238],[1,2580,238]],"truth":[-1,0]} +{"ops":["sorted","sorted","flatMap","sorted"],"records":[[0,2581,3],[0,2582,5],[1,2581,3],[1,2582,5],[2,2581,3],[2,2582,5],[3,2583,5],[3,2584,-1],[4,2584,-1],[4,2583,5]],"truth":[-1,-1,0,1,2,3,5,5,7,6]} +{"ops":["sorted"],"records":[[0,2585,-136],[0,2586,282],[0,2587,72],[0,2588,-50],[1,2585,-136],[1,2588,-50],[1,2587,72],[1,2586,282]],"truth":[-1,-1,-1,-1,0,3,2,1]} +{"ops":["filter","sorted","distinct","peek"],"records":[[0,2589,271],[0,2590,383],[1,2590,383],[2,2590,383],[3,2590,383],[4,2590,383]],"truth":[-1,-1,1,2,3,4]} +{"ops":["filter","distinct","sorted","limit"],"records":[[0,2591,1],[0,2592,1],[0,2593,-1],[0,2594,3],[0,2595,3],[0,2596,4],[1,2596,4],[2,2596,4],[3,2596,4],[4,2596,4]],"truth":[-1,-1,-1,-1,-1,-1,5,6,7,8]} +{"ops":["peek","filter"],"records":[[0,2597,1],[1,2597,1],[0,2598,-1],[1,2598,-1],[0,2599,0],[1,2599,0],[2,2599,0],[0,2600,-1],[1,2600,-1],[0,2601,0],[1,2601,0],[2,2601,0],[0,2602,4],[1,2602,4],[2,2602,4]],"truth":[-1,0,-1,2,-1,4,5,-1,7,-1,9,10,-1,12,13]} +{"ops":["map","map"],"records":[[0,2603,281],[1,2611,167],[2,2612,-33],[0,2604,76],[1,2613,-66],[2,2614,139],[0,2605,80],[1,2615,-38],[2,2616,335],[0,2606,175],[1,2617,26],[2,2618,182],[0,2607,-143],[1,2619,204],[2,2620,226],[0,2608,157],[1,2621,-100],[2,2622,-99],[0,2609,183],[1,2623,82],[2,2624,-27],[0,2610,322],[1,2625,-147],[2,2626,173]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10,-1,12,13,-1,15,16,-1,18,19,-1,21,22]} +{"ops":["distinct","limit","peek"],"records":[[0,2627,4],[1,2627,4],[2,2627,4],[3,2627,4],[0,2628,2],[1,2628,2],[2,2628,2],[3,2628,2]],"truth":[-1,0,1,2,-1,4,5,6]} +{"ops":["filter"],"records":[[0,2633,246],[0,2634,16],[1,2634,16],[0,2635,115],[0,2636,321],[1,2636,321],[0,2637,356],[0,2638,191],[1,2638,191],[0,2639,296],[0,2640,264],[1,2640,264],[0,2641,-3]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,-1,10,-1]} +{"ops":["dropWhile","map","filter","filter"],"records":[[0,2642,3],[1,2642,3],[2,2645,2],[0,2643,1],[1,2643,1],[2,2646,2],[3,2646,2],[0,2644,1],[1,2644,1],[2,2647,2]],"truth":[-1,0,1,-1,3,4,5,-1,7,8]} +{"ops":["distinct","filter"],"records":[[0,2648,414],[1,2648,414],[0,2649,342],[1,2649,342],[2,2649,342],[0,2650,441],[1,2650,441],[0,2651,58],[1,2651,58],[2,2651,58]],"truth":[-1,0,-1,2,3,-1,5,-1,7,8]} +{"ops":["peek","mapMulti"],"records":[[0,2652,-39],[1,2652,-39]],"truth":[-1,0]} +{"ops":["distinct","filter"],"records":[[0,2653,316],[1,2653,316],[0,2654,-46],[1,2654,-46],[2,2654,-46],[0,2655,-47],[1,2655,-47],[0,2656,185],[1,2656,185],[2,2656,185],[0,2657,-130],[1,2657,-130],[0,2658,17],[1,2658,17],[2,2658,17],[0,2659,292],[1,2659,292],[0,2660,275],[1,2660,275],[2,2660,275]],"truth":[-1,0,-1,2,3,-1,5,-1,7,8,-1,10,-1,12,13,-1,15,-1,17,18]} +{"ops":["filter"],"records":[[0,2661,0],[1,2661,0],[0,2662,-1],[0,2663,4],[1,2663,4],[0,2664,4],[1,2664,4]],"truth":[-1,0,-1,-1,3,-1,5]} +{"ops":["takeWhile","filter"],"records":[[0,2665,404]],"truth":[-1]} +{"ops":["limit","limit"],"records":[[0,2666,5],[1,2666,5],[2,2666,5],[0,2667,2],[1,2667,2],[2,2667,2],[0,2668,1],[1,2668,1],[2,2668,1]],"truth":[-1,0,1,-1,3,4,-1,6,7]} +{"ops":["dropWhile","map"],"records":[[0,2670,252],[1,2670,252],[2,2674,-31],[0,2671,380],[1,2671,380],[2,2675,264],[0,2672,-103],[1,2672,-103],[2,2676,-112],[0,2673,57],[1,2673,57],[2,2677,407]],"truth":[-1,0,1,-1,3,4,-1,6,7,-1,9,10]} +{"ops":["dropWhile","limit"],"records":[[0,2678,-48],[0,2679,356],[1,2679,356],[2,2679,356],[0,2680,372],[1,2680,372],[2,2680,372]],"truth":[-1,-1,1,2,-1,4,5]} +{"ops":["peek","distinct","map"],"records":[],"truth":[]} +{"ops":["sorted"],"records":[[0,2682,2],[0,2683,4],[0,2684,5],[1,2684,5],[1,2683,4],[1,2682,2]],"truth":[-1,-1,-1,2,1,0]} +{"ops":["peek","dropWhile","filter"],"records":[[0,2685,0],[1,2685,0]],"truth":[-1,0]} +{"ops":["distinct"],"records":[[0,2686,1],[1,2686,1],[0,2687,1],[0,2688,2],[1,2688,2],[0,2689,1],[0,2690,4],[1,2690,4],[0,2691,-1],[1,2691,-1],[0,2692,5],[1,2692,5],[0,2693,0],[1,2693,0],[0,2694,3],[1,2694,3]],"truth":[-1,0,-1,-1,3,-1,-1,6,-1,8,-1,10,-1,12,-1,14]} +{"ops":["filter","takeWhile"],"records":[[0,2695,77]],"truth":[-1]} +{"ops":["filter","filter"],"records":[[0,2696,4],[1,2696,4],[2,2696,4],[0,2697,2],[1,2697,2],[2,2697,2],[0,2698,1],[0,2699,5],[0,2700,2],[1,2700,2],[2,2700,2],[0,2701,1]],"truth":[-1,0,1,-1,3,4,-1,-1,-1,8,9,-1]} +{"ops":["skip","takeWhile","takeWhile","map"],"records":[[0,2702,198],[1,2702,198]],"truth":[-1,0]} +{"ops":["dropWhile","peek","flatMap"],"records":[[0,2711,221],[1,2711,221],[2,2711,221],[3,2715,221],[3,2716,222],[0,2712,-64],[1,2712,-64],[2,2712,-64],[3,2717,-64],[3,2718,-63],[0,2713,8],[1,2713,8],[2,2713,8],[3,2719,8],[3,2720,9],[0,2714,439],[1,2714,439],[2,2714,439],[3,2721,439]],"truth":[-1,0,1,2,2,-1,5,6,7,7,-1,10,11,12,12,-1,15,16,17]} +{"ops":["filter","skip","filter","limit"],"records":[[0,2722,-124],[1,2722,-124],[2,2722,-124],[3,2722,-124],[4,2722,-124],[0,2723,88],[1,2723,88],[2,2723,88],[3,2723,88],[4,2723,88],[0,2724,34],[1,2724,34],[2,2724,34],[3,2724,34],[4,2724,34],[0,2725,-143],[0,2726,170],[1,2726,170],[2,2726,170],[3,2726,170],[4,2726,170]],"truth":[-1,0,1,2,3,-1,5,6,7,8,-1,10,11,12,13,-1,-1,16,17,18,19]} +{"ops":["filter","sorted"],"records":[[0,2730,0],[0,2731,1],[1,2731,1],[0,2732,2],[0,2733,0],[1,2733,0],[0,2734,0],[0,2735,4],[1,2735,4],[0,2736,2],[2,2735,4],[2,2731,1],[2,2733,0]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,8,2,5]} +{"ops":["distinct","filter","takeWhile","mapMulti"],"records":[],"truth":[]} +{"ops":["filter"],"records":[[0,2737,5],[0,2738,3],[1,2738,3]],"truth":[-1,-1,1]} +{"ops":["map"],"records":[[0,2739,28],[1,2747,202],[0,2740,356],[1,2748,94],[0,2741,39],[1,2749,279],[0,2742,353],[1,2750,73],[0,2743,-26],[1,2751,425],[0,2744,76],[1,2752,-63],[0,2745,21],[1,2753,153],[0,2746,-61],[1,2754,180]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14]} +{"ops":["mapMulti","takeWhile","mapMulti","mapMulti"],"records":[[0,2755,-1],[1,2761,-1],[2,2761,-1],[3,2762,-1],[4,2763,-1],[4,2764,5],[3,2765,5],[4,2766,5],[4,2767,4],[1,2768,5]],"truth":[-1,0,1,2,3,3,2,6,6,0]} +{"ops":["sorted"],"records":[[0,2769,2],[0,2770,1],[0,2771,4],[1,2770,1],[1,2769,2],[1,2771,4]],"truth":[-1,-1,-1,1,0,2]} +{"ops":["distinct","distinct","distinct","sorted"],"records":[[0,2772,-141],[1,2772,-141],[2,2772,-141],[3,2772,-141],[0,2773,342],[1,2773,342],[2,2773,342],[3,2773,342],[0,2774,-24],[1,2774,-24],[2,2774,-24],[3,2774,-24],[0,2775,54],[1,2775,54],[2,2775,54],[3,2775,54],[0,2776,232],[1,2776,232],[2,2776,232],[3,2776,232],[0,2777,40],[1,2777,40],[2,2777,40],[3,2777,40],[4,2773,342],[4,2776,232],[4,2775,54],[4,2777,40],[4,2774,-24],[4,2772,-141]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14,-1,16,17,18,-1,20,21,22,7,19,15,23,11,3]} +{"ops":["dropWhile"],"records":[[0,2778,-30]],"truth":[-1]} +{"ops":["sorted","mapMulti","sorted","sorted"],"records":[],"truth":[]} +{"ops":["takeWhile","filter","sorted"],"records":[[0,2779,2]],"truth":[-1]} +{"ops":["map"],"records":[[0,2788,-1],[1,2796,1],[0,2789,4],[1,2797,1],[0,2790,1],[1,2798,1],[0,2791,0],[1,2799,1],[0,2792,4],[1,2800,1],[0,2793,2],[1,2801,1],[0,2794,2],[1,2802,1],[0,2795,2],[1,2803,1]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14]} +{"ops":["dropWhile","sorted","flatMap","takeWhile"],"records":[[0,2804,436],[1,2804,436],[0,2805,2],[1,2805,2],[0,2806,423],[1,2806,423],[0,2807,228],[1,2807,228],[0,2808,55],[1,2808,55],[2,2805,2],[3,2809,2],[4,2809,2],[3,2810,3],[4,2810,3],[2,2808,55],[3,2811,55],[4,2811,55],[2,2807,228],[2,2806,423],[2,2804,436],[3,2812,436]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,3,10,11,10,13,9,15,16,7,5,1,20]} +{"ops":["mapMulti","flatMap"],"records":[[0,2813,431],[1,2820,431],[2,2821,431],[2,2822,432],[1,2823,430],[2,2824,430],[0,2814,143],[1,2825,143],[2,2826,143],[2,2827,144],[1,2828,142],[2,2829,142],[0,2815,330],[0,2816,131],[1,2830,131],[2,2831,131],[2,2832,132],[1,2833,130],[2,2834,130],[0,2817,196],[1,2835,196],[2,2836,196],[0,2818,-122],[1,2837,-122],[2,2838,-122],[0,2819,-107],[1,2839,-107],[2,2840,-107]],"truth":[-1,0,1,1,0,4,-1,6,7,7,6,10,-1,-1,13,14,14,13,17,-1,19,20,-1,22,23,-1,25,26]} +{"ops":["filter","sorted","sorted","limit"],"records":[[0,2841,388],[1,2841,388],[0,2842,427],[0,2843,308],[1,2843,308],[0,2844,-84],[1,2844,-84],[0,2845,448],[1,2845,448],[2,2844,-84],[2,2843,308],[2,2841,388],[2,2845,448],[3,2845,448],[4,2845,448],[3,2841,388],[4,2841,388],[3,2843,308],[4,2843,308]],"truth":[-1,0,-1,-1,3,-1,5,-1,7,6,4,1,8,12,13,11,15,10,17]} +{"ops":["sorted","sorted","sorted"],"records":[[0,2846,5],[0,2847,5],[0,2848,0],[0,2849,2],[0,2850,2],[0,2851,4],[0,2852,1],[0,2853,-1],[1,2853,-1],[1,2848,0],[1,2852,1],[1,2849,2],[1,2850,2],[1,2851,4],[1,2846,5],[1,2847,5],[2,2853,-1],[2,2848,0],[2,2852,1],[2,2849,2],[2,2850,2],[2,2851,4],[2,2846,5],[2,2847,5],[3,2853,-1],[3,2848,0],[3,2852,1],[3,2849,2],[3,2850,2],[3,2851,4],[3,2846,5],[3,2847,5]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,7,2,6,3,4,5,0,1,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]} +{"ops":["limit","sorted","map","filter"],"records":[[0,2854,0],[1,2854,0],[0,2855,0],[1,2855,0],[2,2854,0],[3,2858,4],[4,2858,4],[2,2855,0],[3,2859,4],[4,2859,4]],"truth":[-1,0,-1,2,1,4,5,3,7,8]} +{"ops":["filter","skip","filter","sorted"],"records":[[0,2860,110],[0,2861,200],[1,2861,200],[0,2862,-103],[0,2863,190],[1,2863,190],[0,2864,432],[0,2865,316],[1,2865,316],[2,2865,316]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,8]} +{"ops":["sorted","dropWhile","filter"],"records":[[0,2866,1],[0,2867,0],[0,2868,3],[0,2869,1],[0,2870,4],[0,2871,-1],[0,2872,3],[1,2871,-1],[1,2867,0],[1,2866,1],[2,2866,1],[1,2869,1],[2,2869,1],[3,2869,1],[1,2868,3],[2,2868,3],[1,2872,3],[2,2872,3],[3,2872,3],[1,2870,4],[2,2870,4]],"truth":[-1,-1,-1,-1,-1,-1,-1,5,1,0,9,3,11,12,2,14,6,16,17,4,19]} +{"ops":["skip","sorted"],"records":[[0,2873,-44],[0,2874,226],[0,2875,-60],[1,2875,-60],[0,2876,263],[1,2876,263],[0,2877,167],[1,2877,167],[0,2878,-132],[1,2878,-132],[0,2879,147],[1,2879,147],[0,2880,159],[1,2880,159],[0,2881,137],[1,2881,137],[2,2876,263],[2,2877,167],[2,2880,159],[2,2879,147],[2,2881,137],[2,2875,-60],[2,2878,-132]],"truth":[-1,-1,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,5,7,13,11,15,3,9]} +{"ops":["dropWhile"],"records":[[0,2882,39]],"truth":[-1]} +{"ops":["skip"],"records":[[0,2883,139],[0,2884,88],[1,2884,88],[0,2885,130],[1,2885,130],[0,2886,250],[1,2886,250],[0,2887,409],[1,2887,409],[0,2888,-115],[1,2888,-115]],"truth":[-1,-1,1,-1,3,-1,5,-1,7,-1,9]} +{"ops":["flatMap","sorted","map"],"records":[[0,2889,445],[1,2897,445],[0,2890,76],[1,2898,76],[0,2891,-89],[1,2899,-89],[0,2892,122],[1,2900,122],[1,2901,123],[0,2893,417],[0,2894,-149],[1,2902,-149],[0,2895,213],[0,2896,1],[1,2903,1],[2,2902,-149],[3,2904,162],[2,2899,-89],[3,2905,-19],[2,2903,1],[3,2906,10],[2,2898,76],[3,2907,-66],[2,2900,122],[3,2908,256],[2,2901,123],[3,2909,263],[2,2897,445],[3,2910,113]],"truth":[-1,0,-1,2,-1,4,-1,6,6,-1,-1,10,-1,-1,13,11,15,5,17,14,19,3,21,7,23,8,25,1,27]} +{"ops":["mapMulti","limit","takeWhile"],"records":[[0,2911,1],[1,2917,1],[2,2917,1],[3,2917,1],[0,2912,3],[0,2913,0],[0,2914,2],[1,2918,2],[2,2918,2],[1,2919,1],[2,2919,1]],"truth":[-1,0,1,2,-1,-1,-1,6,7,6,9]} +{"ops":["takeWhile","sorted"],"records":[[0,2920,229]],"truth":[-1]} +{"ops":["sorted","map"],"records":[[0,2924,31],[1,2924,31],[2,2925,221]],"truth":[-1,0,1]} +{"ops":["filter","filter","sorted","limit"],"records":[],"truth":[]} +{"ops":["skip","sorted"],"records":[[0,2926,367],[1,2926,367],[0,2927,138],[1,2927,138],[0,2928,210],[1,2928,210],[2,2927,138],[2,2928,210],[2,2926,367]],"truth":[-1,0,-1,2,-1,4,3,5,1]} +{"ops":["filter","mapMulti","sorted","filter"],"records":[[0,2929,3],[0,2930,4],[1,2930,4],[2,2937,4],[0,2931,0],[1,2931,0],[0,2932,-1],[0,2933,1],[0,2934,5],[0,2935,4],[1,2935,4],[2,2938,4],[0,2936,-1],[3,2937,4],[4,2937,4],[3,2938,4],[4,2938,4]],"truth":[-1,-1,1,2,-1,4,-1,-1,-1,-1,9,10,-1,3,13,11,15]} +{"ops":["sorted"],"records":[[0,2939,0],[1,2939,0]],"truth":[-1,0]} +{"ops":["filter","sorted","distinct"],"records":[[0,2940,0],[0,2941,-1],[1,2941,-1],[0,2942,5],[0,2943,1],[1,2943,1],[0,2944,-1],[0,2945,5],[1,2945,5],[0,2946,1],[2,2943,1],[3,2943,1],[2,2941,-1],[3,2941,-1],[2,2945,5],[3,2945,5]],"truth":[-1,-1,1,-1,-1,4,-1,-1,7,-1,5,10,2,12,8,14]} +{"ops":["sorted"],"records":[[0,2947,282],[1,2947,282]],"truth":[-1,0]} +{"ops":["mapMulti","peek","mapMulti"],"records":[],"truth":[]} +{"ops":["map"],"records":[[0,2948,42],[1,2953,302],[0,2949,124],[1,2954,275],[0,2950,-30],[1,2955,399],[0,2951,58],[1,2956,414],[0,2952,325],[1,2957,-121]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8]} +{"ops":["mapMulti","filter","sorted","sorted"],"records":[[0,2958,5],[1,2967,5],[1,2968,4],[2,2968,4],[0,2959,2],[1,2969,2],[2,2969,2],[1,2970,1],[0,2960,-1],[1,2971,-1],[1,2972,5],[0,2961,1],[1,2973,1],[0,2962,-1],[1,2974,-1],[1,2975,5],[0,2963,1],[1,2976,1],[0,2964,1],[1,2977,1],[0,2965,1],[1,2978,1],[0,2966,5],[1,2979,5],[1,2980,4],[2,2980,4],[3,2968,4],[3,2980,4],[3,2969,2],[4,2968,4],[4,2980,4],[4,2969,2]],"truth":[-1,0,0,2,-1,4,5,4,-1,8,8,-1,11,-1,13,13,-1,16,-1,18,-1,20,-1,22,22,24,3,25,6,26,27,28]} +{"ops":["dropWhile","sorted","limit","dropWhile"],"records":[[0,2981,-42]],"truth":[-1]} +{"ops":["distinct","distinct"],"records":[[0,2982,0],[1,2982,0],[2,2982,0],[0,2983,3],[1,2983,3],[2,2983,3]],"truth":[-1,0,1,-1,3,4]} +{"ops":["distinct","takeWhile"],"records":[],"truth":[]} +{"ops":["peek"],"records":[[0,2984,1],[1,2984,1],[0,2985,1],[1,2985,1],[0,2986,5],[1,2986,5],[0,2987,-1],[1,2987,-1],[0,2988,2],[1,2988,2],[0,2989,5],[1,2989,5],[0,2990,-1],[1,2990,-1],[0,2991,-1],[1,2991,-1],[0,2992,4],[1,2992,4]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10,-1,12,-1,14,-1,16]} +{"ops":["limit","skip","limit"],"records":[[0,2993,194],[1,2993,194],[2,2993,194],[3,2993,194],[0,2994,240],[1,2994,240],[2,2994,240],[3,2994,240],[0,2995,160],[1,2995,160],[2,2995,160],[3,2995,160],[0,2996,374],[1,2996,374],[2,2996,374],[3,2996,374]],"truth":[-1,0,1,2,-1,4,5,6,-1,8,9,10,-1,12,13,14]} +{"ops":["limit","sorted","sorted","takeWhile"],"records":[],"truth":[]} +{"ops":["limit","distinct","sorted"],"records":[[0,2998,3],[1,2998,3],[2,2998,3],[0,2999,1],[1,2999,1],[2,2999,1],[3,2998,3],[3,2999,1]],"truth":[-1,0,1,-1,3,4,2,5]} +{"ops":["dropWhile"],"records":[],"truth":[]} +{"ops":["skip","skip"],"records":[[0,3000,4],[0,3001,-1],[1,3001,-1],[0,3002,-1],[1,3002,-1],[2,3002,-1]],"truth":[-1,-1,1,-1,3,4]} +{"ops":["sorted","filter","filter"],"records":[[0,3003,3],[0,3004,5],[0,3005,2],[0,3006,5],[0,3007,4],[0,3008,1],[0,3009,0],[0,3010,5],[0,3011,3],[1,3003,3],[1,3009,0],[2,3009,0],[1,3011,3],[1,3007,4],[2,3007,4],[3,3007,4],[1,3008,1],[1,3004,5],[2,3004,5],[1,3005,2],[1,3006,5],[2,3006,5],[3,3006,5],[1,3010,5]],"truth":[-1,-1,-1,-1,-1,-1,-1,-1,-1,0,6,10,8,4,13,14,5,1,17,2,3,20,21,7]} +{"ops":["sorted","mapMulti","distinct","map"],"records":[[0,3012,4],[0,3013,-1],[0,3014,-1],[0,3015,3],[1,3015,3],[1,3012,4],[2,3016,4],[3,3016,4],[4,3017,1],[1,3013,-1],[2,3018,-1],[3,3018,-1],[4,3019,1],[2,3020,5],[3,3020,5],[4,3021,1],[1,3014,-1],[2,3022,-1],[2,3023,5]],"truth":[-1,-1,-1,-1,3,0,5,6,7,1,9,10,11,9,13,14,2,16,16]} +{"ops":["mapMulti","mapMulti","peek","mapMulti"],"records":[[0,3024,3],[0,3025,-1],[1,3030,-1],[2,3031,-1],[3,3031,-1],[4,3032,-1],[4,3033,5],[2,3034,5],[3,3034,5],[4,3035,5],[4,3036,4],[1,3037,5],[2,3038,5],[3,3038,5],[4,3039,5],[4,3040,4],[2,3041,4],[3,3041,4],[4,3042,4],[0,3026,-1],[1,3043,-1],[2,3044,-1],[3,3044,-1],[4,3045,-1],[4,3046,5],[2,3047,5],[3,3047,5],[4,3048,5],[4,3049,4],[1,3050,5],[2,3051,5],[3,3051,5],[4,3052,5],[4,3053,4],[2,3054,4],[3,3054,4],[4,3055,4],[0,3027,5],[1,3056,5],[2,3057,5],[3,3057,5],[4,3058,5],[4,3059,4],[2,3060,4],[3,3060,4],[4,3061,4],[1,3062,4],[2,3063,4],[3,3063,4],[4,3064,4],[0,3028,5],[1,3065,5],[2,3066,5],[3,3066,5],[4,3067,5],[4,3068,4],[2,3069,4],[3,3069,4],[4,3070,4],[1,3071,4],[2,3072,4],[3,3072,4],[4,3073,4],[0,3029,0]],"truth":[-1,-1,1,2,3,4,4,2,7,8,8,1,11,12,13,13,11,16,17,-1,19,20,21,22,22,20,25,26,26,19,29,30,31,31,29,34,35,-1,37,38,39,40,40,38,43,44,37,46,47,48,-1,50,51,52,53,53,51,56,57,50,59,60,61,-1]} +{"ops":["skip","limit","map","filter"],"records":[[0,3074,121],[0,3075,-122],[1,3075,-122],[2,3075,-122],[3,3080,351],[0,3076,184],[1,3076,184],[2,3076,184],[3,3081,89],[4,3081,89],[0,3077,158],[1,3077,158],[2,3077,158],[3,3082,-93],[0,3078,211],[1,3078,211],[2,3078,211],[3,3083,278],[4,3083,278]],"truth":[-1,-1,1,2,3,-1,5,6,7,8,-1,10,11,12,-1,14,15,16,17]} +{"ops":["filter","distinct"],"records":[[0,3084,236],[0,3085,408],[1,3085,408],[2,3085,408],[0,3086,11],[0,3087,112],[1,3087,112],[2,3087,112],[0,3088,0],[0,3089,185],[1,3089,185],[2,3089,185],[0,3090,40],[0,3091,194],[1,3091,194],[2,3091,194],[0,3092,36]],"truth":[-1,-1,1,2,-1,-1,5,6,-1,-1,9,10,-1,-1,13,14,-1]} +{"ops":["limit","sorted","flatMap","dropWhile"],"records":[],"truth":[]} +{"ops":["limit","map"],"records":[[0,3093,1],[1,3093,1],[2,3094,1]],"truth":[-1,0,1]} +{"ops":["sorted"],"records":[[0,3095,-1],[0,3096,5],[0,3097,5],[1,3095,-1],[1,3096,5],[1,3097,5]],"truth":[-1,-1,-1,0,1,2]} +{"ops":["sorted"],"records":[],"truth":[]} +{"ops":["filter","mapMulti","peek"],"records":[[0,3098,362],[1,3098,362],[2,3104,362],[3,3104,362],[2,3105,361],[3,3105,361],[0,3099,99],[0,3100,-91],[0,3101,4],[1,3101,4],[2,3106,4],[3,3106,4],[0,3102,133],[0,3103,18],[1,3103,18]],"truth":[-1,0,1,2,1,4,-1,-1,-1,8,9,10,-1,-1,13]} +{"ops":["limit","sorted","filter","peek"],"records":[[0,3107,0],[1,3107,0],[0,3108,2],[1,3108,2],[2,3107,0],[2,3108,2],[3,3108,2],[4,3108,2]],"truth":[-1,0,-1,2,1,3,5,6]} +{"ops":["limit","sorted","limit","flatMap"],"records":[[0,3109,-1],[1,3109,-1],[0,3110,4],[1,3110,4],[2,3110,4],[3,3110,4],[4,3111,4],[2,3109,-1],[3,3109,-1],[4,3112,-1],[4,3113,0]],"truth":[-1,0,-1,2,3,4,5,1,7,8,8]} +{"ops":["limit"],"records":[[0,3114,5],[1,3114,5],[0,3115,-1],[1,3115,-1],[0,3116,1],[1,3116,1],[0,3117,3],[1,3117,3]],"truth":[-1,0,-1,2,-1,4,-1,6]} +{"ops":["peek"],"records":[[0,3123,274],[1,3123,274],[0,3124,119],[1,3124,119],[0,3125,255],[1,3125,255],[0,3126,-80],[1,3126,-80],[0,3127,313],[1,3127,313],[0,3128,103],[1,3128,103]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8,-1,10]} +{"ops":["mapMulti"],"records":[[0,3129,3],[0,3130,2],[1,3131,2],[1,3132,1]],"truth":[-1,-1,1,1]} +{"ops":["sorted","filter"],"records":[[0,3133,1],[0,3134,1],[0,3135,0],[0,3136,2],[0,3137,0],[1,3136,2],[2,3136,2],[1,3133,1],[1,3134,1],[1,3135,0],[2,3135,0],[1,3137,0],[2,3137,0]],"truth":[-1,-1,-1,-1,-1,3,5,0,1,2,9,4,11]} +{"ops":["distinct"],"records":[[0,3138,367],[1,3138,367],[0,3139,-75],[1,3139,-75],[0,3140,-64],[1,3140,-64],[0,3141,-54],[1,3141,-54],[0,3142,235],[1,3142,235]],"truth":[-1,0,-1,2,-1,4,-1,6,-1,8]} diff --git a/crates/ide-streams/tests/real_run.rs b/crates/ide-streams/tests/real_run.rs new file mode 100644 index 0000000000..740f227249 --- /dev/null +++ b/crates/ide-streams/tests/real_run.rs @@ -0,0 +1,386 @@ +use ide_core::{CancellationToken, LanguageId}; +use ide_language::{Syntax, SyntaxCache}; +use ide_streams::{ + BoxKind, Link, RealRunPlan, RealRunRefusal, Record, RootKind, StepKind, StepSpec, StopContext, StreamChain, + TerminalOutcome, TraceBanner, TraceRecording, TraceValue, find_chains, link_trace, real_run_plan, recorded_steps, +}; +use ide_syntax::{Snapshot, StructureService}; +use std::sync::{Arc, OnceLock}; + +const FIXTURE: &str = include_str!("fixtures/Chains.java"); + +fn service() -> &'static StructureService { + static S: OnceLock = OnceLock::new(); + S.get_or_init(|| StructureService::new(Arc::new(SyntaxCache::new(Arc::new(Syntax::new()))))) +} + +fn line_of(marker: &str) -> u32 { + let tag = format!("// {marker}"); + let found = FIXTURE.lines().position(|l| l.trim_end().ends_with(&tag)); + found.unwrap_or_else(|| panic!("no line marked {marker}")) as u32 +} + +fn chains_at(marker: &str) -> Vec { + let java = LanguageId::new("java"); + let stop = StopContext { line: line_of(marker), in_lambda: false, file_stem: "Chains" }; + let found = + find_chains(service(), &Snapshot::text(&java, FIXTURE), &stop, &CancellationToken::new()).expect("search"); + assert!(found.rejected.is_empty(), "{marker}: unexpected rejections {:?}", found.rejected); + found.chains +} + +#[track_caller] +fn only_chain(marker: &str) -> StreamChain { + let mut chains = chains_at(marker); + assert_eq!(chains.len(), 1, "{marker}: {chains:?}"); + chains.remove(0) +} + +#[track_caller] +fn plan_of(marker: &str) -> RealRunPlan { + real_run_plan(&only_chain(marker)).unwrap_or_else(|e| panic!("{marker}: {e:?}")) +} + +fn spec(name: &str, args: u8, skip: u8) -> StepSpec { + StepSpec { name: name.into(), args, skip } +} + +fn specs(steps: &[StepSpec]) -> Vec<(&str, u8, u8)> { + steps.iter().map(|s| (s.name.as_str(), s.args, s.skip)).collect() +} + +#[test] +fn plan_for_collection_chain() { + let plan = plan_of("C_PLAN_COLLECTION"); + assert_eq!(plan.root, Some(spec("stream", 0, 0))); + assert_eq!(plan.local, None); + assert_eq!(specs(&plan.steps), [("filter", 1, 0), ("map", 1, 0), ("sorted", 0, 0), ("map", 1, 0)]); + assert_eq!(plan.terminal, spec("collect", 1, 0)); + assert_eq!(plan.class_filters, ["java.util.*"]); + assert_eq!(plan.step_kinds, [StepKind::Sync, StepKind::Sync, StepKind::Reorder, StepKind::Sync]); + assert!(!plan.sequentialize); +} + +#[test] +fn plan_for_intstream_range() { + let plan = plan_of("C_PLAN_RANGE"); + assert_eq!(plan.root, Some(spec("range", 2, 0))); + assert_eq!(plan.class_filters, ["java.util.stream.*"]); + assert_eq!(plan.terminal.name, "sum"); +} + +#[test] +fn plan_for_local_root() { + let chain = only_chain("C_PLAN_LOCAL"); + assert_eq!(chain.root_kind, RootKind::Local { name: "s".into() }); + let plan = real_run_plan(&chain).unwrap(); + assert_eq!(plan.root, None); + assert_eq!(plan.local.as_deref(), Some("s")); + assert_eq!(specs(&plan.steps), [("filter", 1, 0)]); + assert_eq!(plan.class_filters, ["java.util.stream.*"]); +} + +#[test] +fn parameter_roots_are_locals() { + assert_eq!(only_chain("C_VARIABLE").root_kind, RootKind::Local { name: "given".into() }); +} + +#[test] +fn plan_refuses_roots_that_are_not_new_streams_or_locals() { + let field = only_chain("C_PLAN_FIELD"); + assert_eq!(field.root_kind, RootKind::Other); + assert_eq!(real_run_plan(&field), Err(RealRunRefusal::NotJavaStreamRoot { root: "this.items".into() })); + + let bare = only_chain("C_PLAN_FIELD_BARE"); + assert_eq!(bare.root_kind, RootKind::Other); + assert_eq!(real_run_plan(&bare), Err(RealRunRefusal::NotJavaStreamRoot { root: "items".into() })); + + let foreign = only_chain("C_FOREIGN_ROOT"); + assert_eq!(real_run_plan(&foreign), Err(RealRunRefusal::NotJavaStreamRoot { root: "repo.findAll()".into() })); +} + +#[test] +fn plan_marks_parallel() { + assert!(plan_of("C_PLAN_PARALLEL").sequentialize); + let modifiers = plan_of("C_PARALLEL"); + assert!(modifiers.sequentialize); + assert_eq!(specs(&modifiers.steps), [("sequential", 0, 0), ("map", 1, 0), ("parallel", 0, 0)]); + assert_eq!(modifiers.step_kinds, [StepKind::Sync]); +} + +#[test] +fn recorded_steps_follow_the_plan() { + let collection = only_chain("C_PLAN_COLLECTION"); + assert_eq!(recorded_steps(&collection), ["stream", "filter", "map", "sorted", "map"]); + assert_eq!(recorded_steps(&collection).len(), real_run_plan(&collection).unwrap().step_kinds.len() + 1); + let modifiers = only_chain("C_PARALLEL"); + assert_eq!(recorded_steps(&modifiers), ["parallelStream", "map"]); + assert_eq!(recorded_steps(&modifiers).len(), real_run_plan(&modifiers).unwrap().step_kinds.len() + 1); + assert_eq!(recorded_steps(&only_chain("C_PLAN_LOCAL")), ["", "filter"]); +} + +#[test] +fn skip_counts_receiver_occurrences() { + let chains = chains_at("C_PLAN_SKIP"); + let outer = chains.iter().find(|c| c.terminal.name == "count").expect("count chain"); + let plan = real_run_plan(outer).unwrap(); + assert_eq!(plan.root, Some(spec("stream", 0, 1))); + assert_eq!(specs(&plan.steps), [("filter", 1, 0)]); + + let inner = chains.iter().find(|c| c.terminal.name == "collect").expect("collect chain"); + assert_eq!(real_run_plan(inner).unwrap().root, Some(spec("stream", 0, 0))); +} + +#[test] +fn later_steps_and_terminal_never_skip() { + let plan = plan_of("C_PLAN_SAME_NAME"); + assert_eq!(specs(&plan.steps), [("map", 1, 0), ("filter", 1, 0), ("map", 1, 0)]); + assert_eq!(plan.terminal, spec("count", 0, 0)); +} + +#[test] +fn root_skip_ignores_calls_inside_lambda_bodies() { + // The first chain's lambda calls `list.stream()`, but only once its terminal runs. + let chains = chains_at("C_PLAN_LAMBDA_CALLS"); + assert_eq!(chains.len(), 2); + let second = chains.iter().find(|c| c.text.starts_with("list.stream()")).expect("second chain"); + assert_eq!(real_run_plan(second).unwrap().root, Some(spec("stream", 0, 1))); +} + +#[test] +fn root_skip_counts_earlier_sibling_chain() { + let chains = chains_at("C_PLAN_SIBLING"); + let roots: Vec<_> = chains.iter().map(|c| real_run_plan(c).unwrap().root.unwrap()).collect(); + assert_eq!(roots, [spec("stream", 0, 0), spec("stream", 0, 1)]); +} + +#[test] +fn root_skip_needs_same_arg_count() { + let chains = chains_at("C_PLAN_ARRAYS_NESTED"); + let counting = chains.iter().find(|c| c.terminal.name == "count").expect("count chain"); + // `Arrays.stream(arr)` is a different overload from the root's `stream()`. + assert_eq!(real_run_plan(counting).unwrap().root, Some(spec("stream", 0, 0))); + let inner = chains.iter().find(|c| c.terminal.name == "collect").expect("collect chain"); + assert_eq!(real_run_plan(inner).unwrap().root, Some(spec("stream", 1, 0))); +} + +#[test] +fn root_skip_counts_sibling_chain_in_if_header() { + let chains = chains_at("C_PLAN_IF_HEADER"); + let roots: Vec<_> = chains.iter().map(|c| real_run_plan(c).unwrap().root.unwrap()).collect(); + assert_eq!(roots, [spec("stream", 0, 0), spec("stream", 0, 1)]); +} + +#[test] +fn root_skip_counts_earlier_condition_of_else_if() { + let root = plan_of("C_PLAN_ELSE_IF").root.unwrap(); + assert_eq!(root, spec("stream", 0, 1)); +} + +#[test] +fn root_skip_ignores_earlier_branch_bodies() { + // The body of the first branch ran only if its condition held, and then the `else if` was never reached. + let root = plan_of("C_PLAN_ELSE_IF_BODY").root.unwrap(); + assert_eq!(root, spec("stream", 0, 0)); +} + +#[test] +fn root_skip_ignores_other_families() { + // `Optional.of` is not a stream source, so the debugger never sees it as a candidate. + assert_eq!(plan_of("C_PLAN_OTHER_FAMILY").root, Some(spec("of", 1, 0))); +} + +#[test] +fn header_chain_still_starts_at_its_own_line() { + let chain = only_chain("C_PLAN_ELSE_IF"); + assert_eq!(chain.first_line, line_of("C_PLAN_ELSE_IF")); +} + +#[test] +fn varargs_of_counts_as_one_parameter() { + assert_eq!(plan_of("C_PLAN_STREAM_OF").root, Some(spec("of", 1, 0))); +} + +#[test] +fn first_line_is_statement_start() { + let chain = only_chain("C_PLAN_FIRST_LINE"); + let start = line_of("C_PLAN_FIRST_LINE"); + assert_eq!(chain.first_line, start); + assert!(chain.range.end.line >= start + 5); + assert_eq!(real_run_plan(&chain).unwrap().first_line, start); + assert_eq!(real_run_plan(&chain).unwrap().last_line, chain.range.end.line); + + // A chain written on one line starts where its statement does. + assert_eq!(only_chain("C_PLAN_COLLECTION").first_line, line_of("C_PLAN_COLLECTION")); +} + +/// A method exit two requests match comes in one event set twice, which the bundle cannot take: +/// `java.util.*` already covers `java.util.stream.*`. +#[test] +fn class_filters_follow_the_source() { + let streams = "java.util.stream.*"; + let lines = &[streams, "java.lang.String", "java.io.BufferedReader"][..]; + let cases: [(&str, &[&str]); 12] = [ + ("C_SRC_ARRAYS", &[streams, "java.util.Arrays"]), + ("C_SRC_CHARS", &[streams, "java.lang.String", "java.lang.AbstractStringBuilder", "java.lang.CharSequence"]), + ("C_LINES_LITERAL", lines), + ("C_LINES", lines), + ("C_SRC_LINES", lines), + ("C_SRC_FILES", &[streams, "java.nio.file.Files"]), + ("C_SRC_PATTERN", &[streams, "java.util.regex.Pattern"]), + ("C_SRC_RANDOM", &["java.util.*"]), + ("C_GENERATE", &[streams]), + ("C_ITERATE_PURE", &[streams]), + ("C_PLAN_RANGE", &[streams]), + ("C_STATIC_INIT", &["java.util.*"]), + ]; + for (marker, expected) in cases { + assert_eq!(plan_of(marker).class_filters, expected, "{marker}"); + } +} + +#[test] +fn nested_collect_then_stream_plans_each_chain() { + let chains = chains_at("C_REOPEN_READER"); + let filters: Vec<_> = chains.iter().map(|c| real_run_plan(c).unwrap().class_filters).collect(); + assert_eq!( + filters, + [vec!["java.util.stream.*", "java.lang.String", "java.io.BufferedReader"], vec!["java.util.*"]] + ); +} + +#[test] +fn plan_refuses_what_the_pipeline_cannot_trace() { + let mut chain = only_chain("C_PLAN_RANGE"); + chain.terminal.role = ide_streams::OpRole::LazyTerminal; + assert_eq!(real_run_plan(&chain), Err(RealRunRefusal::LazyTerminal { op: "sum".into() })); + + let mut chain = only_chain("C_PLAN_RANGE"); + chain.ops[0].role = ide_streams::OpRole::Terminal { void: false }; + assert_eq!(real_run_plan(&chain), Err(RealRunRefusal::UnknownOperation { op: "filter".into() })); +} + +#[test] +fn plan_json_shape() { + let json = serde_json::to_value(plan_of("C_PLAN_COLLECTION")).unwrap(); + assert_eq!(json["root"], serde_json::json!({"name": "stream", "args": 0, "skip": 0})); + assert_eq!(json["local"], serde_json::Value::Null); + assert_eq!(json["classFilters"], serde_json::json!(["java.util.*"])); + assert_eq!(json["stepKinds"], serde_json::json!(["sync", "sync", "reorder", "sync"])); + assert_eq!(json["firstLine"], line_of("C_PLAN_COLLECTION")); + assert_eq!(json["lastLine"], line_of("C_PLAN_COLLECTION")); + assert_eq!(json["sequentialize"], false); + assert_eq!(json["terminal"]["name"], "collect"); + assert_eq!( + serde_json::to_value(RootKind::Local { name: "s".into() }).unwrap(), + serde_json::json!({"kind": "local", "name": "s"}) + ); + assert_eq!( + serde_json::to_value(TraceBanner::BreakpointsSkipped { count: 2 }).unwrap(), + serde_json::json!({"kind": "breakpointsSkipped", "count": 2}) + ); +} + +fn int(value: i32) -> TraceValue { + TraceValue::Boxed { id: value as u64 + 1000, class: BoxKind::Int, value: value.to_string() } +} + +fn text(id: u64, value: &str) -> TraceValue { + TraceValue::Str { id, value: value.into(), truncated: false } +} + +/// The log of the measured collection chain `source -> filter -> map -> sorted -> map`. +fn spike_records() -> Vec { + let at = |step, v| Record { step, value: int(v) }; + let str_at = |step, v: &str| Record { step, value: text(v.parse::().unwrap() + 5000, v) }; + vec![ + at(0, 5), + at(0, 3), + at(0, 8), + at(1, 8), + at(2, 81), + at(0, 1), + at(0, 4), + at(1, 4), + at(2, 41), + at(0, 2), + at(1, 2), + at(2, 21), + at(0, 9), + at(0, 6), + at(1, 6), + at(2, 61), + at(3, 21), + str_at(4, "21"), + at(3, 41), + str_at(4, "41"), + at(3, 61), + str_at(4, "61"), + at(3, 81), + str_at(4, "81"), + ] +} + +fn terminal_value() -> TerminalOutcome { + TerminalOutcome::Value { value: TraceValue::Object { id: 7, class: "java.util.ArrayList".into() } } +} + +fn recording(records: Vec, dropped: u64, terminal: TerminalOutcome) -> TraceRecording { + TraceRecording { records, dropped, terminal } +} + +#[test] +fn link_trace_reproduces_spike_log() { + let plan = plan_of("C_PLAN_COLLECTION"); + let linked = link_trace(&plan, &recording(spike_records(), 0, terminal_value()), 0); + assert_eq!(linked.records, spike_records()); + assert_eq!(linked.links.len(), linked.records.len()); + // `1=8` comes from the `0=8` just before it. + assert_eq!(linked.links[3].parent, Some(2)); + assert_eq!(linked.links[4].parent, Some(3)); + // `sorted` emits `3=21` (record 16) after the whole upstream ran: it is the `2=21` of record 11. + assert_eq!(linked.links[16], Link { parent: Some(11), ambiguous: false }); + assert_eq!(linked.links[17].parent, Some(16)); + assert_eq!(linked.links[22].parent, Some(4)); + assert_eq!(linked.banners, []); +} + +#[test] +fn link_trace_banners() { + let plan = plan_of("C_PLAN_COLLECTION"); + let truncated = link_trace(&plan, &recording(spike_records(), 5, terminal_value()), 0); + assert_eq!(truncated.banners, [TraceBanner::Truncated { dropped: 5 }]); + + let skipped = link_trace(&plan, &recording(spike_records(), 0, terminal_value()), 2); + assert_eq!(skipped.banners, [TraceBanner::BreakpointsSkipped { count: 2 }]); + + let count_plan = plan_of("C_STATIC_INIT"); + assert_eq!(count_plan.terminal.name, "count"); + let sized = link_trace(&count_plan, &recording(Vec::new(), 0, terminal_value()), 0); + assert_eq!(sized.banners, [TraceBanner::CountFromSize]); + // Any record means elements flowed, so the count was not taken from the size. + let source_only = vec![Record { step: 0, value: int(1) }, Record { step: 0, value: int(2) }]; + let flowed = link_trace(&count_plan, &recording(source_only, 0, terminal_value()), 0); + assert_eq!(flowed.banners, []); +} + +#[test] +fn link_trace_flags_pass_through_sort_sequentialize_and_throw() { + let plan = plan_of("C_PLAN_COLLECTION"); + // `sorted` emitting `3=1` before `2=2` was recorded means it did not sort. + let records = vec![ + Record { step: 2, value: int(1) }, + Record { step: 3, value: int(1) }, + Record { step: 2, value: int(2) }, + Record { step: 3, value: int(2) }, + ]; + let threw = TerminalOutcome::Threw { + exception: TraceValue::Object { id: 9, class: "java.lang.IllegalStateException".into() }, + }; + let linked = link_trace(&plan, &recording(records, 0, threw), 0); + assert_eq!(linked.banners, [TraceBanner::SortedPassThrough { step: 3 }, TraceBanner::Threw]); + + let parallel = plan_of("C_PLAN_PARALLEL"); + let linked = link_trace(¶llel, &recording(Vec::new(), 0, TerminalOutcome::Void), 0); + assert_eq!(linked.banners, [TraceBanner::Sequentialized]); +} diff --git a/crates/ide-streams/tests/resolver_oracle.rs b/crates/ide-streams/tests/resolver_oracle.rs new file mode 100644 index 0000000000..65499d9ae6 --- /dev/null +++ b/crates/ide-streams/tests/resolver_oracle.rs @@ -0,0 +1,135 @@ +//! Checks `resolve` against parent links a real JVM produced (`fixtures/java/TraceOracle.java`). + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ide_streams::{BoxKind, Record, TraceValue, resolve, step_kind}; + +/// How the debuggee would identify the same oracle element. +#[derive(Clone, Copy, Debug)] +enum Mode { + /// User objects: one id per object. + Ref, + /// `Stream`: `valueOf` shares boxes inside the Integer cache. + Boxed, + /// `IntStream`: every `peek` boxes again, so outside the cache each record has its own box. + Prim, +} + +const MODES: [Mode; 3] = [Mode::Ref, Mode::Boxed, Mode::Prim]; +const CACHED_BOX_IDS: u64 = 1 << 32; +const FRESH_BOX_IDS: u64 = 1 << 40; + +struct Chain { + ops: Vec, + /// `(stage, object id, value)` in time order. + records: Vec<(u16, u64, i32)>, + truth: Vec>, +} + +fn parse(line: &str) -> Chain { + let json: serde_json::Value = serde_json::from_str(line).expect("oracle line is JSON"); + let ops = json["ops"].as_array().expect("ops").iter().map(|o| o.as_str().expect("op").to_owned()).collect(); + let records = json["records"] + .as_array() + .expect("records") + .iter() + .map(|r| { + let field = |i: usize| r[i].as_i64().expect("record field"); + (field(0) as u16, field(1) as u64, field(2) as i32) + }) + .collect(); + let truth = json["truth"] + .as_array() + .expect("truth") + .iter() + .map(|t| u32::try_from(t.as_i64().expect("truth")).ok()) + .collect(); + Chain { ops, records, truth } +} + +fn records(chain: &Chain, mode: Mode) -> Vec { + chain + .records + .iter() + .enumerate() + .map(|(i, &(step, object, v))| { + let shared = u8::try_from(v + 128).ok().map(|slot| CACHED_BOX_IDS + u64::from(slot)); + let value = match mode { + Mode::Ref => TraceValue::Object { id: object, class: "TraceOracle$Item".into() }, + Mode::Boxed => { + TraceValue::Boxed { id: shared.unwrap_or(object), class: BoxKind::Int, value: v.to_string() } + } + Mode::Prim => TraceValue::Boxed { + id: shared.unwrap_or(FRESH_BOX_IDS + i as u64), + class: BoxKind::Int, + value: v.to_string(), + }, + }; + Record { step, value } + }) + .collect() +} + +#[derive(Default)] +struct Tally { + links: u64, + wrong: u64, + first_wrong: Option, +} + +fn check<'a>(lines: impl Iterator) -> [Tally; 3] { + let mut tallies: [Tally; 3] = Default::default(); + for line in lines.filter(|l| !l.is_empty()) { + let chain = parse(line); + let kinds: Vec<_> = + chain.ops.iter().map(|op| step_kind(op).unwrap_or_else(|| panic!("{op} is a step"))).collect(); + for (mode, tally) in MODES.iter().zip(&mut tallies) { + let links = resolve(&kinds, &records(&chain, *mode)); + let wrong = links.iter().zip(&chain.truth).filter(|(link, truth)| link.parent != **truth).count() as u64; + tally.links += chain.records.iter().filter(|r| r.0 > 0).count() as u64; + tally.wrong += wrong; + if wrong > 0 && tally.first_wrong.is_none() { + tally.first_wrong = Some(line.to_owned()); + } + } + } + tallies +} + +#[track_caller] +fn assert_all_right(tallies: &[Tally; 3], min_links: u64) { + for (mode, tally) in MODES.iter().zip(tallies) { + println!("{mode:?}: {} links, {} wrong", tally.links, tally.wrong); + assert_eq!(tally.wrong, 0, "{mode:?} mislinks, first in: {}", tally.first_wrong.as_deref().unwrap_or_default()); + assert!(tally.links >= min_links, "{mode:?}: only {} links", tally.links); + } +} + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +#[test] +fn oracle_fixture_resolves_without_error() { + let text = std::fs::read_to_string(fixtures().join("resolver/oracle-jdk21-seed1.jsonl")).expect("fixture"); + assert_all_right(&check(text.lines()), 2000); +} + +#[test] +#[ignore = "needs a real JDK >= 11: set OPENIDEA_TEST_JAVA to its bin/java"] +fn oracle_on_real_jdk() { + let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else { + eprintln!("OPENIDEA_TEST_JAVA is not set; skipping"); + return; + }; + let out = Command::new(java) + .arg(fixtures().join("java/TraceOracle.java")) + .args(["1", "20000"]) + .output() + .expect("java starts"); + assert!(out.status.success(), "oracle failed: {}", String::from_utf8_lossy(&out.stderr)); + let tallies = check(std::str::from_utf8(&out.stdout).expect("UTF-8").lines()); + println!("total: {} links", tallies.iter().map(|t| t.links).sum::()); + assert_all_right(&tallies, 2000); +} diff --git a/crates/ide-syntax/src/lib.rs b/crates/ide-syntax/src/lib.rs index 2c1dacd21b..09a8bbb3d7 100644 --- a/crates/ide-syntax/src/lib.rs +++ b/crates/ide-syntax/src/lib.rs @@ -24,12 +24,14 @@ mod kinds; mod lines; mod locals; mod nodes; +mod tree; mod types; #[cfg(test)] mod tests; pub use jvm::{JvmPresentation, JvmTypeKind, jvm_type_header}; +pub use tree::SyntaxTree; pub use types::*; use ide_core::{CancellationToken, DocId, IdeError, LanguageId, Pos, Range}; diff --git a/crates/ide-syntax/src/tests/mod.rs b/crates/ide-syntax/src/tests/mod.rs index fe753dc42c..2af0043204 100644 --- a/crates/ide-syntax/src/tests/mod.rs +++ b/crates/ide-syntax/src/tests/mod.rs @@ -4,6 +4,7 @@ mod jvm; mod locals_langs; mod structure; +mod tree; use crate::*; use ide_core::{LanguageId, Pos, Range}; diff --git a/crates/ide-syntax/src/tests/tree.rs b/crates/ide-syntax/src/tests/tree.rs new file mode 100644 index 0000000000..646f172e53 --- /dev/null +++ b/crates/ide-syntax/src/tests/tree.rs @@ -0,0 +1,39 @@ +use super::*; + +fn find_kind<'t>(node: tree_sitter::Node<'t>, kind: &str) -> Option> { + if node.kind() == kind { + return Some(node); + } + let mut cursor = node.walk(); + node.children(&mut cursor).find_map(|child| find_kind(child, kind)) +} + +#[test] +fn with_tree_reports_utf16_ranges() { + let text = "class A { String s = \"é😀\"; int x = s.length(); }"; + let (range, byte, back) = service() + .with_tree(&Snapshot::text(&lang("java"), text), &none(), |t| { + let call = find_kind(t.tree.root_node(), "method_invocation").unwrap(); + (t.range(&call), t.byte(Pos::new(0, 36)), t.pos(39)) + }) + .unwrap(); + assert_eq!(range, Range::new(Pos::new(0, 36), Pos::new(0, 46))); + assert_eq!(byte, 39); + assert_eq!(back, Pos::new(0, 36)); +} + +#[test] +fn with_tree_needs_a_grammar() { + let plaintext = lang("plaintext"); + let snap = Snapshot::text(&plaintext, "x"); + assert_eq!(service().with_tree(&snap, &none(), |_| ()).unwrap_err(), StructureError::Unsupported); +} + +#[test] +fn with_tree_honours_cancellation() { + let cancel = CancellationToken::new(); + cancel.cancel(); + let java = lang("java"); + let snap = Snapshot::text(&java, "class A {}"); + assert_eq!(service().with_tree(&snap, &cancel, |_| ()).unwrap_err(), StructureError::Cancelled); +} diff --git a/crates/ide-syntax/src/tree.rs b/crates/ide-syntax/src/tree.rs new file mode 100644 index 0000000000..b354c8543e --- /dev/null +++ b/crates/ide-syntax/src/tree.rs @@ -0,0 +1,43 @@ +use crate::lines::Lines; +use crate::{CancellationToken, Ctx, Snapshot, StructureResult, StructureService}; +use ide_core::{Pos, Range}; + +/// A parsed snapshot lent to a closure. Node offsets are bytes into `text`; +/// convert with [`SyntaxTree::range`] / [`SyntaxTree::pos`] before they leave +/// the closure, since IPC coordinates are UTF-16. +pub struct SyntaxTree<'a> { + pub grammar: &'static str, + pub tree: &'a tree_sitter::Tree, + pub text: &'a str, + // Borrowed from the service's `Ctx` so lending a tree does not re-index lines. + lines: &'a Lines<'a>, +} + +impl SyntaxTree<'_> { + pub fn range(&self, node: &tree_sitter::Node) -> Range { + self.lines.range(node.start_byte(), node.end_byte()) + } + + /// Byte offset of `pos`, clamped to its line and to the text. + pub fn byte(&self, pos: Pos) -> usize { + self.lines.byte(pos) + } + + pub fn pos(&self, byte: usize) -> Pos { + self.lines.pos(byte) + } +} + +impl StructureService { + /// Lends the parsed tree to `f` so analysis crates (`ide-streams`) can walk nodes; positions come out via `range`/`pos` (UTF-16). + pub fn with_tree( + &self, + snap: &Snapshot, + cancel: &CancellationToken, + f: impl FnOnce(&SyntaxTree<'_>) -> R, + ) -> StructureResult { + self.run(snap, cancel, |cx: &Ctx| { + Ok(f(&SyntaxTree { grammar: cx.grammar, tree: cx.tree, text: cx.text(), lines: &cx.lines })) + }) + } +} diff --git a/e2e/stream-trace.spec.ts b/e2e/stream-trace.spec.ts new file mode 100644 index 0000000000..fd1eadbd45 --- /dev/null +++ b/e2e/stream-trace.spec.ts @@ -0,0 +1,139 @@ +/** + * Trace Stream Chain on a paused java-debug session: the one chain on the line traces at once, its + * progress shows while the program runs it, and the result opens as Flat columns and Split pairs. + * The host is stubbed at the IPC layer; `smoke/debug.test.ts` traces a real JVM. + */ +import { CHAIN_A, CHAIN_A_READY } from "../src/features/debugger/__tests__/streamChainA"; +import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures"; + +const ROOT = "/dev/acme-api"; +const FILE = `${ROOT}/build.gradle.kts`; +const SESSION = 3; + +declare global { + interface Window { + finishTrace?: () => void; + } +} + +test("traces the stream chain on the paused line into Flat and Split views", async ({ workbench: page }) => { + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate( + async ({ file, root, session, chain, ready }) => { + const h = window.__ipc.handlers; + const debug = (event: Record) => window.__ipc.emit({ type: "debug", session, event }); + const stopAt = (line: number, reason: string) => { + h.debug_stack_trace = () => [ + { id: 11, name: "Main.main", path: file, line, column: 0, presentationHint: null }, + ]; + debug({ kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: false }); + }; + h.debug_capabilities = () => ({ + restartFrame: false, + stepInTargets: false, + functionBreakpoints: false, + dataBreakpoints: false, + setValue: false, + conditionalBreakpoints: true, + hitConditionalBreakpoints: true, + logPoints: true, + hotCodeReplace: false, + jvmMemory: true, + jvmInstances: true, + jvmHeap: false, + jsPage: false, + liveEvaluate: false, + streamTrace: true, + }); + h.debug_start = () => { + setTimeout(() => { + debug({ kind: "started", name: "app", adapter: "java-debug", parent: null }); + debug({ kind: "initialized" }); + stopAt(6, "breakpoint"); + }, 50); + return session; + }; + h.debug_threads = () => [{ id: 1, name: "main" }]; + h.debug_scopes = () => []; + h.debug_stream_chains = () => [chain]; + // The host runs the terminal operation, then steps out of it; the reply waits for `finishTrace`. + h.debug_stream_trace = (args) => { + debug({ kind: "continued", threadId: 1, allThreadsContinued: false }); + window.__ipc.send(args.onProgress, { phase: "arming", records: 0, dropped: 0, elapsedMs: 0 }); + window.__ipc.send(args.onProgress, { phase: "running", records: 24, dropped: 0, elapsedMs: 1400 }); + return new Promise((resolve) => { + window.finishTrace = () => { + stopAt(6, "step"); + resolve(ready); + }; + }); + }; + // Launching a Java configuration needs jdtls and a build; attaching goes straight to `debug_start`. + const stateModule = "/src/features/debugger/state.ts"; + const { startSession } = await import(/* @vite-ignore */ stateModule); + await startSession({ + name: "app", + adapter: "java-debug", + request: "attach", + program: null, + args: [], + cwd: root, + env: {}, + extraJson: JSON.stringify({ hostName: "localhost", port: 5005 }), + }); + }, + { file: FILE, root: ROOT, session: SESSION, chain: CHAIN_A, ready: CHAIN_A_READY }, + ); + + const debugWindow = page.getByRole("region", { name: "Debug", exact: true }); + await expect(debugWindow.getByText("Main.main", { exact: true })).toBeVisible(); + + await page.keyboard.press("Meta+Shift+A"); + const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true }); + await search.getByRole("combobox").fill("Trace Stream Chain"); + await expect(search.getByRole("option", { name: /Trace Stream Chain/ })).toBeVisible(); + await search.getByRole("combobox").press("Enter"); + await expect(search).toBeHidden(); + + const tab = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "Stream Trace" }); + await expect(tab).toHaveAttribute("aria-selected", "true"); + await expect(page.getByRole("progressbar", { name: "Tracing the stream chain" })).toBeVisible(); + await expect(page.getByText("24 records · 1 s", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Stop Recording" })).toBeEnabled(); + await expect(page.getByRole("button", { name: "Abort Operation…" })).toBeEnabled(); + + expect(await ipcCalls(page, "debug_stream_chains")).toEqual([ + { session: SESSION, frame: expect.objectContaining({ id: 11, line: 6 }), top: true }, + ]); + expect(await ipcCalls(page, "debug_stream_trace")).toEqual([ + expect.objectContaining({ + session: SESSION, + threadId: 1, + frame: expect.objectContaining({ id: 11 }), + chainIndex: 0, + range: CHAIN_A.range, + }), + ]); + + await page.evaluate(() => window.finishTrace?.()); + await expect(page.getByRole("progressbar", { name: "Tracing the stream chain" })).toBeHidden(); + const columns = page.locator('[data-testid="stream-trace-column"]'); + await expect(columns).toHaveCount(5); + expect(await columns.evaluateAll((cs) => cs.map((c) => c.querySelectorAll("li").length))).toEqual([8, 4, 4, 4, 4]); + await expect(page.locator('[data-testid="stream-trace-result"]').getByRole("list", { name: "Result" })).toBeVisible(); + // The step-out stop that ends the trace must not bring the source tab back over the result. + await expect.poll(async () => (await ipcCalls(page, "debug_stack_trace")).length).toBeGreaterThanOrEqual(2); + await expect(debugWindow.getByText("Main.main", { exact: true })).toBeVisible(); + await expect(tab).toHaveAttribute("aria-selected", "true"); + + const third = columns.nth(2); + await third.getByRole("button", { name: "81", exact: true }).click(); + await expect(third.getByRole("button", { name: "81", exact: true })).toHaveAttribute("aria-pressed", "true"); + await expect(columns.nth(0).getByRole("button", { name: "8", exact: true })).toHaveAttribute("data-related"); + + await page.getByRole("tablist", { name: "Stream trace view" }).getByRole("tab", { name: "Split" }).click(); + await expect(columns).toHaveCount(2); + await expect(page.locator('[data-testid="stream-trace-result"]')).toHaveCount(0); + await expect(page.getByRole("tablist", { name: "Steps" }).getByRole("tab")).toHaveCount(4); +}); diff --git a/fixtures/java-app/src/main/java/com/example/orders/App.java b/fixtures/java-app/src/main/java/com/example/orders/App.java index 80bd50d7e4..696582014b 100644 --- a/fixtures/java-app/src/main/java/com/example/orders/App.java +++ b/fixtures/java-app/src/main/java/com/example/orders/App.java @@ -12,5 +12,7 @@ public class App { long revenue = book.revenueCents(); System.out.printf("%d orders, revenue %.2f%n", book.size(), revenue / 100.0); book.largest().ifPresent(o -> System.out.println("Largest: " + o.product())); + int alices = book.byCustomer("alice").size(); + System.out.println("alice placed " + alices + " orders"); } } diff --git a/java/jvm-inspect/MANIFEST.MF b/java/jvm-inspect/MANIFEST.MF index ae1c5e38e8..8475f27ecb 100644 --- a/java/jvm-inspect/MANIFEST.MF +++ b/java/jvm-inspect/MANIFEST.MF @@ -2,8 +2,8 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA JVM inspect Bundle-SymbolicName: ai.openidea.jvminspect;singleton:=true -Bundle-Version: 1.0.0 +Bundle-Version: 1.1.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.core.runtime, - org.eclipse.equinox.common,org.eclipse.jdt.debug + org.eclipse.equinox.common,org.eclipse.jdt.debug,org.eclipse.core.resources diff --git a/java/jvm-inspect/README.md b/java/jvm-inspect/README.md index d69b798c9e..6baed033da 100644 --- a/java/jvm-inspect/README.md +++ b/java/jvm-inspect/README.md @@ -2,8 +2,9 @@ An OSGi bundle loaded into JDT LS next to microsoft java-debug. While a Java debug session is suspended, it lists the instances of a class, the fields of an object and the objects that refer to -it, and counts the instances of every loaded class. It works on java-debug's own JDI connection to -the debuggee, so no second debugger connects to the JVM. +it, and counts the instances of every loaded class; it also traces a stream chain while the program +runs it. It works on java-debug's own JDI connection to the debuggee, so no second debugger connects +to the JVM. ## Commands @@ -39,6 +40,112 @@ no `text`. - A referrer array longer than 10 000 elements is not searched for the slot (`via` is empty). - An object collected before its preview is left out of `instances` and `referrers`. +## Stream trace + +The `openidea.jvm.stream.*` commands trace a stream chain while the program itself runs it, so no +lambda runs twice. They take `target` first, like the commands above, then one object: + +| Command | Object after `target` | `ok` | +| ---------------- | -------------------------- | ----------------------------------------------------------------------------------- | +| `stream.arm` | `{threadId, plan, budget}` | `{traceId}` | +| `stream.wait` | `{traceId, ms}` | `{state, records, dropped, elapsedMs, detail?}` | +| `stream.stop` | `{traceId}` | `{records}` | +| `stream.abort` | `{traceId}` | `{state, holders?}`, `holders` being `[{threadId, name}]` | +| `stream.collect` | `{traceId}` | `{records: [{step, value}], dropped, terminal, skippedBreakpoints, sequentialized}` | +| `stream.release` | `{traceId}` | `{}` | + +`plan` is the JSON of `ide_streams::RealRunPlan`; `budget`, a whole number from 1 to 2³¹ − 1 +(default 50 000), caps the records kept, past which they are only counted in `dropped`. `wait`'s +`state` is `running`, `parked`, `failed` or `cancelled` (both with `detail`). `abort`'s is `interrupted`, `stopped` or +`stuck` while the terminal runs, `cancelled` before it started and `finished` once the trace parked +or failed. `collect` takes the new stop's `target.generation`; a record's `step` counts the wrapped +ops from 0 (the source), modifiers left out, and `value`, like the `terminal`'s, is a `JvmValue` +preview (a primitive result previews as `primitive`). `terminal` is `{kind: "value", value}`, +`{kind: "void"}` or `{kind: "threw", exception}`. +Besides the codes above, a reply's `error` can be `noSession` (java-debug registered no session for +the VM), `notAtChainStart`, `busy` (the VM has a trace still running; `collect` before the trace +parked), `noTrace` (the `traceId` is not the VM's current trace), `badArgument` (a `budget` out of +range) or `failed` (`collect` on a failed trace, with its `detail`, or a JDI failure the commands do +not expect, or a VM unlike the plan). `collect` in the stop `arm` ran in is `stale`. Any other malformed argument is an +ordinary `executeCommand` error. + +- `arm` needs the thread suspended by an event (a breakpoint or a step) and a VM that can force early + returns and report return values (HotSpot 11 to 25 can). It defines the recorder + (`recorder/OiRecorder.java`, embedded as `ai/openidea/jvminspect/OiRecorder.bin`) in a + `SecureClassLoader` of its own whose parent is the boot loader, once per VM, and creates the log and + the exception that cancels the terminal (`java.lang.RuntimeException: oi-cancel:`). +- From `arm` until the trace is released, every enabled breakpoint, exception, method entry, method + exit and watchpoint request that is not the bundle's own is switched off, then back on: java-debug + makes a function breakpoint a method entry request and a data breakpoint a watchpoint request. A + breakpoint hit while the bundle invokes into the thread hangs the session. A request java-debug deleted meanwhile (the user edited or removed the + breakpoint) stays off: Eclipse JDI would enable a deleted request again, so only requests the VM + still lists are switched back on. +- One trace per VM. A finished trace (parked or failed) is released by the next `arm` on that VM or + when the VM disconnects; the client need not call `release`. Releasing a parked trace the client + never stepped out of resumes the thread; releasing one whose terminal still runs takes effect when + the terminal returns, and until then the VM's next `arm` is `busy`. The program then runs on with + the terminal's outcome and the trace is `failed` (`released`), so a later `abort` is `finished` and + the next `arm` replaces it. After the VM disconnected, `wait` still answers the trace's last state + and the counts last read, for the 16 latest such traces. +- `arm` refuses a chain that has started (`notAtChainStart`): the stop must be on or after the + statement's first line with no code of those lines before it. javac puts a statement's first + instruction on its first line; ECJ, which JDT LS builds with, gives a head like + `List out =` no code, and a head like `n =` only the store after the chain. A stop inside a + lambda (a synthetic method, or one named `lambda$…`) is refused when a deeper frame of the same class + has code on the chain's lines up to the stop: that frame runs the chain, and the stop is in one of the + chain's lambdas, from which the root is never called. A chain written inside a lambda body has its + lines in the lambda alone and stays traceable. A `local` root + must be declared as a `Stream`, `IntStream`, `LongStream` or `DoubleStream` (`unsupported` + otherwise); `arm` replaces it by `local.peek(recorder)`. +- After the client continues the thread, each build-phase `MethodExit` of the chain's next op is held + and its stream returned as `stream.peek(recorder)` through `forceEarlyReturn`. The root is matched + by name, JVM arity, stream return type and caller (the stopped method, one frame deeper), after the + plan's `skip` such exits; every later op by receiver: a call from that method on the last wrapped + stream is the chain's next op, and one that differs from the plan fails the trace + (`missed `) and lets the program run on. Modifiers are matched but not wrapped. With + `sequentialize`, the source becomes `peek(…).sequential()` and each `parallel()` returns + `sequential()`. +- The build phase ends in `failed` (`the chain did not run: …`), the program running on, when the + statement throws before the terminal is called (the root's or a step's arguments). The bundle also + watches the stopped method's class for method exits, and steps out of its frame: JDWP reports no + method exit for a frame an exception pops, but the step out lands in the caller's handler. Any of + the trace's events with that frame gone, or on a line outside the plan's `firstLine`..`lastLine` + (the statement caught the exception), fails the trace. A breakpoint on the line the step out lands + on is missed (it is switched back on only once the thread is there), and so are breakpoints the + frame's own catch block passes before the trace's next event. +- At the terminal's `MethodEntry`, with no method request left on (any slows the thread to the + interpreter), the bundle runs the terminal once by `invokeMethod`, with the JDI timeout raised, and + forces its result as the entered frame's return, or throws its exception there. The thread stays + suspended (`parked`) until the client's DAP `stepOut`. Breakpoints java-debug created since `arm` + are silenced too, right before the invoke, and again at each 500 ms check of a `wait` while it + runs; all are switched back on when it returns. A breakpoint added between two checks can still be + hit inside the invoke: java-debug reports the stop, and a DAP `continue` of the thread lets the + invoke go on (ide-dap does that unseen while the trace runs). + The outcome is forced into the frame before it is pinned, so the pending return keeps it reachable; + should it be collected before that, the program gets the cancel exception and the trace fails. +- `wait` returns as soon as the trace leaves `running`, or after `ms`, at most 30 000. While the + terminal runs it also checks every 500 ms whether the VM began to shut down + (`jdk.internal.misc.VM.initLevel`): `System.exit` in a lambda makes the VM wait forever to report + its death while the bundle's invoke runs, so no disconnect comes. The trace then fails, with the + breakpoints back on; the debug session has to be stopped. +- `stop` lowers the log's budget to the records so far by a field write: the program keeps running + untouched. `abort` interrupts the thread, waits 2 s for the terminal to return, then throws the + cancel exception into it, waits 2 s more, and else lists the suspended threads that own a monitor. + JDWP holds an interrupt or stop of a thread handling an event until that event's handler exits, and + the invoke runs inside the handler of the terminal's entry; any event of the thread inside the + invoke lifts the hold. So the bundle adds a method entry request on the thread, counted once and + suspending nothing, right before the invoke: it fires on the terminal's own entry. Without it only a + class first prepared inside the invoke lifted the hold, and a VM that had run those stream classes + before (an earlier stream or trace) answered `stuck`. Before the terminal started, either takes the trace + down (`cancelled`, `cancelled before the terminal ran`) and the program runs on untouched. +- `collect` reads the log 16 384 elements per JDWP request and previews every value into the handle + table of the inspect commands, so the UI can expand them; the log keeps them alive until the trace + is released. `skippedBreakpoints` counts the line, function and data breakpoint requests silenced (exception breakpoints + left out: JDI cannot tell whether a silenced request would have been hit). +- Timing, the 1M-element chain of `tests/stream.py` (`real_run_d_million`, Apple M4 Pro, JDT LS + 1.63): 78–138 ms from DAP `continue` to `parked` on JDK 11, 17, 21, 23 and 25; DAP `stepOut` plus + `collect` of its 50 000 records 4.4–4.7 s. + `classes` and `referrers` can take seconds on a large heap. Eclipse JDI fails a request after `getRequestTimeout()` (3000 ms by default), and the timeout is per VM: java-debug's own requests waiting behind the command time out too. These two commands raise it to at least 60 000 ms and, @@ -56,6 +163,22 @@ through these non-API members, by reflection: - `org.eclipse.jdi.internal.connect.PacketManager.fConnection` - `org.eclipse.jdi.internal.connect.SocketConnection.fSocket` +The stream commands reach java-debug's debug session of a VM, and its events, through: + +- `org.eclipse.core.internal.resources.Workspace.notificationManager` → + `NotificationManager.listeners` → `ResourceChangeListenerList.listeners` (a `CopyOnWriteArrayList`) + → `ListenerEntry.listener` +- `com.microsoft.java.debug.plugin.internal.JavaHotCodeReplaceProvider.currentDebugSession`, a + listener registered by each session whose `hotCodeReplace` setting is not `never` (the app sets + `auto`) +- `IDebugSession#getVM()`, `#getEventHub()`, `IEventHub#events()` and RxJava 2's + `Observable#subscribe(Consumer, Consumer)` / `Disposable#dispose()`, loaded from the java-debug bundle +- `DebugEvent.event`, `.eventSet` and `.shouldResume`: set to `false` in the listener, it keeps the + event's thread suspended, as java-debug does for conditional breakpoints + +and, in the debuggee, `jdk.internal.misc.VM.initLevel` and `.SYSTEM_SHUTDOWN` (JDK 9 to 25), read as +static fields to see the VM shutting down while the terminal runs; without them that check is off + and, as API of `org.eclipse.jdt.debug`, `org.eclipse.jdi.VirtualMachine#getRequestTimeout` / `#setRequestTimeout` and `org.eclipse.jdi.TimeoutException`. When any of these is missing or changes shape, every command answers `unsupported`; nothing throws into java-debug. @@ -70,16 +193,18 @@ the same as `java/java-usages`. Check the extracted distribution from its root (`sha256sum -c /path/to/build-dependencies.sha256`), then with Java 25 on `PATH`: ```sh -python3 build.py /path/to/jdtls # writes openidea-jvm-inspect.jar -python3 build.py /path/to/jdtls --test # compiles tests/SelfTest.java with the sources and runs it +python3 build.py /path/to/jdtls # writes openidea-jvm-inspect.jar +python3 build.py /path/to/jdtls --out x.jar # writes x.jar instead +python3 build.py /path/to/jdtls --test # compiles tests/SelfTest.java with the sources and runs it ``` The build uses the distribution's ECJ and plugin jars plus the `jdimodel.jar` nested in `plugins/org.eclipse.jdt.debug_*.jar`, sorted inputs and fixed zip timestamps; bytecode targets -Java 21. Build twice and compare: two builds of the checked-in jar gave +Java 21. The recorder is compiled by the `javac` on `PATH` with `--release 8`, since the debuggee may +run Java 8. Build twice and compare: two builds of the checked-in jar gave ``` -ab53d0e6b9e492b5c3be1179c793c879db94ba44a421bdbd4f2f33319e03464a openidea-jvm-inspect.jar +22980a16bd8e303d67ed2e04d76d8974f2d3981120c26e6d9afa47ba361b1503 openidea-jvm-inspect.jar ``` Change `Bundle-Version` whenever the jar changes: OSGi caches bundles by version. @@ -99,3 +224,15 @@ python3 -I tests/inspect.py /path/to/jdtls /path/to/com.microsoft.java.debug.plu first; `classes` is checked on the JDK 11 one. With `--heap N`, a JDK 21 JVM holds N objects and a DAP `evaluate` sent 0.5 s after `classes` starts must succeed, with the timeout back to 3000 after. It stops every process it started. + +`tests/stream.py` does the same for the stream commands, once per JDK in `OPENIDEA_TEST_JAVA`, with +a launch and an attach; both scripts share `tests/jdtls_harness.py`. The `real_run_*` cases trace +chains end to end (arm, DAP `continue`, `wait`, DAP `stepOut`, `collect`); one debuggee is compiled +with the distribution's ECJ, as JDT LS builds a project. `--bundle` takes a jar built with `--out` (default: the checked-in one) and +`--case NAME` runs only the cases whose name contains `NAME`: + +```sh +PATH=/path/to/jdk25/bin:$PATH \ +OPENIDEA_TEST_JAVA=/path/to/jdk11/bin/java:/path/to/jdk21/bin/java \ +python3 -I tests/stream.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-0.53.2.jar --bundle x.jar +``` diff --git a/java/jvm-inspect/build.py b/java/jvm-inspect/build.py index 133da85683..2f674650c9 100644 --- a/java/jvm-inspect/build.py +++ b/java/jvm-inspect/build.py @@ -1,6 +1,7 @@ -"""Reproducible bundle build: python3 build.py /path/to/jdtls [--test] (JDT LS 1.63.0, Java 25; target Java 21). +"""Reproducible bundle build: python3 build.py /path/to/jdtls [--test] [--out JAR] (JDT LS 1.63.0, Java 25; target Java 21). ---test compiles tests/SelfTest.java with the sources and runs it; it does not write the jar.""" +--test compiles tests/SelfTest.java with the sources and runs it; it does not write the jar. +--out writes the jar there instead of openidea-jvm-inspect.jar next to this file.""" import os import pathlib import subprocess @@ -8,6 +9,9 @@ import sys import tempfile import zipfile +RECORDER = 'ai/openidea/jvminspect/OiRecorder.bin' + + def run(command): code = subprocess.run(command).returncode if code: @@ -15,8 +19,14 @@ def run(command): root = pathlib.Path(__file__).resolve().parent -test = '--test' in sys.argv[1:] -plugins = pathlib.Path(next(a for a in sys.argv[1:] if a != '--test')).resolve() / 'plugins' +args = sys.argv[1:] +jar_path = root / 'openidea-jvm-inspect.jar' +if '--out' in args: + i = args.index('--out') + jar_path = pathlib.Path(args[i + 1]).resolve() + del args[i:i + 2] +test = '--test' in args +plugins = pathlib.Path(next(a for a in args if a != '--test')).resolve() / 'plugins' with tempfile.TemporaryDirectory() as tmp: tmp = pathlib.Path(tmp) # org.eclipse.jdt.debug ships the JDI model as a nested jar, which javac cannot read in place. @@ -29,11 +39,15 @@ with tempfile.TemporaryDirectory() as tmp: 'org.eclipse.jdt.internal.compiler.batch.Main', '-21', '-proc:none', '-classpath', os.pathsep.join(classpath), '-d', str(out), *[str(p) for p in sources]]) + # The recorder is defined in the debuggee, which may run Java 8: a resource, not a class of this bundle. + recorder = tmp / 'recorder' + run(['javac', '--release', '8', '-g:none', '-Xlint:-options', '-d', str(recorder), str(root / 'recorder' / 'OiRecorder.java')]) + (out / RECORDER).write_bytes((recorder / 'OiRecorder.class').read_bytes()) if test: run(['java', '-cp', os.pathsep.join([str(out), *classpath]), 'ai.openidea.jvminspect.SelfTest']) sys.exit(0) - with zipfile.ZipFile(root / 'openidea-jvm-inspect.jar', 'w', zipfile.ZIP_DEFLATED) as jar: - files = {'META-INF/MANIFEST.MF': root / 'MANIFEST.MF', 'plugin.xml': root / 'plugin.xml'} + with zipfile.ZipFile(jar_path, 'w', zipfile.ZIP_DEFLATED) as jar: + files = {'META-INF/MANIFEST.MF': root / 'MANIFEST.MF', 'plugin.xml': root / 'plugin.xml', RECORDER: out / RECORDER} files.update({p.relative_to(out).as_posix(): p for p in out.rglob('*.class')}) for name, path in sorted(files.items()): jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), path.read_bytes()) diff --git a/java/jvm-inspect/openidea-jvm-inspect.jar b/java/jvm-inspect/openidea-jvm-inspect.jar index c25c379210..1207590062 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/plugin.xml b/java/jvm-inspect/plugin.xml index b1939bb4c7..c471b3a89c 100644 --- a/java/jvm-inspect/plugin.xml +++ b/java/jvm-inspect/plugin.xml @@ -8,5 +8,13 @@ + + + + + + + + diff --git a/java/jvm-inspect/recorder/OiRecorder.java b/java/jvm-inspect/recorder/OiRecorder.java new file mode 100644 index 0000000000..42a399992b --- /dev/null +++ b/java/jvm-inspect/recorder/OiRecorder.java @@ -0,0 +1,76 @@ +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.function.DoubleConsumer; +import java.util.function.IntConsumer; +import java.util.function.LongConsumer; + +/** + * Defined in the debuggee by the bundle (no package, Java 8 bytecode, nothing but the JDK) and passed + * to {@code peek} of each traced step. One instance is the log; each step gets an instance that + * appends {@code (step, value)} to it. A record's index in the log is its time. + * + *

The bundle reads and writes the public fields by name through JDI and calls the two + * constructors by signature; renaming any of them breaks the trace. + */ +public final class OiRecorder implements Consumer, IntConsumer, LongConsumer, DoubleConsumer { + public Object[] values; + public int[] steps; + public int size; + /** Lowered to {@code size} by "stop recording" while the terminal runs, so {@code size} may exceed it. */ + public int budget; + /** A long: an endless stream drops past {@code Integer.MAX_VALUE} within seconds. */ + public long dropped; + private final OiRecorder log; + private final int step; + + public OiRecorder(int budget) { + this.budget = budget; + int capacity = Math.max(0, Math.min(budget, 256)); + this.values = new Object[capacity]; + this.steps = new int[capacity]; + this.log = this; + this.step = -1; + } + + public OiRecorder(OiRecorder log, int step) { + this.log = log; + this.step = step; + } + + /** Never throws: a real run must not fail because of the trace. */ + synchronized void add(int s, Object v) { + try { + if (size >= budget) { + dropped++; + return; + } + if (size == values.length) { + int capacity = (int) Math.min((long) budget, Math.max(16L, size * 2L)); + values = Arrays.copyOf(values, capacity); + steps = Arrays.copyOf(steps, capacity); + } + values[size] = v; + steps[size] = s; + size++; + } catch (OutOfMemoryError e) { + // Not Throwable: the cancel exception that abort throws into the thread must get through. + dropped++; + } + } + + public void accept(Object v) { + log.add(step, v); + } + + public void accept(int v) { + log.add(step, Integer.valueOf(v)); + } + + public void accept(long v) { + log.add(step, Long.valueOf(v)); + } + + public void accept(double v) { + log.add(step, Double.valueOf(v)); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/ConnectedVms.java b/java/jvm-inspect/src/ai/openidea/jvminspect/ConnectedVms.java index a0ec74e7af..9257bf2ede 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/ConnectedVms.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/ConnectedVms.java @@ -57,7 +57,8 @@ final class ConnectedVms { } } - private static Field field(Class type, String name) throws NoSuchFieldException { + /** Declared in {@code type} or a superclass, made accessible. */ + static Field field(Class type, String name) throws NoSuchFieldException { for (Class k = type; k != null; k = k.getSuperclass()) { try { Field f = k.getDeclaredField(name); diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/InspectCommand.java b/java/jvm-inspect/src/ai/openidea/jvminspect/InspectCommand.java index 8143be1f26..036fa0d6b4 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/InspectCommand.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/InspectCommand.java @@ -37,7 +37,7 @@ public final class InspectCommand implements IDelegateCommandHandler { /** One per connected VM; also the lock that runs one command per VM at a time. */ private static final Map> HANDLES = new IdentityHashMap<>(); - private static final class Failure extends Exception { + static final class Failure extends Exception { private static final long serialVersionUID = 1L; final String code; @@ -50,12 +50,11 @@ public final class InspectCommand implements IDelegateCommandHandler { @Override public Object executeCommand(String command, List arguments, IProgressMonitor monitor) { try { - List vms = describe(ConnectedVms.read(InspectCommand::loadJavaDebug)); + List vms = connected(); if (command.equals("openidea.jvm.vms")) return ok(summaries(vms)); Target target = Target.of(arguments.get(0)); - VirtualMachine vm = VmSelector.select(vms, target) - .orElseThrow(() -> new Failure("vmNotFound", "no single VM matches " + target)).vm(); - Handles handles = handles(vm); + VirtualMachine vm = select(vms, target); + Handles handles = handlesFor(vm); synchronized (handles) { if (!vm.canGetInstanceInfo()) throw new Failure("unsupported", "the VM cannot list instances"); if (vm.allThreads().stream().noneMatch(ThreadReference::isSuspended)) { @@ -86,7 +85,16 @@ public final class InspectCommand implements IDelegateCommandHandler { } } - private static Class loadJavaDebug(String name) { + /** java-debug's live VMs, with the handle tables of VMs that are gone dropped. */ + static List connected() throws ConnectedVms.Unsupported { + return describe(ConnectedVms.read(InspectCommand::loadJavaDebug)); + } + + static VirtualMachine select(List vms, Target target) throws Failure { + return VmSelector.select(vms, target).orElseThrow(() -> new Failure("vmNotFound", "no single VM matches " + target)).vm(); + } + + static Class loadJavaDebug(String name) { Bundle bundle = Platform.getBundle(JAVA_DEBUG); if (bundle == null) return null; try { @@ -130,7 +138,8 @@ public final class InspectCommand implements IDelegateCommandHandler { return out; } - private static Handles handles(VirtualMachine vm) { + /** Shared with the stream commands, so their objects expand like any other; also the per-VM command lock. */ + static Handles handlesFor(VirtualMachine vm) { synchronized (HANDLES) { return HANDLES.computeIfAbsent(vm, k -> new Handles<>()); } @@ -221,11 +230,11 @@ public final class InspectCommand implements IDelegateCommandHandler { return (Number) argument; } - private static Map ok(Object payload) { + static Map ok(Object payload) { return Values.json("ok", payload); } - private static Map error(String code, String detail) { + static Map error(String code, String detail) { return Values.json("error", code, "detail", detail); } } diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/JavaDebugSessions.java b/java/jvm-inspect/src/ai/openidea/jvminspect/JavaDebugSessions.java new file mode 100644 index 0000000000..bbc60d8ea0 --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/JavaDebugSessions.java @@ -0,0 +1,196 @@ +package ai.openidea.jvminspect; + +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.event.Event; +import com.sun.jdi.event.EventSet; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Collection; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import org.eclipse.core.resources.ResourcesPlugin; + +/** + * java-debug's debug session of a VM, reached through the hot code replace provider that each session + * registers as a workspace resource listener. Nothing here is API: every step that no longer resolves + * is {@link ConnectedVms.Unsupported}, never a crash. + */ +final class JavaDebugSessions { + static final String HCR_PROVIDER = "com.microsoft.java.debug.plugin.internal.JavaHotCodeReplaceProvider"; + static final String SESSION = "com.microsoft.java.debug.core.IDebugSession"; + static final String EVENT_HUB = "com.microsoft.java.debug.core.IEventHub"; + static final String OBSERVABLE = "io.reactivex.Observable"; + static final String CONSUMER = "io.reactivex.functions.Consumer"; + static final String DISPOSABLE = "io.reactivex.disposables.Disposable"; + + interface Listener { + void onEvent(HubEvent event) throws Exception; + } + + interface Subscription extends AutoCloseable { + @Override + void close(); + } + + private JavaDebugSessions() {} + + /** + * Empty when no session of {@code vm} is registered: java-debug registers the provider only when + * its {@code hotCodeReplace} setting is not {@code never}. + */ + static Optional of(VirtualMachine vm) throws ConnectedVms.Unsupported { + Object workspace; + try { + workspace = ResourcesPlugin.getWorkspace(); + } catch (RuntimeException e) { + throw new ConnectedVms.Unsupported(e.toString()); + } + return find(workspace, vm, InspectCommand::loadJavaDebug); + } + + /** + * {@code Workspace.notificationManager.listeners.listeners[].listener}, the providers among them, + * then the one whose {@code currentDebugSession.getVM()} is {@code vm}. + * + * @param loader loads a class of the java-debug bundle by name; {@code null} when it is not there + */ + static Optional find(Object workspace, Object vm, Function> loader) throws ConnectedVms.Unsupported { + Class provider = load(loader, HCR_PROVIDER); + Class session = load(loader, SESSION); + try { + Object notifications = get(workspace, "notificationManager"); + Object list = get(get(notifications, "listeners"), "listeners"); + Object[] entries = list instanceof Collection c ? c.toArray() : (Object[]) list; + Method getVm = session.getMethod("getVM"); + for (Object entry : entries) { + Object listener = get(entry, "listener"); + if (!provider.isInstance(listener)) continue; + Object s = get(listener, "currentDebugSession"); + if (s != null && getVm.invoke(s) == vm) { + Object hub = session.getMethod("getEventHub").invoke(s); + return Optional.of(new Hub(load(loader, EVENT_HUB).getMethod("events").invoke(hub), loader)); + } + } + return Optional.empty(); + } catch (ReflectiveOperationException | RuntimeException e) { + throw new ConnectedVms.Unsupported(e.toString()); + } + } + + /** The events java-debug reads from the VM's event queue, before it acts on them. */ + static final class Hub { + private final Object events; + private final Function> loader; + private volatile Field event; + private volatile Field eventSet; + private volatile Field shouldResume; + + private Hub(Object events, Function> loader) { + this.events = events; + this.loader = loader; + } + + /** + * Runs {@code listener} on java-debug's event thread for every event. Whatever the listener + * throws goes to {@code failed} instead: RxJava drops a subscriber whose callback throws. Hub + * errors go to {@code failed} too. + */ + Subscription subscribe(Listener listener, Consumer failed) throws ConnectedVms.Unsupported { + Class consumer = load(loader, CONSUMER); + Object onNext = consumer(consumer, value -> listener.onEvent(new HubEvent(this, value)), failed); + Object onError = consumer(consumer, value -> failed.accept((Throwable) value), failed); + try { + // Everything is looked up before subscribing: a lookup failing after it would leave a live subscription. + Method dispose = load(loader, DISPOSABLE).getMethod("dispose"); + Method subscribe = load(loader, OBSERVABLE).getMethod("subscribe", consumer, consumer); + Object disposable = subscribe.invoke(events, onNext, onError); + return () -> { + try { + dispose.invoke(disposable); + } catch (ReflectiveOperationException | RuntimeException e) { + failed.accept(e); + } + }; + } catch (InvocationTargetException e) { + throw new ConnectedVms.Unsupported(e.getCause().toString()); + } catch (ReflectiveOperationException | RuntimeException e) { + throw new ConnectedVms.Unsupported(e.toString()); + } + } + + private interface Body { + void accept(Object value) throws Exception; + } + + private static Object consumer(Class type, Body body, Consumer failed) { + return Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, (proxy, method, args) -> switch (method.getName()) { + case "accept" -> { + try { + body.accept(args[0]); + } catch (Throwable t) { + try { + failed.accept(t); + } catch (Throwable ignored) { + // nothing may reach RxJava + } + } + yield null; + } + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + default -> "openidea stream trace listener"; + }); + } + + /** {@code DebugEvent}'s fields, looked up on the first event. */ + private void resolve(Object debugEvent) throws NoSuchFieldException { + if (shouldResume != null) return; + Class type = debugEvent.getClass(); + event = ConnectedVms.field(type, "event"); + eventSet = ConnectedVms.field(type, "eventSet"); + shouldResume = ConnectedVms.field(type, "shouldResume"); + } + } + + /** One {@code com.microsoft.java.debug.core.DebugEvent}. */ + static final class HubEvent { + private final Hub hub; + private final Object raw; + + private HubEvent(Hub hub, Object raw) throws NoSuchFieldException { + this.hub = hub; + this.raw = raw; + hub.resolve(raw); + } + + Event event() throws IllegalAccessException { + return (Event) hub.event.get(raw); + } + + EventSet eventSet() throws IllegalAccessException { + return (EventSet) hub.eventSet.get(raw); + } + + /** + * Keeps java-debug from resuming the event set after its handlers ran, as its own conditional + * breakpoints do. The thread stays suspended until someone calls {@code eventSet().resume()}. + * Only on java-debug's event thread, inside the listener. + */ + void park() throws IllegalAccessException { + hub.shouldResume.setBoolean(raw, false); + } + } + + private static Class load(Function> loader, String name) throws ConnectedVms.Unsupported { + Class type = loader.apply(name); + if (type == null) throw new ConnectedVms.Unsupported(name + " not found"); + return type; + } + + private static Object get(Object object, String field) throws NoSuchFieldException, IllegalAccessException { + return ConnectedVms.field(object.getClass(), field).get(object); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunPlan.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunPlan.java new file mode 100644 index 0000000000..39d0be18a1 --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunPlan.java @@ -0,0 +1,61 @@ +package ai.openidea.jvminspect; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * {@code ide_streams::RealRunPlan}, from the JSON the client sends with {@code stream.arm}. A malformed + * plan is an {@link IllegalArgumentException}, which JDT LS answers as an ordinary command error. + * + * @param root null when the stream is already held in {@code local} + * @param stepKinds {@code "sync"}, {@code "reorder"} or {@code "unlinked"}, relating recorded step i to i + 1 + * @param firstLine 0-based line of the statement's first token + * @param lastLine 0-based line the chain ends on + */ +record RealRunPlan(StepSpec root, String local, List steps, StepSpec terminal, List classFilters, + List stepKinds, boolean sequentialize, int firstLine, int lastLine) { + + /** + * @param args parameter count of the JVM method + * @param skip only the root's: calls of the same name and arity that exit before it in the statement; + * later steps are matched by receiver identity + */ + record StepSpec(String name, int args, int skip) { + static StepSpec of(Object json, String what) { + Map m = member(json, Map.class, what); + return new StepSpec(member(m.get("name"), String.class, what + ".name"), + member(m.get("args"), Number.class, what + ".args").intValue(), + member(m.get("skip"), Number.class, what + ".skip").intValue()); + } + } + + static RealRunPlan of(Object json) { + Map m = member(json, Map.class, "plan"); + Object root = m.get("root"); + List steps = new ArrayList<>(); + List rawSteps = member(m.get("steps"), List.class, "plan.steps"); + for (int i = 0; i < rawSteps.size(); i++) steps.add(StepSpec.of(rawSteps.get(i), "plan.steps[" + i + "]")); + return new RealRunPlan(root == null ? null : StepSpec.of(root, "plan.root"), + m.get("local") == null ? null : member(m.get("local"), String.class, "plan.local"), + List.copyOf(steps), + StepSpec.of(m.get("terminal"), "plan.terminal"), + strings(m.get("classFilters"), "plan.classFilters"), + strings(m.get("stepKinds"), "plan.stepKinds"), + member(m.get("sequentialize"), Boolean.class, "plan.sequentialize"), + member(m.get("firstLine"), Number.class, "plan.firstLine").intValue(), + member(m.get("lastLine"), Number.class, "plan.lastLine").intValue()); + } + + private static List strings(Object json, String what) { + List list = member(json, List.class, what); + List out = new ArrayList<>(list.size()); + for (int i = 0; i < list.size(); i++) out.add(member(list.get(i), String.class, what + "[" + i + "]")); + return List.copyOf(out); + } + + private static T member(Object value, Class type, String what) { + if (!type.isInstance(value)) throw new IllegalArgumentException(what + " is not a " + type.getSimpleName() + ": " + value); + return type.cast(value); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java new file mode 100644 index 0000000000..f6896a2dce --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java @@ -0,0 +1,1054 @@ +package ai.openidea.jvminspect; + +import ai.openidea.jvminspect.InspectCommand.Failure; +import ai.openidea.jvminspect.JavaDebugSessions.Hub; +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.ClassType; +import com.sun.jdi.Field; +import com.sun.jdi.IncompatibleThreadStateException; +import com.sun.jdi.IntegerValue; +import com.sun.jdi.InvocationException; +import com.sun.jdi.LocalVariable; +import com.sun.jdi.LongValue; +import com.sun.jdi.Location; +import com.sun.jdi.Method; +import com.sun.jdi.ObjectCollectedException; +import com.sun.jdi.ObjectReference; +import com.sun.jdi.ReferenceType; +import com.sun.jdi.StackFrame; +import com.sun.jdi.ThreadReference; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.Value; +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.event.Event; +import com.sun.jdi.event.EventSet; +import com.sun.jdi.event.MethodEntryEvent; +import com.sun.jdi.event.MethodExitEvent; +import com.sun.jdi.event.VMDeathEvent; +import com.sun.jdi.event.VMDisconnectEvent; +import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.MethodEntryRequest; +import com.sun.jdi.request.MethodExitRequest; +import com.sun.jdi.request.StepRequest; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.ToLongFunction; + +/** + * One stream trace of a real run, from {@code stream.arm} to {@code stream.release} (spec §5.1). + * + *

After {@code arm} the client continues the thread. Each build-phase {@code MethodExit} of the + * chain's next op is held, and the op's stream comes back as {@code stream.peek(recorder_k)} through + * {@code forceEarlyReturn}. At the terminal's {@code MethodEntry}, with no method request left on, the + * bundle runs the terminal once by {@code invokeMethod}, forces its outcome as the entered frame's, and + * keeps the thread held ({@link State#PARKED}) for the client's DAP {@code stepOut}. + * + *

java-debug's event thread only filters, parks and hands events to {@link #worker}; it takes no + * lock but {@link #stateLock}, which is never held across a JDI call. Everything that touches the + * traced thread runs on the worker, one task at a time; the fields marked "worker" are touched + * nowhere else once {@code arm} returns. Commands wait on the worker, never the other way round. + */ +final class RealRunTrace { + static final int DEFAULT_BUDGET = 50_000; + /** The prefix of the message of the exception that cancels the terminal. */ + static final String CANCEL_PREFIX = "oi-cancel:"; + static final String CANCELLED = "cancelled before the terminal ran"; + static final String EXITED = "the program began to exit while the terminal ran, and the VM cannot finish exiting while" + + " the debugger runs code in it: stop the debug session"; + private static final Set STREAM_TYPES = Set.of("java.util.stream.Stream", "java.util.stream.IntStream", + "java.util.stream.LongStream", "java.util.stream.DoubleStream"); + /** Ops that change how the stream runs, not its elements: matched like steps, never wrapped. */ + private static final Set MODIFIERS = Set.of("parallel", "sequential", "unordered", "onClose"); + /** Elements per JDWP {@code ArrayReference.GetValues} (spec v2 §7). */ + private static final int CHUNK = 16_384; + private static final long ABORT_STEP_MS = 2_000; + private static final long LIVENESS_POLL_MS = 500; + /** How long a command waits for the worker to take the trace down before answering anyway. */ + private static final long WORKER_WAIT_MS = 10_000; + private static final int INVOKE = ObjectReference.INVOKE_SINGLE_THREADED; + + enum State { + /** Set up; the client has not continued the thread yet. */ + ARMED("running"), + BUILDING("running"), + TERMINAL_RUNNING("running"), + /** The terminal returned or threw; the thread is held until the client steps out. */ + PARKED("parked"), + FAILED("failed"), + /** Stopped or aborted before the terminal ran: taken down, the program untouched. */ + CANCELLED("cancelled"); + + final String wire; + + State(String wire) { + this.wire = wire; + } + } + + /** One entry of a method's line table. */ + record LineEntry(int line, long codeIndex) {} + + final long id; + final VirtualMachine vm; + final ThreadReference thread; + final RealRunPlan plan; + final int budget; + /** The stop {@code arm} ran in; {@code collect} needs a later one. */ + private final long generation; + private final long armedNanos = System.nanoTime(); + /** Failures nobody could be told about when they happened: listener errors, cleanup that did not work. */ + private final List errors = new CopyOnWriteArrayList<>(); + private final ThreadPoolExecutor worker; + + private final Object stateLock = new Object(); + private State state = State.ARMED; + private String detail; + private boolean released; + private String terminalKind; + private Value terminalValue; + + // Set by arm before any event can arrive, then only read. + private Method userMethod; + private int depth; + private ClassType recorder; + private Method stepRecorder; + private ObjectReference log; + private ObjectReference cancel; + private JavaDebugSessions.Subscription subscription; + private final List silencers = new CopyOnWriteArrayList<>(); + private final List pinned = new CopyOnWriteArrayList<>(); + /** The log's counts last read, answered once the VM is gone. */ + private volatile int size; + private volatile long dropped; + /** The worker is inside the terminal's invoke, which may never return. Cleared under {@link #silenceLock}. */ + private volatile boolean invoking; + /** Fires once inside the terminal's invoke; see {@link #wakeInsideInvoke}. Its event is not the trace's. */ + private volatile EventRequest wake; + /** + * Orders {@link #resilence} before the restore that follows the invoke: a silence that lands after + * it would leave the user's breakpoints off for good. Held across JDI calls, unlike {@code stateLock}. + */ + private final Object silenceLock = new Object(); + + // Worker. + private final List requests = new ArrayList<>(); + /** Exits of the user's class: only there to notice the statement ending before the terminal. */ + private EventRequest userExits; + /** + * Steps out of the user's frame, which JDWP reports for a frame an exception pops, unlike its + * method exit. Never switched off for the build's invokes: enabled again, it would step out of the + * op's frame instead. + */ + private StepRequest frameExit; + private int rootSkip; + /** Index of the next op in {@code plan.steps()}. */ + private int nextOp; + /** Recorder number of the next wrapped op; modifiers take none. */ + private int nextStep; + private ObjectReference lastWrapped; + /** {@code forceEarlyReturn} at a method exit makes that frame exit once more, returning the forced value. */ + private Method echoMethod; + private Value echoValue; + private EventSet parked; + private Method terminalMethod; + + private RealRunTrace(long id, VirtualMachine vm, ThreadReference thread, RealRunPlan plan, int budget, long generation) { + this.id = id; + this.vm = vm; + this.thread = thread; + this.plan = plan; + this.budget = budget; + this.generation = generation; + worker = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), task -> { + Thread t = new Thread(task, "openidea stream trace " + id); + t.setDaemon(true); + return t; + }); + worker.allowCoreThreadTimeOut(true); + } + + /** + * Checks that the chain has not started, silences the user's breakpoints, defines the recorder if + * the VM has none, creates the log and the cancel exception, listens to java-debug's events and + * watches the chain's construction. {@code thread} must be suspended by an event: this invokes + * into it. On failure everything done so far is undone. + * + * @param generation the client's stop this runs in + */ + static RealRunTrace arm(long id, VirtualMachine vm, ThreadReference thread, RealRunPlan plan, int budget, long generation, Hub hub) + throws Exception { + RealRunTrace trace = new RealRunTrace(id, vm, thread, plan, budget, generation); + try { + trace.setUp(hub); + return trace; + } catch (Exception | Error e) { + trace.release(); + throw e; + } + } + + private void setUp(Hub hub) throws Exception { + StackFrame frame = thread.frame(0); + Location at = frame.location(); + userMethod = at.method(); + depth = thread.frameCount(); + // A stop inside one of the chain's own lambdas passes the line check (the lambda's code starts + // on a chain line), but the root call is made by the frame running the chain, never from here. + // A chain written inside a lambda body has its lines in the lambda alone, and stays traceable. + if (isLambda(userMethod) && chainRunsBelow(at.lineNumber())) { + throw new Failure("notAtChainStart", "line " + at.lineNumber() + " is inside " + userMethod.name() + + ", a lambda of the chain on line " + (plan.firstLine() + 1) + ", which a caller runs"); + } + if (!atChainStart(new LineEntry(at.lineNumber(), at.codeIndex()), plan.firstLine(), lineTable(userMethod))) { + throw new Failure("notAtChainStart", "line " + at.lineNumber() + ", code index " + at.codeIndex() + + ", is not where the statement on line " + (plan.firstLine() + 1) + " starts"); + } + LocalVariable local = plan.root() == null ? streamLocal(frame) : null; + ObjectReference held = null; + if (local != null) { + if (!(frame.getValue(local) instanceof ObjectReference stream)) throw new Failure("unsupported", plan.local() + " is null"); + held = stream; + } + // Before the first invoke: a breakpoint hit inside it would hang the session. + silencers.add(Silencer.silence(vm.eventRequestManager())); + recorder = RecorderLoader.classFor(vm, thread); + stepRecorder = RecorderLoader.method(recorder, "", "(LOiRecorder;I)V"); + log = keep(RecorderLoader.pin(() -> recorder.newInstance(thread, RecorderLoader.method(recorder, "", "(I)V"), + List.of(vm.mirrorOf(budget)), INVOKE))); + ClassType runtimeException = RecorderLoader.classType(vm, "java.lang.RuntimeException"); + byte[] nonce = new byte[8]; + new SecureRandom().nextBytes(nonce); + String message = CANCEL_PREFIX + HexFormat.of().formatHex(nonce); + cancel = keep(RecorderLoader.pin(() -> runtimeException.newInstance(thread, + RecorderLoader.method(runtimeException, "", "(Ljava/lang/String;)V"), List.of(vm.mirrorOf(message)), INVOKE))); + 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()); + // The invokes resumed the thread, which invalidated the frame read before them. + thread.frame(0).setValue(local, lastWrapped); + } else { + rootSkip = plan.root().skip(); + } + // 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. + frameExit = vm.eventRequestManager().createStepRequest(thread, StepRequest.STEP_MIN, StepRequest.STEP_OUT); + own(frameExit); + if (held != null && plan.steps().isEmpty()) { + watchTerminal(); + } else { + watchBuild(); + } + synchronized (stateLock) { + // Publishes the fields above to the worker, whose tasks start under this lock. + } + } + + /** + * Whether a stop is where the chain's statement starts: on or after its first line, with no code + * of those lines before it. javac puts a statement's first instruction on its first line. ECJ, the + * compiler JDT LS builds with, gives a head like {@code List out =} no code, so the first + * instruction is on a later line, and an assignment head's line may hold only the store after the + * chain. + * + * @param stop 1-based line + * @param firstLine 0-based, as in the plan + * @param table the method's line table, 1-based lines + */ + static boolean atChainStart(LineEntry stop, int firstLine, List table) { + if (stop.line() - 1 < firstLine) return false; + for (LineEntry e : table) { + if (e.line() - 1 >= firstLine && e.codeIndex() < stop.codeIndex()) return false; + } + return true; + } + + /** javac names a lambda's body {@code lambda$m$0}, ECJ {@code lambda$0}; both mark it synthetic. */ + private static boolean isLambda(Method method) { + return method.isSynthetic() || method.name().startsWith("lambda$"); + } + + /** + * Whether a deeper frame of the stopped method's class has code on the chain's lines up to the + * stop's (1-based {@code stopLine}): that frame runs the chain, and the stop is in a lambda of it. + */ + private boolean chainRunsBelow(int stopLine) throws Exception { + ReferenceType type = userMethod.declaringType(); + List frames = thread.frames(); + for (StackFrame f : frames.subList(1, frames.size())) { + Method m = f.location().method(); + if (!m.declaringType().equals(type) || m.isNative()) continue; + for (LineEntry e : lineTable(m)) { + if (e.line() - 1 >= plan.firstLine() && e.line() <= stopLine) return true; + } + } + return false; + } + + private static List lineTable(Method method) throws Failure { + try { + List out = new ArrayList<>(); + for (Location l : method.allLineLocations()) out.add(new LineEntry(l.lineNumber(), l.codeIndex())); + return out; + } catch (AbsentInformationException e) { + throw new Failure("unsupported", method + " was compiled without line numbers"); + } + } + + private LocalVariable streamLocal(StackFrame frame) throws Failure { + if (plan.local() == null) throw new Failure("badArgument", "the plan has neither a root call nor a local"); + LocalVariable local; + try { + local = frame.visibleVariableByName(plan.local()); + } catch (AbsentInformationException e) { + throw new Failure("unsupported", "the method was compiled without local variable names"); + } + if (local == null) throw new Failure("unsupported", "no local " + plan.local() + " is visible here"); + if (!STREAM_TYPES.contains(local.typeName())) { + throw new Failure("unsupported", plan.local() + " is declared as " + local.typeName() + ", not as a java.util.stream stream"); + } + return local; + } + + /** On java-debug's event thread, for every event of the VM: never blocks or calls into the VM. */ + private void onEvent(HubEvent hubEvent) throws Exception { + Event event = hubEvent.event(); + if (event instanceof VMDeathEvent || event instanceof VMDisconnectEvent) { + if (fail("the VM disconnected")) worker.execute(this::teardown); + return; + } + EventRequest request = event.request(); + if (request == null || request == wake || !Long.valueOf(id).equals(request.getProperty(Silencer.OWN_PROPERTY))) return; + EventSet set = hubEvent.eventSet(); + hubEvent.park(); + worker.execute(() -> handle(event, set)); + } + + /** Worker: one held event of this trace's requests. The set is resumed unless the terminal parked it. */ + private void handle(Event event, EventSet set) { + boolean hold = false; + try { + if (!building()) return; + if (leftStatement()) { + if (fail("the chain did not run: its statement ended before " + plan.terminal().name() + " was called")) teardown(); + return; + } + if (event.request() == userExits || event.request() == frameExit) return; + if (event instanceof MethodExitEvent exit) { + onExit(exit); + } else if (event instanceof MethodEntryEvent entry) { + hold = onTerminalEntry(entry, set); + } + } catch (VMDisconnectedException e) { + fail("the VM disconnected"); + } catch (Exception | Error e) { + if (fail(e.toString())) teardown(); + } finally { + if (!hold) resume(set); + // A release that came while the terminal ran was left to the worker. + if (released()) dispose(); + } + } + + private boolean released() { + synchronized (stateLock) { + return released; + } + } + + private boolean building() { + synchronized (stateLock) { + if (released) return false; + if (state == State.ARMED) state = State.BUILDING; + return state == State.BUILDING; + } + } + + /** + * Worker. The root is matched by name, JVM arity, return type and caller, after {@code skip} such + * exits; every later op by receiver: a call on the last wrapped stream from the user's method is + * the chain's next op, so a different one means the plan does not fit the run. + */ + private void onExit(MethodExitEvent exit) throws Exception { + Method method = exit.method(); + if (echoMethod != null) { + boolean echo = method.equals(echoMethod) && Objects.equals(exit.returnValue(), echoValue); + echoMethod = null; + echoValue = null; + if (echo) return; + } + if (lastWrapped == null) { + StepSpec root = plan.root(); + if (!matches(method, root) || !STREAM_TYPES.contains(method.returnTypeName()) || !calledByUser()) return; + if (rootSkip > 0) { + rootSkip--; + return; + } + ObjectReference stream = returned(exit, root); + setEnabled(false); + replace(exit, wrap(stream, nextStep++, plan.sequentialize())); + return; + } + if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return; + StepSpec next = plan.steps().get(nextOp); + if (!matches(method, next)) { + if (fail("missed " + next.name())) teardown(); + return; + } + nextOp++; + ObjectReference stream = returned(exit, next); + if (!MODIFIERS.contains(next.name())) { + setEnabled(false); + replace(exit, wrap(stream, nextStep++, false)); + } else if (plan.sequentialize() && next.name().equals("parallel")) { + setEnabled(false); + replace(exit, invoke(stream, "sequential")); + } else { + advance(stream); + } + } + + /** Worker: returns {@code stream} from the exiting op instead of its own result. Requests are off. */ + private void replace(MethodExitEvent exit, ObjectReference stream) throws Exception { + thread.forceEarlyReturn(stream); + echoMethod = exit.method(); + echoValue = stream; + advance(stream); + } + + private void advance(ObjectReference stream) { + lastWrapped = stream; + if (nextOp == plan.steps().size()) { + watchTerminal(); + } else { + setEnabled(true); + } + } + + /** + * Worker: at the terminal's entry, with no method request left on (any slows the thread to the + * interpreter), runs the terminal once by invoke, then makes the entered frame return or throw + * what it did. + * + * @return whether the set stays held: the terminal ran and the client steps out next + */ + private boolean onTerminalEntry(MethodEntryEvent entry, EventSet set) throws Exception { + Method method = entry.method(); + // The instance filter lets static methods through. + if (method.isStatic() || method.isConstructor() || !calledByUser()) return false; + if (!matches(method, plan.terminal())) { + if (fail("missed " + plan.terminal().name())) teardown(); + return false; + } + synchronized (stateLock) { + if (released || state != State.BUILDING) return false; + state = State.TERMINAL_RUNNING; + } + stopWatching(); + // For requests java-debug made since arm, when the user added or edited a breakpoint. + silencers.add(Silencer.silence(vm.eventRequestManager())); + StackFrame frame = thread.frame(0); + ObjectReference self = frame.thisObject(); + List arguments = frame.getArgumentValues(); + String kind; + Value outcome; + wakeInsideInvoke(); + invoking = true; + try (RequestTimeout.Raised raised = RequestTimeout.raise(RequestTimeout.Knob.of(vm), Integer.MAX_VALUE)) { + outcome = self.invokeMethod(thread, method, arguments, INVOKE | ObjectReference.INVOKE_NONVIRTUAL); + kind = "void".equals(method.returnTypeName()) ? "void" : "value"; + } catch (InvocationException e) { + outcome = e.exception(); + kind = "threw"; + } finally { + synchronized (silenceLock) { + invoking = false; + } + deleteWake(); + } + try { + // First: the pending return or exception holds the outcome from then on, so the pin below + // cannot lose it to a collection. Before it, nothing keeps the object the invoke returned. + if (kind.equals("threw")) { + thread.stop((ObjectReference) outcome); + } else { + thread.forceEarlyReturn(kind.equals("void") ? vm.mirrorOfVoid() : outcome); + } + } catch (Exception e) { + // Resumed as it is, the thread would run the terminal a second time. + try { + thread.stop(cancel); + } catch (Exception again) { + errors.add("cancelling the terminal: " + again); + } + restoreSilencers(); + String why = e instanceof ObjectCollectedException + ? "the terminal ran, but what it " + (kind.equals("threw") ? "threw" : "returned") + + " was garbage collected before it could be handed back: the program got the cancel exception instead" + : "the terminal ran but its outcome could not be returned: " + e; + if (fail(why)) teardown(); + return false; + } + if (outcome instanceof ObjectReference object) keep(pinned(object)); + restoreSilencers(); + boolean hold; + synchronized (stateLock) { + terminalKind = kind; + terminalValue = outcome; + hold = !released && state == State.TERMINAL_RUNNING; + if (hold) { + state = State.PARKED; + } else if (state == State.TERMINAL_RUNNING) { + // Released while it ran: no client collects it, and a new arm on the VM must not be busy. + state = State.FAILED; + detail = "released"; + } + stateLock.notifyAll(); + } + closeSubscription(); + if (hold) { + parked = set; + terminalMethod = method; + } + return hold; + } + + /** + * Worker, right before the terminal's invoke. JDWP holds an interrupt or stop of a thread that is + * handling an event until that event's handler exits, and an invoke runs inside the handler of the + * event the thread stopped at, so {@link #abort} would reach the terminal only once it returned. + * Any event of the thread inside the invoke ends that hold, since JDWP keeps no nesting: this one + * comes on the terminal's own entry and then expires, leaving no method request on. Without it + * only a class first prepared inside the invoke ended the hold, which a VM that had run the same + * stream classes before never does. + */ + private void wakeInsideInvoke() { + MethodEntryRequest r = vm.eventRequestManager().createMethodEntryRequest(); + // Eclipse JDI sends ThreadOnly before Count whatever the call order, so only this thread's entries count. + r.addThreadFilter(thread); + r.addCountFilter(1); + r.setSuspendPolicy(EventRequest.SUSPEND_NONE); + r.putProperty(Silencer.OWN_PROPERTY, id); + wake = r; + r.enable(); + } + + /** JDWP already dropped it once it fired; deleting it again is harmless. */ + private void deleteWake() { + EventRequest r = wake; + if (r == null) return; + try { + vm.eventRequestManager().deleteEventRequest(r); + } catch (VMDisconnectedException e) { + // it went with the VM + } catch (RuntimeException e) { + errors.add("deleting the invoke's wake-up request: " + e); + } + } + + /** + * Worker: whether the user's frame is gone or past the chain's lines. An exception thrown before + * the terminal (by the root's arguments, a step's) skips the rest of the statement: uncaught, the + * frame exits; caught in the frame, it runs on outside the statement. Either way no event of the + * chain will come. + */ + private boolean leftStatement() throws IncompatibleThreadStateException { + int count = thread.frameCount(); + // At depth itself frame 0 is the user's method, so the event is that method's own exit. + if (count <= depth) return true; + Location at = thread.frame(count - depth).location(); + int line = at.lineNumber() - 1; + return !at.method().equals(userMethod) || line < plan.firstLine() || line > plan.lastLine(); + } + + private boolean calledByUser() throws IncompatibleThreadStateException { + return thread.frameCount() == depth + 1 && thread.frame(1).location().method().equals(userMethod); + } + + private static boolean matches(Method method, StepSpec spec) { + return method.name().equals(spec.name()) && method.argumentTypeNames().size() == spec.args(); + } + + private static ObjectReference returned(MethodExitEvent exit, StepSpec spec) { + if (!(exit.returnValue() instanceof ObjectReference stream)) throw new IllegalStateException(spec.name() + " returned null"); + return stream; + } + + /** {@code stream.peek(recorder of step)}, {@code .sequential()} too when asked. Requests must be off. */ + private ObjectReference wrap(ObjectReference stream, int step, boolean sequentialize) throws Exception { + ObjectReference rec = keep(RecorderLoader.pin(() -> recorder.newInstance(thread, stepRecorder, List.of(log, vm.mirrorOf(step)), INVOKE))); + ObjectReference wrapped = invoke(stream, "peek", rec); + return sequentialize ? invoke(wrapped, "sequential") : wrapped; + } + + 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))); + } + + /** Invoked virtually, so any declaration of the hierarchy does; a concrete one is preferred. */ + private static Method streamMethod(ReferenceType type, String name, int arity) { + Method found = null; + for (Method m : type.allMethods()) { + if (!m.name().equals(name) || m.argumentTypeNames().size() != arity) continue; + if (!m.isAbstract() && !m.isBridge()) return m; + if (found == null) found = m; + } + if (found == null) throw new IllegalStateException(type.name() + " has no " + name); + return found; + } + + /** Worker (or arm): one method-exit request per class filter, since JDI ANDs the filters of one request. */ + private void watchBuild() { + for (String filter : plan.classFilters()) { + MethodExitRequest r = vm.eventRequestManager().createMethodExitRequest(); + requests.add(r); + r.addThreadFilter(thread); + r.addClassFilter(filter); + own(r); + } + watchUserExits(); + } + + private void watchTerminal() { + deleteRequests(); + echoMethod = null; + echoValue = null; + MethodEntryRequest r = vm.eventRequestManager().createMethodEntryRequest(); + requests.add(r); + r.addThreadFilter(thread); + r.addInstanceFilter(lastWrapped); + // The instance filter lets static methods through: and others would arrive by the thousand. + r.addClassFilter("java.util.stream.*"); + own(r); + watchUserExits(); + } + + /** + * The user's method exits through this when the statement throws, and a frame that catches it + * next calls a method of its own class or exits. The plan's filters name JDK classes only, so no + * exit comes twice in one event set. + */ + private void watchUserExits() { + MethodExitRequest r = vm.eventRequestManager().createMethodExitRequest(); + requests.add(r); + r.addThreadFilter(thread); + r.addClassFilter(userMethod.declaringType()); + own(r); + userExits = r; + } + + private void own(EventRequest r) { + r.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); + r.putProperty(Silencer.OWN_PROPERTY, id); + r.enable(); + } + + private void setEnabled(boolean on) { + for (EventRequest r : requests) r.setEnabled(on); + } + + private void deleteRequests() { + try { + vm.eventRequestManager().deleteEventRequests(requests); + } finally { + requests.clear(); + } + } + + /** All of the trace's requests; also lets the client's DAP step out, since JDI allows one step request per thread. */ + private void stopWatching() { + try { + deleteRequests(); + } finally { + StepRequest step = frameExit; + frameExit = null; + if (step != null) vm.eventRequestManager().deleteEventRequest(step); + } + } + + /** Moves a running trace to {@link State#FAILED}; false when it was no longer running. */ + private boolean fail(String why) { + synchronized (stateLock) { + if (!state.wire.equals("running")) return false; + state = State.FAILED; + detail = why; + stateLock.notifyAll(); + return true; + } + } + + /** Worker: takes the trace's requests out and the user's breakpoints back; the program runs on untouched. */ + private void teardown() { + try { + stopWatching(); + } catch (VMDisconnectedException e) { + // they went with the VM + } catch (RuntimeException e) { + errors.add("deleting the trace's requests: " + e); + } + restoreSilencers(); + closeSubscription(); + } + + /** A request the user removed meanwhile stays off: java-debug made a new one if needed. */ + private void restoreSilencers() { + synchronized (silenceLock) { + for (Silencer s : silencers) { + try { + s.restore(); + } catch (RuntimeException e) { + errors.add("switching breakpoints back on: " + e); + } + } + } + } + + /** + * While the terminal's invoke runs: switches off breakpoints the user added since the last silence, + * since one hit inside the invoke hangs the session. + */ + private void resilence() { + synchronized (silenceLock) { + if (!invoking || state() != State.TERMINAL_RUNNING) return; + try { + Silencer s = Silencer.silence(vm.eventRequestManager()); + if (s.size() > 0) silencers.add(s); + } catch (VMDisconnectedException e) { + // nothing left to silence + } catch (RuntimeException e) { + errors.add("switching new breakpoints off: " + e); + } + } + } + + private void closeSubscription() { + JavaDebugSessions.Subscription s = subscription; + if (s != null) s.close(); + } + + /** Worker: everything the trace holds, a parked thread the client never stepped out included. */ + private void dispose() { + if (parked != null) { + if (stillParked()) resume(parked); + parked = null; + } + teardown(); + for (ObjectReference o : pinned) { + try { + o.enableCollection(); + } catch (VMDisconnectedException | ObjectCollectedException e) { + // nothing left to unpin + } catch (RuntimeException e) { + errors.add("unpinning: " + e); + } + } + pinned.clear(); + } + + /** Still in the terminal's frame: a resume now cannot undo the client's step-out stop. */ + private boolean stillParked() { + try { + return thread.isSuspended() && thread.frameCount() == depth + 1 && thread.frame(0).location().method().equals(terminalMethod); + } catch (IncompatibleThreadStateException | RuntimeException e) { + return false; + } + } + + private void resume(EventSet set) { + try { + set.resume(); + } catch (VMDisconnectedException e) { + // nothing to resume + } catch (RuntimeException e) { + errors.add("resuming the thread: " + e); + } + } + + /** Runs {@code task} on the worker and waits for it, a bounded time. Never from the worker itself. */ + private void onWorker(Runnable task) { + Future done = worker.submit(task); + try { + done.get(WORKER_WAIT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException e) { + errors.add("trace worker: " + e); + } + } + + /** Stop or abort before the terminal ran (ARMED, BUILDING) takes the trace down: nothing was changed yet. */ + private boolean cancelBeforeTerminal() { + synchronized (stateLock) { + if (state != State.ARMED && state != State.BUILDING) return false; + state = State.CANCELLED; + detail = CANCELLED; + stateLock.notifyAll(); + } + onWorker(this::teardown); + return true; + } + + State state() { + synchronized (stateLock) { + return state; + } + } + + /** java-debug no longer lists the VM: a trace still running fails, though no disconnect event reached it. */ + void vmGone() { + fail("the VM disconnected"); + } + + /** + * {@code {state, records, dropped, elapsedMs, detail?}} once the trace leaves the running states or + * after {@code ms}. While the terminal runs it also checks, every {@value #LIVENESS_POLL_MS} ms, + * whether the VM began to exit, and switches off breakpoints added meanwhile: the client keeps a + * wait open while the terminal runs, so this is the only thread that can. + */ + Map await(long ms) throws InterruptedException { + State seen; + String why; + long end = System.nanoTime() + ms * 1_000_000; + while (true) { + if (state() == State.TERMINAL_RUNNING) { + if (exiting()) { + if (fail(EXITED)) abandonTerminal(); + } else { + resilence(); + } + } + long left = (end - System.nanoTime()) / 1_000_000; + synchronized (stateLock) { + if (state.wire.equals("running") && left > 0) stateLock.wait(Math.min(left, LIVENESS_POLL_MS)); + if (!state.wire.equals("running") || end - System.nanoTime() <= 0) { + seen = state; + why = detail; + break; + } + } + } + long[] counts = counts(); + return waitReply(seen, why, counts[0], counts[1]); + } + + /** + * What {@code wait} answers once the VM is gone, from the counts last read: no JDI call. Call it + * after {@link #vmGone}. + */ + Map ended() { + State seen; + String why; + synchronized (stateLock) { + seen = state; + why = detail; + } + return Collections.unmodifiableMap(waitReply(seen, why, size, dropped)); + } + + private Map waitReply(State seen, String why, long records, long droppedRecords) { + if (why == null && !errors.isEmpty()) why = String.join("; ", errors); + Map out = Values.json("state", seen.wire, "records", records, "dropped", droppedRecords, + "elapsedMs", (System.nanoTime() - armedNanos) / 1_000_000); + if (why != null) out.put("detail", why); + return out; + } + + /** + * Whether the VM began to shut down, by {@code jdk.internal.misc.VM.initLevel} (JDK 9 and later). + * The VM never finishes exiting while the trace's invoke runs ({@code System.exit} in a lambda, + * measured on HotSpot 11 to 25), so no disconnect or VM-death event ever comes. + */ + private boolean exiting() { + try { + List types = vm.classesByName("jdk.internal.misc.VM"); + if (types.isEmpty()) return false; + ReferenceType type = types.get(0); + Field level = type.fieldByName("initLevel"); + Field shutdown = type.fieldByName("SYSTEM_SHUTDOWN"); + if (level == null || shutdown == null) return false; + Map values = type.getValues(List.of(level, shutdown)); + return Objects.equals(values.get(level), values.get(shutdown)); + } catch (VMDisconnectedException e) { + return false; + } + } + + /** + * The invoke never returns, so the worker never gets to undo the trace: the breakpoints come back + * from here. No request is left (the terminal's went before the invoke) and restoring is idempotent. + */ + private void abandonTerminal() { + restoreSilencers(); + closeSubscription(); + } + + /** The log's {@code {size, dropped}}, by field read; the last ones read once the VM is gone. */ + private long[] counts() { + try { + Map counts = log.getValues(List.of(field("size"), field("dropped"))); + size = intOf(counts.get(field("size"))); + dropped = longOf(counts.get(field("dropped"))); + } catch (VMDisconnectedException | ObjectCollectedException e) { + // the last counts read + } + return new long[] {size, dropped}; + } + + /** + * Stops recording without touching the program: the budget drops to the records so far, so the + * recorder only counts from now on. A field write, no invoke, so it works while the terminal runs. + * Before the terminal started, it takes the trace down instead. + * + * @return the records kept + */ + int stopRecording() throws Exception { + // The budget field is an int, and size never passes it. + if (!cancelBeforeTerminal()) log.setValue(field("budget"), vm.mirrorOf((int) counts()[0])); + // An append that passed the budget check before the write may still land. + return (int) counts()[0]; + } + + /** + * Interrupts the thread running the terminal, then throws the cancel exception into it, then names + * the suspended threads holding monitors, waiting {@value #ABORT_STEP_MS} ms after each of the + * first two for the invoke to return. Before the terminal started, it takes the trace down instead. + * + * @return {@code {state}}: {@code interrupted}, {@code stopped}, {@code stuck} with {@code holders}, + * {@code cancelled} (before the terminal) or {@code finished} (nothing to abort) + */ + Map abort() throws Exception { + if (cancelBeforeTerminal()) return Values.json("state", "cancelled"); + if (state() != State.TERMINAL_RUNNING) return Values.json("state", "finished"); + thread.interrupt(); + if (leftTerminal(ABORT_STEP_MS)) return Values.json("state", "interrupted"); + thread.stop(cancel); + if (leftTerminal(ABORT_STEP_MS)) return Values.json("state", "stopped"); + return Values.json("state", "stuck", "holders", holders()); + } + + private boolean leftTerminal(long ms) throws InterruptedException { + synchronized (stateLock) { + long end = System.nanoTime() + ms * 1_000_000; + for (long left = ms; state == State.TERMINAL_RUNNING && left > 0; left = (end - System.nanoTime()) / 1_000_000) { + stateLock.wait(left); + } + return state != State.TERMINAL_RUNNING; + } + } + + /** Threads the debugger holds that own a monitor: one may be what the terminal waits for. */ + private List> holders() { + List> out = new ArrayList<>(); + if (!vm.canGetOwnedMonitorInfo()) return out; + for (ThreadReference t : vm.allThreads()) { + try { + if (t.isSuspended() && !t.ownedMonitors().isEmpty()) out.add(Values.json("threadId", t.uniqueID(), "name", t.name())); + } catch (IncompatibleThreadStateException | ObjectCollectedException e) { + // it resumed or ended meanwhile + } + } + return out; + } + + /** + * The records, in the order the program made them, and the terminal's outcome, previewed into + * {@code handles}. Only once parked, in a stop after the trace's ({@code generation} newer than + * arm's). The log keeps its values alive until {@link #release}. + */ + Map collect(Handles handles, long generation) throws Failure { + String kind; + Value outcome; + synchronized (stateLock) { + if (state == State.FAILED || state == State.CANCELLED) throw new Failure("failed", detail); + if (state != State.PARKED) throw new Failure("busy", "trace " + id + " is running"); + kind = terminalKind; + outcome = terminalValue; + } + if (generation <= this.generation) { + throw new Failure("stale", "collect needs a stop after the trace's, not generation " + generation); + } + handles.begin(generation); + ToLongFunction handle = o -> { + long objectId = o.uniqueID(); + handles.put(objectId, o); + return objectId; + }; + Map fields = log.getValues(List.of(field("size"), field("dropped"), field("values"), field("steps"))); + int count = intOf(fields.get(field("size"))); + ArrayReference values = (ArrayReference) fields.get(field("values")); + ArrayReference steps = (ArrayReference) fields.get(field("steps")); + List> records = new ArrayList<>(count); + for (int from = 0; from < count; from += CHUNK) { + int n = Math.min(CHUNK, count - from); + List v = values.getValues(from, n); + List s = steps.getValues(from, n); + for (int i = 0; i < n; i++) records.add(Values.json("step", intOf(s.get(i)), "value", Values.preview(v.get(i), handle))); + } + Map terminal = switch (kind) { + case "void" -> Values.json("kind", "void"); + case "threw" -> Values.json("kind", "threw", "exception", Values.preview(outcome, handle)); + default -> Values.json("kind", "value", "value", Values.preview(outcome, handle)); + }; + 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()); + } + + /** + * Undoes everything {@link #arm} set up, resuming a parked thread the client did not step out of; + * later calls do nothing. While the terminal runs, the worker does it once the terminal returns. + */ + void release() { + boolean now; + synchronized (stateLock) { + if (released) return; + released = true; + if (state == State.ARMED || state == State.BUILDING) { + state = State.FAILED; + detail = "released"; + } + now = state != State.TERMINAL_RUNNING && !invoking; + stateLock.notifyAll(); + } + if (now) onWorker(this::dispose); + } + + private ObjectReference keep(ObjectReference pinnedObject) { + pinned.add(pinnedObject); + return pinnedObject; + } + + private static ObjectReference pinned(ObjectReference object) { + object.disableCollection(); + return object; + } + + private Field field(String name) { + return recorder.fieldByName(name); + } + + private static int intOf(Value value) { + return ((IntegerValue) value).value(); + } + + private static long longOf(Value value) { + return ((LongValue) value).value(); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RecorderLoader.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RecorderLoader.java new file mode 100644 index 0000000000..eca906edb3 --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RecorderLoader.java @@ -0,0 +1,149 @@ +package ai.openidea.jvminspect; + +import com.sun.jdi.ArrayReference; +import com.sun.jdi.ArrayType; +import com.sun.jdi.ClassObjectReference; +import com.sun.jdi.ClassType; +import com.sun.jdi.Method; +import com.sun.jdi.ObjectCollectedException; +import com.sun.jdi.ObjectReference; +import com.sun.jdi.ReferenceType; +import com.sun.jdi.ThreadReference; +import com.sun.jdi.Value; +import com.sun.jdi.VirtualMachine; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Defines {@code OiRecorder} (see {@code recorder/OiRecorder.java}) in the debuggee, once per VM, in a + * {@code SecureClassLoader} of its own whose parent is the boot loader, so it sees only the JDK and no + * class of the program can clash with it. + */ +final class RecorderLoader { + static final String CLASS_NAME = "OiRecorder"; + private static final String RESOURCE = "OiRecorder.bin"; + private static final int INVOKE = ObjectReference.INVOKE_SINGLE_THREADED; + private static final int PIN_ATTEMPTS = 3; + /** Not a WeakHashMap: a ClassType refers to its VM, so the key would never be cleared. */ + private static final Map DEFINED = new IdentityHashMap<>(); + + /** The recorder class of one VM, null until defined; also that VM's lock. */ + private static final class Slot { + ClassType type; + } + + interface Create { + ObjectReference get() throws Exception; + } + + private RecorderLoader() {} + + /** The recorder's class file, Java 8 bytecode, as {@code build.py} embeds it. */ + static byte[] bytes() throws IOException { + try (InputStream in = RecorderLoader.class.getResourceAsStream(RESOURCE)) { + if (in == null) throw new IOException(RESOURCE + " is missing from the bundle"); + return in.readAllBytes(); + } + } + + /** + * The recorder class in {@code vm}, defined on first use. {@code thread} must be suspended by an + * event: defining invokes into it. The loader and the class stay pinned for the VM's life. + */ + static ClassType classFor(VirtualMachine vm, ThreadReference thread) throws Exception { + Slot slot; + synchronized (DEFINED) { + slot = DEFINED.computeIfAbsent(vm, k -> new Slot()); + } + // Per VM: defining invokes into the debuggee, which must not hold up the other VMs. + synchronized (slot) { + if (slot.type == null) slot.type = define(vm, thread); + return slot.type; + } + } + + /** Drops the classes of VMs not in {@code live}. */ + static void retain(Set live) { + synchronized (DEFINED) { + DEFINED.keySet().retainAll(live); + } + } + + private static ClassType define(VirtualMachine vm, ThreadReference thread) throws Exception { + ClassType defined; + ClassType secureLoader = classType(vm, "java.security.SecureClassLoader"); + ObjectReference loader = pin(() -> secureLoader.newInstance(thread, + method(secureLoader, "", "(Ljava/lang/ClassLoader;)V"), Collections.singletonList(null), INVOKE)); + ObjectReference type = null; + ArrayReference array = null; + try { + byte[] bytes = bytes(); + ArrayType byteArray = (ArrayType) loaded(vm, "byte[]"); + array = (ArrayReference) pin(() -> byteArray.newInstance(bytes.length)); + List values = new ArrayList<>(bytes.length); + for (byte b : bytes) values.add(vm.mirrorOf(b)); + array.setValues(values); + Method define = method(classType(vm, "java.lang.ClassLoader"), "defineClass", "(Ljava/lang/String;[BII)Ljava/lang/Class;"); + ArrayReference code = array; + type = pin(() -> (ObjectReference) loader.invokeMethod(thread, define, + List.of(vm.mirrorOf(CLASS_NAME), code, vm.mirrorOf(0), vm.mirrorOf(bytes.length)), INVOKE)); + // defineClass only loads; until Class.forName links it, JDI's methodsByName throws ClassNotPreparedException. + ClassType classClass = classType(vm, "java.lang.Class"); + classClass.invokeMethod(thread, method(classClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"), + List.of(vm.mirrorOf(CLASS_NAME), vm.mirrorOf(true), loader), INVOKE); + defined = (ClassType) ((ClassObjectReference) type).reflectedType(); + } catch (Exception | Error e) { + loader.enableCollection(); + if (type != null) type.enableCollection(); + throw e; + } finally { + if (array != null) array.enableCollection(); + } + return defined; + } + + /** + * {@code create} with collection disabled at once. A string JDI mirrors as an argument is + * unprotected and can be collected before the call; JDWP then refuses the call before it runs, so + * only that is retried. An object collected after {@code create} returned is not: the call ran, and + * a second {@code peek} on a linked stream throws in the program. + * + * @throws ObjectCollectedException when the object {@code create} returned was collected before it + * could be pinned, or every attempt lost an argument + */ + static ObjectReference pin(Create create) throws Exception { + for (int attempt = 1; ; attempt++) { + ObjectReference object; + try { + object = create.get(); + } catch (ObjectCollectedException e) { + if (attempt == PIN_ATTEMPTS) throw e; + continue; + } + object.disableCollection(); + return object; + } + } + + static ClassType classType(VirtualMachine vm, String name) throws ConnectedVms.Unsupported { + return (ClassType) loaded(vm, name); + } + + static Method method(ClassType type, String name, String signature) throws ConnectedVms.Unsupported { + List methods = type.methodsByName(name, signature); + if (methods.isEmpty()) throw new ConnectedVms.Unsupported(type.name() + "." + name + signature + " not found"); + return methods.get(0); + } + + private static ReferenceType loaded(VirtualMachine vm, String name) throws ConnectedVms.Unsupported { + List types = vm.classesByName(name); + if (types.isEmpty()) throw new ConnectedVms.Unsupported(name + " is not loaded in the VM"); + return types.get(0); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/Silencer.java b/java/jvm-inspect/src/ai/openidea/jvminspect/Silencer.java new file mode 100644 index 0000000000..d247409848 --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/Silencer.java @@ -0,0 +1,113 @@ +package ai.openidea.jvminspect; + +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.request.BreakpointRequest; +import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.EventRequestManager; +import com.sun.jdi.request.MethodEntryRequest; +import com.sun.jdi.request.WatchpointRequest; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; + +/** + * Switches off the user's breakpoints of every kind for a trace, and back on after it. A breakpoint + * hit while the bundle invokes into the thread makes java-debug report a stop the invoke then waits + * on forever. java-debug makes a function breakpoint a {@link MethodEntryRequest} and a data + * breakpoint a watchpoint request; any method request left on also runs the terminal in the + * interpreter. + */ +final class Silencer { + /** The property that marks the bundle's own requests; its value is the trace id. */ + static final String OWN_PROPERTY = "oi"; + + private final Supplier> current; + private final List silenced; + private final int breakpoints; + + private Silencer(Supplier> current, List silenced) { + this.current = current; + this.silenced = silenced; + this.breakpoints = (int) silenced.stream().filter(Silencer::isBreakpoint).count(); + } + + static Silencer silence(EventRequestManager erm) { + return silence(() -> { + List requests = new ArrayList<>(erm.breakpointRequests()); + requests.addAll(erm.exceptionRequests()); + requests.addAll(erm.methodEntryRequests()); + requests.addAll(erm.methodExitRequests()); + requests.addAll(erm.accessWatchpointRequests()); + requests.addAll(erm.modificationWatchpointRequests()); + return requests; + }); + } + + /** Method exits are java-debug's own (a step's return value), so they are not counted. */ + private static boolean isBreakpoint(EventRequest r) { + return r instanceof BreakpointRequest || r instanceof MethodEntryRequest || r instanceof WatchpointRequest; + } + + /** + * Switches off the enabled requests not marked {@link #OWN_PROPERTY}. + * + * @param current the breakpoint, exception, method and watchpoint requests the VM has now; asked + * again by {@link #restore} + */ + static Silencer silence(Supplier> current) { + List silenced = new ArrayList<>(); + for (EventRequest r : current.get()) { + if (r.isEnabled() && r.getProperty(OWN_PROPERTY) == null) { + r.disable(); + silenced.add(r); + } + } + return new Silencer(current, silenced); + } + + /** Requests switched off and not yet restored. */ + synchronized int size() { + return silenced.size(); + } + + /** Line, function and data breakpoint requests among the silenced ones, counted when silenced. */ + int silencedBreakpoints() { + return breakpoints; + } + + /** + * Switches back on the silenced requests the VM still has; later calls do nothing. + * + * @return silenced requests not switched back on. java-debug deletes a request when the user edits + * or removes its breakpoint; a new one is already in the right state. + * @throws RuntimeException when the VM's request lists cannot be read for another reason than a + * disconnect; the requests stay silenced, so a later call can restore them + */ + synchronized int restore() { + int failures = 0; + Set present = Collections.newSetFromMap(new IdentityHashMap<>()); + try { + present.addAll(current.get()); + } catch (VMDisconnectedException e) { + // nothing is left to restore + } + for (EventRequest r : silenced) { + // Eclipse JDI enables a deleted request without complaint, re-installing a breakpoint that + // java-debug no longer lists and so never removes: only requests still listed are enabled. + if (!present.contains(r)) { + failures++; + continue; + } + try { + r.enable(); + } catch (RuntimeException e) { + failures++; + } + } + silenced.clear(); + return failures; + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java new file mode 100644 index 0000000000..7913a7c2eb --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java @@ -0,0 +1,210 @@ +package ai.openidea.jvminspect; + +import ai.openidea.jvminspect.InspectCommand.Failure; +import ai.openidea.jvminspect.VmSelector.Target; +import ai.openidea.jvminspect.VmSelector.VmInfo; +import com.sun.jdi.AbsentInformationException; +import com.sun.jdi.ClassNotLoadedException; +import com.sun.jdi.IncompatibleThreadStateException; +import com.sun.jdi.InternalException; +import com.sun.jdi.InvalidStackFrameException; +import com.sun.jdi.InvalidTypeException; +import com.sun.jdi.InvocationException; +import com.sun.jdi.ObjectCollectedException; +import com.sun.jdi.ObjectReference; +import com.sun.jdi.ThreadReference; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.VirtualMachine; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; + +/** + * The {@code openidea.jvm.stream.*} commands: trace a stream chain while the program runs it, one + * trace per VM. Replies have the shape of {@link InspectCommand}'s; the codes are matched by the Rust + * client. + */ +public final class StreamCommand implements IDelegateCommandHandler { + private static final String PREFIX = "openidea.jvm.stream."; + /** {@code stream.wait} holds a JDT LS request thread at most this long. */ + private static final long MAX_WAIT_MS = 30_000; + /** How many traces of VMs that disconnected keep their last {@code wait} answer. */ + private static final int GONE_KEPT = 16; + private static final AtomicLong IDS = new AtomicLong(); + private static final Map TRACES = 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; + + @Override + protected boolean removeEldestEntry(Map.Entry> eldest) { + return size() > GONE_KEPT; + } + }; + + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + try { + List vms = InspectCommand.connected(); + forgetGone(vms); + Target target = Target.of(arguments.get(0)); + Map args = (Map) arguments.get(1); + String name = command.substring(PREFIX.length()); + VirtualMachine vm; + try { + vm = InspectCommand.select(vms, target); + } catch (Failure e) { + Map gone = name.equals("arm") ? null : gone(args); + if (gone == null) throw e; + return InspectCommand.ok(switch (name) { + case "wait" -> gone; + case "release" -> Map.of(); + default -> throw e; + }); + } + return InspectCommand.ok(switch (name) { + case "arm" -> Values.json("traceId", arm(vm, target, args)); + case "wait" -> trace(vm, args).await(Math.min(Math.max(0, number(args, "ms").longValue()), MAX_WAIT_MS)); + 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)); + default -> throw new IllegalArgumentException("unknown command " + command); + }); + } catch (Failure e) { + return InspectCommand.error(e.code, e.getMessage()); + } catch (ConnectedVms.Unsupported e) { + return InspectCommand.error("unsupported", e.getMessage()); + } catch (Handles.Stale e) { + return InspectCommand.error("stale", e.getMessage()); + } catch (IncompatibleThreadStateException e) { + return InspectCommand.error("notSuspended", "the thread is not stopped at an event: " + e.getMessage()); + } catch (AbsentInformationException e) { + return InspectCommand.error("unsupported", "compiled without debug information: " + e.getMessage()); + } catch (ObjectCollectedException e) { + return InspectCommand.error("collected", String.valueOf(e.getMessage())); + } catch (org.eclipse.jdi.TimeoutException e) { + return InspectCommand.error("timedOut", String.valueOf(e.getMessage())); + } catch (VMDisconnectedException e) { + return InspectCommand.error("vmNotFound", "the VM disconnected"); + } catch (InvocationException | ClassNotLoadedException | InvalidTypeException | InvalidStackFrameException | InternalException + | IllegalStateException | ClassCastException e) { + // Failures the commands do not expect, from JDI or from a VM unlike the plan (a stream + // method missing, a value of another kind): still a reply the client can decode. + return InspectCommand.error("failed", e.toString()); + } + } + + /** + * A trace that is still running answers {@code busy}; one that finished (parked or failed) is + * released first, since the client never releases a finished trace itself. + */ + private static long arm(VirtualMachine vm, Target target, Map args) throws Exception { + long threadId = number(args, "threadId").longValue(); + RealRunPlan plan = RealRunPlan.of(args.get("plan")); + int budget = budget(args.get("budget")); + if (!vm.canForceEarlyReturn() || !vm.canGetMethodReturnValues()) { + throw new Failure("unsupported", "the VM cannot force early returns or report method return values"); + } + ThreadReference thread = vm.allThreads().stream().filter(t -> t.uniqueID() == threadId).findFirst() + .orElseThrow(() -> new Failure("stale", "no thread " + threadId)); + if (!thread.isSuspended()) throw new Failure("notSuspended", "thread " + threadId + " is running"); + JavaDebugSessions.Hub hub = JavaDebugSessions.of(vm) + .orElseThrow(() -> new Failure("noSession", "java-debug registered no session for this VM (hotCodeReplace is never?)")); + // The inspect commands' per-VM lock: it also keeps two arms of one VM apart, and the set-up + // invokes into the thread those commands read from. + synchronized (InspectCommand.handlesFor(vm)) { + RealRunTrace current; + synchronized (TRACES) { + current = TRACES.get(vm); + } + if (current != null && current.state().wire.equals("running")) throw new Failure("busy", "trace " + current.id + " is running"); + if (current != null) release(vm, current); + RealRunTrace trace = RealRunTrace.arm(IDS.incrementAndGet(), vm, thread, plan, budget, target.generation(), hub); + synchronized (TRACES) { + TRACES.put(vm, trace); + } + return trace.id; + } + } + + /** Under the inspect commands' lock: the previews go into their handle table, so the UI can expand them. */ + private static Map collect(VirtualMachine vm, Target target, RealRunTrace trace) throws Failure { + Handles handles = InspectCommand.handlesFor(vm); + synchronized (handles) { + return trace.collect(handles, target.generation()); + } + } + + private static RealRunTrace trace(VirtualMachine vm, Map args) throws Failure { + long id = number(args, "traceId").longValue(); + synchronized (TRACES) { + RealRunTrace trace = TRACES.get(vm); + if (trace == null || trace.id != id) throw new Failure("noTrace", "no trace " + id + " on this VM"); + return trace; + } + } + + private static Map gone(Map args) { + if (!(args.get("traceId") instanceof Number id)) return null; + synchronized (TRACES) { + return GONE.get(id.longValue()); + } + } + + /** A trace whose terminal still runs stays the VM's trace, so no arm starts beside it. */ + private static Map release(VirtualMachine vm, RealRunTrace trace) { + trace.release(); + if (!trace.state().wire.equals("running")) { + synchronized (TRACES) { + TRACES.remove(vm, trace); + } + } + return Map.of(); + } + + /** 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<>()); + for (VmInfo v : vms) live.add(v.vm()); + List gone = new ArrayList<>(); + synchronized (TRACES) { + for (Iterator> i = TRACES.entrySet().iterator(); i.hasNext(); ) { + Map.Entry e = i.next(); + if (live.contains(e.getKey())) continue; + RealRunTrace trace = e.getValue(); + trace.vmGone(); + GONE.put(trace.id, trace.ended()); + gone.add(trace); + i.remove(); + } + } + // Outside the lock: release waits on the trace's worker, which may still be talking to the VM. + for (RealRunTrace trace : gone) trace.release(); + RecorderLoader.retain(live); + } + + /** {@link RealRunTrace#DEFAULT_BUDGET} when absent; otherwise a whole number from 1 to {@link Integer#MAX_VALUE}. */ + private static int budget(Object json) throws Failure { + if (json == null) return RealRunTrace.DEFAULT_BUDGET; + if (json instanceof Number n) { + double v = n.doubleValue(); + if (v >= 1 && v <= Integer.MAX_VALUE && v == Math.rint(v)) return n.intValue(); + } + throw new Failure("badArgument", "budget must be a whole number from 1 to " + Integer.MAX_VALUE + ", not " + json); + } + + private static Number number(Map args, String name) { + Object value = args.get(name); + if (!(value instanceof Number n)) throw new IllegalArgumentException(name + " is not a number: " + value); + return n; + } +} diff --git a/java/jvm-inspect/tests/SelfTest.java b/java/jvm-inspect/tests/SelfTest.java index 2218f9ec70..d10ef2246f 100644 --- a/java/jvm-inspect/tests/SelfTest.java +++ b/java/jvm-inspect/tests/SelfTest.java @@ -2,7 +2,25 @@ package ai.openidea.jvminspect; import ai.openidea.jvminspect.VmSelector.Target; import ai.openidea.jvminspect.VmSelector.VmInfo; +import com.sun.jdi.ObjectCollectedException; +import com.sun.jdi.ObjectReference; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.request.BreakpointRequest; +import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.ExceptionRequest; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import java.util.function.DoubleConsumer; +import java.util.function.IntConsumer; +import java.util.function.LongConsumer; /** The JDI-free logic of the bundle; run with {@code build.py --test}. */ public final class SelfTest { @@ -16,6 +34,17 @@ public final class SelfTest { handles_cleared_on_new_generation(); handles_cleared_when_full(); string_preview_rule(); + silencer_switches_off_only_enabled_foreign_requests(); + silencer_skips_requests_java_debug_deleted(); + silencer_restore_fails_loudly_unless_disconnected(); + chain_start_by_javac_and_ecj_line_tables(); + pin_retries_only_a_call_that_did_not_run(); + recorder_resource_is_a_java_8_class(); + recorder_counts_past_the_budget_and_never_throws(); + plan_parsed_from_gson_json(); + sessions_found_by_vm(); + sessions_missing_field_is_unsupported(); + hub_listener_parks_and_failures_are_swallowed(); } /** Stands in for java-debug's provider: its manager has no {@code connectedVMs}. */ @@ -133,6 +162,406 @@ public final class SelfTest { pass("string_preview_rule"); } + static void silencer_switches_off_only_enabled_foreign_requests() { + EventRequest breakpoint = request(BreakpointRequest.class, true, false); + EventRequest exception = request(ExceptionRequest.class, true, false); + EventRequest disabled = request(BreakpointRequest.class, false, false); + EventRequest own = request(BreakpointRequest.class, true, true); + List requests = List.of(breakpoint, exception, disabled, own); + Silencer silencer = Silencer.silence(() -> requests); + check(!breakpoint.isEnabled() && !exception.isEnabled(), "enabled foreign requests are switched off"); + check(own.isEnabled(), "a request marked \"oi\" is left alone"); + check(silencer.size() == 2 && silencer.silencedBreakpoints() == 1, "2 silenced, 1 of them a breakpoint: " + silencer.size()); + check(silencer.restore() == 0, "nothing fails to restore"); + check(breakpoint.isEnabled() && exception.isEnabled(), "the silenced requests are on again"); + check(!disabled.isEnabled(), "a request that was off stays off"); + check(silencer.restore() == 0 && silencer.size() == 0, "a second restore does nothing"); + pass("silencer_switches_off_only_enabled_foreign_requests"); + } + + static void silencer_skips_requests_java_debug_deleted() { + // As Eclipse JDI does it: a deleted request is only gone from the manager's lists, and enable() still works on it. + EventRequest deleted = request(BreakpointRequest.class, true, false); + EventRequest kept = request(BreakpointRequest.class, true, false); + List requests = new ArrayList<>(List.of(deleted, kept)); + Silencer silencer = Silencer.silence(() -> List.copyOf(requests)); + requests.remove(deleted); + requests.add(request(BreakpointRequest.class, true, false)); // java-debug's replacement + check(silencer.restore() == 1, "the deleted request counts as one restore failure"); + check(!deleted.isEnabled(), "a deleted request is not switched back on"); + check(kept.isEnabled(), "the request after the deleted one is still restored"); + pass("silencer_skips_requests_java_debug_deleted"); + } + + static void pin_retries_only_a_call_that_did_not_run() throws Exception { + int[] calls = {0}; + ObjectReference pinned = object(false); + ObjectReference got = RecorderLoader.pin(() -> { + if (++calls[0] == 1) throw new ObjectCollectedException("an argument"); + return pinned; + }); + check(got == pinned && calls[0] == 2, "a call refused for a collected argument is made again"); + + calls[0] = 0; + try { + RecorderLoader.pin(() -> { + calls[0]++; + return object(true); + }); + throw new AssertionError("an object collected after the call must not pass for pinned"); + } catch (ObjectCollectedException expected) { + check(calls[0] == 1, "a call that ran is not made a second time"); + } + pass("pin_retries_only_a_call_that_did_not_run"); + } + + /** An {@link ObjectReference} whose {@code disableCollection} throws when {@code collected}. */ + private static ObjectReference object(boolean collected) { + return (ObjectReference) Proxy.newProxyInstance(SelfTest.class.getClassLoader(), new Class[] {ObjectReference.class}, + (proxy, method, args) -> switch (method.getName()) { + case "disableCollection" -> { + if (collected) throw new ObjectCollectedException(); + yield null; + } + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "object"; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + static void silencer_restore_fails_loudly_unless_disconnected() { + EventRequest breakpoint = request(BreakpointRequest.class, true, false); + RuntimeException[] listing = {null}; + Silencer silencer = Silencer.silence(() -> { + if (listing[0] != null) throw listing[0]; + return List.of(breakpoint); + }); + listing[0] = new IllegalStateException("listing broke"); + try { + silencer.restore(); + throw new AssertionError("an unexpected listing failure must not pass for \"nothing left\""); + } catch (IllegalStateException expected) { + check(silencer.size() == 1, "the request stays silenced for a later restore"); + } + listing[0] = null; + check(silencer.restore() == 0 && breakpoint.isEnabled(), "a later restore switches it back on"); + + EventRequest other = request(BreakpointRequest.class, true, false); + Silencer gone = Silencer.silence(() -> { + if (listing[0] != null) throw listing[0]; + return List.of(other); + }); + listing[0] = new VMDisconnectedException(); + check(gone.restore() == 1 && gone.size() == 0, "a disconnected VM: every silenced request counts as not restored"); + pass("silencer_restore_fails_loudly_unless_disconnected"); + } + + static void chain_start_by_javac_and_ecj_line_tables() { + // Measured line tables (1-based line, start pc) of one method holding + // 9 List out = 10 nums.stream() ... 12 .collect(...); + // 14 n = 15 nums.stream().count(); + // 18 System.out.println( 19 nums.stream().count()); + // 20 List one = nums.stream().map(String::valueOf).collect(...); + List javac = table(9, 0, 10, 3, 11, 13, 12, 18, 14, 30, 15, 33, 16, 44, 17, 47, 18, 60, 19, 66, 18, 76, + 20, 79, 21, 109); + List ecj = table(10, 0, 11, 8, 12, 18, 15, 30, 14, 43, 17, 44, 16, 57, 18, 60, 19, 63, 18, 76, 20, 79, + 21, 109); + check(RealRunTrace.atChainStart(entry(9, 0), 8, javac), "javac: the declaration head holds the first instruction"); + check(!RealRunTrace.atChainStart(entry(10, 3), 8, javac), "javac: the receiver was loaded on the head line already"); + check(RealRunTrace.atChainStart(entry(10, 0), 8, ecj), "ECJ: no code on the head line, the first instruction is on the next"); + check(RealRunTrace.atChainStart(entry(14, 30), 13, javac), "javac: an assignment head starts the statement"); + check(!RealRunTrace.atChainStart(entry(14, 43), 13, ecj), "ECJ: the assignment head's only code runs after the chain"); + check(RealRunTrace.atChainStart(entry(18, 60), 17, javac) && RealRunTrace.atChainStart(entry(18, 60), 17, ecj), + "a call head starts the statement for both"); + check(!RealRunTrace.atChainStart(entry(20, 85), 19, javac), "mid-line, after the first call returned"); + check(!RealRunTrace.atChainStart(entry(18, 60), 19, javac), "a stop before the statement's first line"); + check(!RealRunTrace.atChainStart(entry(21, 109), 19, javac), "a stop after the statement ran"); + pass("chain_start_by_javac_and_ecj_line_tables"); + } + + static void recorder_resource_is_a_java_8_class() throws Exception { + byte[] bytes = RecorderLoader.bytes(); + DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); + check(in.readInt() == 0xCAFEBABE, "class file magic"); + in.readUnsignedShort(); + check(in.readUnsignedShort() == 52, "major version 52 (Java 8)"); + pass("recorder_resource_is_a_java_8_class"); + } + + @SuppressWarnings("unchecked") + static void recorder_counts_past_the_budget_and_never_throws() throws Exception { + byte[] bytes = RecorderLoader.bytes(); + Class type = new ClassLoader(null) { + Class define() { + return defineClass(RecorderLoader.CLASS_NAME, bytes, 0, bytes.length); + } + }.define(); + Object log = type.getConstructor(int.class).newInstance(3); + Object step = type.getConstructor(type, int.class).newInstance(log, 1); + ((Consumer) step).accept("a"); + ((IntConsumer) step).accept(7); + ((LongConsumer) step).accept(8L); + ((DoubleConsumer) step).accept(9.5); + check(field(log, "size").equals(3) && field(log, "dropped").equals(1L), "budget 3: 3 kept, 1 dropped"); + Object[] values = (Object[]) field(log, "values"); + int[] steps = (int[]) field(log, "steps"); + check(List.of(values[0], values[1], values[2]).equals(List.of("a", 7, 8L)), "primitives are boxed: " + List.of(values)); + check(steps[0] == 1 && steps[1] == 1 && steps[2] == 1, "every record carries its step"); + + Object big = type.getConstructor(int.class).newInstance(1000); + Object bigStep = type.getConstructor(type, int.class).newInstance(big, 0); + for (int i = 0; i < 600; i++) ((IntConsumer) bigStep).accept(i); + check(field(big, "size").equals(600) && field(big, "dropped").equals(0L), "the log grows past its first capacity"); + type.getField("budget").setInt(big, 0); // "stop recording" lowers the budget below the size + ((IntConsumer) bigStep).accept(1); + check(field(big, "size").equals(600) && field(big, "dropped").equals(1L), "a budget below the size drops"); + ((Consumer) big).accept("on the log itself"); + check(field(big, "dropped").equals(2L), "the log accepting a value does not throw"); + // An endless stream drops 2^31 values in about 11 s. + type.getField("dropped").setLong(big, Integer.MAX_VALUE); + ((IntConsumer) bigStep).accept(2); + check(field(big, "dropped").equals(Integer.MAX_VALUE + 1L), "dropped counts past Integer.MAX_VALUE: " + field(big, "dropped")); + pass("recorder_counts_past_the_budget_and_never_throws"); + } + + static void plan_parsed_from_gson_json() { + // Gson hands executeCommand arguments over as maps, lists, strings, booleans and doubles. + Map json = new LinkedHashMap<>(); + json.put("root", Map.of("name", "stream", "args", 0.0, "skip", 1.0)); + json.put("local", null); + json.put("steps", List.of(Map.of("name", "filter", "args", 1.0, "skip", 0.0), Map.of("name", "map", "args", 1.0, "skip", 0.0))); + json.put("terminal", Map.of("name", "collect", "args", 1.0, "skip", 0.0)); + json.put("classFilters", List.of("java.util.stream.*", "java.util.Collection")); + json.put("stepKinds", List.of("sync", "sync")); + json.put("sequentialize", false); + json.put("firstLine", 19.0); + json.put("lastLine", 23.0); + RealRunPlan plan = RealRunPlan.of(json); + check(plan.root().equals(new RealRunPlan.StepSpec("stream", 0, 1)) && plan.local() == null, "root: " + plan.root()); + check(plan.steps().equals(List.of(new RealRunPlan.StepSpec("filter", 1, 0), new RealRunPlan.StepSpec("map", 1, 0))), "steps"); + check(plan.terminal().name().equals("collect") && plan.terminal().args() == 1, "terminal: " + plan.terminal()); + check(plan.classFilters().size() == 2 && plan.stepKinds().equals(List.of("sync", "sync")), "filters and kinds"); + check(!plan.sequentialize() && plan.firstLine() == 19 && plan.lastLine() == 23, "sequentialize and lines: " + plan); + json.remove("terminal"); + try { + RealRunPlan.of(json); + throw new AssertionError("a plan without a terminal must be rejected"); + } catch (IllegalArgumentException e) { + check(e.getMessage().contains("terminal"), "detail names the member: " + e.getMessage()); + } + pass("plan_parsed_from_gson_json"); + } + + static void sessions_found_by_vm() throws Exception { + Object vmA = new Object(); + Object vmB = new Object(); + FakeWorkspace workspace = workspace(new FakeSession(vmA), null, new FakeSession(vmB)); + JavaDebugSessions.Hub hub = JavaDebugSessions.find(workspace, vmB, SelfTest::fakeJavaDebug).orElseThrow(); + check(hub != null, "the session of vm B is found"); + check(JavaDebugSessions.find(workspace, new Object(), SelfTest::fakeJavaDebug).isEmpty(), "no session for another VM"); + pass("sessions_found_by_vm"); + } + + static void sessions_missing_field_is_unsupported() { + try { + JavaDebugSessions.find(new Object(), new Object(), SelfTest::fakeJavaDebug); + throw new AssertionError("a workspace without notificationManager must be unsupported"); + } catch (ConnectedVms.Unsupported e) { + check(e.getMessage().contains("notificationManager"), "detail names the field: " + e.getMessage()); + } + try { + JavaDebugSessions.find(workspace(new FakeSession(new Object())), new Object(), name -> null); + throw new AssertionError("a missing java-debug must be unsupported"); + } catch (ConnectedVms.Unsupported e) { + check(e.getMessage().contains(JavaDebugSessions.HCR_PROVIDER), "detail names the class: " + e.getMessage()); + } + pass("sessions_missing_field_is_unsupported"); + } + + static void hub_listener_parks_and_failures_are_swallowed() throws Exception { + Object vm = new Object(); + FakeSession session = new FakeSession(vm); + JavaDebugSessions.Hub hub = JavaDebugSessions.find(workspace(session), vm, SelfTest::fakeJavaDebug).orElseThrow(); + List failures = new ArrayList<>(); + int[] seen = {0}; + JavaDebugSessions.Subscription subscription = hub.subscribe(e -> { + seen[0]++; + if (seen[0] == 2) throw new IllegalStateException("listener bug"); + e.park(); + }, failures::add); + FakeObservable events = session.hub.events; + FakeDebugEvent first = new FakeDebugEvent(); + events.next.accept(first); + check(!first.shouldResume, "park() keeps java-debug from resuming the event set"); + events.next.accept(new FakeDebugEvent()); // must not throw: RxJava would drop the subscription + check(failures.size() == 1 && failures.get(0).getMessage().equals("listener bug"), "a listener failure is reported: " + failures); + events.error.accept(new RuntimeException("hub failed")); + check(failures.size() == 2, "a hub error is reported: " + failures); + subscription.close(); + check(events.disposed, "closing disposes the subscription"); + pass("hub_listener_parks_and_failures_are_swallowed"); + } + + /** Stand-ins for java-debug and RxJava, found by {@link #fakeJavaDebug} under their real names. */ + public interface FakeConsumer { + void accept(Object value) throws Exception; + } + + public interface FakeDisposable { + void dispose(); + } + + public static final class FakeObservable { + FakeConsumer next; + FakeConsumer error; + boolean disposed; + + public FakeDisposable subscribe(FakeConsumer next, FakeConsumer error) { + this.next = next; + this.error = error; + return () -> disposed = true; + } + } + + public interface FakeEventHubApi { + FakeObservable events(); + } + + public static final class FakeEventHub implements FakeEventHubApi { + final FakeObservable events = new FakeObservable(); + + @Override + public FakeObservable events() { + return events; + } + } + + public interface FakeSessionApi { + Object getVM(); + + FakeEventHubApi getEventHub(); + } + + public static final class FakeSession implements FakeSessionApi { + final Object vm; + final FakeEventHub hub = new FakeEventHub(); + + FakeSession(Object vm) { + this.vm = vm; + } + + @Override + public Object getVM() { + return vm; + } + + @Override + public FakeEventHubApi getEventHub() { + return hub; + } + } + + public static final class FakeDebugEvent { + public Object event; + public Object eventSet; + public boolean shouldResume = true; + } + + static final class FakeHcrProvider { + final Object currentDebugSession; + + FakeHcrProvider(Object session) { + this.currentDebugSession = session; + } + } + + static final class FakeEntry { + final Object listener; + + FakeEntry(Object listener) { + this.listener = listener; + } + } + + static final class FakeListenerList { + final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); + } + + static final class FakeNotifications { + final FakeListenerList listeners = new FakeListenerList(); + } + + static final class FakeWorkspace { + final FakeNotifications notificationManager = new FakeNotifications(); + } + + /** A workspace whose listeners are one unrelated listener and one HCR provider per session (null: a provider with no session). */ + private static FakeWorkspace workspace(FakeSession... sessions) { + FakeWorkspace workspace = new FakeWorkspace(); + workspace.notificationManager.listeners.listeners.add(new FakeEntry(new Object())); + for (FakeSession s : sessions) workspace.notificationManager.listeners.listeners.add(new FakeEntry(new FakeHcrProvider(s))); + return workspace; + } + + private static Class fakeJavaDebug(String name) { + return switch (name) { + case JavaDebugSessions.HCR_PROVIDER -> FakeHcrProvider.class; + case JavaDebugSessions.SESSION -> FakeSessionApi.class; + case JavaDebugSessions.EVENT_HUB -> FakeEventHubApi.class; + case JavaDebugSessions.OBSERVABLE -> FakeObservable.class; + case JavaDebugSessions.CONSUMER -> FakeConsumer.class; + case JavaDebugSessions.DISPOSABLE -> FakeDisposable.class; + default -> null; + }; + } + + /** An {@link EventRequest} of {@code type} that only knows enabling and properties. */ + private static EventRequest request(Class type, boolean enabled, boolean own) { + boolean[] on = {enabled}; + Map properties = new HashMap<>(); + if (own) properties.put(Silencer.OWN_PROPERTY, 1L); + return (EventRequest) Proxy.newProxyInstance(SelfTest.class.getClassLoader(), new Class[] {type}, (proxy, method, args) -> { + switch (method.getName()) { + case "isEnabled": + return on[0]; + case "enable": + case "disable": + case "setEnabled": + on[0] = method.getName().equals("enable") || (method.getName().equals("setEnabled") && (Boolean) args[0]); + return null; + case "getProperty": + return properties.get(args[0]); + case "putProperty": + properties.put(args[0], args[1]); + return null; + case "hashCode": + return System.identityHashCode(proxy); + case "equals": + return proxy == args[0]; + case "toString": + return type.getSimpleName() + (on[0] ? " on" : " off"); + default: + throw new UnsupportedOperationException(method.getName()); + } + }); + } + + /** Pairs of (1-based line, start pc). */ + private static List table(int... linesAndPcs) { + List out = new ArrayList<>(); + for (int i = 0; i < linesAndPcs.length; i += 2) out.add(entry(linesAndPcs[i], linesAndPcs[i + 1])); + return out; + } + + private static RealRunTrace.LineEntry entry(int line, long codeIndex) { + return new RealRunTrace.LineEntry(line, codeIndex); + } + + private static Object field(Object object, String name) throws ReflectiveOperationException { + return object.getClass().getField(name).get(object); + } + private static VmInfo vm(Long pid, String host, Integer port) { return new VmInfo(null, pid, host, port, null); } diff --git a/java/jvm-inspect/tests/inspect.py b/java/jvm-inspect/tests/inspect.py index 4ee84dcd06..e560953fcc 100644 --- a/java/jvm-inspect/tests/inspect.py +++ b/java/jvm-inspect/tests/inspect.py @@ -10,17 +10,20 @@ JDK 21 one while a java-debug request waits behind the count. Prints OK/FAIL/SKI import json import os import pathlib -import platform import re -import shutil -import signal -import socket import subprocess import sys import tempfile import threading import time +# -I leaves the script's directory off sys.path; the shared harness lives there. Appended, not +# prepended: this file would shadow the standard library's `inspect`. +sys.path.append(str(pathlib.Path(__file__).resolve().parent)) +sys.dont_write_bytecode = True # no __pycache__ in the source tree +from jdtls_harness import (Lsp, check, debug_session, finish, free_port, kill, report, start_jdtls, # noqa: E402 + stop_jdtls, wait_ready) + COMMANDS = ['openidea.jvm.vms', 'openidea.jvm.classes', 'openidea.jvm.instances', 'openidea.jvm.fields', 'openidea.jvm.referrers'] BREAKPOINT_LINE = 6 @@ -52,19 +55,6 @@ bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-jvm-inspect.jar javas = [p for p in os.environ.get('OPENIDEA_TEST_JAVA', '').split(os.pathsep) if p] if not javas: sys.exit('set OPENIDEA_TEST_JAVA to one or more /bin/java, separated by ' + os.pathsep) -failures = [] -T0 = time.time() - - -def report(status, name, detail=''): - print(f'[{time.time() - T0:6.1f}s] {status} {name}' + (f': {detail}' if detail else ''), flush=True) - if status == 'FAIL': - failures.append(name) - - -def check(name, ok, detail=''): - report('OK' if ok else 'FAIL', name, '' if ok else detail) - return ok def major(java): @@ -74,120 +64,11 @@ def major(java): return int(parts[1]) if parts[0] == '1' else int(re.match(r'\d+', parts[0]).group()) -class Rpc: - """Content-Length framed JSON; responses are matched by id so two threads can wait at once.""" - - def __init__(self, read, write): - self.read, self.write = read, write - self.lock = threading.Lock() - self.cv = threading.Condition() - self.next_id = 0 - self.responses = {} - self.events = [] - threading.Thread(target=self.pump, daemon=True).start() - - def pump(self): - while True: - header = b'' - while not header.endswith(b'\r\n\r\n'): - c = self.read(1) - if not c: - return - header += c - length = int(re.search(rb'Content-Length: (\d+)', header).group(1)) - body = b'' - while len(body) < length: - chunk = self.read(length - len(body)) - if not chunk: - return - body += chunk - self.receive(json.loads(body)) - - def send(self, message): - data = json.dumps(message).encode() - with self.lock: - self.write(b'Content-Length: %d\r\n\r\n' % len(data) + data) - - def allocate(self): - with self.lock: - self.next_id += 1 - return self.next_id - - def store(self, key, message): - with self.cv: - self.responses[key] = message - self.cv.notify_all() - - def wait_for(self, key, timeout, what): - end = time.time() + timeout - with self.cv: - while key not in self.responses: - if not self.cv.wait(max(0.01, end - time.time())) and time.time() > end: - raise TimeoutError(what) - return self.responses.pop(key) - - def wait_event(self, predicate, timeout, what): - end = time.time() + timeout - with self.cv: - while True: - for event in self.events: - if predicate(event): - self.events.remove(event) - return event - if not self.cv.wait(max(0.01, end - time.time())) and time.time() > end: - raise TimeoutError(what) - - -class Lsp(Rpc): - def receive(self, m): - if 'method' in m and 'id' in m: - self.send({'jsonrpc': '2.0', 'id': m['id'], 'result': None}) - elif 'method' in m: - with self.cv: - self.events.append(m) - self.cv.notify_all() - else: - self.store(m['id'], m) - - def request(self, method, params, timeout=120): - rid = self.allocate() - self.send({'jsonrpc': '2.0', 'id': rid, 'method': method, 'params': params}) - return self.wait_for(rid, timeout, method) - - def notify(self, method, params): - self.send({'jsonrpc': '2.0', 'method': method, 'params': params}) - - def command(self, command, *arguments, timeout=120): - r = self.request('workspace/executeCommand', {'command': command, 'arguments': list(arguments)}, timeout) - if 'error' in r: - raise RuntimeError(f'{command}: {r["error"]}') - return r['result'] - +class InspectLsp(Lsp): def inspect(self, name, *arguments, timeout=180): return self.command('openidea.jvm.' + name, *arguments, timeout=timeout) -class Dap(Rpc): - def receive(self, m): - if m['type'] == 'response': - self.store(m['request_seq'], m) - elif m['type'] == 'event': - with self.cv: - self.events.append(m) - self.cv.notify_all() - elif m['type'] == 'request': # runInTerminal and the like: refuse - self.send({'seq': 0, 'type': 'response', 'request_seq': m['seq'], 'command': m['command'], 'success': False}) - - def request(self, command, arguments=None, timeout=60): - rid = self.allocate() - self.send({'seq': rid, 'type': 'request', 'command': command, 'arguments': arguments or {}}) - return self.wait_for(rid, timeout, command) - - def start(self, command, arguments): - rid = self.allocate() - self.send({'seq': rid, 'type': 'request', 'command': command, 'arguments': arguments}) - - # resolved: on macOS the temp dir is under the /var symlink, and JDT LS matches canonical URIs work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-jvm-inspect-')).resolve() project = work / 'project' @@ -196,41 +77,13 @@ project = work / 'project' source = str(project / 'src' / 'Heap.java') classes = work / 'classes' subprocess.run(['javac', '-g', '--release', '8', '-Xlint:-options', '-d', str(classes), source], check=True) -config = work / 'config' -config.mkdir() -system, machine = platform.system(), platform.machine().lower() -config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux') -names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name] -(config / 'config.ini').write_bytes(next(home / n / 'config.ini' for n in names if (home / n / 'config.ini').is_file()).read_bytes()) - -jdtls = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', - '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', - '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', - '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), - '-configuration', str(config), '-data', str(work / 'data')], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=(work / 'jdtls.err').open('w')) - - -def write_jdtls(data): - jdtls.stdin.write(data) - jdtls.stdin.flush() - - -lsp = Lsp(jdtls.stdout.read, write_jdtls) +jdtls = lsp = None jvms = [] # debuggees started here launched = [] # pids of debuggees java-debug started project_name = None modules, classpaths = [], [] -def free_port(): - s = socket.socket() - s.bind(('127.0.0.1', 0)) - port = s.getsockname()[1] - s.close() - return port - - def start_jvm(java, n, xmx='256m'): port = free_port() p = subprocess.Popen([java, f'-Xmx{xmx}', f'-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:{port}', @@ -244,13 +97,7 @@ def start_jvm(java, n, xmx='256m'): def session(): - port = lsp.command('vscode.java.startDebugSession', timeout=60) - sock = socket.create_connection(('127.0.0.1', port)) - reader = sock.makefile('rb', buffering=0) - d = Dap(reader.read, sock.sendall) - d.request('initialize', {'clientID': 'openidea-jvm-inspect', 'adapterID': 'java', 'linesStartAt1': True, - 'columnsStartAt1': True, 'pathFormat': 'path'}) - return d + return debug_session(lsp, 'openidea-jvm-inspect') def stop_at_breakpoint(d, command, arguments): @@ -395,16 +242,12 @@ def check_large_heap(n): try: uri = project.as_uri() - r = lsp.request('initialize', {'processId': os.getpid(), 'rootUri': uri, 'capabilities': {'workspace': {'executeCommand': {}}}, - 'initializationOptions': {'bundles': [str(java_debug), str(bundle)], - 'settings': {'java': {'project': {'sourcePaths': ['src']}}}}, - 'workspaceFolders': [{'uri': uri, 'name': 'project'}]}, timeout=180) - registered = r['result']['capabilities'].get('executeCommandProvider', {}).get('commands', []) - if not check('JDT LS registers the bundle commands and java-debug', all(c in registered for c in COMMANDS + ['vscode.java.startDebugSession']), + wanted = COMMANDS + ['vscode.java.startDebugSession'] + jdtls, lsp, registered = start_jdtls(home, work, project, [java_debug, bundle], wanted, InspectLsp) + if not check('JDT LS registers the bundle commands and java-debug', all(c in registered for c in wanted), [c for c in registered if c.startswith(('openidea', 'vscode.java.start'))]): sys.exit(1) - lsp.notify('initialized', {}) - lsp.wait_event(lambda m: m.get('method') == 'language/status' and m['params'].get('type') in ('ServiceReady', 'Started'), 240, 'ServiceReady') + wait_ready(lsp) lsp.notify('textDocument/didOpen', {'textDocument': {'uri': pathlib.Path(source).as_uri(), 'languageId': 'java', 'version': 1, 'text': HEAP}}) check('vms is empty before any session', ok(lsp.inspect('vms')) == []) for _ in range(30): @@ -420,27 +263,7 @@ try: except Exception as e: report('FAIL', 'harness', repr(e)) finally: - for p in jvms: - if p.poll() is None: - p.kill() - p.wait(10) - for pid in launched: - try: - os.kill(pid, signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass - try: - lsp.request('shutdown', None, 10) - lsp.notify('exit', None) - jdtls.wait(10) - except Exception: - pass - if jdtls.poll() is None: - jdtls.kill() - jdtls.wait(10) - if failures: - print(f'kept {work} (JDT LS stderr in jdtls.err, log in data/.metadata/.log)', flush=True) - else: - shutil.rmtree(work, ignore_errors=True) -print('FAILED: ' + ', '.join(failures) if failures else 'ALL OK', flush=True) -sys.exit(1 if failures else 0) + kill(jvms, launched) + if lsp: + stop_jdtls(jdtls, lsp) +sys.exit(finish(work)) diff --git a/java/jvm-inspect/tests/jdtls_harness.py b/java/jvm-inspect/tests/jdtls_harness.py new file mode 100644 index 0000000000..e26f64f78c --- /dev/null +++ b/java/jvm-inspect/tests/jdtls_harness.py @@ -0,0 +1,264 @@ +"""What inspect.py and stream.py share: JSON-RPC over LSP and DAP, a JDT LS process, OK/FAIL reports. + +Imported by path (the scripts put their own directory on sys.path), so it needs no package. +""" +import json +import os +import platform +import re +import shutil +import signal +import socket +import subprocess +import threading +import time + +failures = [] +T0 = time.time() + + +def report(status, name, detail=''): + print(f'[{time.time() - T0:6.1f}s] {status} {name}' + (f': {detail}' if detail else ''), flush=True) + if status == 'FAIL': + failures.append(name) + + +def check(name, ok, detail=''): + report('OK' if ok else 'FAIL', name, '' if ok else detail) + return ok + + +class Rpc: + """Content-Length framed JSON; responses are matched by id so two threads can wait at once.""" + + def __init__(self, read, write): + self.read, self.write = read, write + self.lock = threading.Lock() + self.cv = threading.Condition() + self.next_id = 0 + self.responses = {} + self.events = [] + threading.Thread(target=self.pump, daemon=True).start() + + def pump(self): + while True: + header = b'' + while not header.endswith(b'\r\n\r\n'): + c = self.read(1) + if not c: + return + header += c + length = int(re.search(rb'Content-Length: (\d+)', header).group(1)) + body = b'' + while len(body) < length: + chunk = self.read(length - len(body)) + if not chunk: + return + body += chunk + self.receive(json.loads(body)) + + def send(self, message): + data = json.dumps(message).encode() + with self.lock: + self.write(b'Content-Length: %d\r\n\r\n' % len(data) + data) + + def allocate(self): + with self.lock: + self.next_id += 1 + return self.next_id + + def store(self, key, message): + with self.cv: + self.responses[key] = message + self.cv.notify_all() + + def wait_for(self, key, timeout, what): + end = time.time() + timeout + with self.cv: + while key not in self.responses: + if not self.cv.wait(max(0.01, end - time.time())) and time.time() > end: + raise TimeoutError(what) + return self.responses.pop(key) + + def wait_event(self, predicate, timeout, what): + end = time.time() + timeout + with self.cv: + while True: + for event in self.events: + if predicate(event): + self.events.remove(event) + return event + if not self.cv.wait(max(0.01, end - time.time())) and time.time() > end: + raise TimeoutError(what) + + +class Lsp(Rpc): + def receive(self, m): + if 'method' in m and 'id' in m: + self.send({'jsonrpc': '2.0', 'id': m['id'], 'result': None}) + elif 'method' in m: + with self.cv: + self.events.append(m) + self.cv.notify_all() + else: + self.store(m['id'], m) + + def request(self, method, params, timeout=120): + rid = self.allocate() + self.send({'jsonrpc': '2.0', 'id': rid, 'method': method, 'params': params}) + return self.wait_for(rid, timeout, method) + + def notify(self, method, params): + self.send({'jsonrpc': '2.0', 'method': method, 'params': params}) + + def command(self, command, *arguments, timeout=120): + r = self.request('workspace/executeCommand', {'command': command, 'arguments': list(arguments)}, timeout) + if 'error' in r: + raise RuntimeError(f'{command}: {r["error"]}') + return r['result'] + + +class Dap(Rpc): + """`output` events go to `output`, not `events`.""" + + def __init__(self, read, write): + self.output = [] + super().__init__(read, write) + + def receive(self, m): + if m['type'] == 'response': + self.store(m['request_seq'], m) + elif m['type'] == 'event': + with self.cv: + if m['event'] == 'output': + self.output.append(m['body'].get('output', '')) + else: + self.events.append(m) + self.cv.notify_all() + elif m['type'] == 'request': # runInTerminal and the like: refuse + self.send({'seq': 0, 'type': 'response', 'request_seq': m['seq'], 'command': m['command'], 'success': False}) + + def request(self, command, arguments=None, timeout=60): + rid = self.allocate() + self.send({'seq': rid, 'type': 'request', 'command': command, 'arguments': arguments or {}}) + return self.wait_for(rid, timeout, command) + + def start(self, command, arguments): + rid = self.allocate() + self.send({'seq': rid, 'type': 'request', 'command': command, 'arguments': arguments}) + + +def start_jdtls(home, work, project, bundles, wanted, lsp_type=Lsp): + """JDT LS from the distribution at `home`, initialized on `project` with `bundles`. + + Returns `(process, lsp, registered)`. JDT LS can build its `initialize` reply before it has read a + bundle's command handlers, so a command of `wanted` missing from the reply is counted as + registered when executing it does not fail with "No delegateCommandHandler". + """ + process, lsp = launch_jdtls(home, work, lsp_type=lsp_type) + try: + registered = initialize(lsp, project, bundles) + late = [c for c in wanted if c not in registered and handled(lsp, c)] + except BaseException: + stop_jdtls(process, lsp) + raise + if late: + report('NOTE', 'left out of the initialize reply but handled', late) + return process, lsp, registered + late + + +def handled(lsp, command): + """Executes `command` with no arguments: any answer but a missing handler means it is registered.""" + r = lsp.request('workspace/executeCommand', {'command': command, 'arguments': []}, 60) + return 'No delegateCommandHandler' not in json.dumps(r.get('error', {})) + + +def launch_jdtls(home, work, lsp_type=Lsp): + """JDT LS from the distribution at `home` on the `java` on PATH, configured and logging under `work`.""" + config = work / 'config' + config.mkdir() + system, machine = platform.system(), platform.machine().lower() + config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux') + names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name] + (config / 'config.ini').write_bytes(next(home / n / 'config.ini' for n in names if (home / n / 'config.ini').is_file()).read_bytes()) + process = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', + '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', + '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', + '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), + '-configuration', str(config), '-data', str(work / 'data')], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=(work / 'jdtls.err').open('w')) + + def write(data): + process.stdin.write(data) + process.stdin.flush() + + return process, lsp_type(process.stdout.read, write) + + +def initialize(lsp, project, bundles): + """Initializes JDT LS on `project` (sources in `src`) with `bundles`; returns the commands it registered.""" + uri = project.as_uri() + r = lsp.request('initialize', {'processId': os.getpid(), 'rootUri': uri, 'capabilities': {'workspace': {'executeCommand': {}}}, + 'initializationOptions': {'bundles': [str(b) for b in bundles], + 'settings': {'java': {'project': {'sourcePaths': ['src']}}}}, + 'workspaceFolders': [{'uri': uri, 'name': project.name}]}, timeout=180) + return r['result']['capabilities'].get('executeCommandProvider', {}).get('commands', []) + + +def wait_ready(lsp): + lsp.notify('initialized', {}) + lsp.wait_event(lambda m: m.get('method') == 'language/status' and m['params'].get('type') in ('ServiceReady', 'Started'), 240, 'ServiceReady') + + +def stop_jdtls(process, lsp): + try: + lsp.request('shutdown', None, 10) + lsp.notify('exit', None) + process.wait(10) + except Exception: + pass + if process.poll() is None: + process.kill() + process.wait(10) + + +def kill(jvms, pids): + """Stops the debuggee processes started here and the ones java-debug launched, by pid.""" + for p in jvms: + if p.poll() is None: + p.kill() + p.wait(10) + for pid in pids: + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + +def debug_session(lsp, client_id): + """A new java-debug DAP session, initialized.""" + port = lsp.command('vscode.java.startDebugSession', timeout=60) + sock = socket.create_connection(('127.0.0.1', port)) + reader = sock.makefile('rb', buffering=0) + d = Dap(reader.read, sock.sendall) + d.request('initialize', {'clientID': client_id, 'adapterID': 'java', 'linesStartAt1': True, + 'columnsStartAt1': True, 'pathFormat': 'path'}) + return d + + +def free_port(): + s = socket.socket() + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + +def finish(work): + """Keeps `work` when something failed, else removes it; prints the verdict. Returns the exit status.""" + if failures: + print(f'kept {work} (JDT LS stderr in jdtls.err, log in data/.metadata/.log)', flush=True) + else: + shutil.rmtree(work, ignore_errors=True) + print('FAILED: ' + ', '.join(failures) if failures else 'ALL OK', flush=True) + return 1 if failures else 0 diff --git a/java/jvm-inspect/tests/stream.py b/java/jvm-inspect/tests/stream.py new file mode 100644 index 0000000000..a6d81dce3e --- /dev/null +++ b/java/jvm-inspect/tests/stream.py @@ -0,0 +1,1323 @@ +"""Drive the stream-trace commands inside a real JDT LS with java-debug. + +Usage: OPENIDEA_TEST_JAVA=/bin/java[:/bin/java...] \ + python3 stream.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-.jar \ + [--bundle /path/to/openidea-jvm-inspect.jar] [--case NAME]... + +JDT LS runs on the `java` on PATH (JDK 25 for 1.63.0); every case runs once per debuggee JDK in +OPENIDEA_TEST_JAVA. `--bundle` defaults to the checked-in jar; build one from the sources with +`build.py --out `. `--case` runs only the cases whose name contains NAME. Prints +OK/FAIL/SKIP per check. + +A case is a function decorated with `@case`. It gets a stopped `Debuggee` from `launch(...)` or +`attach(...)` and drives it with the DAP helpers (`resume`, `step_out`, `expect_stop`, `breakpoints`) +and `stream(...)`. Debuggee programs live in PROGRAMS; `// @name` at the end of a line names that +line for `line('name')`. +""" +import os +import pathlib +import signal +import subprocess +import sys +import tempfile +import threading +import time + +# -I leaves the script's directory off sys.path; the shared harness lives there. Appended, not +# prepended: tests/inspect.py would shadow the standard library's `inspect`. +sys.path.append(str(pathlib.Path(__file__).resolve().parent)) +sys.dont_write_bytecode = True # no __pycache__ in the source tree +from jdtls_harness import (check, debug_session, finish, free_port, kill, report, start_jdtls, stop_jdtls, # noqa: E402 + wait_ready) + +STREAM_COMMANDS = ['openidea.jvm.stream.' + c for c in ('arm', 'wait', 'stop', 'abort', 'collect', 'release')] + +CHAINS = '''import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class Chains { + public static void main(String[] a) throws Exception { + List nums = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 4, 2, 9, 6)); + System.out.println("READY"); + while (true) { + List out = nums.stream().filter(x -> x % 2 == 0).map(String::valueOf).collect(Collectors.toList()); // @loop + Thread.sleep(50); + } + } +} +''' +# One chain per method; `main` runs the method named by its argument. The chains of A, B, C, D, G and H +# are those of the spike behind the spec's Grounding (§2, G1). +REAL = '''import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.locks.LockSupport; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class Real { + static int sideEffects; + static final List nums = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 4, 2, 9, 6)); + + static boolean keep(int x) { + sideEffects++; + return x % 2 == 0; + } + + static final class Hostile { + final int v; + + Hostile(int v) { + this.v = v; + } + + @Override + public String toString() { + throw new IllegalStateException("hostile toString"); + } + } + + public static void main(String[] a) throws Exception { + switch (a[0]) { + case "A": a(); break; + case "B": b(); break; + case "C": c(); break; + case "D": d(); break; + case "G": g(); break; + case "H": h(); break; + case "local": local(); break; + case "parallel": parallel(); break; + case "nested": nested(); break; + case "hostile": hostile(); break; + case "sr": stopRecording(Integer.parseInt(a[1])); break; + case "rel": releaseRunning(Integer.parseInt(a[1])); break; + case "inl": inLambda(); break; + case "abort": abort(); break; + case "twice": abortAfterTrace(); break; + case "exit": exit(); break; + case "mid": mid(); break; + case "fn": functionAndData(); break; + case "throws": throwsBeforeRoot(); break; + case "hit": hitWhileRunning(Integer.parseInt(a[1])); break; + default: throw new IllegalArgumentException(a[0]); + } + System.out.println("END"); + } + + static void a() { + int base = 1; + List out = nums.stream() // @A + .filter(Real::keep) + .map(x -> x * 10 + base) + .sorted() + .map(String::valueOf) + .collect(Collectors.toList()); + System.out.println("A " + out + " side=" + sideEffects); + } + + static void b() { + int sum = IntStream.range(0, 20).filter(i -> i % 3 == 0).map(i -> i * i).sum(); // @B + System.out.println("B " + sum); + } + + static void c() { + long n = nums.stream().filter(x -> x > 100).count(); // @C + System.out.println("C " + n); + } + + static void d() { + long t0 = System.nanoTime(); + long d = IntStream.range(0, 1_000_000).filter(i -> i % 7 == 0).mapToObj(Integer::toString).filter(s -> s.endsWith("7")).count(); // @D + System.out.println("D " + d + " ms=" + (System.nanoTime() - t0) / 1_000_000); + } + + static void g() { + try { + List g = nums.stream().map(x -> 10 / (x - 4)).collect(Collectors.toList()); // @G + System.out.println("G " + g); + } catch (ArithmeticException ex) { + System.out.println("G caught " + ex.getMessage()); // @G_catch + } + } + + static void h() { + int h = nums.stream().mapToInt(x -> { // @H + int y = x * 2; // @H_in + return y; + }).sum(); + System.out.println("H " + h); + long next = nums.stream().count(); // @H_next + System.out.println("H next " + next); + } + + static void local() { + List list = nums; + Stream s = nums.stream(); + long k = s.filter(x -> x > 5).count(); // @local + System.out.println("LOCAL " + k + " " + list.size()); + } + + static void parallel() { + List p = nums.parallelStream().map(x -> x + 1).collect(Collectors.toList()); // @parallel + List q = nums.stream().parallel().map(x -> x * 2).collect(Collectors.toList()); // @parallel2 + System.out.println("P " + p + " " + q); + } + + static void nested() { + long n = nums.stream().flatMap(x -> Stream.of(x, x)).count(); // @nested + System.out.println("NESTED " + n); + } + + static void hostile() { + List hs = new ArrayList<>(); + for (int i = 1; i <= 3; i++) hs.add(new Hostile(i)); + long n = hs.stream().filter(x -> x.v > 0).count(); // @hostile + System.out.println("HOSTILE " + n); + } + + /** Slow enough that "stop recording" lands while the terminal runs, with few records to collect. */ + static boolean evenSlowly(int i) { + if (i % 10 == 0) LockSupport.parkNanos(1_000_000); + if (i == 25_000) { + sideEffects++; // @sr_late + } + return i % 2 == 0; + } + + static void stopRecording(int size) { + long n = Stream.iterate(0, i -> i + 1).limit(size).filter(Real::evenSlowly).count(); // @sr + System.out.println("SR " + n); // @sr_old + System.out.println("SR next"); // @sr_new + } + + static void releaseRunning(int size) { + long n = Stream.iterate(0, i -> i + 1).limit(size).filter(Real::evenSlowly).count(); // @rel + long m = nums.stream().filter(x -> x > 4).count(); // @rel_next + System.out.println("REL " + n + " " + m); + } + + static void inLambda() { + Runnable r = () -> { + long k = nums.stream().filter(x -> x > 4).count(); // @in_lambda + System.out.println("INL " + k); + }; + r.run(); + } + + static void abort() { + try { + Optional f = Stream.generate(() -> 1).filter(x -> x > 1).findFirst(); // @abort + System.out.println("ABORT none " + f); + } catch (RuntimeException e) { + System.out.println("ABORT caught " + e.getMessage()); // @abort_catch + } + } + + static void abortAfterTrace() { + long evens = nums.stream().filter(x -> x % 2 == 0).map(x -> x * 10).count(); // @twice_a + System.out.println("TWICE A " + evens); + try { + long never = Stream.iterate(1L, x -> x + 1).filter(x -> x % 7 == 0).map(x -> x * 2).filter(x -> x < 0).count(); // @twice_endless + System.out.println("TWICE none " + never); + } catch (RuntimeException e) { + System.out.println("TWICE caught " + e.getMessage()); + } + } + + static void exit() { + List e = nums.stream().filter(x -> { // @exit + if (x == 8) System.exit(3); + return true; + }).collect(Collectors.toList()); + System.out.println("EXIT not reached " + e); + } + + static void mid() { + List m = nums.stream().map(String::valueOf).collect(Collectors.toList()); // @mid + List head = // @head + nums.stream() + .map(String::valueOf) + .collect(Collectors.toList()); + System.out.println("MID " + m + " " + head); + } + + static int touched; + + static boolean touch(int x) { + touched++; // @touch + return x % 2 == 0; + } + + static void functionAndData() { + long n = nums.stream().filter(Real::touch).count(); // @fn + System.out.println("FN " + n); + touch(1); // @fn_after + System.out.println("FN after " + touched); + } + + static List parse(String s) { + return new ArrayList<>(Arrays.asList(Integer.parseInt(s))); + } + + static void escapes() { + long n = parse("x").stream().filter(x -> x > 0).count(); // @escapes + System.out.println("ESCAPES not reached " + n); + } + + static void escapesLater() { + long n = nums.stream().filter(x -> x > 0).limit(parse("z").size()).count(); // @escapes_later + System.out.println("ESCAPES_LATER not reached " + n); + } + + static void throwsBeforeRoot() { + try { + escapes(); + } catch (NumberFormatException e) { + System.out.println("ESCAPES caught by the caller"); + } + try { + escapesLater(); + } catch (NumberFormatException e) { + System.out.println("ESCAPES_LATER caught by the caller"); // @later_landing + System.out.println("ESCAPES_LATER after the catch's first line"); // @later_catch + } + long n; + try { + n = parse("y").stream().filter(x -> x > 0).count(); // @caught + } catch (NumberFormatException e) { + n = -1; + } + long m = nums.stream().count(); + System.out.println("THROWS " + n + " " + m); // @throws_end + } + + static void hitWhileRunning(int size) { + long n = Stream.iterate(0, i -> i + 1).limit(size).filter(Real::evenSlowly).count(); // @hit + evenSlowly(25_000); + System.out.println("HIT " + n); + } +} +''' +# Compiled with ECJ, as JDT LS builds a project: a declaration head like `List out =` gets no +# code of its own, and an assignment head's only code is the store after the chain. +ECJ = '''import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class Ecj { + static final List nums = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 4, 2, 9, 6)); + + public static void main(String[] a) { + List out = // @ecj_head + nums.stream() // @ecj_first + .map(String::valueOf) + .collect(Collectors.toList()); + long n; + n = // @ecj_assign + nums.stream().filter(x -> x > 4).count(); + System.out.println("ECJ " + out + " " + n); + } +} +''' +PROGRAMS = {'Chains': CHAINS, 'Real': REAL, 'Ecj': ECJ} +ECJ_PROGRAMS = {'Ecj'} + +args = sys.argv[1:] + + +def option(name): + values = [] + while name in args: + i = args.index(name) + values.append(args[i + 1]) + del args[i:i + 2] + return values + + +bundle = pathlib.Path((option('--bundle') or [pathlib.Path(__file__).resolve().parents[1] / 'openidea-jvm-inspect.jar'])[0]).resolve() +only = option('--case') +home, java_debug = (pathlib.Path(a).resolve() for a in args[:2]) +javas = [p for p in os.environ.get('OPENIDEA_TEST_JAVA', '').split(os.pathsep) if p] +if not javas: + sys.exit('set OPENIDEA_TEST_JAVA to one or more /bin/java, separated by ' + os.pathsep) +# resolved: on macOS the temp dir is under the /var symlink, and JDT LS matches canonical URIs +work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-jvm-stream-')).resolve() +project = work / 'project' +(project / 'src').mkdir(parents=True) +for name, text in PROGRAMS.items(): + (project / 'src' / f'{name}.java').write_text(text) +classes = work / 'classes' +subprocess.run(['javac', '-g', '--release', '8', '-Xlint:-options', '-d', str(classes), + *[str(project / 'src' / f'{n}.java') for n in PROGRAMS if n not in ECJ_PROGRAMS]], check=True) +subprocess.run(['java', '-cp', str(home / 'plugins' / '*'), 'org.eclipse.jdt.internal.compiler.batch.Main', '-8', '-g', '-proc:none', + '-nowarn', '-d', str(classes), *[str(project / 'src' / f'{n}.java') for n in ECJ_PROGRAMS]], check=True) +jdtls = lsp = None +jvms = [] # debuggees started here +launched = [] # pids of debuggees java-debug started +project_name = None +java = None # the debuggee JDK of the current round + + +def source(program): + return str(project / 'src' / f'{program}.java') + + +def line(name, program='Chains'): + """1-based line ending in `// @name`.""" + for i, text in enumerate(PROGRAMS[program].splitlines(), 1): + if text.rstrip().endswith('// @' + name): + return i + raise KeyError(name) + + +class Debuggee: + """One DAP session stopped on `thread`; `target` selects its VM for the bundle commands.""" + + def __init__(self, dap, program, target): + self.dap, self.program, self.target = dap, program, target + self.thread = None + self.generation = 0 + + def end(self): + try: + self.dap.request('disconnect', {'terminateDebuggee': True}, 20) + except Exception as e: # the JVM is killed at exit anyway + report('NOTE', 'disconnect failed', repr(e)) + + +def session(): + return debug_session(lsp, 'openidea-jvm-stream') + + +def breakpoints(dbg, *names): + dbg.dap.request('setBreakpoints', {'source': {'path': source(dbg.program)}, + 'breakpoints': [{'line': line(n, dbg.program)} for n in names]}) + + +def expect_stop(dbg, timeout=60, what='stopped'): + """Waits for the next `stopped`; returns its body. Raises TimeoutError when none comes.""" + e = dbg.dap.wait_event(lambda e: e['event'] in ('stopped', 'terminated'), timeout, what) + if e['event'] == 'terminated': + raise AssertionError(f'{what}: the debuggee terminated') + dbg.thread = e['body']['threadId'] + dbg.generation += 1 + dbg.target = dict(dbg.target, generation=dbg.generation) + return e['body'] + + +def no_stop(dbg, seconds): + """True when no `stopped` arrives within `seconds`.""" + try: + dbg.dap.wait_event(lambda e: e['event'] == 'stopped', seconds, 'stopped') + return False + except TimeoutError: + return True + + +def resume(dbg): + dbg.dap.request('continue', {'threadId': dbg.thread}) + + +def step_out(dbg, timeout=60): + dbg.dap.request('stepOut', {'threadId': dbg.thread}) + return expect_stop(dbg, timeout, 'stepOut') + + +def top(dbg): + return dbg.dap.request('stackTrace', {'threadId': dbg.thread})['body']['stackFrames'][0] + + +def start(dbg, command, arguments, stop_at): + dbg.dap.start(command, arguments) + dbg.dap.wait_event(lambda e: e['event'] == 'initialized', 60, 'initialized') + breakpoints(dbg, *stop_at) + dbg.dap.request('setExceptionBreakpoints', {'filters': []}) + dbg.dap.request('configurationDone') + expect_stop(dbg, 120, 'first breakpoint') + return dbg + + +def launch(program='Chains', stop_at=('loop',), args=''): + """A launch of `program` with `args` stopped at the first of the `stop_at` lines.""" + d = session() + dbg = Debuggee(d, program, {}) + start(dbg, 'launch', {'mainClass': program, 'projectName': project_name, 'modulePaths': [], 'classPaths': [str(classes)], + 'cwd': str(project), 'console': 'internalConsole', 'shortenCommandLine': 'none', 'javaExec': java, + 'args': args}, + stop_at) + pid = d.request('processId')['body']['processId'] + launched.append(pid) + dbg.target = {'pid': pid, 'host': None, 'port': None, 'generation': dbg.generation} + return dbg + + +def start_jvm(program='Chains'): + """A JVM running `program` with a JDWP socket; returns its port once the program printed READY.""" + port = free_port() + p = subprocess.Popen([java, f'-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:{port}', + '-cp', str(classes), program], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + jvms.append(p) + for out in p.stdout: + if out.startswith('READY'): + break + threading.Thread(target=lambda: [None for _ in p.stdout], daemon=True).start() + return port + + +def attach(port, program='Chains', stop_at=('loop',)): + d = session() + dbg = Debuggee(d, program, {'pid': None, 'host': 'localhost', 'port': port, 'generation': 0}) + return start(dbg, 'attach', {'hostName': '127.0.0.1', 'port': port, 'timeout': 30000, 'projectName': project_name}, stop_at) + + +def stream(command, dbg, timeout=120, **arguments): + return lsp.command('openidea.jvm.stream.' + command, dbg.target, arguments, timeout=timeout) + + +def spec(name, args=0, skip=0): + return {'name': name, 'args': args, 'skip': skip} + + +def plan(at, root=spec('stream'), local=None, steps=(spec('filter', 1), spec('map', 1)), terminal=spec('collect', 1), + class_filters=('java.util.stream.*', 'java.util.Collection'), step_kinds=('sync', 'sync'), sequentialize=False, + program='Chains'): + """A `ide_streams::RealRunPlan` for the chain on line `at`; the defaults fit the `loop` chain.""" + first = line(at, program) - 1 + return {'root': root, 'local': local, 'steps': list(steps), 'terminal': terminal, 'classFilters': list(class_filters), + 'stepKinds': list(step_kinds), 'sequentialize': sequentialize, 'firstLine': first, + 'lastLine': statement_end(program, first)} + + +def statement_end(program, first): + """0-based line of the `;` that ends the statement starting on 0-based line `first`, lambda bodies skipped.""" + depth = 0 + for i, text in enumerate(PROGRAMS[program].splitlines()[first:], first): + for ch in text.split('//')[0]: + depth += ch in '({' + depth -= ch in ')}' + if ch == ';' and depth == 0: + return i + raise ValueError(f'no statement end after line {first + 1}') + + +def arm(dbg, at='loop', budget=50_000, **plan_args): + return stream('arm', dbg, threadId=dbg.thread, plan=plan(at, program=dbg.program, **plan_args), budget=budget) + + +def ok(reply): + if 'ok' not in reply: + raise AssertionError(f'expected ok, got {reply}') + return reply['ok'] + + +def error(reply): + return reply.get('error') + + +CASES = [] + + +def case(fn): + CASES.append(fn) + return fn + + +@case +def arm_busy_release(): + dbg = launch() + try: + trace = ok(arm(dbg))['traceId'] + check('arm at the chain\'s breakpoint answers a traceId', isinstance(trace, (int, float)), trace) + state = ok(stream('wait', dbg, traceId=trace, ms=0)) + check('wait on a fresh trace: running, no records', + state.get('state') == 'running' and state.get('records') == 0 and state.get('dropped') == 0, state) + # (stop on a fresh trace takes it down: real_run_cancel_before_terminal) + r = arm(dbg) + check('a second arm on the same VM is busy', error(r) == 'busy', r) + r = stream('wait', dbg, traceId=trace + 1000, ms=0) + check('an unknown traceId is noTrace', error(r) == 'noTrace', r) + check('release answers {}', ok(stream('release', dbg, traceId=trace)) == {}) + again = ok(arm(dbg))['traceId'] + check('arm after release works again', again != trace, again) + ok(stream('release', dbg, traceId=again)) + finally: + dbg.end() + + +@case +def breakpoints_silenced_until_release(): + dbg = launch() + try: + trace = ok(arm(dbg))['traceId'] + resume(dbg) + check('while armed, the breakpoint on the looping chain does not stop', no_stop(dbg, 1.5)) + ok(stream('release', dbg, traceId=trace)) + try: + body = expect_stop(dbg, 10, 'stop after release') + check('after release the same breakpoint stops again', body.get('reason') == 'breakpoint' and top(dbg)['line'] == line('loop'), + body) + except TimeoutError: + check('after release the same breakpoint stops again', False, 'no stop within 10 s') + finally: + dbg.end() + + +@case +def arm_while_running(): + dbg = launch() + try: + breakpoints(dbg) + resume(dbg) + time.sleep(0.2) + r = arm(dbg) + check('arm while the thread runs is notSuspended', error(r) == 'notSuspended', r) + breakpoints(dbg, 'loop') + expect_stop(dbg, 10) + trace = ok(arm(dbg))['traceId'] + check('arm works once the thread stops again', trace is not None) + ok(stream('release', dbg, traceId=trace)) + finally: + dbg.end() + + +@case +def arm_in_attach(): + dbg = attach(start_jvm()) + try: + trace = ok(arm(dbg))['traceId'] + check('arm in an attach session answers a traceId', trace is not None) + ok(stream('release', dbg, traceId=trace)) + finally: + dbg.end() + + +@case +def deleted_breakpoint_stays_deleted(): + dbg = launch() + try: + trace = ok(arm(dbg))['traceId'] + breakpoints(dbg) # java-debug deletes the silenced request + ok(stream('release', dbg, traceId=trace)) + resume(dbg) + check('a breakpoint removed while armed does not come back after release', no_stop(dbg, 1.5)) + finally: + dbg.end() + + +@case +def budget_out_of_range(): + dbg = launch() + try: + for budget in (0, -1, 2.5, 2 ** 31): + r = arm(dbg, budget=budget) + check(f'arm with budget {budget} is badArgument', error(r) == 'badArgument', r) + finally: + dbg.end() + + +# The real run: arm → DAP continue → wait until parked → DAP stepOut → collect. + +def real(name, *stop_at, extra=()): + """A launch of `Real ` stopped at the first of `stop_at` (default: the line named `name`).""" + return launch('Real', stop_at=stop_at or (name,), args=' '.join((name, *map(str, extra)))) + + +def wait_until_done(dbg, trace, timeout=60): + end = time.time() + timeout + while True: + state = ok(stream('wait', dbg, traceId=trace, ms=1000)) + if state['state'] != 'running' or time.time() > end: + return state + + +def run_until_parked(dbg, at, budget=50_000, timeout=60, **plan_args): + """Arms at line `at`, continues; returns (traceId, last wait reply, ms from continue to that reply).""" + trace = ok(arm(dbg, at=at, budget=budget, **plan_args))['traceId'] + t = time.time() + resume(dbg) + state = wait_until_done(dbg, trace, timeout) + return trace, state, (time.time() - t) * 1000 + + +def step_out_and_collect(dbg, trace): + step_out(dbg) + return ok(stream('collect', dbg, traceId=trace)) + + +def show(value): + kind = value.get('kind') + if kind in ('boxed', 'primitive'): + return value.get('text') + if kind == 'string': + return '"' + str(value.get('text')) + '"' + if kind == 'null': + return 'null' + return value.get('typeName') + + +def tokens(collected): + return [f"{r['step']}={show(r['value'])}" for r in collected['records']] + + +def terminal_text(collected): + t = collected['terminal'] + return show(t['value']) if t['kind'] == 'value' else t['kind'] + + +def output_line(dbg, prefix, timeout=30): + """The first program output line starting with `prefix`, waiting for it; None when none comes.""" + end = time.time() + timeout + while time.time() < end: + for text in ''.join(dbg.dap.output).splitlines(): + if text.startswith(prefix): + return text + time.sleep(0.1) + return None + + +def collected_ok(name, collected, records=None, terminal=None, steps=None): + if records is not None: + check(f'{name}: records', tokens(collected) == records if isinstance(records, list) else len(collected['records']) == records, + ' '.join(tokens(collected)[:40])) + if terminal is not None: + check(f'{name}: terminal is {terminal}', terminal_text(collected) == terminal, collected['terminal']) + if steps is not None: + check(f'{name}: recorded steps', sorted({r['step'] for r in collected['records']}) == steps, + sorted({r['step'] for r in collected['records']})) + + +PLAN_A = dict(root=spec('stream'), steps=(spec('filter', 1), spec('map', 1), spec('sorted'), spec('map', 1)), terminal=spec('collect', 1), + step_kinds=('sync', 'sync', 'reorder', 'sync')) +GROUNDING_A = '0=5 0=3 0=8 1=8 2=81 0=1 0=4 1=4 2=41 0=2 1=2 2=21 0=9 0=6 1=6 2=61 3=21 4="21" 3=41 4="41" 3=61 4="61" 3=81 4="81"' + + +@case +def real_run_a(): + dbg = real('A') + try: + trace, state, _ = run_until_parked(dbg, 'A', **PLAN_A) + check('A: wait reaches parked', state['state'] == 'parked' and state['records'] == 24, state) + c = step_out_and_collect(dbg, trace) + collected_ok('A', c, records=GROUNDING_A.split()) + t = c['terminal'] + check('A: the terminal is the ArrayList collect returned, with an id', + t['kind'] == 'value' and t['value'].get('typeName') == 'java.util.ArrayList' and 'id' in t['value'], t) + check('A: nothing dropped, no breakpoint skipped but the chain\'s own, not sequentialized', + c['dropped'] == 0 and c['skippedBreakpoints'] == 1 and c['sequentialized'] is False, c) + resume(dbg) + out = output_line(dbg, 'A ') + check('A: the program ran each lambda once (side=8)', out == 'A [21, 41, 61, 81] side=8', out) + finally: + dbg.end() + + +@case +def real_run_b_c(): + dbg = real('B') + try: + trace, state, _ = run_until_parked(dbg, 'B', root=spec('range', 2), steps=(spec('filter', 1), spec('map', 1)), + terminal=spec('sum'), class_filters=('java.util.stream.*',)) + c = step_out_and_collect(dbg, trace) + collected_ok('B', c, records=34, terminal='819') + resume(dbg) + check('B: program output', output_line(dbg, 'B ') == 'B 819') + finally: + dbg.end() + dbg = real('C') + try: + trace, state, _ = run_until_parked(dbg, 'C', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + c = step_out_and_collect(dbg, trace) + collected_ok('C', c, records=8, terminal='0') + finally: + dbg.end() + + +@case +def real_run_d_million(): + dbg = real('D') + try: + trace, state, ms = run_until_parked(dbg, 'D', root=spec('range', 2), + steps=(spec('filter', 1), spec('mapToObj', 1), spec('filter', 1)), terminal=spec('count'), + class_filters=('java.util.stream.*',), step_kinds=('sync', 'sync', 'sync')) + report('NOTE', f'D: continue to parked {ms:.0f} ms') + check('D: continue to parked under 2000 ms', state['state'] == 'parked' and ms < 2000, f'{state} in {ms:.0f} ms') + t = time.time() + c = step_out_and_collect(dbg, trace) + report('NOTE', f'D: stepOut + collect {(time.time() - t) * 1000:.0f} ms') + collected_ok('D', c, records=50_000, terminal='14286') + check('D: dropped past the budget', c['dropped'] == 1_250_002, c['dropped']) + resume(dbg) + out = output_line(dbg, 'D ') + check('D: program output', out is not None and out.startswith('D 14286 '), out) + finally: + dbg.end() + + +@case +def real_run_g_throws(): + dbg = real('G') + try: + trace, state, _ = run_until_parked(dbg, 'G', steps=(spec('map', 1),), step_kinds=('sync',)) + check('G: parked after the lambda threw', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + t = c['terminal'] + check('G: the terminal threw ArithmeticException', + t['kind'] == 'threw' and t['exception'].get('typeName') == 'java.lang.ArithmeticException', t) + check('G: stepOut lands in the catch', top(dbg)['line'] == line('G_catch', 'Real'), top(dbg)) + resume(dbg) + check('G: program output', output_line(dbg, 'G ') == 'G caught / by zero') + finally: + dbg.end() + + +@case +def real_run_h_breakpoint_in_lambda(): + dbg = real('H', 'H', 'H_in', 'H_next') + try: + trace, state, _ = run_until_parked(dbg, 'H', steps=(spec('mapToInt', 1),), terminal=spec('sum'), step_kinds=('sync',)) + check('H: parked though a breakpoint sits in the lambda', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + collected_ok('H', c, records=16, terminal='76') + check('H: the silenced breakpoints are reported', c['skippedBreakpoints'] >= 1, c['skippedBreakpoints']) + resume(dbg) + try: + expect_stop(dbg, 20, 'next chain') + check('H: the next chain\'s breakpoint still stops', top(dbg)['line'] == line('H_next', 'Real'), top(dbg)) + except TimeoutError: + check('H: the next chain\'s breakpoint still stops', False, 'no stop') + check('H: program output', output_line(dbg, 'H ') == 'H 76') + finally: + dbg.end() + + +@case +def real_run_local_root(): + dbg = real('local') + try: + r = arm(dbg, at='local', root=None, local='list', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + check('local: a local declared as a List is unsupported', error(r) == 'unsupported', r) + trace, state, _ = run_until_parked(dbg, 'local', root=None, local='s', steps=(spec('filter', 1),), terminal=spec('count'), + class_filters=('java.util.stream.*',), step_kinds=('sync',)) + c = step_out_and_collect(dbg, trace) + collected_ok('local', c, terminal='3') + check('local: step 0 recorded every element', sum(r['step'] == 0 for r in c['records']) == 8, tokens(c)) + resume(dbg) + check('local: program output', output_line(dbg, 'LOCAL ') == 'LOCAL 3 8') + finally: + dbg.end() + + +@case +def real_run_parallel(): + dbg = real('parallel', 'parallel', 'parallel2') + try: + trace, state, _ = run_until_parked(dbg, 'parallel', root=spec('parallelStream'), steps=(spec('map', 1),), step_kinds=('sync',), + sequentialize=True) + c = step_out_and_collect(dbg, trace) + collected_ok('parallelStream', 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('parallelStream: sequentialized', c['sequentialized'] is True, c['sequentialized']) + resume(dbg) + expect_stop(dbg, 20, 'parallel2') + trace, state, _ = run_until_parked(dbg, 'parallel2', steps=(spec('parallel'), spec('map', 1)), step_kinds=('sync',), + sequentialize=True) + c = step_out_and_collect(dbg, trace) + collected_ok('parallel()', c, records='0=5 1=10 0=3 1=6 0=8 1=16 0=1 1=2 0=4 1=8 0=2 1=4 0=9 1=18 0=6 1=12'.split()) + resume(dbg) + check('parallel: program output', output_line(dbg, 'P ') == 'P [6, 4, 9, 2, 5, 3, 10, 7] [10, 6, 16, 2, 8, 4, 18, 12]') + finally: + dbg.end() + + +@case +def real_run_nested(): + dbg = real('nested') + try: + trace, state, _ = run_until_parked(dbg, 'nested', steps=(spec('flatMap', 1),), terminal=spec('count'), step_kinds=('sync',)) + c = step_out_and_collect(dbg, trace) + collected_ok('nested', c, records=24, terminal='16', steps=[0, 1]) + finally: + dbg.end() + + +@case +def real_run_hostile_to_string(): + dbg = real('hostile') + try: + trace, state, _ = run_until_parked(dbg, 'hostile', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + c = step_out_and_collect(dbg, trace) + collected_ok('hostile', c, records=['0=Real$Hostile', '1=Real$Hostile'] * 3, terminal='3') + resume(dbg) + out = output_line(dbg, 'END') + text = ''.join(dbg.dap.output) + check('hostile: no toString ran', out == 'END' and 'hostile toString' not in text and 'Exception' not in text, text[-500:]) + finally: + dbg.end() + + +SR_SIZE = 30_000 # about 3 s: the filter parks 1 ms every 10 elements + + +@case +def real_run_stop_recording_and_edit_breakpoints(): + dbg = real('sr', 'sr', 'sr_old', extra=(SR_SIZE,)) + try: + trace = ok(arm(dbg, at='sr', root=spec('iterate', 2), steps=(spec('limit', 1), spec('filter', 1)), + terminal=spec('count'), class_filters=('java.util.stream.*',)))['traceId'] + resume(dbg) + first = ok(stream('wait', dbg, traceId=trace, ms=300)) + check('stop-recording: still running after 300 ms, records growing below the budget', + first['state'] == 'running' and 0 < first['records'] < 50_000, first) + kept = ok(stream('stop', dbg, traceId=trace))['records'] + # sr_late runs inside the terminal's invoke about 2 s from now: hit there, it would hang the session. + dbg.dap.request('setBreakpoints', {'source': {'path': source('Real')}, + 'breakpoints': [{'line': line(n, 'Real')} for n in ('sr', 'sr_new', 'sr_late')]}) + later = ok(stream('wait', dbg, traceId=trace, ms=300)) + check('stop-recording: records stop growing', later['records'] <= kept + 1 and later['dropped'] > first['dropped'], (kept, later)) + state = wait_until_done(dbg, trace, 120) + check('stop-recording: the terminal still finishes', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + collected_ok('stop-recording', c, records=later['records'], terminal=str(SR_SIZE // 2)) + resume(dbg) + try: + expect_stop(dbg, 20, 'edited breakpoint') + check('edit-breakpoints: stops at the breakpoint added mid-trace, not the removed one', + top(dbg)['line'] == line('sr_new', 'Real'), top(dbg)) + except TimeoutError: + check('edit-breakpoints: stops at the breakpoint added mid-trace, not the removed one', False, 'no stop') + finally: + dbg.end() + + +@case +def real_run_abort(): + dbg = real('abort') + try: + trace = ok(arm(dbg, at='abort', root=spec('generate', 1), steps=(spec('filter', 1),), terminal=spec('findFirst'), + class_filters=('java.util.stream.*',), step_kinds=('sync',)))['traceId'] + resume(dbg) + first = ok(stream('wait', dbg, traceId=trace, ms=500)) + check('abort: the endless terminal is running', first['state'] == 'running', first) + t = time.time() + r = ok(stream('abort', dbg, traceId=trace, timeout=30)) + report('NOTE', f'abort: {r} in {(time.time() - t) * 1000:.0f} ms') + check('abort: interrupted or stopped', r.get('state') in ('interrupted', 'stopped'), r) + state = wait_until_done(dbg, trace, 20) + check('abort: parked after the cancel', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + t = c['terminal'] + check('abort: the terminal threw the cancel exception', + t['kind'] == 'threw' and t['exception'].get('typeName') == 'java.lang.RuntimeException', t) + resume(dbg) + out = output_line(dbg, 'ABORT ') + check('abort: the program caught oi-cancel', out is not None and out.startswith('ABORT caught oi-cancel:'), out) + finally: + dbg.end() + + +@case +def real_run_abort_after_a_trace(): + # The first trace loads every class the endless terminal needs, so no class is prepared inside its + # invoke: no event of the thread's own then comes between the terminal's entry and the abort. + dbg = real('twice', 'twice_a', 'twice_endless') + try: + trace, state, _ = run_until_parked(dbg, 'twice_a', terminal=spec('count'), timeout=20) + check('abort-after-trace: the first trace parks', state['state'] == 'parked', state) + collected_ok('abort-after-trace', step_out_and_collect(dbg, trace), records=16, terminal='4') + resume(dbg) + expect_stop(dbg, 20, 'twice_endless') + trace = ok(arm(dbg, at='twice_endless', root=spec('iterate', 2), steps=(spec('filter', 1), spec('map', 1), spec('filter', 1)), + terminal=spec('count'), class_filters=('java.util.stream.*',), step_kinds=('sync', 'sync', 'sync')))['traceId'] + resume(dbg) + first = ok(stream('wait', dbg, traceId=trace, ms=500)) + check('abort-after-trace: the endless terminal is running', first['state'] == 'running', first) + t = time.time() + r = ok(stream('abort', dbg, traceId=trace, timeout=30)) + report('NOTE', f'abort-after-trace: {r} in {(time.time() - t) * 1000:.0f} ms') + check('abort-after-trace: interrupted or stopped', r.get('state') in ('interrupted', 'stopped'), r) + state = wait_until_done(dbg, trace, 20) + check('abort-after-trace: parked after the cancel', state['state'] == 'parked', state) + if state['state'] != 'parked': + return + c = step_out_and_collect(dbg, trace) + t = c['terminal'] + check('abort-after-trace: the terminal threw the cancel exception', + t['kind'] == 'threw' and t['exception'].get('typeName') == 'java.lang.RuntimeException', t) + resume(dbg) + out = output_line(dbg, 'TWICE caught') + check('abort-after-trace: the program caught oi-cancel', out is not None and out.startswith('TWICE caught oi-cancel:'), out) + finally: + dbg.end() + + +def next_breakpoint_stops(dbg, name, what): + """After a trace that ended without parking: the user's breakpoints are back on.""" + try: + expect_stop(dbg, 20, what) + check(f'{name}: the next chain\'s breakpoint still stops', top(dbg)['line'] == line('H_next', 'Real'), top(dbg)) + except TimeoutError: + check(f'{name}: the next chain\'s breakpoint still stops', False, 'no stop') + resume(dbg) + + +PLAN_H = dict(steps=(spec('mapToInt', 1),), terminal=spec('sum'), step_kinds=('sync',)) + + +@case +def real_run_cancel_before_terminal(): + dbg = real('H', 'H', 'H_next') + try: + trace = ok(arm(dbg, at='H', **PLAN_H))['traceId'] + check('cancel: stop while armed answers the records', ok(stream('stop', dbg, traceId=trace)) == {'records': 0}) + state = ok(stream('wait', dbg, traceId=trace, ms=0)) + check('cancel: stop before the terminal cancels the trace', state['state'] == 'cancelled' + and state.get('detail') == 'cancelled before the terminal ran', state) + r = stream('collect', dbg, traceId=trace) + check('cancel: collect on a cancelled trace is failed', error(r) == 'failed', r) + trace = ok(arm(dbg, at='H', **PLAN_H))['traceId'] + r = ok(stream('abort', dbg, traceId=trace)) + check('cancel: abort before the terminal is cancelled', r == {'state': 'cancelled'}, r) + resume(dbg) + next_breakpoint_stops(dbg, 'cancel', 'H_next after cancel') + check('cancel: the program runs on untouched', output_line(dbg, 'H ') == 'H 76') + finally: + dbg.end() + + +@case +def real_run_missed_step(): + dbg = real('H', 'H', 'H_next') + try: + trace, state, _ = run_until_parked(dbg, 'H', steps=(spec('map', 1),), terminal=spec('sum'), step_kinds=('sync',), timeout=20) + check('missed: a chain unlike the plan fails', state['state'] == 'failed' and state.get('detail') == 'missed map', state) + next_breakpoint_stops(dbg, 'missed', 'H_next after missed') + check('missed: the program runs on untouched', output_line(dbg, 'H ') == 'H 76') + finally: + dbg.end() + + +@case +def real_run_release_while_running(): + dbg = real('rel', 'rel', 'rel_next', extra=(SR_SIZE,)) + try: + trace = ok(arm(dbg, at='rel', root=spec('iterate', 2), steps=(spec('limit', 1), spec('filter', 1)), + terminal=spec('count'), class_filters=('java.util.stream.*',)))['traceId'] + resume(dbg) + first = ok(stream('wait', dbg, traceId=trace, ms=300)) + check('release-running: the terminal runs', first['state'] == 'running' and first['records'] > 0, first) + ok(stream('release', dbg, traceId=trace)) + state = wait_until_done(dbg, trace, 60) + check('release-running: wait after the terminal returned is no longer running', + state['state'] == 'failed' and state.get('detail') == 'released', state) + r = ok(stream('abort', dbg, traceId=trace)) + check('release-running: abort leaves the thread alone', r == {'state': 'finished'}, r) + try: + expect_stop(dbg, 20, 'rel_next') + check('release-running: the next breakpoint stops', top(dbg)['line'] == line('rel_next', 'Real'), top(dbg)) + except TimeoutError: + check('release-running: the next breakpoint stops', False, 'no stop') + return + trace, state, _ = run_until_parked(dbg, 'rel_next', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + check('release-running: a new arm on the VM parks', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + collected_ok('release-running', c, terminal='4') + resume(dbg) + check('release-running: program output', output_line(dbg, 'REL ') == f'REL {SR_SIZE // 2} 4') + finally: + dbg.end() + + +@case +def real_run_lambda_frame(): + # Stopped inside the chain's own lambda, with the plan of that chain: its lines pass the line check. + dbg = real('H', 'H_in') + try: + frame = top(dbg) + check('lambda: stopped inside the chain\'s lambda', 'lambda$' in frame['name'], frame) + r = arm(dbg, at='H', **PLAN_H) + check('lambda: arm in a lambda of the chain is notAtChainStart', error(r) == 'notAtChainStart', r) + breakpoints(dbg) + resume(dbg) + check('lambda: program output', output_line(dbg, 'H ') == 'H 76') + finally: + dbg.end() + dbg = real('inl', 'in_lambda') + try: + trace, state, _ = run_until_parked(dbg, 'in_lambda', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + check('lambda: a chain written inside a lambda body is traced', state['state'] == 'parked', state) + c = step_out_and_collect(dbg, trace) + collected_ok('chain in a lambda', c, terminal='4') + resume(dbg) + check('chain in a lambda: program output', output_line(dbg, 'INL ') == 'INL 4') + finally: + dbg.end() + + +@case +def real_run_exit_in_lambda(): + dbg = real('exit') + try: + trace = ok(arm(dbg, at='exit', steps=(spec('filter', 1),), step_kinds=('sync',)))['traceId'] + t = time.time() + resume(dbg) + state = ok(stream('wait', dbg, traceId=trace, ms=5000)) + ms = (time.time() - t) * 1000 + report('NOTE', f'exit-in-lambda: continue to failed {ms:.0f} ms') + # HotSpot does not finish exiting while the exiting thread is inside a JDI invoke: no disconnect comes. + check('exit-in-lambda: wait answers failed within 5 s', state['state'] == 'failed' and ms < 5000 + and 'began to exit' in state.get('detail', ''), f'{state} in {ms:.0f} ms') + again = stream('wait', dbg, traceId=trace, ms=0) + check('exit-in-lambda: a later wait still answers failed', again.get('ok', {}).get('state') == 'failed', again) + t = time.time() + r = stream('release', dbg, traceId=trace) + check('exit-in-lambda: release does not wait on the stuck invoke', 'ok' in r and time.time() - t < 2, r) + finally: + dbg.end() + # java-debug's terminate does not end the wedged VM either; while it lingers, new launches can stall. + time.sleep(2) + try: + os.kill(dbg.target['pid'], signal.SIGKILL) + report('NOTE', 'exit-in-lambda: the VM outlived the session\'s terminate; killed') + except (ProcessLookupError, PermissionError, TypeError): + pass + + +@case +def real_run_mid_line(): + dbg = real('mid', 'mid', 'head') + try: + plan_mid = dict(steps=(spec('map', 1),), step_kinds=('sync',)) + trace = ok(arm(dbg, at='mid', **plan_mid))['traceId'] + check('mid-line: arm at the chain\'s breakpoint works', trace is not None) + ok(stream('release', dbg, traceId=trace)) + dbg.dap.request('stepIn', {'threadId': dbg.thread}) + expect_stop(dbg, 20, 'stepIn') + step_out(dbg) + check('mid-line: stepOut is back on the chain\'s line', top(dbg)['line'] == line('mid', 'Real'), top(dbg)) + r = arm(dbg, at='mid', **plan_mid) + check('mid-line: arm after the first call is notAtChainStart', error(r) == 'notAtChainStart', r) + resume(dbg) + expect_stop(dbg, 20, 'head') + trace, state, _ = run_until_parked(dbg, 'head', **plan_mid) + c = step_out_and_collect(dbg, trace) + collected_ok('declaration head on its own line (javac)', c, records=16) + finally: + dbg.end() + + +@case +def real_run_ecj_heads(): + dbg = launch('Ecj', stop_at=('ecj_first', 'ecj_assign')) + try: + plan_out = dict(steps=(spec('map', 1),), step_kinds=('sync',), program='Ecj') + r = stream('arm', dbg, threadId=dbg.thread, plan=plan('ecj_head', **plan_out), budget=50_000) + check('ECJ: arm at the first code of a statement whose head line has none', 'ok' in r, r) + trace = ok(r)['traceId'] + resume(dbg) + state = wait_until_done(dbg, trace, 20) + c = step_out_and_collect(dbg, trace) + collected_ok('ECJ head', c, records=16) + resume(dbg) + expect_stop(dbg, 20, 'ecj_assign') + r = stream('arm', dbg, threadId=dbg.thread, budget=50_000, + plan=plan('ecj_assign', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',), program='Ecj')) + check('ECJ: an assignment head whose code runs after the chain is notAtChainStart', error(r) == 'notAtChainStart', r) + finally: + dbg.end() + + +@case +def real_run_function_and_data_breakpoints(): + # java-debug makes a function breakpoint a MethodEntryRequest and a data breakpoint a watchpoint + # request; left on, either is hit inside the terminal's invoke (and slows it to the interpreter). + kinds = (('function', 'setFunctionBreakpoints', {'breakpoints': [{'name': 'Real#touch'}]}), + ('data', 'setDataBreakpoints', {'breakpoints': [{'dataId': 'Real#touched', 'accessType': 'write'}]})) + for kind, command, arguments in kinds: + dbg = real('fn') + try: + reply = dbg.dap.request(command, arguments) + check(f'{kind} breakpoint: java-debug verifies it', all(b.get('verified') for b in reply['body']['breakpoints']), reply) + trace, state, _ = run_until_parked(dbg, 'fn', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',), + timeout=20) + check(f'{kind} breakpoint: silenced while the chain runs, so the trace parks', state['state'] == 'parked', state) + if state['state'] != 'parked': + continue + c = step_out_and_collect(dbg, trace) + collected_ok(f'{kind} breakpoint', c, terminal='4') + resume(dbg) + try: + body = expect_stop(dbg, 20, f'{kind} breakpoint after the trace') + check(f'{kind} breakpoint: back on after the trace', body.get('reason') == f'{kind} breakpoint' + and top(dbg)['line'] == line('touch', 'Real'), (body, top(dbg))) + except TimeoutError: + check(f'{kind} breakpoint: back on after the trace', False, 'no stop') + finally: + dbg.end() + + +PLAN_THROWS = dict(steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',)) + + +@case +def real_run_statement_throws_before_the_root(): + # JDWP reports no method exit for a frame an exception pops: the trace must notice the caller's + # catch before the caller's next breakpoint, which is still off until then. + dbg = real('throws', 'escapes', 'escapes_later', 'later_landing', 'later_catch', 'caught', 'throws_end') + try: + trace, state, _ = run_until_parked(dbg, 'escapes', timeout=20, **PLAN_THROWS) + check('throws, uncaught in the frame: the trace fails', state['state'] == 'failed' + and state.get('detail', '').startswith('the chain did not run'), state) + try: + expect_stop(dbg, 20, 'escapes_later') + check('throws, uncaught in the frame: the next breakpoint stops', top(dbg)['line'] == line('escapes_later', 'Real'), + top(dbg)) + except TimeoutError: + check('throws, uncaught in the frame: the next breakpoint stops', False, 'no stop') + return + # The root and filter are wrapped (invokes into the thread) before limit's argument throws. + trace, state, _ = run_until_parked(dbg, 'escapes_later', timeout=20, steps=(spec('filter', 1), spec('limit', 1)), + terminal=spec('count'), step_kinds=('sync', 'sync')) + check('throws in a step argument: the trace fails', state['state'] == 'failed' + and state.get('detail', '').startswith('the chain did not run'), state) + try: + expect_stop(dbg, 20, 'later_catch') + if top(dbg)['line'] == line('later_landing', 'Real'): + report('NOTE', "throws in a step argument: the breakpoint where the step out lands stopped too") + resume(dbg) + expect_stop(dbg, 20, 'later_catch') + else: + # The step out lands on the handler's first line, with its breakpoint still off: JVMTI + # checks for a breakpoint before posting the step, so switching it on then is too late. + report('NOTE', "throws in a step argument: the breakpoint where the step out lands is missed") + check("throws in a step argument: the caller's catch stops", top(dbg)['line'] == line('later_catch', 'Real'), top(dbg)) + except TimeoutError: + check("throws in a step argument: the caller's catch stops", False, 'no stop') + return + resume(dbg) + try: + expect_stop(dbg, 20, 'caught') + check('throws: the breakpoint after stops', top(dbg)['line'] == line('caught', 'Real'), top(dbg)) + except TimeoutError: + check('throws: the breakpoint after stops', False, 'no stop') + return + trace, state, _ = run_until_parked(dbg, 'caught', timeout=20, **PLAN_THROWS) + check('throws, caught in the frame: the trace fails', state['state'] == 'failed' + and state.get('detail', '').startswith('the chain did not run'), state) + try: + expect_stop(dbg, 20, 'throws_end') + check('throws, caught in the frame: a later breakpoint stops', top(dbg)['line'] == line('throws_end', 'Real'), top(dbg)) + except TimeoutError: + check('throws, caught in the frame: a later breakpoint stops', False, 'no stop') + return + resume(dbg) + check('throws: the program runs on untouched', output_line(dbg, 'THROWS ') == 'THROWS -1 8') + finally: + dbg.end() + + +@case +def real_run_breakpoint_hit_while_running(): + # A breakpoint set while the terminal runs and hit before the bundle's next re-silence: ide-dap + # continues the thread (R32), which lets the invoke go on. No `wait` before the hit, so nothing + # re-silences it first. + dbg = real('hit', 'hit', extra=(SR_SIZE,)) + try: + trace = ok(arm(dbg, at='hit', root=spec('iterate', 2), steps=(spec('limit', 1), spec('filter', 1)), + terminal=spec('count'), class_filters=('java.util.stream.*',)))['traceId'] + traced = dbg.thread + resume(dbg) + time.sleep(0.3) + breakpoints(dbg, 'hit', 'sr_late') + try: + body = expect_stop(dbg, 20, 'sr_late inside the invoke') + check('hit-while-running: the new breakpoint stops the traced thread inside the invoke', + body.get('threadId') == traced and top(dbg)['line'] == line('sr_late', 'Real'), (body, top(dbg))) + except TimeoutError: + check('hit-while-running: the new breakpoint stops the traced thread inside the invoke', False, 'no stop') + return + dbg.dap.request('continue', {'threadId': traced}) + state = wait_until_done(dbg, trace, 30) + check('hit-while-running: after a continue the trace still parks', state['state'] == 'parked', state) + if state['state'] != 'parked': + return + c = step_out_and_collect(dbg, trace) + collected_ok('hit-while-running', c, terminal=str(SR_SIZE // 2)) + resume(dbg) + try: + expect_stop(dbg, 20, 'sr_late after the trace') + check('hit-while-running: the breakpoint is back on after the trace', top(dbg)['line'] == line('sr_late', 'Real'), top(dbg)) + except TimeoutError: + check('hit-while-running: the breakpoint is back on after the trace', False, 'no stop') + return + resume(dbg) + check('hit-while-running: program output', output_line(dbg, 'HIT ') == f'HIT {SR_SIZE // 2}') + finally: + dbg.end() + + +@case +def real_run_wait_after_the_vm_is_gone(): + # Once java-debug no longer lists the VM, `wait` still answers the trace's end from what was read + # before, without touching the dead VM. + dbg = real('fn') + trace, state, _ = run_until_parked(dbg, 'fn', steps=(spec('filter', 1),), terminal=spec('count'), step_kinds=('sync',), + timeout=20) + check('gone: the trace parks first', state['state'] == 'parked', state) + dbg.end() + # collect has no answer for a gone VM, so it tells when java-debug dropped it. + for _ in range(100): + if error(stream('collect', dbg, traceId=trace)) == 'vmNotFound': + break + time.sleep(0.1) + else: + check('gone: java-debug drops the VM', False) + return + for attempt in ('first', 'second'): + reply = stream('wait', dbg, traceId=trace, ms=0) + check(f'gone: the {attempt} wait answers the counts read before', 'ok' in reply and reply['ok']['state'] == 'parked' + and reply['ok']['records'] == state['records'], reply) + check('gone: release answers too', 'ok' in stream('release', dbg, traceId=trace)) + + +def run(): + global jdtls, lsp, project_name, java + uri = project.as_uri() + wanted = STREAM_COMMANDS + ['vscode.java.startDebugSession'] + jdtls, lsp, registered = start_jdtls(home, work, project, [java_debug, bundle], wanted) + if not check('JDT LS registers the stream commands and java-debug', all(c in registered for c in wanted), + [c for c in registered if c.startswith(('openidea', 'vscode.java.start'))]): + return + wait_ready(lsp) + for name, text in PROGRAMS.items(): + lsp.notify('textDocument/didOpen', {'textDocument': {'uri': pathlib.Path(source(name)).as_uri(), 'languageId': 'java', + 'version': 1, 'text': text}}) + for _ in range(30): + main = lsp.command('vscode.java.resolveMainClass', uri) + if main: + break + time.sleep(2) + project_name = main[0].get('projectName') + for java in javas: + report('NOTE', 'debuggee', java) + for fn in CASES: + if only and not any(o in fn.__name__ for o in only): + continue + try: + fn() + except Exception as e: + report('FAIL', fn.__name__, repr(e)) + + +try: + run() +except Exception as e: + report('FAIL', 'harness', repr(e)) +finally: + kill(jvms, launched) + if lsp: + stop_jdtls(jdtls, lsp) +sys.exit(finish(work)) diff --git a/smoke/debug.test.ts b/smoke/debug.test.ts index 23c8bc0799..7aee998166 100644 --- a/smoke/debug.test.ts +++ b/smoke/debug.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, afterEach, beforeAll, expect, test } from "vitest"; import { Channel } from "@tauri-apps/api/core"; -import { commands, type HeapProgress, type InstallEvent } from "@/bindings"; +import { commands, type HeapProgress, type InstallEvent, type TraceProgress } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { call, nextRequestId, onIdeEvent } from "@/platform/ipc"; import { useBuildModel } from "@/platform/buildModel"; @@ -20,7 +20,7 @@ import { openProject, useProject } from "@/platform/project"; import { activate as activateBuildTools } from "@/features/build-tools"; import { useBuild } from "@/features/build-tools/store"; import { activate as activateDebugger } from "@/features/debugger"; -import { addBreakpoint } from "@/features/debugger/breakpoints/store"; +import { addBreakpoint, flushBreakpoints } from "@/features/debugger/breakpoints/store"; import { activeSession, evaluate, rootOf, sessionSupports, useDebug } from "@/features/debugger/state"; import { activate as activateRun } from "@/features/run"; import { resetRuns, useRun } from "@/features/run/store"; @@ -63,6 +63,12 @@ interface Case { heap?: { className: string; instances: number }; /** JVM languages: that class's instances, a field of the first one and its referrers (Show Instances). */ instances?: { className: string; count: number; field: string }; + /** + * Java: after Step Over, the session runs to the line of `file` holding `at`, traces the + * stream chain there by running it, then still stops at the breakpoint on the entry point's + * line holding `next`. + */ + streamTrace?: { file: string; at: string; next: string }; } /** Debugging the Kotlin fixture, with either debugger. */ @@ -123,6 +129,11 @@ const CASES: Record = { memory: { className: "com.example.orders.OrderBook", instances: 1 }, heap: { className: "com.example.orders.OrderBook", instances: 1 }, instances: { className: "com.example.orders.OrderBook", count: 1, field: "orders" }, + streamTrace: { + file: "src/main/java/com/example/orders/OrderBook.java", + at: "return orders.stream().filter(", + next: 'System.out.println("alice placed', + }, }, kotlin: { ...kotlin, @@ -516,6 +527,8 @@ async function smoke(language: string) { `${timedOutRetries} timedOut retries`, ); + if (c.streamTrace) await traceStream(language, c.streamTrace, root, path); + await executeAction("debug.resume"); if (c.request) { await until("the request to be served", () => useDebug.getState().sessions[s.id]?.status === "running"); @@ -525,6 +538,69 @@ async function smoke(language: string) { await until("the end", () => Object.values(useDebug.getState().sessions).every((d) => d.status === "terminated")); } +/** The line of `path` holding `text`, 0-based like every IPC line. */ +function lineOf(path: string, text: string): number { + const index = readFileSync(path, "utf8") + .split("\n") + .findIndex((l) => l.includes(text)); + if (index < 0) throw new Error(`no line of ${path} holds ${text}`); + return index; +} + +/** Waits for the active session's next stop after `stops` of them. */ +const stoppedAfter = (stops: number) => () => useDebug.getState().stopSeq > stops && pausedOrEnded(); + +async function traceStream(language: string, t: NonNullable, root: string, entry: string) { + const file = join(root, t.file); + const at = lineOf(file, t.at); + const next = lineOf(entry, t.next); + addBreakpoint(file, at); + addBreakpoint(entry, next); + // Edits reach the adapter debounced; Resume must not outrun them. + await flushBreakpoints(); + let stops = useDebug.getState().stopSeq; + await executeAction("debug.resume"); + const s = await until("the stream chain's breakpoint", stoppedAfter(stops)); + const top = s.frames[0]!; + expect([top.path, top.line, s.stopReason], shown()).toEqual([file, at, "breakpoint"]); + + const chains = await call(commands.debugStreamChains(s.id, top, true)); + const chain = chains.find((ch) => ch.available); + if (!chain) throw new Error(`no chain to trace at ${t.file}:${at}: ${JSON.stringify(chains)}\n${shown()}`); + const phases: string[] = []; + const progress = new Channel(); + progress.onmessage = (p) => { + if (phases.at(-1) !== p.phase) phases.push(p.phase); + }; + stops = useDebug.getState().stopSeq; + const since = Date.now(); + const thread = s.stoppedThread!; + const traced = await call( + commands.debugStreamTrace(s.id, nextRequestId(), thread, top, chain.index, chain.range, progress), + ); + const traceMs = Date.now() - since; + if (traced.status !== "ready") throw new Error(`stream trace: ${JSON.stringify(traced)}\n${shown()}`); + expect(traced.records.length, "recorded values").toBeGreaterThan(0); + expect(traced.links, "a link per record").toHaveLength(traced.records.length); + console.info( + `${language}: traced ${chain.text.replace(/\s*\n\s*/g, "")} in ${traceMs} ms (${phases.join(" → ")}): ` + + `${traced.records.length} records over [${traced.steps.join(", ")}], terminal ${traced.terminal.kind}, ` + + `banners [${traced.banners.map((b) => b.kind).join(", ")}]`, + ); + + // The trace leaves its thread stopped after the terminal operation, its breakpoints back on. + const after = await until("the stop the trace ends in", stoppedAfter(stops)); + expect(after.stoppedThread, shown()).toBe(thread); + stops = useDebug.getState().stopSeq; + await executeAction("debug.resume"); + const reached = await until("the breakpoint after the trace", stoppedAfter(stops)); + expect([reached.frames[0]!.path, reached.frames[0]!.line, reached.stopReason], shown()).toEqual([ + entry, + next, + "breakpoint", + ]); +} + for (const language of Object.keys(CASES)) { test(language, () => smoke(language)); } diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 2ea593d6e6..6a176ec4af 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -46,6 +46,7 @@ pub mod sdk; pub mod search; pub mod spell; pub mod ssh; +pub mod stream_trace; pub mod syntax; pub mod term; pub mod tools; @@ -592,6 +593,9 @@ pub fn builder() -> tauri_specta::Builder { heap::debug_heap_compare, heap::debug_heap_save, heap::debug_heap_close, + stream_trace::debug_stream_chains, + stream_trace::debug_stream_trace, + stream_trace::debug_stream_trace_abort, plugin::plugin_subscribe, plugin::plugin_list, plugin::plugin_set_enabled, diff --git a/src-tauri/src/commands/stream_trace.rs b/src-tauri/src/commands/stream_trace.rs new file mode 100644 index 0000000000..b6d1f3a0f3 --- /dev/null +++ b/src-tauri/src/commands/stream_trace.rs @@ -0,0 +1,62 @@ +//! Java Stream Debugger: stream chains at a stop and real-run traces (`ide_host::ops::stream_trace`). + +use crate::state::AppState; +use ide_core::{DebugSessionId, IdeResult, Range, RequestId}; +use ide_dap::StackFrame; +use ide_host::ops::stream_trace::{AbortState, StreamChainInfo, StreamTraceResult, TraceProgress}; +use tauri::ipc::Channel; +use tauri::{State, Window}; + +/// The stream chains around `frame`'s line; `top`: it is the thread's top frame. +#[tauri::command] +#[specta::specta] +pub async fn debug_stream_chains( + window: Window, + state: State<'_, AppState>, + session: DebugSessionId, + frame: StackFrame, + top: bool, +) -> IdeResult> { + ide_host::ops::stream_trace::debug_stream_chains(&state.host, window.label(), session, frame, top).await +} + +/// Traces chain `chain_index` of [`debug_stream_chains`], whose `range` the UI showed, while the +/// program runs it; cancelling `request` stops recording. +#[tauri::command] +#[specta::specta] +#[allow(clippy::too_many_arguments)] +pub async fn debug_stream_trace( + window: Window, + state: State<'_, AppState>, + session: DebugSessionId, + request: RequestId, + thread_id: i64, + frame: StackFrame, + chain_index: u32, + range: Range, + on_progress: Channel, +) -> IdeResult { + ide_host::ops::stream_trace::debug_stream_trace( + &state.host, + window.label(), + session, + request, + thread_id, + frame, + chain_index, + range, + crate::commands::sender(on_progress), + ) + .await +} + +/// Ends the running trace's terminal operation; `None` when no trace runs. +#[tauri::command] +#[specta::specta] +pub async fn debug_stream_trace_abort( + window: Window, + state: State<'_, AppState>, + session: DebugSessionId, +) -> IdeResult> { + ide_host::ops::stream_trace::debug_stream_trace_abort(&state.host, window.label(), session).await +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index e38a94c8db..d857259423 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -169,6 +169,9 @@ debug_step trusted project_host bin debug_step_in_target trusted project_host bindings async debug_step_in_targets trusted project_host bindings async debug_stop always project_host bindings async +debug_stream_chains trusted project_host bindings async +debug_stream_trace trusted project_host bindings async +debug_stream_trace_abort trusted project_host bindings async debug_threads trusted project_host bindings async debug_unity_processes trusted project_host bindings async debug_variables trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index ae8dfb4c00..f941f834c3 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1444,6 +1444,21 @@ export const commands = { /** Copies the snapshot's dump to `path`, replacing a file there. */ debugHeapSave: (snapshot: HeapSnapshotId, path: IpcPath) => typedError(__TAURI_INVOKE("debug_heap_save", { snapshot, path })), debugHeapClose: (snapshot: HeapSnapshotId) => typedError(__TAURI_INVOKE("debug_heap_close", { snapshot })), + /** The stream chains around `frame`'s line; `top`: it is the thread's top frame. */ + debugStreamChains: (session: DebugSessionId, frame: StackFrame, top: boolean) => typedError(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })), + /** + * Traces chain `chain_index` of [`debug_stream_chains`], whose `range` the UI showed, while the + * program runs it; cancelling `request` stops recording. + */ + debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame, chainIndex: number, range: Range, onProgress: Channel) => typedError(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })), + /** Ends the running trace's terminal operation; `None` when no trace runs. */ + debugStreamTraceAbort: (session: DebugSessionId) => typedError<{ kind: "interrupted" } | { kind: "stopped" } | +/** Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. */ +{ kind: "stuck"; holders: ([number, string])[] } | +/** The terminal had not started. */ +{ kind: "cancelled" } | +/** The trace had already parked or failed. */ +{ kind: "finished" } | null, IdeError>(__TAURI_INVOKE("debug_stream_trace_abort", { session })), /** Routes this window's plugin events to `on_event` (replaces an earlier subscription). */ pluginSubscribe: (onEvent: Channel) => __TAURI_INVOKE("plugin_subscribe", { onEvent }), /** @@ -1891,6 +1906,14 @@ export const commands = { }; /* Types */ +export type AbortState = { kind: "interrupted" } | { kind: "stopped" } | +/** Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. */ +{ kind: "stuck"; holders: ([number, string])[] } | +/** The terminal had not started. */ +{ kind: "cancelled" } | +/** The trace had already parked or failed. */ +{ kind: "finished" }; + /** What importing one entry of a JetBrains `acp.json` file did. */ export type AcpImportOutcome = { /** The `agent_servers` key the entry was imported from. */ @@ -3164,6 +3187,10 @@ export type CatalogPlugin = { problem: string | null, }; +export type ChainUnavailable = { kind: "notTopFrame" } | { kind: "notAtChainStart" } | { kind: "insideChainLambda" } | { kind: "notJavaStreamRoot"; root: string } | { kind: "lazyTerminal"; op: string } | { kind: "noTerminal" } | { kind: "unknownOperation"; op: string } | { kind: "syntaxError" } | +/** The session has no stream tracer: not java-debug, or its jdtls has no inspector bundle. */ +{ kind: "noBackend" }; + export type ChangeKind = "added" | "modified" | "deleted" | "renamed" | "untracked" | "ignored" | "conflicted"; /** @@ -4381,6 +4408,11 @@ export type DebugCapabilities = { jsPage: boolean, /** The adapter evaluates expressions while the program runs, without a stack frame. */ liveEvaluate: boolean, + /** + * A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]). + * Can change during the session, like `jvm_instances`. + */ + streamTrace: boolean, }; /** A completion the adapter offers for an expression (DAP `completions`). */ @@ -7419,6 +7451,12 @@ export type LineMatch = { textOffset: number, }; +/** Link from an output element to the input element it came from. */ +export type Link = { + parent: number | null, + ambiguous: boolean, +}; + /** Settings › System Settings › Caches: where the local data lives. */ export type LocalDataInfo = { /** The directory in use by this run. */ @@ -10570,6 +10608,72 @@ export type StepSource = { feature: boolean, }; +export type StreamChainInfo = StreamChainInfo_Serialize | StreamChainInfo_Deserialize; + +export type StreamChainInfo_Deserialize = { + /** The `chain_index` [`debug_stream_trace`] takes for the same frame. */ + index: number, + range: Range, + text: string, + /** + * Intermediate operations in call order, modifiers included. Empty, like `terminal`, for a + * chain the search rejected. + */ + steps: string[], + terminal: string, + available: boolean, + /** Set exactly when `available` is false. */ + reason?: ChainUnavailable | null, +}; + +export type StreamChainInfo_Serialize = { + /** The `chain_index` [`debug_stream_trace`] takes for the same frame. */ + index: number, + range: Range, + text: string, + /** + * Intermediate operations in call order, modifiers included. Empty, like `terminal`, for a + * chain the search rejected. + */ + steps: string[], + terminal: string, + available: boolean, + /** Set exactly when `available` is false. */ + reason?: ChainUnavailable | null, +}; + +export type StreamTraceResult = StreamTraceResult_Serialize | StreamTraceResult_Deserialize; + +export type StreamTraceResult_Deserialize = ({ status: "ready"; chain: StreamChainInfo_Deserialize; +/** + * Column titles by recorded step: `steps[0]` is the root call's name (empty for a stream + * held in a local), then each operation that records, modifiers left out. + */ +steps: string[]; +/** In recording order. */ +records: TraceRecordView[]; +/** Parallel to `records`. */ +links: Link[]; terminal: TerminalView; banners: TraceBanner[]; +/** The stop the values belong to, for `debug_jvm_memory_fields`. */ +generation: number }) & { detail?: never; reason?: never } | ({ status: "unavailable"; reason: TraceUnavailable }) & { banners?: never; chain?: never; detail?: never; generation?: never; links?: never; records?: never; steps?: never; terminal?: never } | ({ status: "failed"; detail: string }) & { banners?: never; chain?: never; generation?: never; links?: never; reason?: never; records?: never; steps?: never; terminal?: never } | +/** Recording was stopped, or the operation aborted, before the chain ran: nothing went wrong. */ +({ status: "cancelled"; detail: string }) & { banners?: never; chain?: never; generation?: never; links?: never; reason?: never; records?: never; steps?: never; terminal?: never }; + +export type StreamTraceResult_Serialize = ({ status: "ready"; chain: StreamChainInfo_Serialize; +/** + * Column titles by recorded step: `steps[0]` is the root call's name (empty for a stream + * held in a local), then each operation that records, modifiers left out. + */ +steps: string[]; +/** In recording order. */ +records: TraceRecordView[]; +/** Parallel to `records`. */ +links: Link[]; terminal: TerminalView; banners: TraceBanner[]; +/** The stop the values belong to, for `debug_jvm_memory_fields`. */ +generation: number }) & { detail?: never; reason?: never } | ({ status: "unavailable"; reason: TraceUnavailable }) & { banners?: never; chain?: never; detail?: never; generation?: never; links?: never; records?: never; steps?: never; terminal?: never } | ({ status: "failed"; detail: string }) & { banners?: never; chain?: never; generation?: never; links?: never; reason?: never; records?: never; steps?: never; terminal?: never } | +/** Recording was stopped, or the operation aborted, before the chain ran: nothing went wrong. */ +({ status: "cancelled"; detail: string }) & { banners?: never; chain?: never; generation?: never; links?: never; reason?: never; records?: never; steps?: never; terminal?: never }; + export type StructuralEvent = { type: "file"; file: StructuralFile } | { type: "done"; summary: StructuralSummary }; /** All matches in one file; streamed as files complete. */ @@ -10822,6 +10926,8 @@ export type TerminalSettings = { columnWidth?: number | null, }; +export type TerminalView = { kind: "value"; value: JvmValue } | { kind: "void" } | { kind: "threw"; exception: JvmValue }; + export type TestCaseReport = { /** Fully qualified class (`com.acme.OrderTest`, nested: `com.acme.OrderTest$Nested`). */ className: string, @@ -11054,6 +11160,40 @@ export type ToolUpdate = { latest: string, }; +/** Something the user must know to read the trace correctly. */ +export type TraceBanner = { kind: "truncated"; dropped: number } | +/** `count()` on a sized source skips the pipeline, so nothing was recorded. */ +{ kind: "countFromSize" } | { kind: "sortedPassThrough"; step: number } | { kind: "sequentialized" } | { kind: "breakpointsSkipped"; count: number } | +/** Breakpoint stops of the chain's thread while it ran, resumed without being shown. */ +{ kind: "breakpointsResumed"; count: number } | { kind: "threw" }; + +export type TracePhase = "arming" | "running" | +/** The terminal operation runs on, keeping no more records. */ +"recordingStopped" | "aborting" | +/** The terminal operation finished: stepping out of it and reading the records. */ +"collecting"; + +export type TraceProgress = { + phase: TracePhase, + records: number, + dropped: number, + /** Since the program started running the chain, as the bundle measures it. */ + elapsedMs: number, +}; + +export type TraceRecordView = { + step: number, + value: JvmValue, +}; + +export type TraceUnavailable = +/** Not a java-debug session, or no JDT LS bundle behind it. */ +{ kind: "noBackend" } | { kind: "notSuspended" } | { kind: "notAtChainStart"; detail: string } | +/** A trace already runs in this session or its JVM. */ +{ kind: "busy" } | +/** java-debug has no debug session for the JVM. */ +{ kind: "noSession" } | { kind: "unsupported"; detail: string }; + export type TransferError = { path: string, message: string, diff --git a/src/features/debugger/__tests__/actions.test.ts b/src/features/debugger/__tests__/actions.test.ts index 5298deeb3e..a1c57fb0d5 100644 --- a/src/features/debugger/__tests__/actions.test.ts +++ b/src/features/debugger/__tests__/actions.test.ts @@ -109,6 +109,7 @@ const caps = (p: Partial = {}): DebugCapabilities => ({ jvmHeap: false, jsPage: false, liveEvaluate: false, + streamTrace: false, ...p, }); @@ -192,6 +193,9 @@ describe("debugger actions (IDEA parity)", () => { "debug.memory.closeInstances": undefined, "debug.toggleMethodBreakpoint": undefined, "debug.toggleFieldWatchpoint": undefined, + "debug.traceStreamChain": undefined, + "debug.streamTrace.stopRecording": undefined, + "debug.streamTrace.abort": undefined, }; for (const [id, keys] of Object.entries(expected)) { expect(getAction(id), id).toBeTruthy(); diff --git a/src/features/debugger/__tests__/streamChainA.ts b/src/features/debugger/__tests__/streamChainA.ts new file mode 100644 index 0000000000..834990f9fd --- /dev/null +++ b/src/features/debugger/__tests__/streamChainA.ts @@ -0,0 +1,92 @@ +/** + * Chain A as JDK 11–25 record it: `nums.stream().filter(x -> x % 2 == 0).map(x -> x * 10 + 1) + * .sorted().map(String::valueOf).toList()` over `[5, 3, 8, 1, 4, 2, 9, 6]`. The links are what + * `link_trace` gives for it (`ready_links_the_collected_records` in ide-host checks the same log). + */ +import type { JvmValue, Link, StreamChainInfo, StreamTraceResult, TraceRecordView } from "@/platform/ipc"; + +const LOG: [number, string][] = [ + [0, "5"], + [0, "3"], + [0, "8"], + [1, "8"], + [2, "81"], + [0, "1"], + [0, "4"], + [1, "4"], + [2, "41"], + [0, "2"], + [1, "2"], + [2, "21"], + [0, "9"], + [0, "6"], + [1, "6"], + [2, "61"], + [3, "21"], + [4, "21"], + [3, "41"], + [4, "41"], + [3, "61"], + [4, "61"], + [3, "81"], + [4, "81"], +]; + +/** `filter` and both `map`s link to the latest record of the step before; `sorted` by the boxed value. */ +const PARENTS = [ + null, + null, + null, + 2, + 3, + null, + null, + 6, + 7, + null, + 9, + 10, + null, + null, + 13, + 14, + 11, + 16, + 8, + 18, + 15, + 20, + 4, + 22, +]; + +const value = (step: number, text: string, i: number): JvmValue => + step === 4 + ? { kind: "string", id: 100 + i, text, length: text.length } + : { kind: "boxed", id: 100 + i, typeName: "java.lang.Integer", text }; + +export const CHAIN_A_RECORDS: TraceRecordView[] = LOG.map(([step, text], i) => ({ step, value: value(step, text, i) })); + +export const CHAIN_A_LINKS: Link[] = PARENTS.map((parent) => ({ parent, ambiguous: false })); + +export const CHAIN_A_STEPS = ["stream", "filter", "map", "sorted", "map"]; + +export const CHAIN_A: StreamChainInfo = { + index: 0, + range: { start: { line: 5, col: 4 }, end: { line: 10, col: 20 } }, + text: "nums.stream()\n .filter(x -> x % 2 == 0)\n .map(x -> x * 10 + 1)\n .sorted()\n .map(String::valueOf)\n .toList()", + steps: ["filter", "map", "sorted", "map"], + terminal: "toList", + available: true, +}; + +export const CHAIN_A_READY: Extract = { + status: "ready", + chain: CHAIN_A, + steps: CHAIN_A_STEPS, + records: CHAIN_A_RECORDS, + links: CHAIN_A_LINKS, + terminal: { kind: "value", value: { kind: "object", id: 7, typeName: "java.util.ImmutableCollections$ListN" } }, + banners: [], + generation: 9, +}; diff --git a/src/features/debugger/__tests__/streamLayout.test.ts b/src/features/debugger/__tests__/streamLayout.test.ts new file mode 100644 index 0000000000..ede7bd0b2d --- /dev/null +++ b/src/features/debugger/__tests__/streamLayout.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { buildColumns, buildEdges, relatedTo } from "../streams/layout"; +import { CHAIN_A_LINKS, CHAIN_A_RECORDS, CHAIN_A_STEPS } from "./streamChainA"; + +const label = (i: number) => { + const r = CHAIN_A_RECORDS[i]!; + const v = r.value; + return `${r.step}=${v.kind === "string" ? JSON.stringify(v.text) : v.kind === "boxed" ? v.text : "?"}`; +}; + +describe("stream trace layout", () => { + it("puts chain A's records into one column per step", () => { + const columns = buildColumns(CHAIN_A_STEPS, CHAIN_A_RECORDS); + expect(columns.map((c) => c.items.length)).toEqual([8, 4, 4, 4, 4]); + expect(columns.map((c) => c.title)).toEqual(CHAIN_A_STEPS); + expect(columns.map((c) => c.step)).toEqual([0, 1, 2, 3, 4]); + expect(columns[3]!.items.map((it) => label(it.index))).toEqual(["3=21", "3=41", "3=61", "3=81"]); + }); + + it("titles the column of a stream held in a local Source", () => { + const columns = buildColumns(["", "map"], [{ step: 0, value: { kind: "null" } }]); + expect(columns.map((c) => c.title)).toEqual(["Source", "map"]); + expect(columns[1]!.items).toEqual([]); + }); + + it("relates 0=8 to everything it became, across sorted", () => { + const edges = buildEdges(CHAIN_A_LINKS); + const start = CHAIN_A_RECORDS.findIndex((_, i) => label(i) === "0=8"); + const related = [...relatedTo(start, edges)].map(label).sort(); + expect(related).toEqual(["0=8", "1=8", "2=81", "3=81", '4="81"'].sort()); + }); + + it("relates a later record back to its source only", () => { + const edges = buildEdges(CHAIN_A_LINKS); + const end = CHAIN_A_RECORDS.findIndex((_, i) => label(i) === '4="21"'); + expect([...relatedTo(end, edges)].map(label).sort()).toEqual(["0=2", "1=2", "2=21", "3=21", '4="21"'].sort()); + }); + + it("keeps the siblings of a record out of what it relates to", () => { + // flatMap: record 0 made 1 and 2; 1 is not related to 2. + const edges = buildEdges([ + { parent: null, ambiguous: false }, + { parent: 0, ambiguous: false }, + { parent: 0, ambiguous: true }, + ]); + expect([...relatedTo(1, edges)].sort()).toEqual([0, 1]); + }); + + it("drops links without a parent", () => { + expect( + buildEdges([ + { parent: null, ambiguous: false }, + { parent: 0, ambiguous: true }, + { parent: null, ambiguous: false }, + { parent: 2, ambiguous: false }, + ]), + ).toEqual([ + { from: 0, to: 1, ambiguous: true }, + { from: 2, to: 3, ambiguous: false }, + ]); + }); +}); diff --git a/src/features/debugger/__tests__/streamTrace.test.ts b/src/features/debugger/__tests__/streamTrace.test.ts new file mode 100644 index 0000000000..e36f323aed --- /dev/null +++ b/src/features/debugger/__tests__/streamTrace.test.ts @@ -0,0 +1,402 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createElement } from "react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; + +vi.mock("@tauri-apps/api/core", () => ({ + Channel: class { + onmessage: (p: unknown) => void = () => {}; + }, +})); + +const ipc = vi.hoisted(() => ({ + debugStreamChains: vi.fn(), + debugStreamTrace: vi.fn(), + debugStreamTraceAbort: vi.fn(), + cancelRequest: vi.fn(() => Promise.resolve()), + debugStackTrace: vi.fn(), + debugThreads: vi.fn(), + debugScopes: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, commands: { ...real.commands, ...ipc } }; +}); + +const tab = vi.hoisted(() => ({ openStreamTraceTab: vi.fn() })); +vi.mock("../streams/streamTraceInput", async (importOriginal) => ({ + ...(await importOriginal()), + ...tab, +})); + +import type { DebugCapabilities, StackFrame, StreamChainInfo, StreamTraceResult, TraceProgress } from "@/platform/ipc"; +import { getAction, isActionEnabled } from "@/platform/actions"; +import { activate } from "../index"; +import { handleDebugEvent, publishContext, useDebug, type DebugSession } from "../state"; +import { useOverlays } from "../ui/popoverStore"; +import { provideEditorService, provideNotificationService, type EditorService } from "@/workbench/contributions"; +import { + abortTrace, + forgetStreamTrace, + pickStreamChain, + stopRecording, + traceStreamChain, +} from "../streams/streamState"; +import { isTracing, traceValuesOutdated, useStreamTrace } from "../streams/streamStore"; +import { StreamChainChooser } from "../streams/StreamChainChooser"; + +const frame: StackFrame = { id: 10, name: "main", path: "/p/Main.java", line: 5, column: 4, presentationHint: null }; + +const session = { + id: 1, + name: "Main", + adapter: "java-debug", + parent: null, + launch: null, + process: null, + status: "paused", + stoppedThread: 1, + stopReason: "breakpoint", + stopDescription: null, + threads: [{ id: 1, name: "main" }], + selectedThread: 1, + frames: [frame, { id: 11, name: "run", path: "/p/Main.java", line: 20, column: 0, presentationHint: null }], + selectedFrame: 10, + hits: 1, + stops: 1, + exitCode: null, + caps: { streamTrace: true } as DebugCapabilities, +} as DebugSession; + +const chain = (index: number, available = true): StreamChainInfo => ({ + index, + range: { start: { line: 5, col: 4 + index }, end: { line: 7, col: 20 } }, + text: "nums.stream()\n .map(x -> x * 2)\n .toList()", + steps: available ? ["map"] : [], + terminal: available ? "toList" : "", + available, + ...(available ? {} : { reason: { kind: "lazyTerminal" as const, op: "iterator" } }), +}); + +const FAILED: StreamTraceResult = { status: "failed", detail: "no" }; +const READY: StreamTraceResult = { + status: "ready", + chain: chain(0), + steps: ["stream", "map"], + records: [], + links: [], + terminal: { kind: "void" }, + banners: [], + generation: 2, +}; +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); + +function deferred() { + let resolve!: (v: T) => void; + const promise = new Promise((r) => (resolve = r)); + return { promise, resolve }; +} + +const settle = () => new Promise((r) => setTimeout(r, 0)); +const enabled = (id: string) => isActionEnabled(getAction(id)!); +const setSession = (p: Partial) => { + useDebug.setState((s) => ({ sessions: { 1: { ...s.sessions[1]!, ...p } } })); + publishContext(); +}; +const notify = vi.fn(); + +let dispose: () => void; +beforeEach(() => { + vi.clearAllMocks(); + provideNotificationService({ notify }); + useStreamTrace.setState({ bySession: {} }); + useOverlays.setState({ streamChooser: null, streamAbort: null }); + dispose = activate(); + useDebug.setState({ sessions: { 1: session }, active: 1 }); + publishContext(); +}); +afterEach(() => { + cleanup(); + dispose(); + useDebug.setState({ sessions: {}, active: null }); +}); + +describe("Trace Stream Chain", () => { + it("one available chain traces at once", async () => { + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(ok(FAILED)); + await traceStreamChain(1); + expect(ipc.debugStreamChains).toHaveBeenCalledWith(1, frame, true); + expect(ipc.debugStreamTrace).toHaveBeenCalledWith( + 1, + expect.any(Number), + 1, + frame, + 0, + chain(0).range, + expect.anything(), + ); + expect(tab.openStreamTraceTab).toHaveBeenCalledWith(1); + expect(useOverlays.getState().streamChooser).toBeNull(); + expect(useStreamTrace.getState().bySession[1]?.result).toEqual(FAILED); + expect(isTracing(1)).toBe(false); + }); + + it("several chains open the chooser", async () => { + ipc.debugStreamChains.mockReturnValue(ok([chain(0), chain(1, false)])); + await traceStreamChain(1); + expect(useOverlays.getState().streamChooser).not.toBeNull(); + expect(useOverlays.getState().streamChooser?.chains).toHaveLength(2); + expect(ipc.debugStreamTrace).not.toHaveBeenCalled(); + }); + + it("tracing disables resume, steps and pause", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + expect(enabled("debug.resume")).toBe(true); + expect(enabled("debug.traceStreamChain")).toBe(true); + const running = traceStreamChain(1); + await settle(); + expect(isTracing(1)).toBe(true); + expect(enabled("debug.resume")).toBe(false); + expect(enabled("debug.stepOver")).toBe(false); + expect(enabled("debug.traceStreamChain")).toBe(false); + // Moving neither the program nor the trace, these stay available. + expect(enabled("debug.showExecutionPoint")).toBe(true); + expect(enabled("debug.jumpToSource")).toBe(true); + // The trace resumes the program itself, so the session shows as running. + setSession({ status: "running" }); + expect(enabled("debug.pause")).toBe(false); + reply.resolve({ status: "ok", data: FAILED }); + await running; + expect(isTracing(1)).toBe(false); + expect(enabled("debug.pause")).toBe(true); + setSession({ status: "paused" }); + expect(enabled("debug.resume")).toBe(true); + expect(enabled("debug.stepOver")).toBe(true); + }); + + it("asks for the chains of a lower frame as not the top one", async () => { + setSession({ selectedFrame: 11 }); + ipc.debugStreamChains.mockReturnValue(ok([chain(0, false)])); + await traceStreamChain(1); + expect(ipc.debugStreamChains).toHaveBeenCalledWith(1, session.frames[1], false); + }); + + it("says so when the line has no stream chain", async () => { + ipc.debugStreamChains.mockReturnValue(ok([])); + await traceStreamChain(1); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No stream chain on this line" })); + expect(ipc.debugStreamTrace).not.toHaveBeenCalled(); + expect(useOverlays.getState().streamChooser).toBeNull(); + }); + + it("a progress message patches the running trace", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + const channel = ipc.debugStreamTrace.mock.calls[0]![6] as { onmessage: (p: TraceProgress) => void }; + const progress: TraceProgress = { phase: "running", records: 12, dropped: 0, elapsedMs: 40 }; + channel.onmessage(progress); + expect(useStreamTrace.getState().bySession[1]?.progress).toEqual(progress); + reply.resolve({ status: "ok", data: FAILED }); + await running; + }); + + it("a trace forgotten while it runs ignores its late reply", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + forgetStreamTrace(1); + expect(isTracing(1)).toBe(false); + reply.resolve({ status: "ok", data: FAILED }); + await running; + expect(useStreamTrace.getState().bySession[1]).toBeUndefined(); + }); + + it("the chooser closes when the stop or the selected frame changes", async () => { + ipc.debugStreamChains.mockReturnValue(ok([chain(0), chain(1)])); + await traceStreamChain(1); + expect(useOverlays.getState().streamChooser?.frame).toBe(10); + setSession({ selectedFrame: 11 }); + expect(useOverlays.getState().streamChooser).toBeNull(); + setSession({ selectedFrame: 10 }); + await traceStreamChain(1); + setSession({ status: "running" }); + expect(useOverlays.getState().streamChooser).toBeNull(); + }); + + it("a pick from a stale chooser says so instead of tracing", async () => { + useOverlays.setState({ streamChooser: { session: 1, frame: 11, chains: [chain(0)] } }); + await pickStreamChain(chain(0)); + expect(ipc.debugStreamTrace).not.toHaveBeenCalled(); + expect(useOverlays.getState().streamChooser).toBeNull(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "The stop or the selected frame changed; trace the stream chain again" }), + ); + }); + + it("stop recording cancels the request", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + stopRecording(1); + const request = ipc.debugStreamTrace.mock.calls[0]![1]; + expect(ipc.cancelRequest).toHaveBeenCalledWith(request); + expect(useStreamTrace.getState().bySession[1]?.stoppedRecording).toBe(true); + // The program keeps running after a stop: the trace still ends with a result. + expect(isTracing(1)).toBe(true); + reply.resolve({ status: "ok", data: FAILED }); + await running; + expect(isTracing(1)).toBe(false); + }); + + it("abort asks the host to cancel the terminal operation", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + ipc.debugStreamTraceAbort.mockReturnValue(ok({ kind: "interrupted" })); + const running = traceStreamChain(1); + await settle(); + await abortTrace(1); + expect(ipc.debugStreamTraceAbort).toHaveBeenCalledWith(1); + expect(ipc.cancelRequest).not.toHaveBeenCalled(); + expect(useStreamTrace.getState().bySession[1]?.abort).toEqual({ kind: "interrupted" }); + reply.resolve({ status: "ok", data: FAILED }); + await running; + }); + + it("another thread's stop during the trace is not the trace's stop", async () => { + const openFile = vi.fn(() => Promise.resolve()); + provideEditorService({ openFile } as unknown as EditorService); + ipc.debugStackTrace.mockReturnValue(ok([frame])); + ipc.debugThreads.mockReturnValue(ok([{ id: 1, name: "main" }])); + ipc.debugScopes.mockReturnValue(ok([])); + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + const stopOf = (threadId: number) => + ({ kind: "stopped", threadId, reason: "exception", description: null, allThreadsStopped: false }) as const; + setSession({ status: "running" }); + // An exception breakpoint on a worker: a stop of its own, revealed as usual. + handleDebugEvent(1, stopOf(2)); + await settle(); + expect(openFile).toHaveBeenCalledTimes(1); + setSession({ status: "running" }); + handleDebugEvent(1, stopOf(1)); + await settle(); + expect(openFile).toHaveBeenCalledTimes(1); + reply.resolve({ status: "ok", data: READY }); + await running; + const entry = () => useStreamTrace.getState().bySession[1]!; + const live = () => useDebug.getState().sessions[1]; + expect(entry().endStop).toBe(live()!.stops); + expect(traceValuesOutdated(entry(), live())).toBe(false); + + setSession({ status: "running" }); + expect(traceValuesOutdated(entry(), live())).toBe(true); + handleDebugEvent(1, stopOf(1)); + await settle(); + expect(openFile).toHaveBeenCalledTimes(2); + expect(traceValuesOutdated(entry(), live())).toBe(true); + }); + + it("an Abort dialog left open closes when its trace ends", async () => { + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + useOverlays.setState({ streamAbort: 1 }); + reply.resolve({ status: "ok", data: FAILED }); + await running; + expect(useOverlays.getState().streamAbort).toBeNull(); + }); + + it("the chooser shows why a chain cannot be traced and traces only an available one", async () => { + ipc.debugStreamChains.mockReturnValue(ok([chain(0, false), chain(1)])); + ipc.debugStreamTrace.mockReturnValue(ok(FAILED)); + await traceStreamChain(1); + render(createElement(StreamChainChooser)); + const rows = screen.getAllByRole("option"); + expect(rows).toHaveLength(2); + expect(rows[0]!.textContent).toContain("iterator() and spliterator() do not run the pipeline"); + fireEvent.click(rows[0]!); + expect(ipc.debugStreamTrace).not.toHaveBeenCalled(); + expect(useOverlays.getState().streamChooser).not.toBeNull(); + fireEvent.click(rows[1]!); + await settle(); + expect(ipc.debugStreamTrace).toHaveBeenCalledWith( + 1, + expect.any(Number), + 1, + frame, + 1, + chain(1).range, + expect.anything(), + ); + expect(useOverlays.getState().streamChooser).toBeNull(); + }); + + it("forget on session end", async () => { + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(ok(FAILED)); + await traceStreamChain(1); + expect(useStreamTrace.getState().bySession[1]).toBeDefined(); + useDebug.setState({ sessions: {}, active: null }); + expect(useStreamTrace.getState().bySession[1]).toBeUndefined(); + }); + + it("the stop a trace ends in leaves the trace tab in front; a later stop reveals its source", async () => { + const openFile = vi.fn(() => Promise.resolve()); + provideEditorService({ openFile } as unknown as EditorService); + ipc.debugStackTrace.mockReturnValue(ok([frame])); + ipc.debugThreads.mockReturnValue(ok([{ id: 1, name: "main" }])); + ipc.debugScopes.mockReturnValue(ok([])); + const reply = deferred<{ status: "ok"; data: StreamTraceResult }>(); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(reply.promise); + const running = traceStreamChain(1); + await settle(); + const stop = { kind: "stopped", threadId: 1, reason: "step", description: null, allThreadsStopped: false } as const; + setSession({ status: "running" }); + handleDebugEvent(1, stop); + await settle(); + expect(openFile).not.toHaveBeenCalled(); + reply.resolve({ status: "ok", data: READY }); + await running; + + setSession({ status: "running" }); + handleDebugEvent(1, stop); + await settle(); + expect(openFile).toHaveBeenCalledWith(frame.path, expect.objectContaining({ focus: false })); + }); + + it("a reply that comes before its stop still keeps that stop from revealing the source", async () => { + const openFile = vi.fn(() => Promise.resolve()); + provideEditorService({ openFile } as unknown as EditorService); + ipc.debugStackTrace.mockReturnValue(ok([frame])); + ipc.debugThreads.mockReturnValue(ok([{ id: 1, name: "main" }])); + ipc.debugScopes.mockReturnValue(ok([])); + ipc.debugStreamChains.mockReturnValue(ok([chain(0)])); + ipc.debugStreamTrace.mockReturnValue(ok(READY)); + await traceStreamChain(1); + setSession({ status: "running" }); + handleDebugEvent(1, { kind: "stopped", threadId: 1, reason: "step", description: null, allThreadsStopped: false }); + await settle(); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("action when clause", () => { + expect(getAction("debug.traceStreamChain")!.when).toBe("debugCanTraceStream"); + }); +}); diff --git a/src/features/debugger/__tests__/streamTraceEditor.test.tsx b/src/features/debugger/__tests__/streamTraceEditor.test.tsx new file mode 100644 index 0000000000..04e948f5e5 --- /dev/null +++ b/src/features/debugger/__tests__/streamTraceEditor.test.tsx @@ -0,0 +1,466 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ + debugJvmMemoryFields: vi.fn(), + debugStreamTraceAbort: vi.fn(), + cancelRequest: vi.fn(() => Promise.resolve()), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); + +import type { + DebugCapabilities, + JvmFieldsResult, + StreamTraceResult, + TraceBanner, + TraceUnavailable, +} from "@/platform/ipc"; +import { getAction, isActionEnabled } from "@/platform/actions"; +import { provideNotificationService } from "@/workbench/contributions"; +import { registerDebugActions } from "../actions"; +import { publishContext, useDebug, type DebugSession } from "../state"; +import { useOverlays } from "../ui/popoverStore"; +import { useStreamTrace, type TraceEntry } from "../streams/streamStore"; +import { STREAM_TRACE_KIND } from "../streams/streamTraceInput"; +import { StreamTraceEditor } from "../streams/StreamTraceEditor"; +import { StreamAbortDialog } from "../streams/StreamAbortDialog"; +import { CELL_LIMIT } from "../streams/TraceColumns"; +import { CHAIN_A, CHAIN_A_READY } from "./streamChainA"; + +const session = { + id: 1, + name: "Main", + adapter: "java-debug", + parent: null, + launch: null, + process: null, + status: "paused", + stoppedThread: 1, + stopReason: "step", + stopDescription: null, + threads: [{ id: 1, name: "main" }], + selectedThread: 1, + frames: [], + selectedFrame: null, + hits: 1, + stops: 2, + exitCode: null, + caps: { streamTrace: true } as DebugCapabilities, +} as DebugSession; + +const RUNNING: TraceEntry = { + request: 5, + chain: CHAIN_A, + progress: { phase: "running", records: 12, dropped: 0, elapsedMs: 3400 }, + result: null, + error: null, + stoppedRecording: false, + abort: null, + thread: 1, + endStop: null, +}; + +/** One object record mapped to a string: enough to open a value. */ +const OBJECTS: typeof CHAIN_A_READY = { + status: "ready", + chain: CHAIN_A, + steps: ["", "map"], + records: [ + { step: 0, value: { kind: "object", id: 50, typeName: "com.x.Order" } }, + { step: 1, value: { kind: "string", id: 51, text: "order", length: 5 } }, + ], + links: [ + { parent: null, ambiguous: false }, + { parent: 0, ambiguous: false }, + ], + terminal: { kind: "void" }, + banners: [], + generation: 9, +}; + +const FIELDS: JvmFieldsResult = { + status: "ready", + fields: [{ name: "total", value: { kind: "primitive", typeName: "int", text: "3" } }], +}; + +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const notify = vi.fn(); + +function setEntry(patch: Partial) { + useStreamTrace.setState({ bySession: { 1: { ...RUNNING, ...patch } } }); + publishContext(); +} + +const ready = (result: StreamTraceResult, patch: Partial = {}) => + setEntry({ result, progress: null, ...patch }); + +const chainA = (patch: Partial): typeof CHAIN_A_READY => ({ ...CHAIN_A_READY, ...patch }); + +function show() { + return render( + <> + + + , + ); +} + +const item = (text: string) => + within(screen.getByRole("tree")).getByText(text).closest("[role=treeitem]")!; +const toggle = (row: HTMLElement) => fireEvent.mouseDown(row.querySelector("[data-tree-toggle]")!, { button: 0 }); + +let dispose: () => void; +beforeEach(() => { + for (const m of Object.values(ipc)) m.mockClear(); + notify.mockClear(); + provideNotificationService({ notify }); + dispose = registerDebugActions(); + useOverlays.setState({ streamAbort: null }); + useDebug.setState({ sessions: { 1: session }, active: 1 }); + useStreamTrace.setState({ bySession: {} }); + publishContext(); +}); +afterEach(() => { + cleanup(); + dispose(); + useDebug.setState({ sessions: {}, active: null }); + useStreamTrace.setState({ bySession: {} }); +}); + +describe("stream trace actions", () => { + it("registers Stop Recording and Abort, enabled while the active session traces", () => { + expect(getAction("debug.streamTrace.stopRecording")?.title).toBe("Stop Recording"); + expect(getAction("debug.streamTrace.abort")?.title).toBe("Abort Operation…"); + const enabled = (id: string) => isActionEnabled(getAction(id)!); + expect(enabled("debug.streamTrace.stopRecording")).toBe(false); + expect(enabled("debug.streamTrace.abort")).toBe(false); + setEntry({}); + expect(enabled("debug.streamTrace.stopRecording")).toBe(true); + expect(enabled("debug.streamTrace.abort")).toBe(true); + ready(CHAIN_A_READY); + expect(enabled("debug.streamTrace.stopRecording")).toBe(false); + }); +}); + +describe("StreamTraceEditor", () => { + it("shows progress, Stop Recording and Abort while the trace runs", () => { + setEntry({}); + show(); + expect(screen.getByRole("progressbar")).toBeTruthy(); + expect(screen.getByText("12 records · 3 s")).toBeTruthy(); + expect(screen.getByRole("button", { name: "Stop Recording" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Abort Operation…" })).toBeTruthy(); + }); + + it("the buttons act on the tab's session, not the active one", () => { + setEntry({}); + const other = { ...session, id: 2, name: "Other" } as DebugSession; + useDebug.setState({ sessions: { 1: session, 2: other }, active: 2 }); + publishContext(); + show(); + const stop = screen.getByRole("button", { name: "Stop Recording" }); + expect((stop as HTMLButtonElement).disabled).toBe(false); + expect((screen.getByRole("button", { name: "Abort Operation…" }) as HTMLButtonElement).disabled).toBe(false); + fireEvent.click(stop); + expect(ipc.cancelRequest).toHaveBeenCalledWith(5); + expect(useStreamTrace.getState().bySession[1]?.stoppedRecording).toBe(true); + }); + + it("Stop Recording follows the tab's trace while another session's trace is active", () => { + useStreamTrace.setState({ + bySession: { 1: { ...RUNNING, stoppedRecording: true }, 2: { ...RUNNING, request: 6 } }, + }); + const other = { ...session, id: 2, name: "Other" } as DebugSession; + useDebug.setState({ sessions: { 1: session, 2: other }, active: 2 }); + publishContext(); + show(); + expect((screen.getByRole("button", { name: "Stop Recording" }) as HTMLButtonElement).disabled).toBe(true); + expect((screen.getByRole("button", { name: "Abort Operation…" }) as HTMLButtonElement).disabled).toBe(false); + }); + + it("Stop Recording runs its action: the request is cancelled and breakpoints stay off", () => { + setEntry({}); + show(); + fireEvent.click(screen.getByRole("button", { name: "Stop Recording" })); + expect(ipc.cancelRequest).toHaveBeenCalledWith(5); + expect(useStreamTrace.getState().bySession[1]?.stoppedRecording).toBe(true); + expect(screen.getByRole("status").textContent).toContain("Breakpoints stay off until toList finishes"); + }); + + it("Abort asks first; its Abort button aborts the operation", async () => { + ipc.debugStreamTraceAbort.mockReturnValue(ok({ kind: "interrupted" })); + setEntry({}); + show(); + fireEvent.click(screen.getByRole("button", { name: "Abort Operation…" })); + expect(useOverlays.getState().streamAbort).toBe(1); + const dialog = screen.getByRole("dialog"); + expect( + within(dialog).getByText( + "The program will receive java.lang.RuntimeException: oi-cancel. Abort the stream operation?", + ), + ).toBeTruthy(); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Abort" }))); + expect(ipc.debugStreamTraceAbort).toHaveBeenCalledWith(1); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(useStreamTrace.getState().bySession[1]?.abort).toEqual({ kind: "interrupted" }); + }); + + it("Enter in the Abort dialog cancels: Cancel is the default and has the focus", () => { + setEntry({}); + show(); + fireEvent.click(screen.getByRole("button", { name: "Abort Operation…" })); + const dialog = screen.getByRole("dialog"); + const cancel = within(dialog).getByRole("button", { name: "Cancel" }); + expect(cancel.hasAttribute("data-dialog-default")).toBe(true); + expect(within(dialog).getByRole("button", { name: "Abort" }).hasAttribute("data-dialog-default")).toBe(false); + expect(document.activeElement).toBe(cancel); + fireEvent.keyDown(dialog, { key: "Enter" }); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(ipc.debugStreamTraceAbort).not.toHaveBeenCalled(); + }); + + it("Cancel in the Abort dialog leaves the operation alone", () => { + setEntry({}); + show(); + fireEvent.click(screen.getByRole("button", { name: "Abort Operation…" })); + fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(ipc.debugStreamTraceAbort).not.toHaveBeenCalled(); + }); + + it("reports an abort the host refused", async () => { + ipc.debugStreamTraceAbort.mockReturnValue( + Promise.resolve({ status: "error", error: { kind: "internal", message: "gone" } }), + ); + setEntry({}); + show(); + fireEvent.click(screen.getByRole("button", { name: "Abort Operation…" })); + await act(async () => fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Abort" }))); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ level: "error", title: "Cannot abort the operation" }), + ); + }); + + it("says which threads hold the locks a stuck operation needs", () => { + setEntry({ + abort: { + kind: "stuck", + holders: [ + [3, "main"], + [7, "worker-1"], + ], + }, + }); + show(); + expect(screen.getByRole("alert").textContent).toBe("The operation is stuck: main, worker-1 hold locks it needs"); + }); + + it("a stuck operation with no lock holders says how to end it", () => { + setEntry({ abort: { kind: "stuck", holders: [] } }); + show(); + expect(screen.getByRole("alert").textContent).toBe("The operation is stuck; stop the debug session to end it"); + }); + + it("shows a result banner", () => { + ready(chainA({ banners: [{ kind: "truncated", dropped: 3 }] })); + show(); + expect(screen.queryByRole("progressbar")).toBeNull(); + expect(screen.getByRole("status").textContent).toBe("Recording stopped after 24 records (3 more not recorded)"); + }); + + it.each<[TraceBanner, string]>([ + [{ kind: "countFromSize" }, "count() was computed from the source size; the pipeline did not run"], + [{ kind: "sortedPassThrough", step: 3 }, "sorted() kept the order: the source was already sorted"], + [{ kind: "sequentialized" }, "The parallel chain ran sequentially so it could be traced"], + [{ kind: "breakpointsSkipped", count: 1 }, "1 breakpoint was off while the chain ran"], + [{ kind: "breakpointsSkipped", count: 2 }, "2 breakpoints were off while the chain ran"], + [{ kind: "breakpointsResumed", count: 1 }, "1 breakpoint hit while the chain ran was resumed"], + [{ kind: "breakpointsResumed", count: 4 }, "4 breakpoint hits while the chain ran were resumed"], + ])("banner %j", (banner, text) => { + ready(chainA({ banners: [banner] })); + show(); + expect(screen.getByRole("status").textContent).toBe(text); + }); + + it("names the exception the chain threw", () => { + ready( + chainA({ + terminal: { kind: "threw", exception: { kind: "object", id: 8, typeName: "java.lang.IllegalStateException" } }, + banners: [{ kind: "threw" }], + }), + ); + show(); + expect(screen.getByRole("status").textContent).toBe("The chain threw IllegalStateException@8"); + }); + + it("lays chain A out flat: five step columns and the result", () => { + ready(CHAIN_A_READY); + show(); + const columns = screen.getAllByTestId("stream-trace-column"); + expect(columns.map((c) => within(c).getAllByRole("listitem").length)).toEqual([8, 4, 4, 4, 4]); + expect(within(screen.getByTestId("stream-trace-result")).getByText("ImmutableCollections$ListN@7")).toBeTruthy(); + }); + + it("clicking a value highlights what it became", () => { + ready(CHAIN_A_READY); + show(); + const [source] = screen.getAllByTestId("stream-trace-column"); + fireEvent.click(within(source!).getByRole("button", { name: "8" })); + const related = [...document.querySelectorAll("[data-related]")].map((c) => c.textContent); + expect(related.sort()).toEqual(["8", "8", "81", "81", '"81"'].sort()); + expect(within(source!).getByRole("button", { name: "8" }).getAttribute("aria-pressed")).toBe("true"); + }); + + it("draws one curve per link, the related ones marked after a click", () => { + ready(CHAIN_A_READY); + const { container } = show(); + const paths = () => [...container.querySelectorAll("svg path")]; + // 4 links into each of the steps 1–4; the 8 source values have no parent. + expect(paths()).toHaveLength(16); + expect(paths().filter((p) => /ambiguous/.test(p.getAttribute("class")!))).toHaveLength(0); + fireEvent.click(within(screen.getAllByTestId("stream-trace-column")[0]!).getByRole("button", { name: "8" })); + // 0=8 → 1=8 → 2=81 → 3=81 → 4="81". + expect(paths().filter((p) => /relatedCurve/.test(p.getAttribute("class")!))).toHaveLength(4); + }); + + it("dashes a link the host could only guess", () => { + ready({ + ...OBJECTS, + links: [ + { parent: null, ambiguous: false }, + { parent: 0, ambiguous: true }, + ], + }); + const { container } = show(); + const [path] = [...container.querySelectorAll("svg path")]; + expect(path!.getAttribute("class")).toMatch(/ambiguous/); + }); + + it("caps each column and draws no curve to a value past the cap", () => { + const source = Array.from({ length: CELL_LIMIT + 5 }, (_, i) => ({ + step: 0, + value: { kind: "boxed" as const, id: i, typeName: "java.lang.Integer", text: String(i) }, + })); + const mapped = [3, CELL_LIMIT + 2].map((from, i) => ({ + step: 1, + value: { kind: "boxed" as const, id: 90_000 + i, typeName: "java.lang.Integer", text: String(from * 2) }, + })); + ready( + chainA({ + steps: ["stream", "map"], + records: [...source, ...mapped], + links: [ + ...source.map(() => ({ parent: null, ambiguous: false })), + { parent: 3, ambiguous: false }, + { parent: CELL_LIMIT + 2, ambiguous: false }, + ], + terminal: { kind: "void" }, + }), + ); + const { container } = show(); + expect(screen.getByText("Each step shows its first 1,000 values")).toBeTruthy(); + const [first, second] = screen.getAllByTestId("stream-trace-column"); + expect(within(first!).getAllByRole("listitem")).toHaveLength(CELL_LIMIT); + expect(within(second!).getAllByRole("listitem")).toHaveLength(2); + expect(container.querySelectorAll("svg path")).toHaveLength(1); + }); + + it("a reply that lands before its stop shows no outdated note and its values open", async () => { + ipc.debugJvmMemoryFields.mockReturnValue(ok(FIELDS)); + useDebug.setState({ sessions: { 1: { ...session, status: "running" } } }); + ready(OBJECTS); + show(); + expect(screen.queryByRole("status")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Order@50" })); + toggle(item("Order@50")); + expect(await screen.findByText("total")).toBeTruthy(); + expect(ipc.debugJvmMemoryFields).toHaveBeenCalledWith(1, { generation: 9, id: 50 }); + // Its stop's event arrives. + act(() => { + useDebug.setState({ sessions: { 1: { ...session, stops: 3 } } }); + ready(OBJECTS, { endStop: 3 }); + }); + expect(screen.queryByRole("status")).toBeNull(); + }); + + it("Split shows two adjacent steps", () => { + ready(CHAIN_A_READY); + show(); + fireEvent.click(screen.getByRole("tab", { name: "Split" })); + expect(screen.getAllByRole("list")).toHaveLength(2); + expect(screen.queryByTestId("stream-trace-result")).toBeNull(); + fireEvent.click(screen.getByRole("tab", { name: "sorted → map" })); + const lists = screen.getAllByRole("list"); + expect(lists).toHaveLength(2); + expect( + within(lists[1]!) + .getAllByRole("listitem") + .map((c) => c.textContent), + ).toEqual(['"21"', '"41"', '"61"', '"81"']); + }); + + it("opens an object value through the memory reader", async () => { + ipc.debugJvmMemoryFields.mockReturnValue(ok(FIELDS)); + ready(OBJECTS, { endStop: 2 }); + show(); + expect(screen.getAllByTestId("stream-trace-column")[0]!.textContent).toContain("Source"); + fireEvent.click(screen.getByRole("button", { name: "Order@50" })); + toggle(item("Order@50")); + expect(await screen.findByText("total")).toBeTruthy(); + expect(ipc.debugJvmMemoryFields).toHaveBeenCalledWith(1, { generation: 9, id: 50 }); + }); + + it("stops opening values once the program ran on", () => { + ready(OBJECTS, { endStop: 2 }); + show(); + const note = "Values can no longer be expanded after the program resumed"; + expect(screen.queryByText(note)).toBeNull(); + act(() => useDebug.setState({ sessions: { 1: { ...session, stops: 3 } } })); + expect(screen.getByText(note)).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Order@50" })); + expect(item("Order@50").getAttribute("aria-expanded")).toBeNull(); + expect(ipc.debugJvmMemoryFields).not.toHaveBeenCalled(); + // The previews stay. + expect(screen.getByRole("button", { name: '"order"' })).toBeTruthy(); + }); + + it.each<[TraceUnavailable, string]>([ + [{ kind: "notSuspended" }, "The program is not stopped"], + [{ kind: "busy" }, "Another stream trace is running"], + [{ kind: "noSession" }, "The Java debugger has no session for this program"], + [{ kind: "noBackend" }, "Stream tracing needs the Java debugger's inspector"], + [{ kind: "unsupported", detail: "JDK 8" }, "JDK 8"], + [{ kind: "notAtChainStart", detail: "the stop moved" }, "the stop moved"], + ])("explains %j", (reason, text) => { + ready({ status: "unavailable", reason }); + show(); + expect(screen.getByRole("alert").textContent).toBe(text); + }); + + it("shows a failed trace as an error", () => { + ready({ status: "failed", detail: "the debug session ended" }); + show(); + expect(screen.getByRole("alert").textContent).toBe("the debug session ended"); + }); + + it.each(["cancelled before the trace started", "cancelled before the terminal ran"])( + "a recording stopped before the chain ran (%s) is a note, not an error", + (detail) => { + ready({ status: "cancelled", detail }, { stoppedRecording: true }); + show(); + expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.getByText("Recording stopped before the trace started")).toBeTruthy(); + }, + ); + + it("an operation aborted before the chain ran is a note, not an error", () => { + ready({ status: "cancelled", detail: "cancelled before the terminal ran" }); + show(); + expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.getByText("The trace was cancelled before the chain ran")).toBeTruthy(); + }); +}); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 28dc988eaf..f37dfc1c8e 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -7,6 +7,7 @@ import { isTauri, nextRequestId, type AttachableProcess, + type DebugSessionId, type LaunchConfig, type RunConfig, type RunId, @@ -42,6 +43,8 @@ import { refreshMemory, useMemory } from "./memory/memoryState"; import { closeInstances, instancesOutdated, showInstances, showReferrers, useInstances } from "./memory/instancesState"; import { jumpToClass } from "./memory/jumpToClass"; import { captureHeap } from "./heap/heapState"; +import { stopRecording, traceStreamChain } from "./streams/streamState"; +import { isTracing, useStreamTrace } from "./streams/streamStore"; import { startPageProfile, stopPageProfile } from "./js/profile"; import { activeCapturedSnapshot, openHeapDump, saveHeapDump } from "./heap/heapDumpFiles"; import { browserLaunch, browserLaunchConfig, browserUrl, installedDebugBrowser, isBrowserConfig } from "./browser"; @@ -61,9 +64,11 @@ import { evaluate, isLive, justDetached, + pausedThread, rerunSession, revealFrame, rootOf, + selectedFrame, sessionSupports, showExecutionPoint, startBrowserSession, @@ -80,7 +85,13 @@ import { expressionAt, valueHint } from "./editor/valueTooltip"; import { mouseEvaluateTarget } from "./editor/quickEvaluate"; import { showHint } from "@/editor/lsp/hint"; import { pausedLineTargets, startInlineSmartStep } from "./editor/smartStep"; -import { openBreakpointsDialog, openConfigChooser, openEvaluateDialog, openSmartStepChooser } from "./ui/popoverStore"; +import { + openBreakpointsDialog, + openConfigChooser, + openEvaluateDialog, + openSmartStepChooser, + useOverlays, +} from "./ui/popoverStore"; import { tx } from "@/platform/i18n"; import { openAttachPopup } from "./attachPopup"; @@ -114,10 +125,15 @@ async function report(title: string, p: Promise) { function pausedTarget(): { s: DebugSession; thread: number } | null { const s = activeSession(); if (!s || s.status !== "paused") return null; - const thread = s.selectedThread ?? s.stoppedThread ?? s.threads[0]?.id; + const thread = pausedThread(s); return thread == null ? null : { s, thread }; } +/** The trace tab passes its own session; from elsewhere, the active session's trace. */ +function traceTarget(arg: unknown): DebugSessionId | undefined { + return typeof arg === "number" ? arg : activeSession()?.id; +} + function breakpointPathAllowed(path: string): boolean { const reason = classFileBreakpointReason(path); if (!reason) return true; @@ -144,11 +160,6 @@ function notSupported(what: string, s: DebugSession) { }); } -/** The selected frame of the paused session (top frame when none is selected). */ -function selectedFrame(s: DebugSession) { - return s.frames.find((f) => f.id === s.selectedFrame) ?? s.frames[0] ?? null; -} - /** * Smart Step Into: the calls on the current line, picked in the editor (the * dialog when they cannot be placed); one call (or none) steps straight in, like IDEA. @@ -407,7 +418,8 @@ async function warnWithoutXdebug(launch: LaunchConfig) { } export function registerDebugActions(): () => void { - const paused = "debugSessionPaused"; + // A stream trace runs the program from the paused thread, so nothing may move it until the trace ends. + const paused = "debugSessionPaused && !debugStreamTracing"; const step = (id: string, title: string, kind: "over" | "into" | "out", icon: string): Action => ({ id, title, @@ -722,7 +734,8 @@ export function registerDebugActions(): () => void { title: "Pause Program", category: "Debug", icon: "pause", - when: "debugSessionRunning", + // The trace resumes the program itself; a pause would suspend threads under the running trace. + when: "debugSessionRunning && !debugStreamTracing", run: async () => { const s = activeSession(); if (!s || s.status !== "running") return; @@ -808,7 +821,7 @@ export function registerDebugActions(): () => void { title: "Show Execution Point", category: "Debug", icon: "show-execution-point", - when: paused, + when: "debugSessionPaused", run: () => { const s = activeSession(); if (s) void showExecutionPoint(s.id); @@ -850,7 +863,7 @@ export function registerDebugActions(): () => void { title: "Jump to Source", category: "Debug", keyWhen: "debugFramesFocus || debugVariablesFocus", - when: paused, + when: "debugSessionPaused", run: () => { const view = focusedDebugView(); if (view?.jumpToSource) { @@ -1044,6 +1057,49 @@ export function registerDebugActions(): () => void { when: "debugSessionActive", run: () => openEvaluateDialog(evaluateSeed()), }, + { + id: "debug.traceStreamChain", + title: "Trace Stream Chain", + category: "Debug", + icon: "stream-trace", + keywords: ["stream", "chain", "trace", "java"], + when: "debugCanTraceStream", + run: () => { + const t = pausedTarget(); + if (t) void report(tx("Trace Stream Chain failed"), traceStreamChain(t.s.id)); + }, + }, + { + // The trace tab passes its session as `arg`. + id: "debug.streamTrace.stopRecording", + title: "Stop Recording", + category: "Debug", + keywords: ["stream", "trace"], + when: "debugAnyStreamTracing", + enabled: ({ arg }) => { + const id = traceTarget(arg); + return id != null && isTracing(id) && !useStreamTrace.getState().bySession[id]?.stoppedRecording; + }, + run: ({ arg }) => { + const id = traceTarget(arg); + if (id != null) stopRecording(id); + }, + }, + { + id: "debug.streamTrace.abort", + title: "Abort Operation…", + category: "Debug", + keywords: ["stream", "trace", "cancel"], + when: "debugAnyStreamTracing", + enabled: ({ arg }) => { + const id = traceTarget(arg); + return id != null && isTracing(id); + }, + run: ({ arg }) => { + const id = traceTarget(arg); + if (id != null) useOverlays.setState({ streamAbort: id }); + }, + }, { id: "debug.browseConsoleHistory", title: "Browse Console History", diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index 03713beca0..d90b0fc5a6 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -33,6 +33,7 @@ import { installSmartStepPicking, smartStepTargets } from "./editor/smartStep"; import { hotSwapMenuItems, onHotCodeReplace } from "./hotswap"; import { activeSession, + canTraceStream, handleDebugEvent, isLive, loadWatches, @@ -47,12 +48,26 @@ import { jsBrowserType } from "./browser"; import { forgetInstances } from "./memory/instancesState"; import { forgetHeapCapture, forgetHeapOnProjectChange } from "./heap/heapState"; import { heapEditorKind } from "./heap/heapEditorKind"; +import { streamTraceKind } from "./streams/streamTraceKind"; import { installHeapContext } from "./heap/heapDumpFiles"; import { forgetMemory } from "./memory/memoryState"; +import { closeStaleStreamChooser, forgetStreamTrace } from "./streams/streamState"; /** Whether a breakpoint popover, debugger dialog or chooser is open. */ const useAnyOverlay = () => - useOverlays((s) => !!(s.popover || s.evaluate || s.breakpoints || s.chooser || s.attach || s.smartStep)); + useOverlays( + (s) => + !!( + s.popover || + s.evaluate || + s.breakpoints || + s.chooser || + s.attach || + s.smartStep || + s.streamChooser || + s.streamAbort != null + ), + ); /** The Debug stripe button's badge, like Run's: how many debug sessions (child sessions aside) are live. */ function useLiveSessionCount(): number | null { @@ -90,6 +105,7 @@ export function activate(): () => void { useBadge: useLiveSessionCount, }), registerEditorKind(heapEditorKind), + registerEditorKind(streamTraceKind), installHeapContext(), forgetHeapOnProjectChange(), registerOverlay({ @@ -99,7 +115,14 @@ export function activate(): () => void { registerMenuGroup({ id: "debugger.evaluate", menus: ["editor"], - items: () => (activeSession()?.status === "paused" ? [{ kind: "action", action: "debug.evaluate" }] : []), + items: () => { + const s = activeSession(); + if (s?.status !== "paused") return []; + return [ + { kind: "action", action: "debug.evaluate" }, + ...(canTraceStream(s) ? [{ kind: "action" as const, action: "debug.traceStreamChain" }] : []), + ]; + }, }), registerMenuGroup({ id: "debugger.hotswap", @@ -135,11 +158,13 @@ export function activate(): () => void { }), useDebug.subscribe((s, prev) => { if (s.sessions === prev.sessions) return; + closeStaleStreamChooser(); for (const id of Object.keys(prev.sessions)) { if (id in s.sessions) continue; forgetMemory(Number(id)); forgetInstances(Number(id)); forgetHeapCapture(Number(id)); + forgetStreamTrace(Number(id)); } }), useProject.subscribe((s, prev) => { diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 1e01578bf0..e3ae212231 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -55,6 +55,7 @@ import { missingAdapter } from "./missingAdapter"; import { startFailureMessage } from "./startFailure"; import { evaluateWithImports, forgetImports } from "./classImports"; import { JAVA_ADAPTER } from "./java"; +import { isTracing, markTraceStop } from "./streams/streamStore"; export type SessionStatus = "starting" | "running" | "paused" | "stopping" | "terminated"; @@ -410,6 +411,12 @@ export function publishContext() { // Refresh Memory View acts on the selected session only. setContext("debugHasJvmMemory", !!s && isLive(s) && sessionSupports("jvmMemory", s)); setContext("debugHasJsPage", !!s && isLive(s) && sessionSupports("jsPage", s)); + setContext("debugStreamTracing", !!s && isTracing(s.id)); + setContext( + "debugAnyStreamTracing", + Object.values(useDebug.getState().sessions).some((x) => isTracing(x.id)), + ); + setContext("debugCanTraceStream", canTraceStream(s)); } // --- console ----------------------------------------------------------------- @@ -987,6 +994,25 @@ export function sessionSupports(cap: keyof DebugCapabilities, s: DebugSession | return !!s?.caps?.[cap]; } +export function canTraceStream(s: DebugSession | null): boolean { + return !!s && s.status === "paused" && sessionSupports("streamTrace", s) && !isTracing(s.id); +} + +/** The thread a paused session's actions act on. */ +export function pausedThread(s: DebugSession): number | null { + return s.selectedThread ?? s.stoppedThread ?? s.threads[0]?.id ?? null; +} + +/** The selected frame of the paused session (top frame when none is selected). */ +export function selectedFrame(s: DebugSession): StackFrame | null { + return s.frames.find((f) => f.id === s.selectedFrame) ?? s.frames[0] ?? null; +} + +/** The frame a stop selects: the first with source. */ +export function topFrame(frames: StackFrame[]): StackFrame | null { + return frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0] ?? null; +} + function markTerminated(id: DebugSessionId) { stopTaskbarFlash(); forgetImports(id); @@ -1053,7 +1079,7 @@ async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean) const s = useDebug.getState().sessions[id]; if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return; patch(id, { frames }); - const top = frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0]; + const top = topFrame(frames); if (top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) { void logSuspendingHit(id, top); consumeTemporary(top.path, top.line); @@ -1310,7 +1336,8 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) { publishContext(); updateExecutionPoint(); void loadThreads(id); - void loadFrames(id, event.threadId, true); + // The stop a stream trace ends in would bring the source tab over the trace tab that shows its result. + void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1)); const dbg = workflowSettings().debugger; try { if (dbg.showOnBreakpoint) toolWindowService().show("debug"); diff --git a/src/features/debugger/streams/StreamAbortDialog.tsx b/src/features/debugger/streams/StreamAbortDialog.tsx new file mode 100644 index 0000000000..70d832ac22 --- /dev/null +++ b/src/features/debugger/streams/StreamAbortDialog.tsx @@ -0,0 +1,46 @@ +import { useTx } from "@/platform/i18n"; +import { Dialog } from "@/ui"; +import { notifications } from "@/workbench/contributions"; +import { useOverlays } from "../ui/popoverStore"; +import { abortTrace } from "./streamState"; +import { useStreamTrace } from "./streamStore"; + +/** "Abort Operation…" asks first: unlike Stop Recording, it throws into the user's program. */ +export function StreamAbortDialog() { + const tx = useTx(); + const session = useOverlays((s) => s.streamAbort); + // A trace that ended meanwhile has nothing left to abort. + const running = useStreamTrace((s) => { + const e = session == null ? undefined : s.bySession[session]; + return !!e && e.result === null && e.error === null; + }); + const close = () => useOverlays.setState({ streamAbort: null }); + const abort = () => { + close(); + if (session == null) return; + abortTrace(session).catch((e: unknown) => + notifications().notify({ + group: "run", + level: "error", + key: "debug.streamTrace", + title: tx("Cannot abort the operation"), + body: e instanceof Error ? e.message : String(e), + }), + ); + }; + return ( + + {tx("The program will receive java.lang.RuntimeException: oi-cancel. Abort the stream operation?")} + + ); +} diff --git a/src/features/debugger/streams/StreamChainChooser.module.css b/src/features/debugger/streams/StreamChainChooser.module.css new file mode 100644 index 0000000000..23611c8ddf --- /dev/null +++ b/src/features/debugger/streams/StreamChainChooser.module.css @@ -0,0 +1,37 @@ +.list { + height: 220px; +} + +.row { + display: flex; + align-items: center; + gap: var(--space-2); + min-width: 0; + width: 100%; + padding: 0 var(--space-2); +} + +.text { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); + font-size: var(--fs-ui); + color: var(--fg-emphasis); +} + +.reason { + flex: none; + max-width: 50%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--fs-small); + color: var(--fg-subtle); +} + +.unavailable .text { + color: var(--fg-subtle); +} diff --git a/src/features/debugger/streams/StreamChainChooser.tsx b/src/features/debugger/streams/StreamChainChooser.tsx new file mode 100644 index 0000000000..d443aafdf2 --- /dev/null +++ b/src/features/debugger/streams/StreamChainChooser.tsx @@ -0,0 +1,66 @@ +import clsx from "clsx"; +import type { ChainUnavailable } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { Dialog, Icon, List } from "@/ui"; +import { useOverlays } from "../ui/popoverStore"; +import { pickStreamChain } from "./streamState"; +import styles from "./StreamChainChooser.module.css"; + +function unavailableText(reason: ChainUnavailable): string { + switch (reason.kind) { + case "notTopFrame": + return tx("Select the top frame to trace a stream chain"); + case "notAtChainStart": + return tx("Stop at the first line of the chain to trace its real run"); + case "insideChainLambda": + return tx("The chain is already running"); + case "notJavaStreamRoot": + return tx("The stream does not start in this statement"); + case "lazyTerminal": + return tx("iterator() and spliterator() do not run the pipeline"); + case "noTerminal": + return tx("The chain has no terminal operation"); + case "unknownOperation": + return tx("Unknown stream operation"); + case "syntaxError": + return tx("The statement does not parse"); + case "noBackend": + return tx("Stream tracing needs the Java debugger's inspector"); + } +} + +/** Trace Stream Chain's chooser; a chain that cannot be traced stays listed, with why, but does not activate. */ +export function StreamChainChooser() { + const state = useOverlays((s) => s.streamChooser); + const close = () => useOverlays.setState({ streamChooser: null }); + const chains = state?.chains ?? []; + return ( + + String(c.index)} + defaultActiveIndex={Math.max( + 0, + chains.findIndex((c) => !c.reason), + )} + onActivate={(chain) => void pickStreamChain(chain)} + aria-label={tx("Stream chains on the current line")} + className={styles.list} + renderItem={(c) => ( +
+ + {c.text.replace(/\s+/g, " ")} + {c.reason && {unavailableText(c.reason)}} +
+ )} + /> +
+ ); +} diff --git a/src/features/debugger/streams/StreamTraceEditor.module.css b/src/features/debugger/streams/StreamTraceEditor.module.css new file mode 100644 index 0000000000..0ae438a4de --- /dev/null +++ b/src/features/debugger/streams/StreamTraceEditor.module.css @@ -0,0 +1,238 @@ +.root { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + height: 100%; + background: var(--bg-editor); + color: var(--fg); + font-size: var(--fs-ui); +} + +.header { + flex: none; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2) var(--space-4); + padding: var(--space-2) var(--space-3); + border-bottom: 1px solid var(--border); +} + +.chain { + flex: 1 1 320px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--fg-strong); + font-family: var(--font-mono); + -webkit-user-select: text; + user-select: text; +} + +.tools { + flex: none; + display: flex; + align-items: center; + gap: var(--space-2); +} + +.progressText { + color: var(--fg-muted); + font-variant-numeric: tabular-nums; +} + +.banner, +.error { + flex: none; + padding: 4px var(--space-3); + font-size: var(--fs-ui); + color: var(--fg); + border-bottom: 1px solid var(--border); +} +.banner { + background: var(--bg-feedback-warning); + border-bottom-color: var(--border-feedback-warning); +} +.error { + background: var(--bg-feedback-error); + border-bottom-color: var(--border-feedback-error); + -webkit-user-select: text; + user-select: text; +} + +.note { + flex: none; + padding: var(--space-2) var(--space-3); + color: var(--fg-subtle); + font-size: var(--fs-ui); +} + +.result { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; +} + +/* The steps above, the opened value below; the steps scroll, the value pane keeps its height. */ +.body { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; +} + +.flow { + flex: 1; + min-height: 0; + display: flex; + align-items: flex-start; + overflow: auto; + padding: var(--space-2) var(--space-3); +} + +.column { + flex: none; + width: 160px; + display: flex; + flex-direction: column; +} + +.resultColumn { + margin-left: var(--trace-gap); +} + +.columnHead { + display: flex; + align-items: center; + gap: var(--space-2); + height: var(--trace-row); + padding: 0 6px; + border-bottom: 1px solid var(--border); + color: var(--fg-muted); + font-size: var(--fs-small); +} +.columnTitle { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); +} +.count { + flex: none; + color: var(--fg-subtle); + font-variant-numeric: tabular-nums; +} + +.cells { + margin: 0; + padding: 0; + list-style: none; +} + +.cellRow { + display: flex; + height: var(--trace-row); +} + +.cell, +.cellText { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0 6px; + font-family: var(--font-mono); + font-size: var(--fs-ui); + text-align: left; + line-height: var(--trace-row); +} +.cell { + color: var(--fg); + background: none; + border: none; + border-radius: var(--radius-row); + cursor: default; +} +.cell:hover { + background: var(--bg-hover); +} +.cell:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: -2px; +} +.cell.related { + background: var(--accent-soft); + color: var(--fg-strong); +} +.cell[aria-pressed="true"] { + background: var(--bg-selected-strong); + color: var(--fg-strong); +} +.cellText { + color: var(--fg-subtle); +} + +/* Starts below the column heads, so a curve's ends meet the middle of their rows. */ +.curves { + flex: none; + margin-top: var(--trace-row); + overflow: visible; +} +.curve { + fill: none; + stroke: var(--border-strong); + stroke-width: 1; +} +.ambiguous { + stroke: var(--warning); + stroke-dasharray: 3 2; +} +.relatedCurve { + stroke: var(--accent); + stroke-width: 1.5; +} + +.valuePane { + flex: none; + display: flex; + flex-direction: column; + height: min(calc(10 * var(--h-list-row)), 40%); + border-top: 1px solid var(--border); +} + +.valueTree { + flex: 1; + min-height: 0; +} + +.node, +.message { + display: flex; + align-items: center; + min-width: 0; + font-size: var(--fs-ui); +} +.name { + color: var(--fg-strong); +} +.equals { + white-space: pre; + color: var(--fg-subtle); +} +.value { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: var(--font-mono); +} +.message { + color: var(--fg-subtle); +} diff --git a/src/features/debugger/streams/StreamTraceEditor.tsx b/src/features/debugger/streams/StreamTraceEditor.tsx new file mode 100644 index 0000000000..09ce90c19e --- /dev/null +++ b/src/features/debugger/streams/StreamTraceEditor.tsx @@ -0,0 +1,119 @@ +/** The "Stream Trace" editor tab: the session's latest trace while it runs, then what each step did. */ +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import type { DebugSessionId } from "@/platform/ipc"; +import { Button, ProgressBar, T } from "@/ui"; +import type { EditorInput } from "@/workbench/contributions"; +import { formatCount } from "../memory/rows"; +import { useDebug } from "../state"; +import { useActionEnabled } from "../ui/useActionEnabled"; +import { traceValuesOutdated, useStreamTrace, type TraceEntry } from "./streamStore"; +import { traceSessionOf } from "./streamTraceInput"; +import { abortText, bannerText, unavailableText } from "./traceText"; +import { TraceResultView } from "./TraceResultView"; +import styles from "./StreamTraceEditor.module.css"; + +export function StreamTraceEditor({ input }: { input: EditorInput }) { + const session = traceSessionOf(input); + const entry = useStreamTrace((s) => (session == null ? undefined : s.bySession[session])); + // The store forgets a trace with its session, and a tab moved into another window finds none. + if (session == null || !entry) { + return ( +
+
+ This stream trace is no longer available. +
+
+ ); + } + return ; +} + +function TraceView({ session, entry }: { session: DebugSessionId; entry: TraceEntry }) { + const tx = useTx(); + const debug = useDebug((s) => s.sessions[session]); + const running = entry.result === null && entry.error === null; + const result = entry.result; + const terminal = entry.chain.terminal; + const stuck = running ? abortText(entry.abort, tx) : null; + return ( +
+
+ + {entry.chain.text.replace(/\s*\n\s*/g, "")} + + {running && } +
+ {running && } + {running && entry.stoppedRecording && ( +
+ {tx`Breakpoints stay off until ${terminal} finishes`} +
+ )} + {stuck && ( +
+ {stuck} +
+ )} + {entry.error && ( +
+ {entry.error} +
+ )} + {result?.status === "unavailable" && ( +
+ {unavailableText(result.reason, tx)} +
+ )} + {result?.status === "failed" && ( +
+ {result.detail} +
+ )} + {result?.status === "cancelled" && ( +
+ {entry.stoppedRecording ? ( + Recording stopped before the trace started + ) : ( + The trace was cancelled before the chain ran + )} +
+ )} + {result?.status === "ready" && ( + <> + {result.banners.map((b, i) => ( +
+ {bannerText(b, result, tx)} +
+ ))} + + + )} +
+ ); +} + +function RunningTools({ session, entry }: { session: DebugSessionId; entry: TraceEntry }) { + const tx = useTx(); + // The tab's own session: another one may be the active session. + const canStop = useActionEnabled("debug.streamTrace.stopRecording", session); + const canAbort = useActionEnabled("debug.streamTrace.abort", session); + const records = formatCount(entry.progress?.records ?? 0); + const seconds = Math.floor((entry.progress?.elapsedMs ?? 0) / 1000); + return ( +
+ {tx`${records} records · ${seconds} s`} + + +
+ ); +} diff --git a/src/features/debugger/streams/TraceColumns.tsx b/src/features/debugger/streams/TraceColumns.tsx new file mode 100644 index 0000000000..d9863702b8 --- /dev/null +++ b/src/features/debugger/streams/TraceColumns.tsx @@ -0,0 +1,119 @@ +/** Steps side by side, each element linked by a curve to the element of the step before it came from. */ +import { Fragment, type CSSProperties, type ReactNode } from "react"; +import clsx from "clsx"; +import { formatCount } from "../memory/rows"; +import { formatJvmValue } from "../memory/values"; +import type { Column, Edge } from "./layout"; +import styles from "./StreamTraceEditor.module.css"; + +const ROW = 24; +const GAP = 48; +/** Cells drawn per column; a 50 000-record trace would otherwise mount that many buttons and curves. */ +export const CELL_LIMIT = 1000; + +export interface TraceSelection { + selected: number | null; + related: ReadonlySet; + onSelect: (index: number) => void; +} + +/** `slots[i]` is the row of record `i` in its column; `edgesInto[step]` the edges ending in that step. */ +export function TraceColumns({ + columns, + slots, + edgesInto, + selection, + trailing, +}: { + columns: Column[]; + slots: Int32Array; + edgesInto: ReadonlyMap; + selection: TraceSelection; + trailing?: ReactNode; +}) { + return ( +
+ {columns.map((c, i) => ( + + {i > 0 && ( + + )} + + + ))} + {trailing} +
+ ); +} + +const shown = (c: Column) => Math.min(c.items.length, CELL_LIMIT); + +function TraceColumn({ column, selection }: { column: Column; selection: TraceSelection }) { + const { selected, related, onSelect } = selection; + return ( +
+ +
    + {column.items.slice(0, CELL_LIMIT).map(({ index, value }) => ( +
  • + +
  • + ))} +
+
+ ); +} + +export function ColumnHead({ title, count }: { title: string; count?: number }) { + return ( +
+ {title} + {count !== undefined && {formatCount(count)}} +
+ ); +} + +function Curves({ + rows, + edges, + slots, + related, +}: { + rows: number; + edges: Edge[]; + slots: Int32Array; + related: ReadonlySet; +}) { + const y = (i: number) => slots[i]! * ROW + ROW / 2; + const mid = GAP / 2; + return ( + + ); +} diff --git a/src/features/debugger/streams/TraceResultView.tsx b/src/features/debugger/streams/TraceResultView.tsx new file mode 100644 index 0000000000..84a005db7c --- /dev/null +++ b/src/features/debugger/streams/TraceResultView.tsx @@ -0,0 +1,161 @@ +/** A ready trace: every step side by side (Flat), or two adjacent steps at a time (Split). */ +import { useMemo, useState } from "react"; +import clsx from "clsx"; +import { useTx } from "@/platform/i18n"; +import type { DebugSessionId, JvmValue, StreamTraceResult } from "@/platform/ipc"; +import { Tabs } from "@/ui"; +import { formatCount } from "../memory/rows"; +import { formatJvmValue } from "../memory/values"; +import { buildColumns, buildEdges, relatedTo, type Edge } from "./layout"; +import { CELL_LIMIT, ColumnHead, TraceColumns, type TraceSelection } from "./TraceColumns"; +import { TraceValuePane, useTraceFields } from "./TraceValuePane"; +import styles from "./StreamTraceEditor.module.css"; + +type Ready = Extract; +type View = "flat" | "split"; + +/** Selection of the Result cell; records are selected by their index. */ +const RESULT = -1; +const NONE: ReadonlySet = new Set(); + +const opens = (v: JvmValue | null): v is JvmValue => + v?.kind === "object" || v?.kind === "array" || v?.kind === "string"; + +function terminalValue(result: Ready): JvmValue | null { + const t = result.terminal; + return t.kind === "value" ? t.value : t.kind === "threw" ? t.exception : null; +} + +export function TraceResultView({ + session, + result, + outdated, +}: { + session: DebugSessionId; + result: Ready; + outdated: boolean; +}) { + const tx = useTx(); + const [view, setView] = useState("flat"); + const [pair, setPair] = useState(0); + const [selected, setSelected] = useState(null); + const fields = useTraceFields(session); + + const columns = useMemo(() => buildColumns(result.steps, result.records, tx), [result, tx]); + const edges = useMemo(() => buildEdges(result.links), [result]); + const slots = useMemo(() => { + const out = new Int32Array(result.records.length); + for (const c of columns) c.items.forEach((it, row) => (out[it.index] = row)); + return out; + }, [columns, result]); + const edgesInto = useMemo(() => { + const out = new Map(); + for (const e of edges) { + const step = result.records[e.to]!.step; + (out.get(step) ?? out.set(step, []).get(step)!).push(e); + } + return out; + }, [edges, result]); + const related = useMemo( + () => (selected == null || selected === RESULT ? NONE : relatedTo(selected, edges)), + [selected, edges], + ); + + const selection: TraceSelection = { + selected, + related, + onSelect: (i) => setSelected((cur) => (cur === i ? null : i)), + }; + const value = selected === RESULT ? terminalValue(result) : selected != null ? result.records[selected]!.value : null; + const shownPair = Math.min(pair, Math.max(0, columns.length - 2)); + const capped = columns.some((c) => c.items.length > CELL_LIMIT); + const limit = formatCount(CELL_LIMIT); + + return ( +
+ setView(v as View)} + aria-label={tx("Stream trace view")} + /> + {outdated && ( +
+ {tx("Values can no longer be expanded after the program resumed")} +
+ )} + {capped &&
{tx`Each step shows its first ${limit} values`}
} + {view === "split" && columns.length > 1 && ( + { + const text = `${c.title} → ${columns[i + 1]!.title}`; + return { id: String(i), label: {text}, text }; + })} + activeId={String(shownPair)} + onSelect={(id) => setPair(Number(id))} + aria-label={tx("Steps")} + /> + )} +
+ setSelected((cur) => (cur === RESULT ? null : RESULT))} + /> + ) + } + /> + {opens(value) && ( + + )} +
+
+ ); +} + +function ResultColumn({ + value, + selected, + onSelect, +}: { + value: JvmValue | null; + selected: boolean; + onSelect: () => void; +}) { + const tx = useTx(); + const title = tx("Result"); + return ( +
+ +
    +
  • + {value ? ( + + ) : ( + {tx("No result")} + )} +
  • +
+
+ ); +} diff --git a/src/features/debugger/streams/TraceValuePane.tsx b/src/features/debugger/streams/TraceValuePane.tsx new file mode 100644 index 0000000000..0f7297643f --- /dev/null +++ b/src/features/debugger/streams/TraceValuePane.tsx @@ -0,0 +1,105 @@ +/** The selected value of a trace, opened into its fields like an instance in the Memory view. */ +import { useCallback, useMemo, useRef, useState } from "react"; +import { T, Tree } from "@/ui"; +import { useTx } from "@/platform/i18n"; +import { call, commands, type DebugSessionId, type JvmObjectRef, type JvmValue } from "@/platform/ipc"; +import type { NodeEntry } from "../memory/instancesState"; +import { childrenOf, instanceNodes, labelOf, type PaneNode } from "../memory/instancesTree"; +import { refKey } from "../memory/values"; +import styles from "./StreamTraceEditor.module.css"; + +const NOTHING_LOADED: NodeEntry = { + fields: null, + referrers: null, + loadingFields: false, + loadingReferrers: false, + error: null, +}; + +/** Fields read so far for one trace, kept while the user moves between its values. */ +export function useTraceFields(session: DebugSessionId) { + const [nodes, setNodes] = useState>({}); + const asked = useRef(new Set()); + const ensure = useCallback( + (ref: JvmObjectRef) => { + const key = refKey(ref); + if (asked.current.has(key)) return; + asked.current.add(key); + const put = (n: Partial) => setNodes((p) => ({ ...p, [key]: { ...NOTHING_LOADED, ...n } })); + put({ loadingFields: true }); + call(commands.debugJvmMemoryFields(session, ref)).then( + (fields) => put({ fields }), + (e: unknown) => { + // Opening it again asks again. + asked.current.delete(key); + put({ error: e instanceof Error ? e.message : String(e) }); + }, + ); + }, + [session], + ); + return { nodes, ensure }; +} + +export function TraceValuePane({ + value, + generation, + outdated, + fields, +}: { + value: JvmValue; + generation: number; + /** The program ran on: what was read stays open, nothing more is read. */ + outdated: boolean; + fields: ReturnType; +}) { + const tx = useTx(); + const { nodes, ensure } = fields; + const [expanded, setExpanded] = useState>(() => new Set()); + const roots = useMemo(() => instanceNodes(generation, [value]), [generation, value]); + const getChildren = useCallback((n: PaneNode) => childrenOf(n, nodes, tx), [nodes, tx]); + const getLabel = useCallback((n: PaneNode) => labelOf(n, tx), [tx]); + const isExpandable = useCallback( + (n: PaneNode) => n.kind === "value" && !!n.ref && (!outdated || childrenOf(n, nodes) !== undefined), + [nodes, outdated], + ); + return ( +
+ + className={styles.valueTree} + aria-label={tx("Value")} + roots={roots} + getKey={(n) => n.key} + getLabel={getLabel} + getChildren={getChildren} + isExpandable={isExpandable} + expanded={expanded} + onExpandedChange={(next, n, open) => { + setExpanded(next); + if (open && !outdated && n.kind === "value" && n.ref) ensure(n.ref); + }} + renderNode={(n) => } + empty={ + + Nothing to show + + } + /> +
+ ); +} + +function ValueRow({ node, label }: { node: PaneNode; label: string }) { + if (node.kind !== "value") return {label}; + return ( + + {node.name != null && ( + <> + {node.name} + = + + )} + {label} + + ); +} diff --git a/src/features/debugger/streams/layout.ts b/src/features/debugger/streams/layout.ts new file mode 100644 index 0000000000..840b7d95e0 --- /dev/null +++ b/src/features/debugger/streams/layout.ts @@ -0,0 +1,55 @@ +/** Columns and links of a stream trace, from the host's `records` and `links`. No React, no IPC. */ +import type { JvmValue, Link, TraceRecordView } from "@/platform/ipc"; +import { tx as catalogTx } from "@/platform/i18n"; + +/** A component passes its `useTx()`, so the "Source" title follows the locale. */ +type Tx = typeof catalogTx; + +export type Column = { step: number; title: string; items: { index: number; value: JvmValue }[] }; + +/** `from` and `to` are record indexes: `from` is the element of the step before that `to` came from. */ +export type Edge = { from: number; to: number; ambiguous: boolean }; + +/** One column per recorded step, values in recording order. `steps[0]` is empty for a stream held in a local. */ +export function buildColumns(steps: string[], records: TraceRecordView[], tx: Tx = catalogTx): Column[] { + const count = records.reduce((n, r) => Math.max(n, r.step + 1), steps.length); + const columns: Column[] = Array.from({ length: count }, (_, step) => ({ + step, + title: steps[step] || (step === 0 ? tx("Source") : ""), + items: [], + })); + records.forEach((r, index) => columns[r.step]!.items.push({ index, value: r.value })); + return columns; +} + +export function buildEdges(links: Link[]): Edge[] { + const edges: Edge[] = []; + links.forEach((l, to) => { + if (l.parent != null) edges.push({ from: l.parent, to, ambiguous: l.ambiguous }); + }); + return edges; +} + +/** + * `index`, what it came from and what it became. Each way is walked on its own, so the other + * elements a `flatMap` made from the same source stay out. + */ +export function relatedTo(index: number, edges: Edge[]): Set { + const parents = new Map(); + const children = new Map(); + for (const e of edges) { + (parents.get(e.to) ?? parents.set(e.to, []).get(e.to)!).push(e.from); + (children.get(e.from) ?? children.set(e.from, []).get(e.from)!).push(e.to); + } + const out = new Set([index]); + for (const next of [parents, children]) { + const queue = [index]; + for (let at = 0; at < queue.length; at++) + for (const j of next.get(queue[at]!) ?? []) + if (!out.has(j)) { + out.add(j); + queue.push(j); + } + } + return out; +} diff --git a/src/features/debugger/streams/streamState.ts b/src/features/debugger/streams/streamState.ts new file mode 100644 index 0000000000..b52062da04 --- /dev/null +++ b/src/features/debugger/streams/streamState.ts @@ -0,0 +1,134 @@ +import { Channel } from "@tauri-apps/api/core"; +import { + call, + commands, + nextRequestId, + type DebugSessionId, + type RequestId, + type StreamChainInfo, + type TraceProgress, +} from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { notifications } from "@/workbench/contributions"; +import { pausedThread, publishContext, selectedFrame, topFrame, useDebug } from "../state"; +import { openStreamChainChooser, useOverlays } from "../ui/popoverStore"; +import { isTracing, useStreamTrace, type TraceEntry } from "./streamStore"; +import { openStreamTraceTab } from "./streamTraceInput"; + +/** Applies `patch` while `request` is still the session's trace: a forgotten or newer trace ignores late replies. */ +function patchEntry(session: DebugSessionId, request: RequestId, patch: Partial) { + useStreamTrace.setState((s) => { + const e = s.bySession[session]; + return e?.request === request ? { bySession: { ...s.bySession, [session]: { ...e, ...patch } } } : s; + }); +} + +/** The session's running trace, if any. */ +function runningEntry(s: DebugSessionId): TraceEntry | null { + return isTracing(s) ? useStreamTrace.getState().bySession[s]! : null; +} + +/** The paused thread and selected frame the trace starts from, as the step actions pick them. */ +function tracePoint(session: DebugSessionId) { + const s = useDebug.getState().sessions[session]; + if (!s || s.status !== "paused") return null; + const thread = pausedThread(s); + const frame = selectedFrame(s); + return thread == null || !frame ? null : { thread, frame, top: topFrame(s.frames)?.id === frame.id }; +} + +function notify(title: string) { + notifications().notify({ group: "run", level: "info", key: "debug.streamTrace", title }); +} + +/** Lists the chains on the paused line: one that can be traced, alone, runs at once; otherwise the user picks. */ +export async function traceStreamChain(s: DebugSessionId): Promise { + const at = tracePoint(s); + if (!at || isTracing(s)) return; + const chains = await call(commands.debugStreamChains(s, at.frame, at.top)); + const [only] = chains; + if (!only) notify(tx("No stream chain on this line")); + else if (chains.length === 1 && !only.reason) await startTrace(s, only); + else openStreamChainChooser(s, at.frame.id, chains); +} + +/** The chooser's chains belong to the stop and frame they were listed for. */ +function chooserStale(c: { session: DebugSessionId; frame: number }): boolean { + const s = useDebug.getState().sessions[c.session]; + return !s || s.status !== "paused" || selectedFrame(s)?.id !== c.frame; +} + +export function closeStaleStreamChooser(): void { + const c = useOverlays.getState().streamChooser; + if (c && chooserStale(c)) useOverlays.setState({ streamChooser: null }); +} + +/** The chooser's pick. A chooser left open past its stop says so instead of tracing another frame's chain. */ +export async function pickStreamChain(chain: StreamChainInfo): Promise { + const c = useOverlays.getState().streamChooser; + if (!c || chain.reason) return; + useOverlays.setState({ streamChooser: null }); + if (chooserStale(c)) notify(tx("The stop or the selected frame changed; trace the stream chain again")); + else await startTrace(c.session, chain); +} + +export async function startTrace(s: DebugSessionId, chain: StreamChainInfo): Promise { + const at = tracePoint(s); + if (!at || chain.reason || isTracing(s)) return; + const request = nextRequestId(); + const entry: TraceEntry = { + request, + chain, + progress: null, + result: null, + error: null, + stoppedRecording: false, + abort: null, + thread: at.thread, + endStop: null, + }; + useStreamTrace.setState((st) => ({ bySession: { ...st.bySession, [s]: entry } })); + publishContext(); + openStreamTraceTab(s); + const channel = new Channel(); + channel.onmessage = (progress) => patchEntry(s, request, { progress }); + try { + // The host checks `range` against the chain it finds again at this frame, so it goes unchanged. + const result = await call( + commands.debugStreamTrace(s, request, at.thread, at.frame, chain.index, chain.range, channel), + ); + patchEntry(s, request, { result }); + } catch (e) { + patchEntry(s, request, { error: e instanceof Error ? e.message : String(e) }); + } + // Left open, it would come back with the session's next trace. + if (useOverlays.getState().streamAbort === s && !isTracing(s)) useOverlays.setState({ streamAbort: null }); + publishContext(); +} + +/** Engine R reads a cancelled request as "stop recording": the program runs on and the trace still ends with a result. */ +export function stopRecording(s: DebugSessionId): void { + const e = runningEntry(s); + if (!e || e.stoppedRecording) return; + void commands.cancelRequest(e.request).catch(() => {}); + patchEntry(s, e.request, { stoppedRecording: true }); +} + +/** Cancels the terminal operation itself: the program gets `RuntimeException("oi-cancel:")`. */ +export async function abortTrace(s: DebugSessionId): Promise { + const e = runningEntry(s); + if (!e) return; + const abort = await call(commands.debugStreamTraceAbort(s)); + if (abort) patchEntry(s, e.request, { abort }); +} + +export function forgetStreamTrace(s: DebugSessionId): void { + if (useOverlays.getState().streamChooser?.session === s) useOverlays.setState({ streamChooser: null }); + if (useOverlays.getState().streamAbort === s) useOverlays.setState({ streamAbort: null }); + if (!(s in useStreamTrace.getState().bySession)) return; + useStreamTrace.setState((st) => { + const { [s]: _gone, ...rest } = st.bySession; + return { bySession: rest }; + }); + publishContext(); +} diff --git a/src/features/debugger/streams/streamStore.ts b/src/features/debugger/streams/streamStore.ts new file mode 100644 index 0000000000..bdd52e0d91 --- /dev/null +++ b/src/features/debugger/streams/streamStore.ts @@ -0,0 +1,56 @@ +/** The stream trace store. A leaf: `state.ts` reads it for its context keys, so it must not import `state.ts`. */ +import { create } from "zustand"; +import type { + AbortState, + DebugSessionId, + RequestId, + StreamChainInfo, + StreamTraceResult, + TraceProgress, +} from "@/platform/ipc"; + +export interface TraceEntry { + request: RequestId; + chain: StreamChainInfo; + progress: TraceProgress | null; + result: StreamTraceResult | null; + error: string | null; + /** "Stop Recording" was asked: the terminal operation goes on running, the records so far are kept. */ + stoppedRecording: boolean; + /** How far the host got cancelling the terminal operation; `null` until it is cancelled. */ + abort: AbortState | null; + /** The thread the chain runs on; the trace ends with this thread's stop after stepping out of the terminal. */ + thread: number; + /** The session's `stops` at that stop, like the Memory view's `takenAtStop`; `null` until its event arrives. */ + endStop: number | null; +} + +/** The latest trace of each session; it stays after it ends, since its tab shows it. */ +export const useStreamTrace = create<{ bySession: Record }>(() => ({ bySession: {} })); + +export function isTracing(s: DebugSessionId): boolean { + const e = useStreamTrace.getState().bySession[s]; + return !!e && e.result === null && e.error === null; +} + +/** + * Called for each stop event: records it as the stop the trace ended in when it is the traced + * thread's first stop since the trace started, and says whether it was. Another thread may stop + * meanwhile (an exception breakpoint), so stops are not counted. The reply may come before or + * after the event, so a `ready` result still takes it. + */ +export function markTraceStop(s: DebugSessionId, thread: number, stops: number): boolean { + const e = useStreamTrace.getState().bySession[s]; + if (!e || e.endStop !== null || thread !== e.thread || !(isTracing(s) || e.result?.status === "ready")) return false; + useStreamTrace.setState((st) => ({ bySession: { ...st.bySession, [s]: { ...e, endStop: stops } } })); + return true; +} + +/** + * A ready trace's values can be opened only in the stop it ended in. Before that stop's event + * arrives the host is already suspended in it, so they are not outdated yet. + */ +export function traceValuesOutdated(e: TraceEntry, session: { status: string; stops: number } | undefined): boolean { + if (!session || session.status === "terminated") return true; + return e.endStop !== null && (session.status !== "paused" || session.stops !== e.endStop); +} diff --git a/src/features/debugger/streams/streamTraceInput.ts b/src/features/debugger/streams/streamTraceInput.ts new file mode 100644 index 0000000000..aa39c4fb0a --- /dev/null +++ b/src/features/debugger/streams/streamTraceInput.ts @@ -0,0 +1,18 @@ +import type { DebugSessionId } from "@/platform/ipc"; +import { maybeEditorService, type EditorInput } from "@/workbench/contributions"; + +export const STREAM_TRACE_KIND = "stream-trace"; + +/** One tab per session: it shows the session's latest trace from the store, so its data is only the session id. */ +export function openStreamTraceTab(session: DebugSessionId): void { + void maybeEditorService() + ?.openInput({ kind: STREAM_TRACE_KIND, key: `${STREAM_TRACE_KIND}:${session}`, data: { session } }, { focus: true }) + .catch((e) => console.warn("cannot open the stream trace tab", e)); +} + +/** The session a trace tab shows, or `null` for any other tab. */ +export function traceSessionOf(input: EditorInput): DebugSessionId | null { + if (input.kind !== STREAM_TRACE_KIND) return null; + const session = (input.data as { session?: unknown } | undefined)?.session; + return typeof session === "number" ? session : null; +} diff --git a/src/features/debugger/streams/streamTraceKind.ts b/src/features/debugger/streams/streamTraceKind.ts new file mode 100644 index 0000000000..24876992e2 --- /dev/null +++ b/src/features/debugger/streams/streamTraceKind.ts @@ -0,0 +1,12 @@ +import { lazyComponent } from "@/ui"; +import { tx } from "@/platform/i18n"; +import type { EditorKindContribution } from "@/workbench/contributions"; +import { STREAM_TRACE_KIND } from "./streamTraceInput"; + +/** Not `restorable`: the values belong to one stop of a debug session that a restart ends. */ +export const streamTraceKind: EditorKindContribution = { + kind: STREAM_TRACE_KIND, + component: lazyComponent(() => import("./StreamTraceEditor").then((m) => m.StreamTraceEditor)), + title: () => tx("Stream Trace"), + icon: () => "stream-trace", +}; diff --git a/src/features/debugger/streams/traceText.ts b/src/features/debugger/streams/traceText.ts new file mode 100644 index 0000000000..e98811600d --- /dev/null +++ b/src/features/debugger/streams/traceText.ts @@ -0,0 +1,64 @@ +/** What the trace tab says about a result. A component passes its `useTx()` so the text follows the locale. */ +import type { AbortState, StreamTraceResult, TraceBanner, TraceUnavailable } from "@/platform/ipc"; +import { tx as catalogTx } from "@/platform/i18n"; +import { formatCount } from "../memory/rows"; +import { formatJvmValue } from "../memory/values"; + +type Tx = typeof catalogTx; +type Ready = Extract; + +export function unavailableText(reason: TraceUnavailable, tx: Tx = catalogTx): string { + switch (reason.kind) { + case "noBackend": + return tx("Stream tracing needs the Java debugger's inspector"); + case "notSuspended": + return tx("The program is not stopped"); + case "busy": + return tx("Another stream trace is running"); + case "noSession": + return tx("The Java debugger has no session for this program"); + case "notAtChainStart": + case "unsupported": + return reason.detail; + } +} + +export function bannerText(banner: TraceBanner, result: Ready, tx: Tx = catalogTx): string { + switch (banner.kind) { + case "truncated": { + const n = formatCount(result.records.length); + const dropped = formatCount(banner.dropped); + return tx`Recording stopped after ${n} records (${dropped} more not recorded)`; + } + case "countFromSize": + return tx("count() was computed from the source size; the pipeline did not run"); + case "sortedPassThrough": + return tx("sorted() kept the order: the source was already sorted"); + case "sequentialized": + return tx("The parallel chain ran sequentially so it could be traced"); + case "breakpointsSkipped": { + const count = formatCount(banner.count); + return banner.count === 1 + ? tx`${count} breakpoint was off while the chain ran` + : tx`${count} breakpoints were off while the chain ran`; + } + case "breakpointsResumed": { + const count = formatCount(banner.count); + return banner.count === 1 + ? tx`${count} breakpoint hit while the chain ran was resumed` + : tx`${count} breakpoint hits while the chain ran were resumed`; + } + case "threw": { + const exception = result.terminal.kind === "threw" ? formatJvmValue(result.terminal.exception) : ""; + return tx`The chain threw ${exception}`; + } + } +} + +/** Why an abort has not ended the operation yet, or `null` when there is nothing to say. */ +export function abortText(abort: AbortState | null, tx: Tx = catalogTx): string | null { + if (abort?.kind !== "stuck") return null; + if (abort.holders.length === 0) return tx("The operation is stuck; stop the debug session to end it"); + const threads = abort.holders.map(([, name]) => name).join(", "); + return tx`The operation is stuck: ${threads} hold locks it needs`; +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 2bba4af2ca..8056febe31 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -42,6 +42,8 @@ import { useExceptionBreakpoints, } from "../breakpoints/exceptions"; import { EventBreakpointsSection } from "../js/EventBreakpointsSection"; +import { StreamChainChooser } from "../streams/StreamChainChooser"; +import { StreamAbortDialog } from "../streams/StreamAbortDialog"; import { closeBreakpointPopover, useOverlays } from "./popoverStore"; import { VariablesView, type VarRoot } from "./VariablesView"; import { useExpressionCompletion } from "./ExpressionCompletion"; @@ -59,6 +61,8 @@ export function DebuggerOverlays() { + + ); } diff --git a/src/features/debugger/ui/popoverStore.ts b/src/features/debugger/ui/popoverStore.ts index 7de24b4b70..845266696c 100644 --- a/src/features/debugger/ui/popoverStore.ts +++ b/src/features/debugger/ui/popoverStore.ts @@ -1,6 +1,6 @@ /** Open/close state of the debugger's overlays (rendered by `Overlays.tsx`). */ import { create } from "zustand"; -import type { AttachableProcess, DebugSessionId, RunConfig, StepInTarget } from "@/platform/ipc"; +import type { AttachableProcess, DebugSessionId, RunConfig, StepInTarget, StreamChainInfo } from "@/platform/ipc"; /** A Smart Step Into target placed on the paused line (UTF-16 offsets within the line). */ export interface InlineStepTarget { @@ -33,6 +33,13 @@ interface OverlayState { targets: StepInTarget[]; inline?: { path: string; line: number; ranges: InlineStepTarget[]; index: number }; } | null; + /** + * Trace Stream Chain: the chains on the paused line, unavailable ones listed with their reason. + * `frame` is the frame they were found in; chain indexes mean nothing for another one. + */ + streamChooser: { session: DebugSessionId; frame: number; chains: StreamChainInfo[] } | null; + /** The session whose stream trace "Abort Operation…" asks about. */ + streamAbort: DebugSessionId | null; } export const useOverlays = create(() => ({ @@ -42,6 +49,8 @@ export const useOverlays = create(() => ({ chooser: null, attach: null, smartStep: null, + streamChooser: null, + streamAbort: null, })); export function openBreakpointPopover(path: string, id: string, at: { x: number; y: number }, focusLog = false) { @@ -67,3 +76,7 @@ export function openConfigChooser(configs: RunConfig[]) { export function openSmartStepChooser(session: DebugSessionId, thread: number, targets: StepInTarget[]) { useOverlays.setState({ smartStep: { session, thread, targets } }); } + +export function openStreamChainChooser(session: DebugSessionId, frame: number, chains: StreamChainInfo[]) { + useOverlays.setState({ streamChooser: { session, frame, chains } }); +} diff --git a/src/features/debugger/ui/useActionEnabled.ts b/src/features/debugger/ui/useActionEnabled.ts index 8d66440ec6..d341f4c87c 100644 --- a/src/features/debugger/ui/useActionEnabled.ts +++ b/src/features/debugger/ui/useActionEnabled.ts @@ -1,9 +1,9 @@ import { getAction, isActionEnabled } from "@/platform/actions"; import { useContextKeys } from "@/platform/context"; -/** Whether action `id` would run now; a button bound to it shows disabled otherwise. */ -export function useActionEnabled(id: string): boolean { +/** Whether action `id` would run now with `arg`; a button bound to it shows disabled otherwise. */ +export function useActionEnabled(id: string, arg?: unknown): boolean { const ctx = useContextKeys(); const a = getAction(id); - return !!a && isActionEnabled(a, ctx); + return !!a && isActionEnabled(a, ctx, arg); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 5870aa6272..da4ba19db2 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2180,5 +2180,53 @@ "The agent asked for permission to continue": "The agent asked for permission to continue", "The agent task was archived": "The agent task was archived", "The agent did not answer in time": "The agent did not answer in time", - "The agent did not reply with a commit message": "The agent did not reply with a commit message" + "The agent did not reply with a commit message": "The agent did not reply with a commit message", + "Trace Stream Chain": "Trace Stream Chain", + "Trace Stream Chain failed": "Trace Stream Chain failed", + "No stream chain on this line": "No stream chain on this line", + "Choose Stream Chain": "Choose Stream Chain", + "Stream chains on the current line": "Stream chains on the current line", + "Select the top frame to trace a stream chain": "Select the top frame to trace a stream chain", + "Stop at the first line of the chain to trace its real run": "Stop at the first line of the chain to trace its real run", + "The chain is already running": "The chain is already running", + "The stream does not start in this statement": "The stream does not start in this statement", + "iterator() and spliterator() do not run the pipeline": "iterator() and spliterator() do not run the pipeline", + "The chain has no terminal operation": "The chain has no terminal operation", + "Unknown stream operation": "Unknown stream operation", + "The statement does not parse": "The statement does not parse", + "Stream tracing needs the Java debugger's inspector": "Stream tracing needs the Java debugger's inspector", + "The stop or the selected frame changed; trace the stream chain again": "The stop or the selected frame changed; trace the stream chain again", + "Stream Trace": "Stream Trace", + "Stop Recording": "Stop Recording", + "Abort Operation…": "Abort Operation…", + "Abort Operation": "Abort Operation", + "Cannot abort the operation": "Cannot abort the operation", + "The program will receive java.lang.RuntimeException: oi-cancel. Abort the stream operation?": "The program will receive java.lang.RuntimeException: oi-cancel. Abort the stream operation?", + "This stream trace is no longer available.": "This stream trace is no longer available.", + "Tracing the stream chain": "Tracing the stream chain", + "Breakpoints stay off until {terminal} finishes": "Breakpoints stay off until {terminal} finishes", + "The operation is stuck: {threads} hold locks it needs": "The operation is stuck: {threads} hold locks it needs", + "The operation is stuck; stop the debug session to end it": "The operation is stuck; stop the debug session to end it", + "Recording stopped before the trace started": "Recording stopped before the trace started", + "The trace was cancelled before the chain ran": "The trace was cancelled before the chain ran", + "{records} records · {seconds} s": "{records} records · {seconds} s", + "Recording stopped after {n} records ({dropped} more not recorded)": "Recording stopped after {n} records ({dropped} more not recorded)", + "count() was computed from the source size; the pipeline did not run": "count() was computed from the source size; the pipeline did not run", + "sorted() kept the order: the source was already sorted": "sorted() kept the order: the source was already sorted", + "The parallel chain ran sequentially so it could be traced": "The parallel chain ran sequentially so it could be traced", + "{count} breakpoint was off while the chain ran": "{count} breakpoint was off while the chain ran", + "{count} breakpoints were off while the chain ran": "{count} breakpoints were off while the chain ran", + "{count} breakpoint hit while the chain ran was resumed": "{count} breakpoint hit while the chain ran was resumed", + "{count} breakpoint hits while the chain ran were resumed": "{count} breakpoint hits while the chain ran were resumed", + "The chain threw {exception}": "The chain threw {exception}", + "The program is not stopped": "The program is not stopped", + "Another stream trace is running": "Another stream trace is running", + "The Java debugger has no session for this program": "The Java debugger has no session for this program", + "Flat": "Flat", + "Split": "Split", + "Stream trace view": "Stream trace view", + "Values can no longer be expanded after the program resumed": "Values can no longer be expanded after the program resumed", + "Each step shows its first {limit} values": "Each step shows its first {limit} values", + "Steps": "Steps", + "No result": "No result" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1055bf8b71..ff765efecf 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8567,5 +8567,53 @@ "The agent asked for permission to continue": "智能体请求许可以继续", "The agent task was archived": "智能体任务已归档", "The agent did not answer in time": "智能体未在限定时间内回复", - "The agent did not reply with a commit message": "智能体没有返回提交消息" + "The agent did not reply with a commit message": "智能体没有返回提交消息", + "Trace Stream Chain": "跟踪流链", + "Trace Stream Chain failed": "跟踪流链失败", + "No stream chain on this line": "此行没有流链", + "Choose Stream Chain": "选择流链", + "Stream chains on the current line": "当前行中的流链", + "Select the top frame to trace a stream chain": "选择顶层帧以跟踪流链", + "Stop at the first line of the chain to trace its real run": "在链的第一行停下,才能跟踪它的实际运行", + "The chain is already running": "该链已在运行", + "The stream does not start in this statement": "流不是在此语句中开始的", + "iterator() and spliterator() do not run the pipeline": "iterator() 和 spliterator() 不会运行流水线", + "The chain has no terminal operation": "该链没有终端操作", + "Unknown stream operation": "未知的流操作", + "The statement does not parse": "无法解析该语句", + "Stream tracing needs the Java debugger's inspector": "流跟踪需要 Java 调试器的检查器", + "The stop or the selected frame changed; trace the stream chain again": "停止位置或所选帧已更改,请重新跟踪流链", + "Stream Trace": "流跟踪", + "Stop Recording": "停止记录", + "Abort Operation…": "中止操作…", + "Abort Operation": "中止操作", + "Cannot abort the operation": "无法中止该操作", + "The program will receive java.lang.RuntimeException: oi-cancel. Abort the stream operation?": "程序将收到 java.lang.RuntimeException: oi-cancel。要中止流操作吗?", + "This stream trace is no longer available.": "此流跟踪已不可用。", + "Tracing the stream chain": "正在跟踪流链", + "Breakpoints stay off until {terminal} finishes": "{terminal} 完成之前断点保持关闭", + "The operation is stuck: {threads} hold locks it needs": "操作被阻塞:{threads} 持有它所需的锁", + "The operation is stuck; stop the debug session to end it": "操作被阻塞;请停止调试会话以结束它", + "Recording stopped before the trace started": "跟踪开始前已停止记录", + "The trace was cancelled before the chain ran": "链运行前跟踪已取消", + "{records} records · {seconds} s": "{records} 条记录 · {seconds} 秒", + "Recording stopped after {n} records ({dropped} more not recorded)": "记录 {n} 条后已停止(另有 {dropped} 条未记录)", + "count() was computed from the source size; the pipeline did not run": "count() 由源的大小算出;流水线未运行", + "sorted() kept the order: the source was already sorted": "sorted() 保持了原顺序:源已经有序", + "The parallel chain ran sequentially so it could be traced": "并行链已按顺序运行,以便跟踪", + "{count} breakpoint was off while the chain ran": "链运行期间有 {count} 个断点处于关闭状态", + "{count} breakpoints were off while the chain ran": "链运行期间有 {count} 个断点处于关闭状态", + "{count} breakpoint hit while the chain ran was resumed": "链运行期间 {count} 次断点命中已自动继续", + "{count} breakpoint hits while the chain ran were resumed": "链运行期间 {count} 次断点命中已自动继续", + "The chain threw {exception}": "链抛出了 {exception}", + "The program is not stopped": "程序未处于停止状态", + "Another stream trace is running": "另一个流跟踪正在运行", + "The Java debugger has no session for this program": "Java 调试器没有此程序的会话", + "Flat": "平铺", + "Split": "拆分", + "Stream trace view": "流跟踪视图", + "Values can no longer be expanded after the program resumed": "程序恢复运行后,值无法再展开", + "Each step shows its first {limit} values": "每个步骤仅显示前 {limit} 个值", + "Steps": "步骤", + "No result": "无结果" } diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index babab958a5..98c03d48f0 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -488,6 +488,7 @@ const ICONS = { "mute-breakpoint": "run/muteBreakpoints", "view-breakpoints": "run/viewBreakpoints", "heap-snapshot": "actions/profileMemory", + "stream-trace": "openidea/general/streamTrace", // Build tools (Maven / Gradle tool windows) "maven-project": "maven/mavenProject", "maven-module": "maven/mavenModule", diff --git a/src/ui/openidea/general/streamTrace.svg b/src/ui/openidea/general/streamTrace.svg new file mode 100644 index 0000000000..85e85ead83 --- /dev/null +++ b/src/ui/openidea/general/streamTrace.svg @@ -0,0 +1,4 @@ + + + +