diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 59af4d58..ac34d354 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -658,6 +658,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "Lithe", }, + EventMetadata { + id: "lsp.indexing.exclusions_failed", + channel: "lsp/{server}", + level: LogLevel::Warn, + message: "Language server indexing exclusions could not be published for server {server}", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None }, + FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose workspace exclusions could not be published", reason: None }, + ], + span: None, + rate: 120, + owner: "lithe-core", + }, EventMetadata { id: "lsp.message.detail.logged", channel: "lsp/{server}", @@ -926,6 +939,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 1, owner: "lithe-core", }, + EventMetadata { + id: "plugins.host.indexing.exclusions_failed", + channel: "plugins/{plugin}/host", + level: LogLevel::Warn, + message: "Engine indexing exclusions could not be published for server {plugin}", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity assigned by Core to this engine session", reason: None }, + ], + span: None, + rate: 120, + owner: "lithe-core", + }, EventMetadata { id: "plugins.host.message.detail.logged", channel: "plugins/{plugin}/host", @@ -1565,6 +1591,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "vcs.indexing.exclusions_failed", + channel: "vcs/{provider}", + level: LogLevel::Warn, + message: "Engine indexing exclusions could not be published for server {provider}", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None }, + FieldMetadata { name: "provider", field_type: FieldType::Id, required: true, description: "Validated provider identity assigned by Core to this engine session", reason: None }, + ], + span: None, + rate: 120, + owner: "lithe-core", + }, EventMetadata { id: "vcs.message.detail.logged", channel: "vcs/{provider}", diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index d0cd599c..3ed5ede7 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -114,13 +114,18 @@ impl LspEngine { "The plugin's language server does not support remote workspaces", )); } - // Initial provider settings must include native Git decisions even when - // no session or inventory warm-up has run. Never scan under registry locks. + // Resolving native Git decisions walks the whole workspace, which can take + // minutes on a large multi-repository tree and used to outlast the host's + // start deadline before the process was even launched. The start only + // reads the live context; unresolved decisions are resolved after the + // launch by `publish_pending_exclusions`, which pushes them to the + // session through the same path as any later indexing change. Never scan + // under registry locks. let indexing_root = canonical_workspace_path(&request.root_uri); - let indexing_context = if let Some(root) = &indexing_root { - lithe_project::indexing::prepare_provider_exclusions(root)? + let (indexing_context, exclusions_pending) = if let Some(root) = &indexing_root { + lithe_project::indexing::provider_context_without_scan(root)? } else { - None + (None, false) }; let check_indexing = || { if let Some(context) = &indexing_context { @@ -324,6 +329,12 @@ impl LspEngine { return Err(error); } + if exclusions_pending { + if let Some(root) = indexing_root.clone() { + publish_pending_exclusions(root, Arc::clone(&self.sessions), &session); + } + } + Ok(StartServerResponse { channel: session.log_identity.channel(), session_id, @@ -412,3 +423,150 @@ fn startup_attempt(request: &StartServerRequest) -> AttemptSlot { _ => Attempt::none(), } } + +/// Resolves the workspace's native Git decisions off the start path and pushes +/// them to every running session of that workspace. +/// +/// `start_server_attempt` launches the process without waiting for the full +/// workspace walk. Until this finishes, a server that pulls +/// `workspace/configuration` sees only the exclusions known at start; the +/// update below then re-sends the configuration exactly like a later indexing +/// change, so the server narrows its import scope instead of missing it. During +/// the walk the thread holds no session, only a weak reference to the started +/// one, which is used to record a failure in that session's log channel. +fn publish_pending_exclusions( + root: PathBuf, + sessions: Arc>>>, + started: &Arc, +) { + let started = Arc::downgrade(started); + thread::spawn(move || { + #[cfg(test)] + deferred_exclusions::wait_while_held(&root); + // Walk before listing the sessions: the walk can take minutes, and a + // list taken first would keep sessions stopped meanwhile alive for that + // long and leave out the ones started meanwhile. + let result = lithe_project::indexing::prepare_provider_exclusions(&root) + .and_then(|_| { + sessions + .lock() + .map_err(|_| { + CoreError::new(ErrorCode::Unknown, "LSP registry lock was poisoned") + }) + .map(|registry| registry.values().cloned().collect::>()) + }) + .and_then(|running| apply_indexing_to_sessions(&root, running)); + #[cfg(test)] + deferred_exclusions::finish(&root); + let Err(error) = result else { + return; + }; + // log-exempt: User cancellation: a closed workspace or a replaced indexing policy retires the context, and the replacement publishes its own decisions. + if matches!(error.code, ErrorCode::Cancelled) { + return; + } + if let Some(session) = started.upgrade() { + session.log( + "warn", + EngineLog::ExclusionsFailed, + "Indexing exclusions could not be published to the language server", + Some(core_error_detail(&error)), + ); + } + }); +} + +/// Test seam that fixes the order between a start and its deferred Git walk. +/// +/// A test holds a workspace before starting a server, observes the start +/// return while the decisions are still unresolved, then releases the walk and +/// waits for the publisher to finish. Roots no test holds pass straight +/// through, so concurrent tests are unaffected. Every wait is bounded, so a +/// failed assertion cannot leave a publisher thread blocked. +#[cfg(test)] +pub(crate) mod deferred_exclusions { + use std::path::{Path, PathBuf}; + use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; + use std::time::Duration; + + /// Where a held workspace is: its walk waits, the test has released it, or + /// its publisher has finished. + #[derive(Clone, Copy, PartialEq)] + enum Stage { + Held, + Released, + Finished, + } + + /// Workspaces a test is watching; roots not listed are never held. + static ROOTS: Mutex> = Mutex::new(Vec::new()); + static CHANGED: Condvar = Condvar::new(); + const LIMIT: Duration = Duration::from_secs(5); + + fn roots() -> MutexGuard<'static, Vec<(PathBuf, Stage)>> { + ROOTS.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn stage(roots: &[(PathBuf, Stage)], root: &Path) -> Option { + roots + .iter() + .find(|(watched, _)| watched == root) + .map(|(_, stage)| *stage) + } + + fn advance(root: &Path, from: Stage, to: Stage) { + let mut roots = roots(); + if let Some(entry) = roots + .iter_mut() + .find(|(watched, stage)| watched == root && *stage == from) + { + entry.1 = to; + } + CHANGED.notify_all(); + } + + /// Holds the walk of the workspace at `root_uri` until the returned guard + /// releases it or is dropped. + pub(crate) fn hold(root_uri: &str) -> Held { + let root = super::canonical_workspace_path(root_uri).expect("the workspace exists"); + let mut roots = roots(); + roots.retain(|(watched, _)| *watched != root); + roots.push((root.clone(), Stage::Held)); + Held(root) + } + + pub(crate) struct Held(PathBuf); + + impl Held { + /// Releases the walk and waits until its publisher has finished; + /// false when that took longer than the limit. + pub(crate) fn release_and_wait(&self) -> bool { + advance(&self.0, Stage::Held, Stage::Released); + let (_roots, wait) = CHANGED + .wait_timeout_while(roots(), LIMIT, |roots| { + stage(roots, &self.0) != Some(Stage::Finished) + }) + .unwrap_or_else(PoisonError::into_inner); + !wait.timed_out() + } + } + + impl Drop for Held { + fn drop(&mut self) { + roots().retain(|(watched, _)| *watched != self.0); + CHANGED.notify_all(); + } + } + + pub(super) fn wait_while_held(root: &Path) { + let _released = CHANGED + .wait_timeout_while(roots(), LIMIT, |roots| { + stage(roots, root) == Some(Stage::Held) + }) + .unwrap_or_else(PoisonError::into_inner); + } + + pub(super) fn finish(root: &Path) { + advance(root, Stage::Released, Stage::Finished); + } +} diff --git a/rust/crates/lsp-engine/src/logging.rs b/rust/crates/lsp-engine/src/logging.rs index 9d4dca31..75a06e13 100644 --- a/rust/crates/lsp-engine/src/logging.rs +++ b/rust/crates/lsp-engine/src/logging.rs @@ -135,6 +135,9 @@ pub(super) enum EngineLog { ShutdownTimedOut, StderrReceived, StderrReadFailed, + /// Resolving or publishing the workspace's Git exclusions after a start + /// failed; the server keeps the exclusions it was started with. + ExclusionsFailed, MessageLogged, MessageShown, TraceReceived, @@ -189,6 +192,7 @@ impl EngineLog { Self::ShutdownTimedOut => "shutdown.timed_out", Self::StderrReceived => "stderr.received", Self::StderrReadFailed => "stderr.read_failed", + Self::ExclusionsFailed => "indexing.exclusions_failed", Self::MessageLogged => "message.logged", Self::MessageShown => "message.shown", Self::TraceReceived => "trace.received", @@ -218,7 +222,9 @@ impl EngineLog { ); copy(&mut fields, "truncated", input, "truncated"); } - Self::ProcessCleanupFailed | Self::StderrReadFailed => failure(&mut fields, code), + Self::ProcessCleanupFailed | Self::StderrReadFailed | Self::ExclusionsFailed => { + failure(&mut fields, code) + } Self::MessageLogged | Self::MessageShown => { copy(&mut fields, "diagnostic", input, "diagnostic"); copy(&mut fields, "severity", input, "severity"); @@ -594,6 +600,7 @@ mod tests { EngineLog::NotificationReceived, EngineLog::ProcessStarted, EngineLog::ProcessCleanupFailed, + EngineLog::ExclusionsFailed, EngineLog::ProtocolInitialized, EngineLog::ResponseSkipped, EngineLog::ShutdownTimedOut, diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index 320492f6..e5f9a5c6 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -1706,6 +1706,54 @@ fn native_owner_retains_indexing_cancellation_after_registration() { ); } +#[test] +fn startup_launches_before_git_exclusions_resolve_and_publishes_them_afterwards() { + let workspace = TemporaryWorkspace::recursive("indexing-deferred-git-exclusions"); + let root = workspace.root.canonicalize().unwrap(); + let root_uri = url::Url::from_directory_path(&root).unwrap().to_string(); + let status = lithe_project::indexing::configure( + serde_json::from_value(json!({ + "root": root, "manualExcludedDirectories": [], "includedDirectories": [], + "gitIgnoreEnabled": true + })) + .unwrap(), + crate::indexing_changed, + ) + .unwrap(); + let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap(); + assert!(pending, "the fixture starts with unresolved Git decisions"); + // Order under test: the start returns and the server initializes while the + // walk is held, then the walk runs. A start that walks the workspace itself + // resolves the decisions before returning and fails the second assertion. + let walk = crate::engine::deferred_exclusions::hold(&root_uri); + let harness = Harness::start(|request| { + workspace.configure(request); + request.root_uri = root_uri.clone(); + }); + assert!( + notifications(&harness, "initialize").pop().is_some(), + "the server is launched and initialized without waiting for the scan" + ); + let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap(); + assert!(pending, "the start resolved the Git decisions itself"); + assert!( + walk.release_and_wait(), + "the deferred Git walk did not finish within 5 seconds" + ); + let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap(); + assert!( + !pending, + "the background publisher resolves the generation the server started with" + ); + drop(walk); + drop(harness); + let _ = lithe_project::indexing::release(lithe_project::indexing::ReleaseIndexingRequest { + root: root.to_string_lossy().into_owned(), + owner_id: None, + revision: status.revision, + }); +} + #[test] fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions() { let workspace = TemporaryWorkspace::recursive("indexing-released-standalone"); @@ -1743,7 +1791,7 @@ fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions() } #[test] -fn indexing_cold_start_resolves_git_before_provider_initialization() { +fn indexing_cold_start_publishes_git_exclusions_after_provider_launch() { let workspace = TemporaryWorkspace::recursive("indexing-cold-start"); let root = workspace.root.canonicalize().unwrap(); std::fs::create_dir_all(root.join("ignored")).unwrap(); @@ -1789,15 +1837,25 @@ fn indexing_cold_start_resolves_git_before_provider_initialization() { ] { let harness = start(Some(declaration)); assert!(notifications(&harness, "initialize").pop().is_some()); - let value = harness.session().plugin_configuration().unwrap(); - assert_eq!(value["server"]["mode"], "full"); - assert!(value - .pointer(pointer) - .unwrap() - .as_array() - .unwrap() - .iter() - .any(|item| item == entry)); + // A cold start launches first; the Git decisions follow from the + // background publisher, bounded so a lost update fails the test. + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let value = harness.session().plugin_configuration().unwrap(); + assert_eq!(value["server"]["mode"], "full"); + let published = value + .pointer(pointer) + .and_then(Value::as_array) + .is_some_and(|items| items.iter().any(|item| item == entry)); + if published { + break; + } + assert!( + Instant::now() < deadline, + "Git exclusions were not published to {pointer} within 5 seconds" + ); + thread::sleep(Duration::from_millis(10)); + } } let undeclared = start(None); assert_eq!( diff --git a/rust/crates/project/src/indexing.rs b/rust/crates/project/src/indexing.rs index 5ac2a10d..46396159 100644 --- a/rust/crates/project/src/indexing.rs +++ b/rust/crates/project/src/indexing.rs @@ -657,6 +657,23 @@ pub fn prepare_provider_exclusions(root: &Path) -> Result Result<(Option>, bool), CoreError> { + let Some(context) = active_provider_context(root) else { + return Ok((None, false)); + }; + context.check()?; + let pending = + context.policy.git_ignore_enabled && !context.git_resolved.load(Ordering::Acquire); + Ok((Some(context), pending)) +} + fn contains(directory: &str, path: &str) -> bool { relative_path_contains(directory, path, Platform::HOST) } @@ -1933,6 +1950,36 @@ mod tests { assert!(next.check().is_ok()); } + #[test] + fn provider_context_without_scan_reports_pending_git_decisions_without_resolving_them() { + let workspace = Workspace::new(); + assert!(provider_context_without_scan(&workspace.0) + .unwrap() + .0 + .is_none()); + workspace.configure(&[], &[], true); + let (context, pending) = provider_context_without_scan(&workspace.0).unwrap(); + let context = context.unwrap(); + assert!(pending, "Git decisions are unresolved before any scan"); + assert!( + !context.git_resolved.load(Ordering::Acquire), + "the start path must not walk the workspace" + ); + let prepared = prepare_provider_exclusions(&workspace.0).unwrap().unwrap(); + assert_eq!(prepared.revision, context.revision); + let (_, pending) = provider_context_without_scan(&workspace.0).unwrap(); + assert!(!pending, "a resolved generation needs no background scan"); + } + + #[test] + fn provider_context_without_scan_needs_no_scan_when_git_ignore_is_disabled() { + let workspace = Workspace::new(); + workspace.configure(&[], &[], false); + let (context, pending) = provider_context_without_scan(&workspace.0).unwrap(); + assert!(context.is_some()); + assert!(!pending); + } + #[test] fn git_negation_nested_rules_new_directories_and_unicode_are_native() { let workspace = Workspace::new(); diff --git a/rust/logging/events/lsp.json b/rust/logging/events/lsp.json index 2df4c2a3..b99fc94a 100644 --- a/rust/logging/events/lsp.json +++ b/rust/logging/events/lsp.json @@ -164,6 +164,26 @@ "rate": 120, "owner": "lithe-core" }, + { + "id": "lsp.indexing.exclusions_failed", + "channel": "lsp/{server}", + "level": "warn", + "message": "Language server indexing exclusions could not be published for server {server}", + "fields": { + "error": { + "type": "error", + "required": true, + "description": "Failure resolving or publishing the workspace Git exclusions after the server started" + }, + "server": { + "type": "id", + "required": true, + "description": "Validated language server session id whose workspace exclusions could not be published" + } + }, + "rate": 120, + "owner": "lithe-core" + }, { "id": "lsp.stderr.received", "channel": "lsp/{server}", diff --git a/rust/logging/events/plugins.json b/rust/logging/events/plugins.json index 883625c2..a15b3743 100644 --- a/rust/logging/events/plugins.json +++ b/rust/logging/events/plugins.json @@ -48,6 +48,26 @@ "rate": 120, "owner": "lithe-core" }, + { + "id": "plugins.host.indexing.exclusions_failed", + "channel": "plugins/{plugin}/host", + "level": "warn", + "message": "Engine indexing exclusions could not be published for server {plugin}", + "fields": { + "error": { + "type": "error", + "required": true, + "description": "Failure resolving or publishing the workspace Git exclusions after the server started" + }, + "plugin": { + "type": "id", + "required": true, + "description": "Validated plugin identity assigned by Core to this engine session" + } + }, + "rate": 120, + "owner": "lithe-core" + }, { "id": "plugins.host.message.logged", "channel": "plugins/{plugin}/host", diff --git a/rust/logging/events/vcs.json b/rust/logging/events/vcs.json index ac4e2ca4..ad3e6c91 100644 --- a/rust/logging/events/vcs.json +++ b/rust/logging/events/vcs.json @@ -68,6 +68,26 @@ "rate": 120, "owner": "lithe-core" }, + { + "id": "vcs.indexing.exclusions_failed", + "channel": "vcs/{provider}", + "level": "warn", + "message": "Engine indexing exclusions could not be published for server {provider}", + "fields": { + "error": { + "type": "error", + "required": true, + "description": "Failure resolving or publishing the workspace Git exclusions after the server started" + }, + "provider": { + "type": "id", + "required": true, + "description": "Validated provider identity assigned by Core to this engine session" + } + }, + "rate": 120, + "owner": "lithe-core" + }, { "id": "vcs.message.logged", "channel": "vcs/{provider}",