diff --git a/CHANGELOG.md b/CHANGELOG.md index c591086..7a3615c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,102 @@ # Changelog All notable changes to CodeGraph are documented here. Versions follow -[Semantic Versioning](https://semver.org/). Each release is tagged as -`vscode/vX.Y.Z` in the git history. +[Semantic Versioning](https://semver.org/). Releases from 0.18.1 on are tagged +`vX.Y.Z`; earlier ones `vscode/vX.Y.Z`. + +## [0.21.1] - 2026-10-10 + +VS Code extension only; the engine stays 0.21.0. + +- The extension now downloads its engine automatically on first start, with retries. + 0.21.0 asked first, and most users who auto-updated from 0.19.1 (which bundled the engine) dismissed or never saw the prompt and were left without a working extension. + A failed download shows an error with a Retry button. +- An engine older than the extension expects is updated automatically instead of prompting. + +## [0.21.0] - 2026-10-05 + +### Upgrading + +Restart any `codegraph-mcp --watch` daemon after upgrading. +A daemon left running from 0.20.1 keeps writing vectors that 0.21 will not load, and sessions attached to it run without semantic search until it restarts. + +Each project re-embeds once, in the background, the first time 0.21 opens it. +Keyword search keeps working while that runs. + +### Search + +- Identifiers whose words run together, like `getUserById`, are now also embedded in word-split form. + This mostly helps natural-language search in camelCase languages such as TypeScript, Java and C#. + Pass `--split-identifiers=false` to keep the old behaviour. +- Stored vectors now record the model and settings that built them. + Switching the embedding model or these settings re-embeds instead of silently mixing incompatible vectors. +- `--full-body-embedding=false` now takes effect; in 0.20.1 the flag was always on. + +### Reliability + +- A session that started while another CodeGraph process had the shared graph database open could treat it as corrupt and discard every project's saved graph. + It now waits for the other process to finish, and only a genuinely unreadable database is replaced. + The stale-`LOCK` cleanup added in 0.17.0 is gone: the OS releases a lock when its holder exits, so a leftover `LOCK` file never blocked an open, and deleting one could let two processes open the same database on Linux. +- After the database was replaced, a project could stay empty until its files changed. + It is now re-indexed. +- The file watcher honours the workspace's exclude settings and `.codegraphignore`, works on workspaces reached through a symlink, and rescans the graph once per batch of changes instead of once per event (#23). +- `--graph-only` no longer loads the embedding model. +- Two clients starting at the same moment now share one engine, and the engine receives their flags. + +### Build + +- Release engines are built with one pinned Rust toolchain (`rust-toolchain.toml`). + +## [0.20.1] - 2026-08-09 + +- **linux-arm64 engine.** ARM Linux previously had no engine at all; it is now published and fetched like the other platforms (#15). +- Fixed a startup crash on aarch64 Linux before `main()` ran (#15). +- Indexing a second markdown file no longer overwrites chunks from the first. + Doc chunk ids are now namespaced by source file (#16). + +## [0.20.0] - 2026-08-08 + +- **Engines are fetched, not bundled.** The VSIX and the npm package no longer carry every platform's binary. + Each install downloads the one engine it can run from the GitHub release, which took the VSIX from 118 MB to under 1 MB. +- **JetBrains IDE client.** A new plugin connects JetBrains IDEs to the same engine. +- VS Code onboarding: an index that comes back empty now explains why (no folder, no supported languages, misconfigured `indexPaths`, everything excluded) and offers the fix, and the Symbols view offers to index an empty workspace. +- Embedding tools are no longer disabled on healthy Macs where the OS reports 0 MB available memory. + `CODEGRAPH_SKIP_MEMORY_CHECK=1` bypasses the check (#13). +- npm publishing now refuses to pack until every engine asset is on the release. + +## [0.19.1] - 2026-06-30 + +- `codegraph_pr_context` recognises tests by the language's test marker (for example `#[cfg(test)]` modules in Rust), not only by name, so covered functions are no longer reported as untested. +- PR risk is based on callers of signature-changed functions and the untested ratio, not raw caller count. + Callers under `examples/` and `benches/` count as coverage. + +## [0.19.0] - 2026-06-30 + +- **Static embedding model.** `--embedding-model static` (VS Code: `codegraph.embeddingModel`) uses a distilled, ONNX-free model. + It embeds roughly 70x faster and reaches about 90% of the default BGE model's search quality end to end. + The model ships with the VS Code extension and is fetched by the npm install; BGE stays the default. +- COBOL, Fortran, Perl, Dart, Zig and R parsers moved behind the `extra-languages` build feature, cutting the engine by 25 MB. + Telemetry showed no indexed workspace using them. + +## [0.18.0 - 0.18.6] - 2026-06-01 to 2026-06-17 + +- **Shared engine.** One engine process can serve several workspaces and clients with a single loaded model (opt-in via `CODEGRAPH_ENGINE`). +- **Crash recovery.** Fixed a Windows crash loop (thread stack size and UTF-8 truncation of embedding text). + A graph database that crashes the engine on load is detected across restarts and replaced by a fresh one. +- **Memory-safe embedding.** Long embedding runs checkpoint every 20k symbols, back off when RAM runs low, and resume after a kill. +- `codegraph_get_module_summary` no longer returns all zeros on Windows (#5). +- MCP tool results are compact JSON, about 24% smaller; `codegraph_find_entry_points` honours `limit`. + +## [0.17.1 - 0.17.11] - 2026-05-25 to 2026-06-01 + +- **`codegraph_pr_context`.** Analyses a branch's changes in one call: changed symbols, callers, test gaps, related docs. +- **CI PR review.** `--graph-only` skips embeddings, and `--run-tool` runs one tool and exits, which together power a GitHub Action that comments a code-graph review on each PR. +- **Watcher daemon.** `codegraph-server --watch` keeps a workspace's graph fresh in the background for MCP sessions. +- Files are indexed when opened, so hover and go-to-definition work without a prior workspace index. +- The persisted graph is a true snapshot, fixing duplicate symbols that built up across edits and reloads. +- `codegraph_get_ai_context` reports graph statistics, and every tool warns when the graph looks nearly empty. +- VS Code stops auto-restarting the server after 3 crashes in 60 seconds and shows the error instead. +- User exclude settings now add to the default exclude list instead of replacing it. ## [0.17.0] — 2026-05-25 diff --git a/Cargo.lock b/Cargo.lock index 2bd6e00..033ab03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -901,6 +901,8 @@ dependencies = [ "hf-hub", "instant-distance", "log", + "ndarray", + "ort", "parking_lot", "rmp-serde", "rocksdb", @@ -1120,6 +1122,7 @@ dependencies = [ "globset", "lru", "notify", + "rayon", "regex", "serde", "serde_json", diff --git a/README.md b/README.md index 4150b3e..b0bd0da 100644 --- a/README.md +++ b/README.md @@ -30,13 +30,12 @@ The server indexes the current working directory automatically. Install the VSIX: ```bash -code --install-extension codegraph-0.21.0.vsix +code --install-extension codegraph-0.21.1.vsix ``` One VSIX serves every platform. -The analysis engine is not bundled: on first activation the extension offers to download the engine built for your platform, verifies it against the published checksum, and installs it into `~/.codegraph/bin` - the same location the JetBrains plugin uses, so one download serves both. -The download is offered rather than performed automatically, because it is a native binary that runs with your permissions. -Decline it and run **CodeGraph: Download Analysis Engine** from the command palette whenever you are ready. +The analysis engine is not bundled: on first activation the extension downloads the engine built for your platform, verifies it against the published checksum, and installs it into `~/.codegraph/bin` - the same location the JetBrains plugin uses, so one download serves both. +If the download fails, run **CodeGraph: Download Analysis Engine** from the command palette to try again. Once an engine is present, the extension starts it automatically and registers all tools as Language Model Tools for Copilot. @@ -114,6 +113,7 @@ Pass `--split-identifiers=false` to keep the old behaviour. | `--full-body-embedding` | `true` | Embed full function body (~50 lines) for better semantic search and duplicate detection. Takes a value: `--full-body-embedding=false` turns it off | | `--split-identifiers` | `true` | Also embed the word-split form of identifiers whose words are run together, so `getUserById` embeds as "get user by id" too. Names already separated by `_` or `-` are left alone, since they tokenise into the same words; a leading or trailing delimiter separates nothing, so `_handleClick` is split like `handleClick`. Takes a value: `--split-identifiers=false` embeds raw names, as releases up to 0.20.1 did | | `--max-files ` | 5000 | Maximum files to index | +| `--max-threads ` | half the CPUs | Most threads the engine computes on: the embedding model's pool, the pool tokenizing for it, and the async runtime. Also read from `CODEGRAPH_MAX_THREADS`. Lower it to keep the machine responsive while a large workspace embeds | | `--profile ` | `all` | Filter the exposed MCP tool surface to a named subset (see below) | | `--graph-only` | off | Skip embedding generation — build the graph and serve structural tools only. No ONNX model load, 10-50× faster indexing. Semantic search and memory tools unavailable. For CI / one-shot graph queries. | | `--run-tool ` | — | One-shot mode: index, run a single tool, print its result, exit. No MCP handshake. Pair with `--tool-args ''`. | diff --git a/crates/codegraph-memory/Cargo.toml b/crates/codegraph-memory/Cargo.toml index 379d141..d8088a4 100644 --- a/crates/codegraph-memory/Cargo.toml +++ b/crates/codegraph-memory/Cargo.toml @@ -52,6 +52,13 @@ tokenizers = "0.21" safetensors = "0.4" half = "2" +# The ONNX session is built here, not by fastembed, so its thread pool can be +# sized and its spin-waiting turned off (issue #29). Both crates are already +# in the build through fastembed; these must stay at its versions, and the +# platform features (static binaries vs. a loaded DLL) come from its features. +ort = { version = "=2.0.0-rc.9", default-features = false, features = ["ndarray"] } +ndarray = { version = "0.16", default-features = false } + # Embeddings - fastembed with BGE-Small-EN-v1.5 # macOS/Linux: static link ONNX Runtime (ort-download-binaries) # Windows: load onnxruntime DLL at runtime (ort-load-dynamic, avoids CRT /MT vs /MD mismatch) diff --git a/crates/codegraph-memory/src/embedding/engine.rs b/crates/codegraph-memory/src/embedding/engine.rs index 40d4fce..58d265e 100644 --- a/crates/codegraph-memory/src/embedding/engine.rs +++ b/crates/codegraph-memory/src/embedding/engine.rs @@ -155,7 +155,7 @@ impl VectorEngine { } /// Default cache directory for fastembed models -fn default_cache_dir() -> PathBuf { +pub(super) fn default_cache_dir() -> PathBuf { let home = std::env::var("HOME") .or_else(|_| std::env::var("USERPROFILE")) .unwrap_or_else(|_| ".".to_string()); diff --git a/crates/codegraph-memory/src/embedding/fastembed_embed.rs b/crates/codegraph-memory/src/embedding/fastembed_embed.rs index 5db838e..a63fe0d 100644 --- a/crates/codegraph-memory/src/embedding/fastembed_embed.rs +++ b/crates/codegraph-memory/src/embedding/fastembed_embed.rs @@ -1,24 +1,35 @@ // Copyright 2025-2026 Andrey Vasilevsky // SPDX-License-Identifier: Apache-2.0 -//! Fastembed wrapper for codegraph-memory +//! ONNX transformer embeddings for codegraph-memory //! //! Supports configurable embedding models: //! - **BGE-Small-EN-v1.5** (384d, 512-tok context) — fast general-purpose default. -//! - **Jina Code V2** (768d, 8K context) — code-aware, 6× slower than BGE. +//! - **Jina Code V2** (768d) — code-aware, 6× slower than BGE. //! - **Granite-97M-Multilingual-R2** (384d, 32K context) — IBM's //! ModernBERT-based multilingual embedder. 200+ languages, 9 //! programming languages explicitly trained, MTEB Code Retrieval 57. -//! Loaded via fastembed's `UserDefinedEmbeddingModel` path because -//! fastembed-rs <= 4.9.x doesn't yet ship the model in its built-in -//! enum. +//! Fetched from its own HuggingFace repo; fastembed-rs <= 4.9.x +//! doesn't ship the model in its built-in enum. +//! +//! The ONNX session is built here rather than by fastembed's +//! `TextEmbedding`, which sizes ONNX Runtime's thread pool to every core +//! and leaves its threads spin-waiting, with no way to change either +//! (issue #29). fastembed still supplies the model catalogue and pooling; +//! downloading, tokenizer setup and batching mirror what 4.9.1 does, so +//! vectors match the ones it produced. use crate::error::{MemoryError, Result}; use fastembed::{ - EmbeddingModel, InitOptions, InitOptionsUserDefined, Pooling, TextEmbedding, - TokenizerFiles, UserDefinedEmbeddingModel, + EmbeddingModel, OutputKey, Pooling, SingleBatchOutput, TextEmbedding, TokenizerFiles, +}; +use ndarray::Array2; +use ort::{ + session::{builder::GraphOptimizationLevel, builder::SessionBuilder, Session}, + value::Value, }; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use tokenizers::{AddedToken, PaddingParams, PaddingStrategy, Tokenizer, TruncationParams}; /// Configurable embedding model selection #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)] @@ -101,9 +112,24 @@ const GRANITE_97M_ONNX_PATH: &str = "onnx/model.onnx"; #[cfg(target_os = "windows")] const ORT_VERSION: &str = "1.20.0"; -/// Fastembed-based text embedding model +/// Token limit fastembed 4.9.1 applied to its built-in models when the +/// caller set none, which this crate never did. Kept so stored vectors stay +/// valid: Jina Code V2 has always been truncated here, not at its 8K window. +const BUILTIN_MAX_LENGTH: usize = 512; + +/// Output tensor lookup order, as fastembed's `TextEmbedding` uses it. +const OUTPUT_PRECEDENCE: &[OutputKey] = &[ + OutputKey::OnlyOne, + OutputKey::ByName("last_hidden_state"), + OutputKey::ByName("sentence_embedding"), +]; + +/// ONNX transformer embedding model pub(crate) struct FastembedEmbedding { - model: TextEmbedding, + session: Session, + tokenizer: Tokenizer, + need_token_type_ids: bool, + pooling: Pooling, model_type: CodeGraphEmbeddingModel, } @@ -113,53 +139,77 @@ impl FastembedEmbedding { /// The model is automatically downloaded to `cache_dir` on first use. /// On Windows, also ensures onnxruntime.dll is available (downloaded if needed). pub(crate) fn new(cache_dir: PathBuf, model_type: CodeGraphEmbeddingModel) -> Result { - // MUST set FASTEMBED_CACHE_DIR before InitOptions::new() — its Default impl - // calls get_cache_dir() which falls back to ".fastembed_cache" in CWD. - // Note: the env var is FASTEMBED_CACHE_DIR (not _PATH). - unsafe { std::env::set_var("FASTEMBED_CACHE_DIR", &cache_dir) }; - // On Windows with ort-load-dynamic, ensure onnxruntime.dll is available #[cfg(target_os = "windows")] ensure_ort_dll(&cache_dir)?; - log::info!("Loading embedding model: {}", model_type.display_name()); + let threads = super::onnx_threads(); + log::info!( + "Loading embedding model: {} ({threads} ONNX threads)", + model_type.display_name() + ); - let model = match model_type.to_fastembed_builtin() { - Some(builtin) => Self::load_builtin(cache_dir, builtin, model_type)?, - None => Self::load_user_defined(cache_dir, model_type)?, + let (session, tokenizer, pooling) = match model_type.to_fastembed_builtin() { + Some(builtin) => Self::load_builtin(&cache_dir, builtin, model_type, threads)?, + None => Self::load_user_defined(&cache_dir, model_type, threads)?, }; - Ok(Self { model, model_type }) + let need_token_type_ids = session + .inputs + .iter() + .any(|input| input.name == "token_type_ids"); + + Ok(Self { + session, + tokenizer, + need_token_type_ids, + pooling, + model_type, + }) } fn load_builtin( - cache_dir: PathBuf, + cache_dir: &Path, builtin: EmbeddingModel, model_type: CodeGraphEmbeddingModel, - ) -> Result { - let options = InitOptions::new(builtin) - .with_cache_dir(cache_dir) - .with_show_download_progress(true); - - TextEmbedding::try_new(options).map_err(|e| { - MemoryError::model(format!( - "Failed to load {} model: {e}", - model_type.display_name() - )) - }) + threads: usize, + ) -> Result { + let info = TextEmbedding::get_model_info(&builtin) + .map_err(|e| MemoryError::model(format!("Unknown model {builtin:?}: {e}")))?; + let repo = hf_repo(cache_dir, &info.model_code)?; + + let onnx = repo.get(&info.model_file).map_err(|e| { + MemoryError::model(format!("Failed to retrieve {}: {e}", info.model_file)) + })?; + for file in &info.additional_files { + repo.get(file) + .map_err(|e| MemoryError::model(format!("Failed to retrieve {file}: {e}")))?; + } + let tokenizer_files = TokenizerFiles { + tokenizer_file: read_repo_file(&repo, "tokenizer.json")?, + config_file: read_repo_file(&repo, "config.json")?, + special_tokens_map_file: read_repo_file(&repo, "special_tokens_map.json")?, + tokenizer_config_file: read_repo_file(&repo, "tokenizer_config.json")?, + }; + let pooling = TextEmbedding::get_default_pooling_method(&builtin).unwrap_or_default(); + + let session = session_builder(threads) + .and_then(|b| b.commit_from_file(onnx)) + .map_err(|e| load_error(model_type, e))?; + let tokenizer = load_tokenizer(tokenizer_files, BUILTIN_MAX_LENGTH) + .map_err(|e| load_error(model_type, e))?; + Ok((session, tokenizer, pooling)) } /// Load Granite (or other user-defined) ONNX + tokenizer files - /// from HuggingFace via hf-hub, then hand them to fastembed's - /// `try_new_from_user_defined` path. + /// from HuggingFace via hf-hub. fn load_user_defined( - cache_dir: PathBuf, + cache_dir: &Path, model_type: CodeGraphEmbeddingModel, - ) -> Result { + threads: usize, + ) -> Result { let (repo, pooling) = match model_type { - CodeGraphEmbeddingModel::Granite97mMultilingualR2 => { - (GRANITE_97M_REPO, Pooling::Cls) - } + CodeGraphEmbeddingModel::Granite97mMultilingualR2 => (GRANITE_97M_REPO, Pooling::Cls), other => { return Err(MemoryError::model(format!( "load_user_defined called for non-user-defined model: {other:?}" @@ -167,36 +217,26 @@ impl FastembedEmbedding { } }; - let bundle = download_user_defined_model(repo, &cache_dir, model_type)?; - let user_model = UserDefinedEmbeddingModel::new( - bundle.onnx_bytes, - TokenizerFiles { - tokenizer_file: bundle.tokenizer_file, - config_file: bundle.config_file, - special_tokens_map_file: bundle.special_tokens_map_file, - tokenizer_config_file: bundle.tokenizer_config_file, - }, - ) - .with_pooling(pooling); - - let options = InitOptionsUserDefined::new().with_max_length(model_type.max_length()); - - TextEmbedding::try_new_from_user_defined(user_model, options).map_err(|e| { - MemoryError::model(format!( - "Failed to load {} from user-defined ONNX: {e}", - model_type.display_name() - )) - }) + let bundle = download_user_defined_model(repo, cache_dir, model_type)?; + let tokenizer_files = TokenizerFiles { + tokenizer_file: bundle.tokenizer_file, + config_file: bundle.config_file, + special_tokens_map_file: bundle.special_tokens_map_file, + tokenizer_config_file: bundle.tokenizer_config_file, + }; + + let session = session_builder(threads) + .and_then(|b| b.commit_from_memory(&bundle.onnx_bytes)) + .map_err(|e| load_error(model_type, e))?; + let tokenizer = load_tokenizer(tokenizer_files, model_type.max_length()) + .map_err(|e| load_error(model_type, e))?; + Ok((session, tokenizer, pooling)) } /// Generate embedding for a single text pub(crate) fn embed(&self, text: &str) -> Result> { - let results = self - .model - .embed(vec![text.to_string()], None) - .map_err(|e| MemoryError::embedding(format!("Embedding failed: {e}")))?; - - results + self.run_batch(&[text]) + .map_err(|e| MemoryError::embedding(format!("Embedding failed: {e}")))? .into_iter() .next() .ok_or_else(|| MemoryError::embedding("Empty embedding result")) @@ -205,11 +245,6 @@ impl FastembedEmbedding { /// Generate embeddings for a batch of texts. /// Uses batch_size=64 to limit ONNX Runtime peak memory allocation. pub(crate) fn embed_batch(&self, texts: &[&str]) -> Result>> { - if texts.is_empty() { - return Ok(Vec::new()); - } - - let owned: Vec = texts.iter().map(|t| t.to_string()).collect(); // Granite-97m's intermediate tensors at 32K tokens are larger // than BGE-small's at 512. Halve the batch when we know we're // running the long-context model — peak memory stays bounded @@ -218,9 +253,71 @@ impl FastembedEmbedding { CodeGraphEmbeddingModel::Granite97mMultilingualR2 => 32, _ => 64, }; - self.model - .embed(owned, Some(batch_size)) - .map_err(|e| MemoryError::embedding(format!("Batch embedding failed: {e}"))) + // One batch at a time. fastembed ran them in parallel on the rayon + // pool, each one on an ONNX pool already as wide as the machine. + let mut vectors = Vec::with_capacity(texts.len()); + for batch in texts.chunks(batch_size) { + vectors.extend( + self.run_batch(batch) + .map_err(|e| MemoryError::embedding(format!("Batch embedding failed: {e}")))?, + ); + } + Ok(vectors) + } + + /// Tokenize, run and pool one batch, as fastembed's `TextEmbedding::embed` + /// does for each of its batches. + fn run_batch(&self, batch: &[&str]) -> std::result::Result>, String> { + let encodings = self + .tokenizer + .encode_batch(batch.to_vec(), true) + .map_err(|e| format!("Failed to encode the batch: {e}"))?; + let Some(first) = encodings.first() else { + return Ok(Vec::new()); + }; + + // Padding is BatchLongest, so every encoding has the same length. + let shape = (encodings.len(), first.len()); + let mut ids = Vec::with_capacity(shape.0 * shape.1); + let mut mask = Vec::with_capacity(shape.0 * shape.1); + let mut type_ids = Vec::with_capacity(shape.0 * shape.1); + for encoding in &encodings { + ids.extend(encoding.get_ids().iter().map(|&x| i64::from(x))); + mask.extend(encoding.get_attention_mask().iter().map(|&x| i64::from(x))); + type_ids.extend(encoding.get_type_ids().iter().map(|&x| i64::from(x))); + } + let to_err = |e: ndarray::ShapeError| e.to_string(); + let ids = Array2::from_shape_vec(shape, ids).map_err(to_err)?; + let mask = Array2::from_shape_vec(shape, mask).map_err(to_err)?; + let type_ids = Array2::from_shape_vec(shape, type_ids).map_err(to_err)?; + + let ort_err = |e: ort::Error| e.to_string(); + let ids = Value::from_array(ids).map_err(ort_err)?; + let attention_mask = Value::from_array(mask.view()).map_err(ort_err)?; + let mut inputs = ort::inputs![ + "input_ids" => ids, + "attention_mask" => attention_mask, + ] + .map_err(ort_err)?; + if self.need_token_type_ids { + inputs.push(( + "token_type_ids".into(), + Value::from_array(type_ids).map_err(ort_err)?.into(), + )); + } + + let output = SingleBatchOutput { + session_outputs: self.session.run(inputs).map_err(ort_err)?, + attention_mask_array: mask, + }; + let pooled = output + .select_and_pool_output(&OUTPUT_PRECEDENCE, Some(self.pooling.clone())) + .map_err(|e| e.to_string())?; + Ok(pooled + .rows() + .into_iter() + .map(|row| normalize(row.iter().copied())) + .collect()) } /// Get the embedding dimension (depends on model) @@ -234,6 +331,123 @@ impl FastembedEmbedding { } } +type Loaded = (Session, Tokenizer, Pooling); + +fn load_error(model_type: CodeGraphEmbeddingModel, e: impl std::fmt::Display) -> MemoryError { + MemoryError::model(format!( + "Failed to load {} model: {e}", + model_type.display_name() + )) +} + +/// Session options for every model: a capped intra-op pool whose idle +/// threads block instead of spinning. Spinning kept every core busy between +/// batches and, on a 12-core Mac, halved embedding throughput while doing it. +fn session_builder(threads: usize) -> ort::Result { + Session::builder()? + .with_optimization_level(GraphOptimizationLevel::Level3)? + .with_intra_threads(threads)? + .with_intra_op_spinning(false) +} + +/// L2-normalise, with fastembed's epsilon. +fn normalize(values: impl Iterator + Clone) -> Vec { + let norm = values.clone().map(|v| v * v).sum::().sqrt(); + values.map(|v| v / (norm + 1e-12)).collect() +} + +/// The HuggingFace repo for a built-in model, in the cache layout +/// fastembed 4.9.1 used (`models----` under `cache_dir`), so +/// existing downloads are reused. Like fastembed, `HF_HOME` and +/// `HF_ENDPOINT` override the cache and the server. +fn hf_repo(cache_dir: &Path, model_code: &str) -> Result { + let cache = std::env::var_os("HF_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| cache_dir.to_path_buf()); + let endpoint = + std::env::var("HF_ENDPOINT").unwrap_or_else(|_| "https://huggingface.co".to_string()); + let api = hf_hub::api::sync::ApiBuilder::new() + .with_cache_dir(cache) + .with_endpoint(endpoint) + .with_progress(true) + .build() + .map_err(|e| MemoryError::model(format!("Failed to initialise hf-hub API: {e}")))?; + Ok(api.model(model_code.to_string())) +} + +fn read_repo_file(repo: &hf_hub::api::sync::ApiRepo, name: &str) -> Result> { + let local = repo + .get(name) + .map_err(|e| MemoryError::model(format!("Failed to retrieve {name}: {e}")))?; + std::fs::read(&local) + .map_err(|e| MemoryError::model(format!("Failed to read {}: {e}", local.display()))) +} + +/// fastembed 4.9.1's `load_tokenizer`, which it does not export: padding to +/// the longest text in the batch, truncation at the smaller of `max_length` +/// and the tokenizer's own limit, and the model's special tokens. +fn load_tokenizer( + files: TokenizerFiles, + max_length: usize, +) -> std::result::Result { + let json = |bytes: &[u8], name: &str| { + serde_json::from_slice::(bytes) + .map_err(|e| format!("Could not read {name}: {e}")) + }; + let config = json(&files.config_file, "config.json")?; + let special_tokens_map = json(&files.special_tokens_map_file, "special_tokens_map.json")?; + let tokenizer_config = json(&files.tokenizer_config_file, "tokenizer_config.json")?; + let mut tokenizer = Tokenizer::from_bytes(&files.tokenizer_file) + .map_err(|e| format!("Could not read tokenizer.json: {e}"))?; + + // BGE sets model_max_length to 1e30, which only fits in an f64. + let model_max_length = tokenizer_config["model_max_length"] + .as_f64() + .ok_or("tokenizer_config.json has no model_max_length")? as f32; + let max_length = max_length.min(model_max_length as usize); + let pad_id = config["pad_token_id"].as_u64().unwrap_or(0) as u32; + let pad_token = tokenizer_config["pad_token"] + .as_str() + .ok_or("tokenizer_config.json has no pad_token")? + .to_string(); + + tokenizer + .with_padding(Some(PaddingParams { + strategy: PaddingStrategy::BatchLongest, + pad_token, + pad_id, + ..Default::default() + })) + .with_truncation(Some(TruncationParams { + max_length, + ..Default::default() + })) + .map_err(|e| format!("Could not configure the tokenizer: {e}"))?; + + if let serde_json::Value::Object(tokens) = special_tokens_map { + for value in tokens.values() { + let token = match value { + serde_json::Value::String(content) => AddedToken { + content: content.clone(), + special: true, + ..Default::default() + }, + serde_json::Value::Object(_) => AddedToken { + content: value["content"].as_str().unwrap_or_default().to_string(), + special: true, + single_word: value["single_word"].as_bool().unwrap_or_default(), + lstrip: value["lstrip"].as_bool().unwrap_or_default(), + rstrip: value["rstrip"].as_bool().unwrap_or_default(), + normalized: value["normalized"].as_bool().unwrap_or_default(), + }, + _ => continue, + }; + tokenizer.add_special_tokens(&[token]); + } + } + Ok(tokenizer) +} + impl super::Embedder for FastembedEmbedding { fn embed(&self, text: &str) -> Result> { // Explicit path → the inherent method (avoids any trait-method ambiguity). @@ -250,7 +464,7 @@ impl super::Embedder for FastembedEmbedding { } } -/// Bundle of bytes needed to construct a `UserDefinedEmbeddingModel`. +/// ONNX and tokenizer bytes for a user-defined model. struct UserDefinedModelBundle { onnx_bytes: Vec, tokenizer_file: Vec, @@ -267,7 +481,7 @@ struct UserDefinedModelBundle { /// disturbed. fn download_user_defined_model( repo: &str, - cache_dir: &std::path::Path, + cache_dir: &Path, model_type: CodeGraphEmbeddingModel, ) -> Result { use hf_hub::api::sync::ApiBuilder; @@ -299,9 +513,7 @@ fn download_user_defined_model( _ => GRANITE_97M_ONNX_PATH, }; let onnx_local = model_repo.get(onnx_path).map_err(|e| { - MemoryError::model(format!( - "Failed to download {onnx_path} from {repo}: {e}" - )) + MemoryError::model(format!("Failed to download {onnx_path} from {repo}: {e}")) })?; let onnx_bytes = std::fs::read(&onnx_local).map_err(|e| { MemoryError::model(format!( @@ -310,15 +522,13 @@ fn download_user_defined_model( )) })?; - let read_required = - |name: &str, repo: &hf_hub::api::sync::ApiRepo| -> Result> { - let local = repo.get(name).map_err(|e| { - MemoryError::model(format!("Failed to download {name}: {e}")) - })?; - std::fs::read(&local).map_err(|e| { - MemoryError::model(format!("Failed to read {}: {e}", local.display())) - }) - }; + let read_required = |name: &str, repo: &hf_hub::api::sync::ApiRepo| -> Result> { + let local = repo + .get(name) + .map_err(|e| MemoryError::model(format!("Failed to download {name}: {e}")))?; + std::fs::read(&local) + .map_err(|e| MemoryError::model(format!("Failed to read {}: {e}", local.display()))) + }; Ok(UserDefinedModelBundle { onnx_bytes, @@ -344,7 +554,10 @@ fn ensure_ort_dll(cache_dir: &std::path::Path) -> Result<()> { if let Some(exe_dir) = exe_path.parent() { let bundled_dll = exe_dir.join("onnxruntime.dll"); if bundled_dll.exists() { - log::info!("ONNX Runtime DLL found alongside binary: {}", bundled_dll.display()); + log::info!( + "ONNX Runtime DLL found alongside binary: {}", + bundled_dll.display() + ); std::env::set_var("ORT_DYLIB_PATH", &bundled_dll); return Ok(()); } @@ -449,8 +662,104 @@ mod tests { assert!(CodeGraphEmbeddingModel::Granite97mMultilingualR2 .to_fastembed_builtin() .is_none()); - assert!(CodeGraphEmbeddingModel::BgeSmall.to_fastembed_builtin().is_some()); - assert!(CodeGraphEmbeddingModel::JinaCodeV2.to_fastembed_builtin().is_some()); + assert!(CodeGraphEmbeddingModel::BgeSmall + .to_fastembed_builtin() + .is_some()); + assert!(CodeGraphEmbeddingModel::JinaCodeV2 + .to_fastembed_builtin() + .is_some()); + } + + /// Texts that exercise padding (mixed lengths in one batch), truncation + /// (well past 512 tokens) and non-ASCII input. + fn parity_texts() -> Vec { + let long_body = + "fn step(state: &mut State) -> Result<()> { state.tick += 1; } ".repeat(120); + vec![ + "getUserById".to_string(), + "fn parse_config(path: &Path) -> Result".to_string(), + long_body, + "def überprüfen(数据): return 数据 is not None # проверка".to_string(), + "class LruCache { get(key) { return this.map.get(key); } }".to_string(), + ] + } + + fn cosine(a: &[f32], b: &[f32]) -> f32 { + let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum(); + let norm = |v: &[f32]| v.iter().map(|x| x * x).sum::().sqrt(); + dot / (norm(a) * norm(b)) + } + + /// The owned session must reproduce fastembed's `TextEmbedding` vectors, + /// or every stored vector would silently stop matching new queries. + fn assert_matches_fastembed(model_type: CodeGraphEmbeddingModel) { + let cache = super::super::engine::default_cache_dir(); + let ours = FastembedEmbedding::new(cache.clone(), model_type).expect("load model"); + + let theirs = match model_type.to_fastembed_builtin() { + Some(builtin) => fastembed::TextEmbedding::try_new( + fastembed::InitOptions::new(builtin).with_cache_dir(cache), + ) + .expect("load fastembed model"), + None => { + let b = download_user_defined_model(GRANITE_97M_REPO, &cache, model_type) + .expect("download"); + let model = fastembed::UserDefinedEmbeddingModel::new( + b.onnx_bytes, + TokenizerFiles { + tokenizer_file: b.tokenizer_file, + config_file: b.config_file, + special_tokens_map_file: b.special_tokens_map_file, + tokenizer_config_file: b.tokenizer_config_file, + }, + ) + .with_pooling(Pooling::Cls); + fastembed::TextEmbedding::try_new_from_user_defined( + model, + fastembed::InitOptionsUserDefined::new() + .with_max_length(model_type.max_length()), + ) + .expect("load fastembed model") + } + }; + + let texts = parity_texts(); + let refs: Vec<&str> = texts.iter().map(String::as_str).collect(); + let expected = theirs + .embed(texts.clone(), Some(64)) + .expect("fastembed embed"); + let batched = ours.embed_batch(&refs).expect("batch embed"); + assert_eq!(batched.len(), expected.len()); + + for (i, text) in texts.iter().enumerate() { + let single = ours.embed(text).expect("single embed"); + assert_eq!(single.len(), model_type.dimension()); + for (label, got) in [("batched", &batched[i]), ("single", &single)] { + let sim = cosine(got, &expected[i]); + assert!( + sim > 0.9999, + "{model_type:?} text {i} ({label}): cosine {sim} against fastembed" + ); + } + } + } + + #[test] + #[ignore = "downloads the BGE Small EN v1.5 model"] + fn bge_small_matches_fastembed() { + assert_matches_fastembed(CodeGraphEmbeddingModel::BgeSmall); + } + + #[test] + #[ignore = "downloads the 640 MB Jina Code V2 model"] + fn jina_code_matches_fastembed() { + assert_matches_fastembed(CodeGraphEmbeddingModel::JinaCodeV2); + } + + #[test] + #[ignore = "downloads the Granite 97M model"] + fn granite_matches_fastembed() { + assert_matches_fastembed(CodeGraphEmbeddingModel::Granite97mMultilingualR2); } #[test] diff --git a/crates/codegraph-memory/src/embedding/mod.rs b/crates/codegraph-memory/src/embedding/mod.rs index 5d3cea7..997b5a9 100644 --- a/crates/codegraph-memory/src/embedding/mod.rs +++ b/crates/codegraph-memory/src/embedding/mod.rs @@ -14,6 +14,32 @@ pub use fastembed_embed::CodeGraphEmbeddingModel; use crate::error::Result; use std::path::PathBuf; +use std::sync::OnceLock; + +static ONNX_THREADS: OnceLock = OnceLock::new(); + +/// Threads a process uses for compute when nothing caps it: half the cores, +/// at least one. Embedding a workspace on every core made the machine +/// unusable for as long as it ran (issue #29); with idle ONNX threads +/// blocking rather than spinning, half the cores still embeds faster than +/// every core did with spinning. +#[must_use] +pub fn default_thread_budget() -> usize { + std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).max(1)) +} + +/// Size ONNX Runtime's intra-op pool for every model loaded afterwards. +/// +/// Process-wide, like rayon's global pool: set it once at startup, before the +/// first model loads. Returns false if it was already set. Without a call, +/// models use [`default_thread_budget`]. +pub fn set_onnx_threads(threads: usize) -> bool { + ONNX_THREADS.set(threads.max(1)).is_ok() +} + +fn onnx_threads() -> usize { + *ONNX_THREADS.get_or_init(default_thread_budget) +} /// Pluggable embedding backend. The transformer path (fastembed/ONNX) and a /// future static (lookup-table) path both implement this; `VectorEngine` holds a diff --git a/crates/codegraph-memory/src/lib.rs b/crates/codegraph-memory/src/lib.rs index c50d276..42a3c3f 100644 --- a/crates/codegraph-memory/src/lib.rs +++ b/crates/codegraph-memory/src/lib.rs @@ -43,13 +43,16 @@ pub mod storage; pub mod temporal; // Re-exports for convenience -pub use embedding::{CodeGraphEmbeddingModel, EmbeddingBackend, VectorEngine}; +pub use docs::{extract_identifiers, DocChunk, DocClaim, DocSearchResult, DocStore}; +pub use embedding::{ + default_thread_budget, set_onnx_threads, CodeGraphEmbeddingModel, EmbeddingBackend, + VectorEngine, +}; pub use error::MemoryError; pub use node::{ CodeLink, IssueSeverity, LinkedNodeType, MemoryId, MemoryKind, MemoryNode, MemoryNodeBuilder, MemorySource, }; pub use search::{MemorySearch, SearchConfig, SearchResult}; -pub use docs::{extract_identifiers, DocChunk, DocClaim, DocSearchResult, DocStore}; pub use storage::MemoryStore; pub use temporal::TemporalMetadata; diff --git a/crates/codegraph-server/Cargo.toml b/crates/codegraph-server/Cargo.toml index 3028865..f6fcb66 100644 --- a/crates/codegraph-server/Cargo.toml +++ b/crates/codegraph-server/Cargo.toml @@ -89,6 +89,10 @@ codegraph-memory.workspace = true # CLI clap.workspace = true +# Sizes the global pool the tokenizer runs on (issue #29); already in the +# build through the parsers and tokenizers. +rayon = "1.10" + [features] # Off by default → the community binary omits these heavy, unused grammars. # Pro / full builds opt in with `--features extra-languages`. diff --git a/crates/codegraph-server/src/ai_query/engine.rs b/crates/codegraph-server/src/ai_query/engine.rs index ec3e061..1e3844a 100644 --- a/crates/codegraph-server/src/ai_query/engine.rs +++ b/crates/codegraph-server/src/ai_query/engine.rs @@ -54,6 +54,16 @@ pub struct QueryEngine { /// built with different embed settings. No embed run will follow, so the /// search status must not say embeddings are building. daemon_vectors_mismatched: std::sync::atomic::AtomicBool, + /// Held for a whole-workspace embedding pass, so a second one waits for + /// the first instead of running beside it. A full build publishes its + /// vectors only when it finishes, so a pass started meanwhile, such as the + /// reindex tool's `embed_missing_symbols`, found nothing embedded and + /// embedded everything again, both runs competing for the same cores. + /// Run in turn, the second finds the first's vectors. + /// + /// Per-file updates do not take it: they are small, and a save awaits + /// them. + workspace_embed: tokio::sync::Mutex<()>, } /// Search status when the attached watcher daemon's vectors were built with @@ -409,6 +419,7 @@ impl QueryEngine { // off for snake_case, where it does not help. split_identifiers: std::sync::atomic::AtomicBool::new(true), daemon_vectors_mismatched: std::sync::atomic::AtomicBool::new(false), + workspace_embed: tokio::sync::Mutex::new(()), } } @@ -599,6 +610,26 @@ impl QueryEngine { *self.vector_engine.write().await = Some(engine); } + /// Take the whole-workspace embedding turn, waiting for a pass already + /// running (see the `workspace_embed` field). + /// + /// A user-initiated reindex that lands mid-build waits for the whole of + /// that build, which from the outside is indistinguishable from a hang, + /// so the wait and its length are logged rather than left silent. + async fn take_embed_turn(&self, pass: &str) -> tokio::sync::MutexGuard<'_, ()> { + if let Ok(turn) = self.workspace_embed.try_lock() { + return turn; + } + tracing::info!("[QueryEngine] {pass} is waiting for the embedding pass already running"); + let since = Instant::now(); + let turn = self.workspace_embed.lock().await; + tracing::info!( + "[QueryEngine] {pass} waited {:?} for the previous embedding pass", + since.elapsed() + ); + turn + } + /// Build symbol embedding vectors for semantic search. /// Requires vector_engine to be set first. Embeds name + signature + docstring /// for each symbol in batch for efficiency. @@ -617,6 +648,7 @@ impl QueryEngine { /// [`EMBED_LOW_MEM_MB`] it halves the ONNX batch and forces a /// checkpoint — degrade to slow instead of being OOM-killed. pub async fn build_symbol_vectors_checkpointed(&self, slug: Option<&str>) { + let _turn = self.take_embed_turn("build_symbol_vectors").await; let engine = match self.vector_engine.read().await.clone() { Some(e) => e, None => { @@ -812,6 +844,7 @@ impl QueryEngine { /// path after a crash-interrupted embed run: persisted checkpoint vectors /// load on startup and this fills in only the remainder. pub async fn embed_missing_symbols_checkpointed(&self, slug: Option<&str>) { + let _turn = self.take_embed_turn("embed_missing_symbols").await; let engine = match self.vector_engine.read().await.clone() { Some(e) => e, None => return, diff --git a/crates/codegraph-server/src/main.rs b/crates/codegraph-server/src/main.rs index 930f90e..d8514b2 100644 --- a/crates/codegraph-server/src/main.rs +++ b/crates/codegraph-server/src/main.rs @@ -152,6 +152,57 @@ struct Args { /// (default: ~/.codegraph/cg-engine.sock). #[arg(long)] socket: Option, + + /// Most threads the engine computes on: the embedding model's thread + /// pool, the pool tokenizing for it, and the async runtime's workers. + /// 0 or unset means half the logical CPUs. Also read from + /// `CODEGRAPH_MAX_THREADS` when the flag is not given. + #[arg(long)] + max_threads: Option, +} + +impl Args { + /// The thread cap the user asked for, if any: `--max-threads`, else + /// `CODEGRAPH_MAX_THREADS`. Zero and unparsable values mean "not set". + fn requested_threads(&self) -> Option { + self.max_threads + .or_else(|| { + std::env::var("CODEGRAPH_MAX_THREADS") + .ok() + .and_then(|v| v.trim().parse().ok()) + }) + .filter(|&n| n > 0) + } +} + +/// How many threads each pool gets, decided once before any pool exists. +/// +/// Without a requested cap every pool is sized to [`default_thread_budget`] +/// (half the CPUs), except that `RAYON_NUM_THREADS` and +/// `TOKIO_WORKER_THREADS`, which the pools read themselves, still apply: +/// they were the only cap before this one existed. A requested cap +/// overrides them. +/// +/// The async runtime keeps at least two workers. Embedding runs inside a +/// task and holds its worker until a batch finishes; with one worker, every +/// request would wait behind it. Idle workers cost no CPU. +struct ThreadBudget { + compute: usize, + rayon: Option, + tokio: Option, +} + +impl ThreadBudget { + fn new(requested: Option) -> Self { + let compute = requested.unwrap_or_else(codegraph_memory::default_thread_budget); + let unless_env = + |var: &str| (requested.is_some() || std::env::var_os(var).is_none()).then_some(compute); + Self { + compute, + rayon: unless_env("RAYON_NUM_THREADS"), + tokio: unless_env("TOKIO_WORKER_THREADS").map(|n| n.max(2)), + } + } } /// The settings an auto-spawned engine is started with. @@ -185,6 +236,10 @@ fn engine_args(args: &Args) -> Vec { if args.graph_only { out.push("--graph-only".into()); } + if let Some(threads) = args.requested_threads() { + out.push("--max-threads".into()); + out.push(threads.to_string().into()); + } out.push(format!("--full-body-embedding={}", args.full_body_embedding).into()); out.push(format!("--split-identifiers={}", args.split_identifiers).into()); out @@ -345,7 +400,17 @@ fn main() { // index can't overflow the OS main thread either. const STACK_SIZE: usize = 32 * 1024 * 1024; - let rt = tokio::runtime::Builder::new_multi_thread() + // Parsed before any thread pool exists, because the pools are sized from + // it (issue #29). `--help` and argument errors exit here. + let args = Args::parse(); + let budget = ThreadBudget::new(args.requested_threads()); + codegraph_memory::set_onnx_threads(budget.compute); + + let mut builder = tokio::runtime::Builder::new_multi_thread(); + if let Some(workers) = budget.tokio { + builder.worker_threads(workers); + } + let rt = builder .enable_all() .thread_stack_size(STACK_SIZE) .build() @@ -354,13 +419,14 @@ fn main() { std::thread::Builder::new() .name("cg-main".into()) .stack_size(STACK_SIZE) - .spawn(move || rt.block_on(run())) + .spawn(move || rt.block_on(run(args, budget))) .expect("Failed to spawn main worker thread") .join() .expect("main worker thread panicked"); } -async fn run() { +async fn run(args: Args, budget: ThreadBudget) { + let compute_threads = budget.compute; install_crash_handlers(); codegraph_server::crash_phase::mark("startup"); // Clean up after processes that were killed before they could clear their @@ -368,8 +434,6 @@ async fn run() { // own mark so this process's marker is never a candidate. codegraph_server::crash_phase::sweep_orphans(); - let args = Args::parse(); - if args.info { codegraph_server::metadata::print_metadata(); return; @@ -390,6 +454,7 @@ async fn run() { ) .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr)) .init(); + tracing::info!("Compute threads: {compute_threads}"); // Thin MCP client (Model B): relay this process's stdio to a running engine. // No indexing, no model. Handled before the global signal hook; it exits @@ -409,6 +474,21 @@ async fn run() { return; } + // Rayon's global pool spawns its workers as soon as it is built, so it is + // built here - after every path that does no compute work has returned. + // The relay above forwards stdio to another engine and `--info` prints + // metadata; neither parses, indexes or embeds, and a pool per attached + // client is pure overhead. Everything below this point does compute work, + // and nothing above it touches rayon, so the pool is always in place + // before its first use. + if let Some(threads) = budget.rayon { + // Fails only if a global pool already exists, which nothing before + // this point creates. + let _ = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build_global(); + } + // Background watcher daemon. It owns its own signal handling and clean // shutdown (final persist + heartbeat removal), so it runs BEFORE the global // process::exit signal hook below — which would otherwise abort mid-flush. @@ -711,6 +791,14 @@ mod engine_args_tests { assert_eq!(excludes, ["cache", "generated"]); } + /// A thread cap set on the client must bound the engine it starts, since + /// that engine is where the embedding work runs (issue #29). + #[test] + fn a_requested_thread_cap_reaches_an_auto_spawned_engine() { + let got = forwarded(&["--connect", "--max-threads", "3"]); + assert!(got.chunks(2).any(|p| p == ["--max-threads", "3"])); + } + /// Both settings are part of the vector stamp. An engine started without /// them would stamp its vectors differently from the client that started /// it, and that client would then load none of them. @@ -738,3 +826,34 @@ mod engine_args_tests { assert!(!got.iter().any(|a| a == "--graph-only")); } } + +#[cfg(test)] +mod thread_budget_tests { + use super::ThreadBudget; + + #[test] + fn a_requested_cap_sizes_every_pool() { + let budget = ThreadBudget::new(Some(3)); + assert_eq!(budget.compute, 3); + assert_eq!(budget.rayon, Some(3)); + assert_eq!(budget.tokio, Some(3)); + } + + /// Embedding holds a runtime worker for a whole batch; with only one, + /// every request would wait behind it. + #[test] + fn the_runtime_keeps_two_workers_under_a_cap_of_one() { + let budget = ThreadBudget::new(Some(1)); + assert_eq!(budget.compute, 1); + assert_eq!(budget.rayon, Some(1)); + assert_eq!(budget.tokio, Some(2)); + } + + #[test] + fn without_a_cap_compute_uses_the_default_budget() { + assert_eq!( + ThreadBudget::new(None).compute, + codegraph_memory::default_thread_budget() + ); + } +} diff --git a/jetbrains/build.gradle.kts b/jetbrains/build.gradle.kts index 0a1bb79..607277b 100644 --- a/jetbrains/build.gradle.kts +++ b/jetbrains/build.gradle.kts @@ -60,7 +60,7 @@ kotlin { intellijPlatform { pluginConfiguration { id = "ai.codegraph.jetbrains" - name = "CodeGraph" + name = "CodeGraph AI" version = providers.gradleProperty("pluginVersion") vendor { name = "Andrey Vasilevsky" diff --git a/mcp-package/README.md b/mcp-package/README.md index 50d2494..0e966b2 100644 --- a/mcp-package/README.md +++ b/mcp-package/README.md @@ -77,6 +77,7 @@ whatever the client passes rather than forwarded twice. | `--exclude ` | — | Directories to skip (repeatable) | | `--embedding-model ` | `bge-small` | `bge-small`, `jina-code-v2`, `granite-97m` (32K, multilingual), or `static` (model2vec, ~100× faster indexing, ~90% of BGE quality; needs a local model dir - this install downloads one to `~/.codegraph/static_models/jina-code-static-256`, or point `CODEGRAPH_STATIC_MODEL` elsewhere) | | `--max-files ` | 5000 | Maximum files to index | +| `--max-threads ` | half the CPUs | Most threads the engine computes on (embedding model, tokenizer, async runtime). Also read from `CODEGRAPH_MAX_THREADS` | | `--profile ` | `all` | Scope tool surface: `core` (8), `graph` (17), `memory` (14), `security` (pro), `all` (42) | | `--graph-only` | off | Skip embeddings — graph + structural tools only. No ONNX model load, 10-50× faster indexing. For CI / one-shot graph queries. | | `--run-tool ` | — | One-shot: index, run a single tool, print result, exit. No MCP handshake. Pair with `--tool-args ''`. | diff --git a/mcp-package/bin/fetch-engine.js b/mcp-package/bin/fetch-engine.js index a630c06..a3c80e3 100644 --- a/mcp-package/bin/fetch-engine.js +++ b/mcp-package/bin/fetch-engine.js @@ -197,7 +197,63 @@ function requiredAssets(platform = os.platform(), arch = os.arch()) { return PLATFORM_MAP[platform] === "win32" ? [binary, WINDOWS_SIDECAR] : [binary]; } -function download(url, destination, { redirects = 5 } = {}) { +/** + * How long a request may go without making progress before it is abandoned. + * + * Neither transport gives up on its own. A request that never gets a socket - a + * proxy resolver that never answers, which VS Code's patched agent can do - or + * a transfer whose server stops sending mid-body waits forever, and with the + * download now automatic that is an engine update that silently never finishes + * and never retries. The socket's own timeout cannot cover the first case, + * because it is armed only once a socket connects. + * + * This bounds silence, not total time: the engine is ~120 MB and a slow link + * that keeps delivering bytes must be allowed to finish. + */ +const STALL_TIMEOUT_MS = 60_000; + +/** + * Abort `request` with `fail` once it has gone `ms` without `touch()`. + * + * Settling latches the guard, because the body does not stop arriving just + * because the caller is done with it: a settle that only cleared the timer + * would see the next chunk arm a fresh one and hold an otherwise finished + * process alive for another `ms`. `stop()` settles a transfer whose bytes the + * caller already has; `abort()` settles one that failed, and hangs up so the + * rest of the body stops arriving at all. + */ +function stallGuard(url, ms, fail) { + let timer = null; + let request = null; + let settled = false; + const settle = (hangUp) => { + settled = true; + clearTimeout(timer); + if (hangUp && request) request.destroy(); + }; + const touch = () => { + if (settled) return; + clearTimeout(timer); + timer = setTimeout( + () => fail(new Error(`no progress for ${ms / 1000}s fetching ${url}`)), + ms + ); + }; + return { + watch(req) { + request = req; + touch(); + return req; + }, + touch, + stop: () => settle(false), + abort: () => settle(true), + }; +} + +function download(url, destination, options = {}) { + const redirects = options.redirects === undefined ? 5 : options.redirects; + const stallMs = options.stallTimeoutMs || STALL_TIMEOUT_MS; return new Promise((resolve, reject) => { if (redirects < 0) return reject(new Error(`too many redirects for ${url}`)); let file = null; @@ -210,62 +266,91 @@ function download(url, destination, { redirects = 5 } = {}) { * file with a live handle on it cannot be unlinked on Windows. */ const fail = (error) => { + guard.abort(); if (file) file.destroy(); reject(error); }; - transportFor(url) - .get(url, { headers: { "User-Agent": "codegraph-installer" } }, (res) => { - // GitHub release assets always redirect to object storage. - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); - let next; - try { - next = redirectTarget(url, res.headers.location); - } catch (error) { - return fail(error); + const done = (value) => { + guard.stop(); + resolve(value); + }; + const guard = stallGuard(url, stallMs, fail); + guard.watch( + transportFor(url) + .get(url, { headers: { "User-Agent": "codegraph-installer" } }, (res) => { + guard.touch(); + // GitHub release assets always redirect to object storage. + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + let next; + try { + next = redirectTarget(url, res.headers.location); + } catch (error) { + return fail(error); + } + guard.abort(); + return resolve( + download(next, destination, { ...options, redirects: redirects - 1 }) + ); + } + if (res.statusCode !== 200) { + res.resume(); + return fail(new Error(`HTTP ${res.statusCode} for ${url}`)); } - return resolve(download(next, destination, { redirects: redirects - 1 })); - } - if (res.statusCode !== 200) { - res.resume(); - return reject(new Error(`HTTP ${res.statusCode} for ${url}`)); - } - file = fs.createWriteStream(destination); - res.on("error", fail); - file.on("error", fail); - file.on("finish", () => file.close(resolve)); - res.pipe(file); - }) - .on("error", fail); + file = fs.createWriteStream(destination); + res.on("data", guard.touch); + res.on("error", fail); + file.on("error", fail); + file.on("finish", () => file.close(() => done())); + res.pipe(file); + }) + .on("error", fail) + ); }); } function readText(url, options = {}) { const redirects = options.redirects === undefined ? 5 : options.redirects; + const stallMs = options.stallTimeoutMs || STALL_TIMEOUT_MS; return new Promise((resolve, reject) => { if (redirects < 0) return reject(new Error(`too many redirects for ${url}`)); - transportFor(url) - .get(url, { headers: { "User-Agent": "codegraph-installer" } }, (res) => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); - let next; - try { - next = redirectTarget(url, res.headers.location); - } catch (error) { - return reject(error); + const fail = (error) => { + guard.abort(); + reject(error); + }; + const done = (value) => { + guard.stop(); + resolve(value); + }; + const guard = stallGuard(url, stallMs, fail); + guard.watch( + transportFor(url) + .get(url, { headers: { "User-Agent": "codegraph-installer" } }, (res) => { + guard.touch(); + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + let next; + try { + next = redirectTarget(url, res.headers.location); + } catch (error) { + return fail(error); + } + guard.abort(); + return resolve(readText(next, { ...options, redirects: redirects - 1 })); } - return resolve(readText(next, { redirects: redirects - 1 })); - } - if (res.statusCode !== 200) { - res.resume(); - return reject(new Error(`HTTP ${res.statusCode} for ${url}`)); - } - let body = ""; - res.setEncoding("utf8"); - res.on("data", (chunk) => (body += chunk)); - res.on("end", () => resolve(body)); - }) - .on("error", reject); + if (res.statusCode !== 200) { + res.resume(); + return fail(new Error(`HTTP ${res.statusCode} for ${url}`)); + } + let body = ""; + res.setEncoding("utf8"); + res.on("data", (chunk) => { + guard.touch(); + body += chunk; + }); + res.on("error", fail); + res.on("end", () => done(body)); + }) + .on("error", fail) + ); }); } @@ -291,14 +376,23 @@ function sha256(file) { * `.partial` file, producing a spurious checksum failure or - worse - promoting * a half-written engine into place. */ -async function stageVerified(asset, version, targetDir, { baseUrl = RELEASE_BASE } = {}) { +async function stageVerified( + asset, + version, + targetDir, + { baseUrl = RELEASE_BASE, stallTimeoutMs } = {} +) { const assetUrl = `${baseUrl}/v${version}/${asset}`; - const expected = (await readText(`${assetUrl}.sha256`)).trim().split(/\s+/)[0].toLowerCase(); + const transfer = { stallTimeoutMs }; + const expected = (await readText(`${assetUrl}.sha256`, transfer)) + .trim() + .split(/\s+/)[0] + .toLowerCase(); const stamp = `${process.pid}.${crypto.randomBytes(6).toString("hex")}`; const staged = path.join(targetDir, `.${asset}.${stamp}.partial`); try { - await download(assetUrl, staged); + await download(assetUrl, staged, transfer); const actual = await sha256(staged); if (actual.toLowerCase() !== expected) { throw new Error( diff --git a/mcp-package/test/fetch-engine.test.js b/mcp-package/test/fetch-engine.test.js index f1cfe91..20d3dd8 100644 --- a/mcp-package/test/fetch-engine.test.js +++ b/mcp-package/test/fetch-engine.test.js @@ -290,6 +290,216 @@ async function run() { } } + // --- a transfer that stops making progress ---------------------------- + // Neither transport times out on its own, so a server (or a proxy) that + // goes quiet used to hang the update forever. Silence must reject and leave + // nothing behind; a slow transfer that keeps delivering must still finish, + // even when it takes far longer than the stall window in total. + { + const name = platformBinaryName(); + const content = "engine-".repeat(8); + const digest = crypto.createHash("sha256").update(content).digest("hex"); + const stallTimeoutMs = 300; + // The slow case gets a wider window and ticks at a tenth of it, so a + // scheduling hiccup on a loaded machine cannot be mistaken for silence + // while the transfer still takes several windows in total. + const slowStallTimeoutMs = 500; + const cases = [ + { label: "no response at all", serveBinary: () => {} }, + { + label: "headers, then silence", + serveBinary: (res) => { + res.writeHead(200, { "Content-Length": content.length }); + res.write(content.slice(0, 4)); + }, + }, + { + label: "a slow transfer that keeps delivering", + slow: true, + stallTimeoutMs: slowStallTimeoutMs, + serveBinary: (res) => { + res.writeHead(200, { "Content-Length": content.length }); + let sent = 0; + const tick = setInterval(() => { + res.write(content.slice(sent, sent + 2)); + sent += 2; + if (sent >= content.length) { + clearInterval(tick); + res.end(); + } + }, slowStallTimeoutMs / 10); + }, + }, + ]; + for (const { + label, + serveBinary, + slow = false, + stallTimeoutMs: caseStallMs = stallTimeoutMs, + } of cases) { + const dir = scratch(); + const server = http.createServer((req, res) => { + if (req.url.endsWith(".sha256")) { + res.writeHead(200); + res.end(`${digest} ${name}\n`); + return; + } + serveBinary(res); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + try { + const started = Date.now(); + let threw = null; + await ensureEngine(VERSION, dir, { + baseUrl, + stallTimeoutMs: caseStallMs, + // The sidecar is not under test; serve every asset the same way. + platform: "linux", + arch: "x64", + }).catch((e) => (threw = e)); + const elapsed = Date.now() - started; + if (slow) { + check(threw === null, `${label}: completes${threw ? ` (${threw.message})` : ""}`); + check(elapsed > caseStallMs * 2, `${label}: outlasts the stall window in total`); + } else { + check(threw !== null && /no progress/.test(threw.message), `${label}: rejects as stalled`); + check(elapsed < caseStallMs * 10, `${label}: gives up promptly (${elapsed} ms)`); + check(fs.readdirSync(dir).length === 0, `${label}: leaves nothing behind`); + } + } finally { + server.closeAllConnections(); + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } + } + } + + // --- a failed transfer hangs up --------------------------------------- + // The body does not stop arriving just because the download failed. While + // the response keeps flowing, a settle that only disarmed the stall timer + // let the next chunk arm a fresh one, so the rest of a ~120 MB transfer + // still arrived and the process stayed alive for another stall window after + // an install that had already failed - inside an npm postinstall, a hang. + { + const dir = scratch(); + const name = platformBinaryName(); + const stallTimeoutMs = 300; + const digest = crypto.createHash("sha256").update("engine").digest("hex"); + let closedAt = null; + const server = http.createServer((req, res) => { + if (req.url.endsWith(".sha256")) { + res.writeHead(200); + res.end(`${digest} ${name}\n`); + return; + } + // Promise far more than the client will take and keep delivering it: + // only the client hanging up can end this transfer. + res.writeHead(200, { "Content-Length": 1 << 20 }); + const tick = setInterval(() => res.write("engine"), stallTimeoutMs / 10); + res.on("close", () => { + clearInterval(tick); + if (closedAt === null) closedAt = Date.now(); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + // A staged file that cannot be opened is the reachable form of a failure + // that arrives mid-body: the write stream errors while bytes keep coming. + fs.chmodSync(dir, 0o500); + let readOnly = false; + try { + fs.accessSync(dir, fs.constants.W_OK); + } catch { + readOnly = true; + } + try { + if (!readOnly) { + console.log("SKIP a failed transfer hangs up (cannot make a directory read-only here)"); + } else { + let threw = null; + await ensureEngine(VERSION, dir, { + baseUrl, + stallTimeoutMs, + platform: "linux", + arch: "x64", + }).catch((e) => (threw = e)); + const failedAt = Date.now(); + check(threw !== null, "an unwritable staging directory fails the install"); + const deadline = failedAt + stallTimeoutMs * 3; + while (closedAt === null && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + check( + closedAt !== null && closedAt - failedAt < stallTimeoutMs, + `a failed transfer hangs up at once (${closedAt === null ? "still connected" : `${closedAt - failedAt} ms`})` + ); + } + } finally { + fs.chmodSync(dir, 0o700); + server.closeAllConnections(); + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } + } + + // --- a redirect hangs up too ------------------------------------------ + // A redirect's own body is never read, but it still arrives. Settling the + // redirect without hanging up leaves a response open with nothing watching + // it, which keeps an npm postinstall alive after a successful install. + { + const dir = scratch(); + const name = platformBinaryName(); + const stallTimeoutMs = 300; + const digest = crypto.createHash("sha256").update("engine").digest("hex"); + let redirectsOpen = 0; + const server = http.createServer((req, res) => { + if (req.url.startsWith("/objects")) { + const body = req.url.endsWith(".sha256") ? `${digest} ${name}\n` : "engine"; + res.writeHead(200, { "Content-Length": Buffer.byteLength(body) }); + res.end(body); + return; + } + // Promise a redirect body far larger than it ever delivers: only the + // client hanging up can end this response. + res.writeHead(302, { + Location: `/objects${req.url}`, + "Content-Length": 1 << 20, + }); + redirectsOpen++; + const tick = setInterval(() => res.write("redirect"), stallTimeoutMs / 10); + res.on("close", () => { + clearInterval(tick); + redirectsOpen--; + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + try { + let threw = null; + await ensureEngine(VERSION, dir, { + baseUrl, + stallTimeoutMs, + platform: "linux", + arch: "x64", + }).catch((e) => (threw = e)); + check(threw === null, "an install behind a stalling redirect still completes"); + const installedAt = Date.now(); + const deadline = installedAt + stallTimeoutMs * 3; + while (redirectsOpen > 0 && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + check( + redirectsOpen === 0 && Date.now() - installedAt < stallTimeoutMs, + `a followed redirect hangs up at once (${redirectsOpen} left open)` + ); + } finally { + server.closeAllConnections(); + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } + } + // --- nothing is installed until everything is verified ---------------- // Installing each asset as its download finishes is how a Windows install // ends up with a new engine beside the old onnxruntime.dll: that combination diff --git a/vscode/README.md b/vscode/README.md index a960c3a..9f1569c 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -30,12 +30,13 @@ The server indexes the current working directory automatically. Install from the marketplace, or sideload the VSIX: ```bash -code --install-extension codegraph-0.21.0.vsix +code --install-extension codegraph-0.21.1.vsix ``` One VSIX serves every platform. -The analysis engine is not bundled: on first activation the extension offers to download the engine built for your platform, verifies it against the published checksum, and installs it into `~/.codegraph/bin`. -The download is offered rather than performed automatically, because it is a native binary that runs with your permissions - decline it and run **CodeGraph: Download Analysis Engine** from the command palette whenever you are ready. +The analysis engine is not bundled: on first activation the extension downloads the engine built for your platform from this project's GitHub release, verifies it against the published checksum, and installs it into `~/.codegraph/bin`. +When the installed engine is older than the release the extension expects, it is updated the same way, and a failed automatic update is not retried for that version for a day. +If a download fails, run **CodeGraph: Download Analysis Engine** from the command palette to try again. Once an engine is present, the extension starts it automatically and registers all tools as Language Model Tools for Copilot. CodeGraph's Symbols and Memories views live in the CodeGraph activity-bar container, and inline CodeLens above each function reports callers, related tests and complexity (`codegraph.codeLens.enabled` / `codegraph.hover.enabled` turn those off). @@ -58,6 +59,7 @@ The engine's command-line flags (`--workspace`, `--exclude`, `--embedding-model` "codegraph.embeddingModel": "bge-small", // or "static" for ~100× faster indexing "codegraph.staticModelPath": "", // only to override the default model2vec model dir "codegraph.maxFileSizeKB": 1024, + "codegraph.maxThreads": 0, // CPU threads for indexing and embeddings; 0 = half the CPUs "codegraph.codeLens.enabled": true, // caller / test / complexity counts above functions "codegraph.hover.enabled": true, // the same stats on hover "codegraph.debug": false diff --git a/vscode/package.json b/vscode/package.json index 03c8d15..bf2ff4a 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -2,7 +2,7 @@ "name": "codegraph", "displayName": "CodeGraph", "description": "Cross-language code intelligence powered by graph analysis", - "version": "0.21.0", + "version": "0.21.1", "publisher": "aStudioPlus", "author": "Andrey Vasilevsky ", "license": "Apache-2.0", @@ -314,6 +314,13 @@ "scope": "resource", "description": "Directory of the model2vec static model (config.json + tokenizer.json + model.safetensors). Only set this to use a model outside the default location: left empty, the engine resolves ~/.codegraph/static_models/jina-code-static-256, which is where installing @astudioplus/codegraph-mcp from npm puts it. The model is not bundled with the extension - distill one with scripts/distill_static_model.py if you have neither." }, + "codegraph.maxThreads": { + "type": "integer", + "default": 0, + "minimum": 0, + "scope": "machine", + "markdownDescription": "Most CPU threads the engine uses for indexing and embeddings. `0` uses half the logical CPUs. Lower it to keep the machine responsive while a large workspace embeds, raise it to embed faster. Takes effect after the window is reloaded." + }, "codegraph.fullBodyEmbedding": { "type": "boolean", "default": true, diff --git a/vscode/src/engineDownload.test.ts b/vscode/src/engineDownload.test.ts new file mode 100644 index 0000000..e99caac --- /dev/null +++ b/vscode/src/engineDownload.test.ts @@ -0,0 +1,208 @@ +// Copyright 2026 Andrey Vasilevsky +// SPDX-License-Identifier: Apache-2.0 + +import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + window: { + withProgress: vi.fn(), + showWarningMessage: vi.fn(), + showErrorMessage: vi.fn(), + }, + commands: { executeCommand: vi.fn() }, + engine: { + ENGINE_VERSION: '0.21.0', + ensureEngine: vi.fn(), + isStale: vi.fn(), + platformBinaryName: vi.fn(), + }, +})); + +vi.mock('vscode', () => ({ + window: mocks.window, + commands: mocks.commands, + ProgressLocation: { Notification: 15 }, +})); + +// The engine is only ever looked for, never read, and the install directory +// belongs to the developer running the suite. +vi.mock('fs', () => ({ existsSync: () => true })); + +let engineDownload: typeof import('./engineDownload'); + +beforeAll(async () => { + // The module under test reaches the shared fetcher through `require`, which + // keeps the npm package and the extension on one implementation but leaves + // it outside the module graph Vitest can mock. Node's own cache is where + // that `require` looks, so a fake release lives there. + const { createRequire } = await import('node:module'); + const require_ = createRequire(import.meta.url); + const fetcher = require_.resolve('../../mcp-package/bin/fetch-engine.js'); + require_.cache[fetcher] = { + id: fetcher, + filename: fetcher, + loaded: true, + exports: mocks.engine, + } as unknown as NodeJS.Module; + engineDownload = await import('./engineDownload'); +}); + +describe('shouldSkipAutomaticUpdate', () => { + const now = 1_000_000_000_000; + + it('attempts the update when no earlier failure is recorded', () => { + expect(engineDownload.shouldSkipAutomaticUpdate(undefined, '0.21.0', now)).toBe(false); + }); + + it('holds off a version that failed less than a day ago', () => { + const failure = { version: '0.21.0', at: now - engineDownload.UPDATE_RETRY_BACKOFF_MS + 1 }; + expect(engineDownload.shouldSkipAutomaticUpdate(failure, '0.21.0', now)).toBe(true); + }); + + it('tries the same version again once a day has passed', () => { + const failure = { version: '0.21.0', at: now - engineDownload.UPDATE_RETRY_BACKOFF_MS }; + expect(engineDownload.shouldSkipAutomaticUpdate(failure, '0.21.0', now)).toBe(false); + }); + + it('does not hold off a different version', () => { + const failure = { version: '0.20.0', at: now - 1 }; + expect(engineDownload.shouldSkipAutomaticUpdate(failure, '0.21.0', now)).toBe(false); + }); +}); + +const FAILURE_KEY = 'codegraph.engineUpdateFailure'; +const BINARY = '/home/u/.codegraph/bin/codegraph-server-linux-x64'; + +/** The globalState the extension records the last failed automatic update in. */ +function fakeState() { + const values = new Map(); + return { + values, + memento: { + get: (key: string) => values.get(key), + update: async (key: string, value: unknown) => { + if (value === undefined) { + values.delete(key); + } else { + values.set(key, value); + } + }, + } as unknown as Parameters[1], + }; +} + +/** An engine this window is running, whose `start` outcome the test chooses. */ +function fakeLifecycle(start: () => Promise) { + return { + isRunning: () => true, + stop: vi.fn(async () => { }), + start: vi.fn(start), + }; +} + +function warnings(): string[] { + return mocks.window.showWarningMessage.mock.calls.map((call) => String(call[0])); +} + +describe('an engine that is installed but will not start', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.window.withProgress.mockImplementation( + async ( + _options: unknown, + task: (progress: { report: () => void }) => Promise, + ) => task({ report: () => { } }), + ); + mocks.window.showWarningMessage.mockResolvedValue(undefined); + mocks.window.showErrorMessage.mockResolvedValue(undefined); + mocks.engine.platformBinaryName.mockReturnValue('codegraph-server-linux-x64'); + mocks.engine.isStale.mockReturnValue(true); + // A real install stops the running engine once every asset is verified. + mocks.engine.ensureEngine.mockImplementation( + async ( + _version: string, + _dir: string, + options: { beforeInstall?: () => Promise }, + ) => { + await options.beforeInstall?.(); + return { binary: BINARY, fetched: ['codegraph-server-linux-x64'] }; + }, + ); + }); + + it('is not recorded as a failed automatic update', async () => { + const state = fakeState(); + const lifecycle = fakeLifecycle(async () => { + throw new Error('exited with code 127'); + }); + + await engineDownload.updateEngineIfStale('0.21.0', state.memento, lifecycle); + + expect(lifecycle.start).toHaveBeenCalledOnce(); + expect(state.values.get(FAILURE_KEY)).toBeUndefined(); + expect(warnings()).toEqual([ + 'The CodeGraph engine was updated to 0.21.0 but did not start again: exited with code 127', + ]); + // No Update Now: the engine is updated, and updating it again would not + // start it. + expect(mocks.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('still reports the install to the caller of installEngine', async () => { + const lifecycle = fakeLifecycle(async () => { + throw new Error('exited with code 127'); + }); + + const result = await engineDownload.installEngine('0.21.0', lifecycle); + + expect(result).toEqual({ binary: BINARY, startFailed: true }); + expect(mocks.engine.ensureEngine).toHaveBeenCalledOnce(); + expect(mocks.window.showErrorMessage).not.toHaveBeenCalled(); + expect(warnings()).toEqual([ + 'The CodeGraph engine was updated to 0.21.0 but did not start again: exited with code 127', + ]); + }); + + it('reports a clean swap as an install that started', async () => { + const lifecycle = fakeLifecycle(async () => { }); + + const result = await engineDownload.installEngine('0.21.0', lifecycle); + + expect(result).toEqual({ binary: BINARY, startFailed: false }); + expect(warnings()).toEqual([]); + }); + + it('leaves a real download failure reported and backed off', async () => { + const state = fakeState(); + mocks.engine.ensureEngine.mockRejectedValue(new Error('socket hang up')); + const lifecycle = fakeLifecycle(async () => { }); + + await engineDownload.updateEngineIfStale('0.21.0', state.memento, lifecycle); + + expect(state.values.get(FAILURE_KEY)).toMatchObject({ version: '0.21.0' }); + expect(warnings()).toEqual([ + 'Could not update the CodeGraph engine to 0.21.0: socket hang up', + ]); + }); + + it('restarts the engine it stopped when the install itself fails', async () => { + const state = fakeState(); + mocks.engine.ensureEngine.mockImplementation( + async ( + _version: string, + _dir: string, + options: { beforeInstall?: () => Promise }, + ) => { + await options.beforeInstall?.(); + throw new Error('EBUSY'); + }, + ); + const lifecycle = fakeLifecycle(async () => { }); + + await engineDownload.updateEngineIfStale('0.21.0', state.memento, lifecycle); + + expect(lifecycle.stop).toHaveBeenCalledOnce(); + expect(lifecycle.start).toHaveBeenCalledOnce(); + expect(state.values.get(FAILURE_KEY)).toMatchObject({ version: '0.21.0' }); + }); +}); diff --git a/vscode/src/engineDownload.ts b/vscode/src/engineDownload.ts index 954ef19..7ead02c 100644 --- a/vscode/src/engineDownload.ts +++ b/vscode/src/engineDownload.ts @@ -57,8 +57,93 @@ export interface EngineLifecycle { start(): Promise; } -/** globalState key holding the engine version whose update offer was declined. */ -const UPDATE_DECLINED_KEY = 'codegraph.engineUpdateDeclined'; +/** globalState key holding the last failed automatic update, as an `UpdateFailure`. */ +const UPDATE_FAILURE_KEY = 'codegraph.engineUpdateFailure'; + +/** How long a failed automatic update of one engine version holds off the next attempt. */ +export const UPDATE_RETRY_BACKOFF_MS = 24 * 60 * 60 * 1000; + +/** The engine version an automatic update last failed to install, and when. */ +export interface UpdateFailure { + version: string; + at: number; +} + +/** + * Whether the automatic update to [version] should wait out an earlier failure. + * + * Each attempt is a full ~120 MB transfer plus an engine stop and restart, and + * the commonest failure - another window or an MCP client holding the binary - + * outlasts many window activations. Only a failure of the same version counts: + * a newer release deserves its own attempt straight away. + */ +export function shouldSkipAutomaticUpdate( + failure: UpdateFailure | undefined, + version: string, + now: number, +): boolean { + return failure?.version === version && now - failure.at < UPDATE_RETRY_BACKOFF_MS; +} + +/** Forget a failed automatic update, once the engine has been installed some other way. */ +export async function clearUpdateFailure(state: vscode.Memento): Promise { + if (state.get(UPDATE_FAILURE_KEY)) { + await state.update(UPDATE_FAILURE_KEY, undefined); + } +} + +/** + * Stops a running engine at the last moment before its binary is replaced, and + * restarts it afterwards whichever way the install ended. + * + * The engine holds its own binary open, so it is stopped once every asset is + * downloaded and verified - stopping it for the length of a transfer that may + * fail costs the user a working engine for nothing. + */ +function engineSwap(lifecycle: EngineLifecycle | undefined) { + let stopped = false; + return { + beforeInstall: async () => { + if (!stopped && lifecycle?.isRunning()) { + stopped = true; + await lifecycle.stop(); + } + }, + restart: async () => { + if (stopped && lifecycle) { + stopped = false; + await lifecycle.start(); + } + }, + }; +} + +/** + * Start the engine again once its binary has been replaced. + * + * The install is already done by this point, so a start failure is an outcome + * of its own: reported as a failed update it would hold off this version's + * automatic attempt for a day over an engine that is in fact installed, and + * reported as a failed download it sends the user to debug a transfer that + * worked. Nor may it propagate - the caller still has an installed engine to + * record. Returns true when the engine was replaced but will not run, so the + * caller does not also report the install as a plain success. + */ +async function restartAfterInstall( + swap: ReturnType, + version: string, +): Promise { + try { + await swap.restart(); + return false; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + void vscode.window.showWarningMessage( + `The CodeGraph engine was updated to ${version} but did not start again: ${message}`, + ); + return true; + } +} /** The engine asset for this platform, or null when none is published. */ export function platformBinaryName(): string | null { @@ -75,9 +160,11 @@ export function managedEnginePath(): string | null { * Download the engine for [version], reporting progress in the notification * area. * - * Offered rather than automatic: this pulls a native binary that runs with the - * user's permissions, and doing that unasked on first activation is not the - * extension's decision to make. + * Automatic, not offered. 0.21.0 asked first, and 73% of the users it reached by + * auto-update from 0.19.1 - which bundled the engine - ended without one: the + * prompt is a toast, and a toast that is dismissed or never seen reads as "no". + * Installing the extension is the consent; the binary comes from this project's + * own release and is checksum-verified, exactly as the npm postinstall does. */ export async function downloadEngine( version: string, @@ -100,29 +187,31 @@ export async function downloadEngine( } /** - * Offer to replace a managed engine that predates this extension release. + * Replace a managed engine that predates this extension release. * * The managed engine is resolved by filename, so without this an engine left * behind by a previous release is found and reused indefinitely and a client * built against a newer engine keeps talking to the old one. * - * Offered rather than done, for the same reason `downloadEngine` is: this is - * ~120 MB of native binary that will run with the user's permissions. It is also - * deliberately not awaited by the caller - the engine on disk still works, so - * blocking activation behind a transfer would cost every surface the extension - * provides for an update that is not urgent. + * Automatic, like the first download (see `downloadEngine`), and deliberately + * not awaited by the caller: the engine on disk still works, so blocking + * activation behind a transfer would cost every surface the extension provides + * for an update that is not urgent. * * Only an *older* engine counts. `~/.codegraph/bin` is shared with the CLI and * the JetBrains plugin, which ship on their own schedules; treating a newer * engine as a mismatch would have the two clients reinstall over each other on * every launch. * - * A decline is remembered. Activation happens once per window, so without that - * a user with three windows open gets three toasts for the same drift, on every - * launch until they give in; recording the version they declined lets the offer - * come back on the next engine release and not before. + * A failure is reported once per engine version and holds off further + * automatic attempts at that version for a day (see + * `shouldSkipAutomaticUpdate`). Activation happens once per window, and the + * commonest failure - another window or an MCP client still running the old + * binary - repeats until those close, so warning or re-downloading on every + * window would be noise. The warning's Update Now action runs the + * `codegraph.downloadEngine` command, which is not held off. */ -export async function offerEngineUpdateIfStale( +export async function updateEngineIfStale( version: string, state: vscode.Memento, lifecycle?: EngineLifecycle, @@ -134,62 +223,44 @@ export async function offerEngineUpdateIfStale( if (!fetchEngine.isStale(managedInstallDir(), version)) { return; } - if (state.get(UPDATE_DECLINED_KEY) === version) { - return; - } - - const installed = fetchEngine.installedVersion(managedInstallDir()) ?? 'an unknown version'; - const choice = await vscode.window.showInformationMessage( - `The installed CodeGraph engine (${installed}) predates the one this extension ships ` + - `against (${version}). They ship together, so features this build expects may be missing.`, - 'Update', - 'Not Now', - ); - if (choice !== 'Update') { - await state.update(UPDATE_DECLINED_KEY, version); + const previousFailure = state.get(UPDATE_FAILURE_KEY); + if (shouldSkipAutomaticUpdate(previousFailure, version, Date.now())) { return; } - // The engine holds its own binary open, so it is stopped once every asset - // is downloaded and verified - the last possible moment, since stopping it - // for the length of a transfer that may fail costs the user a working - // engine for nothing - and started again whichever way the install ends. - let stopped = false; - const beforeInstall = async () => { - if (lifecycle?.isRunning()) { - stopped = true; - await lifecycle.stop(); - } - }; - + const swap = engineSwap(lifecycle); try { - await downloadEngine(version, { beforeInstall }); - if (stopped && lifecycle) { - await lifecycle.start(); - } - vscode.window.showInformationMessage( - stopped - ? `CodeGraph engine ${version} installed and restarted.` - : `CodeGraph engine ${version} installed. It takes effect the next time the engine starts.`, - ); + await downloadEngine(version, { beforeInstall: swap.beforeInstall }); } catch (error) { - if (stopped && lifecycle) { - // A failed update must not leave the user without an engine: the - // binary on disk is still the one that was running. - await lifecycle.start().catch(() => { }); + // A failed update must not leave the user without an engine: the + // binary on disk is still the one that was running. + await swap.restart().catch(() => { }); + await state.update(UPDATE_FAILURE_KEY, { version, at: Date.now() } satisfies UpdateFailure); + if (previousFailure?.version === version) { + return; } const message = error instanceof Error ? error.message : String(error); // Not fatal: the engine already on disk still runs, and losing a working // install over one version of drift is worse than the drift. "In use" // gets its own wording because it is the one failure the user can act // on, and reading it as a network problem sends them somewhere useless. - vscode.window.showWarningMessage( - isEngineInUse(error) - ? `The CodeGraph engine could not be replaced because it is still running. ` + - `Close other windows or editors using it, then reload this window to try again.` - : `Could not update the CodeGraph engine to ${version}: ${message}`, - ); + void vscode.window + .showWarningMessage( + isEngineInUse(error) + ? 'The CodeGraph engine could not be updated because it is still running. ' + + 'Close other windows or editors using it, then choose Update Now.' + : `Could not update the CodeGraph engine to ${version}: ${message}`, + 'Update Now', + ) + .then((choice) => { + if (choice === 'Update Now') { + void vscode.commands.executeCommand('codegraph.downloadEngine'); + } + }); + return; } + await clearUpdateFailure(state); + await restartAfterInstall(swap, version); } /** True for the "another process holds the binary" failure `fetch-engine.js` names. */ @@ -197,44 +268,82 @@ function isEngineInUse(error: unknown): boolean { return error instanceof Error && error.name === 'EngineInUseError'; } +/** Why the engine could not be installed; reported as `engine_` in telemetry. */ +export type EngineInstallFailure = 'unsupported_platform' | 'checksum' | 'in_use' | 'download'; + +export type EngineInstallResult = + | { binary: string; startFailed: boolean } + | { failure: EngineInstallFailure }; + +/** Waits between attempts; a transient network or proxy hiccup rarely outlasts the second. */ +const RETRY_DELAYS_MS = [2_000, 10_000]; + /** - * Ask whether to download, then do it. + * Install the engine for this platform, retrying transient failures. * - * Returns the engine path, or null if the user declined or it failed - callers - * treat that as "no engine", which is the same state they already handle. + * Never prompts first (see `downloadEngine`). A failure is shown with a Retry + * button but not awaited, so activation reports it and moves on instead of + * waiting on a toast the user may never answer. When [lifecycle] is given, an + * engine this window is running is stopped for the swap and started again. */ -export async function offerEngineDownload(version: string): Promise { +export async function installEngine( + version: string, + lifecycle?: EngineLifecycle, +): Promise { if (!platformBinaryName()) { - vscode.window.showErrorMessage( + void vscode.window.showErrorMessage( `CodeGraph does not publish an engine for ${os.platform()}-${os.arch()}. ` + 'Point the extension at your own build with the codegraph.serverPath setting.', ); - return null; + return { failure: 'unsupported_platform' }; } - const choice = await vscode.window.showInformationMessage( - 'CodeGraph needs its analysis engine, which is downloaded separately for your platform.', - 'Download', - 'Not Now', - ); - if (choice !== 'Download') { - return null; + const swap = engineSwap(lifecycle); + let attempts = 0; + let lastError: unknown; + for (;;) { + attempts++; + let binary: string; + try { + binary = await downloadEngine(version, { beforeInstall: swap.beforeInstall }); + } catch (error) { + await swap.restart().catch(() => { }); + lastError = error; + // Retrying cannot fix bytes that fail verification or a binary + // another process holds open. + if (isChecksumFailure(error) || isEngineInUse(error) || attempts > RETRY_DELAYS_MS.length) { + break; + } + await new Promise((resolve) => setTimeout(resolve, RETRY_DELAYS_MS[attempts - 1])); + continue; + } + const startFailed = await restartAfterInstall(swap, version); + return { binary, startFailed }; } - try { - const binary = await downloadEngine(version); - vscode.window.showInformationMessage('CodeGraph engine installed.'); - return binary; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - // A checksum failure is not a network failure, and saying so matters: - // one is worth retrying, the other means something served the wrong - // bytes. - vscode.window.showErrorMessage( - /checksum/i.test(message) - ? `The downloaded engine failed verification and was discarded: ${message}` + const message = lastError instanceof Error ? lastError.message : String(lastError); + const failure: EngineInstallFailure = isChecksumFailure(lastError) + ? 'checksum' + : isEngineInUse(lastError) + ? 'in_use' + : 'download'; + // A checksum failure is not a network failure, and saying so matters: one is + // worth retrying, the other means something served the wrong bytes. + void vscode.window + .showErrorMessage( + failure === 'checksum' + ? `The downloaded CodeGraph engine failed verification and was discarded: ${message}` : `Could not download the CodeGraph engine: ${message}`, - ); - return null; - } + 'Retry', + ) + .then((choice) => { + if (choice === 'Retry') { + void vscode.commands.executeCommand('codegraph.downloadEngine'); + } + }); + return { failure }; +} + +function isChecksumFailure(error: unknown): boolean { + return error instanceof Error && /checksum/i.test(error.message); } diff --git a/vscode/src/extension.engineSwap.test.ts b/vscode/src/extension.engineSwap.test.ts new file mode 100644 index 0000000..3318b61 --- /dev/null +++ b/vscode/src/extension.engineSwap.test.ts @@ -0,0 +1,331 @@ +// Copyright 2026 Andrey Vasilevsky +// SPDX-License-Identifier: Apache-2.0 + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import type { State as ClientState } from 'vscode-languageclient/node'; + +// Stands alone from `extension.test.ts`, which is quarantined on the lost +// `@vsforge` harness (see vitest.config.ts): the vscode surface activation +// touches is mocked locally so this suite actually runs. +const mocks = vi.hoisted(() => { + const disposable = { dispose: () => { } }; + const channel = { + appendLine: vi.fn(), + append: vi.fn(), + clear: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + }; + return { + // vscode-languageclient's public client states. The real module + // cannot be imported here (it requires the real `vscode`), so they + // are restated - and pinned to the enum itself at compile time + // below, because the numbering is not the order it reads. + State: { Stopped: 1, Running: 2, Starting: 3 } as const, + disposable, + channel, + // Every event the extension reports, keyed by method name. + reporterCalls: {} as Record, + // Listeners the extension registers for the language client's + // state changes. + stateListeners: [] as ((evt: { oldState: number; newState: number }) => void)[], + clientStart: vi.fn(async () => { }), + clientStop: vi.fn(async () => { }), + updateEngineIfStale: vi.fn(async () => { }), + installEngine: vi.fn(async () => ({ binary: '/mock/engine', startFailed: false })), + showInformationMessage: vi.fn(async (..._args: unknown[]) => undefined), + // Command handlers the extension registers, keyed by command id. + commandHandlers: {} as Record Promise>, + }; +}); + +type AssertTrue = T; +type _StatesPinnedToClient = [ + AssertTrue, + AssertTrue, + AssertTrue, +]; +const State = mocks.State; + +const emitState = (newState: number, oldState: number) => { + for (const listener of [...mocks.stateListeners]) { + listener({ oldState, newState }); + } +}; + +vi.mock('vscode', () => ({ + workspace: { + getConfiguration: () => ({ + get: (_key: string, fallback?: unknown) => fallback, + inspect: () => undefined, + }), + workspaceFolders: undefined, + createFileSystemWatcher: () => mocks.disposable, + onDidChangeConfiguration: () => mocks.disposable, + }, + window: { + createOutputChannel: () => mocks.channel, + createStatusBarItem: () => ({ + text: '', + tooltip: '', + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + }), + showInformationMessage: mocks.showInformationMessage, + showWarningMessage: vi.fn(async () => undefined), + showErrorMessage: vi.fn(async () => undefined), + withProgress: vi.fn(async (_opts: unknown, task: () => Promise) => task()), + }, + commands: { + registerCommand: (id: string, handler: () => Promise) => { + mocks.commandHandlers[id] = handler; + return mocks.disposable; + }, + executeCommand: vi.fn(async () => undefined), + }, + extensions: { getExtension: () => undefined }, + StatusBarAlignment: { Right: 2 }, + ProgressLocation: { Notification: 15 }, + version: '1.90.0', +})); + +vi.mock('vscode-languageclient/node', () => ({ + State: mocks.State, + LanguageClient: class { + start = mocks.clientStart; + stop = mocks.clientStop; + isRunning = () => true; + // `sendRequest` only serves the post-start "is it indexed?" probe. + sendRequest = async () => ({ results: [{}] }); + onDidChangeState = (listener: (evt: { oldState: number; newState: number }) => void) => { + mocks.stateListeners.push(listener); + return mocks.disposable; + }; + }, + LanguageClientOptions: vi.fn(), + ServerOptions: vi.fn(), + TransportKind: { stdio: 0 }, +})); + +vi.mock('./telemetry/reporter', () => { + const stub: Record Promise> = {}; + const proxy = new Proxy(stub, { + get(target, prop: string) { + if (!target[prop]) { + target[prop] = (...args: unknown[]) => { + (mocks.reporterCalls[prop] ||= []).push(args); + return Promise.resolve(); + }; + } + return target[prop]; + }, + }); + return { + createReporter: () => proxy, + setServerEdition: vi.fn(), + describeArgShape: vi.fn(() => 'none'), + }; +}); + +vi.mock('./telemetry/machineProfile', () => ({ + detectMachineProfile: vi.fn(async () => ({})), +})); +vi.mock('./engineDownload', () => ({ + clearUpdateFailure: vi.fn(async () => { }), + engineVersion: () => '0.21.0', + installEngine: mocks.installEngine, + managedEnginePath: () => '/mock/engine', + updateEngineIfStale: mocks.updateEngineIfStale, +})); +vi.mock('./server', () => ({ + getServerPath: () => ({ path: '/mock/engine', edition: 'community' }), + engineSpawnEnv: () => ({}), +})); +vi.mock('./commands', () => ({ registerCommands: vi.fn() })); +vi.mock('./views/treeProviders', () => ({ registerTreeDataProviders: vi.fn() })); +vi.mock('./views/codeLensProvider', () => ({ registerCodeLens: vi.fn() })); +vi.mock('./ai/contextProvider', () => ({ CodeGraphAIProvider: class { } })); +vi.mock('./ai/toolManager', () => ({ + CodeGraphToolManager: class { + registerTools() { } + }, +})); +vi.mock('./funnel', () => ({ + handleIndexOutcome: vi.fn(async () => 'none'), + filesIndexed: () => 0, + reportIndexTelemetry: vi.fn(), +})); +// Recovery breadcrumbs belong to the developer running the suite. +vi.mock('fs', () => ({ + readdirSync: () => [], + statSync: () => ({ mtimeMs: 0 }), + readFileSync: () => '{}', + unlinkSync: vi.fn(), + existsSync: () => true, +})); + +const context = { + subscriptions: [] as { dispose: () => void }[], + extensionPath: '/mock/extension', + extension: { packageJSON: { version: '0.21.1' } }, + globalState: { + get: vi.fn(() => undefined), + update: vi.fn(async () => { }), + keys: () => [], + }, +}; + +/** + * Run activation far enough to own a started engine, and hand back the + * lifecycle the engine swap drives it with. Activation is not awaited: it + * sleeps for seconds after this point waiting on the index probe, and the + * swap it hands to `updateEngineIfStale` is already live by then. + */ +async function activateAndCaptureLifecycle() { + const { activate } = await import('./extension'); + void activate(context as never).catch(() => { }); + // The state listener is registered after the client has started, which is + // the point activation owns a running engine. + await vi.waitFor(() => expect(mocks.stateListeners.length).toBeGreaterThan(0)); + const lifecycle = mocks.updateEngineIfStale.mock.calls.at(-1)?.[2]; + expect(lifecycle).toBeDefined(); + // Activation's own start is reported separately; the swap starts clean. + for (const key of Object.keys(mocks.reporterCalls)) delete mocks.reporterCalls[key]; + return lifecycle as { stop: () => Promise; start: () => Promise }; +} + +const infoMessages = (): string[] => + mocks.showInformationMessage.mock.calls.map((call) => String(call[0])); + +beforeEach(() => { + vi.clearAllMocks(); + context.subscriptions = []; + mocks.stateListeners = []; + mocks.clientStart.mockImplementation(async () => { }); + mocks.clientStop.mockImplementation(async () => { }); + mocks.installEngine.mockImplementation(async () => ({ + binary: '/mock/engine', + startFailed: false, + })); + for (const key of Object.keys(mocks.commandHandlers)) delete mocks.commandHandlers[key]; + for (const key of Object.keys(mocks.reporterCalls)) delete mocks.reporterCalls[key]; +}); + +afterEach(() => { + vi.resetModules(); +}); + +// An engine swap stops the running engine, installs the new binary and starts +// it again. None of that is a crash, so none of it may be reported as one - +// including the case the engine actually hits: the replacement binary will not +// run. vscode-languageclient reports a failed start as the public state +// Stopped, the very transition a real crash produces. +describe('engine swap crash telemetry', () => { + it('reports no crash when the swapped-in engine fails to start', async () => { + const lifecycle = await activateAndCaptureLifecycle(); + + await lifecycle.stop(); + emitState(State.Stopped, State.Running); + + // The real sequence: `client.start()` publishes Starting, then - when + // the binary will not run - StartFailed, whose public state is + // Stopped. Both arrive while start() is still awaited. + mocks.clientStart.mockImplementationOnce(async () => { + emitState(State.Starting, State.Stopped); + emitState(State.Stopped, State.Starting); + throw new Error('exec format error'); + }); + await expect(lifecycle.start()).rejects.toThrow('exec format error'); + + expect(mocks.reporterCalls.serverCrash ?? []).toHaveLength(0); + expect(mocks.reporterCalls.serverRestart ?? []).toHaveLength(0); + }); + + it('reports no crash when the swapped-in engine starts', async () => { + const lifecycle = await activateAndCaptureLifecycle(); + + await lifecycle.stop(); + emitState(State.Stopped, State.Running); + + mocks.clientStart.mockImplementationOnce(async () => { + emitState(State.Starting, State.Stopped); + emitState(State.Running, State.Starting); + }); + await lifecycle.start(); + + expect(mocks.reporterCalls.serverCrash ?? []).toHaveLength(0); + expect(mocks.reporterCalls.serverRestart ?? []).toHaveLength(0); + }); + + it('still reports an unexpected stop as a crash', async () => { + await activateAndCaptureLifecycle(); + + emitState(State.Stopped, State.Running); + + expect(mocks.reporterCalls.serverCrash ?? []).toHaveLength(1); + }); + + it('times a crash whose restart never reaches Running from that attempt', async () => { + await activateAndCaptureLifecycle(); + + let nowMs = Date.now(); + const clock = vi.spyOn(Date, 'now').mockImplementation(() => nowMs); + try { + nowMs += 600_000; + emitState(State.Stopped, State.Running); + + // The restart publishes Starting, then fails before Running. + emitState(State.Starting, State.Stopped); + nowMs += 2_000; + emitState(State.Stopped, State.Starting); + } finally { + clock.mockRestore(); + } + + const crashes = (mocks.reporterCalls.serverCrash ?? []) as [{ uptimeSeconds: number }][]; + expect(crashes).toHaveLength(2); + expect(crashes[0][0].uptimeSeconds).toBeCloseTo(600, 0); + expect(crashes[1][0].uptimeSeconds).toBe(2); + }); + + it('reports a crash restart only once the engine is running again', async () => { + await activateAndCaptureLifecycle(); + + emitState(State.Stopped, State.Running); + emitState(State.Starting, State.Stopped); + + expect(mocks.reporterCalls.serverRestart ?? []).toHaveLength(0); + + emitState(State.Running, State.Starting); + + expect(mocks.reporterCalls.serverRestart ?? []).toEqual([['crash']]); + }); +}); + +// The install and the restart are two outcomes. An engine that was replaced +// but will not run has already been warned about, and confirming the install +// after that warning is the difference between reloading the window and +// assuming all is well. +describe('codegraph.downloadEngine reporting', () => { + it('does not confirm an install whose engine failed to start', async () => { + await activateAndCaptureLifecycle(); + mocks.installEngine.mockImplementation(async () => ({ + binary: '/mock/engine', + startFailed: true, + })); + + await mocks.commandHandlers['codegraph.downloadEngine'](); + + expect(infoMessages()).not.toContain('CodeGraph engine installed.'); + }); + + it('confirms an install whose engine started', async () => { + await activateAndCaptureLifecycle(); + + await mocks.commandHandlers['codegraph.downloadEngine'](); + + expect(infoMessages()).toContain('CodeGraph engine installed.'); + }); +}); diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index bfce45a..cee5240 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -10,6 +10,7 @@ import { LanguageClient, LanguageClientOptions, ServerOptions, + State, } from 'vscode-languageclient/node'; import { registerCommands } from './commands'; import { registerTreeDataProviders } from './views/treeProviders'; @@ -17,7 +18,14 @@ import { registerCodeLens } from './views/codeLensProvider'; import { CodeGraphAIProvider } from './ai/contextProvider'; import { CodeGraphToolManager } from './ai/toolManager'; import { getServerPath, engineSpawnEnv } from './server'; -import { engineVersion, managedEnginePath, offerEngineDownload, offerEngineUpdateIfStale } from './engineDownload'; +import { + clearUpdateFailure, + EngineLifecycle, + engineVersion, + installEngine, + managedEnginePath, + updateEngineIfStale, +} from './engineDownload'; import { createReporter, setServerEdition, type Reporter } from './telemetry/reporter'; import { detectMachineProfile } from './telemetry/machineProfile'; import { handleIndexOutcome, filesIndexed, reportIndexTelemetry } from './funnel'; @@ -45,6 +53,10 @@ let rapidCrashTimestamps: number[] = []; // deactivate) so the onDidChangeState→Stopped that follows isn't logged // as a crash. Consume-once: the handler resets it after skipping. let expectedShutdown = false; +// Set for an intentional start (the engine swap) so the transition that follows +// isn't counted or reported as a crash restart - Running when the start +// succeeds, Stopped when it fails. Consume-once. +let expectedStart = false; /** * Read + classify the server's crash breadcrumb. The server's panic hook @@ -267,23 +279,46 @@ export async function activate(context: vscode.ExtensionContext): Promise return; } - // The one command registered before the engine is resolved, because - // declining the download below ends activation and nothing after it - - // commands, tree views, lenses - is ever contributed. Without this, a user - // who says "Not Now" and later changes their mind has no way back short of - // reloading the window and guessing that the prompt returns; the npm - // channel ships `codegraph-mcp-fetch-engine` for exactly that case. + // The one command registered before the engine is resolved, because a + // failed download below ends activation and nothing after it - commands, + // tree views, lenses - is ever contributed. It is what the failure toast's + // Retry button runs, and the way back for anyone who dismissed that toast; + // the npm channel ships `codegraph-mcp-fetch-engine` for the same case. // // Reloading is what puts a late download to use, so the command offers it - // but only when activation did stop early, since in a session that already - // has an engine running a reload prompt is noise. + // has an engine running a reload prompt is noise and a plain confirmation + // is all the user needs. + // The lifecycle callbacks read `client` lazily: the command and the update + // below both run long after activation has created and started it. + const engineLifecycle: EngineLifecycle = { + isRunning: () => client?.isRunning() ?? false, + stop: async () => { + expectedShutdown = true; + await client.stop(); + }, + start: async () => { + expectedStart = true; + try { + await client.start(); + } finally { + expectedShutdown = false; + expectedStart = false; + } + }, + }; context.subscriptions.push( vscode.commands.registerCommand('codegraph.downloadEngine', async () => { const activationStopped = !client; - if (!(await offerEngineDownload(engineVersion()))) { + const result = await installEngine(engineVersion(), engineLifecycle); + if (!('binary' in result)) { return; } + await clearUpdateFailure(context.globalState); if (!activationStopped) { + if (!result.startFailed) { + void vscode.window.showInformationMessage('CodeGraph engine installed.'); + } return; } const choice = await vscode.window.showInformationMessage( @@ -301,20 +336,21 @@ export async function activate(context: vscode.ExtensionContext): Promise // // The published VSIX no longer bundles engines: shipping all four platform // binaries meant a 118 MB download for the one a user can actually run. - // When none is found we offer to fetch this platform's engine, which is - // also where an npm- or JetBrains-installed engine gets picked up, since - // all three channels share ~/.codegraph/bin. + // When none is found we fetch this platform's engine, which is also where + // an npm- or JetBrains-installed engine gets picked up, since all three + // channels share ~/.codegraph/bin. let serverInfo: ReturnType; try { serverInfo = getServerPath(context); } catch { - const downloaded = await offerEngineDownload(engineVersion()); - if (!downloaded) { + const started = Date.now(); + const installed = await installEngine(engineVersion()); + if (!('binary' in installed)) { reporter.activationServerStartResult({ outcome: 'spawn_fail', - durationMs: 0, + durationMs: Date.now() - started, serverBinaryFound: false, - errorHint: 'engine_not_installed', + errorHint: `engine_${installed.failure}`, }); return; } @@ -323,21 +359,16 @@ export async function activate(context: vscode.ExtensionContext): Promise // The managed engine is found by filename alone, so one installed by an // earlier release would otherwise be reused forever. The extension and the - // engine ship in lockstep, so offer to bring it up to the engine release - // this build expects - only when it is the binary we actually resolved, + // engine ship in lockstep, so bring it up to the engine release this + // build expects - only when it is the binary we actually resolved, // since a pro, bundled or locally built engine is the user's to manage. // // Not awaited: the engine on disk still runs, and holding activation - and // with it the language client, the tree views and the lenses - behind a // ~120 MB transfer on a slow network is a far worse trade than one release of - // drift. The lifecycle callbacks read `client` lazily for the same reason: - // by the time the user answers the prompt it has been created and started. + // drift. if (serverInfo.path === managedEnginePath()) { - void offerEngineUpdateIfStale(engineVersion(), context.globalState, { - isRunning: () => client?.isRunning() ?? false, - stop: () => client.stop(), - start: () => client.start(), - }); + void updateEngineIfStale(engineVersion(), context.globalState, engineLifecycle); } setServerEdition(serverInfo.edition === 'pro' ? 'pro' : 'community'); @@ -483,11 +514,16 @@ export async function activate(context: vscode.ExtensionContext): Promise // Watch for unexpected server state changes — crashes fire here. context.subscriptions.push( client.onDidChangeState((evt) => { - // evt.newState: 1=Stopped, 2=Starting, 3=Running - if (evt.newState === 1 && serverUptimeStart > 0) { - // Intentional stop (crash-loop give-up / deactivate) — don't - // count it as a crash. Consume-once. - if (expectedShutdown) { + // `State` is not ordered the way it reads: Stopped=1, Running=2, + // Starting=3, and every internal state that is neither Starting + // nor Running - StartFailed included - reports as Stopped. + if (evt.newState === State.Stopped && serverUptimeStart > 0) { + // Intentional stop (crash-loop give-up / deactivate), or an + // intentional start that failed - vscode-languageclient's + // StartFailed reports its public state as Stopped, so a swap + // whose new binary will not run arrives here, not at Running. + // Neither is a crash. Consume-once. + if (expectedShutdown || expectedStart) { expectedShutdown = false; return; } @@ -542,9 +578,15 @@ export async function activate(context: vscode.ExtensionContext): Promise return; } } - if (evt.newState === 3 && serverUptimeStart > 0) { - serverRestartCount += 1; + if (evt.newState === State.Starting && serverUptimeStart > 0) { serverUptimeStart = Date.now(); + return; + } + if (evt.newState === State.Running && serverUptimeStart > 0) { + if (expectedStart) { + return; + } + serverRestartCount += 1; reporter.serverRestart('crash'); } }), diff --git a/vscode/src/server.spawnEnv.test.ts b/vscode/src/server.spawnEnv.test.ts index 553af06..e81d625 100644 --- a/vscode/src/server.spawnEnv.test.ts +++ b/vscode/src/server.spawnEnv.test.ts @@ -12,7 +12,7 @@ vi.mock('vscode', () => ({})); import { engineSpawnEnv } from './server'; /** Stands in for a `WorkspaceConfiguration` over the given settings. */ -function config(settings: Record) { +function config(settings: Record) { return { get: (key: string) => settings[key] as T | undefined }; } @@ -58,4 +58,24 @@ describe('engineSpawnEnv', () => { expect(env.CODEGRAPH_STATIC_MODEL).toBe('/from/the/users/shell'); }); + + it('caps the engine threads when codegraph.maxThreads is set', () => { + const env = engineSpawnEnv(config({ maxThreads: 4 }), {}); + + expect(env.CODEGRAPH_MAX_THREADS).toBe('4'); + }); + + it('leaves the engine default, or the users own cap, when maxThreads is 0', () => { + expect(engineSpawnEnv(config({ maxThreads: 0 }), {}).CODEGRAPH_MAX_THREADS).toBeUndefined(); + expect( + engineSpawnEnv(config({ maxThreads: 0 }), { CODEGRAPH_MAX_THREADS: '3' }) + .CODEGRAPH_MAX_THREADS, + ).toBe('3'); + }); + + it('lets the setting override an inherited CODEGRAPH_MAX_THREADS', () => { + const env = engineSpawnEnv(config({ maxThreads: 2 }), { CODEGRAPH_MAX_THREADS: '8' }); + + expect(env.CODEGRAPH_MAX_THREADS).toBe('2'); + }); }); diff --git a/vscode/src/server.ts b/vscode/src/server.ts index 1697869..8e62153 100644 --- a/vscode/src/server.ts +++ b/vscode/src/server.ts @@ -37,6 +37,8 @@ export function getServerPath(context: vscode.ExtensionContext): ServerInfo { /** * Environment for the spawned engine process. * + * CODEGRAPH_MAX_THREADS carries `codegraph.maxThreads` when it is set. + * * CODEGRAPH_STATIC_MODEL is set only when the user names a directory. * * It used to default to /bin/jina-code-static-256, which @@ -60,6 +62,12 @@ export function engineSpawnEnv( if (cfg.get('embeddingModel') === 'static' && staticModelPath) { spawnEnv.CODEGRAPH_STATIC_MODEL = staticModelPath; } + // 0 (the default) leaves the engine's own default, half the CPUs, or a + // CODEGRAPH_MAX_THREADS the user exported themselves. + const maxThreads = cfg.get('maxThreads'); + if (typeof maxThreads === 'number' && Number.isInteger(maxThreads) && maxThreads > 0) { + spawnEnv.CODEGRAPH_MAX_THREADS = String(maxThreads); + } return spawnEnv; }