diff --git a/README.md b/README.md index 874358e..5b014fd 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ moving on. Fix any type errors or missing imports immediately. | 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)). The plugin's hook waits up to 3s for them; if jdtls is slower (large projects), raise `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` (max 4). See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | -| False "X cannot be resolved" / "The hierarchy of the type X is inconsistent" on classes from another Maven group of the same repository | The server imports such modules automatically when m2e reports them missing. See [Dependencies on modules in other Maven groups](#dependencies-on-modules-in-other-maven-groups) for the log lines to check, the budget (`JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`) and the stale-install case | +| False "X cannot be resolved" / "The hierarchy of the type X is inconsistent" on classes from another Maven group of the same repository | The server imports such modules automatically, only as far as the open file needs. See [Dependencies on modules in other Maven groups](#dependencies-on-modules-in-other-maven-groups) for the stop reasons, the log lines to check, the limits (`JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`, `JAVA_FUNCTIONAL_LSP_DEPENDENCY_ROUNDS`) and the stale-install case | ### Other Editors @@ -310,39 +310,57 @@ To force a clean rebuild: `rm -rf ~/.cache/jdtls-data/` ### Dependencies on modules in other Maven groups -To keep jdtls fast and within its heap, the server imports only the Maven *group* of the file you open (its tightest parent pom with ``), plus up to 5 more groups as you navigate. A module in that group can depend on a reactor module in *another* group. m2e then looks that dependency up in the local Maven repository at the reactor's version, often a `${revision}` default that is never installed. Every symbol from that module then shows as a false error: "cannot be resolved", "is undefined for the type", or "The hierarchy of the type X is inconsistent" ([#110](https://github.com/aviadshiber/java-functional-lsp/issues/110)). The server fixes this by importing the missing module itself. +To keep jdtls fast and within its heap, the server imports only the Maven *group* of the file you open (its tightest parent pom with ``), plus up to 5 more groups as you navigate. A module in that group can depend on a reactor module in *another* group. m2e then looks that dependency up in the local Maven repository at the reactor's version, often a `${revision}` default that is never installed. Every symbol from that module then shows as a false error: "cannot be resolved", "is undefined for the type", or "The hierarchy of the type X is inconsistent" ([#110](https://github.com/aviadshiber/java-functional-lsp/issues/110)). The server fixes this by importing the missing modules itself, **only as far as the open file needs**. (v0.14.0 imported every module any pom reported missing. On a large monorepo that cascaded through the transitive closure to 60 modules, 3 GB of jdtls heap, and 30 s timeouts on every request.) -How it works: +How it works (v0.14.1): -1. m2e reports the dependency as an error on the dependent's `pom.xml`: `Missing artifact com.example:common:jar:1.0` (prefixed with `Offline / ` when offline). -2. The server looks the `groupId:artifactId` up in an index of the reactor. The index is built once per session and covers the modules reachable from the reactor root through ``, with all profiles included. -3. If the artifact is a module of the repository and no imported folder covers it yet, the server adds the module's directory as a jdtls workspace folder. Additions are batched into one `didChangeWorkspaceFolders` per 500 ms. An added module that is missing its own in-repo dependencies reports them the same way, so the dependency closure is imported only as far as it is actually missing. -4. jdtls fixes the dependent's classpath within a fraction of a second, but it does not re-check files that are already open. When jdtls reports that a project's classpath was updated, the server asks it to re-validate every open `.java` file of that project (`java.project.refreshDiagnostics`). Those results go through the [diagnostics hold](#fresh-jdtls-diagnostics-after-edits). +1. **Demand.** An open `.java` file whose jdtls diagnostics hold #110-class errors (unresolved import or type, "undefined for the type", "hierarchy … inconsistent", "indirectly referenced from required .class files", "must override or implement a supertype method") starts the process for its module. Other open files, and files you never opened, never trigger an import. +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. +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. -Configuration: +Configuration (the repository config can only **lower** a limit; the environment can raise it up to the hard maximum): | Setting | Values | Effect | |---------|--------|--------| -| `JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES` (environment) | `0`–`200` (default `60`) | Session budget of dependency-module folders; `0` disables the import | -| `{"jdtls": {"dependencyModules": N}}` in `.java-functional-lsp.json` | same | Same budget; the environment variable wins | +| `JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES` (environment) | `0`–`200` (default `30`) | Session budget of dependency-module folders; `0` disables the import | +| `{"jdtls": {"dependencyModules": N}}` in `.java-functional-lsp.json` | `0`–default | Lowers the budget (a higher value is ignored with a warning) | +| `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. + +Stop reasons (`jdtls: dependency-module import stopped ()`): + +| Reason | Meaning | +|--------|---------| +| `clean` | The refreshed demand files have no #110-class errors left | +| `no-candidates(none)` | Nothing in the frontier: the errors are not caused by an unimported in-repo module | +| `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) | +| `no-fresh-diagnostics` | jdtls did not answer the refresh, or did not re-publish the file, after one retry | Limits: -- **Budget.** At most N module folders are added per session. A folder that a group later replaces still counts. When the budget runs out, the log shows a `WARNING` listing the modules left unresolved. Raise the budget, or open a file in those modules' group. -- **Stale local installs are not detected.** If an old build of the sibling is installed at the same version in your local repository, m2e resolves the dependency from that jar and reports nothing. You then see the installed version's API, not the source. Run `mvn install` for that module again, or delete it from the local repository. +- **Stale local installs are not detected.** If an old build of the sibling is installed at the same version in your local repository, m2e resolves the dependency from that jar and reports nothing. You then see the installed version's API, not the source, and the import stops with `no-candidates(owner-has-jar)`. Run `mvn install` for that module again, or delete it from the local repository (`~/.m2/repository///`). - **Maven only.** Gradle projects are unchanged. -- **Index bounds.** The index skips poms larger than 1 MB, poms with `.deps.json`, and the budget counts only this session's imports. Troubleshooting (the server log is its stderr, as captured by your LSP client): -- `jdtls: pom.xml errors changed for : … Missing artifact g:a:…` means m2e could not resolve that dependency. +- `jdtls: pom.xml errors changed for : … Missing artifact g:a:…` means m2e could not resolve that dependency. It is logged at INFO for modules with an open file, and at DEBUG for imported dependency modules. - `jdtls: reactor index of : N modules from M poms` means the index was built. `(truncated)` means it hit a bound. -- `jdtls: importing K dependency module(s) (used/budget): g:a (path), …` means those modules were added. -- `jdtls: classpath of updated, refreshing K open file(s)` means open files were re-checked. +- `jdtls: dependency round k: frontier F, candidates C, deferred D, round took Ts, refresh clean|errors|failed, …; importing K dependency module(s) (used/budget): g:a (path), …` is logged once per round. +- `jdtls: dependency-module import stopped (): …` gives the reason (table above). A session summary follows when jdtls stops. - If the errors stay and nothing was imported, the artifact is not a module of this reactor (check the `` path that should reach it), or it is a real external artifact missing from your repository. -- m2e caches failed lookups: `*.lastUpdated` files in the local repository, and the jdtls workspace in `~/.cache/jdtls-data/`. If errors persist after the module is imported, clear the jdtls cache as described above. +- m2e caches failed lookups in `*.lastUpdated` files in the local repository. The jdtls workspace of a module lives in `~/.cache/jdtls-data//`, where `` is the directory named in the `jdtls subprocess started (pid=…, data=…)` log line. If errors persist after the module is imported, stop the editor, delete that directory (and its `.deps.json`), and reopen. v0.14.1 changed the workspace key, so workspaces bloated by v0.14.0 are not reused, and the LRU eviction removes them. ### Fresh jdtls diagnostics after edits diff --git a/pyproject.toml b/pyproject.toml index 6f34e6d..801db80 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "java-functional-lsp" -version = "0.14.0" +version = "0.14.1" description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions" readme = "README.md" license = { text = "MIT" } @@ -26,7 +26,7 @@ classifiers = [ "Topic :: Software Development :: Quality Assurance", ] dependencies = [ - "pygls>=1.3.0", + "pygls>=2.0", "tree-sitter>=0.23.0", "tree-sitter-java>=0.23.0", ] diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index 7aa5dc1..f674674 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.0" +__version__ = "0.14.1" diff --git a/src/java_functional_lsp/dependency_modules.py b/src/java_functional_lsp/dependency_modules.py index bb8928b..3b4ca2b 100644 --- a/src/java_functional_lsp/dependency_modules.py +++ b/src/java_functional_lsp/dependency_modules.py @@ -1,81 +1,240 @@ -"""Import missing in-repo Maven modules as jdtls workspace folders (#110). +"""Import missing in-repo Maven modules as jdtls workspace folders, only as far as needed (#110). jdtls imports only the opened file's Maven group. A dependency on a reactor module in -another group is then resolved by m2e from the local repository at ``${revision}``, -where it is usually missing, and every symbol from it is "cannot be resolved". m2e -reports it as an Error diagnostic on the dependent's pom.xml -(``[Offline / ]Missing artifact g:a:type:version``). - -``DependencyModules`` turns that signal into a batched, debounced -``workspace/didChangeWorkspaceFolders`` add of the module directories found in the -reactor index, within a session budget. Modules added this way report their own -missing dependencies through the same signal, so the closure is imported round by -round, only as far as it is actually missing. - -jdtls fixes the dependent's classpath within a fraction of a second, but it never -republishes diagnostics for documents that are already open. ``ClasspathRefresher`` -therefore sends ``java.project.refreshDiagnostics`` for every open ``.java`` file -under a project whose classpath was updated. - -Both classes are asyncio-only (no locks) and take their side effects as callables, -so they are unit-testable without jdtls. +another group is then resolved by m2e from the local repository at ``${revision}``, where it +is usually missing, and every symbol from it is "cannot be resolved". m2e reports that as an +Error diagnostic on the pom.xml files (``[Offline / ]Missing artifact g:a:type:version``). + +v0.14.0 imported every in-repo GA any pom reported missing; each import surfaced the next +layer of the transitive closure, up to the 60-module budget (3 GB of jdtls heap and 30 s +timeouts on products). ``DependencyModules`` now imports in bounded **rounds** that run only +while an open file has **fresh demand**: + +* **Demand**: an open ``.java`` file whose diagnostics hold #110-class errors (unresolved + import/type, "undefined for the type", "hierarchy ... inconsistent", ...). +* **Fresh**: jdtls never re-publishes an open file after its classpath changes, so the + round asks for it: after **build-idle** (``BuildIdle``) it sends + ``java.project.refreshDiagnostics`` for up to 3 demand files, one at a time. Only the last + publish for that file between the send and the command's response counts, and only when + the document still has the content it had then. +* **Frontier**: the in-repo ```` (plus those inherited from in-repo parent + poms) of the demand modules and of every module imported so far, minus what is imported, + covered by an imported group, or retired. Test-scope edges only for a demand file under + ``src/test``, and only from the demand module. +* **Candidates**: the frontier ∩ m2e "Missing artifact" markers (proof that no installed jar + resolves it), in declaration order with high fan-in "hub" modules last, at most + ``per_round`` per round, sent as **one** didChangeWorkspaceFolders event. +* **STOP** (fixed reasons, logged and sent once to the client): ``clean``, + ``no-candidates(none|markers-pending|owner-has-jar)``, ``budget``, ``rounds``, + ``wall-clock``, ``refresh-cap``, ``jdtls-busy``, ``no-fresh-diagnostics``. Opening a file + in a module that has not had demand before re-arms it, unless a session limit is + exhausted. A phase that stops ``jdtls-busy`` / ``no-fresh-diagnostics`` before importing + anything un-arms its modules, so their next demand publish tries again. + +Everything is asyncio-only (no locks). Side effects are callables, and every wait is a +constructor parameter, so the state machine is unit-testable without jdtls. """ from __future__ import annotations import asyncio +import json import logging import os +import tempfile +import time from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping +from dataclasses import dataclass, field from pathlib import Path from typing import Any from urllib.parse import unquote, urlparse -from .reactor import ReactorIndex, build_reactor_index +from .reactor import Marker, ReactorIndex, build_reactor_index logger = logging.getLogger(__name__) ENV_BUDGET = "JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES" -DEFAULT_BUDGET = 60 +ENV_ROUNDS = "JAVA_FUNCTIONAL_LSP_DEPENDENCY_ROUNDS" +DEFAULT_BUDGET = 30 MAX_BUDGET = 200 -ADD_DEBOUNCE_SEC = 0.5 -REFRESH_DEBOUNCE_SEC = 1.0 -REFRESH_TIMEOUT_SEC = 10.0 -_WARN_LIST_MAX = 20 +DEFAULT_ROUNDS = 6 +MAX_ROUNDS = 20 + +#: Internal constants (v0.14.1 design): not user knobs. +PER_ROUND = 8 +WALL_CLOCK_SEC = 300.0 +REFRESHES_PER_ROUND = 3 +#: Refreshes per session, per allowed round (the probe counts as one), retries included: the +#: default cap is ``REFRESHES_PER_ROUND * (rounds + 1) * 2``, so the rounds limit fires first. +REFRESH_RETRY_FACTOR = 2 +IDLE_QUIET_SEC = 10.0 +ROUND_TIMEOUT_SEC = 90.0 +REFRESH_TIMEOUT_SEC = 20.0 +REFRESH_BACKOFF_SEC = 5.0 +MARKER_WAIT_SEC = 30.0 +HUB_FAN_IN = 25 +#: Bounded demand scan: diagnostics per file, characters per message. +MAX_DIAGNOSTICS_SCANNED = 500 +MAX_MESSAGE_CHARS = 1000 Folder = dict[str, str] SendFolders = Callable[[list[Folder], list[Folder]], Awaitable[None]] +#: ``(uri, on_response) -> answered``; *on_response* runs synchronously when jdtls's reply is dispatched. +SendRefresh = Callable[[str, Callable[[], None]], Awaitable[bool]] +STOP_CLEAN = "clean" +STOP_NO_CANDIDATES_NONE = "no-candidates(none)" +STOP_NO_CANDIDATES_MARKERS = "no-candidates(markers-pending)" +STOP_NO_CANDIDATES_JAR = "no-candidates(owner-has-jar)" +STOP_BUDGET = "budget" +STOP_ROUNDS = "rounds" +STOP_WALL_CLOCK = "wall-clock" +STOP_BUSY = "jdtls-busy" +STOP_NO_FRESH = "no-fresh-diagnostics" +STOP_REFRESHES = "refresh-cap" +STOP_REASONS = ( + STOP_CLEAN, + STOP_NO_CANDIDATES_NONE, + STOP_NO_CANDIDATES_MARKERS, + STOP_NO_CANDIDATES_JAR, + STOP_BUDGET, + STOP_ROUNDS, + STOP_WALL_CLOCK, + STOP_BUSY, + STOP_NO_FRESH, + STOP_REFRESHES, +) +#: Session limits: once hit, later demand stops at once with the same reason. +_TERMINAL = frozenset({STOP_BUDGET, STOP_ROUNDS, STOP_WALL_CLOCK, STOP_REFRESHES}) +#: Stops before any import that un-arm the phase's modules (the next demand tries again). +_RETRYABLE = frozenset({STOP_BUSY, STOP_NO_FRESH}) +_WARN_STOPS = frozenset({STOP_BUSY, STOP_NO_FRESH}) +_STOP_HINTS = { + STOP_NO_CANDIDATES_JAR: "an installed jar may be stale; see the README (troubleshooting)", + STOP_BUDGET: f"raise {ENV_BUDGET} (max {MAX_BUDGET}) or open a file in the missing module's group", + STOP_ROUNDS: f"raise {ENV_ROUNDS} (max {MAX_ROUNDS})", + STOP_BUSY: "jdtls stayed busy; errors may clear later", + STOP_NO_FRESH: "jdtls did not re-validate the open file", + STOP_REFRESHES: "the session's diagnostics-refresh cap is spent; restart the server to try again", +} -def resolve_budget(config: Mapping[str, Any] | None = None, environ: Mapping[str, str] | None = None) -> int: - """Session budget of dependency-module folders. +# --- Demand classification (#110-class errors) ------------------------------------------- - ``JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`` wins over ``{"jdtls": {"dependencyModules": N}}`` - in ``.java-functional-lsp.json``. 0 disables the feature; values are clamped to - ``[0, MAX_BUDGET]``; an invalid value logs a warning and uses ``DEFAULT_BUDGET``. - """ - env = environ if environ is not None else os.environ - raw: object = env.get(ENV_BUDGET) - source = ENV_BUDGET - if raw is None or raw == "": - jdtls_cfg = (config or {}).get("jdtls") - raw = jdtls_cfg.get("dependencyModules") if isinstance(jdtls_cfg, Mapping) else None - source = "jdtls.dependencyModules" - if raw is None: - return DEFAULT_BUDGET +#: jdtls problem ids (Eclipse ``IProblem``) of #110-class errors: ImportNotFound, UndefinedType, +#: UndefinedMethod, UndefinedField, UndefinedName, IsClassPathCorrect. +_DEMAND_PROBLEM_IDS = frozenset({"268435846", "16777218", "67108964", "33554502", "570425394", "16777540"}) +#: Never demand: m2e lifecycle / build-path markers and jdtls's "non-project file". +_NOT_DEMAND_IDS = frozenset({"0", "16", "964"}) +_DEMAND_SUBSTRINGS = ( + "cannot be resolved", + "is undefined for the type", + "indirectly referenced from required", + "must override or implement a supertype method", +) + + +def is_demand_diagnostic(diag: object) -> bool: + """True for an Error diagnostic that an unimported in-repo dependency can cause.""" + if not isinstance(diag, dict) or diag.get("severity") != 1: + return False + code = str(diag.get("code", "")) + if code in _NOT_DEMAND_IDS: + return False + if code in _DEMAND_PROBLEM_IDS: + return True + message = diag.get("message") + if not isinstance(message, str): + return False + message = message[:MAX_MESSAGE_CHARS] + if any(s in message for s in _DEMAND_SUBSTRINGS): + return True + return "The hierarchy of the type" in message and "is inconsistent" in message + + +def has_demand(diagnostics: object) -> bool: + """Whether a jdtls publish for a ``.java`` file holds #110-class errors (bounded scan).""" + if not isinstance(diagnostics, list): + return False + return any(is_demand_diagnostic(d) for d in diagnostics[:MAX_DIAGNOSTICS_SCANNED]) + + +# --- Knobs ----------------------------------------------------------------------------------- + + +def _parse_int(raw: object) -> int | None: + if isinstance(raw, bool) or not isinstance(raw, (int, str)): + return None try: - if isinstance(raw, bool) or not isinstance(raw, (int, str)): - raise ValueError - value = int(raw) + return int(raw) except ValueError: - logger.warning("jdtls: invalid %s %r, using default %d", source, raw, DEFAULT_BUDGET) - return DEFAULT_BUDGET - if value > MAX_BUDGET: - logger.warning("jdtls: %s %d is above the maximum, using %d", source, value, MAX_BUDGET) - return MAX_BUDGET + return None + + +def _env_knob(env_name: str, default: int, hard_max: int, raw: str) -> int: + value = _parse_int(raw) + if value is None: + logger.warning("jdtls: invalid %s %r, using default %d", env_name, raw, default) + return default + if value > hard_max: + logger.warning("jdtls: %s %d is above the maximum, using %d", env_name, value, hard_max) + return hard_max return max(value, 0) +def _config_knob(config_key: str, env_name: str, default: int, raw: object) -> int: + value = _parse_int(raw) + if value is None: + # Repository-controlled: cap what reaches the log. + logger.warning("jdtls: invalid jdtls.%s %s, using default %d", config_key, repr(raw)[:80], default) + return default + if value > default: + logger.warning( + "jdtls: jdtls.%s %d ignored: repository config can only lower it (default %d); set %s to raise it", + config_key, + value, + default, + env_name, + ) + return default + return max(value, 0) + + +def _resolve_knob( + env_name: str, + config_key: str, + default: int, + hard_max: int, + config: Mapping[str, Any] | None, + environ: Mapping[str, str] | None, +) -> int: + """Repo config may only lower *default*; the environment may set anything up to *hard_max*.""" + env = environ if environ is not None else os.environ + raw_env = env.get(env_name) + if raw_env: + return _env_knob(env_name, default, hard_max, raw_env) + jdtls_cfg = (config or {}).get("jdtls") + raw_cfg = jdtls_cfg.get(config_key) if isinstance(jdtls_cfg, Mapping) else None + return default if raw_cfg is None else _config_knob(config_key, env_name, default, raw_cfg) + + +def resolve_budget(config: Mapping[str, Any] | None = None, environ: Mapping[str, str] | None = None) -> int: + """Session budget of dependency-module folders (0 disables the feature). + + ``{"jdtls": {"dependencyModules": N}}`` in ``.java-functional-lsp.json`` can only lower the + default; ``JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES`` wins and may raise it up to ``MAX_BUDGET``. + """ + return _resolve_knob(ENV_BUDGET, "dependencyModules", DEFAULT_BUDGET, MAX_BUDGET, config, environ) + + +def resolve_rounds(config: Mapping[str, Any] | None = None, environ: Mapping[str, str] | None = None) -> int: + """Rounds per session: ``jdtls.dependencyRounds`` can only lower it, ``JAVA_FUNCTIONAL_LSP_DEPENDENCY_ROUNDS`` + may raise it up to ``MAX_ROUNDS``.""" + return _resolve_knob(ENV_ROUNDS, "dependencyRounds", DEFAULT_ROUNDS, MAX_ROUNDS, config, environ) + + +# --- Paths ----------------------------------------------------------------------------------- + + def path_from_uri(uri: str) -> Path | None: """Filesystem path of a ``file:`` URI in any of jdtls's forms (``file:/x/``, ``file:///x``).""" if not isinstance(uri, str) or not uri.startswith("file:"): @@ -110,8 +269,175 @@ def _display(path: Path, root: Path) -> str: return path.name +def _nearest_pom_dir(path: Path) -> Path | None: + for parent in path.parents: + if (parent / "pom.xml").is_file(): + return parent + return None + + +def _is_test_source(path: Path) -> bool: + parts = path.parts + return any(parts[i] == "src" and parts[i + 1] == "test" for i in range(len(parts) - 1)) + + +# --- Build-idle ------------------------------------------------------------------------------ + + +def _is_indexing_task(task: object) -> bool: + if not isinstance(task, str): + return False + lowered = task.lower() + return lowered.startswith("searching") or "index" in lowered + + +class BuildIdle: + """jdtls build-idle detector fed by ``language/progressReport`` (``progressReportProvider``). + + Idle = no open (non-indexing) progress id and no non-indexing progress event for *quiet* + seconds (counted from *since* too, when given). "Searching..."/indexing tasks never block + idle. One timer: every relevant event re-arms the same ``call_later`` handle. + """ + + #: Bound on open progress ids (the oldest is dropped; any open id keeps jdtls busy). + MAX_OPEN = 256 + + def __init__(self, quiet: float = IDLE_QUIET_SEC, clock: Callable[[], float] = time.monotonic) -> None: + self.quiet = quiet + self._clock = clock + self._open: dict[str, str] = {} + self._last = clock() + self._timer: asyncio.TimerHandle | None = None + self._changed: asyncio.Event | None = None + + @property + def open_tasks(self) -> int: + return len(self._open) + + def note_progress(self, params: object) -> None: + if not isinstance(params, dict): + return + task_id = params.get("id") + if not isinstance(task_id, str): + return + complete = bool(params.get("complete")) + if _is_indexing_task(params.get("task")): + self._open.pop(task_id, None) + return + self._last = self._clock() + if complete: + self._open.pop(task_id, None) + else: + if task_id not in self._open and len(self._open) >= self.MAX_OPEN: + self._open.pop(next(iter(self._open))) + self._open[task_id] = str(params.get("task"))[:100] + self._arm() + + def _arm(self) -> None: + if self._timer is not None: + self._timer.cancel() + self._timer = None + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + self._timer = loop.call_later(self.quiet, self._fire) + self._wake() + + def _fire(self) -> None: + self._timer = None + self._wake() + + def _wake(self) -> None: + if self._changed is not None: + self._changed.set() + + def is_idle(self, since: float | None = None) -> bool: + ref = self._last if since is None else max(self._last, since) + return not self._open and self._clock() - ref >= self.quiet + + async def wait(self, since: float | None, timeout: float) -> bool: + """True once idle (see class doc), False when *timeout* passes first.""" + deadline = self._clock() + timeout + if self._changed is None: + self._changed = asyncio.Event() + while not self.is_idle(since): + now = self._clock() + if now >= deadline: + return False + step = deadline - now + if not self._open: # otherwise only a progress event (which wakes us) can end the wait + ref = self._last if since is None else max(self._last, since) + step = min(step, self.quiet - (now - ref)) + self._changed.clear() + try: + await asyncio.wait_for(self._changed.wait(), timeout=max(step, 0.001)) + except asyncio.TimeoutError: + pass + return True + + def reset(self) -> None: + if self._timer is not None: + self._timer.cancel() + self._timer = None + self._open.clear() + self._last = self._clock() + + +# --- Round controller ------------------------------------------------------------------------ + + +@dataclass +class Limits: + budget: int = DEFAULT_BUDGET + rounds: int = DEFAULT_ROUNDS + per_round: int = PER_ROUND + wall_clock: float = WALL_CLOCK_SEC + refreshes_per_round: int = REFRESHES_PER_ROUND + #: None: ``refreshes_per_round * (rounds + 1) * REFRESH_RETRY_FACTOR``. + refreshes_per_session: int | None = None + hub_fan_in: int = HUB_FAN_IN + + @property + def refresh_cap(self) -> int: + if self.refreshes_per_session is not None: + return self.refreshes_per_session + return self.refreshes_per_round * (self.rounds + 1) * REFRESH_RETRY_FACTOR + + +@dataclass +class Timing: + idle_quiet: float = IDLE_QUIET_SEC + round_timeout: float = ROUND_TIMEOUT_SEC + refresh_backoff: float = REFRESH_BACKOFF_SEC + marker_wait: float = MARKER_WAIT_SEC + + +@dataclass(frozen=True) +class _Fresh: + demand: bool + digest: str | None + + +@dataclass +class _Session: + rounds: int = 0 + refreshes: int = 0 + #: Import time of finished phases (round-1 import to STOP, minus refreshes), all re-arms. + import_time: float = 0.0 + #: The current phase: when its round-1 import was sent, and refresh time since then. + phase_start: float | None = None + phase_refresh: float = 0.0 + #: Time spent in refreshes, whole session (reported; not import time). + refresh_time: float = 0.0 + terminal: str | None = None + last_stop: str | None = None + stops: int = 0 + record: list[dict[str, str]] = field(default_factory=list) + + class DependencyModules: - """Session registry and importer of dependency-module folders.""" + """Session registry and demand-driven importer of dependency-module folders.""" def __init__( self, @@ -120,61 +446,191 @@ def __init__( reactor_root_for: Callable[[Path], Path], to_uri: Callable[[Path], str], *, - budget: int = DEFAULT_BUDGET, - debounce: float = ADD_DEBOUNCE_SEC, + send_refresh: SendRefresh | None = None, + open_uris: Callable[[], Iterable[str]] = lambda: (), + uri_key: Callable[[str], str] = lambda uri: uri, + doc_digest: Callable[[str], str | None] = lambda _uri: None, + module_of: Callable[[Path], Path | None] = _nearest_pom_dir, + notify: Callable[[str], None] = lambda _msg: None, + limits: Limits | None = None, + timing: Timing | None = None, index_builder: Callable[[Path], ReactorIndex] = build_reactor_index, + clock: Callable[[], float] = time.monotonic, ) -> None: self._send_folders = send_folders self._covered_roots = covered_roots self._reactor_root_for = reactor_root_for self._to_uri = to_uri + self._send_refresh = send_refresh + self._open_uris = open_uris + self._uri_key = uri_key + self._doc_digest = doc_digest + self._module_of = module_of + self._notify = notify self._index_builder = index_builder - self.budget = budget - self.debounce = debounce + self._clock = clock + self.limits = limits or Limits() + self.timing = timing or Timing() + self.idle = BuildIdle(self.timing.idle_quiet, clock) self._indexes: dict[Path, asyncio.Task[ReactorIndex | None]] = {} + self._roots: dict[Path, Path] = {} + self._tasks: set[asyncio.Task[Any]] = set() #: GA → module dir, folders currently added by this class. self.registry: dict[str, Path] = {} #: Folders removed because a group expansion covered them; never re-added. self._retired: set[Path] = set() - self._pending: dict[str, Path] = {} - self._unresolved: list[str] = [] - self._used = 0 - self._flush_task: asyncio.Task[None] | None = None - self._tasks: set[asyncio.Task[Any]] = set() - self._roots: dict[Path, Path] = {} + #: Resolved module dir → latest m2e "Missing artifact" markers on its pom. + self._markers: dict[Path, frozenset[Marker]] = {} + #: Resolved module dir → number of pom publishes seen. + self._pom_publishes: dict[Path, int] = {} + #: Modules that had demand this session (a new one re-arms the controller). + self._armed: set[Path] = set() + self._pending_modules: list[Path] = [] + #: uri_key → the latest (not necessarily fresh) demand classification of an open file. + self._latest: dict[str, bool] = {} + #: Open refresh windows: uri_key → last publish in the window (None until one arrives). + self._window: dict[str, _Fresh | None] = {} + self._closed: dict[str, _Fresh | None] = {} + self._window_uri: dict[str, str] = {} + self._runner: asyncio.Task[None] | None = None + self._record_path: Path | None = None + self._session = _Session() + + # --- public state --- + + @property + def budget(self) -> int: + return self.limits.budget + + @budget.setter + def budget(self, value: int) -> None: + self.limits.budget = value @property def enabled(self) -> bool: - return self.budget > 0 + return self.limits.budget > 0 @property def used(self) -> int: - return self._used + return len(self._session.record) + + @property + def rounds(self) -> int: + return self._session.rounds + + @property + def last_stop(self) -> str | None: + return self._session.last_stop + + @property + def running(self) -> bool: + return self._runner is not None and not self._runner.done() def folders(self) -> list[Path]: return list(self.registry.values()) - def _spawn(self, coro: Coroutine[Any, Any, Any]) -> None: + # --- inputs from the proxy --- + + def begin_session(self, record_path: Path | None) -> None: + """jdtls (re)started on a data dir: the record of imported modules starts empty. + + jdtls 1.61 does not keep folders added through didChangeWorkspaceFolders across a + restart (verified: only the rootUri project is listed again), so a previous record is + only reported, never counted. + """ + self._record_path = record_path + if record_path is None: + return + try: + previous = json.loads(record_path.read_text()).get("modules", []) + if previous: + logger.info( + "jdtls: previous session imported %d dependency module(s); jdtls does not keep them, " + "starting from 0", + len(previous), + ) + except (OSError, ValueError, AttributeError): + pass + self._save_record() + + def note_pom(self, pom_path: Path, markers: Iterable[Marker]) -> None: + """Every pom.xml publish (changed or not): the latest markers, and one more arrival.""" + module = _real(pom_path.parent) + self._pom_publishes[module] = self._pom_publishes.get(module, 0) + 1 + found = frozenset(markers) + if found: + self._markers[module] = found + else: + self._markers.pop(module, None) + + def note_publish(self, uri: str, diagnostics: object) -> None: + """A jdtls publish for a ``.java`` file.""" + if not self.enabled or not isinstance(uri, str): + return + key = self._uri_key(uri) + in_window = key in self._window + # jdtls publishes for every file of the workspace: classify only open (or refreshed) ones. + if not in_window and key not in self._open_keys(): + return + demand = has_demand(diagnostics) + if in_window: + # Digest of the document now, looked up under the client's spelling of the URI. + self._window[key] = _Fresh(demand, self._safe_digest(self._window_uri.get(key, uri))) + if key not in self._open_keys(): + return + self._latest[key] = demand + if not demand: + return + path = path_from_uri(uri) + module = self._module_of(path) if path is not None else None + if module is None: + return + module = _real(module) + if module in self._armed: + return + self._armed.add(module) + self._pending_modules.append(module) + if not self._kick(): # nothing scheduled (no running loop): do not keep it armed + self._armed.discard(module) + self._pending_modules.remove(module) + + # --- helpers --- + + def _safe_digest(self, uri: str) -> str | None: + try: + return self._doc_digest(uri) + except Exception: + return None + + def _open_list(self) -> list[str]: + try: + return [u for u in self._open_uris() if isinstance(u, str) and u.endswith(".java")] + except Exception: + return [] + + def _open_keys(self) -> set[str]: + return {self._uri_key(u) for u in self._open_list()} + + def _spawn(self, coro: Coroutine[Any, Any, Any]) -> asyncio.Task[Any] | None: try: task: asyncio.Task[Any] = asyncio.get_running_loop().create_task(coro) except RuntimeError: # no running loop (sync unit test): nothing to schedule coro.close() - return + return None self._tasks.add(task) task.add_done_callback(self._tasks.discard) + return task - def note_missing(self, pom_path: Path, gas: list[str]) -> None: - """m2e reported *gas* missing for the module of *pom_path*: queue the in-repo ones.""" - if not self.enabled or not gas: - return - self._spawn(self._consider(pom_path.parent, gas)) + def _kick(self) -> bool: + """Make sure a runner will pick up ``_pending_modules``; False when none can be scheduled.""" + if self.running: + return True + self._runner = self._spawn(self._run()) + return self._runner is not None async def _index_for(self, module_dir: Path) -> ReactorIndex | None: """Reactor index for *module_dir*, built once per reactor root (single flight).""" - root = self._roots.get(module_dir) - if root is None: - root = self._reactor_root_for(module_dir) - self._roots[module_dir] = root + root = self._root_of(module_dir) task = self._indexes.get(root) if task is None: task = asyncio.get_running_loop().create_task(self._build_index(root)) @@ -203,74 +659,367 @@ def _is_covered(self, module_dir: Path) -> bool: return True return any(_is_under(module_dir, _real(folder)) for folder in self._covered_roots()) - async def _consider(self, module_dir: Path, gas: list[str]) -> None: - index = await self._index_for(module_dir) - if index is None: + def _save_record(self) -> None: + if self._record_path is None: return - queued = False - for ga in gas: - target = index.get(ga) - if target is None: - continue # not an in-repo module (a real external artifact, or ambiguous) - if ga in self.registry or ga in self._pending or target in self._retired: - continue - if self._is_covered(target): + tmp: str | None = None + try: + # A fresh, exclusively created temp file (never a predictable, followable name). + with tempfile.NamedTemporaryFile( + "w", dir=self._record_path.parent, prefix=self._record_path.name + ".", suffix=".tmp", delete=False + ) as f: + tmp = f.name + f.write(json.dumps({"schema": 1, "modules": self._session.record})) + os.replace(tmp, self._record_path) + tmp = None + except OSError as e: + logger.debug("jdtls: could not write the dependency-module record: %s", e) + finally: + if tmp is not None: + try: + os.unlink(tmp) + except OSError: + pass + + def _demand_files(self, modules: Iterable[Path] | None) -> list[str]: + """Open files with (latest) demand, most recently opened first, at most the per-round cap.""" + wanted = set(modules) if modules is not None else None + result: list[str] = [] + for uri in reversed(self._open_list()): + key = self._uri_key(uri) + if not self._latest.get(key) or any(self._uri_key(r) == key for r in result): continue - self._pending[ga] = target - queued = True - if queued and (self._flush_task is None or self._flush_task.done()): - self._flush_task = asyncio.get_running_loop().create_task(self._flush_after_debounce(index.root)) - self._tasks.add(self._flush_task) - self._flush_task.add_done_callback(self._tasks.discard) - - async def _flush_after_debounce(self, root: Path) -> None: - # Candidates queued while a flush awaits its send see this task still running and do - # not schedule a flush of their own, so keep flushing until nothing is pending. - while True: - await asyncio.sleep(self.debounce) - await self.flush(root) - if not self._pending: - return - - async def flush(self, root: Path) -> None: - """Send one didChangeWorkspaceFolders add for the queued modules, within the budget.""" - pending, self._pending = self._pending, {} - added: list[Folder] = [] - shown: list[str] = [] - overflow: list[str] = [] - for ga, target in pending.items(): - if ga in self.registry or target in self._retired or self._is_covered(target): + if wanted is not None: + path = path_from_uri(uri) + module = self._module_of(path) if path is not None else None + if module is None or _real(module) not in wanted: + continue + result.append(uri) + if len(result) >= self.limits.refreshes_per_round: + break + return result + + # --- refresh (the fresh-demand gate) --- + + async def _refresh(self, uris: list[str]) -> dict[str, tuple[str, bool]] | None: + """Refresh *uris* one at a time. uri_key → (uri, fresh demand), or None when jdtls did not + re-validate a file (after one retry) or the session's refresh cap is reached (then the + session is terminal: ``STOP_REFRESHES``).""" + result: dict[str, tuple[str, bool]] = {} + if self._send_refresh is None: + return None + for uri in uris: + fresh = await self._refresh_one(uri) + if fresh is None: + return None + result[self._uri_key(uri)] = (uri, fresh) + return result + + async def _refresh_one(self, uri: str) -> bool | None: + assert self._send_refresh is not None + key = self._uri_key(uri) + for attempt in range(2): + if self._session.refreshes >= self.limits.refresh_cap: + logger.info("jdtls: dependency refresh cap (%d per session) reached", self.limits.refresh_cap) + self._session.terminal = STOP_REFRESHES + return None + self._session.refreshes += 1 + self._window[key] = None + self._window_uri[key] = uri + self._closed.pop(key, None) + + def close(key: str = key) -> None: + if key in self._window: + self._closed[key] = self._window.pop(key) + + started = self._clock() + try: + answered = await self._send_refresh(uri, close) + finally: + self._window.pop(key, None) + self._window_uri.pop(key, None) + took = self._clock() - started + self._session.refresh_time += took + if self._session.phase_start is not None: + self._session.phase_refresh += took + seen = self._closed.pop(key, None) + if answered and seen is not None and seen.digest is not None and seen.digest == self._safe_digest(uri): + self._latest[key] = seen.demand + return seen.demand + if attempt == 0: + logger.debug("jdtls: refresh gave no fresh diagnostics (answered=%s); retrying", answered) + await asyncio.sleep(self.timing.refresh_backoff) + return None + + # --- the round loop --- + + async def _run(self) -> None: + # A module armed while a phase runs is only queued (the runner exists): this loop + # gives it its own phase after the current one. + while self._pending_modules: + new = self._take_phase() + try: + reason = await self._process(new) + except asyncio.CancelledError: + raise + except Exception: + logger.warning("jdtls: dependency-module import failed", exc_info=True) + self._close_phase() + self._armed.difference_update(new) # the next demand publish tries again continue - if self._used >= self.budget: - overflow.append(ga) + imported = self._session.phase_start is not None + self._close_phase() + if reason in _RETRYABLE and not imported: + self._armed.difference_update(new) + self._stop(reason) + + def _take_phase(self) -> list[Path]: + """The pending modules of one reactor root (the first pending one's); the rest stay queued.""" + first = self._pending_modules[0] + try: + root = self._root_of(first) + phase = [m for m in self._pending_modules if self._root_of(m) == root] + except Exception: + logger.debug("jdtls: reactor root lookup failed", exc_info=True) + phase = [first] + self._pending_modules = [m for m in self._pending_modules if m not in phase] + return phase + + def _root_of(self, module_dir: Path) -> Path: + root = self._roots.get(module_dir) + if root is None: + root = self._reactor_root_for(module_dir) + self._roots[module_dir] = root + return root + + 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 + fresh = await self._refresh(self._demand_files(new_modules)) + if fresh is None: + return self._session.terminal or STOP_NO_FRESH + demand = [uri for uri, d in fresh.values() if d] + waiting: dict[Path, int] = dict.fromkeys(new_modules, 0) + wait_start = armed_at + while demand: + selected = await self._select(demand, waiting, wait_start) + if isinstance(selected, str): + return selected + outcome = await self._round(demand, *selected) + if isinstance(outcome, str): + return outcome + demand, waiting, wait_start = outcome + return STOP_CLEAN + + async def _select( + self, demand: list[str], waiting: dict[Path, int], wait_start: float + ) -> str | tuple[list[tuple[str, Path]], int, ReactorIndex | None]: + """This round's candidates (after the marker wait), or the STOP reason.""" + pending = await self._wait_markers(waiting, wait_start) + candidates, frontier, index = await self._candidates(demand) + if not candidates and frontier and not pending: + # Fresh demand, a non-empty frontier, no marker yet: one more quiet window. + await asyncio.sleep(self.timing.idle_quiet) + candidates, frontier, index = await self._candidates(demand) + if not candidates: + if not frontier: + return STOP_NO_CANDIDATES_NONE + return STOP_NO_CANDIDATES_MARKERS if pending else STOP_NO_CANDIDATES_JAR + limit = self._limit_reason() + if limit is not None: + self._session.terminal = limit + return limit + return candidates, frontier, index + + async def _round( + self, demand: list[str], candidates: list[tuple[str, Path]], frontier: int, index: ReactorIndex | None + ) -> str | tuple[list[str], dict[Path, int], float]: + """Import one batch, wait for build-idle, refresh: the next round's inputs, or the STOP reason.""" + batch = candidates[: min(self.limits.per_round, self.limits.budget - self.used)] + waiting = {target: self._pom_publishes.get(target, 0) for _, target in batch} + await self._import(batch) + self._session.rounds += 1 + sent_at = self._clock() + if self._session.phase_start is None: + self._session.phase_start = sent_at + + 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 + # 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() + files = [uri for uri in demand if self._uri_key(uri) in open_keys][: self.limits.refreshes_per_round] + fresh = await self._refresh(files) + if fresh is None: + log("failed", demand) + return self._session.terminal or STOP_NO_FRESH + still = [uri for uri, d in fresh.values() if d] + log("errors" if still else "clean", still) + return still, waiting, sent_at + + def _limit_reason(self) -> str | None: + if self.used >= self.limits.budget: + return STOP_BUDGET + if self._session.rounds >= self.limits.rounds: + return STOP_ROUNDS + # Import time summed over phases (round-1 import to STOP, minus refreshes); see _import_time. + if self._session.rounds and self._import_time() >= self.limits.wall_clock: + return STOP_WALL_CLOCK + return None + + async def _wait_markers(self, waiting: dict[Path, int], since: float) -> bool: + """Wait until every module in *waiting* had a pom publish after its recorded count, or + ``marker_wait`` seconds after *since*. True when some are still pending.""" + + def pending() -> bool: + return any(self._pom_publishes.get(m, 0) <= seen for m, seen in waiting.items()) + + while pending(): + remaining = since + self.timing.marker_wait - self._clock() + if remaining <= 0: + return True + await asyncio.sleep(min(remaining, 0.25)) + return False + + async def _candidates(self, demand_uris: list[str]) -> tuple[list[tuple[str, Path]], int, ReactorIndex | None]: + """(ordered candidates as (GA, dir), frontier size, the index) for the demand files.""" + demand_modules: dict[Path, bool] = {} + for uri in demand_uris: + path = path_from_uri(uri) + if path is None: continue - self._used += 1 + module = self._module_of(path) + if module is not None: + module = _real(module) + demand_modules[module] = demand_modules.get(module, False) or _is_test_source(path) + if not demand_modules: + return [], 0, None + # One phase is one reactor root (_take_phase), so the first module's index covers all. + index = await self._index_for(next(iter(demand_modules))) + if index is None: + return [], 0, None + frontier: list[tuple[str, bool]] = [] + seen: set[tuple[str, bool]] = set() + sources: list[tuple[Path, bool]] = [*demand_modules.items(), *((d, False) for d in self.registry.values())] + for module_dir, test in sources: + for dep in index.edges(module_dir, test=test): + key = (dep.ga, dep.test_jar) + if key in seen: + continue + seen.add(key) + target = index.get(dep.ga) + if target is None or dep.ga in self.registry or target in self._retired or self._is_covered(target): + continue + frontier.append(key) + markers = set().union(*self._markers.values()) if self._markers else set() + chosen: list[tuple[str, Path]] = [] + for ga, test_jar in frontier: + target = index.get(ga) + if target is not None and Marker(ga, test_jar) in markers and all(ga != g for g, _ in chosen): + chosen.append((ga, target)) + chosen.sort(key=lambda c: index.is_hub(c[0], self.limits.hub_fan_in)) # stable: hubs last + return chosen, len(frontier), index + + async def _import(self, batch: list[tuple[str, Path]]) -> None: + added: list[Folder] = [] + for ga, target in batch: self.registry[ga] = target + self._session.record.append({"ga": ga, "path": str(target)}) added.append({"uri": self._to_uri(target), "name": target.name}) - shown.append(f"{ga} ({_display(target, root)})") + self._save_record() if added: - logger.info( - "jdtls: importing %d dependency module(s) (%d/%d used): %s", - len(added), - self._used, - self.budget, - ", ".join(shown), - ) await self._send_folders(added, []) - new_unresolved = [ga for ga in overflow if ga not in self._unresolved] - if new_unresolved: - self._unresolved.extend(new_unresolved) - listed = ", ".join(new_unresolved[:_WARN_LIST_MAX]) - more = f" (+{len(new_unresolved) - _WARN_LIST_MAX} more)" if len(new_unresolved) > _WARN_LIST_MAX else "" - logger.warning( - "jdtls: dependency-module budget exhausted (%d); these in-repo modules stay unresolved: %s%s. " - "Raise %s (max %d) or open a file in their group.", - self.budget, - listed, - more, - ENV_BUDGET, - MAX_BUDGET, - ) + + def _log_round( + self, + demand: list[str], + frontier: int, + candidates: list[tuple[str, Path]], + batch: list[tuple[str, Path]], + index: ReactorIndex | None, + elapsed: float, + refresh: str, + ) -> None: + 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", + self._session.rounds, + frontier, + len(candidates), + len(candidates) - len(batch), + elapsed, + refresh, + len(demand), + len(batch), + self.used, + self.limits.budget, + shown, + ) + + def _import_time(self) -> float: + """Session import time: finished phases plus the current one (idle gaps between phases excluded).""" + session = self._session + current = 0.0 + if session.phase_start is not None: + current = max(self._clock() - session.phase_start - session.phase_refresh, 0.0) + return session.import_time + current + + def _close_phase(self) -> None: + session = self._session + session.import_time = self._import_time() + session.phase_start = None + session.phase_refresh = 0.0 + + def _stop(self, reason: str) -> None: + session = self._session + # A repeated session limit, or the same jdtls-busy / no-fresh warning again: log at DEBUG only. + repeated = reason == session.last_stop and (reason in _TERMINAL or reason in _WARN_STOPS) + session.last_stop = reason + session.stops += 1 + import_sec = self._import_time() + text = ( + f"dependency-module import stopped ({reason}): rounds {session.rounds}/{self.limits.rounds}, " + f"imported {self.used}/{self.limits.budget}, import time {import_sec:.0f}s, " + f"refreshes {session.refreshes} ({session.refresh_time:.0f}s)" + ) + hint = _STOP_HINTS.get(reason) + if hint: + text += f"; {hint}" + level = logging.WARNING if reason in _WARN_STOPS else logging.INFO + logger.log(logging.DEBUG if repeated else level, "jdtls: %s", text) + if not repeated: + try: + self._notify(f"java-functional-lsp: {text}") + except Exception: + logger.debug("jdtls: could not notify the client", exc_info=True) + + def log_summary(self) -> None: + """Session-end summary (jdtls stopping).""" + session = self._session + if not session.rounds and not session.stops: + return + logger.info( + "jdtls: dependency-module session: rounds %d, imported %d/%d, refreshes %d (%.1fs), stops %d, last stop %s", + session.rounds, + self.used, + self.limits.budget, + session.refreshes, + session.refresh_time, + session.stops, + session.last_stop or "-", + ) + + # --- group expansion / lifecycle --- def take_covered_by(self, folder: Path) -> list[Folder]: """A group folder is being added: retire the dependency folders it covers. @@ -284,9 +1033,6 @@ def take_covered_by(self, folder: Path) -> list[Folder]: del self.registry[ga] self._retired.add(target) removed.append({"uri": self._to_uri(target), "name": target.name}) - for ga, target in list(self._pending.items()): - if _is_under(target, folder): - del self._pending[ga] if removed: logger.info("jdtls: group %s covers %d dependency module folder(s)", folder.name, len(removed)) return removed @@ -296,67 +1042,18 @@ def reset(self) -> None: for task in list(self._tasks): task.cancel() self._tasks.clear() - self._flush_task = None + self._runner = None self._indexes.clear() self._roots.clear() self.registry.clear() self._retired.clear() - self._pending.clear() - self._unresolved.clear() - self._used = 0 - - -class ClasspathRefresher: - """Re-validate open files after their project's classpath changed (debounced per project).""" - - def __init__( - self, - open_uris: Callable[[], Iterable[str]], - send_refresh: Callable[[str], Awaitable[Any]], - *, - debounce: float = REFRESH_DEBOUNCE_SEC, - ) -> None: - self._open_uris = open_uris - self._send_refresh = send_refresh - self.debounce = debounce - self._timers: dict[Path, asyncio.Task[None]] = {} - - def note_updated(self, project_dir: Path) -> None: - """The classpath of *project_dir* changed; refresh its open files after the debounce.""" - timer = self._timers.get(project_dir) - if timer is not None and not timer.done(): - timer.cancel() - try: - self._timers[project_dir] = asyncio.get_running_loop().create_task(self._refresh_later(project_dir)) - except RuntimeError: - return - - def open_files_under(self, project_dir: Path) -> list[str]: - result: list[str] = [] - try: - uris = list(self._open_uris()) - except Exception: - return result - for uri in uris: - if not uri.endswith(".java"): - continue - path = path_from_uri(uri) - if path is not None and path.is_relative_to(project_dir): - result.append(uri) - return result - - async def _refresh_later(self, project_dir: Path) -> None: - await asyncio.sleep(self.debounce) - if self._timers.get(project_dir) is asyncio.current_task(): - del self._timers[project_dir] - uris = self.open_files_under(project_dir) - if not uris: - return - logger.info("jdtls: classpath of %s updated, refreshing %d open file(s)", project_dir.name, len(uris)) - for uri in uris: - await self._send_refresh(uri) - - def reset(self) -> None: - for timer in self._timers.values(): - timer.cancel() - self._timers.clear() + self._markers.clear() + self._pom_publishes.clear() + self._armed.clear() + self._pending_modules.clear() + self._latest.clear() + self._window.clear() + self._closed.clear() + self._window_uri.clear() + self.idle.reset() + self._session = _Session() diff --git a/src/java_functional_lsp/proxy.py b/src/java_functional_lsp/proxy.py index 9935cfc..1698292 100644 --- a/src/java_functional_lsp/proxy.py +++ b/src/java_functional_lsp/proxy.py @@ -11,6 +11,7 @@ import platform import re import shutil +import signal import subprocess import time from collections import deque @@ -19,9 +20,16 @@ from pathlib import Path from typing import Any -from .dependency_modules import ClasspathRefresher, DependencyModules, path_from_uri, resolve_budget +from .dependency_modules import ( + REFRESH_TIMEOUT_SEC, + DependencyModules, + Limits, + path_from_uri, + resolve_budget, + resolve_rounds, +) from .merkle import _BUILD_FILES, ModuleSnapshot, TreeDiff -from .reactor import find_reactor_root, parse_missing_artifacts +from .reactor import find_reactor_root, parse_missing_markers logger = logging.getLogger(__name__) @@ -32,6 +40,13 @@ _STDERR_LINE_MAX = 1000 _MAX_EXPANDED_GROUPS: int = 5 # hard cap on concurrent Maven group workspace folders (prevents jdtls OOM) _WORKSPACE_CACHE_MAX_SIZE: int = 10 # default LRU cap — override via {"cache": {"maxWorkspaces": N}} +#: Workspace-schema tag in the data-dir key. Bumped to ws2 in v0.14.1 so the workspaces v0.14.0 +#: bloated with up to 60 dependency projects are not reused (LRU eviction reclaims them). +_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_GRACE_SEC = 1.0 # Default jdtls initialization settings. Sent via initializationOptions.settings # so they apply BEFORE the Maven import scan (didChangeConfiguration is too late). @@ -348,8 +363,6 @@ async def read_message(reader: asyncio.StreamReader) -> dict[str, Any] | None: _WORKSPACE_DID_CHANGE_FOLDERS = "workspace/didChangeWorkspaceFolders" -#: jdtls ``language/eventNotification`` eventType for "classpath of project updated". -_EVENT_CLASSPATH_UPDATED = 100 _MAX_QUEUED_NOTIFICATIONS = 200 _MODULE_READY_TIMEOUT = 30.0 @@ -684,6 +697,7 @@ def _evict_lru_workspaces(cache_root: Path, *, max_size: int = _WORKSPACE_CACHE_ for stale in dirs[max_size:]: try: shutil.rmtree(stale) + (cache_root / f"{stale.name}{_DEPS_RECORD_SUFFIX}").unlink(missing_ok=True) logger.info("jdtls: evicted workspace cache %s (LRU)", stale.name) except OSError as e: logger.warning("jdtls: failed to evict workspace cache %s: %s", stale.name, e) @@ -705,6 +719,11 @@ def _wipe_data_dir(data_dir: Path) -> None: logger.info("jdtls: wiped data-dir %s after init timeout", _redact_path(str(data_dir))) +def _data_dir_hash(source: str) -> str: + """12-hex data-dir key for a module/root URI, tagged with the workspace schema.""" + return hashlib.sha256(f"{_WORKSPACE_SCHEMA}|{source}".encode()).hexdigest()[:12] + + def _compute_cache_marker() -> str: """Compute a stable cache marker from jdtls version path + Java version. @@ -822,8 +841,15 @@ def _build_effective_params( jdtls_settings = copy.deepcopy(_DEFAULT_JDTLS_SETTINGS) if config and "jdtls" in config and "settings" in config["jdtls"]: jdtls_settings = copy.deepcopy(config["jdtls"]["settings"]) - init_opts = effective_params.setdefault("initializationOptions", {}) + init_opts = effective_params.get("initializationOptions") + if not isinstance(init_opts, dict): + init_opts = effective_params["initializationOptions"] = {} init_opts["settings"] = jdtls_settings + # language/progressReport drives the build-idle detector of the dependency-module rounds. + extended = init_opts.get("extendedClientCapabilities") + extended = dict(extended) if isinstance(extended, dict) else {} + extended["progressReportProvider"] = True + init_opts["extendedClientCapabilities"] = extended logger.debug("jdtls: initializationOptions.settings = %s", jdtls_settings) return effective_params @@ -967,12 +993,18 @@ def __init__( uri_key: Callable[[str], str] = lambda uri: uri, on_stopped: Callable[[], None] | None = None, open_uris: Callable[[], Iterable[str]] | None = None, + doc_digest: Callable[[str], str | None] | None = None, + notify_client: Callable[[str], 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]] = {} + # Called synchronously when the response to that request id is dispatched (wire order). + self._response_hooks: dict[int, Callable[[], None]] = {} + self._stop_lock = asyncio.Lock() + self._open_uris: Callable[[], Iterable[str]] = open_uris or (lambda: ()) # 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]] = {} @@ -1016,10 +1048,12 @@ def __init__( covered_roots=self._imported_folder_paths, reactor_root_for=_reactor_root_for, to_uri=_path_to_uri, - ) - self._classpath_refresher = ClasspathRefresher( - open_uris=open_uris or (lambda: ()), send_refresh=self._refresh_file_diagnostics, + open_uris=self._open_uris, + uri_key=uri_key, + doc_digest=doc_digest or (lambda _uri: None), + module_of=_module_dir_of, + notify=notify_client or (lambda _msg: None), ) @property @@ -1045,8 +1079,8 @@ def _mark_stopped(self) -> None: self._diagnostics_cache.clear() self._pom_errors.clear() self._log_forwarder.flush() + self.dependency_modules.log_summary() self.dependency_modules.reset() - self._classpath_refresher.reset() if cached: logger.info("jdtls stopped: cleared cached diagnostics for %d files", cached) if self._on_stopped: @@ -1084,10 +1118,7 @@ async def start( # from concurrent coroutines during the executor yield below. self._initial_module_uri = module_root_uri self.modules.mark_added(effective_root_uri) - self.dependency_modules.reset() - self.dependency_modules.budget = resolve_budget(config) - if not self.dependency_modules.enabled: - logger.info("jdtls: importing missing in-repo dependency modules is disabled") + self._configure_dependency_modules(config) # All blocking startup I/O in a single executor call: cache version check # (may rmtree on upgrade), Lombok discovery, and jdtls env build. @@ -1105,9 +1136,10 @@ def _blocking_startup() -> tuple[dict[str, str], str | None]: logger.info("jdtls: using Lombok agent from %s", _redact_path(lombok_jar)) hash_source = module_root_uri or original_root - data_hash = hashlib.sha256(hash_source.encode()).hexdigest()[:12] + data_hash = _data_dir_hash(hash_source) data_dir = cache_root / data_hash data_dir.mkdir(parents=True, exist_ok=True) + self.dependency_modules.begin_session(cache_root / f"{data_hash}{_DEPS_RECORD_SUFFIX}") effective_params = _build_effective_params(init_params, module_root_uri, original_root, config) @@ -1161,6 +1193,12 @@ def _blocking_startup() -> tuple[dict[str, str], str | None]: logger.error("Failed to start jdtls: %s", e) return False + def _configure_dependency_modules(self, config: Mapping[str, Any] | None) -> None: + self.dependency_modules.reset() + self.dependency_modules.limits = Limits(budget=resolve_budget(config), rounds=resolve_rounds(config)) + if not self.dependency_modules.enabled: + logger.info("jdtls: importing missing in-repo dependency modules is disabled") + async def ensure_started( self, init_params: dict[str, Any], @@ -1405,40 +1443,78 @@ async def expand_full_workspace(self) -> None: self._expanded_groups.add(root_uri) async def stop(self) -> None: - """Shutdown jdtls subprocess gracefully.""" - self._mark_stopped() - self._log_forwarder.flush() - - if self._reader_task and not self._reader_task.done(): - self._reader_task.cancel() - if self._stderr_task and not self._stderr_task.done(): - self._stderr_task.cancel() - - for task in list(self._proxy_bg_tasks): - task.cancel() - self._proxy_bg_tasks.clear() - self._module_diff_results.clear() - self._pending_diff_tasks.clear() + """Shut jdtls down within about 3 s. Idempotent (shutdown, exit, a signal, init timeout). - if self._process and self._process.returncode is None: + The shutdown reply is read before the reader is cancelled. The JVM gets + ``_STOP_GRACE_SEC`` to exit after ``exit``, then SIGTERM, then SIGKILL. + """ + async with self._stop_lock: + process = self._process + self._mark_stopped() + self._log_forwarder.flush() + + for task in list(self._proxy_bg_tasks): + task.cancel() + self._proxy_bg_tasks.clear() + self._module_diff_results.clear() + self._pending_diff_tasks.clear() + + if process is not None and process.returncode is None: + await self._terminate(process) + + if self._reader_task and not self._reader_task.done(): + self._reader_task.cancel() + if self._stderr_task and not self._stderr_task.done(): + self._stderr_task.cancel() + + # Cancel all pending requests + for future in self._pending.values(): + if not future.done(): + future.cancel() + self._pending.clear() + 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)) + return + except (asyncio.TimeoutError, OSError): + pass + for sig in (signal.SIGTERM, signal.SIGKILL): + try: + process.send_signal(sig) + except (ProcessLookupError, OSError): + return try: - await self.send_request("shutdown", None, timeout=5.0) - await self.send_notification("exit", None) - await asyncio.wait_for(self._process.wait(), timeout=5.0) - except (asyncio.TimeoutError, OSError): - self._process.kill() - await self._process.wait() - - # Cancel all pending requests - for future in self._pending.values(): - if not future.done(): - future.cancel() - self._pending.clear() + await asyncio.wait_for(process.wait(), timeout=_STOP_GRACE_SEC) + logger.info("jdtls: stopped with %s", signal.Signals(sig).name) + return + except asyncio.TimeoutError: + continue + logger.warning("jdtls: pid %s did not exit after SIGKILL", process.pid) async def send_request(self, method: str, params: Any, timeout: float = REQUEST_TIMEOUT) -> Any | None: """Send a JSON-RPC request and wait for the response.""" + _answered, result = await self._request(method, params, timeout) + return result + + async def _request( + self, + method: str, + params: Any, + timeout: float = REQUEST_TIMEOUT, + on_response: Callable[[], None] | None = None, + ) -> tuple[bool, Any | None]: + """Send a request; (True, result) once jdtls answered it, (False, None) on error or timeout. + + *on_response* runs synchronously when the response is dispatched, before any later message. + """ if not self._process or self._process.stdin is None: - return None + return False, None request_id = self._next_id self._next_id += 1 @@ -1453,21 +1529,30 @@ async def send_request(self, method: str, params: Any, timeout: float = REQUEST_ future: asyncio.Future[Any] = asyncio.get_event_loop().create_future() self._pending[request_id] = future + if on_response is not None: + self._response_hooks[request_id] = on_response try: self._process.stdin.write(encode_message(msg)) await self._process.stdin.drain() result = await asyncio.wait_for(future, timeout=timeout) - return result except asyncio.TimeoutError: logger.warning("jdtls request %s timed out after %.1fs", method, timeout) - self._pending.pop(request_id, None) - return None + return False, None + except asyncio.CancelledError: + if future.cancelled(): # stop() cancelled the pending request + return False, None + raise except (OSError, ConnectionError) as e: logger.error("jdtls communication error on %s: %s", method, e) - self._pending.pop(request_id, None) self._available = False - return None + return False, None + finally: + self._pending.pop(request_id, None) + self._response_hooks.pop(request_id, None) + if isinstance(result, _ErrorResponse): + return False, None + return True, result async def send_notification(self, method: str, params: Any) -> None: """Send a JSON-RPC notification (no response expected).""" @@ -1538,11 +1623,17 @@ def _dispatch_message(self, msg: dict[str, Any]) -> None: if "id" in msg and "method" not in msg: # Response to a request we sent request_id = msg["id"] + hook = self._response_hooks.pop(request_id, None) if isinstance(request_id, int) else None + if hook is not None: + try: + hook() + except Exception: + logger.debug("jdtls: response hook failed", exc_info=True) future = self._pending.pop(request_id, None) if future and not future.done(): if "error" in msg: logger.warning("jdtls error response (id=%s): %s", request_id, msg["error"]) - future.set_result(None) + future.set_result(_ErrorResponse()) else: future.set_result(msg.get("result")) elif "method" in msg and "id" not in msg: @@ -1574,8 +1665,19 @@ def _handle_notification(self, msg: dict[str, Any]) -> None: self._diagnostics_cache[self._uri_key(uri)] = diagnostics if self._on_diagnostics: self._on_diagnostics(uri, diagnostics) - if isinstance(uri, str) and uri.endswith("/pom.xml"): - self._note_pom_diagnostics(uri, diagnostics) + # The dependency-module bookkeeping must never tear down the reader loop. + try: + if isinstance(uri, str) and uri.endswith("/pom.xml"): + self._note_pom_diagnostics(uri, diagnostics) + elif isinstance(uri, str) and uri.endswith(".java"): + self.dependency_modules.note_publish(uri, diagnostics) + except Exception: + logger.warning("jdtls: dependency-module bookkeeping failed for a publish", exc_info=True) + elif method == "language/progressReport": + try: + self.dependency_modules.idle.note_progress(params) + except Exception: + logger.warning("jdtls: build-idle bookkeeping failed", exc_info=True) elif method == "window/logMessage" and isinstance(params, dict): msg_type = params.get("type") level = _LOG_MESSAGE_LEVELS.get(msg_type, logging.DEBUG) if isinstance(msg_type, int) else logging.DEBUG @@ -1586,41 +1688,41 @@ def _handle_notification(self, msg: dict[str, Any]) -> None: level = logging.INFO if status_type == "Error" else logging.DEBUG kind = f"status:{status_type}" if status_type in _LANGUAGE_STATUS_TYPES else "status:other" self._log_forwarder.forward(level, kind, params.get("message", "")) - elif method == "language/eventNotification" and isinstance(params, dict): - if params.get("eventType") == _EVENT_CLASSPATH_UPDATED: - project = path_from_uri(params.get("data")) # type: ignore[arg-type] - if project is not None: - self._classpath_refresher.note_updated(project) - # Other notifications are silently ignored + # Other notifications (incl. language/eventNotification) are silently ignored: jdtls never + # re-publishes an open file after ClasspathUpdated; the dependency rounds refresh it. def _note_pom_diagnostics(self, uri: str, diagnostics: Any) -> None: - """Log a one-line summary whenever the Error diagnostics set of a pom.xml changes. + """Feed pom.xml markers to the dependency rounds; log a summary when the Error set changes. m2e reports import failures (e.g. ``Missing artifact g:a:t:v``) only as diagnostics on the module's pom.xml, which the server never publishes (it filters to ``.java``). Logging them here makes the cause of false - "cannot be resolved" errors visible (#110). Does not alter what is - published to the client. + "cannot be resolved" errors visible (#110): at INFO for a module with an open file, + at DEBUG for the rest (pom churn of imported dependency modules). Does not alter + what is published to the client. """ errors: tuple[str, ...] = () if isinstance(diagnostics, list): errors = tuple( str(d.get("message", "")) - for d in diagnostics + for d in diagnostics[:_MAX_POM_DIAGNOSTICS] if isinstance(d, dict) and d.get("severity") == 1 # DiagnosticSeverity.Error ) + pom = path_from_uri(uri) + if pom is not None: + self.dependency_modules.note_pom(pom, parse_missing_markers(errors)) key = self._uri_key(uri) previous = self._pom_errors.get(key, ()) if previous == errors: return - self._react_to_missing_artifacts(uri, previous, errors) if errors: self._pom_errors[key] = errors else: self._pom_errors.pop(key, None) shown = "; ".join(_sanitize_jdtls_log(m, _POM_DIAG_MSG_MAX_CHARS) for m in errors[:_POM_DIAG_SHOWN]) more = f" (+{len(errors) - _POM_DIAG_SHOWN} more)" if len(errors) > _POM_DIAG_SHOWN else "" - logger.info( + logger.log( + logging.INFO if pom is not None and self._has_open_file_in(pom.parent) else logging.DEBUG, "jdtls: pom.xml errors changed for %s: %d error(s)%s%s", self._pom_display_path(uri), len(errors), @@ -1641,16 +1743,17 @@ def _pom_display_path(self, uri: str) -> str: pass return _sanitize_jdtls_log(_redact_path(path), _POM_DIAG_MSG_MAX_CHARS) - def _react_to_missing_artifacts(self, uri: str, previous: tuple[str, ...], errors: tuple[str, ...]) -> None: - """Import in-repo modules m2e reports missing; refresh open files once they resolve.""" - pom = path_from_uri(uri) - if pom is None: - return - missing = parse_missing_artifacts(errors) - if missing: - self.dependency_modules.note_missing(pom, missing) - elif parse_missing_artifacts(previous): - self._classpath_refresher.note_updated(pom.parent) + def _has_open_file_in(self, module_dir: Path) -> bool: + """Whether a client-open file belongs to the module at *module_dir* (not a nested one).""" + try: + uris = list(self._open_uris()) + except Exception: + return False + for open_uri in uris: + path = path_from_uri(open_uri) if isinstance(open_uri, str) else None + if path is not None and path.is_relative_to(module_dir) and _module_dir_of(path) == module_dir: + return True + return False def _imported_folder_paths(self) -> list[Path]: """Folders jdtls imported for groups/modules (the dependency registry is separate).""" @@ -1668,18 +1771,35 @@ async def _send_folder_change(self, added: list[dict[str, str]], removed: list[d return await self.send_notification(_WORKSPACE_DID_CHANGE_FOLDERS, {"event": {"added": added, "removed": removed}}) - async def _refresh_file_diagnostics(self, uri: str) -> None: - """jdtls does not republish diagnostics for open files after a classpath change; ask it to.""" + async def _refresh_file_diagnostics(self, uri: str, on_response: Callable[[], None] | None = None) -> bool: + """jdtls does not republish diagnostics for open files after a classpath change; ask it to. + + True once jdtls answered. *on_response* runs when the answer is dispatched: jdtls publishes + the file's diagnostics just before it answers. + """ if not self._available: - return - await self.send_request( + return False + answered, _result = await self._request( "workspace/executeCommand", {"command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", False]}, timeout=_REFRESH_DIAGNOSTICS_TIMEOUT, + on_response=on_response, ) + return answered + + +_REFRESH_DIAGNOSTICS_TIMEOUT = REFRESH_TIMEOUT_SEC +_MAX_POM_DIAGNOSTICS = 500 + + +class _ErrorResponse: + """Future result for a JSON-RPC error response (``send_request`` still returns None).""" -_REFRESH_DIAGNOSTICS_TIMEOUT = 10.0 +def _module_dir_of(path: Path) -> Path | None: + """Nearest ancestor directory of *path* holding a module descriptor (the module root).""" + root = find_module_root(str(path)) + return Path(root) if root else None def _path_to_uri(path: Path) -> str: diff --git a/src/java_functional_lsp/reactor.py b/src/java_functional_lsp/reactor.py index d371352..b9677a4 100644 --- a/src/java_functional_lsp/reactor.py +++ b/src/java_functional_lsp/reactor.py @@ -2,9 +2,11 @@ Pure functions, no jdtls. ``build_reactor_index`` maps ``groupId:artifactId`` to the module directory of every module reachable from a reactor root through ```` -(all profiles unioned). The proxy uses it to turn m2e's pom.xml diagnostic -``Missing artifact g:a:type:version`` into "import that in-repo module as a -workspace folder". +(all profiles unioned), and records each module's declared ```` and its +parent. ``ReactorIndex.edges`` turns those into the in-repo dependency edges of a module, +including the ones it inherits from in-repo parent poms. The proxy intersects the edges +with m2e's pom.xml diagnostic ``Missing artifact g:a:type[:classifier]:version`` to +decide which in-repo modules to import as workspace folders. The poms come from the user's checkout, so parsing is defensive: files over ``MAX_POM_BYTES`` or containing a `` / ]Missing artifact g:a:type[:classifier]:version". ``${revision}`` is -#: already interpolated. Only groupId and artifactId are kept. -_MISSING_ARTIFACT_RE = re.compile(rf"(?:^|/\s*)Missing artifact ({_COORDINATE}):({_COORDINATE}):\S+") +#: already interpolated. +_MISSING_ARTIFACT_RE = re.compile(rf"(?:^|/\s*)Missing artifact ({_COORDINATE}):({_COORDINATE}):(\S+)") +#: Scopes whose dependencies are on a module's main classpath. +MAIN_SCOPES = frozenset({"compile", "provided", "runtime", "system"}) +#: Bound on the in-repo parent chain walked for inherited dependencies. +MAX_PARENT_DEPTH = 20 +#: Bound on the dependencies kept per pom (a hostile pom cannot grow the index unboundedly). +MAX_DEPENDENCIES_PER_POM = 2000 +_OWN_GROUP_PLACEHOLDERS = frozenset({"${project.groupId}", "${pom.groupId}", "${groupId}"}) +_PARENT_GROUP_PLACEHOLDERS = frozenset({"${project.parent.groupId}", "${parent.groupId}"}) + + +@dataclass(frozen=True) +class Dependency: + """One declared ````: its GA, scope, and whether it is a test-jar.""" + + ga: str + scope: str = "compile" + test_jar: bool = False + + +@dataclass(frozen=True) +class Marker: + """One m2e "Missing artifact" marker: the GA and whether it names a test-jar.""" + + ga: str + test_jar: bool = False class _ForbiddenDeclarationError(Exception): @@ -81,16 +108,57 @@ class ReactorIndex: poms_read: int = 0 #: True when the walk stopped early at the pom-count or time bound. truncated: bool = False + #: Module directory → its declared ```` (``dependencyManagement`` ignored). + dependencies: dict[Path, tuple[Dependency, ...]] = field(default_factory=dict) + #: Module directory → the GA of its ````. + parent_of: dict[Path, str] = field(default_factory=dict) + #: Unambiguous GA → directory of every indexed pom, aggregators included (parent lookups). + poms: dict[str, Path] = field(default_factory=dict) + #: GA → number of indexed modules declaring it on their main classpath (hub detection). + fan_in: dict[str, int] = field(default_factory=dict) def get(self, ga: str) -> Path | None: return self.modules.get(ga) + def edges(self, module_dir: Path, *, test: bool = False) -> list[Dependency]: + """In-repo-resolvable dependency edges of *module_dir*, in declaration order. + + Main-classpath scopes of the module and of every in-repo parent pom (nearest first; + the chain is looked up by GA inside this index only, with a visited set and a depth + bound). With *test*, test-scope dependencies are included too. Deduplicated by + (GA, test-jar); GAs that are not importable modules of this index are dropped. + """ + result: list[Dependency] = [] + seen: set[tuple[str, bool]] = set() + current: Path | None = module_dir + visited: set[Path] = set() + depth = 0 + while current is not None and current not in visited and depth <= MAX_PARENT_DEPTH: + visited.add(current) + for dep in self.dependencies.get(current, ()): + if dep.scope not in MAIN_SCOPES and not (test and dep.scope == "test"): + continue + key = (dep.ga, dep.test_jar) + if key in seen or dep.ga not in self.modules: + continue + seen.add(key) + result.append(dep) + parent_ga = self.parent_of.get(current) + current = self.poms.get(parent_ga) if parent_ga else None + depth += 1 + return result + + def is_hub(self, ga: str, threshold: int) -> bool: + return self.fan_in.get(ga, 0) >= threshold + @dataclass(frozen=True) class _Pom: group_id: str | None artifact_id: str | None modules: tuple[str, ...] + parent_ga: str | None = None + dependencies: tuple[Dependency, ...] = () def _local(tag: object) -> str: @@ -134,8 +202,37 @@ def _read_pom_bytes(pom: Path) -> bytes | None: return data +def _coordinate(value: str | None) -> str | None: + return value if value and _COORDINATE_RE.fullmatch(value) else None + + +def _parse_dependencies( + project: ET.Element, group_id: str | None, parent_group_id: str | None +) -> tuple[Dependency, ...]: + """Project-level ```` (not ``dependencyManagement``, not profiles).""" + result: list[Dependency] = [] + for dep in _children(_child(project, "dependencies"), "dependency")[:MAX_DEPENDENCIES_PER_POM]: + raw_group = _text(_child(dep, "groupId")) + if raw_group in _OWN_GROUP_PLACEHOLDERS: + raw_group = group_id + elif raw_group in _PARENT_GROUP_PLACEHOLDERS: + raw_group = parent_group_id + g = _coordinate(raw_group) + a = _coordinate(_text(_child(dep, "artifactId"))) + if g is None or a is None: + continue + scope = (_text(_child(dep, "scope")) or "compile").lower() + dep_type = _text(_child(dep, "type")) or "jar" + classifier = _text(_child(dep, "classifier")) + result.append(Dependency(f"{g}:{a}", scope, dep_type == "test-jar" or classifier == "tests")) + return tuple(result) + + def parse_pom(pom: Path) -> _Pom | None: - """Parse the coordinates and ```` (all profiles) of *pom*; None if rejected or invalid.""" + """Parse the coordinates, parent, ```` and ```` (all profiles) of *pom*. + + None if rejected or invalid. + """ data = _read_pom_bytes(pom) if data is None: return None @@ -146,8 +243,12 @@ def parse_pom(pom: Path) -> _Pom | None: if _local(project.tag) != "project": return None parent = _child(project, "parent") - group_id = _text(_child(project, "groupId")) or _text(_child(parent, "groupId") if parent is not None else None) + parent_group = _text(_child(parent, "groupId")) if parent is not None else None + parent_artifact = _text(_child(parent, "artifactId")) if parent is not None else None + group_id = _text(_child(project, "groupId")) or parent_group artifact_id = _text(_child(project, "artifactId")) + pg, pa = _coordinate(parent_group), _coordinate(parent_artifact) + parent_ga = f"{pg}:{pa}" if pg and pa else None module_lists = [_child(project, "modules")] for profile in _children(_child(project, "profiles"), "profile"): module_lists.append(_child(profile, "modules")) @@ -157,7 +258,7 @@ def parse_pom(pom: Path) -> _Pom | None: value = _text(m) if value and value not in modules: modules.append(value) - return _Pom(group_id, artifact_id, tuple(modules)) + return _Pom(group_id, artifact_id, tuple(modules), parent_ga, _parse_dependencies(project, group_id, parent_group)) def _module_pom(base: Path, entry: str) -> Path: @@ -180,6 +281,8 @@ def _contained_dir(pom: Path, real_root: Path) -> Path | None: def _resolve_found(index: ReactorIndex, found: dict[str, set[Path]]) -> None: """Keep GAs declared by exactly one non-aggregator directory; log the ambiguous ones once.""" for ga, dirs in found.items(): + if len(dirs) == 1: + index.poms[ga] = next(iter(dirs)) if ga in index.aggregators: continue if len(dirs) == 1: @@ -238,6 +341,12 @@ def build_reactor_index( found.setdefault(f"{g}:{a}", set()).add(module_dir) if parsed.modules: index.aggregators.add(f"{g}:{a}") + if parsed.dependencies: + index.dependencies[module_dir] = parsed.dependencies + for dep in {d.ga for d in parsed.dependencies if d.scope in MAIN_SCOPES}: + index.fan_in[dep] = index.fan_in.get(dep, 0) + 1 + if parsed.parent_ga: + index.parent_of[module_dir] = parsed.parent_ga for entry in parsed.modules: if "${" in entry: continue @@ -259,13 +368,32 @@ def find_reactor_root(module_dir: Path, boundary: Path | None = None) -> Path: return top +def parse_missing_markers(messages: tuple[str, ...] | list[str]) -> list[Marker]: + """Every m2e "Missing artifact" message as a ``Marker``, in order, deduped. + + ``g:a:type:version`` or ``g:a:type:classifier:version``; a ``test-jar`` type or a + ``tests`` classifier marks a test-jar. + """ + result: list[Marker] = [] + for message in messages: + match = _MISSING_ARTIFACT_RE.search(message) + if not match: + continue + # ":" or "::"; tolerate a truncated message + # ("g:a:jar"): a pom diagnostic must never raise inside the jdtls reader loop. + parts = match.group(3).split(":") + dep_type = parts[0] + classifier = parts[1] if len(parts) > 2 else None # noqa: PLR2004 (type:classifier:version) + marker = Marker(f"{match.group(1)}:{match.group(2)}", dep_type == "test-jar" or classifier == "tests") + if marker not in result: + result.append(marker) + return result + + def parse_missing_artifacts(messages: tuple[str, ...] | list[str]) -> list[str]: """Return the ``groupId:artifactId`` of every m2e "Missing artifact" message, in order, deduped.""" result: list[str] = [] - for message in messages: - match = _MISSING_ARTIFACT_RE.search(message) - if match: - ga = f"{match.group(1)}:{match.group(2)}" - if ga not in result: - result.append(ga) + for marker in parse_missing_markers(messages): + if marker.ga not in result: + result.append(marker.ga) return result diff --git a/src/java_functional_lsp/server.py b/src/java_functional_lsp/server.py index e513eb4..61c1495 100644 --- a/src/java_functional_lsp/server.py +++ b/src/java_functional_lsp/server.py @@ -14,8 +14,10 @@ import logging import os import re +import signal import stat import sys +import threading import time from collections import Counter, OrderedDict from collections.abc import Callable, Coroutine @@ -284,6 +286,8 @@ def __init__(self) -> None: uri_key=_normalize_uri, on_stopped=self._on_jdtls_stopped, open_uris=self._open_document_uris, + doc_digest=self._document_digest, + notify_client=self._notify_client, ) self._user_suppress_patterns: list[re.Pattern[str]] = [] self._skip_jdtls: bool = False @@ -319,6 +323,19 @@ def _open_document_uris(self) -> list[str]: except Exception: # workspace not set up yet (before initialize) return [] + def _document_digest(self, uri: str) -> str | None: + """Content digest of the open document *uri* (any URI spelling), or None if it is not open.""" + client_uri = self._session_opened_uris.get(_normalize_uri(uri)) or uri + doc = self.workspace.text_documents.get(client_uri) + return content_digest(doc.source.encode()) if doc is not None else None + + def _notify_client(self, message: str) -> None: + """One-off status for the user (e.g. why the dependency-module import stopped).""" + try: + self.window_log_message(lsp.LogMessageParams(type=lsp.MessageType.Info, message=message)) + except Exception: + logger.debug("window/logMessage failed", exc_info=True) + def _record_opened(self, uri: str) -> None: """Record *uri* as opened this session, evicting the oldest entry at cap. @@ -761,9 +778,91 @@ def on_initialize(params: lsp.InitializeParams) -> lsp.InitializeResult: # _register_jdtls_capabilities, after jdtls warm-up. HandlerWiring(server, _JDTLS_HANDLERS).wire_eager(negotiation.static) + if _process_mode: + _install_signal_handlers() return lsp.InitializeResult(capabilities=StaticCapabilityBuilder().build(negotiation.static)) +# --- Shutdown (#107, v0.14.1) --- +# +# pygls' built-in EXIT handler calls sys.exit, which then blocks forever in +# thread_pool.shutdown(wait=True) on the _EternalStdinBuffer reader, and nothing stopped jdtls, +# so its JVM outlived the server. SHUTDOWN and EXIT now stop jdtls (bounded), EXIT and +# SIGTERM/SIGHUP end the process with os._exit. pygls 2.x runs these user handlers first and +# awaits them. + +#: Set by main(): only a real server process installs signal handlers and calls os._exit. +_process_mode = False +#: proxy.stop() takes at most ~3 s (shutdown/exit, SIGTERM after 1 s, SIGKILL after 2 s). +_STOP_TIMEOUT_SEC = 3.5 +#: After a signal the process exits within this long, whatever happens. +_SIGNAL_WATCHDOG_SEC = 5.0 +_signals_received = 0 + + +def _hard_exit(code: int) -> None: + logging.shutdown() + os._exit(code) + + +def _watchdog_exit(code: int) -> None: + """The signal watchdog's exit: no logging.shutdown(), which could block on a handler lock + held by a thread stuck writing to a full stderr pipe.""" + os._exit(code) + + +async def _stop_jdtls_bounded() -> None: + try: + await asyncio.wait_for(server._proxy.stop(), timeout=_STOP_TIMEOUT_SEC) + except asyncio.TimeoutError: + logger.warning("jdtls did not stop within %.1fs", _STOP_TIMEOUT_SEC) + except Exception: + logger.warning("jdtls stop failed", exc_info=True) + + +@server.feature(lsp.SHUTDOWN) +async def on_shutdown(_: Any) -> None: + """Stop jdtls before answering shutdown, so the client's exit finds nothing left to do.""" + await _stop_jdtls_bounded() + + +@server.feature(lsp.EXIT) +async def on_exit(_: Any) -> None: + """Stop jdtls (bounded), then end the process without waiting on the stdin reader thread.""" + await _stop_jdtls_bounded() + if _process_mode: + _hard_exit(0 if getattr(server.protocol, "_shutdown", False) else 1) + + +def _install_signal_handlers() -> None: + """SIGTERM/SIGHUP stop jdtls, then exit. Registered from inside the running loop (POSIX only).""" + try: + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGHUP): + loop.add_signal_handler(sig, _on_signal, sig) + except (RuntimeError, NotImplementedError, ValueError, AttributeError) as e: + logger.debug("signal handlers not installed: %s", e) + + +def _on_signal(sig: signal.Signals) -> None: + global _signals_received + _signals_received += 1 + code = 128 + int(sig) + if _signals_received > 1: + _watchdog_exit(code) # a second signal: no more waiting + return + logger.info("received %s: stopping jdtls", sig.name) + watchdog = threading.Timer(_SIGNAL_WATCHDOG_SEC, _watchdog_exit, (code,)) + watchdog.daemon = True + watchdog.start() + _fire_and_forget(_stop_and_exit(code)) + + +async def _stop_and_exit(code: int) -> None: + await _stop_jdtls_bounded() + _hard_exit(code) + + @server.feature(lsp.INITIALIZED) async def on_initialized(_: lsp.InitializedParams) -> None: """Check jdtls availability; actual start deferred to first didOpen.""" @@ -1652,6 +1751,8 @@ def _log_level_from_env() -> int: def main() -> None: """Entry point for the LSP server.""" + global _process_mode + _process_mode = True 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()) diff --git a/tests/e2e_maven.py b/tests/e2e_maven.py new file mode 100644 index 0000000..5fb32bf --- /dev/null +++ b/tests/e2e_maven.py @@ -0,0 +1,438 @@ +"""Shared helpers for the real-jdtls Maven e2e tests (#110). + +Fixture reactors live under ``tmp_path`` and resolve against an isolated local repository +(never ``~/.m2``). That repository is primed once, online, with Maven's plugins only, by +building a two-group fixture; every ``com.example`` artifact is wiped before each test, so +an in-repo module is always "missing" as it is for an unpublished sibling. It is cached in +``~/.cache/java-functional-lsp/`` (override with ``JAVA_FUNCTIONAL_LSP_E2E_M2``). + +The server runs with ``HOME``/``user.home``/``TMPDIR`` pointed into ``tmp_path`` so jdtls, +m2e and the proxy (Lombok lookup, jdtls data cache) stay away from the real home directory. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import shutil +import subprocess +import sys +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager, suppress +from dataclasses import dataclass, field +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 + +PRIME_TIMEOUT_SEC = 300 + +_PLUGIN_MANAGEMENT = """\ + + + + org.apache.maven.pluginsmaven-compiler-plugin\ +3.11.0 + org.apache.maven.pluginsmaven-resources-plugin\ +3.3.1 + org.apache.maven.pluginsmaven-surefire-plugin\ +3.5.4 + + + +""" + + +def root_pom(modules: list[str]) -> str: + mods = "\n".join(f" {m}" for m in modules) + return f"""\ + + + 4.0.0 + com.example + root + ${{revision}} + pom + + X-DEFAULT + 17 + 17 + 17 + +{_PLUGIN_MANAGEMENT} +{mods} + + +""" + + +def deps_xml(*artifact_ids: str) -> str: + """A ```` block on ``com.example::${revision}`` for each id.""" + body = "".join( + f""" + + com.example + {a} + ${{revision}} + """ + for a in artifact_ids + ) + return f"\n {body}\n " if artifact_ids else "" + + +def group_pom(name: str, modules: list[str], deps: str = "") -> str: + mods = "\n".join(f" {m}" for m in modules) + return f"""\ + + + 4.0.0 + + com.example + root + ${{revision}} + + {name} + pom{deps} + +{mods} + + +""" + + +def leaf_pom(parent: str, name: str, deps: str = "") -> str: + return f"""\ + + + 4.0.0 + + com.example + {parent} + ${{revision}} + + {name}{deps} + +""" + + +def write_files(root: Path, files: dict[str, str]) -> None: + for rel, text in files.items(): + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +# --- The two-group fixture: groupB/it's test extends groupA/common's base class. --- + +BASE_JAVA = """\ +package com.example.common; + +public abstract class BaseIntegrationTest { + protected String sut = "system-under-test"; + + protected void cleanCaches() { + sut = null; + } +} +""" + +# The type mismatch is a deterministic jdtls error that needs a resolved JRE: its presence proves a +# publish came from jdtls's semantic pass (the server's custom-only publish and jdtls's non-project, +# syntax-only publish both lack it). It is the only error the file should keep. +TEST_JAVA = """\ +package com.example.it; + +import com.example.common.BaseIntegrationTest; + +public class MyIntegrationTest extends BaseIntegrationTest { + public int run() { + cleanCaches(); + return this.sut.length(); + } + + public int marker() { + return "marker"; + } +} +""" +JDTLS_MARKER = "Type mismatch" +FALSE_ERRORS = ("cannot be resolved", "is undefined for the type", "hierarchy of the type") + + +def write_two_group_fixture(root: Path) -> Path: + """Write the two-group reactor under *root* and return MyIntegrationTest.java.""" + write_files( + root, + { + "pom.xml": root_pom(["groupA", "groupB"]), + "groupA/pom.xml": group_pom("groupA", ["common"]), + "groupB/pom.xml": group_pom("groupB", ["it"]), + "groupA/common/pom.xml": leaf_pom("groupA", "common"), + "groupB/it/pom.xml": leaf_pom("groupB", "it", deps_xml("common")), + "groupA/common/src/main/java/com/example/common/BaseIntegrationTest.java": BASE_JAVA, + "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java": TEST_JAVA, + }, + ) + return root / "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java" + + +def settings_xml(path: Path, repo: Path, *, offline: bool) -> Path: + path.write_text( + '\n' + '\n' + f" {repo}\n" + f" {'true' if offline else 'false'}\n" + "\n" + ) + return path + + +def primed_repo(work: Path, fake_home: Path) -> Path: + """Return a local repository holding Maven's plugins but no com.example artifacts. + + With a truly empty offline repository m2e cannot compute a build plan and creates no + Java project at all, so the plugins are fetched once (online) by building the fixture. + """ + repo = Path( + os.environ.get("JAVA_FUNCTIONAL_LSP_E2E_M2") + or Path.home() / ".cache" / "java-functional-lsp" / "e2e-m2-issue110-v1" + ) + stamp = repo / ".primed" + if not stamp.is_file(): + mvn = shutil.which("mvn") + java_home = find_jdtls_java_home() + if mvn is None or java_home is None: + pytest.skip("Maven is needed once to prime the isolated local repository") + repo.mkdir(parents=True, exist_ok=True) + prime_root = work / "prime" + write_two_group_fixture(prime_root) + settings = settings_xml(work / "settings-online.xml", repo, offline=False) + env = { + **os.environ, + "JAVA_HOME": java_home, + "HOME": str(fake_home), + "MAVEN_OPTS": f"-Duser.home={fake_home}", + } + for goal in ("test-compile", "clean"): + cmd = [mvn, "-B", "-q", "-s", str(settings), "-gs", str(settings), f"-Dmaven.repo.local={repo}"] + try: + proc = subprocess.run( + [*cmd, "-f", str(prime_root / "pom.xml"), goal], + capture_output=True, + text=True, + timeout=PRIME_TIMEOUT_SEC, + check=False, + env=env, + ) + except (OSError, subprocess.SubprocessError) as e: + pytest.skip(f"priming the local repository failed: {e}") + if proc.returncode != 0: + pytest.skip(f"priming the local repository failed (offline?): {proc.stdout[-500:]}") + stamp.write_text("ok\n") + # The reactor build never installs, but a stale com.example would make the test vacuous. + shutil.rmtree(repo / "com" / "example", ignore_errors=True) + return repo + + +def write_offline_config(root: Path, settings: Path) -> None: + """``.java-functional-lsp.json`` pointing m2e at the isolated, offline repository. + + ``jdtls.settings`` replaces the proxy's defaults, so the defaults are repeated here. + """ + (root / ".java-functional-lsp.json").write_text( + json.dumps( + { + "jdtls": { + "settings": { + "java": { + "import": { + "maven": {"enabled": True, "offline": {"enabled": True}}, + "gradle": {"enabled": False}, + "exclusions": ["**/node_modules/**", "**/.metadata/**", "**/target/**"], + }, + "configuration": { + "updateBuildConfiguration": "automatic", + "maven": {"userSettings": str(settings), "globalSettings": str(settings)}, + }, + "maven": {"downloadSources": False}, + } + } + } + } + ) + ) + + +class Watch: + def __init__(self) -> None: + self.history: dict[str, list[list[lsp.Diagnostic]]] = {} + self.changed = asyncio.Event() + + def on_publish(self, params: lsp.PublishDiagnosticsParams) -> None: + self.history.setdefault(params.uri, []).append(list(params.diagnostics)) + self.changed.set() + + def latest(self, uri: str) -> list[lsp.Diagnostic]: + return self.history.get(uri, [[]])[-1] + + async def wait_for(self, uri: str, predicate: Callable[[list[lsp.Diagnostic]], bool], timeout: float) -> bool: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not (self.history.get(uri) and predicate(self.latest(uri))): + remaining = deadline - loop.time() + if remaining <= 0: + return False + self.changed.clear() + try: + await asyncio.wait_for(self.changed.wait(), timeout=remaining) + except asyncio.TimeoutError: + return False + return True + + +def errors(diags: list[lsp.Diagnostic]) -> list[str]: + """Error messages other than the deliberate marker.""" + return [d.message for d in diags if d.severity == lsp.DiagnosticSeverity.Error and JDTLS_MARKER not in d.message] + + +def semantic(diags: list[lsp.Diagnostic]) -> bool: + return any(JDTLS_MARKER in d.message for d in diags) + + +async def _collect(stream: asyncio.StreamReader | None, lines: list[str]) -> None: + """Keep the server's stderr (its log) drained and captured.""" + if stream is None: + return + while line := await stream.readline(): + lines.append(line.decode(errors="replace").rstrip()) + + +_IMPORT_LINE_RE = re.compile(r"importing \d+ dependency module\(s\) \([^)]*\): (.*)$") +_GA_RE = re.compile(r"(com\.example:[A-Za-z0-9_.\-]+)") +_JDTLS_PID_RE = re.compile(r"jdtls subprocess started \(pid=(\d+)") + + +def imported_gas(server_log: list[str]) -> list[str]: + """Every GA the proxy imported as a dependency module, in import order.""" + result: list[str] = [] + for line in server_log: + match = _IMPORT_LINE_RE.search(line) + if match: + result.extend(_GA_RE.findall(match.group(1))) + return result + + +def jdtls_pid(server_log: list[str]) -> int | None: + for line in server_log: + match = _JDTLS_PID_RE.search(line) + if match: + return int(match.group(1)) + return None + + +def pid_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +@dataclass +class Session: + client: LanguageClient + watch: Watch + log: list[str] = field(default_factory=list) + + def open(self, path: Path) -> str: + uri = path.as_uri() + self.client.text_document_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=uri, language_id="java", version=1, text=path.read_text()) + ) + ) + return uri + + +@asynccontextmanager +async def maven_session( + tmp_path: Path, write_fixture: Callable[[Path], object], *, env_extra: dict[str, str] | None = None +) -> AsyncIterator[tuple[Session, Path]]: + """Start the real server on a reactor written by *write_fixture* under ``tmp_path/root``.""" + fake_home = tmp_path / "home" + fake_home.mkdir() + markers = tmp_path / "tmp" + markers.mkdir() + repo = primed_repo(tmp_path, fake_home) + root = tmp_path / "root" + write_fixture(root) + write_offline_config(root, settings_xml(tmp_path / "settings.xml", repo, offline=True)) + + watch = Watch() + client = LanguageClient("e2e-dependency-modules", "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, + "HOME": str(fake_home), + "JAVA_TOOL_OPTIONS": f"-Duser.home={fake_home}", + "TMPDIR": str(markers), + } + for knob in ("JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES", "JAVA_FUNCTIONAL_LSP_DEPENDENCY_ROUNDS"): + env.pop(knob, None) + env["JAVA_FUNCTIONAL_LSP_LOG_LEVEL"] = "INFO" + env.update(env_extra or {}) + await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) + session = Session(client, watch) + stderr_task = asyncio.create_task(_collect(client._server.stderr, session.log)) # type: ignore[union-attr] + try: + 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()) + yield session, root + finally: + # Keep the server log for post-mortems (the path is in pytest's tmp dir). + with suppress(OSError): + (tmp_path / "server.log").write_text("\n".join(session.log)) + pid = jdtls_pid(session.log) + with suppress(Exception): + await asyncio.wait_for(client.shutdown_async(None), timeout=5.0) + client.exit(None) + with suppress(Exception): + await asyncio.wait_for(client.stop(), timeout=5.0) + stderr_task.cancel() + # Never leave a 4 GB JVM behind, whatever the code under test did. + if pid is not None and pid_alive(pid): + with suppress(OSError): + os.kill(pid, 9) + + +async def wait_log(server_log: list[str], needle: str, timeout: float) -> bool: + """Wait until a server log line contains *needle*.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not any(needle in line for line in server_log): + if loop.time() >= deadline: + return False + await asyncio.sleep(0.1) + return True + + +def log_tail(server_log: list[str], n: int = 4000) -> str: + return "\n".join(server_log)[-n:] diff --git a/tests/test_dependency_modules.py b/tests/test_dependency_modules.py index d82485d..b8ed168 100644 --- a/tests/test_dependency_modules.py +++ b/tests/test_dependency_modules.py @@ -1,52 +1,94 @@ -"""Tests for importing missing in-repo Maven modules and refreshing open files (#110 part B).""" +"""Tests for the demand-driven import of missing in-repo Maven modules (#110, v0.14.1). + +The round controller is driven by a fake jdtls (``_Fake``): it records imports and +refreshes, publishes diagnostics for the open file during a refresh (clean once every +needed module is imported), and publishes the pom markers a real import would surface. +All waits are milliseconds (``Timing``). +""" from __future__ import annotations import asyncio +import json import logging import os +import time +from collections.abc import Callable from pathlib import Path from typing import Any -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock import pytest from java_functional_lsp.dependency_modules import ( DEFAULT_BUDGET, + DEFAULT_ROUNDS, ENV_BUDGET, + ENV_ROUNDS, MAX_BUDGET, - ClasspathRefresher, + MAX_ROUNDS, + STOP_BUDGET, + STOP_BUSY, + STOP_CLEAN, + STOP_NO_CANDIDATES_JAR, + STOP_NO_CANDIDATES_MARKERS, + STOP_NO_CANDIDATES_NONE, + STOP_NO_FRESH, + STOP_REASONS, + STOP_REFRESHES, + STOP_ROUNDS, + STOP_WALL_CLOCK, + BuildIdle, DependencyModules, + Limits, + Timing, + has_demand, + is_demand_diagnostic, path_from_uri, resolve_budget, + resolve_rounds, ) from java_functional_lsp.proxy import JdtlsProxy, _find_maven_group_root, _find_repo_boundary -from java_functional_lsp.reactor import ReactorIndex +from java_functional_lsp.reactor import Dependency, Marker, ReactorIndex + +# --- knobs ----------------------------------------------------------------------------------- -class TestBudget: - def test_default(self) -> None: - assert resolve_budget({}, {}) == DEFAULT_BUDGET == 60 +class TestKnobs: + def test_repo_config_value_is_truncated_in_the_log(self, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.dependency_modules"): + assert resolve_budget({"jdtls": {"dependencyModules": "x" * 10_000}}, {}) == DEFAULT_BUDGET + assert "invalid jdtls.dependencyModules" in caplog.text + assert len(caplog.records[0].getMessage()) < 200 + + def test_defaults(self) -> None: + assert resolve_budget({}, {}) == DEFAULT_BUDGET == 30 + assert resolve_rounds({}, {}) == DEFAULT_ROUNDS == 6 - def test_env(self) -> None: - assert resolve_budget({}, {ENV_BUDGET: "7"}) == 7 + def test_env_may_raise_up_to_the_hard_max(self, caplog: pytest.LogCaptureFixture) -> None: + assert resolve_budget({}, {ENV_BUDGET: "70"}) == 70 + assert resolve_rounds({}, {ENV_ROUNDS: "9"}) == 9 + with caplog.at_level(logging.WARNING): + assert resolve_budget({}, {ENV_BUDGET: "5000"}) == MAX_BUDGET == 200 + assert resolve_rounds({}, {ENV_ROUNDS: "99"}) == MAX_ROUNDS == 20 + assert "above the maximum" in caplog.text - def test_config(self) -> None: + def test_repo_config_can_only_lower(self, caplog: pytest.LogCaptureFixture) -> None: assert resolve_budget({"jdtls": {"dependencyModules": 9}}, {}) == 9 + assert resolve_rounds({"jdtls": {"dependencyRounds": 2}}, {}) == 2 + with caplog.at_level(logging.WARNING): + assert resolve_budget({"jdtls": {"dependencyModules": 150}}, {}) == DEFAULT_BUDGET + assert resolve_rounds({"jdtls": {"dependencyRounds": 10}}, {}) == DEFAULT_ROUNDS + assert "can only lower" in caplog.text def test_env_wins_over_config(self) -> None: assert resolve_budget({"jdtls": {"dependencyModules": 9}}, {ENV_BUDGET: "3"}) == 3 + assert resolve_budget({"jdtls": {"dependencyModules": 9}}, {ENV_BUDGET: "50"}) == 50 - def test_zero_disables(self) -> None: + def test_zero_disables_and_negative_is_zero(self) -> None: assert resolve_budget({}, {ENV_BUDGET: "0"}) == 0 - - def test_clamped_to_max(self, caplog: pytest.LogCaptureFixture) -> None: - with caplog.at_level(logging.WARNING): - assert resolve_budget({}, {ENV_BUDGET: "5000"}) == MAX_BUDGET == 200 - assert "above the maximum" in caplog.text - - def test_negative_is_zero(self) -> None: assert resolve_budget({}, {ENV_BUDGET: "-4"}) == 0 + assert resolve_budget({"jdtls": {"dependencyModules": -1}}, {}) == 0 @pytest.mark.parametrize("raw", ["lots", "1.5"]) def test_invalid_env_uses_default(self, raw: str, caplog: pytest.LogCaptureFixture) -> None: @@ -54,13 +96,15 @@ def test_invalid_env_uses_default(self, raw: str, caplog: pytest.LogCaptureFixtu assert resolve_budget({}, {ENV_BUDGET: raw}) == DEFAULT_BUDGET assert "invalid" in caplog.text - @pytest.mark.parametrize("raw", [True, [1], {"max": 1}]) + @pytest.mark.parametrize("raw", [True, [1], {"max": 1}, "x"]) def test_invalid_config_uses_default(self, raw: Any) -> None: assert resolve_budget({"jdtls": {"dependencyModules": raw}}, {}) == DEFAULT_BUDGET def test_reads_os_environ_by_default(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv(ENV_BUDGET, "11") + monkeypatch.setenv(ENV_ROUNDS, "3") assert resolve_budget() == 11 + assert resolve_rounds() == 3 class TestPathFromUri: @@ -80,426 +124,1049 @@ def test_non_file(self, uri: Any) -> None: assert path_from_uri(uri) is None -ROOT = Path("/repo") -COMMON = ROOT / "groupA" / "common" -UTIL = ROOT / "groupA" / "util" -IT = ROOT / "groupB" / "it" - +# --- demand classification ------------------------------------------------------------------- -def _index() -> ReactorIndex: - return ReactorIndex( - ROOT, - {"com.example:common": COMMON, "com.example:util": UTIL, "com.example:it": IT}, - ) +def _err(message: str, code: str | None = None, severity: int = 1) -> dict[str, Any]: + diag: dict[str, Any] = {"severity": severity, "message": message, "range": {}} + if code is not None: + diag["code"] = code + return diag -class _Harness: - def __init__(self, *, budget: int = DEFAULT_BUDGET, covered: list[Path] | None = None) -> None: - self.sent: list[tuple[list[dict[str, str]], list[dict[str, str]]]] = [] - self.covered = covered if covered is not None else [ROOT / "groupB"] - self.builds = 0 - async def send(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: - self.sent.append((added, removed)) +class TestDemand: + @pytest.mark.parametrize( + "diag", + [ + # Real jdtls 1.61 messages (spike S1 / S2 logs). + _err("The import com.example.common cannot be resolved", "268435846"), + _err("BaseIntegrationTest cannot be resolved to a type", "16777218"), + _err("The method cleanCaches() is undefined for the type MyIntegrationTest"), + _err("sut cannot be resolved or is not a field"), + _err("The hierarchy of the type DeltaProductConfigReportConsumerConfiguration is inconsistent"), + _err("The type com.taboola.X cannot be resolved. It is indirectly referenced from required .class files"), + _err("The method configure() of type Foo must override or implement a supertype method"), + _err("unknown text", "16777218"), # by problem id alone + ], + ) + def test_demand(self, diag: dict[str, Any]) -> None: + assert is_demand_diagnostic(diag) - def build(_root: Path) -> ReactorIndex: - self.builds += 1 - return _index() + @pytest.mark.parametrize( + "diag", + [ + _err("Type mismatch: cannot convert from String to int"), + _err("X cannot be resolved to a type", severity=2), # a warning + _err("The project cannot be built until build path errors are resolved", "0"), + _err("The container 'Maven Dependencies' references non existing library '/m2/x.jar'", "964"), + _err("X cannot be resolved", "16"), # non-project file + {"severity": 1, "message": None}, + "not a dict", + ], + ) + def test_not_demand(self, diag: Any) -> None: + assert not is_demand_diagnostic(diag) + + def test_scan_is_bounded(self) -> None: + noise = [_err("Type mismatch")] * 500 + assert not has_demand([*noise, _err("X cannot be resolved to a type")]) + assert has_demand([_err("X cannot be resolved to a type"), *noise]) + assert not has_demand("nope") + + +# --- build-idle ------------------------------------------------------------------------------ + + +def _progress(task_id: str, task: str = "Building", *, complete: bool = False) -> dict[str, Any]: + return {"id": task_id, "task": task, "subTask": None, "status": "0% ", "complete": complete} + + +class TestBuildIdle: + async def test_idle_after_the_quiet_window(self) -> None: + idle = BuildIdle(quiet=0.03) + assert not idle.is_idle() + assert await idle.wait(None, timeout=1.0) + + async def test_open_task_blocks_until_complete_then_quiet(self) -> None: + idle = BuildIdle(quiet=0.03) + idle.note_progress(_progress("a")) + assert not await idle.wait(None, timeout=0.1) # still open: never idle + idle.note_progress(_progress("a", complete=True)) + assert not idle.is_idle() # the complete event itself restarts the quiet window + assert await idle.wait(None, timeout=1.0) + + async def test_indexing_tasks_never_block(self) -> None: + idle = BuildIdle(quiet=0.03) + await idle.wait(None, timeout=1.0) + idle.note_progress(_progress("s", "Searching...")) + idle.note_progress(_progress("i", "Indexing sources")) + assert idle.open_tasks == 0 + assert idle.is_idle() + + async def test_since_extends_the_window(self) -> None: + idle = BuildIdle(quiet=0.05) + await idle.wait(None, timeout=1.0) + assert idle.is_idle() + since = time.monotonic() + assert not idle.is_idle(since) # idle, but not for *quiet* seconds after *since* + assert await idle.wait(since, timeout=1.0) + assert time.monotonic() - since >= 0.05 + + def test_open_ids_are_bounded(self) -> None: + idle = BuildIdle(quiet=10.0) + for i in range(BuildIdle.MAX_OPEN + 50): + idle.note_progress(_progress(str(i))) + assert idle.open_tasks == BuildIdle.MAX_OPEN + assert "0" not in idle._open # the oldest were dropped + assert not idle.is_idle() + + async def test_single_timer(self) -> None: + idle = BuildIdle(quiet=10.0) + handles = [] + for i in range(3): + idle.note_progress(_progress(str(i), complete=True)) + handles.append(idle._timer) + assert all(h is not None for h in handles) + assert [h.cancelled() for h in handles if h is not None] == [True, True, False] + idle.reset() + assert idle._timer is None + + async def test_timeout(self) -> None: + idle = BuildIdle(quiet=0.02) + idle.note_progress(_progress("x")) + assert not await idle.wait(None, timeout=0.05) + + def test_malformed_progress_is_ignored(self) -> None: + idle = BuildIdle(quiet=0.01) + for params in (None, [], {"task": "Building"}, {"id": 3}): + idle.note_progress(params) + assert idle.open_tasks == 0 + + +# --- the round controller -------------------------------------------------------------------- +ROOT = Path("/repo") +TARGET = ROOT / "groupB" / "target" +A = ROOT / "groupA" +MID = A / "mid" +OWNER = ROOT / "groupC" / "owner" +DEEPER = ROOT / "groupC" / "deeper" +X = ROOT / "groupD" / "x" +Y = ROOT / "groupD" / "y" +HUB = ROOT / "groupD" / "hub" +TJ = ROOT / "groupD" / "testlib" +MODULES = { + "g:target": TARGET, + "g:mid": MID, + "g:owner": OWNER, + "g:deeper": DEEPER, + "g:x": X, + "g:y": Y, + "g:hub": HUB, + "g:testlib": TJ, +} +MAIN_FILE = f"file://{TARGET}/src/main/java/T.java" +TEST_FILE = f"file://{TARGET}/src/test/java/TTest.java" +DEMAND = [_err("Base cannot be resolved to a type", "16777218")] +CLEAN: list[dict[str, Any]] = [] +FAST = Timing(idle_quiet=0.01, round_timeout=0.5, refresh_backoff=0.01, marker_wait=0.1) + + +def _index(target_deps: tuple[Dependency, ...] = (Dependency("g:mid"),)) -> ReactorIndex: + """target -> mid; mid's parent groupA declares owner; owner -> deeper.""" + index = ReactorIndex(ROOT, dict(MODULES)) + index.poms = {**MODULES, "g:groupA": A} + index.dependencies = {TARGET: target_deps, A: (Dependency("g:owner"),), OWNER: (Dependency("g:deeper"),)} + index.parent_of = {MID: "g:groupA"} + return index + + +class _Fake: + """A fake jdtls around one DependencyModules.""" + + def __init__( + self, + *, + index: ReactorIndex | None = None, + needed: set[str] | None = None, + limits: Limits | None = None, + timing: Timing = FAST, + open_files: list[str] | None = None, + markers: dict[str, list[tuple[Path, list[Marker]]]] | None = None, + ) -> None: + self.index = index or _index() + self.needed = needed if needed is not None else {"g:mid", "g:owner"} + self.open = open_files if open_files is not None else [MAIN_FILE] + self.digest: dict[str, str] = dict.fromkeys(self.open, "d1") + self.sent: list[list[str]] = [] + self.refreshed: list[str] = [] + self.inflight = 0 + self.max_inflight = 0 + self.answer = True + self.publish = True + self.refresh_delay = 0.0 + self.notified: list[str] = [] + self.on_refresh: Callable[[str], None] | None = None + # GA imported -> pom publishes it causes (the next layer's markers). + self.markers = ( + markers + if markers is not None + else { + "g:mid": [(MID / "pom.xml", [Marker("g:owner")]), (TARGET / "pom.xml", [Marker("g:owner")])], + "g:owner": [(OWNER / "pom.xml", [Marker("g:deeper")]), (TARGET / "pom.xml", [Marker("g:deeper")])], + } + ) self.deps = DependencyModules( - send_folders=send, - covered_roots=lambda: self.covered, + send_folders=self._send, + covered_roots=lambda: [ROOT / "groupB"], reactor_root_for=lambda _d: ROOT, to_uri=lambda p: f"file://{p}", - budget=budget, - debounce=0.01, - index_builder=build, + send_refresh=self._refresh, + open_uris=lambda: list(self.open), + doc_digest=lambda u: self.digest.get(u), # noqa: PLW0108 (self.digest is reassigned) + module_of=self._module_of, + notify=self.notified.append, + limits=limits or Limits(), + timing=timing, + index_builder=lambda _r: self.index, ) - async def settle(self) -> None: - for _ in range(5): - await asyncio.sleep(0.03) - await _drain(self.deps) - - -async def _drain(deps: DependencyModules) -> None: - """Wait until every background task of *deps* has finished (absence is then meaningful).""" - for _ in range(200): - running = [t for t in deps._tasks if not t.done()] - if not running: - return - await asyncio.gather(*running, return_exceptions=True) - raise AssertionError("dependency-module tasks never settled") - - -class TestDependencyModules: - async def test_batches_candidates_into_one_add(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - h.deps.note_missing(IT / "pom.xml", ["com.example:util", "com.example:common"]) - await h.settle() - assert len(h.sent) == 1 - added, removed = h.sent[0] - assert {a["uri"] for a in added} == {f"file://{COMMON}", f"file://{UTIL}"} - assert removed == [] - assert h.deps.used == 2 - assert h.builds == 1 # single flight - - async def test_external_and_covered_artifacts_are_ignored(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["org.external:lib", "com.example:it"]) # it: under groupB - await h.settle() - assert h.builds == 1 # positive control: the index was built and consulted - assert h.sent == [] - assert h.deps.used == 0 - - async def test_aggregators_are_never_imported(self, tmp_path: Path) -> None: - from java_functional_lsp.reactor import build_reactor_index + @staticmethod + def _module_of(path: Path) -> Path | None: + for module in MODULES.values(): + if path.is_relative_to(module): + return module + return None + + @property + def imported(self) -> list[str]: + return [ga for batch in self.sent for ga in batch] + + async def _send(self, added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + by_dir = {str(d): ga for ga, d in MODULES.items()} + batch = [by_dir[a["uri"].removeprefix("file://")] for a in added] + self.sent.append(batch) + for ga in batch: + for pom, markers in self.markers.get(ga, []): + self.deps.note_pom(pom, markers) + + def diagnostics(self) -> list[dict[str, Any]]: + return CLEAN if self.needed <= set(self.imported) else DEMAND + + async def _refresh(self, uri: str, on_response: Callable[[], None]) -> bool: + self.refreshed.append(uri) + self.inflight += 1 + self.max_inflight = max(self.max_inflight, self.inflight) + try: + await asyncio.sleep(self.refresh_delay or 0.001) + if self.publish: + self.deps.note_publish(uri, self.diagnostics()) + if self.on_refresh is not None: + self.on_refresh(uri) + if self.answer: + on_response() + return self.answer + finally: + self.inflight -= 1 + + def start(self, uri: str = MAIN_FILE, *, pom_markers: list[Marker] | None = None) -> None: + """jdtls imported the demand module: its pom's markers, then the file's first (stale) publish.""" + self.deps.note_pom(TARGET / "pom.xml", pom_markers if pom_markers is not None else [Marker("g:mid")]) + self.deps.note_publish(uri, DEMAND) + + async def settle(self, timeout: float = 5.0) -> None: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + await asyncio.sleep(0) + while self.deps.running: + assert loop.time() < deadline, "the round controller never stopped" + await asyncio.sleep(0.01) - agg = "g{a}{m}" - root = tmp_path / "root" - for rel, text in { - "": agg.format(a="root", m="grp"), - "grp": agg.format(a="grp", m="leaf"), - "grp/leaf": "gleaf", - }.items(): - (root / rel).mkdir(parents=True, exist_ok=True) - (root / rel / "pom.xml").write_text(text) - send = AsyncMock() - indexes: list[ReactorIndex] = [] - def build(r: Path) -> ReactorIndex: - indexes.append(build_reactor_index(r)) - return indexes[-1] +class TestRounds: + async def test_parent_inherited_chain_stops_when_clean(self) -> None: + fake = _Fake() + fake.start() + await fake.settle() + # Round 1: mid (target's own edge); round 2: owner (inherited from mid's parent groupA). + # deeper is in the frontier and reported missing, but the file is clean: never imported. + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + assert fake.deps.rounds == 2 + assert len(fake.notified) == 1 + assert "(clean)" in fake.notified[0] + + async def test_clean_at_the_probe_imports_nothing(self) -> None: + fake = _Fake(needed=set()) + fake.start() + await fake.settle() + assert fake.sent == [] + assert fake.refreshed == [MAIN_FILE] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_frontier_union_and_carry_forward(self) -> None: + index = _index((Dependency("g:x"), Dependency("g:y"))) + markers = [Marker("g:x"), Marker("g:y")] + fake = _Fake(index=index, needed={"g:x", "g:y"}, limits=Limits(per_round=1), markers={}) + fake.start(pom_markers=markers) + await fake.settle() + # y was deferred by the per-round cap and carried into round 2. + assert fake.sent == [["g:x"], ["g:y"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_candidates_are_frontier_and_markers(self) -> None: + index = _index((Dependency("g:x"), Dependency("g:y"))) + # deeper is reported missing too, but it is not in the frontier. + fake = _Fake(index=index, needed={"g:y"}, markers={}) + fake.start(pom_markers=[Marker("g:y"), Marker("g:deeper")]) + await fake.settle() + assert fake.sent == [["g:y"]] + + async def test_order_is_declaration_order_with_hubs_last(self) -> None: + index = _index((Dependency("g:hub"), Dependency("g:y"), Dependency("g:x"))) + index.fan_in = {"g:hub": 40} + fake = _Fake(index=index, needed={"g:x"}, markers={}) + fake.start(pom_markers=[Marker("g:hub"), Marker("g:x"), Marker("g:y")]) + await fake.settle() + assert fake.sent == [["g:y", "g:x", "g:hub"]] + + async def test_test_jar_edges_only_for_test_files_and_test_jar_markers(self) -> None: + index = _index((Dependency("g:testlib", "test", test_jar=True),)) + fake = _Fake(index=index, needed={"g:testlib"}, open_files=[TEST_FILE], markers={}) + fake.start(TEST_FILE, pom_markers=[Marker("g:testlib", test_jar=True)]) + await fake.settle() + assert fake.sent == [["g:testlib"]] + + # A plain-jar marker of the same GA does not match the test-jar edge. + fake = _Fake(index=index, needed={"g:testlib"}, open_files=[TEST_FILE], markers={}) + fake.start(TEST_FILE, pom_markers=[Marker("g:testlib")]) + await fake.settle() + assert fake.sent == [] + assert fake.deps.last_stop == STOP_NO_CANDIDATES_JAR + + # A main-source file never follows test-scope edges. + fake = _Fake(index=index, needed={"g:testlib"}, markers={}) + fake.start(pom_markers=[Marker("g:testlib", test_jar=True)]) + await fake.settle() + assert fake.sent == [] + assert fake.deps.last_stop == STOP_NO_CANDIDATES_NONE + + +class TestStopReasons: + def test_reasons_are_a_fixed_enum(self) -> None: + assert set(STOP_REASONS) == { + "clean", + "no-candidates(none)", + "no-candidates(markers-pending)", + "no-candidates(owner-has-jar)", + "budget", + "rounds", + "wall-clock", + "jdtls-busy", + "no-fresh-diagnostics", + "refresh-cap", + } - deps = DependencyModules( - send_folders=send, - covered_roots=list, - reactor_root_for=lambda _d: root, - to_uri=str, - debounce=0, - index_builder=build, + async def test_no_candidates_none(self) -> None: + fake = _Fake(index=_index(())) + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_NO_CANDIDATES_NONE + + async def test_no_candidates_markers_pending(self) -> None: + fake = _Fake() + fake.deps.note_publish(MAIN_FILE, DEMAND) # the demand module's pom never publishes + await fake.settle() + assert fake.sent == [] + assert fake.deps.last_stop == STOP_NO_CANDIDATES_MARKERS + + async def test_no_candidates_owner_has_jar(self) -> None: + fake = _Fake() + fake.start(pom_markers=[]) # the pom published, mid is not missing: a (stale) jar resolves it + await fake.settle() + assert fake.sent == [] + assert fake.deps.last_stop == STOP_NO_CANDIDATES_JAR + assert "stale" in fake.notified[0] + + async def test_markers_of_the_previous_round_are_awaited(self) -> None: + fake = _Fake(markers={}) + fake.start() + + def late_markers(_uri: str) -> None: + if fake.imported == ["g:mid"]: + loop = asyncio.get_running_loop() + loop.call_later(0.05, fake.deps.note_pom, MID / "pom.xml", [Marker("g:owner")]) + + fake.on_refresh = late_markers + await fake.settle() + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_budget_then_later_demand_stops_at_once(self) -> None: + fake = _Fake(limits=Limits(budget=1), open_files=[MAIN_FILE, f"file://{X}/src/main/java/X.java"]) + fake.digest = dict.fromkeys(fake.open, "d1") + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_BUDGET + assert fake.deps.used == 1 + refreshes = len(fake.refreshed) + fake.deps.note_publish(fake.open[1], DEMAND) # a new module re-arms, but the budget is spent + await fake.settle() + assert fake.deps.last_stop == STOP_BUDGET + assert len(fake.refreshed) == refreshes + assert len(fake.notified) == 1 # a repeated session-limit stop is not re-announced + + async def test_budget_cuts_a_round_short(self) -> None: + index = _index((Dependency("g:x"), Dependency("g:y"), Dependency("g:hub"))) + extra = f"file://{OWNER}/src/main/java/O.java" + fake = _Fake( + index=index, + needed={"g:x", "g:y", "g:hub"}, + limits=Limits(budget=2, per_round=8), + open_files=[MAIN_FILE, extra], + markers={}, + ) + fake.digest = dict.fromkeys(fake.open, "d1") + fake.start(pom_markers=[Marker("g:x"), Marker("g:y"), Marker("g:hub")]) + await fake.settle() + assert fake.sent == [["g:x", "g:y"]] # 3 candidates, only 2 left in the budget + assert fake.deps.used == fake.deps.budget == 2 + assert fake.deps.last_stop == STOP_BUDGET + refreshes = len(fake.refreshed) + fake.deps.note_publish(extra, DEMAND) + await fake.settle() + assert fake.deps.last_stop == STOP_BUDGET + assert len(fake.refreshed) == refreshes + + async def test_rounds(self) -> None: + fake = _Fake(limits=Limits(rounds=1)) + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_ROUNDS + + async def test_wall_clock(self) -> None: + fake = _Fake(limits=Limits(wall_clock=0.0)) + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_WALL_CLOCK + + async def test_wall_clock_excludes_refresh_time(self) -> None: + fake = _Fake(limits=Limits(wall_clock=0.15)) + fake.refresh_delay = 0.2 # each refresh alone exceeds the wall clock + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_wall_clock_counts_import_phases_not_session_age(self) -> None: + other = f"file://{X}/src/main/java/X.java" + index = _index() + index.dependencies[X] = (Dependency("g:y"),) + fake = _Fake( + index=index, needed={"g:mid"}, limits=Limits(wall_clock=0.15), open_files=[MAIN_FILE, other], markers={} ) - deps.note_missing(tmp_path / "other" / "pom.xml", ["g:root", "g:grp", "g:leaf"]) - await _drain(deps) - assert [i.aggregators for i in indexes] == [{"g:root", "g:grp"}] - # Positive control: the leaf in the same batch was imported, the aggregators were not. - send.assert_awaited_once() - assert [a["name"] for a in send.await_args.args[0]] == ["leaf"] - - async def test_already_added_is_not_re_added(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - assert len(h.sent) == 1 + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_CLEAN + await asyncio.sleep(0.3) # idle time between phases is not import time + fake.needed = {"g:mid", "g:y"} + fake.deps.note_pom(X / "pom.xml", [Marker("g:y")]) + fake.deps.note_publish(other, DEMAND) # a new module re-arms + await fake.settle() + assert fake.sent == [["g:mid"], ["g:y"]] + assert fake.deps.last_stop == STOP_CLEAN + assert fake.deps._import_time() < 0.15 + + async def test_busy_before_the_probe(self) -> None: + 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")) # never completes + fake.start() + await fake.settle() + assert fake.refreshed == [] + assert fake.deps.last_stop == STOP_BUSY + # Nothing was imported: the module is un-armed, so its next demand publish tries again. + assert fake.deps._armed == set() + fake.deps.idle.note_progress(_progress("build", complete=True)) + fake.deps.note_publish(MAIN_FILE, DEMAND) + await fake.settle() + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_repeated_busy_is_announced_once(self) -> None: + fake = _Fake(timing=Timing(idle_quiet=0.01, round_timeout=0.03, refresh_backoff=0.01, marker_wait=0.1)) + fake.deps.idle.note_progress(_progress("build")) # never completes + for _ in range(3): + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_BUSY + assert len(fake.notified) == 1 + + async def test_no_fresh_at_the_probe_re_arms(self) -> None: + fake = _Fake() + fake.publish = False + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_NO_FRESH + assert fake.deps._armed == set() + fake.publish = True + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_busy_after_an_import(self) -> None: + fake = _Fake(timing=Timing(idle_quiet=0.01, round_timeout=0.1, refresh_backoff=0.01, marker_wait=0.1)) + 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() + assert fake.sent == [["g:mid"]] + assert fake.refreshed == [MAIN_FILE] # the probe only: no refresh into a busy jdtls + assert fake.deps.last_stop == STOP_BUSY + + async def test_no_fresh_diagnostics_after_one_retry(self) -> None: + fake = _Fake() + fake.publish = False # jdtls answers but never re-validates the file + fake.start() + await fake.settle() + assert fake.refreshed == [MAIN_FILE, MAIN_FILE] + assert fake.deps.last_stop == STOP_NO_FRESH + + async def test_unanswered_refresh_is_retried_once(self) -> None: + fake = _Fake() + fake.answer = False # e.g. the 20 s timeout + fake.start() + await fake.settle() + assert fake.refreshed == [MAIN_FILE, MAIN_FILE] + assert fake.deps.last_stop == STOP_NO_FRESH + + async def test_retry_recovers(self) -> None: + fake = _Fake(needed=set()) + calls = 0 + original = fake._refresh + + async def flaky(uri: str, on_response: Callable[[], None]) -> bool: + nonlocal calls + calls += 1 + if calls == 1: + return False + return await original(uri, on_response) + + fake.deps._send_refresh = flaky + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_CLEAN + + async def test_demand_during_a_phase_gets_its_own_phase(self, caplog: pytest.LogCaptureFixture) -> None: + other = f"file://{X}/src/main/java/X.java" + index = _index() + index.dependencies[X] = (Dependency("g:y"),) + fake = _Fake(index=index, needed={"g:mid"}, open_files=[MAIN_FILE, other], markers={}) + fake.digest = dict.fromkeys(fake.open, "d1") + + def second_file_demands(uri: str) -> None: + if uri == MAIN_FILE and fake.imported == ["g:mid"] and not fake.deps._pending_modules: + assert fake.deps.running # round 1 is in flight: X is only queued + fake.deps.note_pom(X / "pom.xml", [Marker("g:y")]) + fake.deps.note_publish(other, DEMAND) + + fake.on_refresh = second_file_demands + with caplog.at_level(logging.INFO, logger="java_functional_lsp.dependency_modules"): + fake.start() + await fake.settle() + # X had its own phase after phase 1 stopped: its probe refresh (clean here). + assert fake.refreshed == [MAIN_FILE, MAIN_FILE, other] + assert fake.sent == [["g:mid"]] + stops = [r.getMessage() for r in caplog.records if "import stopped" in r.getMessage()] + assert len(stops) == 2 + + async def test_extra_quiet_window_catches_a_late_marker(self) -> None: + timing = Timing(idle_quiet=0.2, round_timeout=2.0, refresh_backoff=0.01, marker_wait=0.05) + fake = _Fake(needed={"g:mid"}, timing=timing, markers={}) + fake.start(pom_markers=[]) # the pom published, but no marker yet + + def late_marker(_uri: str) -> None: + if not fake.imported: # the probe: m2e reports mid missing within the extra window + loop = asyncio.get_running_loop() + loop.call_later(0.1, fake.deps.note_pom, TARGET / "pom.xml", [Marker("g:mid")]) + + fake.on_refresh = late_marker + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_failing_phase_is_contained_and_re_arms(self, caplog: pytest.LogCaptureFixture) -> None: + fake = _Fake(needed={"g:mid"}) + original = fake._send + fail = True + + async def broken_send(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + if fail: + raise RuntimeError("boom") + await original(added, removed) + + fake.deps._send_folders = broken_send + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.dependency_modules"): + fake.start() + await fake.settle() + assert not fake.deps.running + assert "dependency-module import failed" in caplog.text + assert fake.deps._armed == set() # the same module's next demand tries again + fail = False + fake.deps.registry.clear() + fake.deps._session.record.clear() + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_failing_phase_keeps_the_queue(self) -> None: + other = f"file://{X}/src/main/java/X.java" + index = _index(()) + index.dependencies[X] = (Dependency("g:y"),) + fake = _Fake(index=index, needed={"g:y"}, open_files=[MAIN_FILE, other], markers={}) + fake.digest = dict.fromkeys(fake.open, "d1") + original = fake._refresh + + async def refresh(uri: str, on_response: Callable[[], None]) -> bool: + if uri == MAIN_FILE: + fake.deps.note_pom(X / "pom.xml", [Marker("g:y")]) + fake.deps.note_publish(other, DEMAND) # queued while the first phase runs + raise RuntimeError("boom") + return await original(uri, on_response) + + fake.deps._send_refresh = refresh + fake.start() + await fake.settle() + assert fake.sent == [["g:y"]] # the queued module still got its phase + assert fake.deps.last_stop == STOP_CLEAN + + async def test_one_phase_is_one_reactor_root(self) -> None: + other_root = Path("/other") + roots = {X: other_root} + fake = _Fake() + fake.deps._reactor_root_for = lambda d: roots.get(d, ROOT) + fake.deps._pending_modules = [TARGET, X, MID] + assert fake.deps._take_phase() == [TARGET, MID] + assert fake.deps._pending_modules == [X] + assert fake.deps._take_phase() == [X] + assert fake.deps._pending_modules == [] async def test_disabled_does_nothing(self) -> None: - h = _Harness(budget=0) - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - assert h.sent == [] - assert h.builds == 0 - - async def test_budget_exhaustion_warns_with_unresolved_gas(self, caplog: pytest.LogCaptureFixture) -> None: - h = _Harness(budget=1) - with caplog.at_level(logging.WARNING, logger="java_functional_lsp.dependency_modules"): - h.deps.note_missing(IT / "pom.xml", ["com.example:common", "com.example:util"]) - await h.settle() - h.deps.note_missing(IT / "pom.xml", ["com.example:util"]) - await h.settle() - assert len(h.sent) == 1 - assert len(h.sent[0][0]) == 1 - warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] - assert len(warnings) == 1 # the same GA is reported once - assert "com.example:util" in warnings[0] - assert ENV_BUDGET in warnings[0] - - async def test_group_expansion_retires_covered_folders(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - removed = h.deps.take_covered_by(ROOT / "groupA") - assert removed == [{"uri": f"file://{COMMON}", "name": "common"}] - assert h.deps.registry == {} - # Never re-added, even if the covering folder is not reported as covered. - h.covered = [] - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - assert len(h.sent) == 1 - assert h.deps.used == 1 # removal does not refund the budget - - async def test_group_expansion_drops_pending_candidates(self) -> None: - h = _Harness() - h.deps.debounce = 0.2 - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await asyncio.sleep(0.05) # indexed and pending, not flushed yet - assert h.deps.take_covered_by(ROOT / "groupA") == [] - await h.settle() - assert h.sent == [] - - async def test_group_expanded_before_flush_skips_candidate(self) -> None: - h = _Harness() - h.deps.debounce = 0.2 - h.deps.note_missing(IT / "pom.xml", ["com.example:common", "com.example:util"]) - for _ in range(100): # until both are queued, well before the debounce ends - if len(h.deps._pending) == 2: - break - await asyncio.sleep(0.005) - assert set(h.deps._pending) == {"com.example:common", "com.example:util"} - h.covered.append(COMMON) # the group holding common was imported meanwhile - await h.settle() - # Positive control: the flush ran and sent util; only the covered candidate was skipped. - assert [[a["name"] for a in added] for added, _ in h.sent] == [["util"]] - - async def test_candidate_queued_during_a_send_is_flushed(self) -> None: - release = asyncio.Event() - sent: list[list[str]] = [] - - async def slow_send(added: list[dict[str, str]], _removed: list[dict[str, str]]) -> None: - sent.append([a["name"] for a in added]) - if len(sent) == 1: - await release.wait() # e.g. stdin.drain() in the real proxy + fake = _Fake(limits=Limits(budget=0)) + fake.start() + await asyncio.sleep(0.05) + assert not fake.deps.running + assert fake.refreshed == [] + assert fake.sent == [] + + +class TestFreshness: + async def test_stale_in_flight_publish_is_not_fresh(self) -> None: + fake = _Fake(needed=set()) + fake.publish = False + fake.start() + # A publish that was already in flight arrives before the refresh is sent: it never + # fills the refresh window, so the round has no fresh diagnostics (one retry, then STOP). + fake.deps.note_publish(MAIN_FILE, DEMAND) + await fake.settle() + assert fake.deps.last_stop == STOP_NO_FRESH + + async def test_publish_after_the_response_is_not_fresh(self) -> None: + fake = _Fake(needed=set()) + fake.publish = False + original = fake._refresh + + async def late(uri: str, on_response: Callable[[], None]) -> bool: + answered = await original(uri, on_response) + fake.deps.note_publish(uri, CLEAN) # after the response was dispatched + return answered + + fake.deps._send_refresh = late + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_NO_FRESH + + async def test_last_publish_in_the_window_decides(self) -> None: + fake = _Fake(needed={"g:mid"}) + + def extra(uri: str) -> None: + fake.deps.note_publish(uri, DEMAND if not fake.imported else CLEAN) + + fake.on_refresh = extra + fake.start() + await fake.settle() + assert fake.sent == [["g:mid"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_uri_spelling_is_keyed(self) -> None: + fake = _Fake(needed=set()) + fake.deps._uri_key = lambda u: u.replace("file:///", "file:/") + original = fake._refresh + + async def echo_other_form(uri: str, on_response: Callable[[], None]) -> bool: + fake.publish = False + fake.deps.note_publish(uri.replace("file:///", "file:/"), CLEAN) # jdtls's own spelling + return await original(uri, on_response) + + fake.deps._send_refresh = echo_other_form + fake.start() + await fake.settle() + assert fake.deps.last_stop == STOP_CLEAN + + async def test_edit_during_refresh_is_not_fresh(self) -> None: + fake = _Fake(needed=set()) + edits = iter(["edited", "edited-again"]) + fake.on_refresh = lambda uri: fake.digest.__setitem__(uri, next(edits)) + fake.start() + await fake.settle() + # Both publishes describe content the document no longer has. + assert fake.refreshed == [MAIN_FILE, MAIN_FILE] + assert fake.deps.last_stop == STOP_NO_FRESH + + async def test_retry_after_an_edit_recovers(self) -> None: + fake = _Fake(needed=set()) + fake.on_refresh = lambda uri: fake.digest.__setitem__(uri, "edited") + fake.start() + await fake.settle() + assert fake.refreshed == [MAIN_FILE, MAIN_FILE] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_unsolicited_publish_never_decides_a_round(self) -> None: + fake = _Fake() + original = fake._send + + async def send_and_publish(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + await original(added, removed) + fake.deps.note_publish(MAIN_FILE, CLEAN) # jdtls re-validated on its own, mid-build + + fake.deps._send_folders = send_and_publish + fake.start() + await fake.settle() + # Each round still refreshed the file and decided on that fresh publish. + assert fake.refreshed == [MAIN_FILE] * 3 + assert fake.sent == [["g:mid"], ["g:owner"]] + assert fake.deps.last_stop == STOP_CLEAN + + async def test_closed_demand_file_is_not_refreshed(self) -> None: + fake = _Fake() + original = fake._send + + async def send_and_close(added: list[dict[str, str]], removed: list[dict[str, str]]) -> None: + await original(added, removed) + fake.open.clear() + + fake.deps._send_folders = send_and_close + fake.start() + await fake.settle() + assert fake.refreshed == [MAIN_FILE] # the probe only + assert fake.deps.last_stop == STOP_CLEAN + + async def test_refresh_cap_per_round_and_one_in_flight(self) -> None: + files = [f"file://{TARGET}/src/main/java/F{i}.java" for i in range(5)] + fake = _Fake(needed=set(), open_files=files) + for uri in files: + fake.deps.note_publish(uri, DEMAND) + fake.deps.note_pom(TARGET / "pom.xml", [Marker("g:mid")]) + await fake.settle() + assert fake.refreshed == files[::-1][:3] # most recently opened first, at most 3 + assert fake.max_inflight == 1 + + async def test_refresh_cap_per_session(self) -> None: + other = f"file://{X}/src/main/java/X.java" + fake = _Fake(limits=Limits(refreshes_per_session=1), open_files=[MAIN_FILE, other]) + fake.digest = dict.fromkeys(fake.open, "d1") + fake.start() + await fake.settle() + assert fake.refreshed == [MAIN_FILE] + # A session limit, not "jdtls did not re-validate the file". + assert fake.deps.last_stop == STOP_REFRESHES + assert "refresh cap" in fake.notified[0] or "refresh-cap" in fake.notified[0] + fake.deps.note_publish(other, DEMAND) # a new module: stops at once, not re-announced + await fake.settle() + assert fake.deps.last_stop == STOP_REFRESHES + assert fake.refreshed == [MAIN_FILE] + assert len(fake.notified) == 1 + + def test_default_refresh_cap_lets_the_rounds_limit_fire_first(self) -> None: + limits = Limits() + # The probe plus every round, each with 3 files and one retry. + assert limits.refresh_cap == 3 * (DEFAULT_ROUNDS + 1) * 2 + assert Limits(rounds=20).refresh_cap == 3 * 21 * 2 + assert Limits(refreshes_per_session=5).refresh_cap == 5 + + async def test_closed_files_do_not_arm(self) -> None: + fake = _Fake(open_files=[]) + fake.start() + await asyncio.sleep(0.05) + assert not fake.deps.running + assert fake.refreshed == [] + + +class TestRecord: + async def test_budget_comes_from_the_proxys_own_record( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + record = tmp_path / "abc.deps.json" + record.write_text(json.dumps({"schema": 1, "modules": [{"ga": f"g:{i}", "path": "/x"} for i in range(5)]})) + fake = _Fake() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.dependency_modules"): + fake.deps.begin_session(record) + # jdtls 1.61 does not keep added folders across a restart: the old record is not counted. + assert fake.deps.used == 0 + assert "does not keep them" in caplog.text + assert json.loads(record.read_text())["modules"] == [] + fake.start() + await fake.settle() + saved = json.loads(record.read_text())["modules"] + assert [m["ga"] for m in saved] == ["g:mid", "g:owner"] + assert saved[0]["path"] == str(MID) + assert fake.deps.used == len(saved) == 2 + + def test_record_write_leaves_no_temp_file_and_ignores_a_planted_name(self, tmp_path: Path) -> None: + record = tmp_path / "abc.deps.json" + victim = tmp_path / "victim" + victim.write_text("keep") + (tmp_path / "abc.deps.json.tmp").symlink_to(victim) # v0.14.1's predictable temp name + fake = _Fake() + fake.deps.begin_session(record) + assert json.loads(record.read_text()) == {"schema": 1, "modules": []} + assert victim.read_text() == "keep" + assert sorted(p.name for p in tmp_path.iterdir()) == ["abc.deps.json", "abc.deps.json.tmp", "victim"] + + def test_unreadable_record_is_ignored(self, tmp_path: Path) -> None: + record = tmp_path / "x.deps.json" + record.write_text("{not json") + fake = _Fake() + fake.deps.begin_session(record) + assert json.loads(record.read_text()) == {"schema": 1, "modules": []} + fake.deps.begin_session(None) + + async def test_retired_folders_still_count(self) -> None: + fake = _Fake(limits=Limits(rounds=1)) + fake.start() + await fake.settle() + assert fake.deps.take_covered_by(A) == [{"uri": f"file://{MID}", "name": "mid"}] + assert fake.deps.registry == {} + assert fake.deps.used == 1 - deps = DependencyModules( - send_folders=slow_send, - covered_roots=list, - reactor_root_for=lambda _d: ROOT, - to_uri=str, - debounce=0.01, - index_builder=lambda _r: _index(), - ) - deps.note_missing(IT / "pom.xml", ["com.example:common"]) - for _ in range(100): - if sent: - break - await asyncio.sleep(0.005) - assert sent == [["common"]] - deps.note_missing(IT / "pom.xml", ["com.example:util"]) # while the first send is in flight - for _ in range(10): - await asyncio.sleep(0.01) - release.set() - await _drain(deps) - assert sent == [["common"], ["util"]] - assert deps._pending == {} - assert set(deps.registry) == {"com.example:common", "com.example:util"} + async def test_reset_forgets_session(self) -> None: + fake = _Fake() + fake.start() + await fake.settle() + fake.deps.reset() + assert fake.deps.registry == {} + assert fake.deps.used == 0 + assert fake.deps.rounds == 0 + assert fake.deps.last_stop is None + + async def test_summary_is_logged(self, caplog: pytest.LogCaptureFixture) -> None: + fake = _Fake() + fake.start() + await fake.settle() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.dependency_modules"): + fake.deps.log_summary() + assert "rounds 2, imported 2/30, refreshes 3 (" in caplog.text + assert "s), stops 1" in caplog.text + assert "refreshes 3 (" in fake.notified[0] # the refresh time is on the STOP line too + + async def test_round_log_names_the_imports(self, caplog: pytest.LogCaptureFixture) -> None: + fake = _Fake() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.dependency_modules"): + fake.start() + 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 "refresh errors" in rounds[0] + assert "refresh clean" in rounds[1] + assert any("stopped (clean)" in r.getMessage() for r in caplog.records) async def test_index_failure_is_contained(self, caplog: pytest.LogCaptureFixture) -> None: - def boom(_root: Path) -> ReactorIndex: - raise OSError("disk") + fake = _Fake() + + def broken(_root: Path) -> ReactorIndex: + raise RuntimeError("boom") + + fake.deps._index_builder = broken + with caplog.at_level(logging.WARNING, logger="java_functional_lsp.dependency_modules"): + fake.start() + await fake.settle() + assert "reactor index of repo failed" in caplog.text + assert fake.deps.last_stop == STOP_NO_CANDIDATES_NONE + + def test_note_publish_without_loop_is_a_no_op(self) -> None: + fake = _Fake() + fake.start() + assert not fake.deps.running + # Nothing was scheduled, so the module is not kept armed (a later publish can arm it). + assert fake.deps._armed == set() + assert fake.deps._pending_modules == [] + + +class TestAggregatorsAndSymlinks: + async def test_aggregators_are_never_candidates(self, tmp_path: Path) -> None: + from java_functional_lsp.reactor import build_reactor_index + agg = "g{a}{d}{m}" + dep = "g{a}" + root = tmp_path / "root" + leaf_deps = dep.format(a="grp").replace("", "") + dep.format(a="leaf").replace( + "", "" + ) + for rel, text in { + "": agg.format(a="root", d="", m="grpapp"), + "grp": agg.format(a="grp", d="", m="leaf"), + "grp/leaf": "gleaf", + "app": f"gapp{leaf_deps}", + }.items(): + (root / rel).mkdir(parents=True, exist_ok=True) + (root / rel / "pom.xml").write_text(text) + index = build_reactor_index(root) + assert index.aggregators == {"g:root", "g:grp"} + app = index.poms["g:app"] deps = DependencyModules( send_folders=AsyncMock(), covered_roots=list, - reactor_root_for=lambda _d: ROOT, + reactor_root_for=lambda _d: root, to_uri=str, - debounce=0, - index_builder=boom, + module_of=lambda _p: app, + open_uris=lambda: [f"file://{app}/src/A.java"], + index_builder=lambda _r: index, ) - with caplog.at_level(logging.WARNING): - deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await asyncio.sleep(0.05) - assert "reactor index" in caplog.text + deps.note_pom(app / "pom.xml", [Marker("g:grp"), Marker("g:leaf")]) + candidates, frontier, _ = await deps._candidates([f"file://{app}/src/A.java"]) + assert [ga for ga, _ in candidates] == ["g:leaf"] + assert frontier == 1 - async def test_reset_forgets_session(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - h.deps.reset() - assert h.deps.used == 0 - assert h.deps.registry == {} - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - await h.settle() - assert len(h.sent) == 2 - assert h.builds == 2 - - def test_note_missing_without_loop_is_a_no_op(self) -> None: - h = _Harness() - h.deps.note_missing(IT / "pom.xml", ["com.example:common"]) - assert h.deps._tasks == set() - assert h.deps._pending == {} - assert h.deps.registry == {} - assert h.deps.used == 0 - assert h.builds == 0 - assert h.sent == [] - - -@pytest.mark.skipif(os.name == "nt", reason="symlinks") -class TestSymlinkedRoot: - """Registry entries are resolved; folders the proxy imported may be spelled through a symlink.""" - - @pytest.fixture - def linked(self, tmp_path: Path) -> tuple[Path, Path]: + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + async def test_symlinked_covered_root_is_not_a_candidate(self, tmp_path: Path) -> None: real = tmp_path / "real" - (real / "groupA" / "common").mkdir(parents=True) - (real / "groupB" / "it").mkdir(parents=True) + common = real / "groupA" / "common" + it = real / "groupB" / "it" + for d in (common, it): + d.mkdir(parents=True) link = tmp_path / "link" link.symlink_to(real, target_is_directory=True) - return real.resolve(), link - - def _deps(self, real: Path, covered: list[Path], sent: list[list[str]]) -> DependencyModules: - async def send(added: list[dict[str, str]], _removed: list[dict[str, str]]) -> None: - sent.append([a["name"] for a in added]) - - return DependencyModules( - send_folders=send, + index = ReactorIndex(real, {"g:common": common, "g:it": it}) + index.dependencies = {it: (Dependency("g:common"),)} + covered: list[Path] = [] + deps = DependencyModules( + send_folders=AsyncMock(), covered_roots=lambda: covered, reactor_root_for=lambda _d: real, to_uri=str, - debounce=0, - index_builder=lambda _r: ReactorIndex(real, {"com.example:common": real / "groupA" / "common"}), + module_of=lambda _p: it, + index_builder=lambda _r: index, ) + deps.note_pom(link / "groupB" / "it" / "pom.xml", [Marker("g:common")]) + uri = f"file://{link}/groupB/it/src/A.java" + # Positive control: nothing covers it yet. + assert [ga for ga, _ in (await deps._candidates([uri]))[0]] == ["g:common"] + covered.append(link / "groupA" / "common") # imported through the symlink + assert (await deps._candidates([uri]))[0] == [] - def test_take_covered_by_matches_the_symlinked_spelling(self, linked: tuple[Path, Path]) -> None: - real, link = linked - deps = self._deps(real, [], []) - deps.registry["com.example:common"] = real / "groupA" / "common" - removed = deps.take_covered_by(link / "groupA") - assert [r["name"] for r in removed] == ["common"] - assert deps.registry == {} - - async def test_symlinked_covered_root_prevents_import(self, linked: tuple[Path, Path]) -> None: - real, link = linked - sent: list[list[str]] = [] - deps = self._deps(real, [link / "groupA"], sent) - deps.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) - await _drain(deps) - assert sent == [] - assert deps.registry == {} - # Positive control: with nothing covering it, the same report imports it. - deps2 = self._deps(real, [], sent) - deps2.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) - await _drain(deps2) - assert sent == [["common"]] - - -class TestClasspathRefresher: - async def test_refreshes_open_java_files_under_project_once(self) -> None: - sent: list[str] = [] - opened = [ - f"file://{IT}/src/test/java/A.java", - f"file://{IT}/src/test/java/B.java", - f"file://{IT}/pom.xml", - f"file://{COMMON}/src/main/java/C.java", - ] - - async def refresh(uri: str) -> None: - sent.append(uri) - - r = ClasspathRefresher(lambda: opened, refresh, debounce=0.02) - r.note_updated(IT) - r.note_updated(IT) # debounced - await asyncio.sleep(0.1) - assert sent == opened[:2] - - async def test_projects_are_debounced_separately(self) -> None: - sent: list[str] = [] - - async def refresh(uri: str) -> None: - sent.append(uri) - - opened = [f"file://{IT}/A.java", f"file://{COMMON}/C.java"] - r = ClasspathRefresher(lambda: opened, refresh, debounce=0.02) - r.note_updated(IT) - r.note_updated(COMMON) - await asyncio.sleep(0.1) - assert sorted(sent) == sorted(opened) - - async def test_open_uris_failure_is_contained(self) -> None: - def broken() -> list[str]: - raise RuntimeError("no workspace") - - send = AsyncMock() - r = ClasspathRefresher(broken, send, debounce=0) - r.note_updated(IT) - await asyncio.sleep(0.02) - send.assert_not_called() - - async def test_reset_cancels_pending(self) -> None: - send = AsyncMock() - r = ClasspathRefresher(lambda: [f"file://{IT}/A.java"], send, debounce=0.05) - r.note_updated(IT) - r.reset() - await asyncio.sleep(0.1) - send.assert_not_called() + @pytest.mark.skipif(os.name == "nt", reason="symlinks") + def test_take_covered_by_matches_the_symlinked_spelling(self, tmp_path: Path) -> None: + real = tmp_path / "real" + (real / "groupA" / "common").mkdir(parents=True) + link = tmp_path / "link" + link.symlink_to(real, target_is_directory=True) + deps = DependencyModules(AsyncMock(), list, lambda _d: real, str) + deps.registry["g:common"] = (real / "groupA" / "common").resolve() + assert [r["name"] for r in deps.take_covered_by(link / "groupA")] == ["common"] -# --- proxy wiring --------------------------------------------------------------------------- +# --- proxy wiring ---------------------------------------------------------------------------- def _pom_diag(message: str, severity: int = 1) -> dict[str, Any]: return {"severity": severity, "message": message, "range": {}} +def _publish(proxy: JdtlsProxy, uri: str, diagnostics: list[Any]) -> None: + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": diagnostics}} + ) + + class TestProxyWiring: - def test_classpath_updated_event_triggers_refresh(self) -> None: + def test_every_pom_publish_feeds_markers(self) -> None: proxy = JdtlsProxy() - proxy._classpath_refresher = MagicMock() - proxy._handle_notification( - {"method": "language/eventNotification", "params": {"eventType": 100, "data": "file:/repo/groupB/it/"}} - ) - proxy._classpath_refresher.note_updated.assert_called_once_with(Path("/repo/groupB/it")) + uri = "file:///repo/groupB/it/pom.xml" + msgs = [ + "Offline / Missing artifact com.example:common:jar:X-DEFAULT", + "Missing artifact com.example:base:jar:tests:X-DEFAULT", + "Non-resolvable parent POM", + ] + for _ in range(2): # identical publishes still count as arrivals + _publish(proxy, uri, [_pom_diag(m) for m in msgs]) + module = Path("/repo/groupB/it").resolve() + deps = proxy.dependency_modules + assert deps._pom_publishes[module] == 2 + assert deps._markers[module] == {Marker("com.example:common"), Marker("com.example:base", test_jar=True)} + _publish(proxy, uri, []) + assert module not in deps._markers - @pytest.mark.parametrize("params", [{"eventType": 200, "data": ["file:/x/"]}, {"eventType": 100, "data": 3}, []]) - def test_other_events_are_ignored(self, params: Any) -> None: + def test_java_publish_reaches_the_controller(self) -> None: proxy = JdtlsProxy() - proxy._classpath_refresher = MagicMock() - proxy._handle_notification({"method": "language/eventNotification", "params": params}) - proxy._classpath_refresher.note_updated.assert_not_called() + seen: list[tuple[str, Any]] = [] + proxy.dependency_modules.note_publish = lambda u, d: seen.append((u, d)) # type: ignore[method-assign] + _publish(proxy, "file:///repo/A.java", DEMAND) + _publish(proxy, "file:///repo/pom.xml", []) + assert seen == [("file:///repo/A.java", DEMAND)] - def test_missing_artifact_on_pom_queues_import_and_clearing_refreshes(self) -> None: + def test_progress_report_reaches_build_idle(self) -> None: proxy = JdtlsProxy() - proxy.dependency_modules = MagicMock() - proxy._classpath_refresher = MagicMock() - uri = "file:///repo/groupB/it/pom.xml" - msg = "Offline / Missing artifact com.example:common:jar:X-DEFAULT" - proxy._handle_notification( - {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": [_pom_diag(msg)]}} - ) - proxy.dependency_modules.note_missing.assert_called_once_with( - Path("/repo/groupB/it/pom.xml"), ["com.example:common"] - ) - proxy._classpath_refresher.note_updated.assert_not_called() + proxy._handle_notification({"method": "language/progressReport", "params": _progress("b")}) + assert proxy.dependency_modules.idle.open_tasks == 1 + + def test_classpath_updated_no_longer_refreshes(self) -> None: + proxy = JdtlsProxy() + proxy.send_request = AsyncMock() # type: ignore[method-assign] proxy._handle_notification( - {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": []}} + {"method": "language/eventNotification", "params": {"eventType": 100, "data": "file:/repo/groupB/it/"}} ) - proxy._classpath_refresher.note_updated.assert_called_once_with(Path("/repo/groupB/it")) + proxy.send_request.assert_not_called() - def test_other_pom_errors_do_not_trigger(self) -> None: - proxy = JdtlsProxy() - proxy.dependency_modules = MagicMock() - proxy._classpath_refresher = MagicMock() - uri = "file:///repo/it/pom.xml" - for diags in ([_pom_diag("Non-resolvable parent POM")], []): - proxy._handle_notification( - {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": diags}} - ) - proxy.dependency_modules.note_missing.assert_not_called() - proxy._classpath_refresher.note_updated.assert_not_called() - - async def test_refresh_sends_execute_command(self) -> None: + async def test_refresh_sends_execute_command_and_reports_the_answer(self) -> None: proxy = JdtlsProxy() proxy._available = True - proxy.send_request = AsyncMock(return_value=None) # type: ignore[method-assign] - await proxy._refresh_file_diagnostics("file:///repo/A.java") - proxy.send_request.assert_awaited_once() - method, params = proxy.send_request.await_args.args + proxy._request = AsyncMock(return_value=(True, None)) # type: ignore[method-assign] + assert await proxy._refresh_file_diagnostics("file:///repo/A.java") + method, params = proxy._request.await_args.args assert method == "workspace/executeCommand" assert params == { "command": "java.project.refreshDiagnostics", "arguments": ["file:///repo/A.java", "thisFile", False], } + proxy._request = AsyncMock(return_value=(False, None)) # type: ignore[method-assign] + assert not await proxy._refresh_file_diagnostics("file:///repo/A.java") async def test_refresh_skipped_when_unavailable(self) -> None: proxy = JdtlsProxy() - proxy.send_request = AsyncMock() # type: ignore[method-assign] - await proxy._refresh_file_diagnostics("file:///repo/A.java") - proxy.send_request.assert_not_called() - - async def test_open_uris_callback_reaches_refresher(self) -> None: - proxy = JdtlsProxy(open_uris=lambda: ["file:///repo/it/A.java"]) - assert proxy._classpath_refresher.open_files_under(Path("/repo/it")) == ["file:///repo/it/A.java"] + proxy._request = AsyncMock() # type: ignore[method-assign] + assert not await proxy._refresh_file_diagnostics("file:///repo/A.java") + proxy._request.assert_not_called() + + def test_callbacks_reach_the_controller(self) -> None: + notes: list[str] = [] + proxy = JdtlsProxy( + open_uris=lambda: ["file:///repo/it/A.java"], doc_digest=lambda _u: "d", notify_client=notes.append + ) + deps = proxy.dependency_modules + assert deps._open_list() == ["file:///repo/it/A.java"] + assert deps._doc_digest("x") == "d" + deps._notify("hi") + assert notes == ["hi"] @pytest.fixture @@ -541,7 +1208,6 @@ async def test_expand_full_workspace_removes_covered_dependency_folders(self, tw proxy._initial_module_uri = two_groups["it"].as_uri() proxy.modules.mark_added(two_groups["it"].as_uri()) proxy.send_notification = AsyncMock() # type: ignore[method-assign] - # A dependency folder inside groupB (e.g. added while the group expansion was pending). proxy.dependency_modules.registry["com.example:it2"] = (two_groups["root"] / "groupB" / "it2").resolve() proxy.dependency_modules.registry["com.example:common"] = two_groups["common"].resolve() await proxy.expand_full_workspace() @@ -553,17 +1219,11 @@ async def test_dependency_folders_are_not_in_group_registries(self, two_groups: proxy = JdtlsProxy() proxy._available = True proxy.send_notification = AsyncMock() # type: ignore[method-assign] - proxy.modules.mark_added(two_groups["it"].as_uri()) - deps = proxy.dependency_modules - deps.debounce = 0 - deps._index_builder = lambda _r: ReactorIndex(two_groups["root"], {"com.example:common": two_groups["common"]}) - deps.note_missing(two_groups["it"] / "pom.xml", ["com.example:common"]) - for _ in range(5): - await asyncio.sleep(0.02) + await proxy.dependency_modules._import([("com.example:common", two_groups["common"])]) proxy.send_notification.assert_awaited_once() assert proxy._expanded_groups == set() assert two_groups["common"].as_uri() not in proxy.modules.uris() - assert "com.example:common" in deps.registry + assert "com.example:common" in proxy.dependency_modules.registry @pytest.mark.skipif(os.name == "nt", reason="symlinks") async def test_symlinked_client_root_still_retires_dependency_folders( @@ -573,32 +1233,14 @@ async def test_symlinked_client_root_still_retires_dependency_folders( link.symlink_to(two_groups["root"], target_is_directory=True) proxy = JdtlsProxy() proxy._available = True - proxy._original_root_uri = link.as_uri() # the client reaches the checkout through a symlink + proxy._original_root_uri = link.as_uri() proxy.send_notification = AsyncMock() # type: ignore[method-assign] proxy.dependency_modules.registry["com.example:common"] = two_groups["common"].resolve() - await proxy.expand_full_workspace() # no initial module: the root keeps the client's spelling + await proxy.expand_full_workspace() params = proxy.send_notification.await_args.args[1] assert [r["name"] for r in params["event"]["removed"]] == ["common"] assert proxy.dependency_modules.registry == {} - @pytest.mark.skipif(os.name == "nt", reason="symlinks") - async def test_symlinked_module_folder_counts_as_covered(self, two_groups: dict[str, Path], tmp_path: Path) -> None: - link = tmp_path / "link" - link.symlink_to(two_groups["root"], target_is_directory=True) - proxy = JdtlsProxy() - proxy._available = True - proxy.send_notification = AsyncMock() # type: ignore[method-assign] - proxy.modules.mark_added((link / "groupA" / "common").as_uri()) # imported via the symlink - proxy.modules.mark_added((link / "groupB" / "it").as_uri()) - deps = proxy.dependency_modules - deps.debounce = 0 - common = two_groups["common"].resolve() - deps._index_builder = lambda _r: ReactorIndex(two_groups["root"].resolve(), {"com.example:common": common}) - deps.note_missing(link / "groupB" / "it" / "pom.xml", ["com.example:common"]) - await _drain(deps) - proxy.send_notification.assert_not_called() - assert deps.registry == {} - async def test_stop_resets_dependency_state(self) -> None: proxy = JdtlsProxy() proxy._available = True diff --git a/tests/test_diagnostics_freshness.py b/tests/test_diagnostics_freshness.py index dbfeaf2..752d170 100644 --- a/tests/test_diagnostics_freshness.py +++ b/tests/test_diagnostics_freshness.py @@ -555,10 +555,11 @@ async def test_superseded_hold_task_does_not_publish_or_steal_event(self, live: 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")): + with patch.object(srv_mod, "_run_analysis", side_effect=RuntimeError("boom")) as failing: await _edit() - await _past_debounce() - assert not srv_mod._freshness.is_pending(URI) + # Poll, not a fixed sleep: on a slow CI runner the debounced analysis can run + # after a 30 ms sleep, i.e. after the patch is gone. + await _until(lambda: failing.called and not srv_mod._freshness.is_pending(URI)) _jdtls_publishes([]) assert live.call_count == 1 diff --git a/tests/test_e2e_dependency_modules.py b/tests/test_e2e_dependency_modules.py index 0898086..2a0c3d5 100644 --- a/tests/test_e2e_dependency_modules.py +++ b/tests/test_e2e_dependency_modules.py @@ -1,39 +1,49 @@ -"""E2E (#110): a dependency on a reactor module in another Maven group resolves. +"""E2E (#110, v0.14.1): cross-group dependency modules are imported only as far as the open file needs. -Real server + real jdtls on a two-group reactor with ``${revision}``:: +Real server + real jdtls on ``${revision}`` reactors whose in-repo artifacts are missing from +an isolated, offline local repository (see ``e2e_maven``). - root/pom.xml (revision X-DEFAULT, modules groupA, groupB) - root/groupA/common BaseIntegrationTest - root/groupB/it MyIntegrationTest extends BaseIntegrationTest (depends on common) - -The client root is ``root``; the group walk scopes jdtls to ``groupB``, so ``common`` is -not imported and m2e looks for ``com.example:common:jar:X-DEFAULT`` in the local -repository. That repository is isolated (never ``~/.m2``), primed with Maven's plugins -only, and used offline, so the artifact is missing, as it is for an unpublished sibling. -Without the fix the test file keeps four false errors next to its one deliberate error ("cannot be resolved", -"undefined for the type"). With it, the proxy imports ``common`` from the pom.xml -"Missing artifact" diagnostic and refreshes the open file. +* ``test_cross_group_dependency_resolves``: one missing sibling is imported, and the round's + post-idle refresh (not an older publish) confirms the file clean. +* ``test_parent_inherited_chain_stops_when_clean`` (also the "no re-publish" case): the needed + type comes from a module that is declared only in an intermediate module's *parent* pom; the + owner itself depends on a deeper module that the open file does not need. jdtls does not + re-publish the file after round 1's import (verified by disabling the post-idle refresh: the + file then keeps "The import com.example.mid cannot be resolved"), so only the refresh can + decide round 2. The import must stop once the file is clean. +* ``test_sigterm_leaves_no_jdtls``: SIGTERM on the server stops its jdtls JVM too. Skipped when jdtls, Java 21+, or Maven (for the one-time priming) is unavailable. -The primed repository is cached in ``~/.cache/java-functional-lsp/`` (override with -``JAVA_FUNCTIONAL_LSP_E2E_M2``). """ from __future__ import annotations import asyncio -import json -import os import shutil -import subprocess -import sys +import signal 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 +from tests.e2e_maven import ( + FALSE_ERRORS, + PRIME_TIMEOUT_SEC, + deps_xml, + errors, + group_pom, + imported_gas, + jdtls_pid, + leaf_pom, + log_tail, + maven_session, + pid_alive, + root_pom, + semantic, + wait_log, + write_files, + write_two_group_fixture, +) pytestmark = [ pytest.mark.e2e, @@ -41,107 +51,86 @@ pytest.mark.skipif(find_jdtls_java_home() is None, reason="no Java 21+ found"), ] -_ROOT_POM = """\ - - - 4.0.0 - com.example - root - ${revision} - pom - - X-DEFAULT - 17 - 17 - 17 - - - - - org.apache.maven.pluginsmaven-compiler-plugin\ -3.11.0 - org.apache.maven.pluginsmaven-resources-plugin\ -3.3.1 - org.apache.maven.pluginsmaven-surefire-plugin\ -3.5.4 - - - - - groupA - groupB - - -""" +_SEMANTIC_TIMEOUT_SEC = 150 +# Counted from the first semantic publish: build-idle (10 s quiet), the probe refresh, the +# import, build-idle again and the round's refresh, per round. +_CLEAN_TIMEOUT_SEC = 150 +# After the file is clean, keep watching long enough for a cascade to show itself. +_CASCADE_WATCH_SEC = 25 -def _group_pom(name: str, module: str) -> str: - return f"""\ - - - 4.0.0 - - com.example - root - ${{revision}} - - {name} - pom - - {module} - - +@pytest.mark.timeout(PRIME_TIMEOUT_SEC * 2 + _SEMANTIC_TIMEOUT_SEC + _CLEAN_TIMEOUT_SEC + 120) +async def test_cross_group_dependency_resolves(tmp_path: Path) -> None: + async with maven_session(tmp_path, write_two_group_fixture) as (session, root): + uri = session.open(root / "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java") + if not await session.watch.wait_for(uri, semantic, _SEMANTIC_TIMEOUT_SEC): + pytest.skip(f"jdtls never analyzed the test file (import too slow?): {session.watch.history.get(uri)}") + clean = await session.watch.wait_for(uri, lambda d: semantic(d) and not errors(d), _CLEAN_TIMEOUT_SEC) + remaining = errors(session.watch.latest(uri)) + assert clean, f"cross-group symbols still unresolved: {remaining}\n{log_tail(session.log)}" + assert not any(marker in e for e in remaining for marker in FALSE_ERRORS) + # The fix itself resolved it: common was imported as a dependency module, rather than + # jdtls resolving it some other way (e.g. a leaked artifact). The round's log line follows + # the refresh that published the clean set. + await wait_log(session.log, "dependency-module import stopped", 60.0) + assert imported_gas(session.log) == ["com.example:common"], log_tail(session.log) + # The probe and the post-idle refresh both ran, and the round's refresh saw the clean set. + stop = next((line for line in session.log if "dependency-module import stopped" in line), None) + assert stop is not None, f"no dependency-module STOP line\n{log_tail(session.log)}" + assert "(clean)" in stop + assert int(stop.split("refreshes ")[1].split()[0].rstrip(";")) >= 2, stop + assert any("dependency round 1" in line and "refresh clean" in line for line in session.log) + + +# groupB/app -> groupA/mid (Target extends Mid). The module is not named "target": jdtls +# excludes that directory name from the import. +# groupA's pom (mid's parent) declares groupC/owner (Mid extends owner's Base). +# groupC/owner -> groupC/deeper, which no signature Target sees ever mentions. +_MID = """\ +package com.example.mid; + +import com.example.owner.Base; + +public class Mid extends Base { + public int mid() { + return 2; + } +} """ +_BASE = """\ +package com.example.owner; - -def _leaf_pom(parent: str, name: str, deps: str = "") -> str: - return f"""\ - - - 4.0.0 - - com.example - {parent} - ${{revision}} - - {name}{deps} - +public class Base { + public int base() { + return 1; + } +} """ +_OWNER_HELPER = """\ +package com.example.owner; +import com.example.deeper.Deeper; -_IT_DEPS = """ - - - com.example - common - ${revision} - - """ - -_BASE = """\ -package com.example.common; - -public abstract class BaseIntegrationTest { - protected String sut = "system-under-test"; - - protected void cleanCaches() { - sut = null; +class OwnerHelper { + Deeper deeper() { + return new Deeper(); } } """ +_DEEPER = """\ +package com.example.deeper; -# The type mismatch is a deterministic jdtls error that needs a resolved JRE: its presence proves a -# publish came from jdtls's semantic pass (the server's custom-only publish and jdtls's non-project, -# syntax-only publish both lack it). It is the only error the file should keep. -_TEST = """\ -package com.example.it; +public class Deeper { +} +""" +_TARGET = """\ +package com.example.app; -import com.example.common.BaseIntegrationTest; +import com.example.mid.Mid; -public class MyIntegrationTest extends BaseIntegrationTest { +public class Target extends Mid { public int run() { - cleanCaches(); - return this.sut.length(); + return base() + mid(); } public int marker() { @@ -149,234 +138,66 @@ def _leaf_pom(parent: str, name: str, deps: str = "") -> str: } } """ -_JDTLS_MARKER = "Type mismatch" -_FALSE_ERRORS = ("cannot be resolved", "is undefined for the type", "hierarchy of the type") - -_SEMANTIC_TIMEOUT_SEC = 150 -_CLEAN_TIMEOUT_SEC = 60 -_PRIME_TIMEOUT_SEC = 300 - - -def _write_fixture(root: Path) -> Path: - """Write the reactor under *root* and return MyIntegrationTest.java.""" - files = { - "pom.xml": _ROOT_POM, - "groupA/pom.xml": _group_pom("groupA", "common"), - "groupB/pom.xml": _group_pom("groupB", "it"), - "groupA/common/pom.xml": _leaf_pom("groupA", "common"), - "groupB/it/pom.xml": _leaf_pom("groupB", "it", _IT_DEPS), - "groupA/common/src/main/java/com/example/common/BaseIntegrationTest.java": _BASE, - "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java": _TEST, - } - for rel, text in files.items(): - path = root / rel - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text) - return root / "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java" - - -def _settings_xml(path: Path, repo: Path, *, offline: bool) -> Path: - path.write_text( - '\n' - '\n' - f" {repo}\n" - f" {'true' if offline else 'false'}\n" - "\n" +_TARGET_PATH = "groupB/app/src/main/java/com/example/app/Target.java" + + +def _write_chain_fixture(root: Path) -> None: + write_files( + root, + { + "pom.xml": root_pom(["groupA", "groupB", "groupC"]), + "groupA/pom.xml": group_pom("groupA", ["mid"], deps_xml("owner")), + "groupB/pom.xml": group_pom("groupB", ["app"]), + "groupC/pom.xml": group_pom("groupC", ["owner", "deeper"]), + "groupA/mid/pom.xml": leaf_pom("groupA", "mid"), + "groupB/app/pom.xml": leaf_pom("groupB", "app", deps_xml("mid")), + "groupC/owner/pom.xml": leaf_pom("groupC", "owner", deps_xml("deeper")), + "groupC/deeper/pom.xml": leaf_pom("groupC", "deeper"), + "groupA/mid/src/main/java/com/example/mid/Mid.java": _MID, + "groupC/owner/src/main/java/com/example/owner/Base.java": _BASE, + "groupC/owner/src/main/java/com/example/owner/OwnerHelper.java": _OWNER_HELPER, + "groupC/deeper/src/main/java/com/example/deeper/Deeper.java": _DEEPER, + _TARGET_PATH: _TARGET, + }, ) - return path - -def _primed_repo(work: Path, fake_home: Path) -> Path: - """Return a local repository holding Maven's plugins but no com.example artifacts. - With a truly empty offline repository m2e cannot compute a build plan and creates no - Java project at all, so the plugins are fetched once (online) by building the fixture. - """ - repo = Path( - os.environ.get("JAVA_FUNCTIONAL_LSP_E2E_M2") - or Path.home() / ".cache" / "java-functional-lsp" / "e2e-m2-issue110-v1" - ) - stamp = repo / ".primed" - if not stamp.is_file(): - mvn = shutil.which("mvn") - java_home = find_jdtls_java_home() - if mvn is None or java_home is None: - pytest.skip("Maven is needed once to prime the isolated local repository") - repo.mkdir(parents=True, exist_ok=True) - prime_root = work / "prime" - _write_fixture(prime_root) - settings = _settings_xml(work / "settings-online.xml", repo, offline=False) - env = { - **os.environ, - "JAVA_HOME": java_home, - "HOME": str(fake_home), - "MAVEN_OPTS": f"-Duser.home={fake_home}", - } - for goal in ("test-compile", "clean"): - cmd = [mvn, "-B", "-q", "-s", str(settings), "-gs", str(settings), f"-Dmaven.repo.local={repo}"] - try: - proc = subprocess.run( - [*cmd, "-f", str(prime_root / "pom.xml"), goal], - capture_output=True, - text=True, - timeout=_PRIME_TIMEOUT_SEC, - check=False, - env=env, - ) - except (OSError, subprocess.SubprocessError) as e: - pytest.skip(f"priming the local repository failed: {e}") - if proc.returncode != 0: - pytest.skip(f"priming the local repository failed (offline?): {proc.stdout[-500:]}") - stamp.write_text("ok\n") - # The reactor build never installs, but a stale com.example would make the test vacuous. - shutil.rmtree(repo / "com" / "example", ignore_errors=True) - return repo - - -class _Watch: - def __init__(self) -> None: - self.history: dict[str, list[list[lsp.Diagnostic]]] = {} - self.changed = asyncio.Event() - - def on_publish(self, params: lsp.PublishDiagnosticsParams) -> None: - self.history.setdefault(params.uri, []).append(list(params.diagnostics)) - self.changed.set() - - def latest(self, uri: str) -> list[lsp.Diagnostic]: - return self.history.get(uri, [[]])[-1] - - async def wait_for(self, uri: str, predicate: object, timeout: float) -> bool: - assert callable(predicate) - loop = asyncio.get_running_loop() - deadline = loop.time() + timeout - while not (self.history.get(uri) and predicate(self.latest(uri))): - remaining = deadline - loop.time() - if remaining <= 0: - return False - self.changed.clear() - try: - await asyncio.wait_for(self.changed.wait(), timeout=remaining) - except asyncio.TimeoutError: - return False - return True - - -async def _collect(stream: asyncio.StreamReader | None, lines: list[str]) -> None: - """Keep the server's stderr (its log) drained and captured.""" - if stream is None: - return - while line := await stream.readline(): - lines.append(line.decode(errors="replace").rstrip()) - - -async def _assert_dependency_module_imported(server_log: list[str]) -> None: - """The fix itself resolved it: common was imported as a dependency module and the open - file refreshed, rather than jdtls resolving it some other way (e.g. a leaked artifact).""" - imports = [line for line in server_log if "importing 1 dependency module(s)" in line] - assert imports, "\n".join(server_log)[-4000:] - assert "com.example:common" in imports[0] - # The refresh follows the pom's "Missing artifact" clearing after a debounce, and may land - # after jdtls's own clean publish. - for _ in range(100): - if any("classpath of it updated, refreshing" in line for line in server_log): - return - await asyncio.sleep(0.1) - raise AssertionError("open file never refreshed:\n" + "\n".join(server_log)[-4000:]) - - -def _errors(diags: list[lsp.Diagnostic]) -> list[str]: - """Error messages other than the deliberate marker.""" - return [d.message for d in diags if d.severity == lsp.DiagnosticSeverity.Error and _JDTLS_MARKER not in d.message] - - -def _semantic(diags: list[lsp.Diagnostic]) -> bool: - return any(_JDTLS_MARKER in d.message for d in diags) - - -@pytest.mark.timeout(_PRIME_TIMEOUT_SEC * 2 + _SEMANTIC_TIMEOUT_SEC + _CLEAN_TIMEOUT_SEC + 60) -async def test_cross_group_dependency_resolves(tmp_path: Path) -> None: - fake_home = tmp_path / "home" - fake_home.mkdir() - markers = tmp_path / "tmp" - markers.mkdir() - repo = _primed_repo(tmp_path, fake_home) - root = tmp_path / "root" - test_file = _write_fixture(root) - settings = _settings_xml(tmp_path / "settings.xml", repo, offline=True) - # jdtls.settings replaces the proxy's defaults, so the defaults are repeated here. - (root / ".java-functional-lsp.json").write_text( - json.dumps( - { - "jdtls": { - "settings": { - "java": { - "import": { - "maven": {"enabled": True, "offline": {"enabled": True}}, - "gradle": {"enabled": False}, - "exclusions": ["**/node_modules/**", "**/.metadata/**", "**/target/**"], - }, - "configuration": { - "updateBuildConfiguration": "automatic", - "maven": {"userSettings": str(settings), "globalSettings": str(settings)}, - }, - "maven": {"downloadSources": False}, - } - } - } - } - ) - ) - - watch = _Watch() - client = LanguageClient("e2e-dependency-modules", "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, - # Keep jdtls, m2e and the proxy (Lombok lookup, jdtls data cache) away from the real ~/.m2 and ~/.cache. - "HOME": str(fake_home), - "JAVA_TOOL_OPTIONS": f"-Duser.home={fake_home}", - "TMPDIR": str(markers), - } - env.pop("JAVA_FUNCTIONAL_LSP_DEPENDENCY_MODULES", None) - env["JAVA_FUNCTIONAL_LSP_LOG_LEVEL"] = "INFO" - await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) - server_log: list[str] = [] - stderr_task = asyncio.create_task(_collect(client._server.stderr, server_log)) - uri = test_file.as_uri() - try: - 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()) - client.text_document_did_open( - lsp.DidOpenTextDocumentParams( - text_document=lsp.TextDocumentItem(uri=uri, language_id="java", version=1, text=_TEST) - ) - ) - if not await watch.wait_for(uri, _semantic, _SEMANTIC_TIMEOUT_SEC): - pytest.skip(f"jdtls never analyzed the test file (import too slow?): {watch.history.get(uri)}") - clean = await watch.wait_for(uri, lambda d: _semantic(d) and not _errors(d), _CLEAN_TIMEOUT_SEC) - errors = _errors(watch.latest(uri)) - assert clean, f"cross-group symbols still unresolved: {errors}" - assert not any(marker in e for e in errors for marker in _FALSE_ERRORS) - await _assert_dependency_module_imported(server_log) - finally: - try: - await asyncio.wait_for(client.shutdown_async(None), timeout=5.0) - client.exit(None) - except Exception: - pass +@pytest.mark.timeout(PRIME_TIMEOUT_SEC * 2 + _SEMANTIC_TIMEOUT_SEC + 2 * _CLEAN_TIMEOUT_SEC + _CASCADE_WATCH_SEC + 120) +async def test_parent_inherited_chain_stops_when_clean(tmp_path: Path) -> None: + async with maven_session(tmp_path, _write_chain_fixture) as (session, root): + uri = session.open(root / _TARGET_PATH) + if not await session.watch.wait_for(uri, semantic, _SEMANTIC_TIMEOUT_SEC): + pytest.skip(f"jdtls never analyzed the target file: {session.watch.history.get(uri)}") + clean = await session.watch.wait_for(uri, lambda d: semantic(d) and not errors(d), 2 * _CLEAN_TIMEOUT_SEC) + assert clean, f"target still has errors: {errors(session.watch.latest(uri))}\n{log_tail(session.log)}" + await wait_log(session.log, "dependency-module import stopped", 60.0) + await asyncio.sleep(_CASCADE_WATCH_SEC) + imported = imported_gas(session.log) + assert "com.example:deeper" not in imported, f"cascade imported an unneeded module: {imported}" + assert set(imported) == {"com.example:mid", "com.example:owner"}, log_tail(session.log) + assert len(imported) <= 2, imported + assert not errors(session.watch.latest(uri)) + + +@pytest.mark.timeout(PRIME_TIMEOUT_SEC * 2 + _SEMANTIC_TIMEOUT_SEC + 60) +async def test_sigterm_leaves_no_jdtls(tmp_path: Path) -> None: + async with maven_session(tmp_path, write_two_group_fixture) as (session, root): + uri = session.open(root / "groupB/it/src/test/java/com/example/it/MyIntegrationTest.java") + if not await session.watch.wait_for(uri, semantic, _SEMANTIC_TIMEOUT_SEC): + pytest.skip("jdtls never analyzed the test file") + pid = jdtls_pid(session.log) + assert pid is not None, log_tail(session.log) + assert pid_alive(pid) + server = session.client._server + assert server is not None + server.send_signal(signal.SIGTERM) try: - await asyncio.wait_for(client.stop(), timeout=5.0) - except Exception: - pass - stderr_task.cancel() + await asyncio.wait_for(server.wait(), timeout=10.0) + except asyncio.TimeoutError: + pytest.fail("the server did not exit within 10 s of SIGTERM") + loop = asyncio.get_running_loop() + deadline = loop.time() + 10.0 + while pid_alive(pid) and loop.time() < deadline: + await asyncio.sleep(0.2) + survived = pid_alive(pid) + assert not survived, f"jdtls JVM pid {pid} survived SIGTERM of the server\n{log_tail(session.log)}" diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 67d11aa..2f69a0b 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -108,7 +108,10 @@ def test_dispatch_error_response(self) -> None: proxy._dispatch_message({"id": 2, "error": {"code": -1, "message": "fail"}}) assert future.done() - assert future.result() is None + # An error sentinel: send_request still returns None, _request reports "not answered". + from java_functional_lsp.proxy import _ErrorResponse + + assert isinstance(future.result(), _ErrorResponse) loop.close() def test_dispatch_diagnostics_notification(self) -> None: diff --git a/tests/test_proxy_scope_logging.py b/tests/test_proxy_scope_logging.py index 3f91c99..1ca91d4 100644 --- a/tests/test_proxy_scope_logging.py +++ b/tests/test_proxy_scope_logging.py @@ -317,9 +317,13 @@ def _publish(self, proxy: JdtlsProxy, uri: str, diagnostics: list[dict[str, obje def test_logs_only_on_change_and_keeps_publishing(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: published: list[tuple[str, list[object]]] = [] - proxy = JdtlsProxy(on_diagnostics=lambda u, d: published.append((u, d))) + module = tmp_path / "groupB" / "it" + (module / "src").mkdir(parents=True) + (module / "pom.xml").write_text("") + opened = [(module / "src" / "A.java").as_uri()] # a file of this module is open: INFO + proxy = JdtlsProxy(on_diagnostics=lambda u, d: published.append((u, d)), open_uris=lambda: opened) proxy._original_root_uri = tmp_path.as_uri() - pom_uri = (tmp_path / "groupB" / "it" / "pom.xml").as_uri() + pom_uri = (module / "pom.xml").as_uri() missing = [ {"severity": 1, "message": f"Offline / Missing artifact com.example:c{i}:jar:X-DEFAULT"} for i in range(5) ] @@ -349,11 +353,24 @@ def test_java_files_are_not_summarized(self, tmp_path: Path, caplog: pytest.LogC self._publish(proxy, uri, [{"severity": 1, "message": "x cannot be resolved"}]) assert _jdtls_lines(caplog) == [] + def test_churn_of_modules_without_open_files_is_debug( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + proxy = JdtlsProxy(open_uris=lambda: [(tmp_path / "other" / "A.java").as_uri()]) + proxy._original_root_uri = tmp_path.as_uri() + uri = (tmp_path / "dep" / "pom.xml").as_uri() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + self._publish(proxy, uri, [{"severity": 1, "message": "Missing artifact g:a:jar:1"}]) + assert _jdtls_lines(caplog) == [] + with caplog.at_level(logging.DEBUG, logger="java_functional_lsp.proxy"): + self._publish(proxy, uri, []) + assert _jdtls_lines(caplog) == [f"jdtls: pom.xml errors changed for {Path('dep') / 'pom.xml'}: 0 error(s)"] + def test_pom_outside_client_root_is_redacted(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: proxy = JdtlsProxy() proxy._original_root_uri = (tmp_path / "elsewhere").as_uri() uri = (tmp_path / "secret-user" / "pom.xml").as_uri() - with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + with caplog.at_level(logging.DEBUG, logger="java_functional_lsp.proxy"): self._publish(proxy, uri, [{"severity": 1, "message": "Missing artifact g:a:jar:1\n\x1b[0m"}]) assert _jdtls_lines(caplog) == [ "jdtls: pom.xml errors changed for .../pom.xml: 1 error(s): Missing artifact g:a:jar:1\\n[0m" diff --git a/tests/test_reactor.py b/tests/test_reactor.py index 064bc6e..4261535 100644 --- a/tests/test_reactor.py +++ b/tests/test_reactor.py @@ -281,3 +281,129 @@ def test_dedupes_in_order(self) -> None: "Missing artifact a.b:x:test-jar:tests:1", ) assert parse_missing_artifacts(messages) == ["a.b:x", "a.b:y"] + + +# --- dependency edges (v0.14.1) ---------------------------------------------------------------- + + +def _deps_pom(artifact: str, parent: str | None, deps: str, *, modules: tuple[str, ...] = ()) -> str: + parent_xml = f"g{parent}" if parent else "" + mods = "" + "".join(f"{m}" for m in modules) + "" if modules else "" + return f"{parent_xml}g{artifact}{deps}{mods}" + + +def _dep(artifact: str, extra: str = "", group: str = "g") -> str: + return f"{group}{artifact}{extra}" + + +@pytest.fixture +def chain(tmp_path: Path) -> Path: + """root -> {grpA (declares owner, managed-only x) -> mid, grpB -> app, grpC -> {owner, deeper, x, tlib}}.""" + root = tmp_path / "chain" + _write(root, "", _deps_pom("root", None, "", modules=("grpA", "grpB", "grpC"))) + _write( + root, + "grpA", + _deps_pom( + "grpA", + "root", + f"{_dep('owner')}" + f"{_dep('x')}", + modules=("mid",), + ), + ) + _write(root, "grpA/mid", _deps_pom("mid", "grpA", "")) + _write(root, "grpB", _deps_pom("grpB", "root", "", modules=("app",))) + app_deps = ( + _dep("mid") + + _dep("x", "test") + + _dep("tlib", "test-jartest") + + _dep("tlib", "tests") + + _dep("deeper", "runtime", group="${project.groupId}") + + _dep("owner", "import") + + _dep("junit", "test", group="org.junit") + + _dep("${weird}") + ) + _write(root, "grpB/app", _deps_pom("app", "grpB", f"{app_deps}")) + _write(root, "grpC", _deps_pom("grpC", "root", "", modules=("owner", "deeper", "x", "tlib"))) + _write(root, "grpC/owner", _deps_pom("owner", "grpC", f"{_dep('deeper')}")) + for leaf in ("deeper", "x", "tlib"): + _write(root, f"grpC/{leaf}", _deps_pom(leaf, "grpC", "")) + return root + + +class TestEdges: + def test_parent_chain_is_inherited(self, chain: Path) -> None: + index = build_reactor_index(chain) + mid = index.poms["g:mid"] + assert index.parent_of[mid] == "g:grpA" + # mid declares nothing itself; owner comes from its parent grpA. dependencyManagement is ignored. + assert [d.ga for d in index.edges(mid)] == ["g:owner"] + owner = index.poms["g:owner"] + assert [d.ga for d in index.edges(owner)] == ["g:deeper"] + + def test_scopes_placeholders_and_test_jars(self, chain: Path) -> None: + index = build_reactor_index(chain) + app = index.poms["g:app"] + # Main classpath: compile + runtime (the ${project.groupId} placeholder resolves); the + # import-scope, external and unparseable entries are dropped; tests classifier is a test-jar. + main = index.edges(app) + assert [(d.ga, d.scope, d.test_jar) for d in main] == [ + ("g:mid", "compile", False), + ("g:tlib", "compile", True), + ("g:deeper", "runtime", False), + ] + with_tests = index.edges(app, test=True) + assert [(d.ga, d.scope, d.test_jar) for d in with_tests] == [ + ("g:mid", "compile", False), + ("g:x", "test", False), + ("g:tlib", "test", True), + ("g:deeper", "runtime", False), + ] + + def test_fan_in_counts_main_scope_declarations(self, chain: Path) -> None: + index = build_reactor_index(chain) + assert index.fan_in["g:deeper"] == 2 # app (runtime) and owner + assert "g:x" not in index.fan_in # test scope / managed only + assert index.is_hub("g:deeper", 2) + assert not index.is_hub("g:deeper", 3) + + def test_parent_cycle_and_unknown_parent_terminate(self, tmp_path: Path) -> None: + root = tmp_path / "cyc" + _write(root, "", _deps_pom("root", "b", "", modules=("a", "b"))) + _write(root, "a", _deps_pom("a", "b", f"{_dep('b')}")) + _write(root, "b", _deps_pom("b", "a", f"{_dep('a')}")) + index = build_reactor_index(root) + a = index.poms["g:a"] + assert [d.ga for d in index.edges(a)] == ["g:b", "g:a"] + assert index.edges(tmp_path / "unknown") == [] + + +class TestMissingMarkers: + def test_type_and_classifier_are_kept(self) -> None: + from java_functional_lsp.reactor import Marker, parse_missing_markers + + assert parse_missing_markers( + [ + "Offline / Missing artifact com.example:common:jar:X-DEFAULT", + "Missing artifact com.example:base:jar:tests:X-DEFAULT", + "Missing artifact com.example:base:test-jar:X-DEFAULT", + "Missing artifact com.example:common:jar:X-DEFAULT", + "Missing artifact com.example:native:jar:linux-x86_64:1.0", + "Non-resolvable parent POM", + ] + ) == [ + Marker("com.example:common"), + Marker("com.example:base", test_jar=True), + Marker("com.example:native"), + ] + + def test_truncated_coordinates_never_raise(self) -> None: + from java_functional_lsp.reactor import Marker, parse_missing_markers + + # One token after g:a: (no version) used to raise "not enough values to unpack" + # inside the jdtls reader loop. + assert parse_missing_markers(["Missing artifact g:a:jar", "Missing artifact g:t:test-jar"]) == [ + Marker("g:a"), + Marker("g:t", test_jar=True), + ] diff --git a/tests/test_shutdown.py b/tests/test_shutdown.py new file mode 100644 index 0000000..8cbe08b --- /dev/null +++ b/tests/test_shutdown.py @@ -0,0 +1,372 @@ +"""Tests for the bounded shutdown path and the v0.14.1 proxy plumbing (#107, #110). + +``JdtlsProxy.stop()`` is driven against real child processes standing in for jdtls: one that +answers ``shutdown`` and exits on ``exit``, one that ignores both (SIGTERM ends it), and one +that also ignores SIGTERM (SIGKILL ends it). Each must finish within ~3 s. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import logging +import os +import signal +import sys +import time +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from lsprotocol import types as lsp +from pygls.workspace import Workspace + +from java_functional_lsp import server as server_mod +from java_functional_lsp.freshness_marker import content_digest +from java_functional_lsp.proxy import JdtlsProxy, _build_effective_params, _data_dir_hash + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals") + +_FAKE_JDTLS = r""" +import json, sys +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 or msg.get("method") == "exit": + sys.exit(0) + if msg.get("method") in ("shutdown", "error/please"): + reply = {"jsonrpc": "2.0", "id": msg["id"], "result": None} + if msg["method"] == "error/please": + reply = {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32603, "message": "nope"}} + body = json.dumps(reply).encode() + sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body) + body) + sys.stdout.buffer.flush() +""" +_DEAF = "import time; time.sleep(60)" +_STUBBORN = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)" + + +async def _proxy_with(script: str) -> tuple[JdtlsProxy, asyncio.subprocess.Process]: + proc = await asyncio.create_subprocess_exec( + sys.executable, "-c", script, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE + ) + proxy = JdtlsProxy() + proxy._process = proc + assert proc.stdout is not None + proxy._reader_task = asyncio.create_task(proxy._reader_loop(proc.stdout)) + proxy._available = True + await asyncio.sleep(0.3) # let the interpreter start (and install its SIGTERM handler) + return proxy, proc + + +class TestBoundedStop: + @pytest.mark.timeout(20) + async def test_cooperative_jdtls_answers_shutdown_and_exits(self, caplog: pytest.LogCaptureFixture) -> None: + proxy, proc = await _proxy_with(_FAKE_JDTLS) + started = time.monotonic() + with caplog.at_level(logging.INFO, logger="java_functional_lsp.proxy"): + await proxy.stop() + assert time.monotonic() - started < 1.0 + assert proc.returncode == 0 + assert "timed out" not in caplog.text # the shutdown reply was read before the reader was cancelled + assert not proxy.is_available + + @pytest.mark.timeout(20) + 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 + assert proc.returncode == -signal.SIGTERM + + @pytest.mark.timeout(20) + async def test_stubborn_jdtls_gets_sigkill_within_three_seconds(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 + + @pytest.mark.timeout(20) + async def test_stop_is_idempotent(self) -> None: + proxy, proc = await _proxy_with(_DEAF) + await asyncio.gather(proxy.stop(), proxy.stop()) + await proxy.stop() + assert proc.returncode is not None + + +class TestServerShutdown: + @pytest.fixture(autouse=True) + def _exits(self, monkeypatch: pytest.MonkeyPatch) -> list[int]: + codes: list[int] = [] + monkeypatch.setattr(server_mod, "_hard_exit", codes.append) + monkeypatch.setattr(server_mod, "_watchdog_exit", codes.append) + self.codes = codes + return codes + + async def test_exit_stops_jdtls_then_hard_exits(self, monkeypatch: pytest.MonkeyPatch) -> None: + stop = AsyncMock() + monkeypatch.setattr(server_mod.server._proxy, "stop", stop) + monkeypatch.setattr(server_mod, "_process_mode", True) + monkeypatch.setattr(server_mod.server.protocol, "_shutdown", True, raising=False) + await server_mod.on_exit(None) + stop.assert_awaited_once() + assert self.codes == [0] + + async def test_exit_without_shutdown_exits_1(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(server_mod.server._proxy, "stop", AsyncMock()) + monkeypatch.setattr(server_mod, "_process_mode", True) + monkeypatch.setattr(server_mod.server.protocol, "_shutdown", False, raising=False) + await server_mod.on_exit(None) + assert self.codes == [1] + + async def test_exit_is_bounded_when_stop_hangs(self, monkeypatch: pytest.MonkeyPatch) -> None: + async def hang() -> None: + await asyncio.sleep(60) + + monkeypatch.setattr(server_mod.server._proxy, "stop", hang) + monkeypatch.setattr(server_mod, "_process_mode", True) + monkeypatch.setattr(server_mod, "_STOP_TIMEOUT_SEC", 0.05) + started = time.monotonic() + await server_mod.on_exit(None) + assert time.monotonic() - started < 1.0 + assert len(self.codes) == 1 + + async def test_in_process_exit_never_hard_exits(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(server_mod.server._proxy, "stop", AsyncMock()) + monkeypatch.setattr(server_mod, "_process_mode", False) + await server_mod.on_exit(None) + assert self.codes == [] + + async def test_shutdown_stops_jdtls(self, monkeypatch: pytest.MonkeyPatch) -> None: + stop = AsyncMock() + monkeypatch.setattr(server_mod.server._proxy, "stop", stop) + await server_mod.on_shutdown(None) + stop.assert_awaited_once() + assert self.codes == [] + + async def test_first_signal_stops_then_exits_second_exits_at_once(self, monkeypatch: pytest.MonkeyPatch) -> None: + timers: list[tuple[float, Any]] = [] + timers_fns: list[Any] = [] + + class FakeTimer: + daemon = False + + def __init__(self, interval: float, fn: Any, args: tuple[Any, ...]) -> None: + timers.append((interval, args)) + timers_fns.append(fn) + + def start(self) -> None: + pass + + monkeypatch.setattr(server_mod.threading, "Timer", FakeTimer) + monkeypatch.setattr(server_mod, "_signals_received", 0) + stop = AsyncMock() + monkeypatch.setattr(server_mod.server._proxy, "stop", stop) + server_mod._on_signal(signal.SIGTERM) + assert timers == [(server_mod._SIGNAL_WATCHDOG_SEC, (143,))] # the hard 5 s watchdog + assert timers_fns == [server_mod._watchdog_exit] # never logging.shutdown() from the watchdog + await asyncio.sleep(0.05) + stop.assert_awaited_once() + assert self.codes == [143] + server_mod._on_signal(signal.SIGTERM) + assert self.codes == [143, 143] + + async def test_signal_handlers_are_registered_in_the_running_loop(self) -> None: + loop = asyncio.get_running_loop() + server_mod._install_signal_handlers() + try: + assert loop.remove_signal_handler(signal.SIGTERM) + assert loop.remove_signal_handler(signal.SIGHUP) + finally: + loop.remove_signal_handler(signal.SIGTERM) + loop.remove_signal_handler(signal.SIGHUP) + + def test_signal_handlers_need_a_running_loop(self) -> None: + server_mod._install_signal_handlers() # no loop: logged at DEBUG, never raises + + +class TestNonAgentClient: + def test_document_digest_and_open_uris_do_not_depend_on_the_client(self, tmp_path: Path) -> None: + srv = server_mod.server + uri = (tmp_path / "A.java").as_uri() + created = srv.protocol._workspace is None + if created: + srv.protocol._workspace = Workspace(root_uri=tmp_path.as_uri(), sync_kind=lsp.TextDocumentSyncKind.Full) + srv._agent_host = False # e.g. an IDE client: no freshness marker, the gate still works + try: + srv.workspace.put_text_document(lsp.TextDocumentItem(uri=uri, language_id="java", version=1, text="x")) + deps = srv._proxy.dependency_modules + assert uri in deps._open_list() + assert deps._doc_digest(uri) == content_digest(b"x") + assert deps._doc_digest((tmp_path / "B.java").as_uri()) is None + finally: + srv.workspace.remove_text_document(uri) + if created: + srv.protocol._workspace = None + + +class TestProxyPlumbing: + def test_data_dir_key_is_tagged_ws2(self) -> None: + uri = "file:///repo/module" + assert _data_dir_hash(uri) == hashlib.sha256(f"ws2|{uri}".encode()).hexdigest()[:12] + assert _data_dir_hash(uri) != hashlib.sha256(uri.encode()).hexdigest()[:12] # v0.14.0's key + + def test_progress_report_provider_is_requested_and_merged(self) -> None: + params = { + "rootUri": "file:///r", + "initializationOptions": {"extendedClientCapabilities": {"classFileContentsSupport": True}}, + } + effective = _build_effective_params(params, None, "file:///r", None) + extended = effective["initializationOptions"]["extendedClientCapabilities"] + assert extended == {"classFileContentsSupport": True, "progressReportProvider": True} + assert params["initializationOptions"]["extendedClientCapabilities"] == {"classFileContentsSupport": True} + bare = _build_effective_params({"initializationOptions": None}, None, "file:///r", None) + assert bare["initializationOptions"]["extendedClientCapabilities"] == {"progressReportProvider": True} + + async def test_response_hook_runs_in_wire_order(self) -> None: + proxy = JdtlsProxy() + order: list[str] = [] + future: asyncio.Future[Any] = asyncio.get_running_loop().create_future() + proxy._pending[5] = future + proxy._response_hooks[5] = lambda: order.append("hook") + future.add_done_callback(lambda _f: order.append("future-callback")) + proxy._dispatch_message({"jsonrpc": "2.0", "id": 5, "result": None}) + order.append("next-message") + await asyncio.sleep(0) + assert order == ["hook", "next-message", "future-callback"] + assert 5 not in proxy._response_hooks + + async def test_request_reports_answered_errors_and_timeouts(self) -> None: + proxy, proc = await _proxy_with(_FAKE_JDTLS) + try: + assert await proxy._request("shutdown", None, timeout=5.0) == (True, None) + assert await proxy._request("other/unanswered", None, timeout=0.2) == (False, None) + # A JSON-RPC error response: not answered, and send_request still returns None. + assert await proxy._request("error/please", None, timeout=5.0) == (False, None) + assert await proxy.send_request("error/please", None, timeout=5.0) is None + assert proxy._pending == {} + finally: + await proxy.stop() + assert proc.returncode is not None + + async def test_refresh_is_not_answered_by_an_error(self) -> None: + proxy, _proc = await _proxy_with(_FAKE_JDTLS) + try: + + async def error_request(method: str, params: Any, timeout: float = 0, on_response: Any = None) -> Any: + return await JdtlsProxy._request(proxy, "error/please", params, timeout, on_response) + + proxy._request = error_request # type: ignore[method-assign] + assert await proxy._refresh_file_diagnostics("file:///x/A.java") is False + finally: + await proxy.stop() + + @pytest.mark.timeout(20) + async def test_request_pending_during_stop_is_not_answered(self) -> None: + proxy, _proc = await _proxy_with(_FAKE_JDTLS) + pending = asyncio.create_task(proxy._request("other/unanswered", None, timeout=30.0)) + await asyncio.sleep(0.1) + await proxy.stop() + assert await asyncio.wait_for(pending, timeout=5.0) == (False, None) + + def test_odd_pom_diagnostic_never_breaks_the_reader(self, monkeypatch: pytest.MonkeyPatch) -> None: + proxy = JdtlsProxy() + + def boom(*_a: Any) -> None: + raise RuntimeError("boom") + + monkeypatch.setattr(proxy.dependency_modules, "note_pom", boom) + monkeypatch.setattr(proxy.dependency_modules, "note_publish", boom) + monkeypatch.setattr(proxy.dependency_modules.idle, "note_progress", boom) + err = {"severity": 1, "message": "Missing artifact g:a:jar"} + for uri in ("file:///r/pom.xml", "file:///r/A.java"): + proxy._handle_notification( + {"method": "textDocument/publishDiagnostics", "params": {"uri": uri, "diagnostics": [err]}} + ) + proxy._handle_notification({"method": "language/progressReport", "params": {"id": "x"}}) + + +def _frame(msg: dict[str, Any]) -> bytes: + body = json.dumps(msg).encode() + return b"Content-Length: %d\r\n\r\n" % len(body) + body + + +async def _read_frame(stdout: asyncio.StreamReader) -> dict[str, Any]: + length = 0 + while True: + line = (await stdout.readline()).strip() + if not line: + break + name, _, value = line.decode().partition(":") + if name.strip().lower() == "content-length": + length = int(value) + parsed: dict[str, Any] = json.loads(await stdout.readexactly(length)) + return parsed + + +class TestServerProcessExit: + """A real ``python -m java_functional_lsp`` process (jdtls off): pygls 2.x awaits the user + SHUTDOWN/EXIT handlers, and EXIT ends the process without hanging on the stdin reader.""" + + async def _server(self) -> asyncio.subprocess.Process: + env = {**os.environ, "JAVA_FUNCTIONAL_LSP_JDTLS": "off"} + proc = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + "java_functional_lsp", + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + env=env, + ) + assert proc.stdin is not None + assert proc.stdout is not None + init = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"processId": None, "capabilities": {}}} + proc.stdin.write(_frame(init)) + await proc.stdin.drain() + while (await asyncio.wait_for(_read_frame(proc.stdout), timeout=15.0)).get("id") != 1: + pass + proc.stdin.write(_frame({"jsonrpc": "2.0", "method": "initialized", "params": {}})) + return proc + + async def _exit(self, proc: asyncio.subprocess.Process) -> int: + assert proc.stdin is not None + proc.stdin.write(_frame({"jsonrpc": "2.0", "method": "exit"})) + await proc.stdin.drain() + try: + return await asyncio.wait_for(proc.wait(), timeout=10.0) + finally: + if proc.returncode is None: + proc.kill() + await proc.wait() + + @pytest.mark.timeout(40) + async def test_shutdown_then_exit_exits_0(self) -> None: + proc = await self._server() + assert proc.stdin is not None + assert proc.stdout is not None + proc.stdin.write(_frame({"jsonrpc": "2.0", "id": 2, "method": "shutdown"})) + await proc.stdin.drain() + while (await asyncio.wait_for(_read_frame(proc.stdout), timeout=15.0)).get("id") != 2: + pass + assert await self._exit(proc) == 0 + + @pytest.mark.timeout(40) + async def test_exit_without_shutdown_exits_1(self) -> None: + proc = await self._server() + assert await self._exit(proc) == 1 diff --git a/uv.lock b/uv.lock index 8b3bbc8..b06ae30 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.14.0" +version = "0.14.1" source = { editable = "." } dependencies = [ { name = "pygls" }, @@ -205,7 +205,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "pygls", specifier = ">=1.3.0" }, + { name = "pygls", specifier = ">=2.0" }, { name = "tree-sitter", specifier = ">=0.23.0" }, { name = "tree-sitter-java", specifier = ">=0.23.0" }, ]