Skip to content

fix: refresh workspace match and watch state on reload - #984

Merged
CppCXY merged 2 commits into
EmmyLuaLs:mainfrom
lewis6991:fix/workspacelibfollowup
Mar 13, 2026
Merged

CppCXY merged 2 commits into
EmmyLuaLs:mainfrom
lewis6991:fix/workspacelibfollowup

Conversation

@lewis6991

Copy link
Copy Markdown
Collaborator

Summary

Config reload rebuilt analysis state, but the language server could keep using stale workspace matching state and stale watched-file registrations. In practice, changes to workspace.library, workspace.packageDirs, or workspace.workspaceRoots were not always reflected until restart, removed roots could stay indexed, and external library roots could keep outdated watch coverage.

What changed

  • rebuild the effective workspace folder set from:
    • client workspace roots
    • configured workspaceRoots
    • configured library
    • configured packageDirs
  • refresh workspace matching state whenever config is reloaded
  • re-register watched-file globs after reload
  • rebuild notify watchers for roots outside the editor workspace
  • clear non-stdlib workspaces before reloading files so removed roots drop out of analysis
  • preserve unsaved open-buffer text across reloads when files enter or leave the workspace
  • clear push diagnostics for files removed by reload
  • separate debounced config reloads from reindex requests so a save no longer cancels a pending config reload
  • share the workspace file matcher between emmylua_code_analysis and emmylua_ls to remove duplicated matching logic

Why

Before this change:

  • adding a library or workspace root via config could require a restart before the LS treated those files as workspace files
  • removing a library could leave files indexed and diagnostics uncleared
  • external library roots could keep stale watcher state after reload
  • reindex scheduling could interfere with config reload scheduling
  • unsaved open-file text could be lost across workspace membership changes during reloadnalysis and LS**

@lewis6991
lewis6991 marked this pull request as draft March 11, 2026 10:53
@lewis6991
lewis6991 force-pushed the fix/workspacelibfollowup branch from b2d5970 to fb766ef Compare March 11, 2026 10:54
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the workspace management and file watching capabilities of the language server. The primary goal is to eliminate issues where configuration changes were not fully applied until a restart, leading to stale analysis states and incorrect file indexing. By introducing a centralized file matcher, a more robust reload mechanism with decoupled debounce tasks, and improved open file handling, the language server now provides a more consistent and responsive experience when workspace configurations are updated. This also includes better management of external library roots and dynamic file watcher registration.

Highlights

  • Refactored Workspace Reload Mechanism: Implemented a new, more robust workspace reload mechanism that ensures configuration changes (like workspace.library, workspace.packageDirs, workspace.workspaceRoots) are immediately reflected without requiring a language server restart. This includes clearing stale workspace data and re-registering file watchers.
  • Centralized File Matching Logic: Introduced a dedicated WorkspaceFileMatcher in emmylua_code_analysis to centralize and improve the logic for determining which files belong to the workspace. This matcher is now shared between the code analysis and language server components, reducing duplication and enhancing consistency.
  • Improved Open File Handling: Enhanced the handling of open files to preserve unsaved buffer text across workspace reloads and membership changes. This prevents data loss when files enter or leave the workspace due to configuration updates.
  • Decoupled Debounce Tasks: Separated the debouncing logic for config reloads and reindex requests. This ensures that a file save (triggering a reindex) no longer cancels a pending configuration reload, improving responsiveness and reliability.
  • Dynamic File Watcher Registration: Updated the file watching mechanism to dynamically register and unregister watchers based on client capabilities and the effective workspace roots, including external library roots. This allows for more precise and efficient file change detection.
  • Clear Diagnostics for Removed Files: Added functionality to clear push diagnostics for files that are removed from the workspace during a reload, ensuring that outdated diagnostic messages do not persist.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • crates/emmylua_code_analysis/src/db_index/module/mod.rs
    • Added clear_non_std_workspaces function to remove non-standard workspaces.
  • crates/emmylua_code_analysis/src/lib.rs
    • Added clear_non_std_workspaces to clear non-standard workspaces from the analysis engine.
    • Introduced reload_workspace_files to manage file updates, removals, and reindexing during workspace reloads.
  • crates/emmylua_code_analysis/src/vfs/collect_workspace_files.rs
    • Introduced build_workspace_folders to consolidate logic for constructing workspace folder lists.
    • Defined WorkspaceFileMatcher and WorkspaceMatchEntry structs for centralized file matching.
    • Refactored collect_workspace_files to utilize the new WorkspaceFileMatcher for improved file discovery.
    • Made find_library_exclude public for broader use.
    • Added helper functions build_workspace_file_matcher, build_workspace_matcher_parts, add_child_workspace_excludes, and extend_loaded_files to support the new matcher architecture.
    • Implemented is_match, watch_roots, and source_file_globs methods for WorkspaceFileMatcher.
    • Added new test cases to validate the behavior of the WorkspaceFileMatcher.
  • crates/emmylua_ls/src/context/lsp_features.rs
    • Added supports_dynamic_watched_files_registration method to check client capabilities for dynamic file watcher registration.
  • crates/emmylua_ls/src/context/mod.rs
    • Updated lock ordering comments to reflect new debounce and reload mechanisms.
    • Removed StatusBar dependency from WorkspaceManager constructor.
  • crates/emmylua_ls/src/context/workspace_manager.rs
    • Removed StatusBar from WorkspaceManager constructor.
    • Introduced config_reload_token, reindex_token, reload_lock, and reload_generation for refined debounce and reload management.
    • Replaced match_workspace_folders and current_open_files with open_file_texts and open_file_state_version for open file tracking.
    • Added methods update_match_state, sync_open_file, close_open_file, is_open_file, workspace_open_files, and workspace_open_files_snapshot for managing open file state.
    • Refactored add_update_emmyrc_task, add_reload_workspace_task, extend_reindex_delay, and reindex_workspace to use the new asynchronous and debounced task handling.
    • Replaced ReindexToken with DebounceToken and PendingTask for more flexible task cancellation and debouncing.
    • Refactored load_emmy_config and added extend_config_files for modular configuration loading.
    • Integrated the new WorkspaceFileMatcher from emmylua_code_analysis.
    • Introduced refresh_workspace_diagnostics, ReloadTaskHandles, spawn_workspace_reload_task, reload_workspace_from_emmyrc, sync_reloaded_open_files, apply_open_file_sync, OpenFilesSnapshot, and OpenFileSyncAction for comprehensive workspace reload logic.
  • crates/emmylua_ls/src/context/workspace_manager/tests.rs
    • Added new test file with comprehensive tests for workspace reload, watcher behavior, config reload, and open file state preservation.
  • crates/emmylua_ls/src/handlers/configuration/mod.rs
    • Updated on_did_change_configuration to use the new add_reload_workspace_task signature, passing the server context snapshot.
  • crates/emmylua_ls/src/handlers/initialized/mod.rs
    • Removed WorkspaceFileMatcher import and replaced calculate_include_and_exclude with build_workspace_folders.
    • Removed direct set_match_workspace_folders and match_file_pattern assignments, now handled by update_match_state.
    • Updated init_analysis call to include open_files and removed client_capabilities from register_files_watch.
    • Refactored init_analysis to leverage build_workspace_folders, clear_non_std_workspaces, and reload_workspace_files.
    • Added logic to clear push diagnostics for removed URIs when pull diagnostics are not supported.
  • crates/emmylua_ls/src/handlers/mod.rs
    • Exported register_files_watch for broader access.
  • crates/emmylua_ls/src/handlers/text_document/register_file_watch.rs
    • Introduced constants WATCH_FILES_REGISTRATION_ID, WATCHED_CONFIG_GLOBS, and WATCHED_CONFIG_FILE_NAMES.
    • Refactored register_files_watch to use a WatchRegistrationPlan based on client capabilities and workspace folders.
    • Added build_watch_registration_plan and is_root_covered_by_workspace_folders for intelligent watcher setup.
    • Updated register_files_watch_use_lsp_client to unregister existing watchers and use dynamic globs.
    • Added build_watch_file_globs, lsp_file_watchers, and unregister_files_watch_use_lsp_client.
    • Refactored register_files_watch_use_fsnotify to use specific watch_roots and match_file_pattern, and added is_watched_path, is_config_watch_path, is_path_covered_by_workspace, and reduce_watch_roots for efficient file system watching.
  • crates/emmylua_ls/src/handlers/text_document/text_document_handler.rs
    • Added sync_open_file calls in on_did_open_text_document and on_did_change_text_document to update open file state.
    • Removed direct manipulation of current_open_files set.
    • Updated calls to reindex_workspace and extend_reindex_delay to align with the new API, removing await.
    • Updated on_did_close_document to use close_open_file for consistent open file management.
  • crates/emmylua_ls/src/handlers/text_document/watched_file_handler.rs
    • Updated current_open_files.contains to is_open_file for checking open file status.
    • Modified add_update_emmyrc_task call to pass the server context snapshot and config path.
Activity
  • The pull request introduces significant refactoring and new features to improve workspace management and file watching.
  • No external review comments or activities have been recorded yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a significant and well-executed refactoring to address how the language server handles workspace configuration reloads. The changes ensure that modifications to workspace.library, workspace.packageDirs, and workspace.workspaceRoots are correctly applied without requiring a server restart. Key improvements include separating config reload and re-indexing tasks, preserving unsaved buffer content across reloads, and enhancing the file watching mechanism. The code is more robust and maintainable. I have one suggestion regarding performance in the new file matching logic.

Comment on lines +259 to +293

for entry in &self.entries {
let Ok(relative_path) = path.strip_prefix(&entry.root) else {
continue;
};

if entry.exclude_dir.iter().any(|dir| path.starts_with(dir)) {
continue;
}

if !entry.exclude.is_empty() {
match wax::any(entry.exclude.iter().map(|s| s.as_str())) {
Ok(exclude_set) if wax::Pattern::is_match(&exclude_set, relative_path) => {
continue;
}
Ok(_) => {}
Err(_) => log::error!("Invalid exclude pattern"),
}
}

if wax::Pattern::is_match(&include_set, relative_path) {
return true;
}
}

false
}

pub fn watch_roots(&self) -> HashSet<PathBuf> {
self.watch_roots.clone()
}

pub fn source_file_globs(&self) -> &[String] {
&self.include
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The is_match function re-compiles glob patterns on every call by using wax::any with string slices. This can be inefficient, especially since is_match might be called frequently for file events. To improve performance, consider pre-compiling the glob patterns into wax::Glob<'static> and storing them in WorkspaceFileMatcher and WorkspaceMatchEntry structs. You could then pass references to these compiled globs to wax::any.

For example, you could change the fields in WorkspaceFileMatcher and WorkspaceMatchEntry:

// In WorkspaceFileMatcher
use wax::Glob;

pub struct WorkspaceFileMatcher {
    include: Vec<Glob<'static>>,
    // ...
}

// In WorkspaceMatchEntry
struct WorkspaceMatchEntry {
    // ...
    exclude: Vec<Glob<'static>>,
    // ...
}

You would then need to update the builder functions to perform the compilation once. wax::Glob has an into_owned() method that can be used to create a 'static version from a String.

@lewis6991
lewis6991 force-pushed the fix/workspacelibfollowup branch 2 times, most recently from 0f05387 to 5ac5952 Compare March 11, 2026 12:17
@lewis6991
lewis6991 marked this pull request as ready for review March 11, 2026 13:54
Config reloads were rebuilding analysis state, but the workspace manager
kept using stale match roots and watched-file registrations. After
changing `workspace.library`, `workspace.packageDirs`, or
`workspace.workspaceRoots`, newly added roots were not treated as
workspace files until restart, removed roots could stay indexed, and
external roots could keep stale watcher coverage.

Fix that by rebuilding the effective workspace folder set whenever
config is loaded and using that same resolved view for indexing, file
matching, and watch registration.

This change:
- rebuilds workspace folders from the base workspace roots plus
  configured workspace roots, libraries, and package dirs
- refreshes `WorkspaceFileMatcher` state on reload so membership checks
  track the new config immediately
- re-registers dynamic watched-file globs and recreates notify watchers
  for roots outside the editor workspace
- clears non-stdlib workspaces before reloading files so removed roots
  drop out of analysis
- preserves open-buffer text across reloads so unsaved edits survive
  when a file enters or leaves the workspace
- clears push diagnostics for files removed by a reload
- separates debounced config reloads from reindex requests so saves no
  longer cancel a pending config reload

Add high-level tests covering:
- config reload surviving a concurrent reindex request
- configured workspace roots being loaded after reload
- removed libraries being dropped from analysis and diagnostics
- unsaved open text surviving workspace membership changes
- watcher state being rebuilt for external library roots
@lewis6991
lewis6991 force-pushed the fix/workspacelibfollowup branch from 5ac5952 to bd63057 Compare March 13, 2026 12:11
@CppCXY
CppCXY merged commit 2e670e8 into EmmyLuaLs:main Mar 13, 2026
22 checks passed
@lewis6991
lewis6991 deleted the fix/workspacelibfollowup branch March 13, 2026 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants