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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions docs/modules/ROOT/pages/installation.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,51 @@ WARNING: *One JVM configuration per process.* JVM options are locked after the J

Each Python process starts its own JVM, and each JVM sees the whole container limit. With several Python processes in one container, give each process its own `heap_size`.

[[windows-avx512]]
=== Windows hosts with AVX-512

On some Windows hosts, `start_jvm` adds `-XX:UseAVX=2 -XX:MaxVectorSize=16` to the JVM options and logs one warning that says so. All of these must be true:

* The system is Windows on x86-64.
* The Windows build is 26100 or 26200 (Windows 11 24H2 and 25H2, Windows Server 2025).
* The CPU has AVX-512 (`IsProcessorFeaturePresent(41)` is true).

Every other host starts as before. The `{native-pkg-name}` package needs nothing: it has no HotSpot JVM, so these flags have no meaning there, and its library is compiled ahead of time for the x86-64 baseline (`-march=compatibility`, without the Vector API). We did not test the native package on an affected host or inspect its machine code.

==== Why

On affected hosts, `{jvm-pkg-name}` has crashed with `EXCEPTION_ACCESS_VIOLATION` in vector index code (`VamanaDiversityProvider.isDiverse`), see {repo-url}/issues/352[issue #352]. The likely cause is a Windows bug (JDK-8365196) that loses AVX-512 register state when a thread resumes after a JVM pause. If so, an affected host can also return a wrong similarity score without an error. We have not reproduced the Windows bug on its own.

In a test on `windows-2025` CI runners, one vector index example crashed in 6 of 600 runs without the flags and in 0 of 600 runs with them. The two sets of runs were on different CPUs (Intel Xeon 8573C without the flags, AMD EPYC 9V74 with them), so the test supports the flags and does not prove that they prevent the crash.

==== What it costs

Vector work is slower with the flags. The table gives how much longer the same example took with the flags than without them, on two affected hosts (medians of 15 runs for each setting, taken in turn on one host). We did not measure other workloads.

[cols="2,1,1"]
|===
| Host | `create_index` phase | Whole example

| Intel Xeon 8573C
| 41% longer
| 24% longer

| AMD EPYC 9V74
| 37% longer
| 21% longer

|===

==== Turn it off

Set the environment variable `ARCADEDB_WINDOWS_AVX512_WORKAROUND=0` (or `false`, `no`, `off`) before the JVM starts. A `-XX:UseAVX` or `-XX:MaxVectorSize` of your own also wins: when either one is in `jvm_args`, `ARCADEDB_JVM_ARGS`, `JAVA_TOOL_OPTIONS` or `_JAVA_OPTIONS`, the package adds neither flag.

Turn it off only when you know that your Windows build has the fix. The author of a https://github.com/Auties00/jdk-c2-avx512-windows-repro[public reproducer] reports that Windows 11 24H2 and 25H2 are fixed from kernel 26100.7920, and that no Windows Server 2025 kernel with the fix exists yet. We have not verified either statement, so the default covers every revision of the two builds.

==== When it will be removed

We will remove the default, or limit it to the revisions without the fix, when a Windows update that fixes the bug is confirmed: the CI test of issue #352 then runs without the flags on a fixed host and does not crash.

[[jvm-cds]]
=== Class-data sharing

Expand Down
6 changes: 5 additions & 1 deletion docs/modules/ROOT/pages/upgrading.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ifdef::env-github[]
:jvm-pkg-name: arcadedb-jvm
endif::[]

// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454, #445 and #504. Pinned by tests/test_run_in_transaction_partial_commit.py, tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py, tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py.
// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454, #445, #504 and #352. Pinned by tests/test_jvm_windows_avx512.py, tests/test_run_in_transaction_partial_commit.py,tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py, tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py.

Read this page before you move a program from 26.11.1, or from one of its post releases, to 26.12.1. It covers both packages, `{native-pkg-name}` and `{jvm-pkg-name}`. The changes of the engine itself are listed with the https://github.com/ArcadeData/arcadedb/releases[releases of ArcadeDB].

Expand Down Expand Up @@ -58,6 +58,10 @@ See xref:how-to/errors.adoc#partial-commit[A block that already committed part o

Before, a relative database path, or a relative `root_path` of `ArcadeDBServer`, did not name one directory once your program had changed its directory with `os.chdir`, because the engine resolved a part of the path against the directory in which it had started. For example, `database_exists` could answer `False` for a database that you had just created, and a second database with the same relative path in another directory was refused as already in use. Now both packages take a relative path from the current directory at the time of the call. `db.get_database_path()` and the error messages show the absolute path, also when you passed a relative one. See xref:how-to/databases-and-queries.adoc[Databases and queries].

=== `{jvm-pkg-name}` uses narrower vectors on some Windows hosts

On Windows on x86-64 with AVX-512, build 26100 or 26200 (Windows 11 24H2 and 25H2, Windows Server 2025), the JVM now starts with `-XX:UseAVX=2 -XX:MaxVectorSize=16` and logs one warning. This works around a likely Windows bug that has crashed the JVM in vector index code. On the two affected hosts that we measured, `create_index` took 37 to 41% longer and a whole vector index example 21 to 24% longer. `ARCADEDB_WINDOWS_AVX512_WORKAROUND=0` turns it off. `{native-pkg-name}` is not changed. See xref:installation.adoc#windows-avx512[Windows hosts with AVX-512].

=== Engine 26.12.1

The engine that the 26.12.1 packages carry changes some behaviour that the other pages describe:
Expand Down
77 changes: 76 additions & 1 deletion src/arcadedb/jvm.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@
_JVM_INTERRUPT = None # the `interrupt` the running JVM was started with
_LOG_DIR_USED = None # the log directory the running JVM was started with

# Windows on x86-64 with AVX-512 on the affected build line (ArcadeData/arcadedb-python#352). The likely cause (JDK-8365196):
# Windows loses AVX-512 register state when a thread resumes after a JVM pause, so C2 code reads a zeroed reference and the
# process dies in jvector's VamanaDiversityProvider.isDiverse. These two flags keep HotSpot off the state that is lost.
# Remove this default when a Windows update that fixes the bug is confirmed.
WINDOWS_AVX512_ENV = "ARCADEDB_WINDOWS_AVX512_WORKAROUND"
_WINDOWS_AVX512_FLAGS = ("-XX:UseAVX=2", "-XX:MaxVectorSize=16")
# 26100 is Windows 11 24H2 and Windows Server 2025. Windows 11 25H2 is an enablement package on the same files that
# reports build 26200.
_WINDOWS_AVX512_BUILDS = (26100, 26200)
_PF_AVX512F_INSTRUCTIONS_AVAILABLE = 41 # argument of IsProcessorFeaturePresent

_ENGINE_LOG_RESOURCE = "arcadedb-log.properties"


Expand Down Expand Up @@ -455,6 +466,16 @@ def start_jvm(
Path for JVM crash logs (default: ``hs_err_pid%p.log`` in the log
directory above). ``-XX:ErrorFile=`` in ``jvm_args`` wins over it.

ARCADEDB_WINDOWS_AVX512_WORKAROUND (optional)
On Windows on x86-64 with AVX-512, build 26100 or 26200 (Windows 11
24H2 and 25H2, Windows Server 2025), the JVM starts with
``-XX:UseAVX=2 -XX:MaxVectorSize=16`` and one warning says so. It
mitigates a JVM crash in vector index code; vector index builds are
slower. ``0`` (or ``false``, ``no``, ``off``) turns the default off.
Neither flag is added when ``-XX:UseAVX`` or ``-XX:MaxVectorSize`` is
in ``jvm_args``, ``ARCADEDB_JVM_ARGS``, ``JAVA_TOOL_OPTIONS`` or
``_JAVA_OPTIONS``.

Note: JVM options must be set BEFORE the first JVM start, as the JVM
can only be configured once per Python process.
"""
Expand Down Expand Up @@ -520,6 +541,7 @@ def start_jvm(
jvm_args=jvm_args,
common_pool_parallelism=common_pool_parallelism,
log_dir=log_dir,
announce=True,
)
_check_initial_heap(jvm_args)
aot_flags = _aot_flags(aot, jvm_args, classpath)
Expand Down Expand Up @@ -795,14 +817,55 @@ def _prepare_log_dir(log_dir: Path, jar_files: Iterable[str]) -> Path:
return log_dir


def _windows_avx512_affected() -> bool:
"""Whether this host is Windows on x86-64, on an affected build, with a CPU that has AVX-512."""
if sys.platform != "win32" or platform.machine().lower() not in ("amd64", "x86_64"):
return False
try:
if sys.getwindowsversion().build not in _WINDOWS_AVX512_BUILDS:
return False
import ctypes

present = ctypes.windll.kernel32.IsProcessorFeaturePresent
return bool(present(_PF_AVX512F_INSTRUCTIONS_AVAILABLE))
except (AttributeError, OSError) as exc: # never fail a start over this check
_LOGGER.debug("AVX-512 check skipped: %s: %s", type(exc).__name__, exc)
return False


def _windows_avx512_flags(args: list[str]) -> list[str]:
"""The AVX-512 workaround flags to add to ``args``.

None when ``ARCADEDB_WINDOWS_AVX512_WORKAROUND`` turns the default off, when the user chose ``-XX:UseAVX`` or
``-XX:MaxVectorSize`` (in ``args``, or in a variable that the JVM reads by itself), or when the host is not affected.
"""
value = os.environ.get(WINDOWS_AVX512_ENV, "").strip().lower()
if value in ("0", "false", "no", "off"):
return []
chosen = [
*args,
os.environ.get("JAVA_TOOL_OPTIONS", ""),
os.environ.get("_JAVA_OPTIONS", ""),
]
if any("-XX:UseAVX" in a or "-XX:MaxVectorSize" in a for a in chosen):
return []
if not _windows_avx512_affected():
return []
return list(_WINDOWS_AVX512_FLAGS)


def _build_jvm_args(
heap_size: Optional[str],
disable_xml_limits: bool,
jvm_args: Optional[Union[Iterable[str], str]],
common_pool_parallelism: Optional[int] = None,
log_dir: Optional[Path] = None,
announce: bool = False,
) -> list[str]:
"""Helper to construct JVM arguments from params, env vars, and defaults."""
"""Helper to construct JVM arguments from params, env vars, and defaults.

``announce`` is set for the arguments that really start the JVM: a default that changes performance is then logged.
"""
if common_pool_parallelism is not None and common_pool_parallelism < 1:
raise ArcadeDBError("common_pool_parallelism must be >= 1")

Expand Down Expand Up @@ -893,6 +956,18 @@ def _build_jvm_args(
if not any("UseCompactObjectHeaders" in arg for arg in merged_args):
merged_args.append("-XX:+UseCompactObjectHeaders")

# Windows hosts with AVX-512 only (see WINDOWS_AVX512_ENV above).
avx512_flags = _windows_avx512_flags(merged_args)
if avx512_flags:
merged_args.extend(avx512_flags)
if announce:
_LOGGER.warning(
"Windows with AVX-512: starting the JVM with %s to avoid a known crash (ArcadeData/arcadedb-python#352); "
"vector index builds are slower. Set %s=0 to turn this off.",
" ".join(avx512_flags),
WINDOWS_AVX512_ENV,
)

# Heap handling (single place):
# - An explicit heap_size wins over every -Xmx from the environment or jvm_args.
# - With heap_size None, a user's -Xmx (deduped to the largest) or other
Expand Down
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
NATIVE_NOT_APPLICABLE = {
"test_jvm.py": "JVM start-up and settings",
"test_jvm_args.py": "JVM arguments",
"test_jvm_windows_avx512.py": "JVM arguments of Windows hosts with AVX-512",
"test_jar_provenance.py": "jar fingerprint of the JVM wheel",
"test_jar_closure.py": "jar closure of the JVM wheel",
"test_java_package_shadowing.py": "JPype package import hooks",
Expand Down
173 changes: 173 additions & 0 deletions tests/test_jvm_windows_avx512.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""The Windows AVX-512 default of the JVM wheel (ArcadeData/arcadedb-python#352).

The operating system, the architecture, the Windows build and the CPU check are faked, so every test runs on every platform.
No JVM is started.
"""

import ctypes
import logging
import platform
import sys
from types import SimpleNamespace

import pytest

from arcadedb import jvm
from arcadedb.exceptions import ArcadeDBError

FLAGS = ["-XX:UseAVX=2", "-XX:MaxVectorSize=16"]
ENV = "ARCADEDB_WINDOWS_AVX512_WORKAROUND"


@pytest.fixture
def fake_host(monkeypatch):
"""Clear the variables that count, then return a function that fakes a host (an affected one by default)."""
for name in (
ENV,
"ARCADEDB_JVM_ARGS",
"ARCADEDB_AOT",
"JAVA_TOOL_OPTIONS",
"_JAVA_OPTIONS",
):
monkeypatch.delenv(name, raising=False)

def fake(system="win32", machine="AMD64", build=26100, avx512=True):
kernel32 = SimpleNamespace(
IsProcessorFeaturePresent=lambda feature: int(avx512 and feature == 41)
)
monkeypatch.setattr(sys, "platform", system)
monkeypatch.setattr(platform, "machine", lambda: machine)
monkeypatch.setattr(
sys,
"getwindowsversion",
lambda: SimpleNamespace(build=build),
raising=False,
)
monkeypatch.setattr(
ctypes, "windll", SimpleNamespace(kernel32=kernel32), raising=False
)

return fake


def _args(log_dir, jvm_args=None, announce=False):
return jvm._build_jvm_args(
heap_size=None,
disable_xml_limits=False,
jvm_args=jvm_args,
log_dir=log_dir,
announce=announce,
)


def _vector_flags(args):
return [a for a in args if "UseAVX" in a or "MaxVectorSize" in a]


def _warnings(caplog):
return [r.getMessage() for r in caplog.records if r.name == "arcadedb.jvm"]


@pytest.mark.parametrize("build", [26100, 26200])
@pytest.mark.parametrize("machine", ["AMD64", "x86_64"])
def test_affected_host_gets_both_flags(fake_host, tmp_path, build, machine):
fake_host(build=build, machine=machine)
assert _vector_flags(_args(tmp_path)) == FLAGS


@pytest.mark.parametrize(
"host",
[
{"system": "linux", "machine": "x86_64"},
{"system": "darwin", "machine": "x86_64"},
{"machine": "ARM64"},
{"build": 20348}, # Windows Server 2022
{"build": 22631}, # Windows 11 23H2
{"build": 28000}, # Windows 11 26H1
{"avx512": False},
],
ids=["linux", "macos", "arm64", "server2022", "win11-23h2", "26h1", "no-avx512"],
)
def test_other_hosts_get_neither_flag(fake_host, tmp_path, caplog, host):
fake_host(**host)
with caplog.at_level(logging.DEBUG, logger="arcadedb.jvm"):
assert _vector_flags(_args(tmp_path, announce=True)) == []
assert _warnings(caplog) == []


@pytest.mark.parametrize(
"variable", [None, "ARCADEDB_JVM_ARGS", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS"]
)
@pytest.mark.parametrize("flag", ["-XX:UseAVX=3", "-XX:MaxVectorSize=64"])
def test_a_flag_of_the_user_turns_the_default_off(
fake_host, monkeypatch, tmp_path, variable, flag
):
fake_host()
if variable is None: # jvm_args
args = _args(tmp_path, jvm_args=[flag])
else:
monkeypatch.setenv(variable, f"-Dfoo=bar {flag}")
args = _args(tmp_path)
# Only what the user put on the command line: JAVA_TOOL_OPTIONS and _JAVA_OPTIONS are read by the JVM itself.
on_command_line = variable in (None, "ARCADEDB_JVM_ARGS")
assert _vector_flags(args) == ([flag] if on_command_line else [])


@pytest.mark.parametrize("value", ["0", "false", "No", " off "])
def test_environment_variable_turns_the_default_off(
fake_host, monkeypatch, tmp_path, value
):
fake_host()
monkeypatch.setenv(ENV, value)
assert _vector_flags(_args(tmp_path)) == []


@pytest.mark.parametrize("value", ["", "1", "true"])
def test_other_values_keep_the_default(fake_host, monkeypatch, tmp_path, value):
fake_host()
monkeypatch.setenv(ENV, value)
assert _vector_flags(_args(tmp_path)) == FLAGS


def test_a_check_that_fails_adds_nothing(fake_host, monkeypatch, tmp_path):
fake_host()

def broken(feature):
raise OSError("no kernel32")

monkeypatch.setattr(ctypes.windll.kernel32, "IsProcessorFeaturePresent", broken)
assert _vector_flags(_args(tmp_path)) == []


def test_arguments_built_for_a_comparison_are_not_logged(fake_host, tmp_path, caplog):
"""A second start_jvm() call builds the arguments again to compare them: that is not a start."""
fake_host()
assert _vector_flags(_args(tmp_path)) == FLAGS
assert _warnings(caplog) == []


def test_start_jvm_passes_the_flags_and_logs_one_line(
fake_host, monkeypatch, tmp_path, caplog
):
fake_host()
(tmp_path / "engine.jar").write_bytes(b"")
passed = []

def stop_here(jvm_path, *args, **kwargs):
passed.extend(args)
raise RuntimeError("no JVM in this test")

monkeypatch.setattr(jvm.jpype, "isJVMStarted", lambda: False)
monkeypatch.setattr(jvm.jpype, "startJVM", stop_here)
monkeypatch.setattr(jvm, "get_jar_path", lambda: str(tmp_path))
monkeypatch.setattr(jvm, "get_bundled_jre_lib_path", lambda: "libjvm")
monkeypatch.setattr(jvm, "_prepare_log_dir", lambda log_dir, jars: tmp_path)

with pytest.raises(ArcadeDBError, match="no JVM in this test"):
jvm.start_jvm()

assert _vector_flags(passed) == FLAGS
(line,) = _warnings(caplog)
assert " ".join(FLAGS) in line
assert f"{ENV}=0" in line
assert "\n" not in line
Loading