Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
39 changes: 39 additions & 0 deletions rust/crates/diagnostics/src/catalog_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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}",
Expand Down
168 changes: 163 additions & 5 deletions rust/crates/lsp-engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Mutex<BTreeMap<String, Arc<RuntimeSession>>>>,
started: &Arc<RuntimeSession>,
) {
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::<Vec<_>>())
})
.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<Vec<(PathBuf, Stage)>> = 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<Stage> {
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);
}
}
9 changes: 8 additions & 1 deletion rust/crates/lsp-engine/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -594,6 +600,7 @@ mod tests {
EngineLog::NotificationReceived,
EngineLog::ProcessStarted,
EngineLog::ProcessCleanupFailed,
EngineLog::ExclusionsFailed,
EngineLog::ProtocolInitialized,
EngineLog::ResponseSkipped,
EngineLog::ShutdownTimedOut,
Expand Down
78 changes: 68 additions & 10 deletions rust/crates/lsp-engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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!(
Expand Down
Loading
Loading