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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ How it works (v0.14.1):
2. **Fresh diagnostics only.** jdtls does not re-check a file that is already open when its classpath changes, so its errors can be minutes old. The server waits until jdtls is **build-idle**: no open `language/progressReport` task (indexing / "Searching…" tasks are ignored) and no progress event for 10 s. It then sends `java.project.refreshDiagnostics` for up to 3 demand files, most recently opened first, one at a time. Only the publish that answers that refresh counts, and only if the document still has the same content.
3. **Frontier.** The candidates come from the reactor index, which is built once per session from the modules reachable from the reactor root through `<modules>` (all profiles). They are the in-repo `<dependencies>` (compile, provided, runtime) of the demand module and of every module imported so far, including those inherited from in-repo parent poms. `dependencyManagement` is ignored. For a file under `src/test`, the demand module's test-scope and `test-jar` dependencies are included too.
4. **Candidates = frontier ∩ m2e markers.** A frontier module is imported only if m2e reports it missing on some pom (`[Offline / ]Missing artifact g:a:type[:classifier]:version`). The marker is the proof that no installed jar resolves it. A `test-jar` edge only matches a `test-jar`/`tests` marker. Candidates keep their declaration order, and high fan-in "hub" modules go last.
5. **One round.** Up to 8 candidates are added as **one** `didChangeWorkspaceFolders` event. The server waits for build-idle (at most 90 s) and refreshes the demand files again. If the fresh diagnostics are clean, it stops. If they are not, it runs the next round. Before deciding round k, it waits (at most 30 s) until the modules imported in round k−1 have published their own pom markers.
5. **One round.** Up to 8 candidates are added as **one** `didChangeWorkspaceFolders` event. The server waits for build-idle (at most 90 s) and refreshes the demand files again. If the fresh diagnostics are clean, it stops. If they are not, it runs the next round. Before deciding round k, it waits (at most 30 s) until the modules imported in round k−1 have published their own pom markers. A large module group's build can outlast one 90 s wait (measured: a 95-module/127-project group on products), so a still-busy jdtls does not stop the phase at once — the wait retries (up to 6 attempts, up to 10 minutes total) and the round resumes as soon as jdtls next reports build-idle. Only once that busy budget is exhausted does the phase stop with `jdtls-busy`.
6. **Stop.** Every stop is logged once and sent to the client once as a `window/logMessage`. Opening a file in a module that had no demand before starts the process again, unless a session limit (budget, rounds, wall clock, refresh cap) was reached. A stop of `jdtls-busy` or `no-fresh-diagnostics` before anything was imported lets the same module try again on its next demand; the same warning twice in a row is logged at DEBUG and not sent again.

If you later open a file in a group that contains one of these modules, the group folder replaces the module folder in the same workspace change. That module folder is never re-added.
Expand All @@ -332,7 +332,7 @@ Configuration (the repository config can only **lower** a limit; the environment
| `JAVA_FUNCTIONAL_LSP_DEPENDENCY_ROUNDS` (environment) | `0`–`20` (default `6`) | Rounds per session |
| `{"jdtls": {"dependencyRounds": N}}` in `.java-functional-lsp.json` | `0`–default | Lowers the rounds |

The remaining limits are fixed: 8 modules per round, a 5-minute import wall clock per session (counted only while imports run: from a round-1 import to its stop, excluding refresh time and the idle time between sessions of demand), 3 refreshes per round (a session cap of 3 × (rounds + 1) × 2, i.e. 42 with the default 6 rounds, so the rounds limit fires first), a 20 s refresh timeout with one retry, and a 90 s build-idle wait per round.
The remaining limits are fixed: 8 modules per round, a 5-minute import wall clock per session (counted only while imports run: from a round-1 import to its stop, excluding refresh time and the idle time between sessions of demand), 3 refreshes per round (a session cap of 3 × (rounds + 1) × 2, i.e. 42 with the default 6 rounds, so the rounds limit fires first), a 20 s refresh timeout with one retry, a 90 s build-idle wait per attempt, and up to 6 attempts (10 minutes total) before a busy jdtls gives up on a round.

Stop reasons (`jdtls: dependency-module import stopped (<reason>)`):

Expand All @@ -343,7 +343,7 @@ Stop reasons (`jdtls: dependency-module import stopped (<reason>)`):
| `no-candidates(markers-pending)` | Frontier modules exist, but m2e has not reported them missing yet (30 s wait) |
| `no-candidates(owner-has-jar)` | Frontier modules exist, m2e reports none of them missing: a jar in your local repository resolves them (see *stale installs* below) |
| `budget` / `rounds` / `wall-clock` / `refresh-cap` | A session limit was reached; later demand stops at once |
| `jdtls-busy` | jdtls did not become build-idle within 90 s (before the first refresh, or after an import) |
| `jdtls-busy` | jdtls did not become build-idle within 90 s, retried for up to 10 minutes (before the first refresh, or after an import) |
| `no-fresh-diagnostics` | jdtls did not answer the refresh, or did not re-publish the file, after one retry |

Limits:
Expand Down
2 changes: 1 addition & 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.14.1"
version = "0.14.2"
description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions"
readme = "README.md"
license = { text = "MIT" }
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.14.1"
__version__ = "0.14.2"
72 changes: 59 additions & 13 deletions src/java_functional_lsp/dependency_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@
REFRESH_RETRY_FACTOR = 2
IDLE_QUIET_SEC = 10.0
ROUND_TIMEOUT_SEC = 90.0
#: A busy jdtls-busy wait is retried (still waiting for build-idle) instead of stopping at once:
#: a 95-module/127-project group build routinely outlasts one 90 s round timeout (measured on
#: the products monorepo, v0.14.1 gate). Bounded so a build that never goes idle still stops.
BUSY_WAIT_BUDGET_SEC = 600.0
BUSY_WAIT_RETRIES = 6
REFRESH_TIMEOUT_SEC = 20.0
REFRESH_BACKOFF_SEC = 5.0
MARKER_WAIT_SEC = 30.0
Expand Down Expand Up @@ -409,6 +414,8 @@ def refresh_cap(self) -> int:
class Timing:
idle_quiet: float = IDLE_QUIET_SEC
round_timeout: float = ROUND_TIMEOUT_SEC
busy_wait_budget: float = BUSY_WAIT_BUDGET_SEC
busy_wait_retries: int = BUSY_WAIT_RETRIES
refresh_backoff: float = REFRESH_BACKOFF_SEC
marker_wait: float = MARKER_WAIT_SEC

Expand Down Expand Up @@ -792,13 +799,51 @@ def _root_of(self, module_dir: Path) -> Path:
self._roots[module_dir] = root
return root

async def _wait_idle(self, since: float | None) -> str | None:
"""Wait for build-idle, retrying within a busy budget so a build that outlasts one round
timeout is not a dead end (#DEV-v0.14.2, large module groups on products).

Each attempt waits up to ``round_timeout`` for :meth:`BuildIdle.wait`. Between attempts
this re-checks the session's existing limits (budget/rounds/wall-clock): if one has
already been reached, that is latched onto ``self._session.terminal`` (mirroring
:meth:`_select`) and returned immediately, so the caller reports and stops on the real
reason instead of a generic busy timeout, and later demand for the same module short-
circuits via the ``terminal`` check at the top of :meth:`_process` rather than retrying
forever. Only once the busy budget (``timing.busy_wait_budget``) or the retry count is
exhausted does this give up on idle itself, returning the final ``jdtls-busy``. Returns
``None`` when idle was reached.
"""
deadline = self._clock() + self.timing.busy_wait_budget
attempt = 0
while True:
if await self.idle.wait(since, self.timing.round_timeout):
return None
attempt += 1
# A terminal session limit outranks an ordinary busy timeout, even on what would
# otherwise be the final attempt: it must latch and report the real reason (not a
# retryable jdtls-busy) so a re-arm does not busy-wait through the same limit again.
limit = self._limit_reason()
if limit is not None:
self._session.terminal = limit
return limit
if attempt >= self.timing.busy_wait_retries or self._clock() >= deadline:
return STOP_BUSY
logger.info(
"jdtls: still busy after %.0fs, waiting for build-idle (attempt %d/%d, up to %.0fs more)",
attempt * self.timing.round_timeout,
attempt,
self.timing.busy_wait_retries,
max(deadline - self._clock(), 0.0),
)

async def _process(self, new_modules: list[Path]) -> str:
"""Probe the newly armed modules (one reactor root), then run rounds until a STOP reason."""
if self._session.terminal is not None:
return self._session.terminal
armed_at = self._clock()
if not await self.idle.wait(None, self.timing.round_timeout):
return STOP_BUSY
idle_stop = await self._wait_idle(None)
if idle_stop is not None:
return idle_stop
fresh = await self._refresh(self._demand_files(new_modules))
if fresh is None:
return self._session.terminal or STOP_NO_FRESH
Expand Down Expand Up @@ -850,9 +895,10 @@ async def _round(
def log(refresh: str, files: list[str]) -> None:
self._log_round(files, frontier, candidates, batch, index, self._clock() - sent_at, refresh)

if not await self.idle.wait(sent_at, self.timing.round_timeout):
log("skipped (busy)", demand)
return STOP_BUSY
idle_stop = await self._wait_idle(sent_at)
if idle_stop is not None:
log(f"skipped ({idle_stop})", demand)
return idle_stop
# The files with demand in this round (already most recent first), still open: an
# unsolicited publish in between never decides the round.
open_keys = self._open_keys()
Expand Down Expand Up @@ -951,19 +997,19 @@ def _log_round(
root = index.root if index is not None else Path("/")
shown = ", ".join(f"{ga} ({_display(target, root)})" for ga, target in batch)
logger.info(
"jdtls: dependency round %d: frontier %d, candidates %d, deferred %d, round took %.1fs, refresh %s, "
"demand left %d file(s); importing %d dependency module(s) (%d/%d used): %s",
"jdtls: dependency round %d: imported %d dependency module(s) (%d/%d used): %s -> build idle "
"(round took %.1fs) -> refresh %s, demand left %d file(s) (frontier %d, candidates %d, deferred %d)",
self._session.rounds,
frontier,
len(candidates),
len(candidates) - len(batch),
elapsed,
refresh,
len(demand),
len(batch),
self.used,
self.limits.budget,
shown,
elapsed,
refresh,
len(demand),
frontier,
len(candidates),
len(candidates) - len(batch),
)

def _import_time(self) -> float:
Expand Down
27 changes: 21 additions & 6 deletions src/java_functional_lsp/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,21 @@
_WORKSPACE_SCHEMA = "ws2"
#: The proxy's own record of the dependency modules it imported, beside the data dir.
_DEPS_RECORD_SUFFIX = ".deps.json"
#: stop(): shutdown request + exit, SIGTERM the JVM after this long, SIGKILL after twice as long.
#: stop(): shutdown request timeout, and the SIGTERM/SIGKILL wait after each signal.
_STOP_GRACE_SEC = 1.0
#: After the `exit` notification, wait this long for the JVM to exit **on its own** before
#: SIGTERM. Eclipse's ResourcesPlugin.getWorkspace().save() (its SaveManager) runs on exit and
#: writes the workspace .snap; SIGTERM mid-save can leave a torn .snap, which the *next* start
#: reports as "The workspace exited with unsaved changes in the previous session; refreshing
#: workspace to recover changes" (jdtls then falls back to jdt.ls-java-project for files under
#: an affected project). This is more likely mid-import, when the save has more to persist.
#: Separate from ``_STOP_GRACE_SEC`` (which also bounds the shutdown *request* reply) so a slow
#: shutdown reply cannot eat into the JVM's own exit budget. Not yet measured against a real
#: jdtls mid-import exit (#DEV-v0.14.2 item 2, deferred): chosen as a multiple of the cooperative
#: case (<1s, see test_shutdown.py) that keeps the total stop bound (shutdown reply + this +
#: SIGTERM wait + SIGKILL wait) at a few seconds, worst case, which client shutdown paths
#: (including Claude Code's) tolerate for a graceful child-process exit.
_EXIT_GRACE_SEC = 3.0

# Default jdtls initialization settings. Sent via initializationOptions.settings
# so they apply BEFORE the Maven import scan (didChangeConfiguration is too late).
Expand Down Expand Up @@ -1443,10 +1456,12 @@ async def expand_full_workspace(self) -> None:
self._expanded_groups.add(root_uri)

async def stop(self) -> None:
"""Shut jdtls down within about 3 s. Idempotent (shutdown, exit, a signal, init timeout).
"""Shut jdtls down within about 6 s worst case (cooperative case: well under 1 s).
Idempotent (shutdown, exit, a signal, init timeout).

The shutdown reply is read before the reader is cancelled. The JVM gets
``_STOP_GRACE_SEC`` to exit after ``exit``, then SIGTERM, then SIGKILL.
``_EXIT_GRACE_SEC`` to save and exit on its own after ``exit``, then SIGTERM
(``_STOP_GRACE_SEC``), then SIGKILL (``_STOP_GRACE_SEC``).
"""
async with self._stop_lock:
process = self._process
Expand Down Expand Up @@ -1475,12 +1490,12 @@ async def stop(self) -> None:
self._response_hooks.clear()

async def _terminate(self, process: asyncio.subprocess.Process) -> None:
loop = asyncio.get_running_loop()
deadline = loop.time() + _STOP_GRACE_SEC
try:
await self.send_request("shutdown", None, timeout=_STOP_GRACE_SEC)
await self.send_notification("exit", None)
await asyncio.wait_for(process.wait(), timeout=max(deadline - loop.time(), 0.05))
# A dedicated budget for the JVM to save and exit on its own (see _EXIT_GRACE_SEC):
# never shortened by time the shutdown reply already took.
await asyncio.wait_for(process.wait(), timeout=_EXIT_GRACE_SEC)
return
except (asyncio.TimeoutError, OSError):
pass
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e_maven.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ async def _collect(stream: asyncio.StreamReader | None, lines: list[str]) -> Non
lines.append(line.decode(errors="replace").rstrip())


_IMPORT_LINE_RE = re.compile(r"importing \d+ dependency module\(s\) \([^)]*\): (.*)$")
_IMPORT_LINE_RE = re.compile(r"imported \d+ dependency module\(s\) \([^)]*\): (.*?) -> build idle")
_GA_RE = re.compile(r"(com\.example:[A-Za-z0-9_.\-]+)")
_JDTLS_PID_RE = re.compile(r"jdtls subprocess started \(pid=(\d+)")

Expand Down
Loading
Loading