Skip to content
This repository was archived by the owner on Nov 21, 2026. It is now read-only.
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
2 changes: 1 addition & 1 deletion bindings/python/docs/api/jvm.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ start_jvm(
Pass `False` to keep the JDK defaults.
- `jvm_args` (`Optional[Iterable[str] | str]`, default `None`): Additional JVM flags as a string or iterable
- `common_pool_parallelism` (`Optional[int]`, default `None`): Explicit cap for `ForkJoinPool.common.parallelism`; a value below 1 raises `ArcadeDBError`
- `interrupt` (`Optional[bool]`, default `None`, meaning `False`): What Ctrl-C does. `False` leaves SIGINT to Python, so a `KeyboardInterrupt` is raised and `finally` blocks, `atexit` hooks, and the rollback of a `with db.transaction():` run. A Java call in progress, such as a slow query, is not interrupted: the `KeyboardInterrupt` arrives when it returns (about 9 s after Ctrl-C for a 10 s query, measured), and `kill -TERM` from another terminal still ends the process at once. A Java call that waits in an interruptible way (`Thread.sleep`, `Object.wait`, `wait_completion()` on an async executor) is woken by Ctrl-C, and JPype 1.7.1 can then raise `java.lang.InterruptedException` or `RuntimeError` and deliver the `KeyboardInterrupt` late; see [Known Engine Issues](../guide/known-issues.md) for the workaround. `True` is JPype's script default: the JVM handles SIGINT and ends the whole process with exit status 130, without Python cleanup. It can be given only to the first `start_jvm()`; a different value afterwards raises `ArcadeDBError`
- `interrupt` (`Optional[bool]`, default `None`, meaning `False`): What Ctrl-C does. `False` leaves SIGINT to Python, so a `KeyboardInterrupt` is raised and `finally` blocks, `atexit` hooks, and the rollback of a `with db.transaction():` run. A Java call in progress, such as a slow query, is not interrupted: the `KeyboardInterrupt` arrives when it returns (about 9 s after Ctrl-C for a 10 s query, measured). After the JVM starts, the bindings give SIGINT and SIGTERM back to Python, so a long blocking Python call (`time.sleep()`, `Lock.acquire()`, `queue.get()`) is interrupted at once and `kill -TERM` ends the process with status -15 and no Python cleanup; see [Known Engine Issues](../guide/known-issues.md). `True` is JPype's script default: the JVM handles SIGINT and ends the whole process with exit status 130, without Python cleanup. It can be given only to the first `start_jvm()`; a different value afterwards raises `ArcadeDBError`

**Raises:**

Expand Down
2 changes: 1 addition & 1 deletion bindings/python/docs/development/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ asserts, so the list below stops at the file.
| `test_log_dir.py` | The engine log, the crash log and `logging.properties` go to a per-user directory and never the working directory (a child JVM started from an empty read-only directory), `ARCADEDB_LOG_DIR` and `jvm_args` overrides, the temp-directory fallback, and the directory per platform |
| `test_xml_limits.py` | `disable_xml_limits` defaults to false, an import that hits a JDK entity limit names the option, and `import_documents(disable_xml_limits=True)` lifts the limits for that call only and restores them |
| `test_jvm_payload.py` | A static check that no Python list crosses into the JVM |
| `test_sigint.py` | Ctrl-C raises `KeyboardInterrupt` and runs cleanup once the JVM is started; `interrupt=True` keeps JPype's default (not collected on Windows) |
| `test_sigint.py` | Ctrl-C raises `KeyboardInterrupt` and runs cleanup once the JVM is started, also out of one long `time.sleep()` with a transaction open; SIGTERM ends the process with -15; `interrupt=True` keeps JPype's default (not collected on Windows) |
| `test_bridge_fixes.py` | Two fixes in the Java bridge: nested values read back as Python in the same transaction, and a date written as midnight UTC in any JVM time zone |
| `test_java_package_shadowing.py` | A folder named `java/` or `com/` must not change what a query returns |
| `test_runtime_cache.py` | The dev-mode runtime cache follows the wheel it was extracted from |
Expand Down
68 changes: 11 additions & 57 deletions bindings/python/docs/guide/known-issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,75 +42,29 @@ passing on every engine. Upstream's snapshot image that CI builds the wheel from
the engine from before the fix, with the same version string, so the test file probes the
behavior and asserts the old answer on such an engine.

## Ctrl-C during an interruptible Java wait can raise `InterruptedException`, not `KeyboardInterrupt`
## Ctrl-C and `kill -TERM` with the JVM started (fixed in the next release of these bindings)

JPype 1.7.1, the newest release and the one a fresh install gets (the package declares
`jpype1>=1.5.0`); measured through the bindings with a 26.10.1 snapshot of the engine, and again
on JPype master (874a197, 2026-10-06), where it is unchanged.
Open. This is a race in JPype, not in ArcadeDB; it is reported as
[jpype-project/jpype#1496](https://github.com/jpype-project/jpype/issues/1496).

With the default `interrupt=False`, JPype handles SIGINT in Java. Its handler first interrupts
the main thread with `Thread.interrupt()` and only then tells Python that Ctrl-C arrived. A
Java call that waits in an interruptible way wakes up between the two steps, and JPype finds
no Python interrupt yet. `Thread.sleep()` and `Object.wait()` do, and so does the engine's
`wait_completion()` on an async executor (its Java source handles `InterruptedException`;
this one was not measured). Instead of a `KeyboardInterrupt` from the call you see one of:

- `java.lang.InterruptedException` raised from the call, and the `KeyboardInterrupt` a
moment later in whatever statement runs next: a `finally` block, an `atexit` hook such as
the bindings' own close of open databases. The program ends with exit status 1 or by
SIGINT, with a traceback that names `InterruptedException`.
- `RuntimeError: Fatal error occurred`, with `Fatal error in exception handling` and
`Handling: java.lang.InterruptedException: sleep interrupted` on stderr. `finally` blocks
and `atexit` hooks still ran. A statement that calls a Python function (`register_function()`)
maps this `RuntimeError` to the `KeyboardInterrupt`, chained from an `ArcadeDBError`, because
Ctrl-C is the only thing that causes it there.

SIGINT at a random moment of a 1.5 s `Thread.sleep()` on two pinned cores gave one of these in
14 of 400 interrupts (3.5%) with the cores idle, and in 26 of 200 (13%) with two busy loops
sharing the two cores. `Object.wait()` with the busy loops: 42 of 200 (21%). A Python loop,
and a Java call that ignores `Thread.interrupt()` (a socket `accept()` with a timeout, which
returns with its `KeyboardInterrupt` when it times out), had no failure in 150 interrupts each
with the busy loops.

Wait in Python instead, so the main thread is never inside the Java wait: run the call in a
daemon thread and poll it with `join`. Ctrl-C then raises `KeyboardInterrupt` in the main
thread within the poll interval, and 150 of 150 interrupts with the busy loops did, with a
`Thread.sleep()` in the worker:
Measured on release 26.10.2.post1 with JPype 1.7.1 (the newest, and the one a fresh install gets; the package declares `jpype1>=1.5.0`). JPype's two bugs behind it, [jpype-project/jpype#1496](https://github.com/jpype-project/jpype/issues/1496) and [jpype-project/jpype#1497](https://github.com/jpype-project/jpype/issues/1497), are still open. The bindings no longer depend on JPype's handlers: after the JVM starts, `start_jvm()` gives SIGINT and SIGTERM back to Python.

```python
import threading
With the default `interrupt=False`, JPype installs its own Java handlers for SIGINT and SIGTERM, which replace Python's at the operating-system level. Three things went wrong on the JVM wheel (the native wheel has no such handler):

worker = threading.Thread(target=async_exec.wait_completion, daemon=True)
worker.start()
while worker.is_alive():
worker.join(0.1) # Ctrl-C raises KeyboardInterrupt here, never inside the Java wait
```
- A script blocked in one long call in the main thread (`time.sleep(60)`, `Lock.acquire()`, `queue.get()`, `Thread.join()`) did not stop on Ctrl-C, with or without an open transaction. The signal reaches the JVM, which tells Python from its own signal thread. That sets the "interrupt pending" flag but wakes nobody, so the `KeyboardInterrupt` waited until the call ended, and it arrived at once if any other signal woke the thread. A busy Python loop did not stop either.
- A Java call that waits in an interruptible way (`Thread.sleep()`, `Object.wait()`) could raise `java.lang.InterruptedException` or `RuntimeError: Fatal error occurred` instead of `KeyboardInterrupt` (JPype interrupts the Java thread before it tells Python).
- `kill -TERM` with no Python handler for SIGTERM, the normal state of a script, crashed the process in `PyErr_SetInterruptEx` (exit status -6).

The worker keeps waiting after Ctrl-C and ends with the process. A Python wait loop such as
`while True: time.sleep(1)`, as in the server examples, is not affected.
Now SIGINT and SIGTERM behave as in a script without a JVM. Ctrl-C raises `KeyboardInterrupt` in the main thread at once, and the rollback of a `with db.transaction():` block, `finally` blocks, and `atexit` hooks run. A Java call in progress is not interrupted: the `KeyboardInterrupt` arrives when it returns. `kill -TERM` ends the process with status -15 and runs no Python cleanup, and the next open of the database replays the log (`was not closed properly last time`); committed data is intact. To clean up on SIGTERM, register a handler yourself, for example `signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))`.

The same handler has a second problem with `interrupt=False` when Python has no handler of its
own for SIGTERM, which is the normal state of a script: `kill -TERM` crashes the process with a
SIGSEGV in `PyErr_SetInterruptEx` (exit status -6 and an `hs_err_pid*.log`) instead of stopping
it ([jpype-project/jpype#1497](https://github.com/jpype-project/jpype/issues/1497); measured on
JPype 1.7.1 and master, Temurin 21 and 25, 10 of 10 attempts each, and through the bindings, 3
of 3). Register a handler after the first database is opened, which is after the JVM has
started; the process then stops at once, 3 of 3 through the bindings. A handler registered
before the JVM starts also avoids the crash, but runs only when the main thread next executes
Python code, so a blocking call such as `time.sleep(30)` delays it until the call returns:
On a release without the fix, restore the handlers yourself right after the JVM starts (the first `create_database()` or `open_database()` call), from the main thread:

```python
import signal
import sys

db = arcadedb.create_database("./mydb")
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(signal.SIGTERM, signal.SIG_DFL)
```

Tests: `tests/test_sigint.py` covers a Python loop and a Java call that Ctrl-C cannot wake.
It has no test of the waits above, because the failure is random (humemai/arcadedb-embedded-python#179).
Tests: `tests/test_sigint.py` covers a Python loop, one long `time.sleep()` with a transaction open, a Java call that Ctrl-C cannot wake, and SIGTERM.


## `Result.get()` keeps a Python object for every number that comes back from Java
Expand Down
48 changes: 40 additions & 8 deletions bindings/python/src/arcadedb_embedded/jvm.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import re
import shlex
import shutil
import signal
import sys
import tempfile
import threading
Expand Down Expand Up @@ -362,14 +363,12 @@ def start_jvm(
What Ctrl-C (SIGINT) does. The default, False, leaves it to Python: a
KeyboardInterrupt is raised, so ``finally`` blocks, ``atexit`` hooks and
the rollback of a ``with db.transaction():`` run. A Java call in
progress (a slow query) is not interrupted: the KeyboardInterrupt
arrives when it returns (``kill -TERM`` from another terminal still
ends the process at once, through the JVM's shutdown hooks). A Java call
that waits in an interruptible way (``Thread.sleep``, ``Object.wait``,
the engine's async ``wait_completion()``) is woken by Ctrl-C, and JPype
1.7.1 can then raise ``java.lang.InterruptedException`` or
``RuntimeError`` and deliver the ``KeyboardInterrupt`` late; "Known
Engine Issues" in the documentation has the workaround.
progress (a slow query, a wait in the engine) is not interrupted: the
KeyboardInterrupt arrives when it returns. SIGINT and SIGTERM are the
process's own again after the JVM starts, as in a script without a
JVM: a long blocking Python call (``time.sleep``, ``Lock.acquire``,
``queue.get``) is interrupted at once, and ``kill -TERM`` ends the
process with status -15 without running Python cleanup.
Pass True for JPype's script default, where the JVM handles SIGINT and
ends the whole process at once with exit status 130, with no Python
cleanup.
Expand Down Expand Up @@ -504,6 +503,9 @@ def start_jvm(
except Exception as e:
raise ArcadeDBError(f"Failed to start JVM: {e}") from e

if not _JVM_INTERRUPT:
_restore_python_signal_handlers()

# Registered AFTER JPype's own atexit hook so it runs BEFORE it (atexit
# is LIFO): close any Database left open. Engine >= 850ce7c37 (#5418)
# also daemonizes its background threads and installs its own JVM
Expand All @@ -525,6 +527,36 @@ def start_jvm(
faulthandler.disable()


def _restore_python_signal_handlers() -> None:
"""Give SIGINT and SIGTERM back to Python after JPype took them (``interrupt=False``).

JPype installs ``sun.misc.Signal`` handlers for both signals while it starts the JVM, which
replaces the handlers Python had registered with the operating system. A SIGINT is then
delivered to the JVM, which tells Python from its signal-dispatcher thread
(``PyErr_SetInterruptEx``). That sets the "interrupt pending" flag but wakes nobody: the main
thread, blocked in a long ``time.sleep()``, ``Lock.acquire()``, ``queue.get()`` or
``Thread.join()``, got EINTR before the flag was set, went back to sleep, and raises the
``KeyboardInterrupt`` only when the call ends (observed: a process with an open transaction
that did not exit for the whole 30 s or 120 s of the sleep; 10 of 10 on the JVM wheel, never
on the native one). A SIGTERM with no Python handler crashed the process with exit status -6
(jpype-project/jpype#1497). The same JPype handler also interrupts the Java thread first,
which is the race of jpype-project/jpype#1496.

Registering the handler Python already has again puts the operating-system disposition back
(``signal.signal`` calls ``sigaction``), so SIGINT raises ``KeyboardInterrupt`` in the main
thread exactly as in a process without a JVM and SIGTERM ends the process with status -15.
A Java call in progress is then not interrupted by Ctrl-C: the ``KeyboardInterrupt`` arrives
when it returns. Only the main thread may do this; elsewhere it is skipped.
"""
for signum in (signal.SIGINT, signal.SIGTERM):
try:
current = signal.getsignal(signum)
if current is not None: # None: set by C code, nothing Python can restore
signal.signal(signum, current)
except (ValueError, OSError): # not the main thread / not settable
_LOGGER.debug("could not restore the Python handler for signal %s", signum)


def _close_active_databases():
"""Close every Database still open so JVM shutdown cannot block."""
if not jpype.isJVMStarted():
Expand Down
46 changes: 43 additions & 3 deletions bindings/python/tests/test_sigint.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@
server = jpype.JClass("java.net.ServerSocket")(0, 1, loopback)
server.setSoTimeout(4000)
server.accept()
elif sys.argv[1] == "sleep":
# ONE long blocking call, not a loop of short ones: the main thread is
# in a single clock_nanosleep() and only a signal delivered to it wakes it.
time.sleep(60)
else:
while True:
time.sleep(0.05)
Expand All @@ -60,7 +64,10 @@
"""


def _run_sigint(tmp_path, mode, interrupt):
def _run_signal(tmp_path, mode, interrupt, sig=signal.SIGINT, bound=60):
"""Send ``sig`` to a child with an open transaction; fail if it has not exited within
``bound`` seconds (a KeyboardInterrupt stuck behind a blocking call looks like this).
"""
proc = subprocess.Popen( # nosec B603 - fixed argv, no shell, test-owned
[sys.executable, "-c", _CHILD, mode, str(tmp_path / "db"), interrupt],
stdout=subprocess.PIPE,
Expand All @@ -73,11 +80,20 @@ def _run_sigint(tmp_path, mode, interrupt):
)
assert "READY" in proc.stdout.readline()
time.sleep(1.0)
proc.send_signal(signal.SIGINT)
out, _ = proc.communicate(timeout=60)
proc.send_signal(sig)
try:
out, _ = proc.communicate(timeout=bound)
except subprocess.TimeoutExpired:
proc.kill() # our own child
proc.communicate()
pytest.fail(f"child still running {bound} s after signal {int(sig)}")
return proc.returncode, out


def _run_sigint(tmp_path, mode, interrupt):
return _run_signal(tmp_path, mode, interrupt)


@pytest.mark.parametrize("mode", ["python", "java"])
def test_ctrl_c_raises_keyboard_interrupt_and_runs_cleanup(tmp_path, mode):
"""Python loop and a blocked Java call that Ctrl-C cannot wake (the
Expand All @@ -91,6 +107,30 @@ def test_ctrl_c_raises_keyboard_interrupt_and_runs_cleanup(tmp_path, mode):
assert "ATEXIT" in lines


def test_ctrl_c_wakes_a_long_blocking_call_with_a_transaction_open(tmp_path):
"""A single time.sleep(60) in the main thread inside a transaction: Ctrl-C ends it at once
(KeyboardInterrupt, rollback, cleanup, exit 0). With JPype's own SIGINT handler left in
place the KeyboardInterrupt was pending but nobody woke the sleeping thread, so the
process did not exit for the 60 s (10 of 10 runs on the JVM wheel; never on the native).
"""
t0 = time.monotonic()
code, out = _run_signal(tmp_path, "sleep", "0", bound=20)
assert time.monotonic() - t0 < 25
assert code == 0, out
lines = out.split()
assert "KEYBOARD_INTERRUPT" in lines and "FINALLY" in lines
assert lines[lines.index("COUNT") + 1] == "0"
assert "ATEXIT" in lines


def test_sigterm_ends_the_process_with_status_minus_15(tmp_path):
"""No Python handler for SIGTERM, as in a plain script: the process dies by SIGTERM, as
without a JVM. JPype's handler used to crash it with SIGABRT (exit -6, jpype#1497).
"""
code, _ = _run_signal(tmp_path, "sleep", "0", sig=signal.SIGTERM, bound=20)
assert code == -signal.SIGTERM


def test_interrupt_true_keeps_the_jvm_handling_sigint(tmp_path):
"""The opt-back: the JVM ends the process with 130 and Python never sees
the interrupt."""
Expand Down
Loading