From 95629324fcf21a08387ce8eca7647e9b5e299019 Mon Sep 17 00:00:00 2001 From: Aviad Shiber Date: Wed, 30 Sep 2026 14:24:59 +0300 Subject: [PATCH 1/2] fix: resume a busy dependency-module round and give jdtls time to save on stop (v0.14.2) Follow-ups from the v0.14.1 products-gate evidence (#115): 1. A large module group's jdtls build routinely outlasts the fixed 90 s round timeout (measured: a 95-module/127-project service/boot group never went idle within 90 s across three gate runs, t2/t2b/t2c). The old code treated a busy timeout as a dead end: it stopped with jdtls-busy and un-armed the module, so only a new demand publish (which jdtls never sends without a fresh classpath change) could try again. _wait_idle() now retries the wait for build-idle within a bounded busy budget (up to 6 attempts, 10 minutes) instead of failing at the first 90 s timeout, so the round resumes as soon as jdtls next reports idle. The session's existing budget/rounds/wall-clock limits are still checked between attempts, and a final jdtls-busy STOP (which still un-arms the module) only fires once the busy budget itself is exhausted. 2. Mid-import shutdown: stop() gave the JVM only ~1 s after the exit notification before SIGTERM, shared with the shutdown-request timeout. Research (Eclipse bug 272648 and related Eclipse Platform/JDT-LS reports) confirms "the workspace exited with unsaved changes" comes from an incomplete ResourcesPlugin SaveManager .snap write, which SIGTERM mid-save can produce. A dedicated exit-grace constant now bounds the JVM's own post-exit save-and-exit (3 seconds), decoupled from the shutdown reply timeout. Total worst-case stop bound: about 6 seconds (shutdown reply + exit grace + SIGTERM wait + SIGKILL wait); the cooperative path is unaffected (well under 1 second). The exact real-jdtls mid-import exit duration was not measured (too costly for this change, deferred); the exit-grace budget is a reasoned estimate, stated in the code comment. 3. Added the missing proxy test: note_publish and idle.note_progress raising is caught and logged, and the next message of each kind is still handled (diagnostics cache updated / BuildIdle updated). 4. The round-log line now states the order explicitly (imported, then idle, then refresh), instead of reading as if the import happened after going clean. 5. Investigated tests/test_diagnostics_freshness.py's fixed-sleep helpers (_past_debounce, _past_min_age): every use is already followed by the bounded _until() poll (the prior CI-flake fix already covers this); no further fixed-sleep-then-assert instances were found there or elsewhere in tests/. Fail-before: the busy-round-resume test and the slow-to-save shutdown test were both run against a detached origin/main worktree and shown to fail there (a final busy stop, and a SIGTERM mid-save respectively), then the scratch worktree was removed. Co-Authored-By: Claude Sonnet 5 --- README.md | 6 +- pyproject.toml | 2 +- src/java_functional_lsp/__init__.py | 2 +- src/java_functional_lsp/dependency_modules.py | 54 +++++++++-- src/java_functional_lsp/proxy.py | 27 ++++-- tests/e2e_maven.py | 2 +- tests/test_dependency_modules.py | 19 +++- tests/test_shutdown.py | 96 ++++++++++++++++++- uv.lock | 2 +- 9 files changed, 183 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 5b014fd..a7b456d 100644 --- a/README.md +++ b/README.md @@ -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 `` (all profiles). They are the in-repo `` (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. @@ -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 ()`): @@ -343,7 +343,7 @@ Stop reasons (`jdtls: dependency-module import stopped ()`): | `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: diff --git a/pyproject.toml b/pyproject.toml index 801db80..c9221d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" } diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index f674674..ee541b5 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.14.1" +__version__ = "0.14.2" diff --git a/src/java_functional_lsp/dependency_modules.py b/src/java_functional_lsp/dependency_modules.py index 3b4ca2b..bdeff94 100644 --- a/src/java_functional_lsp/dependency_modules.py +++ b/src/java_functional_lsp/dependency_modules.py @@ -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 @@ -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 @@ -792,12 +799,39 @@ def _root_of(self, module_dir: Path) -> Path: self._roots[module_dir] = root return root + async def _wait_idle(self, since: float | None) -> bool: + """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), so a long busy + build still cannot outlive them. Only once the busy budget (``timing.busy_wait_budget``) + or the retry count is exhausted does this return False, i.e. a final ``jdtls-busy``. + """ + deadline = self._clock() + self.timing.busy_wait_budget + attempt = 0 + while True: + if await self.idle.wait(since, self.timing.round_timeout): + return True + attempt += 1 + if attempt >= self.timing.busy_wait_retries or self._clock() >= deadline: + return False + if self._limit_reason() is not None: + return False + 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): + if not await self._wait_idle(None): return STOP_BUSY fresh = await self._refresh(self._demand_files(new_modules)) if fresh is None: @@ -850,7 +884,7 @@ 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): + if not await self._wait_idle(sent_at): log("skipped (busy)", demand) return STOP_BUSY # The files with demand in this round (already most recent first), still open: an @@ -951,19 +985,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: diff --git a/src/java_functional_lsp/proxy.py b/src/java_functional_lsp/proxy.py index 1698292..f5805d3 100644 --- a/src/java_functional_lsp/proxy.py +++ b/src/java_functional_lsp/proxy.py @@ -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). @@ -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 @@ -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 diff --git a/tests/e2e_maven.py b/tests/e2e_maven.py index 5fb32bf..b1dfedf 100644 --- a/tests/e2e_maven.py +++ b/tests/e2e_maven.py @@ -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+)") diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py index b8ed168..4436a04 100644 --- a/tests/test_dependency_modules.py +++ b/tests/test_dependency_modules.py @@ -604,6 +604,22 @@ async def test_repeated_busy_is_announced_once(self) -> None: assert fake.deps.last_stop == STOP_BUSY assert len(fake.notified) == 1 + async def test_busy_beyond_one_round_timeout_resumes_when_idle_returns(self) -> None: + """A build that outlasts one round timeout is not a dead end (v0.14.2): the busy wait + retries and the phase resumes once BuildIdle next reports idle, instead of stopping and + un-arming the module at the first timeout. Only Timing fields that exist on v0.14.1 + (round_timeout/idle_quiet/refresh_backoff/marker_wait) are set here, so this test also + serves as the fail-before reproduction against the pre-fix code.""" + fake = _Fake(timing=Timing(idle_quiet=0.01, round_timeout=0.05, refresh_backoff=0.01, marker_wait=0.1)) + fake.deps.idle.note_progress(_progress("build")) # busy past this round's timeout + loop = asyncio.get_running_loop() + # Completes well after one round_timeout (0.05s) but well within any busy budget. + loop.call_later(0.18, fake.deps.idle.note_progress, _progress("build", complete=True)) + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + async def test_no_fresh_at_the_probe_re_arms(self) -> None: fake = _Fake() fake.publish = False @@ -985,7 +1001,8 @@ async def test_round_log_names_the_imports(self, caplog: pytest.LogCaptureFixtur await fake.settle() rounds = [r.getMessage() for r in caplog.records if "dependency round" in r.getMessage()] assert len(rounds) == 2 - assert "importing 1 dependency module(s) (1/30 used): g:mid (groupA/mid)" in rounds[0] + assert "imported 1 dependency module(s) (1/30 used): g:mid (groupA/mid)" in rounds[0] + assert rounds[0].index("imported") < rounds[0].index("build idle") < rounds[0].index("refresh") assert "refresh errors" in rounds[0] assert "refresh clean" in rounds[1] assert any("stopped (clean)" in r.getMessage() for r in caplog.records) diff --git a/tests/test_shutdown.py b/tests/test_shutdown.py index 8cbe08b..f81bb5f 100644 --- a/tests/test_shutdown.py +++ b/tests/test_shutdown.py @@ -57,6 +57,33 @@ def read(): """ _DEAF = "import time; time.sleep(60)" _STUBBORN = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)" +_SLOW_TO_SAVE = r""" +import json, sys, time +def read(): + headers = {} + while True: + line = sys.stdin.buffer.readline() + if not line: + return None + line = line.strip() + if not line: + break + k, _, v = line.decode().partition(":") + headers[k.strip().lower()] = v.strip() + return json.loads(sys.stdin.buffer.read(int(headers["content-length"]))) +while True: + msg = read() + if msg is None: + sys.exit(0) + if msg.get("method") == "exit": + time.sleep(1.5) # simulates the Eclipse SaveManager still writing the workspace .snap + sys.exit(0) + if msg.get("method") == "shutdown": + reply = {"jsonrpc": "2.0", "id": msg["id"], "result": None} + body = json.dumps(reply).encode() + sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body) + body) + sys.stdout.buffer.flush() +""" async def _proxy_with(script: str) -> tuple[JdtlsProxy, asyncio.subprocess.Process]: @@ -89,17 +116,32 @@ async def test_deaf_jdtls_gets_sigterm(self) -> None: proxy, proc = await _proxy_with(_DEAF) started = time.monotonic() await proxy.stop() - assert time.monotonic() - started < 3.5 + # _STOP_GRACE_SEC (shutdown reply) + _EXIT_GRACE_SEC (natural-exit wait) + slack. + assert time.monotonic() - started < 5.5 assert proc.returncode == -signal.SIGTERM @pytest.mark.timeout(20) - async def test_stubborn_jdtls_gets_sigkill_within_three_seconds(self) -> None: + async def test_stubborn_jdtls_gets_sigkill(self) -> None: proxy, proc = await _proxy_with(_STUBBORN) started = time.monotonic() await proxy.stop() elapsed = time.monotonic() - started assert proc.returncode == -signal.SIGKILL - assert 1.5 < elapsed < 3.5 + # _STOP_GRACE_SEC + _EXIT_GRACE_SEC + _STOP_GRACE_SEC (SIGTERM wait), then SIGKILL. + assert 4.5 < elapsed < 6.5 + + @pytest.mark.timeout(20) + async def test_jdtls_slow_to_save_still_exits_on_its_own(self, caplog: pytest.LogCaptureFixture) -> None: + """A jdtls that takes longer than _STOP_GRACE_SEC (but less than _EXIT_GRACE_SEC) to + save and exit after ``exit`` is not SIGTERMed mid-save (v0.14.2, item 2).""" + proxy, proc = await _proxy_with(_SLOW_TO_SAVE) + started = time.monotonic() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + await proxy.stop() + elapsed = time.monotonic() - started + assert proc.returncode == 0 # exited on its own, not killed by a signal + assert "SIGTERM" not in caplog.text + assert 1.5 <= elapsed < 3.0 @pytest.mark.timeout(20) async def test_stop_is_idempotent(self) -> None: @@ -300,6 +342,54 @@ def boom(*_a: Any) -> None: ) proxy._handle_notification({"method": "language/progressReport", "params": {"id": "x"}}) + def test_note_publish_raising_does_not_break_the_next_publish( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """A publishDiagnostics that makes ``note_publish`` raise is caught and logged; the + cache still updates, and the *next* publish is handled normally (v0.14.2, item 3).""" + proxy = JdtlsProxy() + + def boom(*_a: Any) -> None: + raise RuntimeError("boom") + + monkeypatch.setattr(proxy.dependency_modules, "note_publish", boom) + err = {"severity": 1, "message": "Base cannot be resolved to a type"} + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.proxy"): + proxy._handle_notification( + { + "method": "textDocument/publishDiagnostics", + "params": {"uri": "file:///r/A.java", "diagnostics": [err]}, + } + ) + assert proxy._diagnostics_cache[proxy._uri_key("file:///r/A.java")] == [err] + assert "dependency-module bookkeeping failed" in caplog.text + + monkeypatch.undo() # note_publish behaves normally again + second = [{"severity": 1, "message": "second"}] + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": "file:///r/B.java", "diagnostics": second}} + ) + assert proxy._diagnostics_cache[proxy._uri_key("file:///r/B.java")] == second + + def test_note_progress_raising_does_not_break_the_next_progress( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """Same guard for ``idle.note_progress``: a raising progress report is caught and logged, + and the next progress report still updates ``BuildIdle`` (v0.14.2, item 3).""" + proxy = JdtlsProxy() + + def boom(*_a: Any) -> None: + raise RuntimeError("boom") + + monkeypatch.setattr(proxy.dependency_modules.idle, "note_progress", boom) + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.proxy"): + proxy._handle_notification({"method": "language/progressReport", "params": {"id": "x", "task": "build"}}) + assert "build-idle bookkeeping failed" in caplog.text + + monkeypatch.undo() # idle.note_progress behaves normally again + proxy._handle_notification({"method": "language/progressReport", "params": {"id": "y", "task": "build"}}) + assert proxy.dependency_modules.idle.open_tasks == 1 + def _frame(msg: dict[str, Any]) -> bytes: body = json.dumps(msg).encode() diff --git a/uv.lock b/uv.lock index b06ae30..4555445 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.14.1" +version = "0.14.2" source = { editable = "." } dependencies = [ { name = "pygls" }, From bd6e087933edad112afb241a3508951649eb2daa Mon Sep 17 00:00:00 2001 From: Aviad Shiber Date: Wed, 30 Sep 2026 15:34:00 +0300 Subject: [PATCH 2/2] fix: latch the real session-limit reason through a busy retry (PR #117) _wait_idle's busy-retry loop returned a bare busy timeout even when a session limit (budget/rounds/wall-clock) had already been reached mid-retry, instead of latching self._session.terminal like _select does. Since the generic jdtls-busy reason is retryable, the module was un-armed and its next demand re-entered the same limited session and busy-waited again, repeating indefinitely on a persistently busy jdtls -- exactly the large-module-group scenario this PR targets. _wait_idle now returns the real STOP reason (or None on idle) and latches it onto the session before the busy-retry exhaustion check, so a terminal limit is never masked as jdtls-busy even on the final retry attempt, and _process/_round log and report the true reason. Adds two tests covering previously-untested _wait_idle paths (the busy_wait_budget deadline, and a session limit reached mid-retry) plus a third for the limit-vs-exhaustion race on the final attempt; each was verified to fail against a hand-mutated pre-fix reproduction. Co-Authored-By: Claude Sonnet 5 --- src/java_functional_lsp/dependency_modules.py | 38 +++++--- tests/test_dependency_modules.py | 96 +++++++++++++++++++ 2 files changed, 121 insertions(+), 13 deletions(-) diff --git a/src/java_functional_lsp/dependency_modules.py b/src/java_functional_lsp/dependency_modules.py index bdeff94..571f881 100644 --- a/src/java_functional_lsp/dependency_modules.py +++ b/src/java_functional_lsp/dependency_modules.py @@ -799,25 +799,35 @@ def _root_of(self, module_dir: Path) -> Path: self._roots[module_dir] = root return root - async def _wait_idle(self, since: float | None) -> bool: + 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), so a long busy - build still cannot outlive them. Only once the busy budget (``timing.busy_wait_budget``) - or the retry count is exhausted does this return False, i.e. a final ``jdtls-busy``. + 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 True + 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 False - if self._limit_reason() is not None: - return False + 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, @@ -831,8 +841,9 @@ async def _process(self, new_modules: list[Path]) -> str: if self._session.terminal is not None: return self._session.terminal armed_at = self._clock() - if not await self._wait_idle(None): - 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 @@ -884,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._wait_idle(sent_at): - 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() diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py index 4436a04..8d0f88e 100644 --- a/tests/test_dependency_modules.py +++ b/tests/test_dependency_modules.py @@ -620,6 +620,102 @@ async def test_busy_beyond_one_round_timeout_resumes_when_idle_returns(self) -> assert fake.sent == [["g:mid"], ["g:owner"]] assert fake.deps.last_stop == STOP_CLEAN + async def test_busy_wait_budget_cuts_the_retry_loop_short(self) -> None: + """The busy_wait_budget deadline can end the busy-retry loop before busy_wait_retries + would (PR #117 review). Without the deadline check, the loop would only give up after + busy_wait_retries attempts -- 100 * 0.05s = 5s here -- well past settle()'s timeout, so + this test fails loudly (a timeout AssertionError, not a wrong-value assertion) if that + check is deleted.""" + fake = _Fake( + timing=Timing( + idle_quiet=0.01, + round_timeout=0.05, + refresh_backoff=0.01, + marker_wait=0.1, + busy_wait_retries=100, + busy_wait_budget=0.12, + ) + ) + fake.deps.idle.note_progress(_progress("build")) # never completes + fake.start() + await fake.settle(timeout=1.0) + assert fake.deps.last_stop == STOP_BUSY + + async def test_session_limit_cuts_a_busy_retry_short(self) -> None: + """A session limit (wall-clock here) reached mid busy-retry stops `_wait_idle` at once + via `_limit_reason`, latching the real reason onto `_session.terminal` (mirroring + `_select`) instead of returning a bare busy timeout (PR #117 review). Before the fix, + `_wait_idle` returned `False` for this case exactly like an ordinary busy timeout, so the + caller always reported `STOP_BUSY`; since that is retryable, `_run` un-armed the module + and the next demand publish re-entered the same limited session and busy-waited again, + repeating indefinitely instead of stopping for good.""" + extra = f"file://{X}/src/main/java/X.java" + fake = _Fake( + timing=Timing( + idle_quiet=0.01, + round_timeout=0.05, + refresh_backoff=0.01, + marker_wait=0.1, + busy_wait_retries=100, + busy_wait_budget=10.0, + ), + limits=Limits(wall_clock=0.02), + open_files=[MAIN_FILE, extra], + ) + original = fake._send + + async def send_and_build(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + await original(added, removed) + fake.deps.idle.note_progress(_progress("import")) # the import never finishes building + + fake.deps._send_folders = send_and_build + fake.start() + await fake.settle(timeout=1.0) + assert fake.deps.last_stop == STOP_WALL_CLOCK + assert fake.deps._session.terminal == STOP_WALL_CLOCK + refreshed = len(fake.refreshed) + sent = len(fake.sent) + # A *different*, not-yet-armed module demands next: the latched session limit must stop + # it at once (README: "A session limit was reached; later demand stops at once"), not + # re-enter the busy-retry loop for another round of the same limited session. + fake.deps.note_publish(extra, DEMAND) + await fake.settle() + assert fake.deps.last_stop == STOP_WALL_CLOCK + assert len(fake.refreshed) == refreshed + assert len(fake.sent) == sent # short-circuited via `terminal`: no retry storm + + async def test_session_limit_on_the_final_busy_attempt_still_latches(self) -> None: + """A session limit reached on exactly the *last* busy-retry attempt (busy_wait_retries=1 + here) must still latch the real reason onto `_session.terminal`, not fall through to a + retryable `STOP_BUSY` because the retry count is also exhausted on that same attempt. + The limit check must outrank the exhaustion check: checking exhaustion first would return + `jdtls-busy` on the final attempt even though the session was already over its limit, which + is the same "later demand re-enters and busy-waits forever" bug as + ``test_session_limit_cuts_a_busy_retry_short``, just triggered by the retry count instead + of the busy budget racing the limit.""" + fake = _Fake( + timing=Timing( + idle_quiet=0.01, + round_timeout=0.05, + refresh_backoff=0.01, + marker_wait=0.1, + busy_wait_retries=1, + busy_wait_budget=10.0, + ), + limits=Limits(wall_clock=0.02), + ) + original = fake._send + + async def send_and_build(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + await original(added, removed) + fake.deps.idle.note_progress(_progress("import")) # the import never finishes building + + fake.deps._send_folders = send_and_build + fake.start() + await fake.settle(timeout=1.0) + assert fake.deps.last_stop == STOP_WALL_CLOCK + assert fake.deps._session.terminal == STOP_WALL_CLOCK + async def test_no_fresh_at_the_probe_re_arms(self) -> None: fake = _Fake() fake.publish = False