Skip to content

Latest commit

 

History

History
168 lines (135 loc) · 8.21 KB

embedding.md

File metadata and controls

168 lines (135 loc) · 8.21 KB

Embed CPython in a JVM process

Use the Java Interpreter API or the Clojure com.blockether.vis-python-runtime namespace. Both use the same native runtime. The Clojure functions translate arguments and return values.

Initialize once, close sessions when finished

  1. Set the unpacked archive directory with Native.use(path) or use-library!. If you omit the path, the loader uses VIS_PYTHON_NATIVE_PATH. If that variable is unset or blank, the loader looks for a prebuild in a classpath directory. The loader rejects an invalid path and does not download the library.
  2. Initialize the interpreter once per process. It stays loaded for the process lifetime. Session names select separate globals, not separate interpreters.
  3. Apply process policy before installing runtime modules or executing guest code.
  4. Call installRuntime(session) / install-runtime! for block execution and host tools. If you configure a package directory, the runtime processes its .pth files on the first refresh. It processes them again when the .pth files or tracked editable-install metadata change. These files can run code. Install only packages you trust.
  5. Call closeSession(session) / close-session! to drop the session and its owned modules. This releases globals and handles with no other references. The library stays loaded and shared imports remain.

Initialization accepts source paths, a Python home, a bytecode cache prefix, and a shared package directory. In Java, pass Interpreter.DEFAULT for the default location. Pass null to leave the location unset. In Clojure, omit the key for the default location. Supply nil to leave the location unset. If Python home is unset, CPython uses its normal search for the standard library. This setting does not make the deployment self-contained. If the cache prefix is unset, CPython uses its normal cache locations. An unset package directory adds no shared package path.

Choose an execution API

Java Clojure Input Result
Interpreter.eval eval-str One Python expression Python str(result) as JVM text
Interpreter.exec exec! Python statements No return value; changes session globals
Interpreter.run run Statements and optional trailing expression Result encoded as JSON text
Interpreter.runBlock run-block A runtime block, including supported await calls JSON with stdout and error

eval does not deserialize Python objects into Java objects. Use run and your JSON reader when you need numbers, lists, or maps.

runBlock discards the value of a trailing expression. The JSON stdout field contains captured text from Python stdout and, by default, Python stderr. The error field is null on success or a Python error string on failure. Text captured before a failure stays in stdout.

Expression and statement failures throw VisPythonException. Blocks return Python failures in the JSON error field. Loading or bridge failures can throw VisPythonException. Read diagnostic fields with exception.data() in Java or (.data exception) in Clojure. The fields depend on the failure. Examples include symbol, status, platform, and path.

For module-style code that must own an asyncio event loop, do not call asyncio.run inside an already asynchronous block. The synchronous exec path runs ordinary Python statements; block execution already has its own async runner.

Expose a host callback

One callback is bound for the whole interpreter. Authorize each request against the callback's caller session, not a session field supplied in the JSON payload. An empty caller identifies no session. Reject the request.

Interpreter.bindHost((caller, name, payload) -> {
    if (!"example".equals(caller) || !"greeting".equals(name)) {
        return "{\"error\":\"Host call denied\"}";
    }
    return "{\"value\":\"Hello from Java\"}";
});
Interpreter.installSyncTool("example", "greeting");
System.out.println(Interpreter.eval("example", "greeting()"));
// Hello from Java

The Clojure equivalent is:

(python/bind-host!
  (fn [caller name payload]
    (if (and (= caller "example") (= name "greeting"))
      "{\"value\":\"Hello from Clojure\"}"
      "{\"error\":\"Host call denied\"}")))
(python/install-sync-tool! "example" "greeting")
(python/eval-str "example" "greeting()") ; => "Hello from Clojure"

These examples follow the initialization and runtime installation steps above. Requests contain session, args, and kwargs. Do not use the payload's session field to authorize a request. Return {"value": ...} on success or {"error": "..."} on failure. An error reply can also include error_data. Parse requests with a JSON library. Encode replies with the same library. Do not interpolate untrusted text.

installSyncTool creates an ordinary Python function. installTool creates a runtime tool. Use await to call it from a block.

Callbacks can run at the same time because the runtime releases the GIL during host calls. Keep callback state thread-safe. Do not re-enter the interpreter from a callback. At shutdown, unbind the callback with bindHost(null) or (bind-host! nil) after guest calls finish.

Concurrency is shared, not isolated

There is one CPython interpreter and one GIL per process. Sessions keep separate globals but share imported modules and process policy. Different session names do not make CPU-bound Python run in parallel. Other Python threads can run while a host callback releases the GIL.

Filesystem roots, network access, stdin, thread limits, and diagnostics are process-wide. Configure them centrally. A policy change applies to all sessions. Use separate worker processes for workloads with different trust or policy requirements. Run trusted extensions in a separate process, not in an unconfined session in the sandbox process.

Call interrupt / interrupt! from another thread to request KeyboardInterrupt. The return value tells whether the bridge scheduled the exception in an active thread. CPython raises a pending exception at a bytecode boundary. A blocking native call or host callback can delay delivery. If the interrupted block is waiting on gather, the bridge stops the batch. Queued slots do not start. The bridge schedules KeyboardInterrupt for each running slot. An interrupt does not enforce a deadline. Enforce hard deadlines in the parent process.

Embedded interpreter confinement

confine / confine! sets process-wide filesystem roots and blocks restricted process and FFI operations through the audit hook. The runtime adds the interpreter installation and absolute import paths to the read roots. It adds the configured bytecode cache to the write roots. Two empty root lists turn off these confinement restrictions. They do not change network or thread policy.

Use network / network! to grant or deny network access for the interpreter. Use the host's network proxy to restrict destinations. Use threads / threads! to set thread and runtime pool limits.

Interpreter policy applies only inside the embedded runtime. It does not confine child processes. Vis uses vis-jail for OS process confinement. Vis owns the jail integration.

The runtime is not a virtual machine. A session name alone is not a security boundary. Review the native packages and host capabilities you expose. Do not configure a trusted filesystem capability as a way to bypass guest policy.

Keep diagnostics bounded

Logging is off by default. Enable it with logging / logging!. Drain the native ring with drainLog / drain-log!. For periodic drains, attach a sink with drainTo / logs!. The NDJSON records contain host-chosen names, counts, and durations. They contain no guest output, source, or payloads. A full ring can drop records. The next drain reports the loss.

Generate the reference locally

From a source checkout with a full JDK 25:

clojure -T:build javac
clojure -X:docs

Open target/docs/index.html. The build uses standard Javadoc for Java and Codox for Clojure, compiles the Java example, and fails on malformed Javadoc. Generated files stay under target/; documentation dependencies exist only in the :docs alias and are not shipped runtime dependencies.