一次 ZSH/starship 响应缓慢问题排查记录

梳理记录前几天解决 zsh / oh-my-zsh 在包含 Rust 源码文件的目录下响应缓慢的问题,根源是 starship.rsRust 相关的插件,尝试调用指定版本 toolchain 的 rustc 失败导致。

  1. 先通过修改 .zshrc 在行首加入 zmodload zsh/zprof 和行末加入 zprof,查看 profiling 数据。
1)   45          36.31     0.81   46.80%     30.22     0.67   38.95%  *omz*source
2)    2          21.78    10.89   28.06%     21.78    10.89   28.06%  compaudit
3)    1          10.65    10.65   13.72%      5.40     5.40    6.96%  handle_update

这个结果说明时间大量消耗在 oh-my-zsh 的初始化上,但是没有定位是哪个部分。

Claude 给出的建议包括优化 oh-my-zsh 配置、优化 compinit 、清理 ~/.zcompdump*,但是由于并非每次打开新的 terminal 时出现的现象、同时 ~/.zcompdump 的体积在数十 kb 的规模,应该不会是原因。

一些相关的 leads:每次按下回车后都很缓慢、并且在目录下有 *.rs 这类 Rust 源码的目录下才会出现。

  1. 由于出现问题的目录都包含 Rust 源码,提到这个线索后,Claude 建议我检查是否 zshgitRustCargo 相关插件的影响。对比检查发现只需要有 .rs 文件就能复现,不需要存在 .git 目录和 Cargo.toml 文件。通过 zsh -xv 来启动 zsh 来查看 zsh 的启动过程。

定位到问题在于 starship.rs

  1. 通过 env STARSHIP_LOG=trace starship explain 检查,发现日志有一条错误 [DEBUG] - (starship::modules::rust): Rustup rustc version is Err。确定是 Rust 相关的问题。
[TRACE] - (starship::modules::rust): Searching for rustup toolchain in environment.
[TRACE] - (starship::modules::rust): Searching for toolchain in toolchain file
[DEBUG] - (starship::modules::rust): Environmental toolchain override is Some("1.69.0-aarch64-apple-darwin")
[TRACE] - (starship::modules::rust): Running rustc --version directly with "/Users/leechael/.rustup/toolchains/1.69.0-aarch64-apple-darwin/bin/rustc"
[TRACE] - (starship::utils): Creating Command for binary "/Users/leechael/.rustup/toolchains/1.69.0-aarch64-apple-darwin/bin/rustc"
[TRACE] - (starship::utils): Unable to find "/Users/leechael/.rustup/toolchains/1.69.0-aarch64-apple-darwin/bin/rustc" in PATH, CannotFindBinaryPath
[TRACE] - (starship::modules::rust): Running rustup 1.69.0-aarch64-apple-darwin rustc --version
[TRACE] - (starship::utils): Creating Command for binary "rustup"
[TRACE] - (starship::utils): Using "/Users/leechael/.cargo/bin/rustup" as "rustup"
[DEBUG] - (starship::modules::rust): Rustup rustc version is Err
[TRACE] - (starship::config): Parsing color_string: red
[TRACE] - (starship::config): Read predefined color: red
[TRACE] - (starship::modules): Took 13.458331666s to compute module "rust"

Claude 建议检查 rustc, rustup 相关版本和配置。

Rust 工具链版本不匹配: 系统尝试使用 "1.69.0-aarch64-apple-darwin" 版本的工具链,但似乎无法找到对应的二进制文件。 路径问题: 系统无法在 PATH 中找到 "/Users/leechael/.rustup/toolchains/1.69.0-aarch64-apple-darwin/bin/rustc"。 执行时间过长: Rust 模块的计算耗时超过 13 秒,这显然是导致延迟的主要原因。

由于此前不存在这个问题,机器也一直有在使用 Rust 进行一些开发编译工作,因此大概率是和版本相关。

更新 Rust 相关 toolchain,再次测试检查,问题解决。