Metadata-Version: 2.1
Name: pemjax
Version: 0.2.4
Summary: PemJaX
Author: THU IGinX
Author-email: TSIginX@gmail.com
License: https://www.apache.org/licenses/LICENSE-2.0
Classifier: Development Status :: 5 - Production/Stable
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Operating System :: Unix
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: find-libpython

# PemJaX

## What is it?

PemJa is an open source cross language call framework based on FFI. It aims to provide a high-performance

framework of calling between different languages.

PemJaX is an extension of PemJa , specifically designed to support WindowsOS. 
This package inherits all the functionalities of PemJa and introduces necessary modifications and
enhancements to ensure seamless operation in WindowsOS.

## UDF timeouts

`TimeoutSafeWrapper(obj, seconds)` retains the thread-based JNI interface, but
**thread cancellation requires explicit cooperation from the UDF**. The watchdog
sets a cancellation request; the UDF calls `check_cancelled()` at safe points.
There is no asynchronous exception injection or automatic tracing: either can
interrupt `finally`, `__enter__`, or module initialization and corrupt shared state.

Put checkpoints inside a resource's `try/finally` or `with` body, between units of
work, and after blocking operations. Do not put them in cleanup or `__enter__`.
Checkpoints inside standard imports defer cancellation until the import completes.
The internal cancellation exception derives from `BaseException`, so ordinary
`except Exception` handlers do not swallow it. A broad handler can still catch it;
the UDF must reach another checkpoint outside that handler to stop.

```python
from pemja.timeout_handler import check_cancelled

def calculate(rows):
    with open("results.txt", "w") as output:
        for row in rows:
            check_cancelled()
            output.write(str(row) + "\n")
```

**Migration:** existing UDFs without checkpoints or a cooperating `interrupt()`
hook can continue after the caller receives a timeout. Add checkpoints for trusted
cooperative UDFs, or select process mode when termination must be enforced.
Blocking native calls can continue until they return, and native code holding the
GIL can also delay the watchdog. Thread mode cannot safely terminate arbitrary code.

A missed deadline always raises `TimeoutError`, even if the UDF catches
cancellation and returns a value. The default cancellation grace period is 0.5
seconds. `interrupt()` runs in a separate tracked callback so it cannot block the
caller indefinitely; it must itself be safe to call concurrently with the UDF.
Both worker and callback must finish before a timed-out object can be reused,
including through a newly created wrapper. Normal concurrent calls retain their
previous behavior. Generators are timed on each `next()` and closed only after
that invocation finishes. Existing trace/profile hooks are left untouched.
The legacy JNI import `timeout_handler` and the public import
`pemja.timeout_handler` share cancellation state, pending tasks and error types.

```python
from pemja.timeout_handler import TimeoutSafeWrapper, TimeoutError, pending_tasks

safe = TimeoutSafeWrapper(udf, default_timeout=5)
try:
    result = safe.calculate(data)
except TimeoutError as error:
    # This is a snapshot at the time the exception was raised, not a promise
    # that an uninterruptible native call has stopped.
    print(error.terminated)
    # error.task.wait(remaining_seconds) can wait for both worker and callback.
    # pending_tasks() exposes timed-out work that still needs cleanup.
```

When hard termination is needed, use an isolated process for importable callables
and pickleable Python arguments/results:

```python
from pemja.timeout_handler import ProcessWithTimeout
from my_udfs import calculate

result = ProcessWithTimeout(
    calculate, args=(data,), python_executable="/path/to/python"
).run_with_timeout(5)
# Also available as timeout(5, mode="process") or
# TimeoutSafeWrapper(obj, 5, mode="process", python_executable=...).
```

Each call gets a fresh interpreter. On timeout the Windows job or POSIX process
group receives termination, and the worker is reaped. Remaining contained children
are also terminated after a successful call. On Windows, user code cannot start
until the actual worker joins the job, including when a virtualenv launcher
creates a separate Python process. Failure to establish containment rejects the call.
Interrupted imports cannot contaminate later calls. Requests and results use
private temporary files, so a large request or a child inheriting output handles
cannot leave the caller blocked on a pipe. At most 64 KiB of each output stream is
forwarded on completion.

Cleanup has a one-second wait budget. OS termination or cleanup failures remain
visible in `pending_tasks()`: a timeout has `terminated=False`, while other paths
raise `ProcessCleanupError`. Use `error.task.close()` to retry and inspect
`error.task.cleanup_error` for details. `terminated` is a snapshot, not a guarantee
that the OS will always be able to kill a process. Filesystem operations and OS
process creation themselves are not guaranteed to finish within a time limit.

Pass the Python executable explicitly from JNI, where `sys.executable` can name
the JVM. Process mode accepts trusted, importable callables and pickleable Python
values. It does not support local functions, live Java objects/callbacks, or
generators; instance mutations stay in the child. Argument serialization and OS
process creation precede the timeout; child initialization, unpickling, imports,
execution and result serialization count toward it. Parent-side result decoding
follows the timeout. Deliberately escaped descendants and external writes are
outside this contract: process mode is not a security sandbox or a transaction.
The private `_async_raise` compatibility helper remains unsafe and is not used by
either managed timeout mode.

Run the standalone regression suite with
`python -B -m unittest discover -s src/test/python -v`. The suite runs without
requiring a JNI build or model downloads.

## Where to get it

Python binary installers for the latest released version are available at the [Python package index](https://pypi.org/project/pemjax)

```bash
pip install pemjax
```

Java Maven Dependency
```
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>pemja</artifactId>
    <version>{version}</version>
</dependency>
```

## Dependencies

- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org)

## Installation from sources

Prerequisites for building PemJa:
* Unix-like environment (we use Linux, Mac OS X), Windows
* Git
* Maven (we recommend version 3.2.5 and require at least 3.1.1)
* Java 8 or 11 (Java 9 or 10 may work) with $JAVA_HOME correctly set
* Python >= 3.8 (we recommend version 3.8, 3.9, 3.10, 3.11)


**NOTE for windows:**
* Microsoft Visual C++ 14.0 or greater is required. Get it with ["Microsoft C++ Build Tools"](https://www.microsoft.com/en-in/download/details.aspx?id=48159)
* The compressed package in folder *dist* must be uncompressed and use the following command to install ```pip install dist/$packageName$```


```
git clone https://github.com/IGinX-THU/pemja.git
cd pemja
mvn clean package -DskipTests
pip install -r dev/dev-requirements.txt
python setup.py sdist
pip install dist/*.tar.gz
```

## Usage

```java
String path = ...;
PythonInterpreterConfig config = PythonInterpreterConfig
    .newBuilder()
    .setPythonExec("python3") // specify python exec, use "python" on Windows
    .addPythonPaths(path) // add path to search path
    .build();

PythonInterpreter interpreter = new PythonInterpreter(config);

// set & get
interpreter.set("a", 12345);
interpreter.get("a"); // Object
interpreter.get("a", Integer.class); // Integer

// exec & eval
interpreter.exec("print(a)");

// invoke functions
interpreter.exec("import str_upper");
String result = interpreter.invoke("str_upper.upper", "abcd");
// Object invoke(String name, Object... args);
// Object invoke(String name, Object[] args, Map<String, Object> kwargs);

// invoke object methods
/*
// invoke.py
class A:
       def __init__(self):
           self._a = 0
   
       def get_value(self):
           return self._a
   
       def add(self, n):
           self._a += n
   
       def add_all(self, *args):
           for item in args:
               self._a += item
               return self._a
   
       def minus(self, n):
           self._a -= n
           return self._a
*/

interpreter.exec("import invoke");
interpreter.exec("a = invoke.A()");
interpreter.invokeMethod("a", "add", 3);
interpreter.invokeMethod("a", "minus", 2);
interpreter.invokeMethod("a", "add_all", 1, 2, 3);


// python callback java methods
/*
// invoke_callback.py
from pemja import findClass

StringBuilder = findClass('java.lang.StringBuilder')
Integer = findClass('java.lang.Integer')

def callback_java():
    sb = StringBuilder()
    sb.append('pemja')
    sb.append('java')
    sb.append('python')
    sb.append(Integer.toHexString(Integer.MAX_VALUE))
    return sb.toString()
*/
interpreter.exec("import call_back")
print(interpreter.invoke("call_back.callback_java"))
```
