Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e6a9b8e
Bound the tree-sitter parse cache so edited versions are evicted [MEM…
MelbourneDeveloper Nov 18, 2026
c73b73a
Evict ended CPU sessions, including ones whose sampler closed [MEM-06…
MelbourneDeveloper Nov 18, 2026
0b140ed
Progress notifier holds a weak service reference [MEM-060-PROGRESS-TASK]
MelbourneDeveloper Nov 18, 2026
0c47351
Stop evicted and shut-down memory sessions in their backend [MEM-060-…
MelbourneDeveloper Nov 18, 2026
eef1819
Reference example owns its request tasks and aborts them at session e…
MelbourneDeveloper Nov 18, 2026
d90fcc7
Reference example releases memos for URIs it no longer tracks [MEM-06…
MelbourneDeveloper Nov 18, 2026
50c62b5
Add an RAII owner for queued ingress requests [MEM-060-QUEUED-REQUEST]
MelbourneDeveloper Nov 18, 2026
e8d6384
Satisfy clippy in the parse-cache bound and its regression test
MelbourneDeveloper Nov 18, 2026
44d6b52
Bound unread sidecar notifications and count the overflow [MEM-060-SI…
MelbourneDeveloper Nov 18, 2026
f778b07
Live scheduler exits when its consumer drops the triggers [MEM-060-SC…
MelbourneDeveloper Nov 18, 2026
6ab9c70
Reference example coalesces workspace-change notifications behind a s…
MelbourneDeveloper Nov 18, 2026
48d97f9
Profiler UI: evict DAP session state on terminate, bound per-capture …
MelbourneDeveloper Nov 18, 2026
0db8a04
Profiler UI dispose releases the processes tree view and provider [ME…
MelbourneDeveloper Nov 18, 2026
7c7aa2c
Pin that the .NET forwarder ends with a dropped session [MEM-060-DOTN…
MelbourneDeveloper Nov 18, 2026
30cfe89
Add an RAII diagnostics sink registration [MEM-060-DIAGNOSTICS-SINK]
MelbourneDeveloper Nov 18, 2026
45b5392
Profiler UI file log sink: dispose closes it and two capped files bou…
MelbourneDeveloper Nov 18, 2026
4e90de9
Keep only the newest profiler artifacts of each kind on disk [MEM-060…
MelbourneDeveloper Nov 18, 2026
b823179
Document the v0.6.0 leak fixes: plan, spec bounds, changelog
MelbourneDeveloper Nov 18, 2026
ec0dd19
Cite profiler spec headings for the profiler-side lifetime fixes; add…
MelbourneDeveloper Nov 18, 2026
0b9ca60
Parse cache eviction without unreachable branches, restoring the tree…
MelbourneDeveloper Nov 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/lsp-profiler-dotnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ tracing.workspace = true

[dev-dependencies]
tempfile.workspace = true
tokio = { workspace = true, features = ["test-util"] }
17 changes: 17 additions & 0 deletions crates/lsp-profiler-dotnet/src/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,4 +369,21 @@ mod tests {
);
assert_eq!(other, SamplerError::AttachFailed("boom".to_owned()));
}

/// Virtual time a dropped session may take to release its engine.
const ABANDON_BOUND: Duration = Duration::from_secs(60);

/// [PROF-DOTNET-CPU] The forwarder is spawned unowned, so it must
/// end with its consumer: a session dropped without `stop` (a dropped
/// service, an aborted request) signals stop from `SamplerHandle::drop`.
#[tokio::test(start_paused = true)]
async fn a_dropped_session_ends_the_wait_for_stop() -> Result<(), String> {
let parts = SamplerHandle::channel(42, String::new(), FINISH_TIMEOUT);
drop(parts.handle);
tokio::time::timeout(ABANDON_BOUND, wait_for_stop(&parts.sink, None))
.await
.map_err(|_elapsed| {
"the forwarder keeps the engine sampling for a session that was dropped".to_owned()
})
}
}
56 changes: 56 additions & 0 deletions crates/lsp-profiler/src/export/artifact_retention_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! [PROF-EXPORT]: a server that profiles for days writes a heap profile
//! per snapshot and three CPU artifacts per recording. The output directory
//! must keep only the newest of each kind.

use std::path::Path;

use super::{artifact_path, write_artifact, MAX_ARTIFACTS_PER_KIND};

/// Artifacts written: well past the bound.
const WRITTEN: usize = MAX_ARTIFACTS_PER_KIND + 16;
/// An artifact kind.
const KIND: &str = "heapprofile";
/// A file the profiler did not write.
const FOREIGN: &str = "notes.heapprofile";

/// Profiler artifacts of `kind` in `dir`.
fn artifacts(dir: &Path, kind: &str) -> Result<Vec<String>, String> {
let mut names = Vec::new();
for entry in std::fs::read_dir(dir).map_err(|error| error.to_string())? {
let path = entry.map_err(|error| error.to_string())?.path();
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned());
if path.extension().is_some_and(|ext| ext == kind) {
names.extend(name);
}
}
Ok(names)
}

#[test]
fn the_output_directory_keeps_only_the_newest_artifacts_of_each_kind() -> Result<(), String> {
let dir = tempfile::tempdir().map_err(|error| error.to_string())?;
std::fs::write(dir.path().join(FOREIGN), b"user file").map_err(|error| error.to_string())?;
for index in 0..WRITTEN {
let _written = write_artifact(
&artifact_path(dir.path(), &format!("snap-{index:04}"), KIND),
b"{}",
)?;
}
let kept = artifacts(dir.path(), KIND)?;
if kept.len() > MAX_ARTIFACTS_PER_KIND + 1 {
return Err(format!(
"{} {KIND} files kept for a bound of {MAX_ARTIFACTS_PER_KIND}",
kept.len()
));
}
let newest = format!("lsp-profiler-snap-{:04}.{KIND}", WRITTEN - 1);
if !kept.contains(&newest) {
return Err(format!("the newest artifact {newest} was removed"));
}
if !kept.iter().any(|name| name == FOREIGN) {
return Err("a file the profiler did not write was removed".to_owned());
}
Ok(())
}
54 changes: 50 additions & 4 deletions crates/lsp-profiler/src/export/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@ pub mod flamegraph;
pub mod speedscope;

use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::aggregate::{FrameKey, ProfileData};
use crate::wire::ProfileArtifacts;

/// Artifacts of one kind (extension) kept in the output directory; older ones
/// are removed as new ones are written. [PROF-EXPORT]
pub const MAX_ARTIFACTS_PER_KIND: usize = 32;

/// Identity of the profile being exported.
#[derive(Debug, Clone, PartialEq)]
pub struct ExportMeta<'a> {
Expand Down Expand Up @@ -59,21 +64,58 @@ pub fn export_artifacts(
}
}

/// File-name prefix of every artifact the profiler writes.
pub const ARTIFACT_PREFIX: &str = "lsp-profiler-";

/// Path of one artifact: `lsp-profiler-<session>.<extension>`.
#[must_use]
pub fn artifact_path(output_dir: &Path, session_id: &str, extension: &str) -> PathBuf {
output_dir.join(format!("lsp-profiler-{session_id}.{extension}"))
output_dir.join(format!("{ARTIFACT_PREFIX}{session_id}.{extension}"))
}

/// Write `contents` to `path`, naming the path in any error.
/// Write `contents` to `path`, naming the path in any error, then remove the
/// oldest artifacts of its kind beyond [`MAX_ARTIFACTS_PER_KIND`].
///
/// # Errors
///
/// Returns a message when the write fails.
pub fn write_artifact(path: &Path, contents: &[u8]) -> Result<PathBuf, String> {
std::fs::write(path, contents)
.map(|()| path.to_path_buf())
.map_err(|err| format!("Failed to write {}: {err}", path.display()))
.map_err(|err| format!("Failed to write {}: {err}", path.display()))?;
prune_kind(path);
Ok(path.to_path_buf())
}

/// Remove the oldest profiler artifacts sharing `written`'s extension beyond
/// [`MAX_ARTIFACTS_PER_KIND`]; files the profiler did not write stay.
/// [PROF-EXPORT]
fn prune_kind(written: &Path) {
let (Some(dir), Some(kind)) = (written.parent(), written.extension()) else {
return;
};
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let mut artifacts: Vec<(SystemTime, PathBuf)> = entries
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension() == Some(kind) && is_artifact(path))
.filter_map(|path| Some((std::fs::metadata(&path).ok()?.modified().ok()?, path)))
.collect();
artifacts.sort();
let excess = artifacts.len().saturating_sub(MAX_ARTIFACTS_PER_KIND);
for (_, stale) in artifacts.into_iter().take(excess) {
if let Err(error) = std::fs::remove_file(&stale) {
tracing::debug!(%error, "cannot remove an old profiler artifact");
}
}
}

/// Whether `path` names a file the profiler wrote.
fn is_artifact(path: &Path) -> bool {
path.file_name()
.and_then(std::ffi::OsStr::to_str)
.is_some_and(|name| name.starts_with(ARTIFACT_PREFIX))
}

/// Human-readable label of a frame: `name (file:line)` when located.
Expand Down Expand Up @@ -183,6 +225,10 @@ pub(crate) mod test_data {
}
}

#[cfg(test)]
#[path = "artifact_retention_tests.rs"]
mod artifact_retention_tests;

#[cfg(test)]
mod tests {
use super::test_data::{meta, sample_data};
Expand Down
2 changes: 1 addition & 1 deletion crates/lsp-profiler/src/memory/heapprofile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub fn build(snapshot: &HeapSnapshot) -> Value {
pub fn export(snapshot: &HeapSnapshot, output_dir: &Path) -> Result<std::path::PathBuf, String> {
let json = serde_json::to_string(&build(snapshot))
.map_err(|err| format!("Failed to serialize heapprofile: {err}"))?;
let path = output_dir.join(format!("lsp-profiler-{}.heapprofile", snapshot.snapshot_id));
let path = crate::export::artifact_path(output_dir, &snapshot.snapshot_id, "heapprofile");
crate::export::write_artifact(&path, json.as_bytes())
}

Expand Down
49 changes: 39 additions & 10 deletions crates/lsp-profiler/src/memory/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ use crate::diagnostics::DiagnosticStyle;
use crate::runtime::{MemoryContext, Runtime};
use crate::wire::{FileDiagnostics, HeapDiff, HeapSnapshot, MemoryOutcome, MemoryResult};

#[cfg(test)]
#[path = "session_lifetime_tests.rs"]
mod lifetime_tests;

/// Sessions kept at once; the oldest is evicted beyond this.
const MAX_SESSIONS: usize = 32;
/// Allocation sites per snapshot when the request does not say.
Expand Down Expand Up @@ -115,9 +119,12 @@ impl MemorySessionManager {
snapshot_count: 0,
gate: StepGate::new(),
};
let mut sessions = self.sessions.lock().await;
let _ = sessions.insert(context.session_id.clone(), session);
evict_oldest(&mut sessions);
let evicted = {
let mut sessions = self.sessions.lock().await;
let _ = sessions.insert(context.session_id.clone(), session);
evict_oldest(&mut sessions)
};
release(evicted).await;
context
}

Expand Down Expand Up @@ -181,6 +188,13 @@ impl MemorySessionManager {
let _ = self.sessions.lock().await.remove(session_id);
}

/// Close every session and stop each in its backend. Call on shutdown.
pub async fn stop_all(&self) {
let drained: Vec<MemorySession> =
self.sessions.lock().await.drain().map(|(_, s)| s).collect();
release(drained).await;
}

/// Parse evaluated courier output with the session's runtime, then score it.
///
/// # Errors
Expand Down Expand Up @@ -293,18 +307,33 @@ impl MemorySession {
}
}

/// Evict the oldest sessions beyond [`MAX_SESSIONS`].
fn evict_oldest(sessions: &mut HashMap<String, MemorySession>) {
/// Remove the oldest sessions beyond [`MAX_SESSIONS`]; returns them so their
/// backends can be stopped once the map lock is released.
fn evict_oldest(sessions: &mut HashMap<String, MemorySession>) -> Vec<MemorySession> {
let mut evicted = Vec::new();
while sessions.len() > MAX_SESSIONS {
let oldest = sessions
.values()
.min_by_key(|s| s.started_at)
.map(|s| s.context.session_id.clone());
match oldest {
Some(id) => {
let _ = sessions.remove(&id);
}
None => return,
match oldest.and_then(|id| sessions.remove(&id)) {
Some(session) => evicted.push(session),
None => break,
}
}
evicted
}

/// Stop sessions that left the manager without a `memory/stop`, so their
/// backends release per-session state ([PROF-MEMORY-SESSION]).
async fn release(sessions: Vec<MemorySession>) {
for session in sessions {
let id = &session.context.session_id;
let Some(backend) = session.runtime.memory() else {
continue;
};
if let Err(error) = backend.stop(&session.context).await {
tracing::warn!(session_id = %id, %error, "cannot stop an evicted memory session");
}
}
}
Loading
Loading