From 7f7ca702d32533546c5f926560ff02f4127ee527 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 08:34:59 +0800 Subject: [PATCH] =?UTF-8?q?fix(workspace):=20=E8=BF=9C=E7=A8=8B=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E7=BB=93=E6=9D=9F=E6=97=B6=E9=87=8A=E6=94=BE=E5=AE=83?= =?UTF-8?q?=E5=BB=BA=E7=AB=8B=E7=9A=84=E6=90=9C=E7=B4=A2=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=20(1lck/Lithe-IDEA#2277)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit workspace 新增会话结束钩子(on_session_end / is_registered),remote.disconnect、 断线后遗忘会话和 remote.closeAll 都会运行;project 的搜索索引键带上会话, 缓存初始化时登记钩子,会话结束即删掉该会话的全部索引。仍持有旧会话的请求 先插入槽位再检查会话是否还在,不会在会话结束后留下新条目。 --- rust/contracts/rust-core-api.md | 8 ++- rust/crates/core/src/tests/remote_sessions.rs | 70 +++++++++++++++++-- rust/crates/project/Cargo.toml | 3 +- rust/crates/project/src/lib.rs | 2 + rust/crates/project/src/search_index.rs | 43 +++++++++++- rust/crates/workspace/src/scope.rs | 6 +- rust/crates/workspace/src/sessions.rs | 66 +++++++++++++++-- rust/crates/workspace/src/test_support.rs | 28 +++++++- 8 files changed, 206 insertions(+), 20 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6efe44d8..5245aed4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -6099,7 +6099,13 @@ ends with its programs once the server's idle timeout (ten minutes) passes without a client; one whose programs were kept lasts until they end. `remote.closeAll` (no payload, returning `{ closed }` with the number of connections) ends all of them; the host calls it while quitting because exiting without it can leave the OpenSSH tree and -the remote server running. Requests over it take `sessionId`: +the remote server running. Every session id is new, so when a connection +leaves Core — through `remote.disconnect`, `remote.closeAll`, or a broken link +that makes a request return `connection_closed` — Core also drops the search +indexes built through it, including one a request that still held the +session was building; the client does not call +`workspace.searchIndex.invalidate` for them, and cannot once the session is +gone. Requests over it take `sessionId`: | Command | Request | Result | | --- | --- | --- | diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 24dfcc9f..9dcf62b2 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -307,11 +307,8 @@ fn remote_build_detects_a_root_opened_through_a_host_symbolic_link() { impl Drop for HostFixture { fn drop(&mut self) { - let _ = crate::execute_json(&json!({ - "id": test_support::unique_id(), "command": "workspace.searchIndex.invalidate", "timeoutMilliseconds": 1_000, - "remoteWorkspace": {"sessionId": self.id, "localRoot": self.root.join("placeholder"), "remoteRoot": self.root.join("host")}, - "payload": {"root": self.root.join("placeholder")} - }).to_string()); + // Unregistering runs the session-end hooks, which drop the search + // indexes the session built. test_support::unregister(&self.id); let _ = self.socket.shutdown(Shutdown::Both); if self.done.recv_timeout(STEP + STEP).is_ok() { @@ -465,6 +462,69 @@ fn remote_search_reads_host_content_and_applies_incremental_updates_without_loca assert_eq!(local["ok"], true, "{local}"); } +// Every session ends with a new id, so indexes keyed by an ended session can +// never be reached again and must not stay cached (1lck/Lithe-IDEA#2277). +#[test] +fn ending_a_remote_session_releases_its_search_indexes() { + let search = |host: &HostFixture| { + std::fs::write(host.root.join("host/Indexed.txt"), "IndexedWord\n").unwrap(); + host.call("workspace.searchEverywhere", json!({"query": "Indexed"})); + host.call("workspace.search", json!({"query": "IndexedWord"})); + assert!(lithe_project::cached_indexes_for_session(&host.id) > 0); + }; + + // `remote.disconnect` releases the indexes of the session it closes. + let closed = HostFixture::new(); + search(&closed); + let disconnected: Value = serde_json::from_str(&crate::execute_json( + &json!({ + "id": test_support::unique_id(), "command": "remote.disconnect", + "payload": {"sessionId": closed.id, "programs": "end"} + }) + .to_string(), + )) + .unwrap(); + assert_eq!(disconnected["ok"], true, "{disconnected}"); + assert_eq!(lithe_project::cached_indexes_for_session(&closed.id), 0); + + // A request that already held the host when the session ended still + // builds its index, but must not leave it cached. + let racing = HostFixture::new(); + search(&racing); + let held = { + let workspace: lithe_workspace::Workspace = serde_json::from_value(json!({ + "sessionId": racing.id, + "localRoot": racing.root.join("placeholder"), + "remoteRoot": racing.root.join("host"), + })) + .unwrap(); + let _scope = lithe_workspace::Scope::begin(Some(workspace)).unwrap(); + lithe_workspace::current().unwrap() + }; + let link = test_support::forget_keeping_link(&racing.id); + assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0); + let found = { + let _scope = lithe_workspace::enter(Some(held)); + lithe_project::search( + serde_json::from_value(json!({ + "root": racing.root.join("placeholder"), + "query": "IndexedWord", + })) + .unwrap(), + ) + .unwrap() + }; + assert!( + found + .matches + .iter() + .any(|item| item.kind == "content" && item.path == "Indexed.txt"), + "the held host must still search the host" + ); + assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0); + drop(link); +} + #[test] fn real_remote_git_status_stage_commit_and_history_never_touch_the_placeholder() { let host = HostFixture::new(); diff --git a/rust/crates/project/Cargo.toml b/rust/crates/project/Cargo.toml index 870ce107..b31dd72c 100644 --- a/rust/crates/project/Cargo.toml +++ b/rust/crates/project/Cargo.toml @@ -6,7 +6,8 @@ license = "Apache-2.0" description = "Project services for Lithe: workspace files, indexing policy, search, local history, document rendering and Markdown outlines" [features] -# Lets lithe-core's tests trace which directories a workspace scan enumerates. +# Lets lithe-core's tests trace which directories a workspace scan enumerates and count +# the search indexes a remote session still holds. test-support = [] [dependencies] diff --git a/rust/crates/project/src/lib.rs b/rust/crates/project/src/lib.rs index bc05b6ae..eaeb4817 100644 --- a/rust/crates/project/src/lib.rs +++ b/rust/crates/project/src/lib.rs @@ -36,6 +36,8 @@ pub use html_preview::*; pub use markdown::*; pub use markdown_outline::*; pub use markdown_reference::*; +#[cfg(feature = "test-support")] +pub use search_index::cached_indexes_for_session; pub use search_paging::{project_search_page, search_page, SearchPageRequest}; pub use search_preferences::*; diff --git a/rust/crates/project/src/search_index.rs b/rust/crates/project/src/search_index.rs index 258dfd7b..24fe9714 100644 --- a/rust/crates/project/src/search_index.rs +++ b/rust/crates/project/src/search_index.rs @@ -51,6 +51,8 @@ pub(crate) struct SearchIndexStats { struct IndexKey { root: PathBuf, host: PathBuf, + /// The remote session the index reads through; `None` for this machine. + session: Option, hidden_directories: Vec, hidden_file_patterns: Vec, names_only: bool, @@ -70,13 +72,29 @@ type IndexSlot = Arc>>; static INDEX_CACHE: OnceLock>> = OnceLock::new(); fn cache() -> &'static std::sync::Mutex> { - INDEX_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())) + INDEX_CACHE.get_or_init(|| { + // Every session ends with a new id, so without this a process that + // reconnects or reopens remote workspaces keeps one content index and + // one name index per session until it exits (1lck/Lithe-IDEA#2277). + workspace::sessions::on_session_end(release_session); + std::sync::Mutex::new(HashMap::new()) + }) +} + +/// Drops every index built through `session`, including in-flight builds, +/// which can then no longer publish into the cache. +fn release_session(session: &str) { + let Ok(mut indexes) = cache().lock() else { + return; + }; + indexes.retain(|key, _| key.session.as_deref() != Some(session)); } fn key(root: &Path, rules: &VisibilityRules) -> IndexKey { IndexKey { root: root.to_path_buf(), host: workspace::identity_key(root), + session: workspace::current().map(|host| host.session_id().to_owned()), hidden_directories: rules.hidden_directories.clone(), hidden_file_patterns: rules.hidden_file_patterns.clone(), names_only: false, @@ -120,10 +138,11 @@ fn get_index( rules: &VisibilityRules, names_only: bool, ) -> Result { + let mut cache_key = key(root, rules); + cache_key.names_only = names_only; + let session = cache_key.session.clone(); let slot = { let mut indexes = cache().lock().map_err(|_| index_lock_error())?; - let mut cache_key = key(root, rules); - cache_key.names_only = names_only; // Keep one visibility variant per workspace/source, including in-flight builds. indexes.retain(|existing, _| { existing.host != cache_key.host @@ -136,6 +155,12 @@ fn get_index( .or_insert_with(|| Arc::new(std::sync::Mutex::new(None))), ) }; + // The session may have ended while this request still held its host. + // Checking after the insert closes the gap: either the check sees the + // session gone, or its end hook runs after the insert and removes it. + if let Some(session) = session.filter(|session| !workspace::sessions::is_registered(session)) { + release_session(&session); + } let mut index = slot.lock().map_err(|_| index_lock_error())?; if let Some(index) = index.as_ref() { return Ok(Arc::clone(index)); @@ -151,6 +176,18 @@ fn index_lock_error() -> CoreError { CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned") } +/// Counts cached indexes, built or still building, that read through +/// `session`, so lithe-core's tests can prove that ending a session releases them. +#[cfg(feature = "test-support")] +pub fn cached_indexes_for_session(session: &str) -> usize { + cache().lock().map_or(0, |indexes| { + indexes + .keys() + .filter(|key| key.session.as_deref() == Some(session)) + .count() + }) +} + pub(crate) fn invalidate_root(root: &Path) { let Ok(mut indexes) = cache().lock() else { return; diff --git a/rust/crates/workspace/src/scope.rs b/rust/crates/workspace/src/scope.rs index 1d777870..0483e38f 100644 --- a/rust/crates/workspace/src/scope.rs +++ b/rust/crates/workspace/src/scope.rs @@ -152,7 +152,9 @@ impl Host { .unwrap_or_else(|| path.to_owned()) } - pub(crate) fn identity(&self) -> &str { + /// The id of the session this host belongs to, which keys process-wide + /// state released through [`crate::sessions::on_session_end`]. + pub fn session_id(&self) -> &str { &self.workspace.session_id } } @@ -221,7 +223,7 @@ pub fn remote_path(path: &Path) -> PathBuf { /// Includes host identity in process-local repository coordination keys. pub fn identity_key(path: &Path) -> PathBuf { current() - .map(|host| PathBuf::from(host.identity()).join(path.strip_prefix("/").unwrap_or(path))) + .map(|host| PathBuf::from(host.session_id()).join(path.strip_prefix("/").unwrap_or(path))) .unwrap_or_else(|| path.to_owned()) } diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 08266f16..3e419276 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -364,14 +364,63 @@ pub(crate) fn lookup(id: &str) -> Result, CoreError> { }) } +/// Releases process-wide state another crate keys by a session id, such as +/// the search indexes `lithe-project` builds over a remote workspace. +pub type SessionEndHook = fn(&str); + +fn session_end_hooks() -> &'static Mutex> { + static HOOKS: OnceLock>> = OnceLock::new(); + HOOKS.get_or_init(Mutex::default) +} + +/// Runs `hook` with the id of every session that leaves the registry from now +/// on: `remote.disconnect`, a broken link that forgets the session, and +/// application exit. Session ids are never reused, so state keyed by an ended +/// id can never be reached again. Registering a hook twice runs it once. +/// +/// A caller that may insert state for a session after the session ended must +/// insert first and then check [`is_registered`]: either the check sees the +/// session gone, or the hook runs after the insert and removes it. +pub fn on_session_end(hook: SessionEndHook) { + let mut hooks = session_end_hooks() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if !hooks + .iter() + .any(|existing| std::ptr::fn_addr_eq(*existing, hook)) + { + hooks.push(hook); + } +} + +/// Whether `id` names a session that is still registered. +pub fn is_registered(id: &str) -> bool { + registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .contains_key(id) +} + +/// Runs the session-end hooks for `id`, which has just left the registry. +pub(crate) fn ended(id: &str) { + let hooks = session_end_hooks() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + for hook in hooks { + hook(id); + } +} + /// Removes a connection whose session ended and closes it in the background, /// so the host reconnects instead of retrying a dead session. pub(crate) fn forget(id: &str) { - if let Some(connection) = registry() + let connection = registry() .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(id) - { + .remove(id); + if let Some(connection) = connection { + ended(id); std::thread::spawn(move || connection.close()); } } @@ -1077,6 +1126,7 @@ pub fn disconnect(request: DisconnectRequest) -> DisconnectResult { let Some(connection) = connection else { return DisconnectResult::default(); }; + ended(&request.session_id); let kept = match request.programs { ProgramsOnClose::End => { connection.close(); @@ -1109,13 +1159,19 @@ pub(crate) fn close_registered() -> usize { /// Drains the owned registry, allowing isolated lifecycle tests without closing /// unrelated sessions concurrently exercising the application registry. pub(crate) fn close_registry(connections: &Mutex>>) -> usize { - let connections: Vec> = connections + let connections: Vec<(String, Arc)> = connections .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .drain() - .map(|(_, connection)| connection) .collect(); let count = connections.len(); + let connections: Vec> = connections + .into_iter() + .map(|(id, connection)| { + ended(&id); + connection + }) + .collect(); let closers: Vec<_> = connections .into_iter() .map(|connection| std::thread::spawn(move || connection.close())) diff --git a/rust/crates/workspace/src/test_support.rs b/rust/crates/workspace/src/test_support.rs index 45eec91a..6197f509 100644 --- a/rust/crates/workspace/src/test_support.rs +++ b/rust/crates/workspace/src/test_support.rs @@ -1,7 +1,7 @@ //! Hooks for `lithe-core`'s end-to-end tests, which drive real Core commands //! against an in-process host server instead of an SSH child. -use crate::sessions::{lookup, nonce, registry, Connection, ConnectionTransport}; +use crate::sessions::{ended, lookup, nonce, registry, Connection, ConnectionTransport}; use lithe_remote::client::trust::Target; use lithe_remote::client::{RemoteSession, TransportChain}; use std::sync::Arc; @@ -32,13 +32,35 @@ pub fn drop_link(id: &str) { lookup(id).unwrap().close(); } -/// Removes the session from the registry and shuts it down. +/// Removes the session from the registry, runs the session-end hooks and +/// shuts it down, as `remote.disconnect` does. pub fn unregister(id: &str) { - if let Some(connection) = registry().lock().unwrap().remove(id) { + let connection = registry().lock().unwrap().remove(id); + if let Some(connection) = connection { + ended(id); connection.close(); } } +/// Removes the session from the registry and runs the session-end hooks but +/// leaves its link open, as a request that already holds the session's host +/// sees when `remote.disconnect` runs at the same time. Dropping the result +/// closes the link. +pub fn forget_keeping_link(id: &str) -> KeptLink { + let connection = registry().lock().unwrap().remove(id).unwrap(); + ended(id); + KeptLink(connection) +} + +/// An unregistered session's link, closed when dropped. +pub struct KeptLink(Arc); + +impl Drop for KeptLink { + fn drop(&mut self) { + self.0.close(); + } +} + /// A fresh unguessable id, the same shape as session ids. pub fn unique_id() -> String { nonce()