Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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)",
]
Expand Down
2 changes: 1 addition & 1 deletion src/java_functional_lsp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""java-functional-lsp: A Java LSP server enforcing functional programming best practices."""

__version__ = "0.12.0"
__version__ = "0.12.1"
53 changes: 47 additions & 6 deletions src/java_functional_lsp/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<other>".
_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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)."""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -1258,15 +1285,15 @@ 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)
except asyncio.CancelledError:
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.
Expand Down Expand Up @@ -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 = "<other>"
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."""
Expand All @@ -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
Loading
Loading