diff --git a/README.md b/README.md index f74a0a0..1793b58 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ moving on. Fix any type errors or missing imports immediately. | "java-functional-lsp not found" | Run `brew install aviadshiber/tap/java-functional-lsp` | | Plugin not active | Run `claude plugin list` to verify, then `/reload-plugins` | | Diagnostics slow on first open | Normal — tree-sitter parses on first load, then incremental | +| Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)); jdtls results arrive with the next tool result. See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | ### Other Editors @@ -306,6 +307,27 @@ The jdtls Eclipse workspace index is cached in `~/.cache/jdtls-data/`. Warm star To force a clean rebuild: `rm -rf ~/.cache/jdtls-data/` +### Fresh jdtls diagnostics after edits + +jdtls re-validates a file 0.4–2.4s after the last edit to *any* file, and its results carry no document version. So after an edit, java-functional-lsp holds back jdtls diagnostics for that file until jdtls publishes again, rather than re-sending the previous edit's results as if they were current ([#109](https://github.com/aviadshiber/java-functional-lsp/issues/109)): + +| Mode | Default for | After an edit | +|------|-------------|---------------| +| `custom-first` | Claude Code | Custom diagnostics publish at once, without jdtls errors; the full set follows when jdtls has re-validated | +| `hold-all` | Other editors | Nothing is published for the file until jdtls has re-validated (no flickering squiggles) | +| `off` | — | Previous behavior: custom diagnostics plus the last known jdtls diagnostics after 150ms | + +If jdtls doesn't publish in time (3s after the last edit, stretched when jdtls is slow, 10s at most), the last known jdtls diagnostics are used. Files whose module is still being imported, and files matched by `java.diagnostic.filter`, are never held. While you edit the same file in quick succession, its diagnostics update only once the burst settles. + +Environment variables: + +| Variable | Values | Effect | +|----------|--------|--------| +| `JAVA_FUNCTIONAL_LSP_DIAG_HOLD` | `custom-first`, `hold-all`, `off` | Overrides the mode above; `off` restores the previous behavior | +| `JAVA_FUNCTIONAL_LSP_LOG_LEVEL` | `DEBUG`, `INFO` (default), `WARNING` | Verbosity of java-functional-lsp's own logs; `DEBUG` adds one line per publish decision (file name, trigger, counts). Library logging (pygls) is unaffected — note that pygls already logs the JSON it sends, including diagnostic messages, at `INFO` | + +The log reports `jdtls freshness: released=… too_early=… timeout=… late_correction=…` every 100 decisions and when jdtls stops. Repeated `timeout` lines mean jdtls is slow or stuck on that module. A growing `late_correction` count means jdtls results were released too early. + ### Suppressing jdtls diagnostics For project-specific jdtls false positives (e.g., annotation processor methods, MapStruct mappers), use `suppressJdtlsPatterns` to add custom regex filters: diff --git a/pyproject.toml b/pyproject.toml index c1c42ec..6db843d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "java-functional-lsp" -version = "0.12.0" +version = "0.12.1" description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions" readme = "README.md" license = { text = "MIT" } @@ -65,6 +65,8 @@ python_classes = ["Test*"] python_functions = ["test_*"] addopts = "--cov=java_functional_lsp --cov-report=term-missing --cov-fail-under=80" asyncio_mode = "auto" +# Safety net so a hung await fails the test instead of the CI job; e2e tests set their own. +timeout = 120 markers = [ "e2e: end-to-end tests that spawn a real jdtls subprocess (require jdtls + Java 21+; skipped when unavailable)", ] diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index 7dbd099..ffef784 100644 --- a/src/java_functional_lsp/__init__.py +++ b/src/java_functional_lsp/__init__.py @@ -1,3 +1,3 @@ """java-functional-lsp: A Java LSP server enforcing functional programming best practices.""" -__version__ = "0.12.0" +__version__ = "0.12.1" diff --git a/src/java_functional_lsp/proxy.py b/src/java_functional_lsp/proxy.py index 4b41e9f..76392b6 100644 --- a/src/java_functional_lsp/proxy.py +++ b/src/java_functional_lsp/proxy.py @@ -57,6 +57,9 @@ #: Java 21"`` before the server even starts. _MIN_JDTLS_JAVA_MAJOR = 21 +#: Distinct jdtls→client request methods tracked individually; the rest count as "". +_MAX_DROPPED_METHODS = 50 + #: Matches the first version token in ``java -version`` output. Handles: #: - modern format: ``openjdk version "21.0.10" 2026-01-20`` #: - legacy Java 8: ``openjdk version "1.8.0_452"`` (captures ``1``; caller @@ -788,14 +791,24 @@ def _build_effective_params( class JdtlsProxy: """Manages a jdtls subprocess and provides async request/notification forwarding.""" - def __init__(self, on_diagnostics: Callable[[str, list[Any]], None] | None = None) -> None: + def __init__( + self, + on_diagnostics: Callable[[str, list[Any]], None] | None = None, + uri_key: Callable[[str], str] = lambda uri: uri, + on_stopped: Callable[[], None] | None = None, + ) -> None: self._process: asyncio.subprocess.Process | None = None self._reader_task: asyncio.Task[None] | None = None self._stderr_task: asyncio.Task[None] | None = None self._next_id: int = 1 self._pending: dict[int, asyncio.Future[Any]] = {} + # Keyed by uri_key(uri): jdtls may echo a URI in a different encoding than + # the client sent, so lookups must go through the same canonical key. self._diagnostics_cache: dict[str, list[Any]] = {} + self._uri_key = uri_key self._on_diagnostics = on_diagnostics + self._on_stopped = on_stopped + self._dropped_request_counts: dict[str, int] = {} self._available = False self._jdtls_capabilities: dict[str, Any] = {} # Lazy-start state @@ -834,7 +847,19 @@ def capabilities(self) -> dict[str, Any]: def get_cached_diagnostics(self, uri: str) -> list[Any]: """Get the latest jdtls diagnostics for a URI.""" - return list(self._diagnostics_cache.get(uri, [])) + return list(self._diagnostics_cache.get(self._uri_key(uri), [])) + + def _mark_stopped(self) -> None: + """Drop state that belongs to the dead jdtls process and notify the owner.""" + if not self._available and not self._diagnostics_cache: + return # already handled (reader EOF, then stop()) + self._available = False + cached = len(self._diagnostics_cache) + self._diagnostics_cache.clear() + if cached: + logger.info("jdtls stopped: cleared cached diagnostics for %d files", cached) + if self._on_stopped: + self._on_stopped() def check_available(self) -> bool: """Check if jdtls is on PATH (lightweight, no subprocess started).""" @@ -929,6 +954,8 @@ def _blocking_startup() -> tuple[dict[str, str], str | None]: self._jdtls_capabilities = result.get("capabilities", {}) logger.info("jdtls initialized (capabilities: %s)", list(self._jdtls_capabilities.keys())) + server_info = result.get("serverInfo") or {} + logger.info("jdtls server: %s %s", server_info.get("name", "?"), server_info.get("version", "?")) await self.send_notification("initialized", {}) self._available = True @@ -1170,7 +1197,7 @@ async def expand_full_workspace(self) -> None: async def stop(self) -> None: """Shutdown jdtls subprocess gracefully.""" - self._available = False + self._mark_stopped() if self._reader_task and not self._reader_task.done(): self._reader_task.cancel() @@ -1258,7 +1285,7 @@ async def _reader_loop(self, reader: asyncio.StreamReader) -> None: msg = await read_message(reader) if msg is None: logger.warning("jdtls stdout closed — subprocess may have exited") - self._available = False + self._mark_stopped() break self._dispatch_message(msg) @@ -1266,7 +1293,7 @@ async def _reader_loop(self, reader: asyncio.StreamReader) -> None: pass except Exception as e: logger.error("jdtls reader loop error: %s", e) - self._available = False + self._mark_stopped() async def _stderr_reader(self, stderr: asyncio.StreamReader) -> None: """Background task: log jdtls stderr output for debugging. @@ -1311,6 +1338,20 @@ def _dispatch_message(self, msg: dict[str, Any]) -> None: elif "method" in msg and "id" not in msg: # Notification from jdtls self._handle_notification(msg) + elif "method" in msg: + self._note_dropped_request(str(msg["method"])) + + def _note_dropped_request(self, method: str) -> None: + """Count jdtls→client requests the proxy leaves unanswered (method names only, never params).""" + method = method[:100] + if method not in self._dropped_request_counts and len(self._dropped_request_counts) >= _MAX_DROPPED_METHODS: + method = "" + count = self._dropped_request_counts.get(method, 0) + 1 + self._dropped_request_counts[method] = count + if count == 1: + logger.info("jdtls request %r dropped (no client-side handler)", method) + else: + logger.debug("jdtls request %r dropped (%d times)", method, count) def _handle_notification(self, msg: dict[str, Any]) -> None: """Handle a notification from jdtls.""" @@ -1320,7 +1361,7 @@ def _handle_notification(self, msg: dict[str, Any]) -> None: if method == "textDocument/publishDiagnostics": uri = params.get("uri", "") diagnostics = params.get("diagnostics", []) - self._diagnostics_cache[uri] = diagnostics + self._diagnostics_cache[self._uri_key(uri)] = diagnostics if self._on_diagnostics: self._on_diagnostics(uri, diagnostics) # Other notifications (window/logMessage, etc.) are silently ignored diff --git a/src/java_functional_lsp/server.py b/src/java_functional_lsp/server.py index c40c0fb..937edf5 100644 --- a/src/java_functional_lsp/server.py +++ b/src/java_functional_lsp/server.py @@ -7,17 +7,20 @@ from __future__ import annotations import asyncio +import fnmatch +import functools +import hashlib import json import logging import os import re import sys import time -from collections import OrderedDict -from collections.abc import Coroutine +from collections import Counter, OrderedDict +from collections.abc import Callable, Coroutine from pathlib import Path from threading import Event -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from typing import BinaryIO @@ -81,6 +84,9 @@ _MAX_OPENED_URIS = 4096 +# Cached: jdtls publishes for thousands of workspace files and each is normalized for +# the diagnostics cache key and the opened-files gate. +@functools.lru_cache(maxsize=8192) def _normalize_uri(uri: str) -> str: """Canonicalize a file:// URI so equivalent paths compare equal. @@ -105,6 +111,157 @@ def _normalize_uri(uri: str) -> str: return normalized if normalized is not None else uri +# Publish modes while an edited file waits for jdtls (#109). "hold-all" publishes +# nothing until jdtls answers; "custom-first" publishes custom diagnostics at the +# debounce and the full merge once jdtls answers — for agent hosts that attach +# diagnostics right after the edit and would otherwise miss the custom ones. +_HOLD_OFF = "off" +_HOLD_ALL = "hold-all" +_HOLD_CUSTOM_FIRST = "custom-first" +_HOLD_MODES = (_HOLD_OFF, _HOLD_ALL, _HOLD_CUSTOM_FIRST) +_CUSTOM_FIRST_CLIENTS = ("Claude Code",) +_CUSTOM_SOURCE = "java-functional-lsp" + + +_PublishOutcome = Literal["released", "too_early", "late_correction", "untracked"] +_HoldEvent = Literal["released", "too_early", "late_correction", "timeout", "ineligible"] + + +class _JdtlsFreshness: + """Decides when cached jdtls diagnostics are fresh enough to publish after an edit. + + jdtls validates on one debounced job shared by all files — any didChange resets it, + and it publishes 0.4-2.4s later — and its publishes carry no document version. So + freshness is inferred from timing: a publish for a file is fresh once jdtls's minimum + debounce has passed since that file's last edit, and the wait is bounded by the last + change to any file (which restarts the job). The server owns the tasks. + """ + + # jdtls 1.61.0 BaseDocumentLifeCycleHandler: validation debounce <=400ms, publish + # debounce 400-2000ms, any didChange reschedules; BaseDiagnosticsHandler.endReporting + # publishes without a version. Re-check on jdtls upgrades: + # https://github.com/eclipse-jdtls/eclipse.jdt.ls/blob/v1.61.0/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/BaseDocumentLifeCycleHandler.java + FRESH_MIN_AGE = 0.4 + DEADLINE_AFTER_CHANGE = 3.0 + CEILING = 10.0 + LATE_CORRECTION_WINDOW = 2.0 + EWMA_ALPHA = 0.3 + SUMMARY_EVERY = 100 + + def __init__( + self, + clock: Callable[[], float] = time.monotonic, + *, + fresh_min_age: float = FRESH_MIN_AGE, + deadline_after_change: float = DEADLINE_AFTER_CHANGE, + ceiling: float = CEILING, + ) -> None: + self.clock = clock + self.fresh_min_age = fresh_min_age + self.deadline_after_change = deadline_after_change + self.ceiling = ceiling + self._pending: dict[str, float] = {} # key -> time of its last forwarded change + self._released: dict[str, tuple[float, str]] = {} + self._last_change: float | None = None + self._latency_ewma = 0.0 + self._latency_max = 0.0 + self.counts: Counter[str] = Counter() + + def note_forwarded_change(self) -> None: + self._last_change = self.clock() + + def mark_pending(self, key: str) -> None: + self._pending[key] = self.clock() + self._released.pop(key, None) + + def is_pending(self, key: str) -> bool: + return key in self._pending + + def deadline(self, key: str) -> float | None: + changed = self._pending.get(key) + if changed is None: + return None + last_any = self._last_change if self._last_change is not None else changed + after_change = max(self.deadline_after_change, 2 * self._latency_ewma) + return min(last_any + after_change, changed + self.ceiling) + + def on_publish(self, key: str, signature: Callable[[], str]) -> _PublishOutcome: + """Classify a jdtls publish; *signature* is computed only when it is needed.""" + now = self.clock() + changed = self._pending.get(key) + if changed is not None: + age = now - changed + # Fixed floor, not adaptive: an adaptive floor would reject normal-latency + # publishes after one slow one and could never come back down. + if age < self.fresh_min_age: + self.record("too_early") + return "too_early" + del self._pending[key] + self._released[key] = (now, signature()) + self._latency_max = max(self._latency_max, age) + self._latency_ewma = ( + age if not self._latency_ewma else self._latency_ewma + self.EWMA_ALPHA * (age - self._latency_ewma) + ) + self.record("released") + return "released" + return self._after_release(key, now, signature) + + def _after_release(self, key: str, now: float, signature: Callable[[], str]) -> _PublishOutcome: + """A jdtls publish that changes the set shortly after a release means that release was stale. + + Counted at most once per release; identical republishes keep the window open. + """ + released = self._released.get(key) + if released is None: + return "untracked" + at, released_signature = released + if now - at > self.LATE_CORRECTION_WINDOW: + del self._released[key] + return "untracked" + if signature() == released_signature: + return "untracked" + del self._released[key] + self.record("late_correction") + return "late_correction" + + def expire(self, key: str) -> bool: + """Drop *key* once its deadline has passed. Returns True when it timed out.""" + deadline = self.deadline(key) + if deadline is None or self.clock() < deadline: + return False + del self._pending[key] + self.record("timeout") + return True + + def forget(self, key: str) -> None: + self._pending.pop(key, None) + self._released.pop(key, None) + + def reset(self) -> int: + """Clear all tracking; returns how many files were still pending.""" + pending = len(self._pending) + self._pending.clear() + self._released.clear() + self._last_change = None + return pending + + def record(self, event: _HoldEvent) -> None: + self.counts[event] += 1 + if sum(self.counts.values()) % self.SUMMARY_EVERY == 0: + logger.info("%s", self.summary()) + + def summary(self) -> str: + counts = " ".join(f"{name}={n}" for name, n in sorted(self.counts.items())) or "no-holds" + return ( + f"jdtls freshness: {counts} latency_ewma_ms={self._latency_ewma * 1000:.0f} " + f"latency_max_ms={self._latency_max * 1000:.0f}" + ) + + +def _diagnostics_signature(diagnostics: list[Any]) -> str: + return hashlib.sha256(json.dumps(diagnostics, sort_keys=True, default=str).encode()).hexdigest() + + class JavaFunctionalLspServer(LanguageServer): def __init__(self) -> None: from . import __version__ @@ -113,9 +270,14 @@ def __init__(self) -> None: self._parser = get_parser() self._config: dict[str, Any] = {} self._init_params: dict[str, Any] = {} - self._proxy = JdtlsProxy(on_diagnostics=self._on_jdtls_diagnostics) + self._proxy = JdtlsProxy( + on_diagnostics=self._on_jdtls_diagnostics, + uri_key=_normalize_uri, + on_stopped=self._on_jdtls_stopped, + ) self._user_suppress_patterns: list[re.Pattern[str]] = [] self._skip_jdtls: bool = False + self._hold_mode: str = _HOLD_OFF self._skip_jdtls_registration: bool = False self._init_generation: int = 0 # Capability entries the negotiator decided to register dynamically @@ -129,26 +291,34 @@ def __init__(self) -> None: # survive the async race between didClose and late jdtls publishes. # Bounded LRU: insertion-ordered, oldest evicted on overflow so a long # session navigating many files can't grow the set unboundedly. - # Reset on initialize. - self._session_opened_uris: OrderedDict[str, None] = OrderedDict() + # Reset on initialize. Values are the URI string exactly as the client + # sent it, so publishes triggered by jdtls go out under the client's form. + self._session_opened_uris: OrderedDict[str, str] = OrderedDict() + # Module root per opened file (normalized key), resolved once: the lookup walks + # the filesystem and didChange arrives per keystroke in IDEs. + self._module_uris: dict[str, str | None] = {} def _record_opened(self, uri: str) -> None: """Record *uri* as opened this session, evicting the oldest entry at cap. - Stores the normalized form so gate lookups in ``_on_jdtls_diagnostics`` - can use a fast raw-first check without redundant normalization. + Keys are normalized so gate lookups in ``_on_jdtls_diagnostics`` can use a + fast raw-first check without redundant normalization. """ + client_uri = uri uri = _normalize_uri(uri) if uri in self._session_opened_uris: + self._session_opened_uris[uri] = client_uri self._session_opened_uris.move_to_end(uri) return - self._session_opened_uris[uri] = None + self._session_opened_uris[uri] = client_uri # Size check uses > so the dict stabilises at exactly _MAX_OPENED_URIS # entries after the pop: we insert first (reaching MAX+1 momentarily), # then evict. The transient overshoot is invisible to other callers # because asyncio is single-threaded and no await intervenes here. if len(self._session_opened_uris) > _MAX_OPENED_URIS: - self._session_opened_uris.popitem(last=False) + evicted, _ = self._session_opened_uris.popitem(last=False) + self._module_uris.pop(evicted, None) + _freshness.forget(evicted) def _on_jdtls_diagnostics(self, uri: str, diagnostics: list[Any]) -> None: """Called when jdtls publishes diagnostics — merge with custom and re-publish. @@ -194,14 +364,34 @@ def _on_jdtls_diagnostics(self, uri: str, diagnostics: list[Any]) -> None: # mismatches (e.g., client sends literal space, jdtls echoes %20). if uri not in self._session_opened_uris and _normalize_uri(uri) not in self._session_opened_uris: return + key = _normalize_uri(uri) + outcome = _freshness.on_publish(key, lambda: _diagnostics_signature(diagnostics)) + if outcome == "too_early": + logger.debug("jdtls publish for %s arrived too soon after the last edit; still holding", Path(uri).name) + return + if outcome == "released": + # The hold task (waiting, or still in its debounce sleep) publishes the merge. + event = _hold_events.get(key) + if event is not None: + event.set() + return + if outcome == "late_correction": + logger.debug("jdtls corrected %s shortly after its hold was released", Path(uri).name) try: - _analyze_and_publish(uri) + _analyze_and_publish(uri, trigger="jdtls") except FileNotFoundError: # The file was in the opened-URIs set but vanished from disk # between didOpen and this late jdtls publish. Benign. pass except Exception as e: - logger.error("Error re-publishing diagnostics for %s: %s", uri, e) + logger.error("Error re-publishing diagnostics for %s: %s", Path(uri).name, type(e).__name__) + + def _on_jdtls_stopped(self) -> None: + """Release every held file: no fresh jdtls publish can arrive from a dead process.""" + released = _release_all_holds() + if released: + logger.info("jdtls stopped: released %d files waiting for diagnostics", released) + logger.info("%s", _freshness.summary()) server = JavaFunctionalLspServer() @@ -211,6 +401,9 @@ def _on_jdtls_diagnostics(self, uri: str, diagnostics: list[Any]) -> None: # Background tasks (prevent GC of fire-and-forget tasks) _bg_tasks: set[asyncio.Task[None]] = set() _DEBOUNCE_SECONDS = 0.15 +_freshness = _JdtlsFreshness() +# Wakes the hold task of a URI (normalized) when its fresh jdtls publish arrives. +_hold_events: dict[str, asyncio.Event] = {} def _fire_and_forget(coro: Coroutine[Any, Any, Any]) -> None: @@ -447,7 +640,7 @@ def _is_jdtls_suppressed(diag: dict[str, Any], user_patterns: list[re.Pattern[st return False -def _run_analysis(source: str, uri: str) -> list[lsp.Diagnostic]: +def _run_analysis(source: str, uri: str, *, include_jdtls: bool = True) -> list[lsp.Diagnostic]: """Run custom analyzers on source text and merge with jdtls diagnostics. jdtls processing is isolated: if it fails, custom diagnostics still publish. @@ -455,7 +648,7 @@ def _run_analysis(source: str, uri: str) -> list[lsp.Diagnostic]: custom_diags = _analyze_document(source, uri) jdtls_diags: list[lsp.Diagnostic] = [] - if server._proxy.is_available: + if include_jdtls and server._proxy.is_available: try: raw = server._proxy.get_cached_diagnostics(uri) raw = [ @@ -463,7 +656,7 @@ def _run_analysis(source: str, uri: str) -> list[lsp.Diagnostic]: ] jdtls_diags = _jdtls_raw_to_lsp_diagnostics(raw) except Exception as e: - logger.warning("jdtls diagnostic processing failed for %s: %s", uri, e) + logger.warning("jdtls diagnostic processing failed for %s: %s", Path(uri).name, type(e).__name__) return jdtls_diags + custom_diags @@ -505,7 +698,11 @@ def on_initialize(params: lsp.InitializeParams) -> lsp.InitializeResult: server._skip_jdtls_registration = False server._init_generation += 1 server._session_opened_uris.clear() + server._module_uris.clear() _jdtls_capabilities_registered = False + _release_all_holds() + server._hold_mode = _resolve_hold_mode(client_name) + logger.info("jdtls diagnostics hold mode: %s", server._hold_mode) jdtls_override = os.environ.get("JAVA_FUNCTIONAL_LSP_JDTLS", "").strip().lower() if jdtls_override == "off": @@ -633,30 +830,131 @@ async def _register_jdtls_capabilities() -> None: # --- Document sync (forward to jdtls + run custom analyzers) --- -def _analyze_and_publish(uri: str) -> None: - """Read document source, run analysis, publish results.""" - doc = server.workspace.get_text_document(uri) - diagnostics = _run_analysis(doc.source, uri) - server.text_document_publish_diagnostics(lsp.PublishDiagnosticsParams(uri=uri, diagnostics=diagnostics)) +def _analyze_and_publish(uri: str, *, include_jdtls: bool = True, trigger: str = "open") -> None: + """Read document source, run analysis, publish results under the client's URI form.""" + client_uri = server._session_opened_uris.get(_normalize_uri(uri)) or uri + doc = server.workspace.get_text_document(client_uri) + diagnostics = _run_analysis(doc.source, client_uri, include_jdtls=include_jdtls) + if logger.isEnabledFor(logging.DEBUG): + java = sum(1 for d in diagnostics if d.source != _CUSTOM_SOURCE) + logger.debug( + "publish %s trigger=%s java=%d custom=%d", Path(client_uri).name, trigger, java, len(diagnostics) - java + ) + server.text_document_publish_diagnostics(lsp.PublishDiagnosticsParams(uri=client_uri, diagnostics=diagnostics)) + + +def _resolve_hold_mode(client_name: str) -> str: + override = os.environ.get("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", "").strip().lower() + if override in _HOLD_MODES: + return override + if override: + logger.warning("Unknown JAVA_FUNCTIONAL_LSP_DIAG_HOLD value %r; expected %s", override, "/".join(_HOLD_MODES)) + return _HOLD_CUSTOM_FIRST if any(token in client_name for token in _CUSTOM_FIRST_CLIENTS) else _HOLD_ALL + + +def _matches_diagnostic_filter(uri: str) -> bool: + """jdtls never publishes for files matched by ``java.diagnostic.filter``, so don't wait for it.""" + settings = (server._config.get("jdtls") or {}).get("settings") or {} + patterns = ((settings.get("java") or {}).get("diagnostic") or {}).get("filter") or [] + if not patterns: + return False + path = to_fs_path(uri) or uri + return any(isinstance(p, str) and fnmatch.fnmatch(path, p) for p in patterns) + + +def _hold_eligible(uri: str, key: str) -> bool: + """Whether an edit to *uri* should wait for jdtls to publish fresh diagnostics.""" + if key not in server._module_uris: + server._module_uris[key] = _resolve_module_uri(uri) + module_uri = server._module_uris[key] + # Until the module is imported jdtls publishes late or only syntax errors (code 16). + if module_uri is None or not server._proxy.modules.is_ready(module_uri): + return False + return not _matches_diagnostic_filter(uri) + + +def _release_all_holds() -> int: + """Stop tracking every held file and wake its hold task; returns how many were held.""" + released = _freshness.reset() + for event in _hold_events.values(): + event.set() + return released + + +def _is_current_task(uri: str) -> bool: + # On Python 3.10/3.11 wait_for can swallow a cancel() racing with the event, + # leaving a superseded hold task running next to its replacement. + return _pending.get(uri) is asyncio.current_task() + + +def _track_forwarded_edit(uri: str) -> None: + """Record an edit jdtls received; mark the file as waiting for jdtls when eligible.""" + _freshness.note_forwarded_change() + if server._hold_mode == _HOLD_OFF: + return + key = _normalize_uri(uri) + # jdtls publishes for files outside the opened set are gated out, so they could never release. + if key in server._session_opened_uris and _hold_eligible(uri, key): + _freshness.mark_pending(key) + else: + _freshness.record("ineligible") + + +async def _hold_until_fresh(uri: str, key: str) -> None: + """Publish once jdtls has re-validated *uri* after the latest edit, or its deadline passes.""" + event = _hold_events.setdefault(key, asyncio.Event()) + trigger = "jdtls" + try: + if server._hold_mode == _HOLD_CUSTOM_FIRST: + _analyze_and_publish(uri, include_jdtls=False, trigger="custom-first") + while _freshness.is_pending(key): + if _freshness.expire(key): + trigger = "timeout" + logger.info("jdtls did not re-validate %s in time; publishing cached diagnostics", Path(uri).name) + break + deadline = _freshness.deadline(key) + remaining = (deadline - _freshness.clock()) if deadline is not None else 0.0 + event.clear() + try: + await asyncio.wait_for(event.wait(), timeout=max(remaining, 0.0)) + except asyncio.TimeoutError: + pass + finally: + if _hold_events.get(key) is event and _is_current_task(uri): + del _hold_events[key] + if _is_current_task(uri): + _analyze_and_publish(uri, trigger=trigger) async def _deferred_validate(uri: str) -> None: """Debounced validation — waits before analyzing to batch rapid edits.""" await asyncio.sleep(_DEBOUNCE_SECONDS) + key = _normalize_uri(uri) try: - _analyze_and_publish(uri) + if _freshness.is_pending(key): + await _hold_until_fresh(uri, key) + else: + _analyze_and_publish(uri, trigger="change") except Exception as e: - logger.error("Validation failed for %s: %s", uri, e) + # Never leave a file pending without a hold task: its jdtls publish would be swallowed. + if _is_current_task(uri): + _freshness.forget(key) + logger.error("Validation failed for %s: %s", Path(uri).name, type(e).__name__) -def _forward_or_queue(method: str, serialized: Any) -> None: - """Forward a notification to jdtls if available, or queue it if starting.""" +def _forward_or_queue(method: str, serialized: Any) -> bool: + """Forward a notification to jdtls if available, or queue it if starting. + + Returns True only when it was sent to a running jdtls. + """ if server._skip_jdtls: - return + return False if server._proxy.is_available: _fire_and_forget(server._proxy.send_notification(method, serialized)) - elif server._proxy._lazy_start_fired and not server._proxy._start_failed: + return True + if server._proxy._lazy_start_fired and not server._proxy._start_failed: server._proxy.queue_notification(method, serialized) + return False @server.feature(lsp.TEXT_DOCUMENT_DID_OPEN) @@ -689,18 +987,20 @@ async def on_did_open(params: lsp.DidOpenTextDocumentParams) -> None: server._proxy._lazy_start_fired = True _fire_and_forget(_lazy_start_jdtls(uri)) - # Custom diagnostics always publish immediately — never blocked by jdtls. + # Custom diagnostics always publish immediately — never blocked by jdtls. A file + # still waiting for jdtls gets its jdtls set from the hold, not the stale cache. try: - _analyze_and_publish(uri) + _analyze_and_publish(uri, include_jdtls=not _freshness.is_pending(_normalize_uri(uri))) except Exception as e: - logger.error("Analysis failed on open for %s: %s", uri, e) + logger.error("Analysis failed on open for %s: %s", Path(uri).name, type(e).__name__) @server.feature(lsp.TEXT_DOCUMENT_DID_CHANGE) async def on_did_change(params: lsp.DidChangeTextDocumentParams) -> None: """Forward to jdtls and schedule debounced re-analysis.""" uri = params.text_document.uri - _forward_or_queue("textDocument/didChange", _serialize_params(params)) + if _forward_or_queue("textDocument/didChange", _serialize_params(params)): + _track_forwarded_edit(uri) # Cancel pending validation, schedule new one (150ms debounce for IDE typing) if uri in _pending: _pending[uri].cancel() @@ -711,6 +1011,9 @@ async def on_did_change(params: lsp.DidChangeTextDocumentParams) -> None: async def on_did_save(params: lsp.DidSaveTextDocumentParams) -> None: """Forward to jdtls and re-analyze immediately (no debounce on save).""" _forward_or_queue("textDocument/didSave", _serialize_params(params)) + if _freshness.is_pending(_normalize_uri(params.text_document.uri)): + # jdtls does not validate on save; the pending edit's hold publishes the fresh merge. + return try: _analyze_and_publish(params.text_document.uri) except Exception as e: @@ -724,6 +1027,11 @@ async def on_did_close(params: lsp.DidCloseTextDocumentParams) -> None: if uri in _pending: _pending[uri].cancel() del _pending[uri] + key = _normalize_uri(uri) + _freshness.forget(key) + event = _hold_events.pop(key, None) + if event is not None: + event.set() # Clear diagnostics for the closed document (LSP best practice) server.text_document_publish_diagnostics(lsp.PublishDiagnosticsParams(uri=uri, diagnostics=[])) _forward_or_queue("textDocument/didClose", _serialize_params(params)) @@ -1250,9 +1558,16 @@ def read(self, n: int) -> bytes: return data +def _log_level_from_env() -> int: + level = getattr(logging, os.environ.get("JAVA_FUNCTIONAL_LSP_LOG_LEVEL", "INFO").strip().upper(), None) + return level if isinstance(level, int) else logging.INFO + + def main() -> None: """Entry point for the LSP server.""" logging.basicConfig(level=logging.INFO, format="%(name)s %(levelname)s: %(message)s") + # Only this package's loggers: root DEBUG would also enable pygls/jdtls payload logging. + logging.getLogger("java_functional_lsp").setLevel(_log_level_from_env()) server.start_io(stdin=_EternalStdinBuffer(sys.stdin.buffer)) # type: ignore[arg-type] diff --git a/tests/conftest.py b/tests/conftest.py index 02953ce..e232114 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,20 @@ from java_functional_lsp.analyzers.base import get_parser +@pytest.fixture(autouse=True) +def isolate_diagnostics_hold(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the server singleton's hold mode and freshness state from leaking between tests. + + on_initialize switches the mode to hold-all/custom-first; later in-process tests + would otherwise hold their publishes. + """ + from java_functional_lsp import server as srv_mod + + monkeypatch.setattr(srv_mod.server, "_hold_mode", srv_mod._HOLD_OFF) + monkeypatch.setattr(srv_mod, "_freshness", srv_mod._JdtlsFreshness()) + monkeypatch.setattr(srv_mod, "_hold_events", {}) + + @pytest.fixture def parser(): # type: ignore[no-untyped-def] """Return a reusable tree-sitter Java parser.""" diff --git a/tests/test_diagnostics_freshness.py b/tests/test_diagnostics_freshness.py new file mode 100644 index 0000000..ebdb086 --- /dev/null +++ b/tests/test_diagnostics_freshness.py @@ -0,0 +1,645 @@ +"""Tests for holding edit-triggered publishes until jdtls re-validates (#109).""" + +from __future__ import annotations + +import asyncio +import logging +from collections.abc import AsyncIterator, Callable +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from lsprotocol import types as lsp +from pygls.workspace import Workspace + +from java_functional_lsp import server as srv_mod +from java_functional_lsp.proxy import JdtlsProxy +from java_functional_lsp.server import ( + _HOLD_ALL, + _HOLD_CUSTOM_FIRST, + _HOLD_OFF, + _JdtlsFreshness, + _resolve_hold_mode, + on_did_change, + on_did_close, + on_did_open, + on_did_save, + on_initialize, + server, +) + +URI = "file:///mod/src/Foo.java" +OTHER_URI = "file:///mod/src/Other.java" +MODULE = "file:///mod" +SOURCE = "class Foo { String f() { return null; } }" + + +def _java_diag(message: str, line: int = 0) -> dict[str, Any]: + return { + "range": {"start": {"line": line, "character": 0}, "end": {"line": line, "character": 3}}, + "message": message, + "severity": 1, + "source": "Java", + } + + +class FakeClock: + def __init__(self) -> None: + self.now = 100.0 + + def __call__(self) -> float: + return self.now + + +# --- _JdtlsFreshness (pure state, fake clock) --- + + +class TestFreshnessState: + def _state(self) -> tuple[_JdtlsFreshness, FakeClock]: + clock = FakeClock() + return _JdtlsFreshness(clock=clock), clock + + def _release(self, state: _JdtlsFreshness, clock: FakeClock, after: float, key: str = "k") -> str: + state.note_forwarded_change() + state.mark_pending(key) + clock.now += after + return state.on_publish(key, lambda: "sig") + + def test_publish_after_min_age_releases(self) -> None: + state, clock = self._state() + assert self._release(state, clock, 0.5) == "released" + assert not state.is_pending("k") + + def test_publish_right_after_change_is_too_early(self) -> None: + state, clock = self._state() + assert self._release(state, clock, 0.1) == "too_early" + assert state.is_pending("k") + + def test_change_to_other_file_does_not_block_release(self) -> None: + """A publish reflects this file's latest content once its own edit is old enough.""" + state, clock = self._state() + state.note_forwarded_change() + state.mark_pending("a") + clock.now += 1.0 + state.note_forwarded_change() # edit to another file + clock.now += 0.1 + assert state.on_publish("a", lambda: "sig") == "released" + + def test_signature_is_computed_only_when_needed(self) -> None: + state, _ = self._state() + signature = MagicMock(return_value="sig") + assert state.on_publish("k", signature) == "untracked" + signature.assert_not_called() + + def test_untracked_uri(self) -> None: + state, _ = self._state() + assert state.on_publish("k", lambda: "sig") == "untracked" + + def test_no_forwarded_change_still_releases_after_min_age(self) -> None: + state, clock = self._state() + state.mark_pending("k") + clock.now += 0.5 + assert state.on_publish("k", lambda: "sig") == "released" + + def test_deadline_extends_with_later_changes_but_caps_at_ceiling(self) -> None: + state, clock = self._state() + state.note_forwarded_change() + state.mark_pending("a") + start = clock.now + assert state.deadline("a") == pytest.approx(start + state.deadline_after_change) + for _ in range(20): + clock.now += 1.0 + state.note_forwarded_change() + assert state.deadline("a") == pytest.approx(start + state.ceiling) + + def test_ceiling_counts_from_the_files_latest_edit(self) -> None: + state, clock = self._state() + for _ in range(20): # keeps typing in the same file + state.note_forwarded_change() + state.mark_pending("a") + clock.now += 1.0 + assert state.deadline("a") == pytest.approx(clock.now - 1.0 + state.deadline_after_change) + + def test_constructor_timing_overrides(self) -> None: + state = _JdtlsFreshness(clock=FakeClock(), fresh_min_age=0.1, deadline_after_change=1.0, ceiling=2.0) + assert (state.fresh_min_age, state.deadline_after_change, state.ceiling) == (0.1, 1.0, 2.0) + + def test_production_defaults_match_readme(self) -> None: + state = _JdtlsFreshness() + assert (state.fresh_min_age, state.deadline_after_change, state.ceiling) == (0.4, 3.0, 10.0) + + def test_expire_only_after_deadline(self) -> None: + state, clock = self._state() + state.note_forwarded_change() + state.mark_pending("k") + clock.now += state.deadline_after_change - 0.01 + assert not state.expire("k") + clock.now += 0.02 + assert state.expire("k") + assert not state.is_pending("k") + assert state.counts["timeout"] == 1 + + def test_slow_jdtls_stretches_deadline(self) -> None: + state, clock = self._state() + for _ in range(10): + assert self._release(state, clock, 4.0) == "released" + state.note_forwarded_change() + state.mark_pending("k") + assert state.deadline("k") == pytest.approx(clock.now + 8.0, rel=0.05) + + def test_slow_release_does_not_reject_later_normal_publishes(self) -> None: + state, clock = self._state() + assert self._release(state, clock, 2.4) == "released" + assert self._release(state, clock, 0.5) == "released" + + def test_late_correction_counted_once(self) -> None: + state, clock = self._state() + state.note_forwarded_change() + state.mark_pending("k") + clock.now += 0.5 + state.on_publish("k", lambda: "first") + clock.now += 0.5 + assert state.on_publish("k", lambda: "first") == "untracked" + assert state.on_publish("k", lambda: "second") == "late_correction" + assert state.on_publish("k", lambda: "third") == "untracked" + assert state.counts["late_correction"] == 1 + + def test_new_edit_closes_late_correction_window(self) -> None: + state, clock = self._state() + self._release(state, clock, 0.5) + state.mark_pending("k") # next edit + clock.now += 0.5 + assert state.on_publish("k", lambda: "other") == "released" + assert state.counts["late_correction"] == 0 + + def test_different_signature_after_window_is_not_late(self) -> None: + state, clock = self._state() + state.note_forwarded_change() + state.mark_pending("k") + clock.now += 0.5 + state.on_publish("k", lambda: "first") + clock.now += state.LATE_CORRECTION_WINDOW + 1 + assert state.on_publish("k", lambda: "second") == "untracked" + + def test_reset_returns_pending_count(self) -> None: + state, _ = self._state() + state.note_forwarded_change() + state.mark_pending("a") + state.mark_pending("b") + assert state.reset() == 2 + assert not state.is_pending("a") + + def test_summary_mentions_counts(self) -> None: + state, clock = self._state() + self._release(state, clock, 0.5) + assert "released=1" in state.summary() + + +class TestHoldMode: + def test_claude_code_gets_custom_first(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", raising=False) + assert _resolve_hold_mode("Claude Code") == _HOLD_CUSTOM_FIRST + + def test_other_clients_get_hold_all(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", raising=False) + assert _resolve_hold_mode("Visual Studio Code") == _HOLD_ALL + + @pytest.mark.parametrize("value", ["off", "OFF ", "hold-all", "custom-first"]) + def test_env_override(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", value) + assert _resolve_hold_mode("Claude Code") == value.strip().lower() + + def test_unknown_env_value_falls_back(self, monkeypatch: pytest.MonkeyPatch, caplog: Any) -> None: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", "bogus") + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.server"): + assert _resolve_hold_mode("Neovim") == _HOLD_ALL + assert "bogus" in caplog.text + + +# --- Wiring: handlers + hold task against a mocked live jdtls --- + + +def _put_document(uri: str) -> None: + server.workspace.put_text_document(lsp.TextDocumentItem(uri=uri, language_id="java", version=1, text=SOURCE)) + server._record_opened(uri) + + +@pytest.fixture +async def live(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[MagicMock]: + """A server whose jdtls looks live, with a ready module, fast debounce and a captured publisher. + + Deadlines are long so that release-path tests never depend on wall-clock speed; + timeout tests shorten them explicitly. + """ + created_workspace = server.protocol._workspace is None + if created_workspace: + server.protocol._workspace = Workspace(root_uri=MODULE, sync_kind=lsp.TextDocumentSyncKind.Full) + _put_document(URI) + fresh = _JdtlsFreshness(fresh_min_age=0.05, deadline_after_change=30.0, ceiling=60.0) + monkeypatch.setattr(srv_mod, "_freshness", fresh) + monkeypatch.setattr(srv_mod, "_DEBOUNCE_SECONDS", 0.01) + monkeypatch.setattr(srv_mod, "_resolve_module_uri", MagicMock(return_value=MODULE)) + monkeypatch.setattr(server, "_skip_jdtls", False) + monkeypatch.setattr(server, "_hold_mode", _HOLD_ALL) + monkeypatch.setattr(server._proxy, "_available", True) + monkeypatch.setattr(server._proxy, "send_notification", AsyncMock()) + server._proxy.modules.mark_ready(MODULE) + server._proxy._diagnostics_cache.clear() + publisher = MagicMock() + with patch.object(server, "text_document_publish_diagnostics", publisher): + yield publisher + tasks = [srv_mod._pending.pop(uri) for uri in (URI, OTHER_URI) if uri in srv_mod._pending] + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, *list(srv_mod._bg_tasks), return_exceptions=True) + server._proxy._diagnostics_cache.clear() + server._proxy.modules.clear() + for uri in (URI, OTHER_URI): + server._session_opened_uris.pop(srv_mod._normalize_uri(uri), None) + server.workspace.remove_text_document(uri) + if created_workspace: + server.protocol._workspace = None + + +def _published(publisher: MagicMock) -> list[lsp.PublishDiagnosticsParams]: + return [call.args[0] for call in publisher.call_args_list] + + +def _messages(params: lsp.PublishDiagnosticsParams, source: str) -> list[str]: + return [d.message for d in params.diagnostics if d.source == source] + + +async def _until(predicate: Callable[[], bool], timeout: float = 2.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not predicate(): + assert asyncio.get_running_loop().time() < deadline, "condition not reached in time" + await asyncio.sleep(0.005) + + +async def _edit(uri: str = URI) -> None: + await on_did_change( + lsp.DidChangeTextDocumentParams( + text_document=lsp.VersionedTextDocumentIdentifier(uri=uri, version=2), + content_changes=[lsp.TextDocumentContentChangeWholeDocument(text=SOURCE)], + ) + ) + + +async def _past_debounce() -> None: + await asyncio.sleep(0.03) + + +async def _past_min_age() -> None: + await asyncio.sleep(0.08) + + +def _jdtls_publishes(diags: list[dict[str, Any]], uri: str = URI) -> None: + server._proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": diags}} + ) + + +def _short_deadlines() -> None: + srv_mod._freshness.deadline_after_change = 0.3 + srv_mod._freshness.ceiling = 1.0 + + +class TestHoldWiring: + async def test_hold_all_publishes_only_fresh_jdtls(self, live: MagicMock) -> None: + _jdtls_publishes([_java_diag("Bar cannot be resolved to a type")]) # pre-edit state + live.reset_mock() + await _edit() + await _past_debounce() + assert live.call_count == 0, "stale merge must not be published at the debounce" + await _past_min_age() + _jdtls_publishes([]) # jdtls re-validated: import fixed + await _until(lambda: live.call_count == 1) + final = _published(live)[0] + assert _messages(final, "Java") == [] + assert _messages(final, "java-functional-lsp") + assert srv_mod._freshness.counts["released"] == 1 + + async def test_custom_first_omits_stale_java_then_merges(self, live: MagicMock) -> None: + server._hold_mode = _HOLD_CUSTOM_FIRST + _jdtls_publishes([_java_diag("Bar cannot be resolved to a type")]) + live.reset_mock() + await _edit() + await _until(lambda: live.call_count == 1) + first = _published(live)[0] + assert _messages(first, "Java") == [], "stale jdtls set must not ride on the custom-first publish" + assert _messages(first, "java-functional-lsp") + await _past_min_age() + _jdtls_publishes([_java_diag("The constructor Foo(int) is undefined", 1)]) + await _until(lambda: live.call_count == 2) + assert _messages(_published(live)[1], "Java") == ["The constructor Foo(int) is undefined"] + + async def test_custom_first_timeout_falls_back_to_cache(self, live: MagicMock) -> None: + server._hold_mode = _HOLD_CUSTOM_FIRST + _short_deadlines() + _jdtls_publishes([_java_diag("cached")]) + live.reset_mock() + await _edit() + await _until(lambda: live.call_count == 2, timeout=3.0) + custom_only, fallback = _published(live) + assert _messages(custom_only, "Java") == [] + assert _messages(fallback, "Java") == ["cached"] + assert srv_mod._freshness.counts["timeout"] == 1 + + async def test_too_early_publish_keeps_holding(self, live: MagicMock) -> None: + await _edit() + _jdtls_publishes([_java_diag("stale in-flight result")]) # arrives right after the change + await _past_debounce() + assert live.call_count == 0 + await _past_min_age() + _jdtls_publishes([]) + await _until(lambda: live.call_count == 1) + assert _messages(_published(live)[0], "Java") == [] + + async def test_rapid_edits_never_publish_superseded_jdtls_set(self, live: MagicMock) -> None: + _jdtls_publishes([_java_diag("Bar cannot be resolved to a type")]) + live.reset_mock() + await _edit() + await _past_min_age() + await _edit() # N+1 before jdtls answered N + _jdtls_publishes([_java_diag("Bar cannot be resolved to a type")]) # in-flight result for N + await _past_min_age() + _jdtls_publishes([]) # result for N+1 + await _until(lambda: live.call_count == 1) + await _past_debounce() + published = _published(live) + assert len(published) == 1 + assert _messages(published[0], "Java") == [] + assert srv_mod._freshness.counts["too_early"] == 1 + + async def test_edit_to_other_file_does_not_delay_release(self, live: MagicMock) -> None: + _put_document(OTHER_URI) + await _edit(URI) + await _past_min_age() + await _edit(OTHER_URI) + _jdtls_publishes([_java_diag("fresh for Foo")], uri=URI) # right after Other's change + await _until(lambda: live.call_count == 1) + published = _published(live)[0] + assert published.uri == URI + assert _messages(published, "Java") == ["fresh for Foo"] + assert srv_mod._freshness.is_pending(srv_mod._normalize_uri(OTHER_URI)) + assert srv_mod._freshness.counts["too_early"] == 0 + + async def test_timeout_publishes_cached(self, live: MagicMock) -> None: + _short_deadlines() + _jdtls_publishes([_java_diag("cached")]) + live.reset_mock() + await _edit() + await _past_debounce() + assert live.call_count == 0 + await _until(lambda: live.call_count == 1, timeout=2.0) + assert _messages(_published(live)[0], "Java") == ["cached"] + assert srv_mod._freshness.counts["timeout"] == 1 + + async def test_save_while_pending_defers_to_hold(self, live: MagicMock) -> None: + await _edit() + live.reset_mock() + await on_did_save(lsp.DidSaveTextDocumentParams(text_document=lsp.TextDocumentIdentifier(uri=URI))) + assert live.call_count == 0 + sent = server._proxy.send_notification + assert isinstance(sent, AsyncMock) + forwarded = [call.args[0] for call in sent.call_args_list] + assert "textDocument/didSave" in forwarded + await _past_min_age() + _jdtls_publishes([]) + await _until(lambda: live.call_count == 1) + assert _messages(_published(live)[0], "Java") == [] + + async def test_save_when_not_pending_publishes(self, live: MagicMock) -> None: + await on_did_save(lsp.DidSaveTextDocumentParams(text_document=lsp.TextDocumentIdentifier(uri=URI))) + assert live.call_count == 1 + + async def test_late_correction_republishes(self, live: MagicMock) -> None: + await _edit() + await _past_min_age() + _jdtls_publishes([_java_diag("first")]) + await _until(lambda: live.call_count == 1) + _jdtls_publishes([_java_diag("corrected")]) + assert live.call_count == 2 + assert _messages(_published(live)[1], "Java") == ["corrected"] + assert srv_mod._freshness.counts["late_correction"] == 1 + + async def test_did_open_while_pending_skips_stale_jdtls_and_hold_still_releases(self, live: MagicMock) -> None: + _jdtls_publishes([_java_diag("stale")]) + live.reset_mock() + await _edit() + with patch.object(server._proxy, "add_module_if_new", AsyncMock()): + await on_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=URI, language_id="java", version=3, text=SOURCE) + ) + ) + assert live.call_count == 1 + assert _messages(_published(live)[0], "Java") == [] + assert _messages(_published(live)[0], "java-functional-lsp") + await _past_min_age() + _jdtls_publishes([_java_diag("fresh")]) + await _until(lambda: live.call_count == 2) + assert _messages(_published(live)[1], "Java") == ["fresh"] + + async def test_module_not_ready_uses_debounce_path(self, live: MagicMock) -> None: + _jdtls_publishes([_java_diag("cached")]) + server._proxy.modules.clear() # after the publish, which would mark the module READY again + live.reset_mock() + await _edit() + await _until(lambda: live.call_count == 1) + assert _messages(_published(live)[0], "Java") == ["cached"] + assert srv_mod._freshness.counts["ineligible"] == 1 + + @pytest.mark.parametrize("patterns", [["**/generated/*.java"], [42]]) + async def test_non_matching_diagnostic_filter_still_holds( + self, live: MagicMock, monkeypatch: pytest.MonkeyPatch, patterns: list[Any] + ) -> None: + monkeypatch.setattr(server, "_config", {"jdtls": {"settings": {"java": {"diagnostic": {"filter": patterns}}}}}) + await _edit() + assert srv_mod._freshness.is_pending(URI) + assert live.call_count == 0 + + async def test_diagnostic_filter_uri_is_not_held(self, live: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + server, "_config", {"jdtls": {"settings": {"java": {"diagnostic": {"filter": ["*/src/*.java"]}}}}} + ) + live.reset_mock() + await _edit() + assert not srv_mod._freshness.is_pending(URI) + assert srv_mod._freshness.counts["ineligible"] == 1 + await _until(lambda: live.call_count == 1) + + async def test_unopened_file_is_not_held(self, live: MagicMock) -> None: + server._session_opened_uris.pop(URI, None) + await _edit() + assert not srv_mod._freshness.is_pending(URI) + await _until(lambda: live.call_count == 1) + + async def test_hold_off_keeps_old_behavior(self, live: MagicMock) -> None: + server._hold_mode = _HOLD_OFF + _jdtls_publishes([_java_diag("cached")]) + live.reset_mock() + await _edit() + await _until(lambda: live.call_count == 1) + assert _messages(_published(live)[0], "Java") == ["cached"] + + async def test_jdtls_unavailable_uses_debounce_path(self, live: MagicMock) -> None: + server._proxy._available = False + await _edit() + assert not srv_mod._freshness.is_pending(URI) + await _until(lambda: live.call_count == 1) + + async def test_jdtls_stop_releases_hold(self, live: MagicMock) -> None: + _jdtls_publishes([_java_diag("from dead jdtls")]) + live.reset_mock() + await _edit() + await _past_debounce() + server._proxy._mark_stopped() + assert server._proxy._diagnostics_cache == {} + await _until(lambda: live.call_count == 1) + assert _messages(_published(live)[0], "Java") == [] + + async def test_reinitialize_releases_hold(self, live: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + for attr in ( + "_config", + "_init_params", + "_user_suppress_patterns", + "_dynamic_features", + "_init_generation", + "_skip_jdtls_registration", + ): + monkeypatch.setattr(server, attr, getattr(server, attr)) + monkeypatch.setattr(srv_mod, "_jdtls_capabilities_registered", srv_mod._jdtls_capabilities_registered) + monkeypatch.setattr(srv_mod, "HandlerWiring", MagicMock()) + monkeypatch.delenv("JAVA_FUNCTIONAL_LSP_DIAG_HOLD", raising=False) + await _edit() + await _past_debounce() + with patch.object(srv_mod, "_load_config", return_value={}): + on_initialize( + lsp.InitializeParams( + capabilities=lsp.ClientCapabilities(), + root_uri=MODULE, + client_info=lsp.ClientInfo(name="Claude Code"), + ) + ) + assert not srv_mod._freshness.is_pending(URI) + assert server._hold_mode == _HOLD_CUSTOM_FIRST + await _until(lambda: live.call_count == 1) + + async def test_close_while_pending_cancels_hold(self, live: MagicMock) -> None: + _short_deadlines() + await _edit() + await _past_debounce() + hold_task = srv_mod._pending[URI] + await on_did_close(lsp.DidCloseTextDocumentParams(text_document=lsp.TextDocumentIdentifier(uri=URI))) + live.reset_mock() + await asyncio.sleep(0.4) # past the (short) deadline: an uncancelled hold would have published + assert live.call_count == 0 + assert hold_task.cancelled() + assert not srv_mod._freshness.is_pending(URI) + assert URI not in srv_mod._hold_events + + async def test_superseded_hold_task_does_not_publish_or_steal_event(self, live: MagicMock) -> None: + srv_mod._freshness.note_forwarded_change() + srv_mod._freshness.mark_pending(URI) + replacement = asyncio.create_task(asyncio.sleep(10)) + srv_mod._pending[URI] = replacement # the live task for URI + stray = asyncio.create_task(srv_mod._hold_until_fresh(URI, URI)) + await _past_min_age() + _jdtls_publishes([]) + await asyncio.wait_for(stray, timeout=2.0) + assert live.call_count == 0 + assert URI in srv_mod._hold_events, "the superseded task must not delete the live task's event" + + async def test_custom_first_publish_failure_does_not_strand_file(self, live: MagicMock) -> None: + server._hold_mode = _HOLD_CUSTOM_FIRST + with patch.object(srv_mod, "_run_analysis", side_effect=RuntimeError("boom")): + await _edit() + await _past_debounce() + assert not srv_mod._freshness.is_pending(URI) + _jdtls_publishes([]) + assert live.call_count == 1 + + async def test_encoded_jdtls_uri_releases_hold_and_publishes_client_uri(self, live: MagicMock) -> None: + client_uri = "file:///mod/src/My Foo.java" + _put_document(client_uri) + try: + await _edit(client_uri) + await _past_min_age() + _jdtls_publishes([_java_diag("err")], uri="file:///mod/src/My%20Foo.java") + await _until(lambda: live.call_count == 1) + assert _published(live)[0].uri == client_uri + assert _messages(_published(live)[0], "Java") == ["err"] + assert server._proxy.get_cached_diagnostics(client_uri)[0]["message"] == "err" + finally: + task = srv_mod._pending.pop(client_uri, None) + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + server._session_opened_uris.pop(srv_mod._normalize_uri(client_uri), None) + server.workspace.remove_text_document(client_uri) + + +# --- Proxy additions --- + + +class TestProxyFreshnessSupport: + def test_stop_clears_cache_and_notifies(self) -> None: + stopped = MagicMock() + proxy = JdtlsProxy(on_stopped=stopped) + proxy._diagnostics_cache["file:///a.java"] = [_java_diag("x")] + proxy._mark_stopped() + assert proxy._diagnostics_cache == {} + assert not proxy.is_available + stopped.assert_called_once() + + async def test_reader_eof_marks_stopped_once(self) -> None: + stopped = MagicMock() + proxy = JdtlsProxy(on_stopped=stopped) + proxy._available = True + reader = asyncio.StreamReader() + reader.feed_eof() + await proxy._reader_loop(reader) + proxy._mark_stopped() # stop() after the EOF must not notify again + stopped.assert_called_once() + + async def test_reader_error_marks_stopped(self) -> None: + stopped = MagicMock() + proxy = JdtlsProxy(on_stopped=stopped) + proxy._available = True + with patch("java_functional_lsp.proxy.read_message", AsyncMock(side_effect=ValueError("bad frame"))): + await proxy._reader_loop(asyncio.StreamReader()) + stopped.assert_called_once() + assert not proxy.is_available + + def test_dropped_request_method_is_truncated_and_capped(self) -> None: + proxy = JdtlsProxy() + proxy._note_dropped_request("x" * 500) + for i in range(60): + proxy._note_dropped_request(f"m{i}") + assert "x" * 100 in proxy._dropped_request_counts + assert len(proxy._dropped_request_counts) <= 51 + assert proxy._dropped_request_counts[""] == 11 + + def test_dropped_requests_counted_by_method(self, caplog: Any) -> None: + proxy = JdtlsProxy() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + for request_id in (1, 2): + proxy._dispatch_message( + {"id": request_id, "method": "workspace/configuration", "params": {"items": [{"section": "x"}]}} + ) + assert proxy._dropped_request_counts == {"workspace/configuration": 2} + assert caplog.text.count("'workspace/configuration' dropped") == 1 + assert "section" not in caplog.text + + +class TestLogLevel: + @pytest.mark.parametrize(("value", "expected"), [("DEBUG", logging.DEBUG), (" warning ", logging.WARNING)]) + def test_valid_values(self, monkeypatch: pytest.MonkeyPatch, value: str, expected: int) -> None: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_LOG_LEVEL", value) + assert srv_mod._log_level_from_env() == expected + + @pytest.mark.parametrize("value", ["verbose", "", "basicConfig"]) + def test_invalid_values_fall_back_to_info(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_LOG_LEVEL", value) + assert srv_mod._log_level_from_env() == logging.INFO diff --git a/tests/test_e2e_cross_file.py b/tests/test_e2e_cross_file.py new file mode 100644 index 0000000..5abb91f --- /dev/null +++ b/tests/test_e2e_cross_file.py @@ -0,0 +1,169 @@ +"""E2E: does jdtls converge a dependent file after a cross-file signature change? (#109, H2) + +Reproduces the issue's arity variant against a real jdtls: ``Foo`` gains a constructor +parameter, then ``Caller``'s call site is updated, both written to disk like an agent's +Edit tool does. With didSave jdtls converges every time; without it, in roughly 2 of 5 +runs jdtls's only post-edit publish for Caller still reports the old arity and is never +corrected (xfail, non-strict — the wrapper-side fix is tracked as #109 Part B). +""" + +from __future__ import annotations + +import asyncio +import os +import shutil +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import pytest + +from java_functional_lsp.proxy import JdtlsProxy, find_jdtls_java_home + +pytestmark = [ + pytest.mark.e2e, + pytest.mark.skipif(shutil.which("jdtls") is None, reason="jdtls binary not found on PATH"), + pytest.mark.skipif(find_jdtls_java_home() is None, reason="no Java 21+ found"), +] + +_POM = """\ + + 4.0.0 + example + crossfile + 1 + + 17 + 17 + + +""" +_FOO_V1 = "package p;\n\npublic class Foo {\n public Foo(int a, int b) {}\n}\n" +_FOO_V2 = "package p;\n\npublic class Foo {\n public Foo(int a, int b, int c) {}\n}\n" +_CALLER_V1 = "package p;\n\npublic class Caller {\n Foo make() {\n return new Foo(1, 2);\n }\n}\n" +_CALLER_V2 = "package p;\n\npublic class Caller {\n Foo make() {\n return new Foo(1, 2, 3);\n }\n}\n" +_NON_PROJECT_CODE = "16" +_READY_TIMEOUT_SEC = 120 +_CONVERGE_TIMEOUT_SEC = 30 +_QUIET_SEC = 4.0 + + +def _errors(diags: list[Any]) -> list[str]: + return [d.get("message", "") for d in diags if isinstance(d, dict) and d.get("severity") == 1] + + +@dataclass +class _CallerWatch: + """Records every jdtls publish for Caller.""" + + caller_uri: str + history: list[list[str]] = field(default_factory=list) + last: list[Any] = field(default_factory=list) + arrived: asyncio.Event = field(default_factory=asyncio.Event) + + def on_diagnostics(self, uri: str, diags: list[Any]) -> None: + if uri == self.caller_uri: + self.last = diags + self.history.append(_errors(diags)) + self.arrived.set() + + def project_ready(self) -> bool: + non_project = any(str(d.get("code")) == _NON_PROJECT_CODE for d in self.last if isinstance(d, dict)) + return not non_project and self.history[-1] == [] + + async def next_publish(self, timeout: float) -> bool: + self.arrived.clear() + try: + await asyncio.wait_for(self.arrived.wait(), timeout=timeout) + except asyncio.TimeoutError: + return False + return True + + async def wait_project_ready(self) -> bool: + """Wait for a Caller publish without the non-project (code 16) marker.""" + if self.history and self.project_ready(): + return True # published while the files were still being opened + deadline = asyncio.get_running_loop().time() + _READY_TIMEOUT_SEC + while asyncio.get_running_loop().time() < deadline: + if await self.next_publish(deadline - asyncio.get_running_loop().time()) and self.project_ready(): + return True + return False + + async def wait_quiet(self) -> None: + """Wait until Caller has published at least once and then stayed quiet.""" + deadline = asyncio.get_running_loop().time() + _CONVERGE_TIMEOUT_SEC + while asyncio.get_running_loop().time() < deadline: + if not await self.next_publish(_QUIET_SEC) and self.history: + return + + +async def _start_jdtls(root: Path, watch: _CallerWatch) -> JdtlsProxy: + proxy = JdtlsProxy(on_diagnostics=watch.on_diagnostics) + init_params = { + "processId": os.getpid(), + "rootUri": root.as_uri(), + "rootPath": str(root), + "capabilities": {"workspace": {"configuration": False, "workspaceFolders": False}}, + "initializationOptions": {}, + } + assert await proxy.start(init_params), "jdtls failed to start" + return proxy + + +@pytest.mark.timeout(_READY_TIMEOUT_SEC + _CONVERGE_TIMEOUT_SEC + 60) +@pytest.mark.parametrize( + "send_save", + [ + pytest.param(True, id="didSave"), + pytest.param( + False, + id="no-didSave", + marks=[ + pytest.mark.skipif( + not os.environ.get("JFL_E2E_MEASURE_H2"), + reason="measurement only (stale in ~2/5 runs); set JFL_E2E_MEASURE_H2=1 to run", + ), + pytest.mark.xfail( + strict=False, + reason="H2: without didSave jdtls re-validates Caller against the old Foo (#109 Part B)", + ), + ], + ), + ], +) +async def test_caller_converges_after_cross_file_arity_change(tmp_path: Path, send_save: bool) -> None: + src = tmp_path / "src" / "main" / "java" / "p" + src.mkdir(parents=True) + (tmp_path / "pom.xml").write_text(_POM) + foo, caller = src / "Foo.java", src / "Caller.java" + foo.write_text(_FOO_V1) + caller.write_text(_CALLER_V1) + watch = _CallerWatch(caller_uri=caller.as_uri()) + proxy = await _start_jdtls(tmp_path, watch) + try: + for path, text in ((foo, _FOO_V1), (caller, _CALLER_V1)): + await proxy.send_notification( + "textDocument/didOpen", + {"textDocument": {"uri": path.as_uri(), "languageId": "java", "version": 1, "text": text}}, + ) + if not await watch.wait_project_ready(): + pytest.skip("jdtls did not import the Maven project in time") + + # Mimic an agent's Edit tool: write the file, then didChange (+ didSave). + watch.history.clear() + for path, text in ((foo, _FOO_V2), (caller, _CALLER_V2)): + path.write_text(text) + uri = path.as_uri() + await proxy.send_notification( + "textDocument/didChange", + {"textDocument": {"uri": uri, "version": 2}, "contentChanges": [{"text": text}]}, + ) + if send_save: + await proxy.send_notification("textDocument/didSave", {"textDocument": {"uri": uri}}) + # A trailing publish can re-introduce the old-arity error after a clean one, + # so judge the last post-edit publish once jdtls has gone quiet. + await watch.wait_quiet() + assert watch.history, "jdtls never re-published Caller after the edit" + assert watch.history[-1] == [], f"Caller publishes after the edit (errors per publish): {watch.history}" + finally: + await proxy.stop() diff --git a/tests/test_e2e_hold.py b/tests/test_e2e_hold.py new file mode 100644 index 0000000..eb9a471 --- /dev/null +++ b/tests/test_e2e_hold.py @@ -0,0 +1,159 @@ +"""E2E through the real server + real jdtls with default hold constants (#109). + +Opens a Maven project where ``Foo`` references ``q.Bar`` without importing it, waits +for jdtls to report "Bar cannot be resolved", then adds the import. With the hold +(``custom-first``, what Claude Code gets) no publish after the fix may still carry the +resolved error; with ``off`` the previous behavior re-publishes it at the debounce. +""" + +from __future__ import annotations + +import asyncio +import os +import shutil +import sys +from pathlib import Path + +import pytest +from lsprotocol import types as lsp +from pygls.lsp.client import LanguageClient + +from java_functional_lsp.proxy import find_jdtls_java_home + +pytestmark = [ + pytest.mark.e2e, + pytest.mark.skipif(shutil.which("jdtls") is None, reason="jdtls binary not found on PATH"), + pytest.mark.skipif(find_jdtls_java_home() is None, reason="no Java 21+ found"), +] + +_POM = """\ + + 4.0.0 + example + hold + 1 + + 17 + 17 + + +""" +_BAR = "package q;\n\npublic class Bar {}\n" +_FOO_BROKEN = "package p;\n\npublic class Foo {\n Bar bar;\n}\n" +_FOO_FIXED = "package p;\n\nimport q.Bar;\n\npublic class Foo {\n Bar bar;\n}\n" +_UNRESOLVED = "Bar cannot be resolved" +_READY_TIMEOUT_SEC = 150 +_OBSERVE_SEC = 8.0 + + +def _has_unresolved(diags: list[lsp.Diagnostic]) -> bool: + return any(_UNRESOLVED in d.message for d in diags) + + +def _write_project(root: Path) -> Path: + (root / "pom.xml").write_text(_POM) + src = root / "src" / "main" / "java" + (src / "p").mkdir(parents=True) + (src / "q").mkdir(parents=True) + (src / "q" / "Bar.java").write_text(_BAR) + foo = src / "p" / "Foo.java" + foo.write_text(_FOO_BROKEN) + return foo + + +class _FooWatch: + """Records every publish the server sends for Foo.""" + + def __init__(self, foo_uri: str) -> None: + self.foo_uri = foo_uri + self.history: list[list[lsp.Diagnostic]] = [] + self.arrived = asyncio.Event() + + def on_publish(self, params: lsp.PublishDiagnosticsParams) -> None: + if params.uri == self.foo_uri: + self.history.append(list(params.diagnostics)) + self.arrived.set() + + async def wait_unresolved(self) -> bool: + deadline = asyncio.get_running_loop().time() + _READY_TIMEOUT_SEC + while not (self.history and _has_unresolved(self.history[-1])): + remaining = deadline - asyncio.get_running_loop().time() + if remaining <= 0: + return False + self.arrived.clear() + try: + await asyncio.wait_for(self.arrived.wait(), timeout=remaining) + except asyncio.TimeoutError: + return False + return True + + +async def _start_server(root: Path, mode: str, watch: _FooWatch) -> LanguageClient: + client = LanguageClient("e2e-hold", "1.0") + + def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a plain function + watch.on_publish(params) + + client.feature(lsp.TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS)(on_publish) + env = {**os.environ, "JAVA_FUNCTIONAL_LSP_DIAG_HOLD": mode} + await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) + await client.initialize_async( + lsp.InitializeParams( + process_id=os.getpid(), + root_uri=root.as_uri(), + capabilities=lsp.ClientCapabilities(), + client_info=lsp.ClientInfo(name="Claude Code"), + ) + ) + client.initialized(lsp.InitializedParams()) + return client + + +async def _stop_server(client: LanguageClient) -> None: + try: + await asyncio.wait_for(client.shutdown_async(None), timeout=5.0) + client.exit(None) + except Exception: + pass + try: + await asyncio.wait_for(client.stop(), timeout=5.0) + except Exception: + pass + + +@pytest.mark.timeout(_READY_TIMEOUT_SEC + 60) +@pytest.mark.parametrize("mode", ["custom-first", "off"]) +async def test_fixing_import_never_republishes_resolved_error(tmp_path: Path, mode: str) -> None: + foo = _write_project(tmp_path) + foo_uri = foo.as_uri() + watch = _FooWatch(foo_uri) + client = await _start_server(tmp_path, mode, watch) + try: + client.text_document_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=foo_uri, language_id="java", version=1, text=_FOO_BROKEN) + ) + ) + if not await watch.wait_unresolved(): + pytest.skip("jdtls did not report the unresolved type in time (project import too slow)") + + history = watch.history + before_fix = len(history) + foo.write_text(_FOO_FIXED) + client.text_document_did_change( + lsp.DidChangeTextDocumentParams( + text_document=lsp.VersionedTextDocumentIdentifier(uri=foo_uri, version=2), + content_changes=[lsp.TextDocumentContentChangeWholeDocument(text=_FOO_FIXED)], + ) + ) + await asyncio.sleep(_OBSERVE_SEC) + after_fix = history[before_fix:] + assert after_fix, "server published nothing after the fix" + stale = [i for i, diags in enumerate(after_fix) if _has_unresolved(diags)] + if mode == "off": + assert stale, "expected the pre-fix behavior to re-publish the resolved error" + else: + assert not stale, f"publishes {stale} after the fix still carried '{_UNRESOLVED}'" + assert not _has_unresolved(after_fix[-1]) + finally: + await _stop_server(client) diff --git a/tests/test_server.py b/tests/test_server.py index 2200422..4791837 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -469,7 +469,7 @@ def test_on_jdtls_diagnostics_project_file_marks_ready(self) -> None: patch("java_functional_lsp.server._fire_and_forget"), ): server._on_jdtls_diagnostics(uri, [real_diag]) - mock_pub.assert_called_once_with(uri) + mock_pub.assert_called_once_with(uri, trigger="jdtls") assert server._proxy.modules.get_state("file:///mod") == ModuleState.READY finally: server._proxy.modules.clear() @@ -861,7 +861,7 @@ def test_on_jdtls_diagnostics_matches_opened_uri_across_encodings(self) -> None: patch("java_functional_lsp.server._fire_and_forget"), ): server._on_jdtls_diagnostics("file:///a/has%20space.java", []) - mock_pub.assert_called_once_with("file:///a/has%20space.java") + mock_pub.assert_called_once_with("file:///a/has%20space.java", trigger="jdtls") @pytest.mark.parametrize( "entry", diff --git a/uv.lock b/uv.lock index 4a87e90..c669b5e 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.12.0" +version = "0.12.1" source = { editable = "." } dependencies = [ { name = "pygls" },