Skip to content

Commit a4d71da

Browse files
AACS111zhengfupingclaudexiaoyumuxi
authored
fix(lsp-engine): 启动语言服务器不再等待整个工作区的 Git 忽略规则扫描 (#78)
* fix(lsp-engine): 启动语言服务器不再等待整个工作区的 Git 忽略规则扫描 大型多模块工作区上,start_server_attempt 在拉起进程前同步调用 prepare_provider_exclusions 遍历整个工作区,首次计算会超过桌面端 2 分钟的启动时限,JDT LS 进程根本没有被启动。 现在启动只读取当前索引上下文(provider_context_without_scan), Git 决策尚未解析时先启动进程,再由 publish_pending_exclusions 在 后台线程解析,并经 apply_indexing_to_sessions 推送给会话,与之后 的索引变化走同一路径。后台失败记 *.indexing.exclusions_failed。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(lsp-engine): 后台排除规则先扫描再取会话,回归测试固定启动与扫描的顺序 - publish_pending_exclusions 先完成工作区扫描,再从注册表取会话推送。 原来先取会话列表再扫描:扫描可能持续几分钟,期间一直持有这些会话的强引用, 中途停止的会话要等扫描结束才释放,中途启动的会话也不在列表里。 - 新增仅测试用的 deferred_exclusions 闸门:测试先按住某个工作区的后台扫描, 确认启动返回、服务器已初始化时 Git 决策仍未解析,再放行并有界等待发布完成。 原测试在旧的同步扫描实现上同样通过,不能证明启动不再等扫描;改用闸门后, 把启动路径换回同步扫描时测试失败("the start resolved the Git decisions itself")。 未被按住的工作区直接通过,所有等待都以 5 秒为上限。 --------- Co-authored-by: zhengfuping <fuping.zheng@onmicro.com.cn> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Yao Jingxi <23722032@bjtu.edu.cn>
1 parent 6a29169 commit a4d71da

8 files changed

Lines changed: 385 additions & 16 deletions

File tree

‎rust/crates/diagnostics/src/catalog_generated.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,19 @@ pub static EVENTS: &[EventMetadata] = &[
658658
rate: 60,
659659
owner: "Lithe",
660660
},
661+
EventMetadata {
662+
id: "lsp.indexing.exclusions_failed",
663+
channel: "lsp/{server}",
664+
level: LogLevel::Warn,
665+
message: "Language server indexing exclusions could not be published for server {server}",
666+
fields: &[
667+
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None },
668+
FieldMetadata { name: "server", field_type: FieldType::Id, required: true, description: "Validated language server session id whose workspace exclusions could not be published", reason: None },
669+
],
670+
span: None,
671+
rate: 120,
672+
owner: "lithe-core",
673+
},
661674
EventMetadata {
662675
id: "lsp.message.detail.logged",
663676
channel: "lsp/{server}",
@@ -926,6 +939,19 @@ pub static EVENTS: &[EventMetadata] = &[
926939
rate: 1,
927940
owner: "lithe-core",
928941
},
942+
EventMetadata {
943+
id: "plugins.host.indexing.exclusions_failed",
944+
channel: "plugins/{plugin}/host",
945+
level: LogLevel::Warn,
946+
message: "Engine indexing exclusions could not be published for server {plugin}",
947+
fields: &[
948+
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None },
949+
FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity assigned by Core to this engine session", reason: None },
950+
],
951+
span: None,
952+
rate: 120,
953+
owner: "lithe-core",
954+
},
929955
EventMetadata {
930956
id: "plugins.host.message.detail.logged",
931957
channel: "plugins/{plugin}/host",
@@ -1565,6 +1591,19 @@ pub static EVENTS: &[EventMetadata] = &[
15651591
rate: 60,
15661592
owner: "lithe-core",
15671593
},
1594+
EventMetadata {
1595+
id: "vcs.indexing.exclusions_failed",
1596+
channel: "vcs/{provider}",
1597+
level: LogLevel::Warn,
1598+
message: "Engine indexing exclusions could not be published for server {provider}",
1599+
fields: &[
1600+
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Failure resolving or publishing the workspace Git exclusions after the server started", reason: None },
1601+
FieldMetadata { name: "provider", field_type: FieldType::Id, required: true, description: "Validated provider identity assigned by Core to this engine session", reason: None },
1602+
],
1603+
span: None,
1604+
rate: 120,
1605+
owner: "lithe-core",
1606+
},
15681607
EventMetadata {
15691608
id: "vcs.message.detail.logged",
15701609
channel: "vcs/{provider}",

‎rust/crates/lsp-engine/src/engine.rs‎

Lines changed: 163 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,18 @@ impl LspEngine {
114114
"The plugin's language server does not support remote workspaces",
115115
));
116116
}
117-
// Initial provider settings must include native Git decisions even when
118-
// no session or inventory warm-up has run. Never scan under registry locks.
117+
// Resolving native Git decisions walks the whole workspace, which can take
118+
// minutes on a large multi-repository tree and used to outlast the host's
119+
// start deadline before the process was even launched. The start only
120+
// reads the live context; unresolved decisions are resolved after the
121+
// launch by `publish_pending_exclusions`, which pushes them to the
122+
// session through the same path as any later indexing change. Never scan
123+
// under registry locks.
119124
let indexing_root = canonical_workspace_path(&request.root_uri);
120-
let indexing_context = if let Some(root) = &indexing_root {
121-
lithe_project::indexing::prepare_provider_exclusions(root)?
125+
let (indexing_context, exclusions_pending) = if let Some(root) = &indexing_root {
126+
lithe_project::indexing::provider_context_without_scan(root)?
122127
} else {
123-
None
128+
(None, false)
124129
};
125130
let check_indexing = || {
126131
if let Some(context) = &indexing_context {
@@ -324,6 +329,12 @@ impl LspEngine {
324329
return Err(error);
325330
}
326331

332+
if exclusions_pending {
333+
if let Some(root) = indexing_root.clone() {
334+
publish_pending_exclusions(root, Arc::clone(&self.sessions), &session);
335+
}
336+
}
337+
327338
Ok(StartServerResponse {
328339
channel: session.log_identity.channel(),
329340
session_id,
@@ -412,3 +423,150 @@ fn startup_attempt(request: &StartServerRequest) -> AttemptSlot {
412423
_ => Attempt::none(),
413424
}
414425
}
426+
427+
/// Resolves the workspace's native Git decisions off the start path and pushes
428+
/// them to every running session of that workspace.
429+
///
430+
/// `start_server_attempt` launches the process without waiting for the full
431+
/// workspace walk. Until this finishes, a server that pulls
432+
/// `workspace/configuration` sees only the exclusions known at start; the
433+
/// update below then re-sends the configuration exactly like a later indexing
434+
/// change, so the server narrows its import scope instead of missing it. During
435+
/// the walk the thread holds no session, only a weak reference to the started
436+
/// one, which is used to record a failure in that session's log channel.
437+
fn publish_pending_exclusions(
438+
root: PathBuf,
439+
sessions: Arc<Mutex<BTreeMap<String, Arc<RuntimeSession>>>>,
440+
started: &Arc<RuntimeSession>,
441+
) {
442+
let started = Arc::downgrade(started);
443+
thread::spawn(move || {
444+
#[cfg(test)]
445+
deferred_exclusions::wait_while_held(&root);
446+
// Walk before listing the sessions: the walk can take minutes, and a
447+
// list taken first would keep sessions stopped meanwhile alive for that
448+
// long and leave out the ones started meanwhile.
449+
let result = lithe_project::indexing::prepare_provider_exclusions(&root)
450+
.and_then(|_| {
451+
sessions
452+
.lock()
453+
.map_err(|_| {
454+
CoreError::new(ErrorCode::Unknown, "LSP registry lock was poisoned")
455+
})
456+
.map(|registry| registry.values().cloned().collect::<Vec<_>>())
457+
})
458+
.and_then(|running| apply_indexing_to_sessions(&root, running));
459+
#[cfg(test)]
460+
deferred_exclusions::finish(&root);
461+
let Err(error) = result else {
462+
return;
463+
};
464+
// log-exempt: User cancellation: a closed workspace or a replaced indexing policy retires the context, and the replacement publishes its own decisions.
465+
if matches!(error.code, ErrorCode::Cancelled) {
466+
return;
467+
}
468+
if let Some(session) = started.upgrade() {
469+
session.log(
470+
"warn",
471+
EngineLog::ExclusionsFailed,
472+
"Indexing exclusions could not be published to the language server",
473+
Some(core_error_detail(&error)),
474+
);
475+
}
476+
});
477+
}
478+
479+
/// Test seam that fixes the order between a start and its deferred Git walk.
480+
///
481+
/// A test holds a workspace before starting a server, observes the start
482+
/// return while the decisions are still unresolved, then releases the walk and
483+
/// waits for the publisher to finish. Roots no test holds pass straight
484+
/// through, so concurrent tests are unaffected. Every wait is bounded, so a
485+
/// failed assertion cannot leave a publisher thread blocked.
486+
#[cfg(test)]
487+
pub(crate) mod deferred_exclusions {
488+
use std::path::{Path, PathBuf};
489+
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
490+
use std::time::Duration;
491+
492+
/// Where a held workspace is: its walk waits, the test has released it, or
493+
/// its publisher has finished.
494+
#[derive(Clone, Copy, PartialEq)]
495+
enum Stage {
496+
Held,
497+
Released,
498+
Finished,
499+
}
500+
501+
/// Workspaces a test is watching; roots not listed are never held.
502+
static ROOTS: Mutex<Vec<(PathBuf, Stage)>> = Mutex::new(Vec::new());
503+
static CHANGED: Condvar = Condvar::new();
504+
const LIMIT: Duration = Duration::from_secs(5);
505+
506+
fn roots() -> MutexGuard<'static, Vec<(PathBuf, Stage)>> {
507+
ROOTS.lock().unwrap_or_else(PoisonError::into_inner)
508+
}
509+
510+
fn stage(roots: &[(PathBuf, Stage)], root: &Path) -> Option<Stage> {
511+
roots
512+
.iter()
513+
.find(|(watched, _)| watched == root)
514+
.map(|(_, stage)| *stage)
515+
}
516+
517+
fn advance(root: &Path, from: Stage, to: Stage) {
518+
let mut roots = roots();
519+
if let Some(entry) = roots
520+
.iter_mut()
521+
.find(|(watched, stage)| watched == root && *stage == from)
522+
{
523+
entry.1 = to;
524+
}
525+
CHANGED.notify_all();
526+
}
527+
528+
/// Holds the walk of the workspace at `root_uri` until the returned guard
529+
/// releases it or is dropped.
530+
pub(crate) fn hold(root_uri: &str) -> Held {
531+
let root = super::canonical_workspace_path(root_uri).expect("the workspace exists");
532+
let mut roots = roots();
533+
roots.retain(|(watched, _)| *watched != root);
534+
roots.push((root.clone(), Stage::Held));
535+
Held(root)
536+
}
537+
538+
pub(crate) struct Held(PathBuf);
539+
540+
impl Held {
541+
/// Releases the walk and waits until its publisher has finished;
542+
/// false when that took longer than the limit.
543+
pub(crate) fn release_and_wait(&self) -> bool {
544+
advance(&self.0, Stage::Held, Stage::Released);
545+
let (_roots, wait) = CHANGED
546+
.wait_timeout_while(roots(), LIMIT, |roots| {
547+
stage(roots, &self.0) != Some(Stage::Finished)
548+
})
549+
.unwrap_or_else(PoisonError::into_inner);
550+
!wait.timed_out()
551+
}
552+
}
553+
554+
impl Drop for Held {
555+
fn drop(&mut self) {
556+
roots().retain(|(watched, _)| *watched != self.0);
557+
CHANGED.notify_all();
558+
}
559+
}
560+
561+
pub(super) fn wait_while_held(root: &Path) {
562+
let _released = CHANGED
563+
.wait_timeout_while(roots(), LIMIT, |roots| {
564+
stage(roots, root) == Some(Stage::Held)
565+
})
566+
.unwrap_or_else(PoisonError::into_inner);
567+
}
568+
569+
pub(super) fn finish(root: &Path) {
570+
advance(root, Stage::Released, Stage::Finished);
571+
}
572+
}

‎rust/crates/lsp-engine/src/logging.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ pub(super) enum EngineLog {
135135
ShutdownTimedOut,
136136
StderrReceived,
137137
StderrReadFailed,
138+
/// Resolving or publishing the workspace's Git exclusions after a start
139+
/// failed; the server keeps the exclusions it was started with.
140+
ExclusionsFailed,
138141
MessageLogged,
139142
MessageShown,
140143
TraceReceived,
@@ -189,6 +192,7 @@ impl EngineLog {
189192
Self::ShutdownTimedOut => "shutdown.timed_out",
190193
Self::StderrReceived => "stderr.received",
191194
Self::StderrReadFailed => "stderr.read_failed",
195+
Self::ExclusionsFailed => "indexing.exclusions_failed",
192196
Self::MessageLogged => "message.logged",
193197
Self::MessageShown => "message.shown",
194198
Self::TraceReceived => "trace.received",
@@ -218,7 +222,9 @@ impl EngineLog {
218222
);
219223
copy(&mut fields, "truncated", input, "truncated");
220224
}
221-
Self::ProcessCleanupFailed | Self::StderrReadFailed => failure(&mut fields, code),
225+
Self::ProcessCleanupFailed | Self::StderrReadFailed | Self::ExclusionsFailed => {
226+
failure(&mut fields, code)
227+
}
222228
Self::MessageLogged | Self::MessageShown => {
223229
copy(&mut fields, "diagnostic", input, "diagnostic");
224230
copy(&mut fields, "severity", input, "severity");
@@ -594,6 +600,7 @@ mod tests {
594600
EngineLog::NotificationReceived,
595601
EngineLog::ProcessStarted,
596602
EngineLog::ProcessCleanupFailed,
603+
EngineLog::ExclusionsFailed,
597604
EngineLog::ProtocolInitialized,
598605
EngineLog::ResponseSkipped,
599606
EngineLog::ShutdownTimedOut,

‎rust/crates/lsp-engine/src/tests.rs‎

Lines changed: 68 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1706,6 +1706,54 @@ fn native_owner_retains_indexing_cancellation_after_registration() {
17061706
);
17071707
}
17081708

1709+
#[test]
1710+
fn startup_launches_before_git_exclusions_resolve_and_publishes_them_afterwards() {
1711+
let workspace = TemporaryWorkspace::recursive("indexing-deferred-git-exclusions");
1712+
let root = workspace.root.canonicalize().unwrap();
1713+
let root_uri = url::Url::from_directory_path(&root).unwrap().to_string();
1714+
let status = lithe_project::indexing::configure(
1715+
serde_json::from_value(json!({
1716+
"root": root, "manualExcludedDirectories": [], "includedDirectories": [],
1717+
"gitIgnoreEnabled": true
1718+
}))
1719+
.unwrap(),
1720+
crate::indexing_changed,
1721+
)
1722+
.unwrap();
1723+
let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap();
1724+
assert!(pending, "the fixture starts with unresolved Git decisions");
1725+
// Order under test: the start returns and the server initializes while the
1726+
// walk is held, then the walk runs. A start that walks the workspace itself
1727+
// resolves the decisions before returning and fails the second assertion.
1728+
let walk = crate::engine::deferred_exclusions::hold(&root_uri);
1729+
let harness = Harness::start(|request| {
1730+
workspace.configure(request);
1731+
request.root_uri = root_uri.clone();
1732+
});
1733+
assert!(
1734+
notifications(&harness, "initialize").pop().is_some(),
1735+
"the server is launched and initialized without waiting for the scan"
1736+
);
1737+
let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap();
1738+
assert!(pending, "the start resolved the Git decisions itself");
1739+
assert!(
1740+
walk.release_and_wait(),
1741+
"the deferred Git walk did not finish within 5 seconds"
1742+
);
1743+
let (_, pending) = lithe_project::indexing::provider_context_without_scan(&root).unwrap();
1744+
assert!(
1745+
!pending,
1746+
"the background publisher resolves the generation the server started with"
1747+
);
1748+
drop(walk);
1749+
drop(harness);
1750+
let _ = lithe_project::indexing::release(lithe_project::indexing::ReleaseIndexingRequest {
1751+
root: root.to_string_lossy().into_owned(),
1752+
owner_id: None,
1753+
revision: status.revision,
1754+
});
1755+
}
1756+
17091757
#[test]
17101758
fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions() {
17111759
let workspace = TemporaryWorkspace::recursive("indexing-released-standalone");
@@ -1743,7 +1791,7 @@ fn indexing_released_root_allows_a_standalone_provider_without_old_exclusions()
17431791
}
17441792

17451793
#[test]
1746-
fn indexing_cold_start_resolves_git_before_provider_initialization() {
1794+
fn indexing_cold_start_publishes_git_exclusions_after_provider_launch() {
17471795
let workspace = TemporaryWorkspace::recursive("indexing-cold-start");
17481796
let root = workspace.root.canonicalize().unwrap();
17491797
std::fs::create_dir_all(root.join("ignored")).unwrap();
@@ -1789,15 +1837,25 @@ fn indexing_cold_start_resolves_git_before_provider_initialization() {
17891837
] {
17901838
let harness = start(Some(declaration));
17911839
assert!(notifications(&harness, "initialize").pop().is_some());
1792-
let value = harness.session().plugin_configuration().unwrap();
1793-
assert_eq!(value["server"]["mode"], "full");
1794-
assert!(value
1795-
.pointer(pointer)
1796-
.unwrap()
1797-
.as_array()
1798-
.unwrap()
1799-
.iter()
1800-
.any(|item| item == entry));
1840+
// A cold start launches first; the Git decisions follow from the
1841+
// background publisher, bounded so a lost update fails the test.
1842+
let deadline = Instant::now() + Duration::from_secs(5);
1843+
loop {
1844+
let value = harness.session().plugin_configuration().unwrap();
1845+
assert_eq!(value["server"]["mode"], "full");
1846+
let published = value
1847+
.pointer(pointer)
1848+
.and_then(Value::as_array)
1849+
.is_some_and(|items| items.iter().any(|item| item == entry));
1850+
if published {
1851+
break;
1852+
}
1853+
assert!(
1854+
Instant::now() < deadline,
1855+
"Git exclusions were not published to {pointer} within 5 seconds"
1856+
);
1857+
thread::sleep(Duration::from_millis(10));
1858+
}
18011859
}
18021860
let undeclared = start(None);
18031861
assert_eq!(

0 commit comments

Comments
 (0)