diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a2e6ee9..e36f6bb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -317,6 +317,12 @@ jobs: PYTHON_LIB=$(python3 -c "import sysconfig; print(sysconfig.get_config_var('LIBDIR'))") echo "LD_LIBRARY_PATH=${PYTHON_LIB}:${LD_LIBRARY_PATH}" >> $GITHUB_ENV + - name: Check formatting + run: rebar3 fmt --check + + - name: Run elvis lint + run: rebar3 lint + - name: Compile run: rebar3 compile diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ad98da4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,191 @@ +# Agents + +Instructions for AI coding agents working on erlang_python. Read this file +before you change anything; it applies to every agent and every change. The +same rules, written for people, are in [CONTRIBUTING.md](CONTRIBUTING.md). + +## Project Overview + +erlang_python embeds CPython in the Erlang VM through a NIF: Erlang processes +call Python, and Python calls back into Erlang. Python runs in contexts: +`worker` (a thread per context on the main interpreter), `owngil` (a thread +and a subinterpreter with its own GIL, Python 3.14 and later) and `isolated` +(a child OS process). Isolated sessions give each session a fresh child +started from a prepared template. Requires Erlang/OTP 27 or later, Python +3.12 or later with headers, CMake and a C compiler. + +## First principle: a NIF bug takes down the node + +The C code and the Erlang code around each NIF call run inside the VM. A +crash, a leak or a deadlock there belongs to the whole node, not to one +process. Every change to `c_src`, to `priv/_erlang_impl` or to the Erlang +side of a NIF call must hold three things before it is called done, +committed or opened as a pull request: + +1. **The whole defect class is fixed.** A finding, yours or a reviewer's, + names examples. Grep for every other site of the same pattern (each + `enif_binary_to_term`, each `Py_BuildValue` with an `O` argument, each + raw resource cast) and fix or clear each one. Counts and line numbers + quoted in a report drift: check them against the current tree. +2. **The mechanism is right, not just plausible.** Say which thread owns + the object, which locks are held and in what order, whether the call can + block and whether it holds the GIL while it does, and whether escaping + even applies at that position. The rules are in + [c_src/README.md](c_src/README.md#rules-that-are-easy-to-break). +3. **A test proves it.** The test fails on main without the change. A leak + gets a test that measures memory; a race gets a test that forces the + interleaving instead of waiting on timing. + +## Python code is not a security boundary + +Python code that erlang_python runs holds every authority of the user +running the node. The audit-hook sandbox keeps Python from forking the VM, +and isolated mode bounds what a child may consume and contains its crashes; +neither confines what Python may reach (see +[docs/security.md](docs/security.md) and the limits in +[docs/isolated.md](docs/isolated.md#limits)). + +So anything Python code can do is a bug at most, never a vulnerability: +getting past the audit hook, an isolated child or a session reading files, +the network or the environment, a limit (rlimits, cgroups, `clear_env`) +that was not applied, a C extension crashing the node, atom exhaustion from +atoms Python sends. Treat it as a bug: + +- fix it in a public pull request, with a public issue if one is needed; +- list it under **Fixed** in the CHANGELOG, in plain English; +- do not open a GitHub Security Advisory, request a CVE, embargo the fix, + give it a severity, or describe how to attack it; +- when it arrived as an advisory, close the advisory as not a vulnerability + and link the pull request that fixes it. + +Only a problem that gives something to someone who cannot already run code +on the node goes through [SECURITY.md](SECURITY.md): memory corruption or +code execution in the VM from data, not code, that passes through the +library (terms, bytes in channels, buffers and shared memory), or the +library loading or running code from a place the configuration did not +name. If unsure, ask the maintainer before treating anything as a security +issue. + +## Required Checks + +Every change must be formatted and pass all checks before committing. This +list matches what CI gates on; see [CONTRIBUTING.md](CONTRIBUTING.md) for +the rest of the workflow. + +```bash +rebar3 fmt # Auto-format (always run first) +rebar3 compile # Builds priv/py_nif.so through CMake +rebar3 ct --readable=compact # Common Test suites +rebar3 fmt --check # CI fails on unformatted code +rebar3 lint # Elvis linter must pass +rebar3 xref # Cross-reference analysis must pass +rebar3 dialyzer # Type checking must pass +make lint-docs # Snippets in README.md and docs/ must be valid +make check-code-map # Every module and suite has its row +rebar3 ex_doc # Docs must build +``` + +`rebar3 compile` can succeed without building anything. CMake caches the +interpreter and the build tool in `_build/cmake`; when either moves, +compile prints a CMake error, exits 0 and keeps the old `py_nif.so`. After +a toolchain or Python change, run `rm -rf _build/cmake` before compiling, +pick the interpreter with `PYTHON_CONFIG=...`, and check what the NIF links +against (`otool -L` on macOS, `ldd` on Linux). + +## Tests + +- Every behaviour change comes with a test in the same change that pins + it, and the test fails on main. A manual smoke check is not a test. +- Prefer Common Test cases that drive Python through `py:exec` and + `py:eval` over ad hoc scripts. Gate a version-specific case on the + runtime and name it after the gate. +- A feature has three kinds of tests: unit cases, a profile (a bench + escript in `examples/` with numbers before and after), and a stress + suite gated by `STRESS=1`, run once under ASan. +- A test fails for one reason. A case that measures time or memory prints + its numbers with `ct:pal` and asserts only on invariants. + +## Plans + +Read the files a change touches before you change them. For a large +refactor, or a change across many modules, propose a short plan and wait +for the maintainer before you start. + +- Lead with what each piece gives the user, in plain English, and ASCII + call paths (open, call, nested call, close, failure). Files and commits + come after. +- A plan that adds a primitive also covers the code that uses it (for + example `py_buffer` on top of `py_shm`). Stage it inside the plan; do not + leave it for a follow-up. + +## Pull Requests + +Work on one issue goes in one pull request. Give each change a reviewer has +to look at its own commit, with its tests, rather than opening a pull +request per change. Docs and CHANGELOG entries go in the same pull request. +Pull requests are merged with a merge commit, so the commits stay. + +- Commit subject in the imperative, under about 60 characters, saying what + the code now does. The body is one short paragraph on why and how; no + list of files. +- Descriptions state what was wrong and why it matters, the fix in a few + lines, and breaking changes, as prose. Reference issues with `Fixes #N`. + No test plan, no test counts, no file-by-file walkthrough, no labelled + sections. +- No `Co-Authored-By`, "Generated with" or similar trailers, in commits or + pull requests. +- Show the maintainer the full commit message and pull request text before + you commit, push or open anything, and wait for approval. Ask before + anything that publishes or cannot be undone: a push, a pull request, a + merge, a tag, a release, closing an issue. +- CHANGELOG: under the unreleased version, in `Added`, `Changed`, `Removed` + or `Fixed`. Plain English, what was wrong or what is new and what it + means for the user. Public API names are fine; code snippets, internal + function names and implementation details are not. +- Follow "Write for the person who reads it" in + [CONTRIBUTING.md](CONTRIBUTING.md#write-for-the-person-who-reads-it): + plain English, no inflated wording, never "comprehensive", no em dashes, + and a person has read the change before it is opened. + +## Releases + +A release is one commit on `main` that bumps `vsn` in +`src/erlang_python.app.src` and dates the CHANGELOG section, then an +annotated tag `vX.Y.Z` on that commit and a GitHub release whose notes are +that CHANGELOG section as is. The maintainer tags, releases and +publishes to Hex; do not do any of it unless asked. + +Before a release, review the documentation and maintainability of main +from a reader's point of view (the `docs-maintainability-review` skill, if +your agent has it) and give the plan to the maintainer. The review changes +no source code, its documentation work goes on its own branch, and the +release waits until the maintainer has said which findings to fix first. + +## Where Things Are + +- [docs/architecture.md](docs/architecture.md): how the pieces fit. +- [docs/code-map.md](docs/code-map.md): every module, C file and suite, + with the guide that covers it. +- [docs/protocols.md](docs/protocols.md) and + [docs/state-machines.md](docs/state-machines.md): message and frame + shapes, process states. +- [docs/decisions/](docs/decisions/overview.md): decision records. A change + that reverses or extends one adds a new record; the old one is not + edited. +- [c_src/README.md](c_src/README.md): the C files and their rules. +- [test/coverage_audit.md](test/coverage_audit.md): which suite covers each + documented API. +- [CONTRIBUTING.md](CONTRIBUTING.md#recipes): what a new NIF, `erlang.*` + function, context option, suite or guide must touch. + +## Formatting and Linting Notes + +erlfmt formats `src`, `test`, `examples`, `scripts` and `rebar.config`. +The C and Python sources have no formatter; follow the style around the +change. + +Elvis rules are configured in `elvis.config`, the only lint configuration. +The modules that broke a rule when the rules were adopted are listed in +that rule's `ignore`. A new module follows every rule. When you rework a +module, take it off the lists it no longer needs; never add a module to a +list to make a change pass. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..907c74e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# Claude + +@AGENTS.md diff --git a/docs/contributing.md b/CONTRIBUTING.md similarity index 54% rename from docs/contributing.md rename to CONTRIBUTING.md index 44edc01..742ef1f 100644 --- a/docs/contributing.md +++ b/CONTRIBUTING.md @@ -1,10 +1,77 @@ # Contributing -How to build, test and extend erlang_python. Read this before your first -change; each recipe lists every file a change of that kind touches, so -nothing is left half done. Design background is in -[architecture](architecture.md), file ownership in [code map](code-map.md), -message shapes in [protocols](protocols.md). +This page is for people changing erlang_python itself: how to build and +test it, what a change of each kind touches, and how to send it. For using +the library, start with [Getting Started](docs/getting-started.md). Design +background is in [architecture](docs/architecture.md), file ownership in +[code map](docs/code-map.md), message shapes in +[protocols](docs/protocols.md). AI agents also follow +[AGENTS.md](https://github.com/benoitc/erlang-python/blob/main/AGENTS.md). + +## Write for the person who reads it + +Every issue, pull request and comment is read by a person. Make it easy for +them. + +- Read what you send before you send it. You are responsible for every + line, whether you wrote it or a tool did. +- Use plain English and short sentences. Say what happens, what you + expected, and how to reproduce it. Explain any term a reader may not + know. +- Don't inflate it. No buzzwords, no severity scores, CVSS or CWE labels, + no "critical" for a bug, no long generated write-ups. If it takes a page + to explain, cut it down until it doesn't. +- A bug report gives: the erlang_python, OTP and Python versions, the OS, + the context mode (`worker`, `owngil`, `isolated`, a session), a minimal + reproduction, what you got and what you expected. For a crash of the + node, the C stack trace or the ASan report helps most. +- A pull request says what was wrong and why it matters, the fix in a few + lines, and any breaking change. Link the issue. Don't walk through the + diff file by file; the reviewer reads the code. +- A fix comes with a test that fails without it. + +AI tools are fine to use. Before you open anything, you must have read the +change, run the tests, and be able to answer questions about it yourself. + +Maintainers read every issue and pull request before acting on it. We close +without further review: + +- text we cannot understand after one request to clarify; +- descriptions that don't match the code or the reproduction; +- reports that cannot be reproduced; +- submissions opened by an automated agent that no person has read. + +## Security issues and bugs + +Python code that erlang_python runs holds every authority of the user +running the node. The sandbox keeps Python from forking the VM, and +isolated mode bounds what a child may consume and contains its crashes; +neither confines what Python may reach. [Security](docs/security.md) and +the limits in [Isolated Contexts](docs/isolated.md#limits) say what each +one bounds. + +So anything Python code can do is a bug, not a security issue. That +includes reports described as a sandbox escape or a denial of service, +when they come from: + +- Python getting past the audit hook; +- an isolated child or a session reading files, the network or the + environment; +- a limit (rlimits, cgroups, `clear_env`) that was not applied; +- a C extension crashing the node, or atoms sent from Python filling the + atom table. + +Report these as a normal bug, in public. The fix goes in a public pull +request and in the CHANGELOG under Fixed. We don't publish advisories or +request CVEs for them, and advisories filed for them are closed with a link +to the fix. + +Only problems that give something to someone who cannot already run code +on the node go through [SECURITY.md](https://github.com/benoitc/erlang-python/blob/main/SECURITY.md): memory corruption or +code execution in the VM from data, not code, that passes through the +library (terms, bytes in channels, buffers and shared memory), or the +library loading or running code from a place the configuration did not +name. ## Build @@ -22,8 +89,11 @@ Notes: compile. A change in any `c_src` file rebuilds the one NIF. - The interpreter used at build time is the one embedded at run time. `python3-config` on `PATH` is the default. -- `rm -rf _build` when switching Python versions or build flags; CMake - caches the interpreter. +- CMake caches the interpreter and the build tool in `_build/cmake`. When + either moves, `rebar3 compile` prints a CMake error but exits 0 and keeps + the old `py_nif.so`. Run `rm -rf _build/cmake` when you switch Python + versions, build flags or toolchains, and check what the NIF links against + (`otool -L` on macOS, `ldd` on Linux). ## Test @@ -31,9 +101,7 @@ Notes: rebar3 ct --readable=compact # everything rebar3 ct --suite test/py_isolated_SUITE # one suite rebar3 ct --suite test/py_context_SUITE --case test_call # one case -rebar3 dialyzer && rebar3 xref # required before a PR -make lint-docs # snippets in README and docs/ -make check-code-map # every file in the code map +STRESS=1 rebar3 ct --suite test/py_worker_loop_stress_SUITE # stress suites ``` Notes: @@ -53,9 +121,11 @@ rebar3 compile LD_PRELOAD=$(gcc -print-file-name=libasan.so) ASAN_OPTIONS=detect_leaks=0 rebar3 ct ``` -CI runs the matrix in `.github/workflows/ci.yml`: OTP 27 to 29 with Python -3.12 to 3.14 on Ubuntu and macOS, FreeBSD 14 through `vmactions/freebsd-vm`, -free-threaded 3.13t, and ASan. A PR is merged when all of them are green. +A test must fail for one reason. A case that also passes when the call +crashes, or that asserts a value it computed itself, is worse than no test +because it reads as coverage. A feature comes with unit cases, a bench +escript in `examples/` with numbers before and after, and a stress suite +gated by `STRESS=1`. ### FreeBSD by hand @@ -102,11 +172,40 @@ ssh -p 2222 root@127.0.0.1 'rm -rf ep && mkdir ep && tar -C ep -xzf ep.tgz && cd erlang-runtime28 | grep bin/erl` shows where. Use `-accel kvm` and the amd64 image on Linux hosts. +## Before you commit + +Run what CI runs. These are the checks that gate a pull request: + +```sh +rebar3 fmt # format first, then check the rest +rebar3 compile +rebar3 ct --readable=compact +rebar3 fmt --check +rebar3 lint +rebar3 xref +rebar3 dialyzer +make lint-docs # snippets in README.md, CONTRIBUTING.md and docs/ +make check-code-map # every file in the code map +rebar3 ex_doc +``` + +erlfmt formats `src`, `test`, `examples`, `scripts` and `rebar.config`; the +C and Python sources have no formatter, so follow the style around your +change. Elvis reads `elvis.config`. The modules that broke a rule when the +rules were adopted are listed in that rule's `ignore`; a new module follows +every rule, and a module comes off a list when it is reworked, never onto +one to make a change pass. + +CI runs the matrix in `.github/workflows/ci.yml`: OTP 27 to 29 with Python +3.12 to 3.14 on Ubuntu and macOS, FreeBSD 14 through `vmactions/freebsd-vm`, +free-threaded 3.13t, ASan, the lint job (formatting, Elvis, xref, dialyzer, +code map) and the documentation build. A pull request is merged when all of +them are green. + ## Recipes -Every recipe ends with the same three steps: a test case, `rebar3 -dialyzer && rebar3 xref`, and an entry in `CHANGELOG.md` under the -unreleased version. +Every recipe ends with the same steps: a test case, the checks above, and +an entry in `CHANGELOG.md` under the unreleased version. ### Add a NIF @@ -202,14 +301,40 @@ supervisor to carry it. 4. If the page documents a new API, add its rows to `test/coverage_audit.md`. -## Before opening a pull request +## Pull requests + +Branch from `main` using the prefix that fits: `fix/`, `feat/`, `perf/`, +`refactor/`, `docs/`, `test/` or `chore/`. + +Work on one issue goes in one pull request, with one commit per step a +reviewer has to look at, each with its tests. Docs and the CHANGELOG entry +go in the same pull request. Pull requests are merged with a merge commit, +so the commits stay as you wrote them. + +Write the commit subject in the imperative, describing what the code now +does rather than what it used to do, in about 60 characters. Keep the body +to one short paragraph on why and how; the diff lists the files. Do not add +generated-by or co-authored-by trailers. -- `rebar3 ct`, `rebar3 dialyzer`, `rebar3 xref`, `make lint-docs` all - clean locally. -- `CHANGELOG.md` updated under the unreleased version: `Added`, `Changed`, - `Removed` or `Fixed`. Removing a public function is a major version. +Say what the change is for and how it works. Skip the test inventory: CI +reports that. If the change touches the public API, show it in a short code +block. + +- `CHANGELOG.md` is updated under the unreleased version: `Added`, + `Changed`, `Removed` or `Fixed`, in plain English, saying what was wrong + or what is new and what it means for the user. No code snippets or + implementation details. Removing a public function is a major version. - A change that reverses or extends a decision in `docs/decisions/` gets a new record there; the old one is not edited. -- The PR text says what the change intends and which path it takes; the - diff already lists the files. -- One squashed commit per PR. + +Sync a branch that has fallen behind by merging `main` into it, not by +rebasing. + +## Releases + +The version lives in `src/erlang_python.app.src`. A release is one commit +on `main` that bumps it and dates the CHANGELOG section, then an annotated +tag `vX.Y.Z` on that commit and a GitHub release whose notes are that +CHANGELOG section as is. Before a release, the documentation is reviewed +from a reader's point of view, and the findings the maintainer picks are +fixed first. diff --git a/Makefile b/Makefile index b44db69..2bfb13c 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ compile: test: rebar3 ct --readable=compact -# Validate fenced code blocks in README.md and docs/*.md. +# Validate fenced code blocks in README.md, CONTRIBUTING.md and docs/*.md. # Erlang `py:Fn(...)` calls must reference a real export at the right # arity; Python blocks must parse (IndentationError tolerated for # tutorial fragments). Mark a block to skip with `` diff --git a/README.md b/README.md index d82f198..c5b195f 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ rebar3 compile To work on erlang_python itself (tests, CI matrix, FreeBSD VM, how to add a NIF, an `erlang.*` function, an option, a suite or a guide), see -[docs/contributing.md](docs/contributing.md). +[CONTRIBUTING.md](CONTRIBUTING.md). ## Quick Start diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f0d6af1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,57 @@ +# Security Policy + +## Supported Versions + +Security fixes are applied to the latest minor release on the `main` branch. + +| Version | Supported | +| ------- | --------- | +| 5.0.x | yes | +| < 5.0 | no | + +## What is a security issue + +Private reports are for problems that give something to someone who cannot +already run code on the node: memory corruption or code execution in the +VM from data, not code, that passes through erlang_python (terms, bytes in +channels, buffers and shared memory), or erlang_python loading or running +code from a place the configuration did not name. + +## What is a bug + +Python code that erlang_python runs holds every authority of the user +running the node. The sandbox keeps Python from forking the VM, and +isolated mode bounds what a child may consume and contains its crashes; +neither confines what Python may reach. See +[docs/security.md](docs/security.md) and the limits in +[docs/isolated.md](docs/isolated.md#limits). + +So anything Python code can do is a bug, even when described as a sandbox +escape or a denial of service: getting past the audit hook, an isolated +child or a session reading files, the network or the environment, a limit +that was not applied, a C extension crashing the node, atoms sent from +Python filling the atom table. Report it as a public bug; see +[Security issues and bugs](CONTRIBUTING.md#security-issues-and-bugs). We +don't publish advisories or request CVEs for these, and advisories filed +for them are closed as bugs with a link to the fix. + +Write the report in plain English, with a minimal reproduction, as described +in [CONTRIBUTING.md](CONTRIBUTING.md#write-for-the-person-who-reads-it). + +## Reporting a Vulnerability + +Please report suspected vulnerabilities privately through GitHub's +[Private Vulnerability Reporting](https://github.com/benoitc/erlang-python/security/advisories/new). + +Do not open public issues or pull requests for security problems. + +When reporting, include: + +- A description of the issue and its impact. +- Steps to reproduce, or a proof of concept. +- Affected versions and platform details. +- Any suggested fix or mitigation. + +You can expect an initial acknowledgement within 7 days. We will work with +you on a fix and coordinate disclosure once a patched release is available. +Credit will be given in the advisory unless you prefer to remain anonymous. diff --git a/docs/security.md b/docs/security.md index a2af68a..ad05f30 100644 --- a/docs/security.md +++ b/docs/security.md @@ -190,6 +190,7 @@ Signal handling is also not supported in the Erlang event loop. The `ErlangEvent ## See Also +- [Security policy](https://github.com/benoitc/erlang-python/blob/main/SECURITY.md) - What to report privately, and what is a bug - [Getting Started](getting-started.md) - Basic usage guide - [Asyncio](asyncio.md) - Erlang-native asyncio event loop - [Threading](threading.md) - Python threading support diff --git a/elvis.config b/elvis.config new file mode 100644 index 0000000..b7eff3b --- /dev/null +++ b/elvis.config @@ -0,0 +1,142 @@ +[ + {config, [ + #{ + files => ["src/**/*.erl"], + rules => [ + %% Same global settings as erlang_quic + {elvis_style, no_macros, disable}, + {elvis_style, prefer_strict_generators, disable}, + {elvis_style, prefer_sigils, disable}, + {elvis_style, consistent_ok_error_spec, disable}, + {elvis_style, abc_size, disable}, + {elvis_style, code_complexity, disable}, + {elvis_style, consistent_variable_naming, disable}, + {elvis_style, no_common_caveats_call, disable}, + {elvis_style, no_init_lists, disable}, + {elvis_style, no_spec_with_records, disable}, + {elvis_style, param_pattern_matching, disable}, + {elvis_style, no_used_ignored_variables, disable}, + {elvis_text_style, max_line_length, #{limit => 120}}, + + %% Exemptions for the modules that existed when the rules were + %% adopted. A new module follows every rule; shrink these lists + %% when a module is reworked, never grow them to pass a change. + + %% Processes that wait for a reply or a stop with no deadline + {elvis_style, no_receive_without_timeout, #{ + ignore => [ + py_byte_channel, + py_channel, + py_context, + py_context_embedded, + py_reactor_context, + py_reimport_session, + py_session, + py_thread_handler + ] + }}, + {elvis_style, state_record_and_type, #{ + ignore => [ + py_callback, + py_event_loop, + py_event_loop_pool, + py_event_worker, + py_event_worker_registry, + py_isolated, + py_logger, + py_reimport_session, + py_session_template, + py_shm, + py_thread_handler, + py_tracer + ] + }}, + %% ?NIF_STUB is an expression used by every stub + {elvis_style, macro_definition_parentheses, #{ignore => [py_nif]}}, + %% Early exits while a pool starts its contexts + {elvis_style, no_throw, #{ignore => [py_context_router]}}, + {elvis_style, no_if_expression, #{ + ignore => [py_isolated, py_semaphore, py_stream] + }}, + {elvis_style, no_block_expressions, #{ + ignore => [py, py_session_template, py_shm] + }}, + {elvis_style, guard_operators, #{ + ignore => [py_child, py_context_embedded, py_util] + }}, + {elvis_style, no_boolean_in_comparison, #{ignore => [py_shm]}}, + {elvis_style, no_deep_nesting, #{ + ignore => [py_context_embedded, py_event_loop_pool] + }}, + {elvis_style, dont_repeat_yourself, #{ + ignore => [ + py_byte_channel, + py_channel, + py_context, + py_context_embedded, + py_event_loop, + py_event_loop_pool, + py_isolated, + py_reimport_session, + py_session, + py_session_template, + py_shm, + py_state, + py_thread_handler + ] + }}, + {elvis_style, max_function_length, #{ + ignore => [ + erlang_python_sup, + py, + py_context_embedded, + py_context_router, + py_event_loop_pool, + py_event_worker, + py_import, + py_isolated, + py_reactor_context, + py_reimport_session, + py_session_template, + py_shm, + py_stream, + py_thread_handler, + py_tracer + ] + }}, + {elvis_style, max_function_clause_length, #{ + ignore => [ + erlang_python_sup, + py, + py_context_embedded, + py_context_router, + py_event_loop_pool, + py_import, + py_isolated, + py_reactor_context, + py_session_template, + py_stream + ] + }}, + {elvis_style, max_module_length, #{ + ignore => [ + py, + py_context_embedded, + py_event_loop_pool, + py_isolated, + py_nif, + py_session_template + ] + }}, + {elvis_style, no_god_modules, #{ + ignore => [py, py_context, py_event_loop_pool, py_nif, py_shm] + }} + ], + ruleset => erl_files_strict + }, + #{ + files => ["rebar.config"], + ruleset => rebar_config + } + ]} +]. diff --git a/examples/ai_chat.erl b/examples/ai_chat.erl index 59dd4fd..4888e39 100644 --- a/examples/ai_chat.erl +++ b/examples/ai_chat.erl @@ -31,10 +31,11 @@ main(Args) -> io:format("~n=== AI Chat Example ===~n~n"), - VenvPath = case Args of - [Path | _] -> Path; - [] -> "/tmp/ai-venv" - end, + VenvPath = + case Args of + [Path | _] -> Path; + [] -> "/tmp/ai-venv" + end, case activate_venv(VenvPath) of ok -> ok; @@ -75,8 +76,10 @@ activate_venv(VenvPath) -> ok; {error, VenvError} -> io:format("Error: ~p~n", [VenvError]), - io:format("~nSetup: python3.14 -m venv ~s && ~s/bin/pip install requests~n~n", - [VenvPath, VenvPath]), + io:format( + "~nSetup: python3.14 -m venv ~s && ~s/bin/pip install requests~n~n", + [VenvPath, VenvPath] + ), error end. @@ -85,7 +88,10 @@ init_ai_helpers() -> ScriptDir = filename:dirname(escript:script_name()), ProjectRoot = filename:dirname(ScriptDir), ExamplesDir = list_to_binary(filename:join(ProjectRoot, "examples")), - {ok, _} = py:eval(<<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, #{path => ExamplesDir}), + {ok, _} = py:eval( + <<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, + #{path => ExamplesDir} + ), ok. get_llm_type() -> diff --git a/examples/bench_async_task.erl b/examples/bench_async_task.erl index 9b737a1..3e19f98 100644 --- a/examples/bench_async_task.erl +++ b/examples/bench_async_task.erl @@ -55,14 +55,10 @@ parse_args(Args) -> parse_args(Args, #{mode => standard}). parse_args([], Acc) -> Acc; -parse_args(["--quick" | Rest], Acc) -> - parse_args(Rest, Acc#{mode => quick}); -parse_args(["--full" | Rest], Acc) -> - parse_args(Rest, Acc#{mode => full}); -parse_args(["--help" | _], Acc) -> - Acc#{help => true}; -parse_args([_ | Rest], Acc) -> - parse_args(Rest, Acc). +parse_args(["--quick" | Rest], Acc) -> parse_args(Rest, Acc#{mode => quick}); +parse_args(["--full" | Rest], Acc) -> parse_args(Rest, Acc#{mode => full}); +parse_args(["--help" | _], Acc) -> Acc#{help => true}; +parse_args([_ | Rest], Acc) -> parse_args(Rest, Acc). print_help() -> io:format("Usage: escript examples/bench_async_task.erl [OPTIONS]~n~n"), @@ -102,7 +98,6 @@ run_benchmarks(quick) -> bench_create_task_await(100), bench_concurrent_tasks(10, 10), bench_spawn_fire_forget(100); - run_benchmarks(full) -> io:format("Running full benchmarks...~n~n"), bench_baseline(5000), @@ -110,7 +105,6 @@ run_benchmarks(full) -> bench_concurrent_tasks(50, 100), bench_concurrent_tasks(100, 50), bench_spawn_fire_forget(1000); - run_benchmarks(standard) -> io:format("Running standard benchmarks...~n~n"), bench_baseline(1000), @@ -124,9 +118,12 @@ bench_baseline(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, N) + ) end), print_results(Time, N, "calls"). @@ -137,10 +134,13 @@ bench_create_task_await(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop:await(Ref) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + Ref = py_event_loop:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop:await(Ref) + end, + lists:seq(1, N) + ) end), print_results(Time, N, "tasks"). @@ -149,21 +149,34 @@ bench_create_task_await(N) -> bench_concurrent_tasks(NumProcs, TasksPerProc) -> TotalTasks = NumProcs * TasksPerProc, io:format("Benchmark: Concurrent tasks (math.sqrt)~n"), - io:format(" Processes: ~p, Tasks/process: ~p, Total: ~p~n", - [NumProcs, TasksPerProc, TotalTasks]), + io:format( + " Processes: ~p, Tasks/process: ~p, Total: ~p~n", + [NumProcs, TasksPerProc, TotalTasks] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop:await(Ref) - end, lists:seq(1, TasksPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + Ref = py_event_loop:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop:await(Ref) + end, + lists:seq(1, TasksPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), TimeMs = Time / 1000, @@ -178,9 +191,12 @@ bench_spawn_fire_forget(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - ok = py_event_loop:spawn_task(math, sqrt, [float(I)]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + ok = py_event_loop:spawn_task(math, sqrt, [float(I)]) + end, + lists:seq(1, N) + ) end), print_results(Time, N, "spawns"), diff --git a/examples/bench_byte_channel.erl b/examples/bench_byte_channel.erl index f064179..e264ea0 100755 --- a/examples/bench_byte_channel.erl +++ b/examples/bench_byte_channel.erl @@ -47,48 +47,66 @@ run_erlang_send_bench() -> Sizes = [64, 256, 1024, 4096, 16384], Iterations = 10000, - io:format("~8s | ~14s | ~14s | ~14s~n", - ["Size", "Channel", "ByteChannel", "PyBuffer"]), - io:format("~8s | ~14s | ~14s | ~14s~n", - ["(bytes)", "(msg/sec)", "(msg/sec)", "(writes/sec)"]), + io:format( + "~8s | ~14s | ~14s | ~14s~n", + ["Size", "Channel", "ByteChannel", "PyBuffer"] + ), + io:format( + "~8s | ~14s | ~14s | ~14s~n", + ["(bytes)", "(msg/sec)", "(msg/sec)", "(writes/sec)"] + ), io:format("~s~n", [string:copies("-", 58)]), - lists:foreach(fun(Size) -> - Data = binary:copy(<<0>>, Size), - - %% Channel (term-based) - {ok, Ch} = py_channel:new(), - ChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data) - end, lists:seq(1, Iterations)), - ChEnd = erlang:monotonic_time(microsecond), - ChRate = Iterations / ((ChEnd - ChStart) / 1000000), - py_channel:close(Ch), - - %% ByteChannel (raw bytes) - {ok, BCh} = py_byte_channel:new(), - BChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_byte_channel:send(BCh, Data) - end, lists:seq(1, Iterations)), - BChEnd = erlang:monotonic_time(microsecond), - BChRate = Iterations / ((BChEnd - BChStart) / 1000000), - py_byte_channel:close(BCh), - - %% PyBuffer - {ok, Buf} = py_buffer:new(), - BufStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_buffer:write(Buf, Data) - end, lists:seq(1, Iterations)), - BufEnd = erlang:monotonic_time(microsecond), - BufRate = Iterations / ((BufEnd - BufStart) / 1000000), - py_buffer:close(Buf), - - io:format("~8B | ~14w | ~14w | ~14w~n", - [Size, round(ChRate), round(BChRate), round(BufRate)]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = binary:copy(<<0>>, Size), + + %% Channel (term-based) + {ok, Ch} = py_channel:new(), + ChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data) + end, + lists:seq(1, Iterations) + ), + ChEnd = erlang:monotonic_time(microsecond), + ChRate = Iterations / ((ChEnd - ChStart) / 1000000), + py_channel:close(Ch), + + %% ByteChannel (raw bytes) + {ok, BCh} = py_byte_channel:new(), + BChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_byte_channel:send(BCh, Data) + end, + lists:seq(1, Iterations) + ), + BChEnd = erlang:monotonic_time(microsecond), + BChRate = Iterations / ((BChEnd - BChStart) / 1000000), + py_byte_channel:close(BCh), + + %% PyBuffer + {ok, Buf} = py_buffer:new(), + BufStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_buffer:write(Buf, Data) + end, + lists:seq(1, Iterations) + ), + BufEnd = erlang:monotonic_time(microsecond), + BufRate = Iterations / ((BufEnd - BufStart) / 1000000), + py_buffer:close(Buf), + + io:format( + "~8B | ~14w | ~14w | ~14w~n", + [Size, round(ChRate), round(BChRate), round(BufRate)] + ) + end, + Sizes + ), ok. %% Benchmark Erlang-side roundtrip (send + receive, no Python) @@ -99,40 +117,55 @@ run_erlang_roundtrip_bench() -> Sizes = [64, 256, 1024, 4096, 16384], Iterations = 10000, - io:format("~8s | ~14s | ~14s~n", - ["Size", "Channel", "ByteChannel"]), - io:format("~8s | ~14s | ~14s~n", - ["(bytes)", "(roundtrip/s)", "(roundtrip/s)"]), + io:format( + "~8s | ~14s | ~14s~n", + ["Size", "Channel", "ByteChannel"] + ), + io:format( + "~8s | ~14s | ~14s~n", + ["(bytes)", "(roundtrip/s)", "(roundtrip/s)"] + ), io:format("~s~n", [string:copies("-", 42)]), - lists:foreach(fun(Size) -> - Data = binary:copy(<<0>>, Size), - - %% Channel roundtrip - {ok, Ch} = py_channel:new(), - ChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, Iterations)), - ChEnd = erlang:monotonic_time(microsecond), - ChRate = Iterations / ((ChEnd - ChStart) / 1000000), - py_channel:close(Ch), - - %% ByteChannel roundtrip - {ok, BCh} = py_byte_channel:new(), - BChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_byte_channel:send(BCh, Data), - {ok, _} = py_byte_channel:try_receive(BCh) - end, lists:seq(1, Iterations)), - BChEnd = erlang:monotonic_time(microsecond), - BChRate = Iterations / ((BChEnd - BChStart) / 1000000), - py_byte_channel:close(BCh), - - io:format("~8B | ~14w | ~14w~n", - [Size, round(ChRate), round(BChRate)]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = binary:copy(<<0>>, Size), + + %% Channel roundtrip + {ok, Ch} = py_channel:new(), + ChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, Iterations) + ), + ChEnd = erlang:monotonic_time(microsecond), + ChRate = Iterations / ((ChEnd - ChStart) / 1000000), + py_channel:close(Ch), + + %% ByteChannel roundtrip + {ok, BCh} = py_byte_channel:new(), + BChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_byte_channel:send(BCh, Data), + {ok, _} = py_byte_channel:try_receive(BCh) + end, + lists:seq(1, Iterations) + ), + BChEnd = erlang:monotonic_time(microsecond), + BChRate = Iterations / ((BChEnd - BChStart) / 1000000), + py_byte_channel:close(BCh), + + io:format( + "~8B | ~14w | ~14w~n", + [Size, round(ChRate), round(BChRate)] + ) + end, + Sizes + ), ok. %% Benchmark Python receive performance @@ -142,69 +175,88 @@ run_python_receive_bench() -> io:format("Iterations: 1000~n~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang import Channel, ByteChannel - -def recv_channel(ch_ref): - ch = Channel(ch_ref) - return ch.try_receive() - -def recv_byte_channel(ch_ref): - ch = ByteChannel(ch_ref) - return ch.try_receive_bytes() - -def read_buffer(buf): - return buf.read() -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang import Channel, ByteChannel\n" + "\n" + "def recv_channel(ch_ref):\n" + " ch = Channel(ch_ref)\n" + " return ch.try_receive()\n" + "\n" + "def recv_byte_channel(ch_ref):\n" + " ch = ByteChannel(ch_ref)\n" + " return ch.try_receive_bytes()\n" + "\n" + "def read_buffer(buf):\n" + " return buf.read()\n" + >>), Sizes = [64, 256, 1024, 4096, 16384], Iterations = 1000, - io:format("~8s | ~12s | ~12s | ~12s~n", - ["Size", "Channel", "ByteChannel", "PyBuffer"]), - io:format("~8s | ~12s | ~12s | ~12s~n", - ["(bytes)", "(ops/sec)", "(ops/sec)", "(ops/sec)"]), + io:format( + "~8s | ~12s | ~12s | ~12s~n", + ["Size", "Channel", "ByteChannel", "PyBuffer"] + ), + io:format( + "~8s | ~12s | ~12s | ~12s~n", + ["(bytes)", "(ops/sec)", "(ops/sec)", "(ops/sec)"] + ), io:format("~s~n", [string:copies("-", 54)]), - lists:foreach(fun(Size) -> - Data = binary:copy(<<0>>, Size), - - %% Channel: Erlang send -> Python receive - {ok, Ch} = py_channel:new(), - ChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py:eval(Ctx, <<"recv_channel(ch)">>, #{<<"ch">> => Ch}) - end, lists:seq(1, Iterations)), - ChEnd = erlang:monotonic_time(microsecond), - ChRate = Iterations / ((ChEnd - ChStart) / 1000000), - py_channel:close(Ch), - - %% ByteChannel: Erlang send -> Python receive - {ok, BCh} = py_byte_channel:new(), - BChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_byte_channel:send(BCh, Data), - {ok, _} = py:eval(Ctx, <<"recv_byte_channel(ch)">>, #{<<"ch">> => BCh}) - end, lists:seq(1, Iterations)), - BChEnd = erlang:monotonic_time(microsecond), - BChRate = Iterations / ((BChEnd - BChStart) / 1000000), - py_byte_channel:close(BCh), - - %% PyBuffer: Erlang write -> Python read - BufStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - {ok, Buf} = py_buffer:new(Size), - ok = py_buffer:write(Buf, Data), - ok = py_buffer:close(Buf), - {ok, _} = py:eval(Ctx, <<"read_buffer(buf)">>, #{<<"buf">> => Buf}) - end, lists:seq(1, Iterations)), - BufEnd = erlang:monotonic_time(microsecond), - BufRate = Iterations / ((BufEnd - BufStart) / 1000000), - - io:format("~8B | ~12w | ~12w | ~12w~n", - [Size, round(ChRate), round(BChRate), round(BufRate)]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = binary:copy(<<0>>, Size), + + %% Channel: Erlang send -> Python receive + {ok, Ch} = py_channel:new(), + ChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py:eval(Ctx, <<"recv_channel(ch)">>, #{<<"ch">> => Ch}) + end, + lists:seq(1, Iterations) + ), + ChEnd = erlang:monotonic_time(microsecond), + ChRate = Iterations / ((ChEnd - ChStart) / 1000000), + py_channel:close(Ch), + + %% ByteChannel: Erlang send -> Python receive + {ok, BCh} = py_byte_channel:new(), + BChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_byte_channel:send(BCh, Data), + {ok, _} = py:eval(Ctx, <<"recv_byte_channel(ch)">>, #{<<"ch">> => BCh}) + end, + lists:seq(1, Iterations) + ), + BChEnd = erlang:monotonic_time(microsecond), + BChRate = Iterations / ((BChEnd - BChStart) / 1000000), + py_byte_channel:close(BCh), + + %% PyBuffer: Erlang write -> Python read + BufStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + {ok, Buf} = py_buffer:new(Size), + ok = py_buffer:write(Buf, Data), + ok = py_buffer:close(Buf), + {ok, _} = py:eval(Ctx, <<"read_buffer(buf)">>, #{<<"buf">> => Buf}) + end, + lists:seq(1, Iterations) + ), + BufEnd = erlang:monotonic_time(microsecond), + BufRate = Iterations / ((BufEnd - BufStart) / 1000000), + + io:format( + "~8B | ~12w | ~12w | ~12w~n", + [Size, round(ChRate), round(BChRate), round(BufRate)] + ) + end, + Sizes + ), ok. %% Benchmark streaming (1MB transfer with varying chunk sizes) @@ -213,88 +265,114 @@ run_streaming_bench() -> io:format("Pattern: Erlang sends chunks -> Python receives all~n~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang import Channel, ByteChannel - -def stream_channel(ch_ref, num_chunks): - ch = Channel(ch_ref) - total = 0 - for _ in range(num_chunks): - msg = ch.try_receive() - if msg is None: - break - total += len(msg) - return total - -def stream_byte_channel(ch_ref, num_chunks): - ch = ByteChannel(ch_ref) - total = 0 - for _ in range(num_chunks): - data = ch.try_receive_bytes() - if data is None: - break - total += len(data) - return total - -def stream_buffer(buf): - total = 0 - while True: - chunk = buf.read(8192) - if not chunk: - break - total += len(chunk) - return total -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang import Channel, ByteChannel\n" + "\n" + "def stream_channel(ch_ref, num_chunks):\n" + " ch = Channel(ch_ref)\n" + " total = 0\n" + " for _ in range(num_chunks):\n" + " msg = ch.try_receive()\n" + " if msg is None:\n" + " break\n" + " total += len(msg)\n" + " return total\n" + "\n" + "def stream_byte_channel(ch_ref, num_chunks):\n" + " ch = ByteChannel(ch_ref)\n" + " total = 0\n" + " for _ in range(num_chunks):\n" + " data = ch.try_receive_bytes()\n" + " if data is None:\n" + " break\n" + " total += len(data)\n" + " return total\n" + "\n" + "def stream_buffer(buf):\n" + " total = 0\n" + " while True:\n" + " chunk = buf.read(8192)\n" + " if not chunk:\n" + " break\n" + " total += len(chunk)\n" + " return total\n" + >>), ChunkSizes = [1024, 4096, 16384, 65536], - TotalBytes = 1048576, % 1MB - - io:format("~10s | ~12s | ~12s | ~12s~n", - ["Chunk", "Channel", "ByteChannel", "PyBuffer"]), - io:format("~10s | ~12s | ~12s | ~12s~n", - ["(bytes)", "(MB/sec)", "(MB/sec)", "(MB/sec)"]), + % 1MB + TotalBytes = 1048576, + + io:format( + "~10s | ~12s | ~12s | ~12s~n", + ["Chunk", "Channel", "ByteChannel", "PyBuffer"] + ), + io:format( + "~10s | ~12s | ~12s | ~12s~n", + ["(bytes)", "(MB/sec)", "(MB/sec)", "(MB/sec)"] + ), io:format("~s~n", [string:copies("-", 54)]), - lists:foreach(fun(ChunkSize) -> - NumChunks = TotalBytes div ChunkSize, - Chunk = binary:copy(<<0>>, ChunkSize), - - %% Channel streaming - {ok, Ch} = py_channel:new(), - ChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Chunk) - end, lists:seq(1, NumChunks)), - {ok, _} = py:eval(Ctx, <<"stream_channel(ch, n)">>, - #{<<"ch">> => Ch, <<"n">> => NumChunks}), - ChEnd = erlang:monotonic_time(microsecond), - ChMBps = (TotalBytes / 1048576) / ((ChEnd - ChStart) / 1000000), - py_channel:close(Ch), - - %% ByteChannel streaming - {ok, BCh} = py_byte_channel:new(), - BChStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_byte_channel:send(BCh, Chunk) - end, lists:seq(1, NumChunks)), - {ok, _} = py:eval(Ctx, <<"stream_byte_channel(ch, n)">>, - #{<<"ch">> => BCh, <<"n">> => NumChunks}), - BChEnd = erlang:monotonic_time(microsecond), - BChMBps = (TotalBytes / 1048576) / ((BChEnd - BChStart) / 1000000), - py_byte_channel:close(BCh), - - %% PyBuffer streaming - {ok, Buf} = py_buffer:new(TotalBytes), - BufStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_buffer:write(Buf, Chunk) - end, lists:seq(1, NumChunks)), - ok = py_buffer:close(Buf), - {ok, _} = py:eval(Ctx, <<"stream_buffer(buf)">>, #{<<"buf">> => Buf}), - BufEnd = erlang:monotonic_time(microsecond), - BufMBps = (TotalBytes / 1048576) / ((BufEnd - BufStart) / 1000000), - - io:format("~10B | ~12.2f | ~12.2f | ~12.2f~n", - [ChunkSize, ChMBps, BChMBps, BufMBps]) - end, ChunkSizes), + lists:foreach( + fun(ChunkSize) -> + NumChunks = TotalBytes div ChunkSize, + Chunk = binary:copy(<<0>>, ChunkSize), + + %% Channel streaming + {ok, Ch} = py_channel:new(), + ChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Chunk) + end, + lists:seq(1, NumChunks) + ), + {ok, _} = py:eval( + Ctx, + <<"stream_channel(ch, n)">>, + #{<<"ch">> => Ch, <<"n">> => NumChunks} + ), + ChEnd = erlang:monotonic_time(microsecond), + ChMBps = (TotalBytes / 1048576) / ((ChEnd - ChStart) / 1000000), + py_channel:close(Ch), + + %% ByteChannel streaming + {ok, BCh} = py_byte_channel:new(), + BChStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_byte_channel:send(BCh, Chunk) + end, + lists:seq(1, NumChunks) + ), + {ok, _} = py:eval( + Ctx, + <<"stream_byte_channel(ch, n)">>, + #{<<"ch">> => BCh, <<"n">> => NumChunks} + ), + BChEnd = erlang:monotonic_time(microsecond), + BChMBps = (TotalBytes / 1048576) / ((BChEnd - BChStart) / 1000000), + py_byte_channel:close(BCh), + + %% PyBuffer streaming + {ok, Buf} = py_buffer:new(TotalBytes), + BufStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_buffer:write(Buf, Chunk) + end, + lists:seq(1, NumChunks) + ), + ok = py_buffer:close(Buf), + {ok, _} = py:eval(Ctx, <<"stream_buffer(buf)">>, #{<<"buf">> => Buf}), + BufEnd = erlang:monotonic_time(microsecond), + BufMBps = (TotalBytes / 1048576) / ((BufEnd - BufStart) / 1000000), + + io:format( + "~10B | ~12.2f | ~12.2f | ~12.2f~n", + [ChunkSize, ChMBps, BChMBps, BufMBps] + ) + end, + ChunkSizes + ), ok. diff --git a/examples/bench_channel.erl b/examples/bench_channel.erl index c8189fa..6d47ba3 100644 --- a/examples/bench_channel.erl +++ b/examples/bench_channel.erl @@ -43,191 +43,225 @@ run_channel_throughput_bench() -> Sizes = [64, 256, 1024, 4096, 16384], - io:format("~8s | ~12s | ~12s | ~12s~n", - ["Size", "Send (msg/s)", "Recv (msg/s)", "Round (msg/s)"]), + io:format( + "~8s | ~12s | ~12s | ~12s~n", + ["Size", "Send (msg/s)", "Recv (msg/s)", "Round (msg/s)"] + ), io:format("~s~n", [string:copies("-", 52)]), - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - Iterations = 1000, - - %% Benchmark send - SendStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data) - end, lists:seq(1, Iterations)), - SendEnd = erlang:monotonic_time(microsecond), - SendTime = (SendEnd - SendStart) / 1000000, - SendRate = Iterations / SendTime, - - %% Benchmark receive (drain the queue) - RecvStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, Iterations)), - RecvEnd = erlang:monotonic_time(microsecond), - RecvTime = (RecvEnd - RecvStart) / 1000000, - RecvRate = Iterations / RecvTime, - - %% Benchmark round-trip (send + receive) - RoundStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, Iterations)), - RoundEnd = erlang:monotonic_time(microsecond), - RoundTime = (RoundEnd - RoundStart) / 1000000, - RoundRate = Iterations / RoundTime, - - io:format("~8B | ~12w | ~12w | ~12w~n", - [Size, round(SendRate), round(RecvRate), round(RoundRate)]), - - py_channel:close(Ch) - end, Sizes), + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + Iterations = 1000, + + %% Benchmark send + SendStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data) + end, + lists:seq(1, Iterations) + ), + SendEnd = erlang:monotonic_time(microsecond), + SendTime = (SendEnd - SendStart) / 1000000, + SendRate = Iterations / SendTime, + + %% Benchmark receive (drain the queue) + RecvStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, Iterations) + ), + RecvEnd = erlang:monotonic_time(microsecond), + RecvTime = (RecvEnd - RecvStart) / 1000000, + RecvRate = Iterations / RecvTime, + + %% Benchmark round-trip (send + receive) + RoundStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, Iterations) + ), + RoundEnd = erlang:monotonic_time(microsecond), + RoundTime = (RoundEnd - RoundStart) / 1000000, + RoundRate = Iterations / RoundTime, + + io:format( + "~8B | ~12w | ~12w | ~12w~n", + [Size, round(SendRate), round(RecvRate), round(RoundRate)] + ), + + py_channel:close(Ch) + end, + Sizes + ), ok. run_channel_vs_reactor_bench() -> io:format("~n--- Channel vs Reactor Comparison ---~n"), io:format("Iterations: 5000~n~n"), - Code = <<" -import time -import socket -import erlang -import erlang.reactor as reactor - -def bench_channel_python(iterations=5000): - '''Benchmark Channel from Python side''' - results = {} - sizes = [64, 256, 1024, 4096, 16384] - - for size in sizes: - test_data = b'X' * size - - # We can't easily create channels from Python yet, - # so we benchmark try_receive on pre-filled channels - # This measures Python-side overhead - - # Measure try_receive with None ref (measures call overhead) - start = time.perf_counter() - for _ in range(iterations): - try: - # Just measure the erlang.call overhead - pass - except: - pass - call_time = time.perf_counter() - start - - results[size] = { - 'call_overhead_ms': call_time * 1000, - 'ops_per_sec': iterations / max(call_time, 0.0001), - } - - return results - -def bench_reactor_protocol(iterations=200): - '''Benchmark Reactor Protocol pattern''' - results = {} - sizes = [64, 256, 1024, 4096, 16384] - - class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'read_pending' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'read_pending' - - for size in sizes: - test_data = b'X' * size - times = [] - - for _ in range(iterations): - s1, s2 = socket.socketpair() - s1.setblocking(False) - s2.setblocking(False) - - try: - reactor.set_protocol_factory(EchoProtocol) - reactor.init_connection(s1.fileno(), {'type': 'test'}) - - s2.send(test_data) - - start = time.perf_counter() - action = reactor.on_read_ready(s1.fileno()) - elapsed = time.perf_counter() - start - times.append(elapsed) - - reactor.close_connection(s1.fileno()) - finally: - s1.close() - s2.close() - - import statistics - avg_time = statistics.mean(times) - results[size] = { - 'avg_time_ms': avg_time * 1000, - 'ops_per_sec': 1.0 / avg_time, - } - - return results - -_reactor_results = bench_reactor_protocol() -">>, + Code = << + "\n" + "import time\n" + "import socket\n" + "import erlang\n" + "import erlang.reactor as reactor\n" + "\n" + "def bench_channel_python(iterations=5000):\n" + " '''Benchmark Channel from Python side'''\n" + " results = {}\n" + " sizes = [64, 256, 1024, 4096, 16384]\n" + "\n" + " for size in sizes:\n" + " test_data = b'X' * size\n" + "\n" + " # We can't easily create channels from Python yet,\n" + " # so we benchmark try_receive on pre-filled channels\n" + " # This measures Python-side overhead\n" + "\n" + " # Measure try_receive with None ref (measures call overhead)\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " try:\n" + " # Just measure the erlang.call overhead\n" + " pass\n" + " except:\n" + " pass\n" + " call_time = time.perf_counter() - start\n" + "\n" + " results[size] = {\n" + " 'call_overhead_ms': call_time * 1000,\n" + " 'ops_per_sec': iterations / max(call_time, 0.0001),\n" + " }\n" + "\n" + " return results\n" + "\n" + "def bench_reactor_protocol(iterations=200):\n" + " '''Benchmark Reactor Protocol pattern'''\n" + " results = {}\n" + " sizes = [64, 256, 1024, 4096, 16384]\n" + "\n" + " class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'read_pending'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'read_pending'\n" + "\n" + " for size in sizes:\n" + " test_data = b'X' * size\n" + " times = []\n" + "\n" + " for _ in range(iterations):\n" + " s1, s2 = socket.socketpair()\n" + " s1.setblocking(False)\n" + " s2.setblocking(False)\n" + "\n" + " try:\n" + " reactor.set_protocol_factory(EchoProtocol)\n" + " reactor.init_connection(s1.fileno(), {'type': 'test'})\n" + "\n" + " s2.send(test_data)\n" + "\n" + " start = time.perf_counter()\n" + " action = reactor.on_read_ready(s1.fileno())\n" + " elapsed = time.perf_counter() - start\n" + " times.append(elapsed)\n" + "\n" + " reactor.close_connection(s1.fileno())\n" + " finally:\n" + " s1.close()\n" + " s2.close()\n" + "\n" + " import statistics\n" + " avg_time = statistics.mean(times)\n" + " results[size] = {\n" + " 'avg_time_ms': avg_time * 1000,\n" + " 'ops_per_sec': 1.0 / avg_time,\n" + " }\n" + "\n" + " return results\n" + "\n" + "_reactor_results = bench_reactor_protocol()\n" + >>, ok = py:exec(Code), {ok, ReactorResults} = py:eval(<<"_reactor_results">>), io:format("Reactor Protocol (echo pattern):~n"), - io:format("~8s | ~12s | ~12s~n", - ["Size", "Avg (ms)", "Ops/sec"]), + io:format( + "~8s | ~12s | ~12s~n", + ["Size", "Avg (ms)", "Ops/sec"] + ), io:format("~s~n", [string:copies("-", 36)]), Sizes = [64, 256, 1024, 4096, 16384], - lists:foreach(fun(Size) -> - Data = maps:get(Size, ReactorResults), - AvgMs = maps:get(<<"avg_time_ms">>, Data), - OpsPerSec = maps:get(<<"ops_per_sec">>, Data), - io:format("~8B | ~12.3f | ~12w~n", - [Size, AvgMs, round(OpsPerSec)]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = maps:get(Size, ReactorResults), + AvgMs = maps:get(<<"avg_time_ms">>, Data), + OpsPerSec = maps:get(<<"ops_per_sec">>, Data), + io:format( + "~8B | ~12.3f | ~12w~n", + [Size, AvgMs, round(OpsPerSec)] + ) + end, + Sizes + ), %% Now compare with Channel round-trip io:format("~nChannel Round-trip (Erlang send + NIF receive):~n"), - io:format("~8s | ~12s | ~12s | ~8s~n", - ["Size", "Avg (ms)", "Ops/sec", "vs React"]), + io:format( + "~8s | ~12s | ~12s | ~8s~n", + ["Size", "Avg (ms)", "Ops/sec", "vs React"] + ), io:format("~s~n", [string:copies("-", 48)]), - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - Iterations = 1000, + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + Iterations = 1000, - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), - TotalTime = (End - Start) / 1000000, - AvgMs = (TotalTime / Iterations) * 1000, - OpsPerSec = Iterations / TotalTime, + TotalTime = (End - Start) / 1000000, + AvgMs = (TotalTime / Iterations) * 1000, + OpsPerSec = Iterations / TotalTime, - ReactorData = maps:get(Size, ReactorResults), - ReactorOps = maps:get(<<"ops_per_sec">>, ReactorData), - Ratio = OpsPerSec / ReactorOps, + ReactorData = maps:get(Size, ReactorResults), + ReactorOps = maps:get(<<"ops_per_sec">>, ReactorData), + Ratio = OpsPerSec / ReactorOps, - io:format("~8B | ~12.3f | ~12w | ~.1fx~n", - [Size, AvgMs, round(OpsPerSec), Ratio]), + io:format( + "~8B | ~12.3f | ~12w | ~.1fx~n", + [Size, AvgMs, round(OpsPerSec), Ratio] + ), - py_channel:close(Ch) - end, Sizes), + py_channel:close(Ch) + end, + Sizes + ), ok. run_channel_latency_bench() -> @@ -236,34 +270,44 @@ run_channel_latency_bench() -> Sizes = [64, 1024, 16384], - io:format("~8s | ~10s | ~10s | ~10s | ~10s~n", - ["Size", "Min (us)", "Avg (us)", "P99 (us)", "Max (us)"]), + io:format( + "~8s | ~10s | ~10s | ~10s | ~10s~n", + ["Size", "Min (us)", "Avg (us)", "P99 (us)", "Max (us)"] + ), io:format("~s~n", [string:copies("-", 56)]), - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - Iterations = 10000, - - %% Collect latencies - Latencies = lists:map(fun(_) -> - Start = erlang:monotonic_time(microsecond), - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch), - End = erlang:monotonic_time(microsecond), - End - Start - end, lists:seq(1, Iterations)), - - Sorted = lists:sort(Latencies), - Min = hd(Sorted), - Max = lists:last(Sorted), - Avg = lists:sum(Latencies) / Iterations, - P99Idx = round(Iterations * 0.99), - P99 = lists:nth(P99Idx, Sorted), - - io:format("~8B | ~10.1f | ~10.1f | ~10.1f | ~10.1f~n", - [Size, float(Min), Avg, float(P99), float(Max)]), - - py_channel:close(Ch) - end, Sizes), + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + Iterations = 10000, + + %% Collect latencies + Latencies = lists:map( + fun(_) -> + Start = erlang:monotonic_time(microsecond), + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch), + End = erlang:monotonic_time(microsecond), + End - Start + end, + lists:seq(1, Iterations) + ), + + Sorted = lists:sort(Latencies), + Min = hd(Sorted), + Max = lists:last(Sorted), + Avg = lists:sum(Latencies) / Iterations, + P99Idx = round(Iterations * 0.99), + P99 = lists:nth(P99Idx, Sorted), + + io:format( + "~8B | ~10.1f | ~10.1f | ~10.1f | ~10.1f~n", + [Size, float(Min), Avg, float(P99), float(Max)] + ), + + py_channel:close(Ch) + end, + Sizes + ), ok. diff --git a/examples/bench_channel_async.erl b/examples/bench_channel_async.erl index 37bbbd5..d17571e 100644 --- a/examples/bench_channel_async.erl +++ b/examples/bench_channel_async.erl @@ -57,35 +57,44 @@ run_sync_channel_bench() -> Sizes = [64, 1024, 16384], Iterations = 5000, - io:format("~8s | ~12s | ~12s~n", - ["Size", "Throughput", "Avg (us)"]), + io:format( + "~8s | ~12s | ~12s~n", + ["Size", "Throughput", "Avg (us)"] + ), io:format("~s~n", [string:copies("-", 38)]), - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - - %% Fill channel - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data) - end, lists:seq(1, Iterations)), - - %% Time receiving all messages via NIF - Start = erlang:monotonic_time(microsecond), - receive_all_sync(Ch, Iterations), - End = erlang:monotonic_time(microsecond), - - TotalTime = (End - Start) / 1000000, - AvgUs = (TotalTime / Iterations) * 1000000, - Throughput = round(Iterations / TotalTime), - - io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), - - py_channel:close(Ch) - end, Sizes), + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + + %% Fill channel + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data) + end, + lists:seq(1, Iterations) + ), + + %% Time receiving all messages via NIF + Start = erlang:monotonic_time(microsecond), + receive_all_sync(Ch, Iterations), + End = erlang:monotonic_time(microsecond), + + TotalTime = (End - Start) / 1000000, + AvgUs = (TotalTime / Iterations) * 1000000, + Throughput = round(Iterations / TotalTime), + + io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), + + py_channel:close(Ch) + end, + Sizes + ), ok. -receive_all_sync(_Ch, 0) -> ok; +receive_all_sync(_Ch, 0) -> + ok; receive_all_sync(Ch, N) -> {ok, _} = py_nif:channel_try_receive(Ch), receive_all_sync(Ch, N - 1). @@ -96,16 +105,21 @@ run_async_channel_bench() -> Iterations = 1000, - io:format("~15s | ~12s | ~12s~n", - ["Operation", "Throughput", "Avg (us)"]), + io:format( + "~15s | ~12s | ~12s~n", + ["Operation", "Throughput", "Avg (us)"] + ), io:format("~s~n", [string:copies("-", 44)]), %% Test math.sqrt via async task API Start1 = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - Ref = py_event_loop:create_task(math, sqrt, [2.0]), - {ok, _} = py_event_loop:await(Ref, 5000) - end, lists:seq(1, Iterations)), + lists:foreach( + fun(_) -> + Ref = py_event_loop:create_task(math, sqrt, [2.0]), + {ok, _} = py_event_loop:await(Ref, 5000) + end, + lists:seq(1, Iterations) + ), End1 = erlang:monotonic_time(microsecond), TotalTime1 = (End1 - Start1) / 1000000, @@ -121,15 +135,21 @@ run_async_channel_bench() -> Start2 = erlang:monotonic_time(microsecond), Parent = self(), - lists:foreach(fun(_) -> - spawn(fun() -> - lists:foreach(fun(_) -> - Ref = py_event_loop:create_task(math, sqrt, [2.0]), - {ok, _} = py_event_loop:await(Ref, 5000) - end, lists:seq(1, TasksPerProc)), - Parent ! done - end) - end, lists:seq(1, NumProcs)), + lists:foreach( + fun(_) -> + spawn(fun() -> + lists:foreach( + fun(_) -> + Ref = py_event_loop:create_task(math, sqrt, [2.0]), + {ok, _} = py_event_loop:await(Ref, 5000) + end, + lists:seq(1, TasksPerProc) + ), + Parent ! done + end) + end, + lists:seq(1, NumProcs) + ), wait_all(NumProcs), End2 = erlang:monotonic_time(microsecond), @@ -141,9 +161,12 @@ run_async_channel_bench() -> ok. -wait_all(0) -> ok; +wait_all(0) -> + ok; wait_all(N) -> - receive done -> wait_all(N - 1) end. + receive + done -> wait_all(N - 1) + end. run_comparison_bench() -> io:format("~n--- Sync vs Async Comparison ---~n"), @@ -153,8 +176,10 @@ run_comparison_bench() -> Iterations = 1000, io:format("Message size: ~B bytes, Iterations: ~B~n~n", [Size, Iterations]), - io:format("~15s | ~12s | ~12s~n", - ["Method", "Time (ms)", "Throughput"]), + io:format( + "~15s | ~12s | ~12s~n", + ["Method", "Time (ms)", "Throughput"] + ), io:format("~s~n", [string:copies("-", 45)]), Data = binary:copy(<<0>>, Size), @@ -172,9 +197,12 @@ run_comparison_bench() -> %% py:call sync (Python stdlib function) PyStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - {ok, _} = py:call(math, sqrt, [2.0]) - end, lists:seq(1, Iterations)), + lists:foreach( + fun(_) -> + {ok, _} = py:call(math, sqrt, [2.0]) + end, + lists:seq(1, Iterations) + ), PyEnd = erlang:monotonic_time(microsecond), PyTime = (PyEnd - PyStart) / 1000, PyThroughput = round(Iterations / (PyTime / 1000)), @@ -182,10 +210,13 @@ run_comparison_bench() -> %% Async task API (sequential) AsyncStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - Ref = py_event_loop:create_task(math, sqrt, [2.0]), - {ok, _} = py_event_loop:await(Ref, 5000) - end, lists:seq(1, Iterations)), + lists:foreach( + fun(_) -> + Ref = py_event_loop:create_task(math, sqrt, [2.0]), + {ok, _} = py_event_loop:await(Ref, 5000) + end, + lists:seq(1, Iterations) + ), AsyncEnd = erlang:monotonic_time(microsecond), AsyncTime = (AsyncEnd - AsyncStart) / 1000, AsyncThroughput = round(Iterations / (AsyncTime / 1000)), @@ -193,13 +224,19 @@ run_comparison_bench() -> %% Spawn task (fire-and-forget, then collect) SpawnStart = erlang:monotonic_time(microsecond), - Refs = lists:map(fun(_) -> - py_event_loop:create_task(math, sqrt, [2.0]) - end, lists:seq(1, Iterations)), + Refs = lists:map( + fun(_) -> + py_event_loop:create_task(math, sqrt, [2.0]) + end, + lists:seq(1, Iterations) + ), %% Await all - lists:foreach(fun(R) -> - {ok, _} = py_event_loop:await(R, 5000) - end, Refs), + lists:foreach( + fun(R) -> + {ok, _} = py_event_loop:await(R, 5000) + end, + Refs + ), SpawnEnd = erlang:monotonic_time(microsecond), SpawnTime = (SpawnEnd - SpawnStart) / 1000, SpawnThroughput = round(Iterations / (SpawnTime / 1000)), diff --git a/examples/bench_channel_receive.erl b/examples/bench_channel_receive.erl index a8437f6..790255b 100644 --- a/examples/bench_channel_receive.erl +++ b/examples/bench_channel_receive.erl @@ -51,39 +51,49 @@ run_sync_receive_bench() -> Ctx = py:context(1), %% Define sync receiver function - ok = py:exec(Ctx, <<" -from erlang import Channel - -def sync_receive_n(ch_ref, n): - ch = Channel(ch_ref) - for _ in range(n): - ch.receive() - return n -">>), - - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - - %% Fill channel - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data) - end, lists:seq(1, Iterations)), - - %% Time Python sync receive - Start = erlang:monotonic_time(microsecond), - {ok, Iterations} = py:eval(Ctx, <<"sync_receive_n(ch, n)">>, - #{<<"ch">> => Ch, <<"n">> => Iterations}), - End = erlang:monotonic_time(microsecond), - - TotalTime = (End - Start) / 1000000, - AvgUs = (TotalTime / Iterations) * 1000000, - Throughput = round(Iterations / TotalTime), - - io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), - - py_channel:close(Ch) - end, Sizes), + ok = py:exec(Ctx, << + "\n" + "from erlang import Channel\n" + "\n" + "def sync_receive_n(ch_ref, n):\n" + " ch = Channel(ch_ref)\n" + " for _ in range(n):\n" + " ch.receive()\n" + " return n\n" + >>), + + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + + %% Fill channel + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data) + end, + lists:seq(1, Iterations) + ), + + %% Time Python sync receive + Start = erlang:monotonic_time(microsecond), + {ok, Iterations} = py:eval( + Ctx, + <<"sync_receive_n(ch, n)">>, + #{<<"ch">> => Ch, <<"n">> => Iterations} + ), + End = erlang:monotonic_time(microsecond), + + TotalTime = (End - Start) / 1000000, + AvgUs = (TotalTime / Iterations) * 1000000, + Throughput = round(Iterations / TotalTime), + + io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), + + py_channel:close(Ch) + end, + Sizes + ), ok. run_async_receive_bench() -> @@ -99,43 +109,53 @@ run_async_receive_bench() -> Ctx = py:context(1), %% Define async receiver function - ok = py:exec(Ctx, <<" -import erlang -from erlang import Channel - -async def async_receive_n(ch_ref, n): - ch = Channel(ch_ref) - for _ in range(n): - await ch.async_receive() - return n - -def run_async_receive(ch_ref, n): - return erlang.run(async_receive_n(ch_ref, n)) -">>), - - lists:foreach(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<0>>, Size), - - %% Fill channel - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data) - end, lists:seq(1, Iterations)), - - %% Time Python async receive - Start = erlang:monotonic_time(microsecond), - {ok, Iterations} = py:eval(Ctx, <<"run_async_receive(ch, n)">>, - #{<<"ch">> => Ch, <<"n">> => Iterations}), - End = erlang:monotonic_time(microsecond), - - TotalTime = (End - Start) / 1000000, - AvgUs = (TotalTime / Iterations) * 1000000, - Throughput = round(Iterations / TotalTime), - - io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), - - py_channel:close(Ch) - end, Sizes), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import Channel\n" + "\n" + "async def async_receive_n(ch_ref, n):\n" + " ch = Channel(ch_ref)\n" + " for _ in range(n):\n" + " await ch.async_receive()\n" + " return n\n" + "\n" + "def run_async_receive(ch_ref, n):\n" + " return erlang.run(async_receive_n(ch_ref, n))\n" + >>), + + lists:foreach( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<0>>, Size), + + %% Fill channel + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data) + end, + lists:seq(1, Iterations) + ), + + %% Time Python async receive + Start = erlang:monotonic_time(microsecond), + {ok, Iterations} = py:eval( + Ctx, + <<"run_async_receive(ch, n)">>, + #{<<"ch">> => Ch, <<"n">> => Iterations} + ), + End = erlang:monotonic_time(microsecond), + + TotalTime = (End - Start) / 1000000, + AvgUs = (TotalTime / Iterations) * 1000000, + Throughput = round(Iterations / TotalTime), + + io:format("~8B | ~12w | ~12.2f~n", [Size, Throughput, AvgUs]), + + py_channel:close(Ch) + end, + Sizes + ), ok. run_comparison() -> @@ -148,25 +168,26 @@ run_comparison() -> Ctx = py:context(1), %% Define both functions - ok = py:exec(Ctx, <<" -import erlang -from erlang import Channel - -def sync_receive_n(ch_ref, n): - ch = Channel(ch_ref) - for _ in range(n): - ch.receive() - return n - -async def async_receive_n(ch_ref, n): - ch = Channel(ch_ref) - for _ in range(n): - await ch.async_receive() - return n - -def run_async_receive(ch_ref, n): - return erlang.run(async_receive_n(ch_ref, n)) -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import Channel\n" + "\n" + "def sync_receive_n(ch_ref, n):\n" + " ch = Channel(ch_ref)\n" + " for _ in range(n):\n" + " ch.receive()\n" + " return n\n" + "\n" + "async def async_receive_n(ch_ref, n):\n" + " ch = Channel(ch_ref)\n" + " for _ in range(n):\n" + " await ch.async_receive()\n" + " return n\n" + "\n" + "def run_async_receive(ch_ref, n):\n" + " return erlang.run(async_receive_n(ch_ref, n))\n" + >>), io:format("~15s | ~12s | ~12s~n", ["Method", "Time (ms)", "Throughput"]), io:format("~s~n", [string:copies("-", 45)]), @@ -177,8 +198,11 @@ def run_async_receive(ch_ref, n): {ok, SyncCh} = py_channel:new(), lists:foreach(fun(_) -> ok = py_channel:send(SyncCh, Data) end, lists:seq(1, Iterations)), SyncStart = erlang:monotonic_time(microsecond), - {ok, Iterations} = py:eval(Ctx, <<"sync_receive_n(ch, n)">>, - #{<<"ch">> => SyncCh, <<"n">> => Iterations}), + {ok, Iterations} = py:eval( + Ctx, + <<"sync_receive_n(ch, n)">>, + #{<<"ch">> => SyncCh, <<"n">> => Iterations} + ), SyncEnd = erlang:monotonic_time(microsecond), SyncTime = (SyncEnd - SyncStart) / 1000, SyncThroughput = round(Iterations / (SyncTime / 1000)), @@ -189,8 +213,11 @@ def run_async_receive(ch_ref, n): {ok, AsyncCh} = py_channel:new(), lists:foreach(fun(_) -> ok = py_channel:send(AsyncCh, Data) end, lists:seq(1, Iterations)), AsyncStart = erlang:monotonic_time(microsecond), - {ok, Iterations} = py:eval(Ctx, <<"run_async_receive(ch, n)">>, - #{<<"ch">> => AsyncCh, <<"n">> => Iterations}), + {ok, Iterations} = py:eval( + Ctx, + <<"run_async_receive(ch, n)">>, + #{<<"ch">> => AsyncCh, <<"n">> => Iterations} + ), AsyncEnd = erlang:monotonic_time(microsecond), AsyncTime = (AsyncEnd - AsyncStart) / 1000, AsyncThroughput = round(Iterations / (AsyncTime / 1000)), @@ -214,7 +241,8 @@ def run_async_receive(ch_ref, n): io:format("NIF baseline is ~.1fx faster than sync receive~n", [SyncTime / NifTime]), ok. -receive_all_nif(_Ch, 0) -> ok; +receive_all_nif(_Ch, 0) -> + ok; receive_all_nif(Ch, N) -> {ok, _} = py_nif:channel_try_receive(Ch), receive_all_nif(Ch, N - 1). diff --git a/examples/bench_event_loop_pool.erl b/examples/bench_event_loop_pool.erl index 3dd72b3..e0f9a8d 100644 --- a/examples/bench_event_loop_pool.erl +++ b/examples/bench_event_loop_pool.erl @@ -22,7 +22,8 @@ main(_Args) -> %% Verify pool is ready case py_event_loop_pool:get_loop() of - {ok, _} -> ok; + {ok, _} -> + ok; {error, R} -> io:format("Pool not available: ~p~n", [R]), halt(1) @@ -54,48 +55,71 @@ bench_single_vs_pool_sequential(N) -> %% Single event loop {T1, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop:await(Ref) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + Ref = py_event_loop:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop:await(Ref) + end, + lists:seq(1, N) + ) end), %% Pool (should be similar since same caller = same loop) {T2, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop_pool:await(Ref) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop_pool:await(Ref) + end, + lists:seq(1, N) + ) end), - io:format(" py_event_loop: ~.2f ms (~p tasks/sec)~n", - [T1/1000, round(N / (T1/1000000))]), - io:format(" py_event_loop_pool: ~.2f ms (~p tasks/sec)~n~n", - [T2/1000, round(N / (T2/1000000))]). + io:format( + " py_event_loop: ~.2f ms (~p tasks/sec)~n", + [T1 / 1000, round(N / (T1 / 1000000))] + ), + io:format( + " py_event_loop_pool: ~.2f ms (~p tasks/sec)~n~n", + [T2 / 1000, round(N / (T2 / 1000000))] + ). %% Pool with concurrent callers (each gets own loop = parallel) bench_pool_concurrent(NumProcs, TasksPerProc) -> TotalTasks = NumProcs * TasksPerProc, io:format("Benchmark: Concurrent callers via pool~n"), - io:format(" Processes: ~p, Tasks/process: ~p, Total: ~p~n", - [NumProcs, TasksPerProc, TotalTasks]), + io:format( + " Processes: ~p, Tasks/process: ~p, Total: ~p~n", + [NumProcs, TasksPerProc, TotalTasks] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop_pool:await(Ref) - end, lists:seq(1, TasksPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop_pool:await(Ref) + end, + lists:seq(1, TasksPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), - io:format(" Total time: ~.2f ms~n", [Time/1000]), - io:format(" Throughput: ~p tasks/sec~n~n", [round(TotalTasks / (Time/1000000))]). + io:format(" Total time: ~.2f ms~n", [Time / 1000]), + io:format(" Throughput: ~p tasks/sec~n~n", [round(TotalTasks / (Time / 1000000))]). %% High throughput test bench_pool_throughput(N) -> @@ -104,10 +128,12 @@ bench_pool_throughput(N) -> %% Submit all tasks first, then await all {Time, _} = timer:tc(fun() -> - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I)]) - || I <- lists:seq(1, N)], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I)]) + || I <- lists:seq(1, N) + ], [py_event_loop_pool:await(Ref) || Ref <- Refs] end), - io:format(" Total time: ~.2f ms~n", [Time/1000]), - io:format(" Throughput: ~p tasks/sec~n~n", [round(N / (Time/1000000))]). + io:format(" Total time: ~.2f ms~n", [Time / 1000]), + io:format(" Throughput: ~p tasks/sec~n~n", [round(N / (Time / 1000000))]). diff --git a/examples/bench_owngil.erl b/examples/bench_owngil.erl index fd77be9..9049913 100644 --- a/examples/bench_owngil.erl +++ b/examples/bench_owngil.erl @@ -55,24 +55,27 @@ bench_single_latency() -> io:format(" ~-15s ~10s ~12s~n", ["Mode", "us/call", "calls/sec"]), io:format(" ~-15s ~10s ~12s~n", ["----", "-------", "---------"]), - lists:foreach(fun({Label, Mode}) -> - {ok, Ctx} = py_context:start_link(1, Mode), - - %% Warmup - [py_context:call(Ctx, math, sqrt, [N], #{}) || N <- lists:seq(1, 100)], - - %% Benchmark - Iterations = 1000, - Start = erlang:monotonic_time(microsecond), - [py_context:call(Ctx, math, sqrt, [N], #{}) || N <- lists:seq(1, Iterations)], - Elapsed = erlang:monotonic_time(microsecond) - Start, - - UsPerCall = Elapsed / Iterations, - CallsPerSec = round(Iterations * 1000000 / Elapsed), - io:format(" ~-15s ~10.1f ~12w~n", [Label, UsPerCall, CallsPerSec]), - - py_context:stop(Ctx) - end, [{worker, worker}, {owngil, owngil}]), + lists:foreach( + fun({Label, Mode}) -> + {ok, Ctx} = py_context:start_link(1, Mode), + + %% Warmup + [py_context:call(Ctx, math, sqrt, [N], #{}) || N <- lists:seq(1, 100)], + + %% Benchmark + Iterations = 1000, + Start = erlang:monotonic_time(microsecond), + [py_context:call(Ctx, math, sqrt, [N], #{}) || N <- lists:seq(1, Iterations)], + Elapsed = erlang:monotonic_time(microsecond) - Start, + + UsPerCall = Elapsed / Iterations, + CallsPerSec = round(Iterations * 1000000 / Elapsed), + io:format(" ~-15s ~10.1f ~12w~n", [Label, UsPerCall, CallsPerSec]), + + py_context:stop(Ctx) + end, + [{worker, worker}, {owngil, owngil}] + ), io:format("~n"). %% ============================================================================ @@ -88,33 +91,49 @@ bench_parallel_throughput() -> CallsPerContext = 250, TotalCalls = NumContexts * CallsPerContext, - lists:foreach(fun({Label, Mode}) -> - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, Mode), - Ctx - end || N <- lists:seq(1, NumContexts)], - - %% Warmup - [py_context:call(Ctx, math, sqrt, [16], #{}) || Ctx <- Contexts], - - %% Parallel benchmark - Parent = self(), - Start = erlang:monotonic_time(millisecond), - - Pids = [spawn(fun() -> - [py_context:call(Ctx, math, sqrt, [N], #{}) - || N <- lists:seq(1, CallsPerContext)], - Parent ! {done, self()} - end) || Ctx <- Contexts], - - [receive {done, Pid} -> ok end || Pid <- Pids], - - Elapsed = erlang:monotonic_time(millisecond) - Start, - CallsPerSec = round(TotalCalls * 1000 / max(1, Elapsed)), - io:format(" ~-15s ~10w ~12w~n", [Label, Elapsed, CallsPerSec]), - - [py_context:stop(Ctx) || Ctx <- Contexts] - end, [{worker, worker}, {owngil, owngil}]), + lists:foreach( + fun({Label, Mode}) -> + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, Mode), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], + + %% Warmup + [py_context:call(Ctx, math, sqrt, [16], #{}) || Ctx <- Contexts], + + %% Parallel benchmark + Parent = self(), + Start = erlang:monotonic_time(millisecond), + + Pids = [ + spawn(fun() -> + [ + py_context:call(Ctx, math, sqrt, [N], #{}) + || N <- lists:seq(1, CallsPerContext) + ], + Parent ! {done, self()} + end) + || Ctx <- Contexts + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ], + + Elapsed = erlang:monotonic_time(millisecond) - Start, + CallsPerSec = round(TotalCalls * 1000 / max(1, Elapsed)), + io:format(" ~-15s ~10w ~12w~n", [Label, Elapsed, CallsPerSec]), + + [py_context:stop(Ctx) || Ctx <- Contexts] + end, + [{worker, worker}, {owngil, owngil}] + ), io:format("~n"). %% ============================================================================ @@ -129,32 +148,46 @@ bench_cpu_speedup() -> NumContexts = 4, Code = <<"sum(range(500000))">>, - lists:foreach(fun({Label, Mode}) -> - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, Mode), - Ctx - end || N <- lists:seq(1, NumContexts)], - - %% Sequential execution - SeqStart = erlang:monotonic_time(millisecond), - [py_context:eval(Ctx, Code, #{}) || Ctx <- Contexts], - SeqTime = erlang:monotonic_time(millisecond) - SeqStart, - - %% Parallel execution - Parent = self(), - ParStart = erlang:monotonic_time(millisecond), - Pids = [spawn(fun() -> - py_context:eval(Ctx, Code, #{}), - Parent ! {done, self()} - end) || Ctx <- Contexts], - [receive {done, Pid} -> ok end || Pid <- Pids], - ParTime = erlang:monotonic_time(millisecond) - ParStart, - - Speedup = SeqTime / max(1, ParTime), - io:format(" ~-15s ~10w ~10w ~10.2fx~n", [Label, SeqTime, ParTime, Speedup]), - - [py_context:stop(Ctx) || Ctx <- Contexts] - end, [{worker, worker}, {owngil, owngil}]), + lists:foreach( + fun({Label, Mode}) -> + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, Mode), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], + + %% Sequential execution + SeqStart = erlang:monotonic_time(millisecond), + [py_context:eval(Ctx, Code, #{}) || Ctx <- Contexts], + SeqTime = erlang:monotonic_time(millisecond) - SeqStart, + + %% Parallel execution + Parent = self(), + ParStart = erlang:monotonic_time(millisecond), + Pids = [ + spawn(fun() -> + py_context:eval(Ctx, Code, #{}), + Parent ! {done, self()} + end) + || Ctx <- Contexts + ], + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ], + ParTime = erlang:monotonic_time(millisecond) - ParStart, + + Speedup = SeqTime / max(1, ParTime), + io:format(" ~-15s ~10w ~10w ~10.2fx~n", [Label, SeqTime, ParTime, Speedup]), + + [py_context:stop(Ctx) || Ctx <- Contexts] + end, + [{worker, worker}, {owngil, owngil}] + ), io:format("~n"), io:format("Notes:~n"), diff --git a/examples/bench_owngil_pool.erl b/examples/bench_owngil_pool.erl index e9285d6..8789abe 100755 --- a/examples/bench_owngil_pool.erl +++ b/examples/bench_owngil_pool.erl @@ -80,15 +80,18 @@ bench_sequential(Label, N) -> io:format(" ~s Sequential (~p calls): ", [Label, N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop_pool:await(Ref) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop_pool:await(Ref) + end, + lists:seq(1, N) + ) end), Rate = round(N / (Time / 1000000)), - io:format("~.1f ms (~p calls/sec)~n", [Time/1000, Rate]), - #{time_ms => Time/1000, rate => Rate}. + io:format("~.1f ms (~p calls/sec)~n", [Time / 1000, Rate]), + #{time_ms => Time / 1000, rate => Rate}. %% Concurrent callers (each process gets own worker in OWN_GIL mode) bench_concurrent(Label, NumProcs, TasksPerProc, _Complexity) -> @@ -97,20 +100,31 @@ bench_concurrent(Label, NumProcs, TasksPerProc, _Complexity) -> Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), - {ok, _} = py_event_loop_pool:await(Ref) - end, lists:seq(1, TasksPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + Ref = py_event_loop_pool:create_task(math, sqrt, [float(I)]), + {ok, _} = py_event_loop_pool:await(Ref) + end, + lists:seq(1, TasksPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), Rate = round(TotalTasks / (Time / 1000000)), - io:format("~.1f ms (~p calls/sec)~n", [Time/1000, Rate]), - #{time_ms => Time/1000, rate => Rate, total => TotalTasks}. + io:format("~.1f ms (~p calls/sec)~n", [Time / 1000, Rate]), + #{time_ms => Time / 1000, rate => Rate, total => TotalTasks}. %% CPU-bound parallel tasks (shows true GIL parallelism) bench_parallel_cpu(Label, NumProcs) -> @@ -118,21 +132,30 @@ bench_parallel_cpu(Label, NumProcs) -> Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - %% Use time.sleep as a proxy for CPU work - %% In OWN_GIL mode, these run truly in parallel - Ref = py_event_loop_pool:create_task(time, sleep, [0.1]), - Result = py_event_loop_pool:await(Ref, 5000), - Parent ! {done, self(), Result} - end) || _ <- lists:seq(1, NumProcs)], - - Results = [receive {done, Pid, R} -> R after 5000 -> timeout end || Pid <- Pids], + Pids = [ + spawn_link(fun() -> + %% Use time.sleep as a proxy for CPU work + %% In OWN_GIL mode, these run truly in parallel + Ref = py_event_loop_pool:create_task(time, sleep, [0.1]), + Result = py_event_loop_pool:await(Ref, 5000), + Parent ! {done, self(), Result} + end) + || _ <- lists:seq(1, NumProcs) + ], + + Results = [ + receive + {done, Pid, R} -> R + after 5000 -> timeout + end + || Pid <- Pids + ], %% Count successes length([X || {ok, _} = X <- Results]) end), - io:format("~.1f ms~n", [Time/1000]), - #{time_ms => Time/1000, num_procs => NumProcs}. + io:format("~.1f ms~n", [Time / 1000]), + #{time_ms => Time / 1000, num_procs => NumProcs}. print_comparison(Regular, Owngil) -> io:format("~n"), @@ -141,38 +164,48 @@ print_comparison(Regular, Owngil) -> io:format("================================================================~n~n"), io:format("~-30s ~12s ~12s ~10s~n", ["Benchmark", "Regular", "OWN_GIL", "Speedup"]), - io:format("~-30s ~12s ~12s ~10s~n", [string:copies("-", 30), - string:copies("-", 12), - string:copies("-", 12), - string:copies("-", 10)]), + io:format("~-30s ~12s ~12s ~10s~n", [ + string:copies("-", 30), + string:copies("-", 12), + string:copies("-", 12), + string:copies("-", 10) + ]), %% Sequential (should be similar) SeqR = maps:get(rate, maps:get(sequential, Regular)), SeqO = maps:get(rate, maps:get(sequential, Owngil)), SeqSpeedup = SeqO / max(1, SeqR), - io:format("~-30s ~10w/s ~10w/s ~8.2fx~n", - ["Sequential (single caller)", SeqR, SeqO, SeqSpeedup]), + io:format( + "~-30s ~10w/s ~10w/s ~8.2fx~n", + ["Sequential (single caller)", SeqR, SeqO, SeqSpeedup] + ), %% Concurrent light CL_R = maps:get(rate, maps:get(concurrent_light, Regular)), CL_O = maps:get(rate, maps:get(concurrent_light, Owngil)), CL_Speedup = CL_O / max(1, CL_R), - io:format("~-30s ~10w/s ~10w/s ~8.2fx~n", - ["Concurrent (4 procs x 100)", CL_R, CL_O, CL_Speedup]), + io:format( + "~-30s ~10w/s ~10w/s ~8.2fx~n", + ["Concurrent (4 procs x 100)", CL_R, CL_O, CL_Speedup] + ), %% Concurrent medium CM_R = maps:get(rate, maps:get(concurrent_medium, Regular)), CM_O = maps:get(rate, maps:get(concurrent_medium, Owngil)), CM_Speedup = CM_O / max(1, CM_R), - io:format("~-30s ~10w/s ~10w/s ~8.2fx~n", - ["Concurrent (8 procs x 50)", CM_R, CM_O, CM_Speedup]), + io:format( + "~-30s ~10w/s ~10w/s ~8.2fx~n", + ["Concurrent (8 procs x 50)", CM_R, CM_O, CM_Speedup] + ), %% CPU-bound CPU_R = maps:get(time_ms, maps:get(parallel_cpu, Regular)), CPU_O = maps:get(time_ms, maps:get(parallel_cpu, Owngil)), CPU_Speedup = CPU_R / max(1, CPU_O), - io:format("~-30s ~10.1f ms ~10.1f ms ~8.2fx~n", - ["CPU-bound (4 parallel)", CPU_R, CPU_O, CPU_Speedup]), + io:format( + "~-30s ~10.1f ms ~10.1f ms ~8.2fx~n", + ["CPU-bound (4 parallel)", CPU_R, CPU_O, CPU_Speedup] + ), io:format("~n"), io:format("Notes:~n"), diff --git a/examples/bench_py_buffer.erl b/examples/bench_py_buffer.erl index 6e3f7e5..b95034f 100644 --- a/examples/bench_py_buffer.erl +++ b/examples/bench_py_buffer.erl @@ -44,30 +44,40 @@ run_write_throughput_bench() -> Sizes = [64, 256, 1024, 4096, 16384], - io:format("~8s | ~12s | ~12s~n", - ["Size", "Writes/sec", "MB/sec"]), + io:format( + "~8s | ~12s | ~12s~n", + ["Size", "Writes/sec", "MB/sec"] + ), io:format("~s~n", [string:copies("-", 38)]), - lists:foreach(fun(Size) -> - {ok, Buf} = py_buffer:new(), - Data = binary:copy(<<0>>, Size), - Iterations = 1000, - - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_buffer:write(Buf, Data) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - TotalTime = (End - Start) / 1000000, - WriteRate = Iterations / TotalTime, - MBPerSec = (Iterations * Size) / TotalTime / 1048576, - - io:format("~8B | ~12w | ~12.2f~n", - [Size, round(WriteRate), MBPerSec]), - - py_buffer:close(Buf) - end, Sizes), + lists:foreach( + fun(Size) -> + {ok, Buf} = py_buffer:new(), + Data = binary:copy(<<0>>, Size), + Iterations = 1000, + + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_buffer:write(Buf, Data) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + TotalTime = (End - Start) / 1000000, + WriteRate = Iterations / TotalTime, + MBPerSec = (Iterations * Size) / TotalTime / 1048576, + + io:format( + "~8B | ~12w | ~12.2f~n", + [Size, round(WriteRate), MBPerSec] + ), + + py_buffer:close(Buf) + end, + Sizes + ), ok. run_read_throughput_bench() -> @@ -75,62 +85,76 @@ run_read_throughput_bench() -> io:format("Reads per batch: 1000~n~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import time - -def bench_buffer_reads(buf, size, iterations): - '''Read from buffer and measure throughput.''' - # Read all data - start = time.perf_counter() - total_read = 0 - while True: - data = buf.read(size) - if not data: - break - total_read += len(data) - elapsed = time.perf_counter() - start - - if elapsed > 0: - reads_per_sec = (total_read / size) / elapsed - mb_per_sec = total_read / elapsed / 1048576 - else: - reads_per_sec = 0 - mb_per_sec = 0 - - return { - 'total_bytes': total_read, - 'reads_per_sec': reads_per_sec, - 'mb_per_sec': mb_per_sec, - } -">>), + ok = py:exec(Ctx, << + "\n" + "import time\n" + "\n" + "def bench_buffer_reads(buf, size, iterations):\n" + " '''Read from buffer and measure throughput.'''\n" + " # Read all data\n" + " start = time.perf_counter()\n" + " total_read = 0\n" + " while True:\n" + " data = buf.read(size)\n" + " if not data:\n" + " break\n" + " total_read += len(data)\n" + " elapsed = time.perf_counter() - start\n" + "\n" + " if elapsed > 0:\n" + " reads_per_sec = (total_read / size) / elapsed\n" + " mb_per_sec = total_read / elapsed / 1048576\n" + " else:\n" + " reads_per_sec = 0\n" + " mb_per_sec = 0\n" + "\n" + " return {\n" + " 'total_bytes': total_read,\n" + " 'reads_per_sec': reads_per_sec,\n" + " 'mb_per_sec': mb_per_sec,\n" + " }\n" + >>), Sizes = [64, 256, 1024, 4096, 16384], - io:format("~8s | ~12s | ~12s~n", - ["Size", "Reads/sec", "MB/sec"]), + io:format( + "~8s | ~12s | ~12s~n", + ["Size", "Reads/sec", "MB/sec"] + ), io:format("~s~n", [string:copies("-", 38)]), - lists:foreach(fun(Size) -> - Iterations = 1000, - {ok, Buf} = py_buffer:new(Size * Iterations), - Data = binary:copy(<<0>>, Size), - - %% Fill the buffer - lists:foreach(fun(_) -> - ok = py_buffer:write(Buf, Data) - end, lists:seq(1, Iterations)), - ok = py_buffer:close(Buf), - - %% Measure Python read performance - {ok, Result} = py:eval(Ctx, <<"bench_buffer_reads(buf, size, iterations)">>, - #{<<"buf">> => Buf, <<"size">> => Size, <<"iterations">> => Iterations}), - - ReadsPerSec = maps:get(<<"reads_per_sec">>, Result), - MBPerSec = maps:get(<<"mb_per_sec">>, Result), + lists:foreach( + fun(Size) -> + Iterations = 1000, + {ok, Buf} = py_buffer:new(Size * Iterations), + Data = binary:copy(<<0>>, Size), + + %% Fill the buffer + lists:foreach( + fun(_) -> + ok = py_buffer:write(Buf, Data) + end, + lists:seq(1, Iterations) + ), + ok = py_buffer:close(Buf), - io:format("~8B | ~12w | ~12.2f~n", - [Size, round(ReadsPerSec), MBPerSec]) - end, Sizes), + %% Measure Python read performance + {ok, Result} = py:eval( + Ctx, + <<"bench_buffer_reads(buf, size, iterations)">>, + #{<<"buf">> => Buf, <<"size">> => Size, <<"iterations">> => Iterations} + ), + + ReadsPerSec = maps:get(<<"reads_per_sec">>, Result), + MBPerSec = maps:get(<<"mb_per_sec">>, Result), + + io:format( + "~8B | ~12w | ~12.2f~n", + [Size, round(ReadsPerSec), MBPerSec] + ) + end, + Sizes + ), ok. run_buffer_vs_channel_bench() -> @@ -139,57 +163,71 @@ run_buffer_vs_channel_bench() -> io:format("Iterations: 1000~n~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang.channel import Channel - -def read_buffer_all(buf): - '''Read entire buffer.''' - return buf.read() - -def recv_channel(ch_ref): - '''Receive from channel.''' - ch = Channel(ch_ref) - return ch.try_receive() -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang.channel import Channel\n" + "\n" + "def read_buffer_all(buf):\n" + " '''Read entire buffer.'''\n" + " return buf.read()\n" + "\n" + "def recv_channel(ch_ref):\n" + " '''Receive from channel.'''\n" + " ch = Channel(ch_ref)\n" + " return ch.try_receive()\n" + >>), Sizes = [64, 256, 1024, 4096, 16384], - io:format("~8s | ~14s | ~14s | ~8s~n", - ["Size", "Buffer (ops/s)", "Channel (ops/s)", "Ratio"]), + io:format( + "~8s | ~14s | ~14s | ~8s~n", + ["Size", "Buffer (ops/s)", "Channel (ops/s)", "Ratio"] + ), io:format("~s~n", [string:copies("-", 52)]), - lists:foreach(fun(Size) -> - Data = binary:copy(<<0>>, Size), - Iterations = 1000, - - %% Benchmark PyBuffer: Erlang write -> Python read - BufStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - {ok, Buf} = py_buffer:new(Size), - ok = py_buffer:write(Buf, Data), - ok = py_buffer:close(Buf), - {ok, _} = py:eval(Ctx, <<"read_buffer_all(buf)">>, #{<<"buf">> => Buf}) - end, lists:seq(1, Iterations)), - BufEnd = erlang:monotonic_time(microsecond), - BufTime = (BufEnd - BufStart) / 1000000, - BufOpsPerSec = Iterations / BufTime, - - %% Benchmark Channel: Erlang send -> Python receive - {ok, Ch} = py_channel:new(), - ChanStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py:eval(Ctx, <<"recv_channel(ch)">>, #{<<"ch">> => Ch}) - end, lists:seq(1, Iterations)), - ChanEnd = erlang:monotonic_time(microsecond), - ChanTime = (ChanEnd - ChanStart) / 1000000, - ChanOpsPerSec = Iterations / ChanTime, - py_channel:close(Ch), - - Ratio = BufOpsPerSec / ChanOpsPerSec, - io:format("~8B | ~14w | ~14w | ~.2fx~n", - [Size, round(BufOpsPerSec), round(ChanOpsPerSec), Ratio]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = binary:copy(<<0>>, Size), + Iterations = 1000, + + %% Benchmark PyBuffer: Erlang write -> Python read + BufStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + {ok, Buf} = py_buffer:new(Size), + ok = py_buffer:write(Buf, Data), + ok = py_buffer:close(Buf), + {ok, _} = py:eval(Ctx, <<"read_buffer_all(buf)">>, #{<<"buf">> => Buf}) + end, + lists:seq(1, Iterations) + ), + BufEnd = erlang:monotonic_time(microsecond), + BufTime = (BufEnd - BufStart) / 1000000, + BufOpsPerSec = Iterations / BufTime, + + %% Benchmark Channel: Erlang send -> Python receive + {ok, Ch} = py_channel:new(), + ChanStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py:eval(Ctx, <<"recv_channel(ch)">>, #{<<"ch">> => Ch}) + end, + lists:seq(1, Iterations) + ), + ChanEnd = erlang:monotonic_time(microsecond), + ChanTime = (ChanEnd - ChanStart) / 1000000, + ChanOpsPerSec = Iterations / ChanTime, + py_channel:close(Ch), + + Ratio = BufOpsPerSec / ChanOpsPerSec, + io:format( + "~8B | ~14w | ~14w | ~.2fx~n", + [Size, round(BufOpsPerSec), round(ChanOpsPerSec), Ratio] + ) + end, + Sizes + ), ok. run_streaming_bench() -> @@ -197,69 +235,87 @@ run_streaming_bench() -> io:format("Total data: 1MB, varying chunk sizes~n~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang.channel import Channel - -def stream_read_buffer(buf): - '''Stream read entire buffer.''' - total = 0 - while True: - chunk = buf.read(8192) # 8KB reads - if not chunk: - break - total += len(chunk) - return total - -def stream_recv_channel(ch_ref, num_chunks): - '''Stream receive from channel.''' - ch = Channel(ch_ref) - total = 0 - for _ in range(num_chunks): - msg = ch.try_receive() - if msg is None: - break - total += len(msg) - return total -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang.channel import Channel\n" + "\n" + "def stream_read_buffer(buf):\n" + " '''Stream read entire buffer.'''\n" + " total = 0\n" + " while True:\n" + " chunk = buf.read(8192) # 8KB reads\n" + " if not chunk:\n" + " break\n" + " total += len(chunk)\n" + " return total\n" + "\n" + "def stream_recv_channel(ch_ref, num_chunks):\n" + " '''Stream receive from channel.'''\n" + " ch = Channel(ch_ref)\n" + " total = 0\n" + " for _ in range(num_chunks):\n" + " msg = ch.try_receive()\n" + " if msg is None:\n" + " break\n" + " total += len(msg)\n" + " return total\n" + >>), ChunkSizes = [256, 1024, 4096, 16384, 65536], - TotalBytes = 1048576, % 1MB + % 1MB + TotalBytes = 1048576, - io:format("~10s | ~14s | ~14s | ~8s~n", - ["Chunk", "Buffer (MB/s)", "Channel (MB/s)", "Ratio"]), + io:format( + "~10s | ~14s | ~14s | ~8s~n", + ["Chunk", "Buffer (MB/s)", "Channel (MB/s)", "Ratio"] + ), io:format("~s~n", [string:copies("-", 54)]), - lists:foreach(fun(ChunkSize) -> - NumChunks = TotalBytes div ChunkSize, - Chunk = binary:copy(<<0>>, ChunkSize), - - %% Benchmark PyBuffer streaming (Erlang write -> Python read) - {ok, Buf} = py_buffer:new(TotalBytes), - BufStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_buffer:write(Buf, Chunk) - end, lists:seq(1, NumChunks)), - ok = py_buffer:close(Buf), - {ok, _} = py:eval(Ctx, <<"stream_read_buffer(buf)">>, #{<<"buf">> => Buf}), - BufEnd = erlang:monotonic_time(microsecond), - BufTime = (BufEnd - BufStart) / 1000000, - BufMBPerSec = (TotalBytes / 1048576) / BufTime, - - %% Benchmark Channel streaming (Erlang send -> Python receive) - {ok, Ch} = py_channel:new(), - ChanStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Chunk) - end, lists:seq(1, NumChunks)), - {ok, _} = py:eval(Ctx, <<"stream_recv_channel(ch, num_chunks)">>, - #{<<"ch">> => Ch, <<"num_chunks">> => NumChunks}), - ChanEnd = erlang:monotonic_time(microsecond), - ChanTime = (ChanEnd - ChanStart) / 1000000, - ChanMBPerSec = (TotalBytes / 1048576) / ChanTime, - py_channel:close(Ch), - - Ratio = BufMBPerSec / ChanMBPerSec, - io:format("~10B | ~14.2f | ~14.2f | ~.2fx~n", - [ChunkSize, BufMBPerSec, ChanMBPerSec, Ratio]) - end, ChunkSizes), + lists:foreach( + fun(ChunkSize) -> + NumChunks = TotalBytes div ChunkSize, + Chunk = binary:copy(<<0>>, ChunkSize), + + %% Benchmark PyBuffer streaming (Erlang write -> Python read) + {ok, Buf} = py_buffer:new(TotalBytes), + BufStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_buffer:write(Buf, Chunk) + end, + lists:seq(1, NumChunks) + ), + ok = py_buffer:close(Buf), + {ok, _} = py:eval(Ctx, <<"stream_read_buffer(buf)">>, #{<<"buf">> => Buf}), + BufEnd = erlang:monotonic_time(microsecond), + BufTime = (BufEnd - BufStart) / 1000000, + BufMBPerSec = (TotalBytes / 1048576) / BufTime, + + %% Benchmark Channel streaming (Erlang send -> Python receive) + {ok, Ch} = py_channel:new(), + ChanStart = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Chunk) + end, + lists:seq(1, NumChunks) + ), + {ok, _} = py:eval( + Ctx, + <<"stream_recv_channel(ch, num_chunks)">>, + #{<<"ch">> => Ch, <<"num_chunks">> => NumChunks} + ), + ChanEnd = erlang:monotonic_time(microsecond), + ChanTime = (ChanEnd - ChanStart) / 1000000, + ChanMBPerSec = (TotalBytes / 1048576) / ChanTime, + py_channel:close(Ch), + + Ratio = BufMBPerSec / ChanMBPerSec, + io:format( + "~10B | ~14.2f | ~14.2f | ~.2fx~n", + [ChunkSize, BufMBPerSec, ChanMBPerSec, Ratio] + ) + end, + ChunkSizes + ), ok. diff --git a/examples/bench_reactor_buffer.erl b/examples/bench_reactor_buffer.erl index 4bb66ef..6124a06 100644 --- a/examples/bench_reactor_buffer.erl +++ b/examples/bench_reactor_buffer.erl @@ -40,159 +40,178 @@ run_buffer_operations_bench() -> io:format("~n--- Buffer Operations Benchmark ---~n"), io:format("Iterations: 10000~n~n"), - Code = <<" -import time -import erlang - -def run_buffer_ops_bench(iterations=10000): - results = {} - sizes = [64, 256, 1024, 4096, 16384, 65536] - - for size in sizes: - test_data = b'X' * size - buf = erlang.ReactorBuffer._test_create(test_data) - regular_bytes = bytes(test_data) - - # Benchmark: extend bytearray (uses buffer protocol) - start = time.perf_counter() - for _ in range(iterations): - ba = bytearray() - ba.extend(buf) - extend_buf_time = time.perf_counter() - start - - start = time.perf_counter() - for _ in range(iterations): - ba = bytearray() - ba.extend(regular_bytes) - extend_bytes_time = time.perf_counter() - start - - # Benchmark: startswith - prefix = test_data[:10] - start = time.perf_counter() - for _ in range(iterations): - _ = buf.startswith(prefix) - startswith_buf_time = time.perf_counter() - start - - start = time.perf_counter() - for _ in range(iterations): - _ = regular_bytes.startswith(prefix) - startswith_bytes_time = time.perf_counter() - start - - results[size] = { - 'extend_buf': extend_buf_time * 1000, - 'extend_bytes': extend_bytes_time * 1000, - 'startswith_buf': startswith_buf_time * 1000, - 'startswith_bytes': startswith_bytes_time * 1000, - } - - return results - -_buffer_ops_results = run_buffer_ops_bench() -">>, + Code = << + "\n" + "import time\n" + "import erlang\n" + "\n" + "def run_buffer_ops_bench(iterations=10000):\n" + " results = {}\n" + " sizes = [64, 256, 1024, 4096, 16384, 65536]\n" + "\n" + " for size in sizes:\n" + " test_data = b'X' * size\n" + " buf = erlang.ReactorBuffer._test_create(test_data)\n" + " regular_bytes = bytes(test_data)\n" + "\n" + " # Benchmark: extend bytearray (uses buffer protocol)\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " ba = bytearray()\n" + " ba.extend(buf)\n" + " extend_buf_time = time.perf_counter() - start\n" + "\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " ba = bytearray()\n" + " ba.extend(regular_bytes)\n" + " extend_bytes_time = time.perf_counter() - start\n" + "\n" + " # Benchmark: startswith\n" + " prefix = test_data[:10]\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " _ = buf.startswith(prefix)\n" + " startswith_buf_time = time.perf_counter() - start\n" + "\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " _ = regular_bytes.startswith(prefix)\n" + " startswith_bytes_time = time.perf_counter() - start\n" + "\n" + " results[size] = {\n" + " 'extend_buf': extend_buf_time * 1000,\n" + " 'extend_bytes': extend_bytes_time * 1000,\n" + " 'startswith_buf': startswith_buf_time * 1000,\n" + " 'startswith_bytes': startswith_bytes_time * 1000,\n" + " }\n" + "\n" + " return results\n" + "\n" + "_buffer_ops_results = run_buffer_ops_bench()\n" + >>, ok = py:exec(Code), {ok, Results} = py:eval(<<"_buffer_ops_results">>), - io:format("~8s | ~12s | ~12s | ~12s | ~8s~n", - ["Size", "Operation", "Buffer (ms)", "Bytes (ms)", "Ratio"]), + io:format( + "~8s | ~12s | ~12s | ~12s | ~8s~n", + ["Size", "Operation", "Buffer (ms)", "Bytes (ms)", "Ratio"] + ), io:format("~s~n", [string:copies("-", 60)]), Sizes = [64, 256, 1024, 4096, 16384, 65536], - lists:foreach(fun(Size) -> - Data = maps:get(Size, Results), - - ExtBuf = maps:get(<<"extend_buf">>, Data), - ExtBytes = maps:get(<<"extend_bytes">>, Data), - ExtRatio = ExtBytes / max(ExtBuf, 0.001), - - SwBuf = maps:get(<<"startswith_buf">>, Data), - SwBytes = maps:get(<<"startswith_bytes">>, Data), - SwRatio = SwBytes / max(SwBuf, 0.001), - - io:format("~8B | ~12s | ~12.3f | ~12.3f | ~.2f x~n", - [Size, "extend", ExtBuf, ExtBytes, ExtRatio]), - io:format("~8s | ~12s | ~12.3f | ~12.3f | ~.2f x~n", - ["", "startswith", SwBuf, SwBytes, SwRatio]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = maps:get(Size, Results), + + ExtBuf = maps:get(<<"extend_buf">>, Data), + ExtBytes = maps:get(<<"extend_bytes">>, Data), + ExtRatio = ExtBytes / max(ExtBuf, 0.001), + + SwBuf = maps:get(<<"startswith_buf">>, Data), + SwBytes = maps:get(<<"startswith_bytes">>, Data), + SwRatio = SwBytes / max(SwBuf, 0.001), + + io:format( + "~8B | ~12s | ~12.3f | ~12.3f | ~.2f x~n", + [Size, "extend", ExtBuf, ExtBytes, ExtRatio] + ), + io:format( + "~8s | ~12s | ~12.3f | ~12.3f | ~.2f x~n", + ["", "startswith", SwBuf, SwBytes, SwRatio] + ) + end, + Sizes + ), ok. run_protocol_simulation_bench() -> io:format("~n--- Protocol Simulation Benchmark ---~n"), io:format("Iterations: 5000~n~n"), - Code = <<" -import time -import erlang - -def run_protocol_sim_bench(iterations=5000): - results = {} - sizes = [64, 256, 1024, 4096, 16384, 65536] - - for size in sizes: - test_data = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n' + b'X' * (size - 40) - test_data = test_data[:size] - - buf = erlang.ReactorBuffer._test_create(test_data) - regular_bytes = bytes(test_data) - - def parse_request(data): - if data.startswith(b'GET'): - method = 'GET' - elif data.startswith(b'POST'): - method = 'POST' - else: - method = 'OTHER' - pos = data.find(b'\\r\\n\\r\\n') - write_buf = bytearray() - write_buf.extend(data) - return len(write_buf) - - # Benchmark with ReactorBuffer - start = time.perf_counter() - for _ in range(iterations): - _ = parse_request(buf) - buf_time = time.perf_counter() - start - - # Benchmark with regular bytes - start = time.perf_counter() - for _ in range(iterations): - _ = parse_request(regular_bytes) - bytes_time = time.perf_counter() - start - - results[size] = { - 'buffer_ops_per_sec': iterations / buf_time, - 'bytes_ops_per_sec': iterations / bytes_time, - } - - return results - -_protocol_sim_results = run_protocol_sim_bench() -">>, + Code = << + "\n" + "import time\n" + "import erlang\n" + "\n" + "def run_protocol_sim_bench(iterations=5000):\n" + " results = {}\n" + " sizes = [64, 256, 1024, 4096, 16384, 65536]\n" + "\n" + " for size in sizes:\n" + " test_data = b'GET / HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n' + b'X' * (size - 40)\n" + " test_data = test_data[:size]\n" + "\n" + " buf = erlang.ReactorBuffer._test_create(test_data)\n" + " regular_bytes = bytes(test_data)\n" + "\n" + " def parse_request(data):\n" + " if data.startswith(b'GET'):\n" + " method = 'GET'\n" + " elif data.startswith(b'POST'):\n" + " method = 'POST'\n" + " else:\n" + " method = 'OTHER'\n" + " pos = data.find(b'\\r\\n\\r\\n')\n" + " write_buf = bytearray()\n" + " write_buf.extend(data)\n" + " return len(write_buf)\n" + "\n" + " # Benchmark with ReactorBuffer\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " _ = parse_request(buf)\n" + " buf_time = time.perf_counter() - start\n" + "\n" + " # Benchmark with regular bytes\n" + " start = time.perf_counter()\n" + " for _ in range(iterations):\n" + " _ = parse_request(regular_bytes)\n" + " bytes_time = time.perf_counter() - start\n" + "\n" + " results[size] = {\n" + " 'buffer_ops_per_sec': iterations / buf_time,\n" + " 'bytes_ops_per_sec': iterations / bytes_time,\n" + " }\n" + "\n" + " return results\n" + "\n" + "_protocol_sim_results = run_protocol_sim_bench()\n" + >>, ok = py:exec(Code), {ok, Results} = py:eval(<<"_protocol_sim_results">>), - io:format("~8s | ~14s | ~14s | ~8s~n", - ["Size", "Buffer (ops/s)", "Bytes (ops/s)", "Speedup"]), + io:format( + "~8s | ~14s | ~14s | ~8s~n", + ["Size", "Buffer (ops/s)", "Bytes (ops/s)", "Speedup"] + ), io:format("~s~n", [string:copies("-", 52)]), Sizes = [64, 256, 1024, 4096, 16384, 65536], - SpeedupsList = lists:map(fun(Size) -> - Data = maps:get(Size, Results), - - BufOps = maps:get(<<"buffer_ops_per_sec">>, Data), - BytesOps = maps:get(<<"bytes_ops_per_sec">>, Data), - Speedup = BufOps / max(BytesOps, 1), - - io:format("~8B | ~14w | ~14w | ~.2f~n", - [Size, round(BufOps), round(BytesOps), Speedup]), - {Size, Speedup} - end, Sizes), + SpeedupsList = lists:map( + fun(Size) -> + Data = maps:get(Size, Results), + + BufOps = maps:get(<<"buffer_ops_per_sec">>, Data), + BytesOps = maps:get(<<"bytes_ops_per_sec">>, Data), + Speedup = BufOps / max(BytesOps, 1), + + io:format( + "~8B | ~14w | ~14w | ~.2f~n", + [Size, round(BufOps), round(BytesOps), Speedup] + ), + {Size, Speedup} + end, + Sizes + ), %% Calculate average speedup for >= 1KB LargeSpeedups = [S || {Size, S} <- SpeedupsList, Size >= 1024], case LargeSpeedups of - [] -> ok; + [] -> + ok; _ -> AvgSpeedup = lists:sum(LargeSpeedups) / length(LargeSpeedups), Improvement = (AvgSpeedup - 1.0) * 100, @@ -205,83 +224,91 @@ run_echo_protocol_bench() -> io:format("~n--- Echo Protocol Benchmark ---~n"), io:format("Iterations: 200~n~n"), - Code = <<" -import time -import socket -import statistics -import erlang.reactor as reactor - -def run_echo_bench(iterations=200): - class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'read_pending' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'read_pending' - - results = {} - sizes = [64, 256, 1024, 4096, 16384] - - for size in sizes: - test_data = b'X' * size - times = [] - - for _ in range(iterations): - s1, s2 = socket.socketpair() - s1.setblocking(False) - s2.setblocking(False) - - try: - reactor.set_protocol_factory(EchoProtocol) - reactor.init_connection(s1.fileno(), {'type': 'test'}) - - s2.send(test_data) - - start = time.perf_counter() - action = reactor.on_read_ready(s1.fileno()) - elapsed = time.perf_counter() - start - times.append(elapsed) - - reactor.close_connection(s1.fileno()) - finally: - s1.close() - s2.close() - - avg_time = statistics.mean(times) - results[size] = { - 'avg_time_ms': avg_time * 1000, - 'ops_per_sec': 1.0 / avg_time, - 'p50_ms': statistics.median(times) * 1000, - 'p95_ms': sorted(times)[int(len(times) * 0.95)] * 1000, - } - - return results - -_echo_bench_results = run_echo_bench() -">>, + Code = << + "\n" + "import time\n" + "import socket\n" + "import statistics\n" + "import erlang.reactor as reactor\n" + "\n" + "def run_echo_bench(iterations=200):\n" + " class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'read_pending'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'read_pending'\n" + "\n" + " results = {}\n" + " sizes = [64, 256, 1024, 4096, 16384]\n" + "\n" + " for size in sizes:\n" + " test_data = b'X' * size\n" + " times = []\n" + "\n" + " for _ in range(iterations):\n" + " s1, s2 = socket.socketpair()\n" + " s1.setblocking(False)\n" + " s2.setblocking(False)\n" + "\n" + " try:\n" + " reactor.set_protocol_factory(EchoProtocol)\n" + " reactor.init_connection(s1.fileno(), {'type': 'test'})\n" + "\n" + " s2.send(test_data)\n" + "\n" + " start = time.perf_counter()\n" + " action = reactor.on_read_ready(s1.fileno())\n" + " elapsed = time.perf_counter() - start\n" + " times.append(elapsed)\n" + "\n" + " reactor.close_connection(s1.fileno())\n" + " finally:\n" + " s1.close()\n" + " s2.close()\n" + "\n" + " avg_time = statistics.mean(times)\n" + " results[size] = {\n" + " 'avg_time_ms': avg_time * 1000,\n" + " 'ops_per_sec': 1.0 / avg_time,\n" + " 'p50_ms': statistics.median(times) * 1000,\n" + " 'p95_ms': sorted(times)[int(len(times) * 0.95)] * 1000,\n" + " }\n" + "\n" + " return results\n" + "\n" + "_echo_bench_results = run_echo_bench()\n" + >>, ok = py:exec(Code), {ok, Results} = py:eval(<<"_echo_bench_results">>), - io:format("~8s | ~10s | ~10s | ~10s | ~10s~n", - ["Size", "Avg (ms)", "P50 (ms)", "P95 (ms)", "Ops/sec"]), + io:format( + "~8s | ~10s | ~10s | ~10s | ~10s~n", + ["Size", "Avg (ms)", "P50 (ms)", "P95 (ms)", "Ops/sec"] + ), io:format("~s~n", [string:copies("-", 56)]), Sizes = [64, 256, 1024, 4096, 16384], - lists:foreach(fun(Size) -> - Data = maps:get(Size, Results), - - AvgMs = maps:get(<<"avg_time_ms">>, Data), - P50Ms = maps:get(<<"p50_ms">>, Data), - P95Ms = maps:get(<<"p95_ms">>, Data), - OpsPerSec = maps:get(<<"ops_per_sec">>, Data), - - io:format("~8B | ~10.3f | ~10.3f | ~10.3f | ~10w~n", - [Size, AvgMs, P50Ms, P95Ms, round(OpsPerSec)]) - end, Sizes), + lists:foreach( + fun(Size) -> + Data = maps:get(Size, Results), + + AvgMs = maps:get(<<"avg_time_ms">>, Data), + P50Ms = maps:get(<<"p50_ms">>, Data), + P95Ms = maps:get(<<"p95_ms">>, Data), + OpsPerSec = maps:get(<<"ops_per_sec">>, Data), + + io:format( + "~8B | ~10.3f | ~10.3f | ~10.3f | ~10w~n", + [Size, AvgMs, P50Ms, P95Ms, round(OpsPerSec)] + ) + end, + Sizes + ), ok. diff --git a/examples/bench_reactor_modes.erl b/examples/bench_reactor_modes.erl index dd0389d..2718e19 100644 --- a/examples/bench_reactor_modes.erl +++ b/examples/bench_reactor_modes.erl @@ -31,17 +31,20 @@ main(_Args) -> {WkPersistent, WkLifecycle} = run_reactor_worker_bench(), %% OWN_GIL mode benchmarks (if supported) - {OgPersistent, OgLifecycle} = case py_nif:owngil_supported() of - true -> - io:format("~n--- Reactor (OWN_GIL Mode) ---~n"), - run_reactor_owngil_bench(); - false -> - io:format("~n[Skipping OWN_GIL benchmarks - Python < 3.14]~n"), - {[], []} - end, + {OgPersistent, OgLifecycle} = + case py_nif:owngil_supported() of + true -> + io:format("~n--- Reactor (OWN_GIL Mode) ---~n"), + run_reactor_owngil_bench(); + false -> + io:format("~n[Skipping OWN_GIL benchmarks - Python < 3.14]~n"), + {[], []} + end, %% Print comparison summary - print_comparison(ChPersistent, ChLifecycle, WkPersistent, WkLifecycle, OgPersistent, OgLifecycle), + print_comparison( + ChPersistent, ChLifecycle, WkPersistent, WkLifecycle, OgPersistent, OgLifecycle + ), halt(0). @@ -65,62 +68,81 @@ run_channel_bench() -> %% First: Messages on persistent channel (no creation overhead) io:format(" A) Messages on persistent channel (1000 msgs):~n"), - PersistentResults = lists:map(fun(Size) -> - {ok, Ch} = py_channel:new(), - Data = binary:copy(<<$X>>, Size), - Iterations = 1000, - - %% Warm up - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, 100)), - - %% Benchmark messages on persistent channel - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - py_channel:close(Ch), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + PersistentResults = lists:map( + fun(Size) -> + {ok, Ch} = py_channel:new(), + Data = binary:copy(<<$X>>, Size), + Iterations = 1000, + + %% Warm up + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, 100) + ), + + %% Benchmark messages on persistent channel + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + py_channel:close(Ch), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), %% Second: Full lifecycle (create + send + receive + close) io:format("~n B) Full lifecycle per op (create+send+recv+close, 200 ops):~n"), - LifecycleResults = lists:map(fun(Size) -> - Data = binary:copy(<<$X>>, Size), - Iterations = 200, - - %% Benchmark full lifecycle - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - {ok, Ch} = py_channel:new(), - ok = py_channel:send(Ch, Data), - {ok, _} = py_nif:channel_try_receive(Ch), - py_channel:close(Ch) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + LifecycleResults = lists:map( + fun(Size) -> + Data = binary:copy(<<$X>>, Size), + Iterations = 200, + + %% Benchmark full lifecycle + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + {ok, Ch} = py_channel:new(), + ok = py_channel:send(Ch, Data), + {ok, _} = py_nif:channel_try_receive(Ch), + py_channel:close(Ch) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), %% Return persistent results for comparison (more representative) {PersistentResults, LifecycleResults}. @@ -131,125 +153,149 @@ run_channel_bench() -> run_reactor_worker_bench() -> %% Protocol that stays open for multiple messages - PersistentSetup = <<" -import erlang.reactor as reactor - -class PersistentEchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'read_pending' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'read_pending' - -reactor.set_protocol_factory(PersistentEchoProtocol) -">>, + PersistentSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class PersistentEchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'read_pending'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'read_pending'\n" + "\n" + "reactor.set_protocol_factory(PersistentEchoProtocol)\n" + >>, %% Protocol that closes after one message - LifecycleSetup = <<" -import erlang.reactor as reactor - -class OneMessageProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(OneMessageProtocol) -">>, + LifecycleSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class OneMessageProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(OneMessageProtocol)\n" + >>, Sizes = [64, 1024, 16384], %% First: Messages on persistent connection io:format(" A) Messages on persistent connection (500 msgs):~n"), - PersistentResults = lists:map(fun(Size) -> - Data = binary:copy(<<$X>>, Size), - Iterations = 500, - - {ok, Ctx} = py_reactor_context:start_link(900 + Size, worker, #{ - setup_code => PersistentSetup - }), - - %% Create one persistent connection - {ok, LSock} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), - {ok, Port} = inet:port(LSock), - {ok, Client} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), - {ok, Server} = gen_tcp:accept(LSock, 1000), - gen_tcp:close(LSock), - {ok, Fd} = inet:getfd(Server), - ok = py_reactor_context:handoff(Ctx, Fd, #{type => bench}), - timer:sleep(10), - - %% Warm up - lists:foreach(fun(_) -> - ok = gen_tcp:send(Client, Data), - {ok, _} = recv_all(Client, Size, 5000) - end, lists:seq(1, 50)), - - %% Benchmark messages on persistent connection - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = gen_tcp:send(Client, Data), - {ok, _} = recv_all(Client, Size, 5000) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - gen_tcp:close(Client), - py_reactor_context:stop(Ctx), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + PersistentResults = lists:map( + fun(Size) -> + Data = binary:copy(<<$X>>, Size), + Iterations = 500, + + {ok, Ctx} = py_reactor_context:start_link(900 + Size, worker, #{ + setup_code => PersistentSetup + }), + + %% Create one persistent connection + {ok, LSock} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), + {ok, Port} = inet:port(LSock), + {ok, Client} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), + {ok, Server} = gen_tcp:accept(LSock, 1000), + gen_tcp:close(LSock), + {ok, Fd} = inet:getfd(Server), + ok = py_reactor_context:handoff(Ctx, Fd, #{type => bench}), + timer:sleep(10), + + %% Warm up + lists:foreach( + fun(_) -> + ok = gen_tcp:send(Client, Data), + {ok, _} = recv_all(Client, Size, 5000) + end, + lists:seq(1, 50) + ), + + %% Benchmark messages on persistent connection + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = gen_tcp:send(Client, Data), + {ok, _} = recv_all(Client, Size, 5000) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + gen_tcp:close(Client), + py_reactor_context:stop(Ctx), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), %% Second: Full lifecycle per operation io:format("~n B) Full lifecycle per op (connect+handoff+echo+close, 100 ops):~n"), - LifecycleResults = lists:map(fun(Size) -> - Data = binary:copy(<<$X>>, Size), - Iterations = 100, - - {ok, Ctx} = py_reactor_context:start_link(800 + Size, worker, #{ - setup_code => LifecycleSetup - }), - - %% Warm up - lists:foreach(fun(_) -> - run_single_reactor_test(Ctx, Data) - end, lists:seq(1, 10)), - - %% Benchmark full lifecycle - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - run_single_reactor_test(Ctx, Data) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - py_reactor_context:stop(Ctx), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + LifecycleResults = lists:map( + fun(Size) -> + Data = binary:copy(<<$X>>, Size), + Iterations = 100, + + {ok, Ctx} = py_reactor_context:start_link(800 + Size, worker, #{ + setup_code => LifecycleSetup + }), + + %% Warm up + lists:foreach( + fun(_) -> + run_single_reactor_test(Ctx, Data) + end, + lists:seq(1, 10) + ), + + %% Benchmark full lifecycle + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + run_single_reactor_test(Ctx, Data) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + py_reactor_context:stop(Ctx), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), {PersistentResults, LifecycleResults}. @@ -295,125 +341,149 @@ recv_all(Socket, Remaining, Timeout, Acc) -> run_reactor_owngil_bench() -> %% Protocol that stays open for multiple messages - PersistentSetup = <<" -import erlang.reactor as reactor - -class PersistentEchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'read_pending' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'read_pending' - -reactor.set_protocol_factory(PersistentEchoProtocol) -">>, + PersistentSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class PersistentEchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'read_pending'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'read_pending'\n" + "\n" + "reactor.set_protocol_factory(PersistentEchoProtocol)\n" + >>, %% Protocol that closes after one message - LifecycleSetup = <<" -import erlang.reactor as reactor - -class OneMessageProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(OneMessageProtocol) -">>, + LifecycleSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class OneMessageProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(OneMessageProtocol)\n" + >>, Sizes = [64, 1024, 16384], %% First: Messages on persistent connection io:format(" A) Messages on persistent connection (500 msgs):~n"), - PersistentResults = lists:map(fun(Size) -> - Data = binary:copy(<<$X>>, Size), - Iterations = 500, - - {ok, Ctx} = py_reactor_context:start_link(1900 + Size, owngil, #{ - setup_code => PersistentSetup - }), - - %% Create one persistent connection - {ok, LSock} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), - {ok, Port} = inet:port(LSock), - {ok, Client} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), - {ok, Server} = gen_tcp:accept(LSock, 1000), - gen_tcp:close(LSock), - {ok, Fd} = inet:getfd(Server), - ok = py_reactor_context:handoff(Ctx, Fd, #{type => bench}), - timer:sleep(10), - - %% Warm up - lists:foreach(fun(_) -> - ok = gen_tcp:send(Client, Data), - {ok, _} = recv_all(Client, Size, 5000) - end, lists:seq(1, 50)), - - %% Benchmark messages on persistent connection - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - ok = gen_tcp:send(Client, Data), - {ok, _} = recv_all(Client, Size, 5000) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - gen_tcp:close(Client), - py_reactor_context:stop(Ctx), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + PersistentResults = lists:map( + fun(Size) -> + Data = binary:copy(<<$X>>, Size), + Iterations = 500, + + {ok, Ctx} = py_reactor_context:start_link(1900 + Size, owngil, #{ + setup_code => PersistentSetup + }), + + %% Create one persistent connection + {ok, LSock} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), + {ok, Port} = inet:port(LSock), + {ok, Client} = gen_tcp:connect("127.0.0.1", Port, [binary, {active, false}]), + {ok, Server} = gen_tcp:accept(LSock, 1000), + gen_tcp:close(LSock), + {ok, Fd} = inet:getfd(Server), + ok = py_reactor_context:handoff(Ctx, Fd, #{type => bench}), + timer:sleep(10), + + %% Warm up + lists:foreach( + fun(_) -> + ok = gen_tcp:send(Client, Data), + {ok, _} = recv_all(Client, Size, 5000) + end, + lists:seq(1, 50) + ), + + %% Benchmark messages on persistent connection + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + ok = gen_tcp:send(Client, Data), + {ok, _} = recv_all(Client, Size, 5000) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + gen_tcp:close(Client), + py_reactor_context:stop(Ctx), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), %% Second: Full lifecycle per operation io:format("~n B) Full lifecycle per op (connect+handoff+echo+close, 100 ops):~n"), - LifecycleResults = lists:map(fun(Size) -> - Data = binary:copy(<<$X>>, Size), - Iterations = 100, - - {ok, Ctx} = py_reactor_context:start_link(1800 + Size, owngil, #{ - setup_code => LifecycleSetup - }), - - %% Warm up - lists:foreach(fun(_) -> - run_single_reactor_test(Ctx, Data) - end, lists:seq(1, 10)), - - %% Benchmark full lifecycle - Start = erlang:monotonic_time(microsecond), - lists:foreach(fun(_) -> - run_single_reactor_test(Ctx, Data) - end, lists:seq(1, Iterations)), - End = erlang:monotonic_time(microsecond), - - py_reactor_context:stop(Ctx), - - TimeMs = (End - Start) / 1000, - OpsPerSec = round(Iterations / (TimeMs / 1000)), - LatencyUs = (End - Start) / Iterations, - - io:format(" Size ~6B: ~8.1f us/op, ~8w ops/sec~n", - [Size, LatencyUs, OpsPerSec]), - - {Size, LatencyUs, OpsPerSec} - end, Sizes), + LifecycleResults = lists:map( + fun(Size) -> + Data = binary:copy(<<$X>>, Size), + Iterations = 100, + + {ok, Ctx} = py_reactor_context:start_link(1800 + Size, owngil, #{ + setup_code => LifecycleSetup + }), + + %% Warm up + lists:foreach( + fun(_) -> + run_single_reactor_test(Ctx, Data) + end, + lists:seq(1, 10) + ), + + %% Benchmark full lifecycle + Start = erlang:monotonic_time(microsecond), + lists:foreach( + fun(_) -> + run_single_reactor_test(Ctx, Data) + end, + lists:seq(1, Iterations) + ), + End = erlang:monotonic_time(microsecond), + + py_reactor_context:stop(Ctx), + + TimeMs = (End - Start) / 1000, + OpsPerSec = round(Iterations / (TimeMs / 1000)), + LatencyUs = (End - Start) / Iterations, + + io:format( + " Size ~6B: ~8.1f us/op, ~8w ops/sec~n", + [Size, LatencyUs, OpsPerSec] + ), + + {Size, LatencyUs, OpsPerSec} + end, + Sizes + ), {PersistentResults, LifecycleResults}. @@ -430,35 +500,51 @@ print_comparison(ChPersistent, ChLifecycle, WkPersistent, WkLifecycle, OgPersist %% Persistent connection comparison (messages/sec on existing connection) io:format("A) PERSISTENT CONNECTION (messages on existing connection)~n"), io:format("-----------------------------------------------------------~n"), - io:format("~8s | ~12s | ~12s | ~12s~n", - ["Size", "Channel", "Reactor/W", "Reactor/OG"]), + io:format( + "~8s | ~12s | ~12s | ~12s~n", + ["Size", "Channel", "Reactor/W", "Reactor/OG"] + ), io:format("~s~n", [string:copies("-", 52)]), - lists:foreach(fun({{Size, _, ChOps}, {_, _, WkOps}}) -> - OgOps = case lists:keyfind(Size, 1, OgPersistent) of - {_, _, O} -> integer_to_list(O); - false -> "N/A" + lists:foreach( + fun({{Size, _, ChOps}, {_, _, WkOps}}) -> + OgOps = + case lists:keyfind(Size, 1, OgPersistent) of + {_, _, O} -> integer_to_list(O); + false -> "N/A" + end, + io:format( + "~8B | ~12w | ~12w | ~12s~n", + [Size, ChOps, WkOps, OgOps] + ) end, - io:format("~8B | ~12w | ~12w | ~12s~n", - [Size, ChOps, WkOps, OgOps]) - end, lists:zip(ChPersistent, WkPersistent)), + lists:zip(ChPersistent, WkPersistent) + ), %% Full lifecycle comparison (connections/sec including setup/teardown) io:format("~n"), io:format("B) FULL LIFECYCLE (create + send/recv + close per op)~n"), io:format("-----------------------------------------------------------~n"), - io:format("~8s | ~12s | ~12s | ~12s~n", - ["Size", "Channel", "Reactor/W", "Reactor/OG"]), + io:format( + "~8s | ~12s | ~12s | ~12s~n", + ["Size", "Channel", "Reactor/W", "Reactor/OG"] + ), io:format("~s~n", [string:copies("-", 52)]), - lists:foreach(fun({{Size, _, ChOps}, {_, _, WkOps}}) -> - OgOps = case lists:keyfind(Size, 1, OgLifecycle) of - {_, _, O} -> integer_to_list(O); - false -> "N/A" + lists:foreach( + fun({{Size, _, ChOps}, {_, _, WkOps}}) -> + OgOps = + case lists:keyfind(Size, 1, OgLifecycle) of + {_, _, O} -> integer_to_list(O); + false -> "N/A" + end, + io:format( + "~8B | ~12w | ~12w | ~12s~n", + [Size, ChOps, WkOps, OgOps] + ) end, - io:format("~8B | ~12w | ~12w | ~12s~n", - [Size, ChOps, WkOps, OgOps]) - end, lists:zip(ChLifecycle, WkLifecycle)), + lists:zip(ChLifecycle, WkLifecycle) + ), io:format("~n"), io:format("Legend:~n"), diff --git a/examples/bench_resource_pool.erl b/examples/bench_resource_pool.erl index 356e94e..7af26a6 100644 --- a/examples/bench_resource_pool.erl +++ b/examples/bench_resource_pool.erl @@ -67,9 +67,12 @@ bench_resource_pool_sequential(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py_resource_pool:call(math, sqrt, [I]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py_resource_pool:call(math, sqrt, [I]) + end, + lists:seq(1, N) + ) end), print_results(Time, N). @@ -77,20 +80,33 @@ bench_resource_pool_sequential(N) -> bench_resource_pool_concurrent(NumProcs, CallsPerProc) -> TotalCalls = NumProcs * CallsPerProc, io:format("Resource Pool: Concurrent calls~n"), - io:format(" Processes: ~p, Calls/process: ~p, Total: ~p~n", - [NumProcs, CallsPerProc, TotalCalls]), + io:format( + " Processes: ~p, Calls/process: ~p, Total: ~p~n", + [NumProcs, CallsPerProc, TotalCalls] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py_resource_pool:call(math, sqrt, [I]) - end, lists:seq(1, CallsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + {ok, _} = py_resource_pool:call(math, sqrt, [I]) + end, + lists:seq(1, CallsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), print_results(Time, TotalCalls). @@ -101,9 +117,12 @@ bench_old_pool_sequential(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, N) + ) end), print_results(Time, N). @@ -111,20 +130,33 @@ bench_old_pool_sequential(N) -> bench_old_pool_concurrent(NumProcs, CallsPerProc) -> TotalCalls = NumProcs * CallsPerProc, io:format("Old Pool (py:call): Concurrent calls~n"), - io:format(" Processes: ~p, Calls/process: ~p, Total: ~p~n", - [NumProcs, CallsPerProc, TotalCalls]), + io:format( + " Processes: ~p, Calls/process: ~p, Total: ~p~n", + [NumProcs, CallsPerProc, TotalCalls] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, CallsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, CallsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), print_results(Time, TotalCalls). diff --git a/examples/bench_sessions.erl b/examples/bench_sessions.erl index b3928a8..9f7dc0e 100644 --- a/examples/bench_sessions.erl +++ b/examples/bench_sessions.erl @@ -20,33 +20,35 @@ -mode(compile). --define(PY, <<" -import sys, types, erlang -m = types.ModuleType('bench_sessions_wf'); sys.modules['bench_sessions_wf'] = m -exec(''' -from dataclasses import dataclass -import json, decimal, datetime - -@dataclass -class Step: - n: int - -STATE = {} - -def handle(event, state): - n = state.get('n', 0) + 1 - return {'commands': [['activity', 'charge', {'n': n}]], 'state': {'n': Step(n).n}} - -def reenter(n): - import erlang - return 0 if n == 0 else erlang.call('bench_reenter', erlang.self(), n) + 1 -''', m.__dict__) -">>). +-define(PY, << + "\n" + "import sys, types, erlang\n" + "m = types.ModuleType('bench_sessions_wf'); sys.modules['bench_sessions_wf'] = m\n" + "exec('''\n" + "from dataclasses import dataclass\n" + "import json, decimal, datetime\n" + "\n" + "@dataclass\n" + "class Step:\n" + " n: int\n" + "\n" + "STATE = {}\n" + "\n" + "def handle(event, state):\n" + " n = state.get('n', 0) + 1\n" + " return {'commands': [['activity', 'charge', {'n': n}]], 'state': {'n': Step(n).n}}\n" + "\n" + "def reenter(n):\n" + " import erlang\n" + " return 0 if n == 0 else erlang.call('bench_reenter', erlang.self(), n) + 1\n" + "''', m.__dict__)\n" +>>). main(_) -> {ok, _} = application:ensure_all_started(erlang_python), py:register_function(bench_reenter, fun([Ctx, N]) -> - {ok, R} = py_context:call(Ctx, bench_sessions_wf, reenter, [N - 1]), R + {ok, R} = py_context:call(Ctx, bench_sessions_wf, reenter, [N - 1]), + R end), Fork = template(#{start => fork}), Spawn = template(#{start => spawn}), @@ -54,72 +56,120 @@ main(_) -> io:format("~n== fresh session: new + first call + close ==~n"), row("fork", session_loop(Fork, 200)), row("spawn", session_loop(Spawn, 20)), - row("spawn, warm pool", [begin timer:sleep(80), hd(session_loop(Warm, 1)) end - || _ <- lists:seq(1, 20)]), + row("spawn, warm pool", [ + begin + timer:sleep(80), + hd(session_loop(Warm, 1)) + end + || _ <- lists:seq(1, 20) + ]), row("plain isolated", [plain() || _ <- lists:seq(1, 20)]), io:format("~n== sessions per second, fork template ==~n"), - [begin - L = throughput(Fork, C, 3), - io:format(" ~2w callers ~7.1f sessions/s p50 ~6.2f ms~n", [C, length(L) / 3, p50(L)]) - end || C <- [1, 8, 64]], + [ + begin + L = throughput(Fork, C, 3), + io:format(" ~2w callers ~7.1f sessions/s p50 ~6.2f ms~n", [C, length(L) / 3, p50(L)]) + end + || C <- [1, 8, 64] + ], io:format("~n== calls inside a session ==~n"), {ok, S} = py_session:new(Fork), - row("call", [us(fun() -> {ok, _} = py_context:call(S, bench_sessions_wf, handle, [[], #{}]) end) - || _ <- lists:seq(1, 2000)]), - row("re-entrant call", [us(fun() -> {ok, 1} = py_context:call(S, bench_sessions_wf, reenter, [1]) end) - || _ <- lists:seq(1, 1000)]), + row("call", [ + us(fun() -> {ok, _} = py_context:call(S, bench_sessions_wf, handle, [[], #{}]) end) + || _ <- lists:seq(1, 2000) + ]), + row("re-entrant call", [ + us(fun() -> {ok, 1} = py_context:call(S, bench_sessions_wf, reenter, [1]) end) + || _ <- lists:seq(1, 1000) + ]), py_session:close(S), io:format("~n== re-import runs (no process per run) ==~n"), %% the same workflow as a module file: a re-import run imports it anew Dir = filename:join(py_child:sock_dir(), "bench_reimport"), ok = filelib:ensure_dir(filename:join(Dir, "x")), ok = file:write_file(filename:join(Dir, "bench_reimport_wf.py"), reimport_module()), - [begin - {ok, R} = py_session:template(#{start => reimport, mode => M, contexts => 4, - paths => [Dir]}), - row(atom_to_list(M) ++ ", one run", - [us(fun() -> {ok, _} = py_session:run(R, bench_reimport_wf, handle, [[], #{}]) end) - || _ <- lists:seq(1, 500)]), - L = reimport_throughput(R, 8, 3), - io:format(" ~-18s ~7.1f runs/s with 8 callers~n", [M, length(L) / 3]), - {ok, RS} = py_session:new(R), - {ok, _} = py_context:call(RS, bench_reimport_wf, handle, [[], #{}]), - row(atom_to_list(M) ++ " session call", - [us(fun() -> {ok, _} = py_context:call(RS, bench_reimport_wf, handle, [[], #{}]) end) - || _ <- lists:seq(1, 2000)]), - py_session:close(RS) - end || M <- [worker] ++ [owngil || py_nif:owngil_supported()]], + [ + begin + {ok, R} = py_session:template(#{ + start => reimport, + mode => M, + contexts => 4, + paths => [Dir] + }), + row( + atom_to_list(M) ++ ", one run", + [ + us(fun() -> + {ok, _} = py_session:run(R, bench_reimport_wf, handle, [[], #{}]) + end) + || _ <- lists:seq(1, 500) + ] + ), + L = reimport_throughput(R, 8, 3), + io:format(" ~-18s ~7.1f runs/s with 8 callers~n", [M, length(L) / 3]), + {ok, RS} = py_session:new(R), + {ok, _} = py_context:call(RS, bench_reimport_wf, handle, [[], #{}]), + row( + atom_to_list(M) ++ " session call", + [ + us(fun() -> + {ok, _} = py_context:call(RS, bench_reimport_wf, handle, [[], #{}]) + end) + || _ <- lists:seq(1, 2000) + ] + ), + py_session:close(RS) + end + || M <- [worker] ++ [owngil || py_nif:owngil_supported()] + ], ok. reimport_module() -> - <<"from dataclasses import dataclass\nimport json, decimal, datetime\n\n" - "@dataclass\nclass Step:\n n: int\n\n" - "def handle(event, state):\n" - " n = state.get('n', 0) + 1\n" - " return {'commands': [['activity', 'charge', {'n': n}]], 'state': {'n': Step(n).n}}\n">>. + << + "from dataclasses import dataclass\nimport json, decimal, datetime\n\n" + "@dataclass\nclass Step:\n n: int\n\n" + "def handle(event, state):\n" + " n = state.get('n', 0) + 1\n" + " return {'commands': [['activity', 'charge', {'n': n}]], 'state': {'n': Step(n).n}}\n" + >>. reimport_throughput(T, Callers, Secs) -> Self = self(), Deadline = erlang:monotonic_time(millisecond) + Secs * 1000, Loop = fun L(Acc) -> case erlang:monotonic_time(millisecond) < Deadline of - true -> L([us(fun() -> {ok, _} = py_session:run(T, bench_reimport_wf, handle, [[], #{}]) end) | Acc]); - false -> Acc + true -> + L([ + us(fun() -> + {ok, _} = py_session:run(T, bench_reimport_wf, handle, [[], #{}]) + end) + | Acc + ]); + false -> + Acc end end, Pids = [spawn_link(fun() -> Self ! {done, self(), Loop([])} end) || _ <- lists:seq(1, Callers)], - lists:append([receive {done, P, L} -> L end || P <- Pids]). + lists:append([ + receive + {done, P, L} -> L + end + || P <- Pids + ]). template(Opts) -> {ok, T} = py_session:template(Opts#{preload => ?PY}), T. session_loop(T, N) -> - [us(fun() -> + [ + us(fun() -> {ok, S} = py_session:new(T), {ok, _} = py_context:call(S, bench_sessions_wf, handle, [[], #{}]), py_session:close(S) - end) || _ <- lists:seq(1, N)]. + end) + || _ <- lists:seq(1, N) + ]. plain() -> us(fun() -> @@ -138,7 +188,12 @@ throughput(T, Callers, Secs) -> end end, Pids = [spawn_link(fun() -> Self ! {done, self(), Loop([])} end) || _ <- lists:seq(1, Callers)], - lists:append([receive {done, P, L} -> L end || P <- Pids]). + lists:append([ + receive + {done, P, L} -> L + end + || P <- Pids + ]). us(F) -> T0 = erlang:monotonic_time(microsecond), diff --git a/examples/bench_worker_loop.erl b/examples/bench_worker_loop.erl index ae51dda..669ea76 100644 --- a/examples/bench_worker_loop.erl +++ b/examples/bench_worker_loop.erl @@ -21,32 +21,33 @@ -define(HOST, {127, 0, 0, 1}). --define(PY, <<" -import asyncio, erlang, sys, types -m = types.ModuleType('bench_wl'); sys.modules['bench_wl'] = m - -class Echo(asyncio.Protocol): - def connection_made(self, t): self.t = t - def data_received(self, d): self.t.write(d) - -class EchoClose(asyncio.Protocol): - def connection_made(self, t): self.t = t - def data_received(self, d): self.t.write(d); self.t.close() - -_servers = {} -async def serve(fd, keepalive): - srv = await erlang.server.serve(fd, Echo if keepalive else EchoClose) - _servers[fd] = srv - return 'ok' -async def adopt(fd): - await erlang.server.adopt(fd, EchoClose) - return 'ok' -async def noop(): - return 1 -def sync_noop(): - return 1 -m.serve = serve; m.adopt = adopt; m.noop = noop; m.sync_noop = sync_noop -">>). +-define(PY, << + "\n" + "import asyncio, erlang, sys, types\n" + "m = types.ModuleType('bench_wl'); sys.modules['bench_wl'] = m\n" + "\n" + "class Echo(asyncio.Protocol):\n" + " def connection_made(self, t): self.t = t\n" + " def data_received(self, d): self.t.write(d)\n" + "\n" + "class EchoClose(asyncio.Protocol):\n" + " def connection_made(self, t): self.t = t\n" + " def data_received(self, d): self.t.write(d); self.t.close()\n" + "\n" + "_servers = {}\n" + "async def serve(fd, keepalive):\n" + " srv = await erlang.server.serve(fd, Echo if keepalive else EchoClose)\n" + " _servers[fd] = srv\n" + " return 'ok'\n" + "async def adopt(fd):\n" + " await erlang.server.adopt(fd, EchoClose)\n" + " return 'ok'\n" + "async def noop():\n" + " return 1\n" + "def sync_noop():\n" + " return 1\n" + "m.serve = serve; m.adopt = adopt; m.noop = noop; m.sync_noop = sync_noop\n" +>>). main(_Args) -> io:format("~n"), @@ -88,8 +89,10 @@ bench_single_worker() -> {ok, <<"ok">>} = py_context:submit_await(W, bench_wl, serve, [Dup, false]), N = 5000, {Ms, Fails} = timed(fun() -> parallel_conns(Port, N, 50) end), - io:format(" connect+echo+close: ~p conns in ~p ms = ~p conn/s (failed ~p)~n", - [N, Ms, N * 1000 div max(1, Ms), Fails]), + io:format( + " connect+echo+close: ~p conns in ~p ms = ~p conn/s (failed ~p)~n", + [N, Ms, N * 1000 div max(1, Ms), Fails] + ), ok = py_context:stop_loop(W), py_context:stop(W), gen_tcp:close(LSock), @@ -101,8 +104,10 @@ bench_single_worker() -> Conns = 50, Reqs = 20000, {Ms2, _} = timed(fun() -> keepalive_requests(Port2, Conns, Reqs div Conns) end), - io:format(" keep-alive echo: ~p reqs on ~p conns in ~p ms = ~p req/s~n", - [Reqs, Conns, Ms2, Reqs * 1000 div max(1, Ms2)]), + io:format( + " keep-alive echo: ~p reqs on ~p conns in ~p ms = ~p req/s~n", + [Reqs, Conns, Ms2, Reqs * 1000 div max(1, Ms2)] + ), ok = py_context:stop_loop(W2), py_context:stop(W2), gen_tcp:close(LSock2), @@ -116,19 +121,25 @@ bench_scaling() -> io:format("2. Scaling: connect+echo+close, workers accepting on one listen fd~n"), io:format(" ~-8s ~12s ~12s~n", ["workers", "conn/s", "ms"]), N = 8000, - lists:foreach(fun(Workers) -> - Ws = [worker() || _ <- lists:seq(1, Workers)], - {LSock, Port, LFd} = listen(), - [begin - {ok, Dup} = py:dup_fd(LFd), - {ok, <<"ok">>} = py_context:submit_await(W, bench_wl, serve, [Dup, false]) - end || W <- Ws], - {Ms, _} = timed(fun() -> parallel_conns(Port, N, 100) end), - io:format(" ~-8w ~12w ~12w~n", [Workers, N * 1000 div max(1, Ms), Ms]), - [ok = py_context:stop_loop(W) || W <- Ws], - [py_context:stop(W) || W <- Ws], - gen_tcp:close(LSock) - end, [1, 2, 4, 8]), + lists:foreach( + fun(Workers) -> + Ws = [worker() || _ <- lists:seq(1, Workers)], + {LSock, Port, LFd} = listen(), + [ + begin + {ok, Dup} = py:dup_fd(LFd), + {ok, <<"ok">>} = py_context:submit_await(W, bench_wl, serve, [Dup, false]) + end + || W <- Ws + ], + {Ms, _} = timed(fun() -> parallel_conns(Port, N, 100) end), + io:format(" ~-8w ~12w ~12w~n", [Workers, N * 1000 div max(1, Ms), Ms]), + [ok = py_context:stop_loop(W) || W <- Ws], + [py_context:stop(W) || W <- Ws], + gen_tcp:close(LSock) + end, + [1, 2, 4, 8] + ), io:format("~n"). %% ============================================================================ @@ -151,18 +162,32 @@ bench_submit_latency() -> py_context:stop(Idle), W = worker(), - lists:foreach(fun(Callers) -> - Per = N div Callers, - {Ms, _} = timed(fun() -> - Self = self(), - [spawn_link(fun() -> - [{ok, 1} = py_context:submit_await(W, bench_wl, noop, []) || _ <- lists:seq(1, Per)], - Self ! done - end) || _ <- lists:seq(1, Callers)], - [receive done -> ok end || _ <- lists:seq(1, Callers)] - end), - row(io_lib:format("submit_await coroutine, running loop, ~p callers", [Callers]), N, Ms) - end, [1, 10, 100]), + lists:foreach( + fun(Callers) -> + Per = N div Callers, + {Ms, _} = timed(fun() -> + Self = self(), + [ + spawn_link(fun() -> + [ + {ok, 1} = py_context:submit_await(W, bench_wl, noop, []) + || _ <- lists:seq(1, Per) + ], + Self ! done + end) + || _ <- lists:seq(1, Callers) + ], + [ + receive + done -> ok + end + || _ <- lists:seq(1, Callers) + ] + end), + row(io_lib:format("submit_await coroutine, running loop, ~p callers", [Callers]), N, Ms) + end, + [1, 10, 100] + ), ok = py_context:stop_loop(W), py_context:stop(W), io:format("~n"). @@ -193,7 +218,8 @@ bench_adopt_vs_accept() -> Acceptor = spawn_link(fun() -> acceptor(LSock2, W2) end), {MsAd, _} = timed(fun() -> parallel_conns(Port2, N, 50) end), io:format(" Erlang accept+adopt: ~p conn/s~n", [N * 1000 div max(1, MsAd)]), - unlink(Acceptor), exit(Acceptor, kill), + unlink(Acceptor), + exit(Acceptor, kill), ok = py_context:stop_loop(W2), py_context:stop(W2), gen_tcp:close(LSock2), @@ -234,11 +260,20 @@ timed(Fun) -> parallel_conns(Port, N, Clients) -> Self = self(), Per = N div Clients, - [spawn_link(fun() -> - Fails = length([bad || _ <- lists:seq(1, Per), roundtrip(Port) =/= ok]), - Self ! {done, Fails} - end) || _ <- lists:seq(1, Clients)], - lists:sum([receive {done, F} -> F after 120000 -> Per end || _ <- lists:seq(1, Clients)]). + [ + spawn_link(fun() -> + Fails = length([bad || _ <- lists:seq(1, Per), roundtrip(Port) =/= ok]), + Self ! {done, Fails} + end) + || _ <- lists:seq(1, Clients) + ], + lists:sum([ + receive + {done, F} -> F + after 120000 -> Per + end + || _ <- lists:seq(1, Clients) + ]). roundtrip(Port) -> case gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000) of @@ -246,19 +281,36 @@ roundtrip(Port) -> ok = gen_tcp:send(S, <<"x">>), R = gen_tcp:recv(S, 0, 5000), gen_tcp:close(S), - case R of {ok, <<"x">>} -> ok; _ -> bad end; + case R of + {ok, <<"x">>} -> ok; + _ -> bad + end; _ -> bad end. keepalive_requests(Port, Conns, PerConn) -> Self = self(), - [spawn_link(fun() -> - {ok, S} = gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000), - [begin ok = gen_tcp:send(S, <<"ping">>), {ok, <<"ping">>} = gen_tcp:recv(S, 4, 5000) end - || _ <- lists:seq(1, PerConn)], - gen_tcp:close(S), - Self ! done - end) || _ <- lists:seq(1, Conns)], - [receive done -> ok after 120000 -> ok end || _ <- lists:seq(1, Conns)], + [ + spawn_link(fun() -> + {ok, S} = gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000), + [ + begin + ok = gen_tcp:send(S, <<"ping">>), + {ok, <<"ping">>} = gen_tcp:recv(S, 4, 5000) + end + || _ <- lists:seq(1, PerConn) + ], + gen_tcp:close(S), + Self ! done + end) + || _ <- lists:seq(1, Conns) + ], + [ + receive + done -> ok + after 120000 -> ok + end + || _ <- lists:seq(1, Conns) + ], ok. diff --git a/examples/benchmark.erl b/examples/benchmark.erl index 1bdcdee..6332458 100755 --- a/examples/benchmark.erl +++ b/examples/benchmark.erl @@ -46,16 +46,11 @@ parse_args(Args) -> parse_args(Args, #{mode => standard}). parse_args([], Acc) -> Acc; -parse_args(["--quick" | Rest], Acc) -> - parse_args(Rest, Acc#{mode => quick}); -parse_args(["--full" | Rest], Acc) -> - parse_args(Rest, Acc#{mode => full}); -parse_args(["--concurrent" | Rest], Acc) -> - parse_args(Rest, Acc#{mode => concurrent}); -parse_args(["--help" | _], Acc) -> - Acc#{help => true}; -parse_args([_ | Rest], Acc) -> - parse_args(Rest, Acc). +parse_args(["--quick" | Rest], Acc) -> parse_args(Rest, Acc#{mode => quick}); +parse_args(["--full" | Rest], Acc) -> parse_args(Rest, Acc#{mode => full}); +parse_args(["--concurrent" | Rest], Acc) -> parse_args(Rest, Acc#{mode => concurrent}); +parse_args(["--help" | _], Acc) -> Acc#{help => true}; +parse_args([_ | Rest], Acc) -> parse_args(Rest, Acc). print_help() -> io:format("Usage: escript examples/benchmark.erl [OPTIONS]~n~n"), @@ -84,7 +79,6 @@ run_benchmarks(quick) -> bench_concurrent(10, 10), bench_streaming(100), bench_schedule_inline(20); - run_benchmarks(full) -> io:format("Running full benchmarks...~n~n"), bench_simple_call(10000), @@ -95,7 +89,6 @@ run_benchmarks(full) -> bench_type_conversion(1000), bench_semaphore(10000), bench_schedule_inline(500); - run_benchmarks(concurrent) -> io:format("Running concurrency benchmarks...~n~n"), bench_concurrent(10, 10), @@ -104,7 +97,6 @@ run_benchmarks(concurrent) -> bench_concurrent(200, 100), bench_concurrent(500, 100), bench_concurrent(1000, 50); - run_benchmarks(standard) -> io:format("Running standard benchmarks...~n~n"), bench_simple_call(1000), @@ -121,9 +113,12 @@ bench_simple_call(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -140,9 +135,12 @@ bench_eval(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:eval(<<"x * x">>, #{x => I}) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:eval(<<"x * x">>, #{x => I}) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -157,20 +155,33 @@ bench_eval(N) -> bench_concurrent(NumProcs, CallsPerProc) -> TotalCalls = NumProcs * CallsPerProc, io:format("Benchmark: Concurrent calls~n"), - io:format(" Processes: ~p, Calls/process: ~p, Total: ~p~n", - [NumProcs, CallsPerProc, TotalCalls]), + io:format( + " Processes: ~p, Calls/process: ~p, Total: ~p~n", + [NumProcs, CallsPerProc, TotalCalls] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, CallsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, CallsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), TimeMs = Time / 1000, @@ -185,9 +196,12 @@ bench_streaming(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(_) -> - {ok, _} = py:stream_eval(<<"(x**2 for x in range(100))">>) - end, lists:seq(1, N)) + lists:foreach( + fun(_) -> + {ok, _} = py:stream_eval(<<"(x**2 for x in range(100))">>) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -210,9 +224,12 @@ bench_type_conversion(N) -> }, {Time, _} = timer:tc(fun() -> - lists:foreach(fun(_) -> - {ok, _} = py:call(json, dumps, [ComplexData]) - end, lists:seq(1, N)) + lists:foreach( + fun(_) -> + {ok, _} = py:call(json, dumps, [ComplexData]) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -229,10 +246,13 @@ bench_semaphore(N) -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(_) -> - ok = py_semaphore:acquire(1000), - ok = py_semaphore:release() - end, lists:seq(1, N)) + lists:foreach( + fun(_) -> + ok = py_semaphore:acquire(1000), + ok = py_semaphore:release() + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -250,48 +270,55 @@ bench_schedule_inline(N) -> %% Set up test functions Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ -import erlang - -def increment(x): - return x + 1 - -__main__.increment = increment - -# Chain using schedule_py (messaging overhead) -def chain_schedule_py(x, count): - if count <= 0: - return x - x = erlang.schedule_py('__main__', 'increment', [x]) - return erlang.schedule_py('__main__', 'chain_schedule_py', [x, count - 1]) - -__main__.chain_schedule_py = chain_schedule_py - -# Chain using schedule_inline (no messaging) -def chain_schedule_inline(x, count): - if count <= 0: - return x - x = increment(x) - return erlang.schedule_inline('__main__', 'chain_schedule_inline', [x, count - 1]) - -__main__.chain_schedule_inline = chain_schedule_inline -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "import erlang\n" + "\n" + "def increment(x):\n" + " return x + 1\n" + "\n" + "__main__.increment = increment\n" + "\n" + "# Chain using schedule_py (messaging overhead)\n" + "def chain_schedule_py(x, count):\n" + " if count <= 0:\n" + " return x\n" + " x = erlang.schedule_py('__main__', 'increment', [x])\n" + " return erlang.schedule_py('__main__', 'chain_schedule_py', [x, count - 1])\n" + "\n" + "__main__.chain_schedule_py = chain_schedule_py\n" + "\n" + "# Chain using schedule_inline (no messaging)\n" + "def chain_schedule_inline(x, count):\n" + " if count <= 0:\n" + " return x\n" + " x = increment(x)\n" + " return erlang.schedule_inline('__main__', 'chain_schedule_inline', [x, count - 1])\n" + "\n" + "__main__.chain_schedule_inline = chain_schedule_inline\n" + >>), ChainLen = 10, %% Benchmark schedule_py {TimePy, _} = timer:tc(fun() -> - lists:foreach(fun(_) -> - {ok, _} = py:call(Ctx, '__main__', chain_schedule_py, [0, ChainLen]) - end, lists:seq(1, N)) + lists:foreach( + fun(_) -> + {ok, _} = py:call(Ctx, '__main__', chain_schedule_py, [0, ChainLen]) + end, + lists:seq(1, N) + ) end), %% Benchmark schedule_inline {TimeInline, _} = timer:tc(fun() -> - lists:foreach(fun(_) -> - {ok, _} = py:call(Ctx, '__main__', chain_schedule_inline, [0, ChainLen]) - end, lists:seq(1, N)) + lists:foreach( + fun(_) -> + {ok, _} = py:call(Ctx, '__main__', chain_schedule_inline, [0, ChainLen]) + end, + lists:seq(1, N) + ) end), TotalCalls = N * ChainLen, diff --git a/examples/benchmark_compare.erl b/examples/benchmark_compare.erl index c7bfc8b..fd9e13d 100644 --- a/examples/benchmark_compare.erl +++ b/examples/benchmark_compare.erl @@ -58,9 +58,12 @@ bench_sync_call() -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -81,9 +84,12 @@ bench_sync_eval() -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:eval(<<"x * x + y">>, #{x => I, y => I}) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + {ok, _} = py:eval(<<"x * x + y">>, #{x => I, y => I}) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -108,10 +114,13 @@ bench_cast_single() -> io:format(" Iterations: ~p~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(I) -> - Ref = py:spawn_call(math, sqrt, [I]), - {ok, _} = py:await(Ref, 5000) - end, lists:seq(1, N)) + lists:foreach( + fun(I) -> + Ref = py:spawn_call(math, sqrt, [I]), + {ok, _} = py:await(Ref, 5000) + end, + lists:seq(1, N) + ) end), TimeMs = Time / 1000, @@ -132,13 +141,18 @@ bench_cast_multiple() -> io:format(" Batches: ~p (10 cast calls each)~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(Batch) -> - %% Start 10 cast calls - Refs = [py:spawn_call(math, sqrt, [Batch * 10 + I]) - || I <- lists:seq(1, 10)], - %% Await all - [{ok, _} = py:await(Ref, 5000) || Ref <- Refs] - end, lists:seq(1, N)) + lists:foreach( + fun(Batch) -> + %% Start 10 cast calls + Refs = [ + py:spawn_call(math, sqrt, [Batch * 10 + I]) + || I <- lists:seq(1, 10) + ], + %% Await all + [{ok, _} = py:await(Ref, 5000) || Ref <- Refs] + end, + lists:seq(1, N) + ) end), TotalCalls = N * 10, @@ -160,13 +174,18 @@ bench_cast_parallel() -> io:format(" Batches: ~p (10 concurrent calls each)~n", [N]), {Time, _} = timer:tc(fun() -> - lists:foreach(fun(Batch) -> - %% Start 10 cast calls in parallel - Refs = [py:spawn_call(math, factorial, [20 + (Batch rem 10)]) - || _ <- lists:seq(1, 10)], - %% Await all results - [py:await(Ref, 5000) || Ref <- Refs] - end, lists:seq(1, N)) + lists:foreach( + fun(Batch) -> + %% Start 10 cast calls in parallel + Refs = [ + py:spawn_call(math, factorial, [20 + (Batch rem 10)]) + || _ <- lists:seq(1, 10) + ], + %% Await all results + [py:await(Ref, 5000) || Ref <- Refs] + end, + lists:seq(1, N) + ) end), TotalCalls = N * 10, @@ -191,20 +210,33 @@ bench_concurrent_sync() -> TotalCalls = NumProcs * CallsPerProc, io:format("▶ ~s~n", [Name]), - io:format(" Processes: ~p, Calls/proc: ~p, Total: ~p~n", - [NumProcs, CallsPerProc, TotalCalls]), + io:format( + " Processes: ~p, Calls/proc: ~p, Total: ~p~n", + [NumProcs, CallsPerProc, TotalCalls] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - {ok, _} = py:call(math, sqrt, [I]) - end, lists:seq(1, CallsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + {ok, _} = py:call(math, sqrt, [I]) + end, + lists:seq(1, CallsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), TimeMs = Time / 1000, @@ -222,21 +254,34 @@ bench_concurrent_cast() -> TotalCalls = NumProcs * CallsPerProc, io:format("▶ ~s~n", [Name]), - io:format(" Processes: ~p, Casts/proc: ~p, Total: ~p~n", - [NumProcs, CallsPerProc, TotalCalls]), + io:format( + " Processes: ~p, Casts/proc: ~p, Total: ~p~n", + [NumProcs, CallsPerProc, TotalCalls] + ), Parent = self(), {Time, _} = timer:tc(fun() -> - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - Ref = py:spawn_call(math, factorial, [20 + I]), - {ok, _} = py:await(Ref, 5000) - end, lists:seq(1, CallsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], - - [receive {done, Pid} -> ok end || Pid <- Pids] + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + Ref = py:spawn_call(math, factorial, [20 + I]), + {ok, _} = py:await(Ref, 5000) + end, + lists:seq(1, CallsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], + + [ + receive + {done, Pid} -> ok + end + || Pid <- Pids + ] end), TimeMs = Time / 1000, @@ -260,19 +305,26 @@ print_summary(Results) -> io:format("│ Benchmark │ Latency │ Thru/sec │~n"), io:format("├────────────────────────────────────────┼───────────┼───────────┤~n"), - lists:foreach(fun({Name, Latency, Throughput}) -> - LatStr = if - Latency < 0 -> "N/A"; - Latency < 1000 -> io_lib:format("~.3f ms", [Latency]); - true -> io_lib:format("~.1f ms", [Latency]) - end, - ThrStr = if - Throughput =:= 0 -> "N/A"; - true -> integer_to_list(Throughput) + lists:foreach( + fun({Name, Latency, Throughput}) -> + LatStr = + if + Latency < 0 -> "N/A"; + Latency < 1000 -> io_lib:format("~.3f ms", [Latency]); + true -> io_lib:format("~.1f ms", [Latency]) + end, + ThrStr = + if + Throughput =:= 0 -> "N/A"; + true -> integer_to_list(Throughput) + end, + io:format( + "│ ~-38s │ ~-9s │ ~-9s │~n", + [string:slice(Name, 0, 38), LatStr, ThrStr] + ) end, - io:format("│ ~-38s │ ~-9s │ ~-9s │~n", - [string:slice(Name, 0, 38), LatStr, ThrStr]) - end, Results), + Results + ), io:format("└────────────────────────────────────────┴───────────┴───────────┘~n~n"), diff --git a/examples/distributed_python.erl b/examples/distributed_python.erl index 6f07f36..371aafc 100644 --- a/examples/distributed_python.erl +++ b/examples/distributed_python.erl @@ -101,12 +101,15 @@ demo_distributed(Workers) -> %% Setup Python on all workers io:format("Setting up Python environments on workers...~n"), - lists:foreach(fun(Node) -> - case setup_remote_node(Node) of - ok -> io:format(" ~p: ready~n", [Node]); - {error, Reason} -> io:format(" ~p: failed (~p)~n", [Node, Reason]) - end - end, Workers), + lists:foreach( + fun(Node) -> + case setup_remote_node(Node) of + ok -> io:format(" ~p: ready~n", [Node]); + {error, Reason} -> io:format(" ~p: failed (~p)~n", [Node, Reason]) + end + end, + Workers + ), %% Demo 1: Distribute computation across nodes demo_distributed_compute(Workers), @@ -120,9 +123,12 @@ demo_distributed(Workers) -> %% Demo 4: Cluster status io:format("~nCluster Status:~n"), Status = cluster_status(), - lists:foreach(fun({Node, S}) -> - io:format(" ~p: ~p~n", [Node, S]) - end, Status), + lists:foreach( + fun({Node, S}) -> + io:format(" ~p: ~p~n", [Node, S]) + end, + Status + ), ok. @@ -164,18 +170,26 @@ demo_parallel_map() -> %% Sequential for comparison SeqStart = erlang:monotonic_time(millisecond), - SeqResults = [begin - timer:sleep(50), %% Simulate work - N * N - end || N <- Numbers], + SeqResults = [ + begin + %% Simulate work + timer:sleep(50), + N * N + end + || N <- Numbers + ], SeqTime = erlang:monotonic_time(millisecond) - SeqStart, %% Parallel using multiple Erlang processes ParStart = erlang:monotonic_time(millisecond), - ParResults = parallel_map_local(fun(N) -> - timer:sleep(50), %% Simulate work - N * N - end, Numbers), + ParResults = parallel_map_local( + fun(N) -> + %% Simulate work + timer:sleep(50), + N * N + end, + Numbers + ), ParTime = erlang:monotonic_time(millisecond) - ParStart, io:format(" Input: ~p~n", [Numbers]), @@ -192,7 +206,7 @@ demo_async_tasks() -> Tasks = [ {math, pow, [2, I]} - || I <- lists:seq(1, 5) + || I <- lists:seq(1, 5) ], Start = erlang:monotonic_time(millisecond), @@ -200,7 +214,7 @@ demo_async_tasks() -> %% Create tasks (non-blocking) Refs = [ py_event_loop:create_task(M, F, A) - || {M, F, A} <- Tasks + || {M, F, A} <- Tasks ], %% Await all results @@ -249,9 +263,14 @@ parallel_map_numpy(Nodes, Items) -> %% Submit work to each node asynchronously using numpy Keys = [ - {Node, Batch, rpc:async_call(Node, py, eval, - [<<"list(__import__('numpy').sqrt(data))">>, #{data => Batch}])} - || {Node, Batch} <- NodePartitions, Batch =/= [] + {Node, Batch, + rpc:async_call( + Node, + py, + eval, + [<<"list(__import__('numpy').sqrt(data))">>, #{data => Batch}] + )} + || {Node, Batch} <- NodePartitions, Batch =/= [] ], %% Collect results @@ -260,7 +279,7 @@ parallel_map_numpy(Nodes, Items) -> {ok, R} when is_list(R) -> R; _ -> [] end - || {_Node, _Batch, Key} <- Keys + || {_Node, _Batch, Key} <- Keys ]). demo_distributed_inference(Workers) -> @@ -270,7 +289,7 @@ demo_distributed_inference(Workers) -> %% Simulated input data (batch of feature vectors) Inputs = [ [rand:uniform() || _ <- lists:seq(1, 10)] - || _ <- lists:seq(1, 20) + || _ <- lists:seq(1, 20) ], Start = erlang:monotonic_time(millisecond), @@ -291,7 +310,10 @@ demo_distributed_pipeline(Workers) -> %% Define pipeline stages using numpy (each runs on a different node) Stages = [ {lists:nth(1, Workers), <<"list(__import__('numpy').sqrt(data))">>}, - {lists:nth((2 rem length(Workers)) + 1, Workers), <<"list(__import__('numpy').floor(data))">>} + { + lists:nth((2 rem length(Workers)) + 1, Workers), + <<"list(__import__('numpy').floor(data))">> + } ], Start = erlang:monotonic_time(millisecond), @@ -353,17 +375,20 @@ parallel_map(Nodes, Module, Func, Items) -> %% Submit work to each node asynchronously Keys = [ {Node, Batch, rpc:async_call(Node, py, call, [Module, Func, [Batch]])} - || {Node, Batch} <- NodePartitions, Batch =/= [] + || {Node, Batch} <- NodePartitions, Batch =/= [] ], %% Collect results in order - Results = lists:flatmap(fun({_Node, Batch, Key}) -> - case rpc:yield(Key) of - {ok, R} when is_list(R) -> R; - {ok, R} -> [R || _ <- Batch]; - {badrpc, _} -> [{error, failed} || _ <- Batch] - end - end, Keys), + Results = lists:flatmap( + fun({_Node, Batch, Key}) -> + case rpc:yield(Key) of + {ok, R} when is_list(R) -> R; + {ok, R} -> [R || _ <- Batch]; + {badrpc, _} -> [{error, failed} || _ <- Batch] + end + end, + Keys + ), Results. @@ -376,16 +401,20 @@ distributed_inference(Nodes, Inputs) -> %% Assign each input to a node Assignments = [ {lists:nth(((I - 1) rem NodeCount) + 1, Nodes), Input} - || {I, Input} <- IndexedInputs + || {I, Input} <- IndexedInputs ], %% Submit all inference requests Refs = [ - {rpc:async_call(Node, py, eval, [ - <<"sum(x) / len(x)">>, %% Simple "inference" - compute mean - #{x => Input} - ]), Node} - || {Node, Input} <- Assignments + { + rpc:async_call(Node, py, eval, [ + %% Simple "inference" - compute mean + <<"sum(x) / len(x)">>, + #{x => Input} + ]), + Node + } + || {Node, Input} <- Assignments ], %% Collect results with timeout handling @@ -394,7 +423,7 @@ distributed_inference(Nodes, Inputs) -> {value, Result} -> Result; timeout -> {error, timeout} end - || {Key, _Node} <- Refs + || {Key, _Node} <- Refs ]. %% @doc Get cluster status @@ -425,14 +454,18 @@ local_status() -> %% @doc Run data through a pipeline of stages across nodes pipeline(Data, Stages) -> - lists:foldl(fun({Node, Expr}, Acc) -> - case rpc:call(Node, py, eval, [Expr, #{data => Acc}], 30000) of - {ok, Result} when is_list(Result) -> Result; - {ok, Result} -> [Result]; - {badrpc, _} -> Acc; - {error, _} -> Acc - end - end, Data, Stages). + lists:foldl( + fun({Node, Expr}, Acc) -> + case rpc:call(Node, py, eval, [Expr, #{data => Acc}], 30000) of + {ok, Result} when is_list(Result) -> Result; + {ok, Result} -> [Result]; + {badrpc, _} -> Acc; + {error, _} -> Acc + end + end, + Data, + Stages + ). %%% ============================================================================ %%% Helper Functions @@ -462,7 +495,12 @@ parallel_map_local(Fun, Items) -> end), Ref end - || Item <- Items + || Item <- Items ], - [receive {Ref, Result} -> Result after 5000 -> {error, timeout} end - || Ref <- Refs]. + [ + receive + {Ref, Result} -> Result + after 5000 -> {error, timeout} + end + || Ref <- Refs + ]. diff --git a/examples/embedder_example.erl b/examples/embedder_example.erl index 67bea96..3280094 100644 --- a/examples/embedder_example.erl +++ b/examples/embedder_example.erl @@ -28,10 +28,11 @@ main(Args) -> io:format("~n=== Sentence-Transformers Embedder Example ===~n~n"), %% Activate venv - VenvPath = case Args of - [Path | _] -> Path; - [] -> "/tmp/embedder-venv" - end, + VenvPath = + case Args of + [Path | _] -> Path; + [] -> "/tmp/embedder-venv" + end, io:format("Activating venv: ~s~n", [VenvPath]), case py:activate_venv(VenvPath) of @@ -39,15 +40,20 @@ main(Args) -> io:format("Venv activated~n~n"); {error, VenvError} -> io:format("Error: ~p~n", [VenvError]), - io:format("Run: python -m venv ~s && ~s/bin/pip install sentence-transformers~n", [VenvPath, VenvPath]), + io:format("Run: python -m venv ~s && ~s/bin/pip install sentence-transformers~n", [ + VenvPath, VenvPath + ]), halt(1) end, %% Add examples directory to Python path and import module with reload ExamplesDir = filename:join(ProjectRoot, "examples"), - PathSetup = list_to_binary(io_lib:format( - "(lambda: (__import__('sys').path.insert(0, '~s') if '~s' not in __import__('sys').path else None, __import__('importlib').reload(__import__('embedding_helper'))))()[1]", - [ExamplesDir, ExamplesDir])), + PathSetup = list_to_binary( + io_lib:format( + "(lambda: (__import__('sys').path.insert(0, '~s') if '~s' not in __import__('sys').path else None, __import__('importlib').reload(__import__('embedding_helper'))))()[1]", + [ExamplesDir, ExamplesDir] + ) + ), %% Get model info (this loads the model) io:format("Loading model...~n"), @@ -67,8 +73,10 @@ main(Args) -> io:format("=== Embeddings ===~n"), lists:foreach( fun({Text, Emb}) -> - io:format(" ~s~n -> [~.4f, ~.4f, ...] (dim=~p)~n", - [Text, hd(Emb), lists:nth(2, Emb), length(Emb)]) + io:format( + " ~s~n -> [~.4f, ~.4f, ...] (dim=~p)~n", + [Text, hd(Emb), lists:nth(2, Emb), length(Emb)] + ) end, lists:zip(Texts, Embeddings) ), @@ -80,8 +88,10 @@ main(Args) -> io:format("Query: ~s~n~n", [Query]), - Similarities = [{cosine_similarity(QueryEmb, Emb), Text} - || {Text, Emb} <- lists:zip(Texts, Embeddings)], + Similarities = [ + {cosine_similarity(QueryEmb, Emb), Text} + || {Text, Emb} <- lists:zip(Texts, Embeddings) + ], Sorted = lists:reverse(lists:keysort(1, Similarities)), lists:foreach( diff --git a/examples/erlang_concurrency.erl b/examples/erlang_concurrency.erl index 020ac08..17ada93 100644 --- a/examples/erlang_concurrency.erl +++ b/examples/erlang_concurrency.erl @@ -54,15 +54,30 @@ examples_dir() -> list_to_binary(filename:join(ProjectRoot, "examples")). add_to_python_path(Dir) -> - {ok, _} = py:eval(<<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, #{path => Dir}), + {ok, _} = py:eval( + <<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, + #{path => Dir} + ), ok. cleanup() -> %% Unregister all functions - lists:foreach(fun(Name) -> - py:unregister_function(Name) - end, [slow_compute, fast_compute, spawn_workers, parallel_fetch, - parallel_map, fib, prime_check, process_item, echo]), + lists:foreach( + fun(Name) -> + py:unregister_function(Name) + end, + [ + slow_compute, + fast_compute, + spawn_workers, + parallel_fetch, + parallel_map, + fib, + prime_check, + process_item, + echo + ] + ), ok = application:stop(erlang_python). %%% ============================================================================ @@ -75,7 +90,8 @@ register_functions() -> %% Simulated slow computation (sleeps to simulate I/O or heavy work) py:register_function(slow_compute, fun([N]) -> - timer:sleep(100), % 100ms delay + % 100ms delay + timer:sleep(100), N * N end), @@ -120,45 +136,57 @@ register_functions() -> %% Spawn multiple Erlang workers and collect results py:register_function(spawn_workers, fun([Tasks]) -> Parent = self(), - Refs = lists:map(fun(Task) -> - Ref = make_ref(), - spawn(fun() -> - Result = execute_task(Task), - Parent ! {Ref, Result} - end), - Ref - end, Tasks), + Refs = lists:map( + fun(Task) -> + Ref = make_ref(), + spawn(fun() -> + Result = execute_task(Task), + Parent ! {Ref, Result} + end), + Ref + end, + Tasks + ), %% Collect all results - lists:map(fun(Ref) -> - receive - {Ref, Result} -> Result - after 5000 -> - {error, timeout} - end - end, Refs) + lists:map( + fun(Ref) -> + receive + {Ref, Result} -> Result + after 5000 -> + {error, timeout} + end + end, + Refs + ) end), %% Parallel fetch simulation using Erlang processes py:register_function(parallel_fetch, fun([Urls]) -> Parent = self(), - Refs = lists:map(fun(Url) -> - Ref = make_ref(), - spawn(fun() -> - %% Simulate HTTP fetch with variable latency - Latency = rand:uniform(100) + 50, - timer:sleep(Latency), - Result = #{url => Url, status => 200, latency_ms => Latency}, - Parent ! {Ref, Result} - end), - Ref - end, Urls), - lists:map(fun(Ref) -> - receive - {Ref, Result} -> Result - after 5000 -> - {error, timeout} - end - end, Refs) + Refs = lists:map( + fun(Url) -> + Ref = make_ref(), + spawn(fun() -> + %% Simulate HTTP fetch with variable latency + Latency = rand:uniform(100) + 50, + timer:sleep(Latency), + Result = #{url => Url, status => 200, latency_ms => Latency}, + Parent ! {Ref, Result} + end), + Ref + end, + Urls + ), + lists:map( + fun(Ref) -> + receive + {Ref, Result} -> Result + after 5000 -> + {error, timeout} + end + end, + Refs + ) end), io:format(" Registered: echo, slow_compute, fast_compute, fib, prime_check~n"), @@ -171,23 +199,29 @@ parallel_map_impl(FuncName, Items) when is_binary(FuncName) -> parallel_map_impl(FuncName, Items) -> Parent = self(), %% Spawn a process for each item - RefsAndItems = lists:map(fun(Item) -> - Ref = make_ref(), - spawn(fun() -> - %% Execute the named function - Result = execute_function(FuncName, Item), - Parent ! {Ref, Result} - end), - {Ref, Item} - end, Items), + RefsAndItems = lists:map( + fun(Item) -> + Ref = make_ref(), + spawn(fun() -> + %% Execute the named function + Result = execute_function(FuncName, Item), + Parent ! {Ref, Result} + end), + {Ref, Item} + end, + Items + ), %% Collect results in order - lists:map(fun({Ref, _Item}) -> - receive - {Ref, Result} -> Result - after 5000 -> - {error, timeout} - end - end, RefsAndItems). + lists:map( + fun({Ref, _Item}) -> + receive + {Ref, Result} -> Result + after 5000 -> + {error, timeout} + end + end, + RefsAndItems + ). %% Execute a registered function by name execute_function(slow_compute, N) -> @@ -221,7 +255,9 @@ demo_basic_callbacks() -> io:format("~n--- Demo 1: Basic Erlang Callbacks ---~n"), %% Test echo - {ok, Echo} = py:eval(<<"__import__('erlang_concurrency').call_erlang('echo', 'Hello from Python!')">>), + {ok, Echo} = py:eval( + <<"__import__('erlang_concurrency').call_erlang('echo', 'Hello from Python!')">> + ), io:format(" Echo result: ~s~n", [Echo]), %% Test computation @@ -280,12 +316,17 @@ demo_erlang_processes() -> ), EndTime = erlang:monotonic_time(millisecond), - io:format(" Completed ~p items in ~p ms (each takes 50ms, parallel!)~n", - [length(Items), EndTime - StartTime]), + io:format( + " Completed ~p items in ~p ms (each takes 50ms, parallel!)~n", + [length(Items), EndTime - StartTime] + ), io:format(" Results:~n"), - lists:foreach(fun(R) -> - io:format(" ~p~n", [R]) - end, Results), + lists:foreach( + fun(R) -> + io:format(" ~p~n", [R]) + end, + Results + ), ok. @@ -312,9 +353,12 @@ demo_distributed_work() -> io:format(" Completed in ~p ms~n", [EndTime - StartTime]), io:format(" Results:~n"), - lists:foreach(fun(R) -> - io:format(" ~p~n", [R]) - end, Results), + lists:foreach( + fun(R) -> + io:format(" ~p~n", [R]) + end, + Results + ), %% Demonstrate parallel_fetch io:format("~n Simulating parallel HTTP fetches via Erlang processes...~n"), @@ -335,12 +379,19 @@ demo_distributed_work() -> %% Calculate total latency if sequential TotalLatency = lists:sum([maps:get(<<"latency_ms">>, R, 0) || R <- FetchResults]), - io:format(" Fetched ~p URLs in ~p ms (would be ~p ms sequential):~n", - [length(Urls), EndTime2 - StartTime2, TotalLatency]), - lists:foreach(fun(R) -> - io:format(" ~s: ~p ms~n", - [maps:get(<<"url">>, R), maps:get(<<"latency_ms">>, R)]) - end, FetchResults), + io:format( + " Fetched ~p URLs in ~p ms (would be ~p ms sequential):~n", + [length(Urls), EndTime2 - StartTime2, TotalLatency] + ), + lists:foreach( + fun(R) -> + io:format( + " ~s: ~p ms~n", + [maps:get(<<"url">>, R), maps:get(<<"latency_ms">>, R)] + ) + end, + FetchResults + ), ok. @@ -350,7 +401,7 @@ demo_distributed_work() -> fib(0) -> 0; fib(1) -> 1; -fib(N) when N > 1 -> fib(N-1) + fib(N-2). +fib(N) when N > 1 -> fib(N - 1) + fib(N - 2). is_prime(N) when N < 2 -> false; is_prime(2) -> true; @@ -372,10 +423,12 @@ process_data(Item) -> #{original => Item, processed => Item}. execute_task(#{<<"type">> := <<"compute">>, <<"value">> := V}) -> - timer:sleep(50), % Simulate computation + % Simulate computation + timer:sleep(50), #{result => V * 2, type => compute}; execute_task(#{<<"type">> := <<"io">>, <<"value">> := V}) -> - timer:sleep(rand:uniform(100)), % Simulate I/O with variable latency + % Simulate I/O with variable latency + timer:sleep(rand:uniform(100)), #{result => V, type => io}; execute_task(Task) -> #{result => Task, type => unknown}. diff --git a/examples/logging_example.erl b/examples/logging_example.erl index 9cfd3df..2152972 100755 --- a/examples/logging_example.erl +++ b/examples/logging_example.erl @@ -35,17 +35,18 @@ logging_demo() -> %% Log messages from Python io:format("Sending log messages from Python:~n"), - ok = py:exec(<<" -import logging - -# Create a custom logger -logger = logging.getLogger('myapp') - -logger.debug('Debug: detailed diagnostic info') -logger.info('Info: normal operation message') -logger.warning('Warning: something unexpected') -logger.error('Error: something failed') -">>), + ok = py:exec(<< + "\n" + "import logging\n" + "\n" + "# Create a custom logger\n" + "logger = logging.getLogger('myapp')\n" + "\n" + "logger.debug('Debug: detailed diagnostic info')\n" + "logger.info('Info: normal operation message')\n" + "logger.warning('Warning: something unexpected')\n" + "logger.error('Error: something failed')\n" + >>), %% Give async messages time to be delivered timer:sleep(100), @@ -61,80 +62,85 @@ tracing_demo() -> %% Create some traced operations io:format("Running traced Python code...~n~n"), - ok = py:exec(<<" -import erlang -import time - -# Basic span -with erlang.Span('process-order', order_id=12345): - time.sleep(0.001) # Simulate work - -# Nested spans -with erlang.Span('handle-request', endpoint='/api/users'): - with erlang.Span('validate-input'): - time.sleep(0.0005) - with erlang.Span('query-database', table='users'): - time.sleep(0.001) - with erlang.Span('format-response'): - time.sleep(0.0002) - -# Span with events -with erlang.Span('batch-process') as span: - span.event('started', batch_size=100) - time.sleep(0.0005) - span.event('progress', completed=50, remaining=50) - time.sleep(0.0005) - span.event('finished', total_processed=100) - -# Traced function using decorator -@erlang.trace() -def calculate_something(): - time.sleep(0.0002) - return 42 - -result = calculate_something() - -# Span with error -try: - with erlang.Span('risky-operation'): - raise ValueError('Something went wrong!') -except ValueError: - pass -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import time\n" + "\n" + "# Basic span\n" + "with erlang.Span('process-order', order_id=12345):\n" + " time.sleep(0.001) # Simulate work\n" + "\n" + "# Nested spans\n" + "with erlang.Span('handle-request', endpoint='/api/users'):\n" + " with erlang.Span('validate-input'):\n" + " time.sleep(0.0005)\n" + " with erlang.Span('query-database', table='users'):\n" + " time.sleep(0.001)\n" + " with erlang.Span('format-response'):\n" + " time.sleep(0.0002)\n" + "\n" + "# Span with events\n" + "with erlang.Span('batch-process') as span:\n" + " span.event('started', batch_size=100)\n" + " time.sleep(0.0005)\n" + " span.event('progress', completed=50, remaining=50)\n" + " time.sleep(0.0005)\n" + " span.event('finished', total_processed=100)\n" + "\n" + "# Traced function using decorator\n" + "@erlang.trace()\n" + "def calculate_something():\n" + " time.sleep(0.0002)\n" + " return 42\n" + "\n" + "result = calculate_something()\n" + "\n" + "# Span with error\n" + "try:\n" + " with erlang.Span('risky-operation'):\n" + " raise ValueError('Something went wrong!')\n" + "except ValueError:\n" + " pass\n" + >>), %% Retrieve and display spans {ok, Spans} = py:get_traces(), io:format("Collected ~p spans:~n~n", [length(Spans)]), - lists:foreach(fun(Span) -> - Name = maps:get(name, Span), - Status = maps:get(status, Span), - Duration = maps:get(duration_us, Span), - ParentId = maps:get(parent_id, Span), - Events = maps:get(events, Span, []), - Attrs = maps:get(attributes, Span), - - ParentStr = case ParentId of - undefined -> "none"; - _ -> integer_to_list(ParentId rem 10000) ++ "..." - end, - - io:format(" ~s~n", [Name]), - io:format(" Status: ~p, Duration: ~p us~n", [Status, Duration]), - io:format(" Parent: ~s~n", [ParentStr]), - - case maps:size(Attrs) of - 0 -> ok; - _ -> io:format(" Attributes: ~p~n", [Attrs]) - end, - - case length(Events) of - 0 -> ok; - N -> io:format(" Events: ~p~n", [N]) + lists:foreach( + fun(Span) -> + Name = maps:get(name, Span), + Status = maps:get(status, Span), + Duration = maps:get(duration_us, Span), + ParentId = maps:get(parent_id, Span), + Events = maps:get(events, Span, []), + Attrs = maps:get(attributes, Span), + + ParentStr = + case ParentId of + undefined -> "none"; + _ -> integer_to_list(ParentId rem 10000) ++ "..." + end, + + io:format(" ~s~n", [Name]), + io:format(" Status: ~p, Duration: ~p us~n", [Status, Duration]), + io:format(" Parent: ~s~n", [ParentStr]), + + case maps:size(Attrs) of + 0 -> ok; + _ -> io:format(" Attributes: ~p~n", [Attrs]) + end, + + case length(Events) of + 0 -> ok; + N -> io:format(" Events: ~p~n", [N]) + end, + + io:format("~n") end, - - io:format("~n") - end, Spans), + Spans + ), %% Clean up ok = py:clear_traces(), diff --git a/examples/py_buffer_example.erl b/examples/py_buffer_example.erl index 8fcb135..2ad3410 100755 --- a/examples/py_buffer_example.erl +++ b/examples/py_buffer_example.erl @@ -60,12 +60,13 @@ basic_buffer_demo() -> %% Pass to Python and read io:format("Reading from Python...~n"), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -def read_all(buf): - data = buf.read() - print(f' Read {len(data)} bytes: {data}') - return data -">>), + ok = py:exec(Ctx, << + "\n" + "def read_all(buf):\n" + " data = buf.read()\n" + " print(f' Read {len(data)} bytes: {data}')\n" + " return data\n" + >>), {ok, Data} = py:eval(Ctx, <<"read_all(buf)">>, #{<<"buf">> => Buf}), io:format("Erlang received: ~p~n~n", [Data]), @@ -89,30 +90,31 @@ http_body_demo() -> %% Build WSGI-like environ Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import json - -def handle_request(environ): - '''Simulate WSGI request handler.''' - method = environ.get('REQUEST_METHOD', 'GET') - path = environ.get('PATH_INFO', '/') - content_type = environ.get('CONTENT_TYPE', '') - - print(f' {method} {path}') - print(f' Content-Type: {content_type}') - - # Read body from wsgi.input (PyBuffer) - wsgi_input = environ.get('wsgi.input') - if wsgi_input: - body = wsgi_input.read() - print(f' Body ({len(body)} bytes): {body[:50]}...' if len(body) > 50 else f' Body: {body}') - - if content_type == 'application/json': - data = json.loads(body) - return {'status': 'ok', 'user': data.get('user')} - - return {'status': 'ok'} -">>), + ok = py:exec(Ctx, << + "\n" + "import json\n" + "\n" + "def handle_request(environ):\n" + " '''Simulate WSGI request handler.'''\n" + " method = environ.get('REQUEST_METHOD', 'GET')\n" + " path = environ.get('PATH_INFO', '/')\n" + " content_type = environ.get('CONTENT_TYPE', '')\n" + "\n" + " print(f' {method} {path}')\n" + " print(f' Content-Type: {content_type}')\n" + "\n" + " # Read body from wsgi.input (PyBuffer)\n" + " wsgi_input = environ.get('wsgi.input')\n" + " if wsgi_input:\n" + " body = wsgi_input.read()\n" + " print(f' Body ({len(body)} bytes): {body[:50]}...' if len(body) > 50 else f' Body: {body}')\n" + "\n" + " if content_type == 'application/json':\n" + " data = json.loads(body)\n" + " return {'status': 'ok', 'user': data.get('user')}\n" + "\n" + " return {'status': 'ok'}\n" + >>), Environ = #{ <<"REQUEST_METHOD">> => <<"POST">>, @@ -138,34 +140,35 @@ file_like_demo() -> ok = py_buffer:write(Buf, <<"Role: Admin\n">>), ok = py_buffer:close(Buf), - ok = py:exec(Ctx, <<" -def demonstrate_file_methods(buf): - '''Show file-like methods.''' - print(' File-like properties:') - print(f' readable(): {buf.readable()}') - print(f' writable(): {buf.writable()}') - print(f' seekable(): {buf.seekable()}') - print(f' len(buf): {len(buf)}') - print() - - # Read first line - line1 = buf.readline() - print(f' readline(): {line1}') - - # Current position - pos = buf.tell() - print(f' tell(): {pos}') - - # Seek back to start - buf.seek(0) - print(f' seek(0), tell(): {buf.tell()}') - - # Read all remaining - rest = buf.read() - print(f' read(): {rest[:30]}...') - - return 'done' -">>), + ok = py:exec(Ctx, << + "\n" + "def demonstrate_file_methods(buf):\n" + " '''Show file-like methods.'''\n" + " print(' File-like properties:')\n" + " print(f' readable(): {buf.readable()}')\n" + " print(f' writable(): {buf.writable()}')\n" + " print(f' seekable(): {buf.seekable()}')\n" + " print(f' len(buf): {len(buf)}')\n" + " print()\n" + "\n" + " # Read first line\n" + " line1 = buf.readline()\n" + " print(f' readline(): {line1}')\n" + "\n" + " # Current position\n" + " pos = buf.tell()\n" + " print(f' tell(): {pos}')\n" + "\n" + " # Seek back to start\n" + " buf.seek(0)\n" + " print(f' seek(0), tell(): {buf.tell()}')\n" + "\n" + " # Read all remaining\n" + " rest = buf.read()\n" + " print(f' read(): {rest[:30]}...')\n" + "\n" + " return 'done'\n" + >>), {ok, _} = py:eval(Ctx, <<"demonstrate_file_methods(buf)">>, #{<<"buf">> => Buf}), io:format("~n"), @@ -182,36 +185,37 @@ memoryview_demo() -> ok = py_buffer:write(Buf, Data), ok = py_buffer:close(Buf), - ok = py:exec(Ctx, <<" -def zero_copy_parse(buf): - '''Demonstrate zero-copy access via memoryview.''' - - # Get memoryview - no data copying! - mv = memoryview(buf) - print(f' memoryview created, {len(mv)} bytes') - print(f' readonly: {mv.readonly}') - print(f' ndim: {mv.ndim}') - - # Find colon positions using find (uses memchr internally) - data_bytes = bytes(mv) # Only for find, still efficient - - # Parse header - first_colon = buf.find(b':') - header = bytes(mv[:first_colon]) - print(f' Header: {header}') - - # Find PAYLOAD section - payload_start = buf.find(b'PAYLOAD:') + 8 - payload_end = buf.find(b':END') - payload = bytes(mv[payload_start:payload_end]) - print(f' Payload: {payload}') - - # Release memoryview - mv.release() - print(' memoryview released') - - return payload -">>), + ok = py:exec(Ctx, << + "\n" + "def zero_copy_parse(buf):\n" + " '''Demonstrate zero-copy access via memoryview.'''\n" + "\n" + " # Get memoryview - no data copying!\n" + " mv = memoryview(buf)\n" + " print(f' memoryview created, {len(mv)} bytes')\n" + " print(f' readonly: {mv.readonly}')\n" + " print(f' ndim: {mv.ndim}')\n" + "\n" + " # Find colon positions using find (uses memchr internally)\n" + " data_bytes = bytes(mv) # Only for find, still efficient\n" + "\n" + " # Parse header\n" + " first_colon = buf.find(b':')\n" + " header = bytes(mv[:first_colon])\n" + " print(f' Header: {header}')\n" + "\n" + " # Find PAYLOAD section\n" + " payload_start = buf.find(b'PAYLOAD:') + 8\n" + " payload_end = buf.find(b':END')\n" + " payload = bytes(mv[payload_start:payload_end])\n" + " print(f' Payload: {payload}')\n" + "\n" + " # Release memoryview\n" + " mv.release()\n" + " print(' memoryview released')\n" + "\n" + " return payload\n" + >>), {ok, Payload} = py:eval(Ctx, <<"zero_copy_parse(buf)">>, #{<<"buf">> => Buf}), io:format("Extracted payload: ~p~n~n", [Payload]), @@ -230,29 +234,30 @@ line_iteration_demo() -> ok = py_buffer:write(Buf, <<"3,Charlie,92\n">>), ok = py_buffer:close(Buf), - ok = py:exec(Ctx, <<" -def process_csv(buf): - '''Iterate over lines like a file.''' - records = [] - header = None - - for line in buf: - line = line.strip() - if not line: - continue - - parts = line.decode().split(',') - - if header is None: - header = parts - print(f' Header: {header}') - else: - record = dict(zip(header, parts)) - records.append(record) - print(f' Record: {record}') - - return records -">>), + ok = py:exec(Ctx, << + "\n" + "def process_csv(buf):\n" + " '''Iterate over lines like a file.'''\n" + " records = []\n" + " header = None\n" + "\n" + " for line in buf:\n" + " line = line.strip()\n" + " if not line:\n" + " continue\n" + "\n" + " parts = line.decode().split(',')\n" + "\n" + " if header is None:\n" + " header = parts\n" + " print(f' Header: {header}')\n" + " else:\n" + " record = dict(zip(header, parts))\n" + " records.append(record)\n" + " print(f' Record: {record}')\n" + "\n" + " return records\n" + >>), {ok, Records} = py:eval(Ctx, <<"process_csv(buf)">>, #{<<"buf">> => Buf}), io:format("Parsed ~p records~n~n", [length(Records)]), @@ -267,35 +272,36 @@ asyncio_demo() -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio - -async def async_buffer_reader(buf): - '''Read from buffer asynchronously as Erlang streams data.''' - chunks = [] - read_count = 0 - - while not buf.at_eof(): - available = buf.readable_amount() - if available > 0: - chunk = buf.read_nonblock(available) - chunks.append(chunk) - read_count += 1 - print(f' [Python] Read chunk {read_count}: {len(chunk)} bytes') - else: - # Yield to event loop while waiting for Erlang to write more - await asyncio.sleep(0.005) - - return b''.join(chunks) - -def run_async_reader(buf): - '''Run async reader.''' - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(async_buffer_reader(buf)) - finally: - loop.close() -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def async_buffer_reader(buf):\n" + " '''Read from buffer asynchronously as Erlang streams data.'''\n" + " chunks = []\n" + " read_count = 0\n" + "\n" + " while not buf.at_eof():\n" + " available = buf.readable_amount()\n" + " if available > 0:\n" + " chunk = buf.read_nonblock(available)\n" + " chunks.append(chunk)\n" + " read_count += 1\n" + " print(f' [Python] Read chunk {read_count}: {len(chunk)} bytes')\n" + " else:\n" + " # Yield to event loop while waiting for Erlang to write more\n" + " await asyncio.sleep(0.005)\n" + "\n" + " return b''.join(chunks)\n" + "\n" + "def run_async_reader(buf):\n" + " '''Run async reader.'''\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(async_buffer_reader(buf))\n" + " finally:\n" + " loop.close()\n" + >>), %% Spawn a process to stream data from Erlang spawn_link(fun() -> @@ -304,11 +310,15 @@ def run_async_reader(buf): <<" Streaming chunk 2.">>, <<" Final chunk 3.">> ], - lists:foreach(fun(Chunk) -> - timer:sleep(30), %% Simulate network delay - io:format(" [Erlang] Writing: ~p~n", [Chunk]), - ok = py_buffer:write(Buf, Chunk) - end, Chunks), + lists:foreach( + fun(Chunk) -> + %% Simulate network delay + timer:sleep(30), + io:format(" [Erlang] Writing: ~p~n", [Chunk]), + ok = py_buffer:write(Buf, Chunk) + end, + Chunks + ), timer:sleep(10), io:format(" [Erlang] Closing buffer (EOF)~n"), ok = py_buffer:close(Buf), @@ -320,7 +330,10 @@ def run_async_reader(buf): {ok, Result} = py:eval(Ctx, <<"run_async_reader(buf)">>, #{<<"buf">> => Buf}), %% Wait for writer - receive writer_done -> ok after 2000 -> ok end, + receive + writer_done -> ok + after 2000 -> ok + end, io:format(" Final result: ~p~n~n", [Result]), ok. diff --git a/examples/rag_example.erl b/examples/rag_example.erl index 936239f..af178d3 100644 --- a/examples/rag_example.erl +++ b/examples/rag_example.erl @@ -28,10 +28,11 @@ main(Args) -> io:format("~n=== RAG (Retrieval-Augmented Generation) Example ===~n~n"), - VenvPath = case Args of - [Path | _] -> Path; - [] -> "/tmp/ai-venv" - end, + VenvPath = + case Args of + [Path | _] -> Path; + [] -> "/tmp/ai-venv" + end, case activate_venv(VenvPath) of ok -> ok; @@ -75,23 +76,29 @@ main(Args) -> <<"Can you update Erlang code while the system is running?">> ], - lists:foreach(fun(Question) -> - io:format("~n========================================~n"), - io:format("Question: ~s~n", [Question]), - io:format("========================================~n~n"), - - %% Retrieve relevant context - Context = retrieve(Question, Index, 2), - io:format("Retrieved context:~n"), - lists:foreach(fun({Score, Text}) -> - io:format(" [~.3f] ~s~n", [Score, Text]) - end, Context), - - %% Generate answer - io:format("~nGenerating answer...~n"), - Answer = generate_answer(Question, Context), - io:format("~nAnswer: ~s~n", [Answer]) - end, Questions), + lists:foreach( + fun(Question) -> + io:format("~n========================================~n"), + io:format("Question: ~s~n", [Question]), + io:format("========================================~n~n"), + + %% Retrieve relevant context + Context = retrieve(Question, Index, 2), + io:format("Retrieved context:~n"), + lists:foreach( + fun({Score, Text}) -> + io:format(" [~.3f] ~s~n", [Score, Text]) + end, + Context + ), + + %% Generate answer + io:format("~nGenerating answer...~n"), + Answer = generate_answer(Question, Context), + io:format("~nAnswer: ~s~n", [Answer]) + end, + Questions + ), io:format("~n=== Done ===~n~n"), cleanup(). @@ -122,7 +129,10 @@ activate_venv(VenvPath) -> end. add_to_python_path(Dir) -> - {ok, _} = py:eval(<<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, #{path => Dir}), + {ok, _} = py:eval( + <<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, + #{path => Dir} + ), ok. build_index(Documents) -> @@ -131,8 +141,10 @@ build_index(Documents) -> retrieve(Query, Index, TopK) -> {ok, QueryEmb} = py:call(ai_helpers, embed_single, [Query]), - Scored = [{cosine_similarity(QueryEmb, Emb), Text} - || {Text, Emb} <- Index], + Scored = [ + {cosine_similarity(QueryEmb, Emb), Text} + || {Text, Emb} <- Index + ], Sorted = lists:reverse(lists:sort(Scored)), lists:sublist(Sorted, TopK). diff --git a/examples/reactor_echo.erl b/examples/reactor_echo.erl index 40117b4..c9ea463 100644 --- a/examples/reactor_echo.erl +++ b/examples/reactor_echo.erl @@ -28,32 +28,33 @@ main(_) -> {ok, Ctx} = py_reactor_context:start_link(1, worker), %% Set up Python echo protocol - ok = py:exec(Ctx, <<" -import erlang.reactor as reactor - -class EchoProtocol(reactor.Protocol): - '''Simple echo protocol - sends back whatever it receives.''' - - def data_received(self, data): - # Echo data back - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'read_pending' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - if self.write_buffer: - return 'continue' - return 'read_pending' - - def connection_lost(self): - print(f'Connection closed: fd={self.fd}') - -reactor.set_protocol_factory(EchoProtocol) -print('Echo protocol registered') -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class EchoProtocol(reactor.Protocol):\n" + " '''Simple echo protocol - sends back whatever it receives.'''\n" + "\n" + " def data_received(self, data):\n" + " # Echo data back\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'read_pending'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " if self.write_buffer:\n" + " return 'continue'\n" + " return 'read_pending'\n" + "\n" + " def connection_lost(self):\n" + " print(f'Connection closed: fd={self.fd}')\n" + "\n" + "reactor.set_protocol_factory(EchoProtocol)\n" + "print('Echo protocol registered')\n" + >>), %% Listen on port 9999 Port = 9999, @@ -77,29 +78,29 @@ accept_loop(LSock, Ctx) -> {ok, Fd} = prim_inet:getfd(Sock), %% Get client info - ClientInfo = case inet:peername(Sock) of - {ok, {Addr, Port}} -> - #{addr => format_addr(Addr), port => Port}; - _ -> - #{addr => <<"unknown">>, port => 0} - end, - - io:format("Accepted connection from ~s:~p (fd=~p)~n", - [maps:get(addr, ClientInfo), maps:get(port, ClientInfo), Fd]), + ClientInfo = + case inet:peername(Sock) of + {ok, {Addr, Port}} -> + #{addr => format_addr(Addr), port => Port}; + _ -> + #{addr => <<"unknown">>, port => 0} + end, + + io:format( + "Accepted connection from ~s:~p (fd=~p)~n", + [maps:get(addr, ClientInfo), maps:get(port, ClientInfo), Fd] + ), %% Hand off to reactor context Ctx ! {fd_handoff, Fd, ClientInfo}, accept_loop(LSock, Ctx); - {error, timeout} -> %% No connection, keep waiting accept_loop(LSock, Ctx); - {error, closed} -> io:format("Listen socket closed~n"), ok; - {error, Reason} -> io:format("Accept error: ~p~n", [Reason]), accept_loop(LSock, Ctx) diff --git a/examples/reentrant_callback.erl b/examples/reentrant_callback.erl index dc00949..adf806f 100644 --- a/examples/reentrant_callback.erl +++ b/examples/reentrant_callback.erl @@ -35,11 +35,12 @@ simple_example() -> io:format("--- Simple Reentrant Callback ---~n"), %% Define a Python function - ok = py:exec(<<" -def square(x): - '''Simple Python function''' - return x * x -">>), + ok = py:exec(<< + "\n" + "def square(x):\n" + " '''Simple Python function'''\n" + " return x * x\n" + >>), %% Register an Erlang function that uses Python py:register_function(square_via_python, fun([X]) -> @@ -48,13 +49,14 @@ def square(x): end), %% Define a Python function that calls back to Erlang - ok = py:exec(<<" -def process_number(x): - '''Calls Erlang which calls Python''' - from erlang import call - squared = call('square_via_python', x) - return squared + 1 -">>), + ok = py:exec(<< + "\n" + "def process_number(x):\n" + " '''Calls Erlang which calls Python'''\n" + " from erlang import call\n" + " squared = call('square_via_python', x)\n" + " return squared + 1\n" + >>), %% Test the full round-trip {ok, Result1} = py:call('__main__', process_number, [5]), @@ -77,7 +79,8 @@ nested_example() -> io:format(" [Erlang] recurse(~p, ~p)~n", [Level, Max]), case Level >= Max of true -> - Level; %% Base case + %% Base case + Level; false -> %% Call back into Python to continue {ok, Result} = py:call('__main__', python_recurse, [Level + 1, Max]), @@ -86,19 +89,20 @@ nested_example() -> end), %% Define Python functions for recursion - ok = py:exec(<<" -def start_recursion(max_level): - '''Entry point - starts the recursive chain''' - from erlang import call - print(f' [Python] start_recursion({max_level})') - return call('recurse', 1, max_level) - -def python_recurse(level, max_level): - '''Called from Erlang during recursion''' - from erlang import call - print(f' [Python] python_recurse({level}, {max_level})') - return call('recurse', level, max_level) -">>), + ok = py:exec(<< + "\n" + "def start_recursion(max_level):\n" + " '''Entry point - starts the recursive chain'''\n" + " from erlang import call\n" + " print(f' [Python] start_recursion({max_level})')\n" + " return call('recurse', 1, max_level)\n" + "\n" + "def python_recurse(level, max_level):\n" + " '''Called from Erlang during recursion'''\n" + " from erlang import call\n" + " print(f' [Python] python_recurse({level}, {max_level})')\n" + " return call('recurse', level, max_level)\n" + >>), %% Test with 4 levels of nesting io:format("Testing 4 levels of nesting:~n"), @@ -123,25 +127,26 @@ pipeline_example() -> end), %% Define Python pipeline - ok = py:exec(<<" -def transform_pipeline(text): - '''Transform text through Python and Erlang functions''' - from erlang import call - - # Step 1: Python processing - step1 = text.strip() - - # Step 2: Erlang uppercase - step2 = call('erlang_uppercase', step1) - - # Step 3: Python add prefix - step3 = 'Result: ' + step2 - - # Step 4: Erlang wrap in brackets - step4 = call('erlang_wrap', step3) - - return step4 -">>), + ok = py:exec(<< + "\n" + "def transform_pipeline(text):\n" + " '''Transform text through Python and Erlang functions'''\n" + " from erlang import call\n" + "\n" + " # Step 1: Python processing\n" + " step1 = text.strip()\n" + "\n" + " # Step 2: Erlang uppercase\n" + " step2 = call('erlang_uppercase', step1)\n" + "\n" + " # Step 3: Python add prefix\n" + " step3 = 'Result: ' + step2\n" + "\n" + " # Step 4: Erlang wrap in brackets\n" + " step4 = call('erlang_wrap', step3)\n" + "\n" + " return step4\n" + >>), %% Test the pipeline {ok, Result} = py:call('__main__', transform_pipeline, [<<" hello world ">>]), diff --git a/examples/reentrant_demo.erl b/examples/reentrant_demo.erl index 59d9fa7..2a46e7f 100644 --- a/examples/reentrant_demo.erl +++ b/examples/reentrant_demo.erl @@ -26,11 +26,12 @@ start() -> {ok, _} = application:ensure_all_started(erlang_python), %% Load our Python demo module - {ok, _} = py:exec(<<" -import sys -sys.path.insert(0, 'examples') -import reentrant_demo -">>), + {ok, _} = py:exec(<< + "\n" + "import sys\n" + "sys.path.insert(0, 'examples')\n" + "import reentrant_demo\n" + >>), %% Register Erlang functions that Python can call register_callbacks(), @@ -111,14 +112,20 @@ register_callbacks() -> %% Processor handler py:register_function(processor_handle, fun([Name, Value]) -> %% Call back to the processor's compute method - {ok, Result} = py:eval(iolist_to_binary(io_lib:format( - "reentrant_demo.DataProcessor('~s').compute(~p, 100)", [Name, Value]))), + {ok, Result} = py:eval( + iolist_to_binary( + io_lib:format( + "reentrant_demo.DataProcessor('~s').compute(~p, 100)", [Name, Value] + ) + ) + ), Result end), %% Factor lookup for processor py:register_function(get_factor, fun([_Name]) -> - 2 % Simple factor + % Simple factor + 2 end), ok. @@ -137,7 +144,12 @@ demo_basic() -> io:format("Flow: Python -> Erlang -> Python -> Erlang (result)~n"), io:format("Result: ~p (expected: 21)~n", [Result]), - io:format("Test ~s~n", [if Result == 21 -> "PASSED"; true -> "FAILED" end]), + io:format("Test ~s~n", [ + if + Result == 21 -> "PASSED"; + true -> "FAILED" + end + ]), Result. %% @doc Demonstrate Fibonacci with reentrant memoization. @@ -155,7 +167,12 @@ demo_fibonacci() -> {ok, Fib15} = py:call(reentrant_demo, fibonacci, [15]), io:format("fibonacci(15) = ~p (expected: 610)~n", [Fib15]), - io:format("Test ~s~n", [if Fib10 == 55, Fib15 == 610 -> "PASSED"; true -> "FAILED" end]), + io:format("Test ~s~n", [ + if + Fib10 == 55, Fib15 == 610 -> "PASSED"; + true -> "FAILED" + end + ]), {Fib10, Fib15}. %% @doc Demonstrate deeply nested callbacks. @@ -171,7 +188,12 @@ demo_nested() -> {ok, Result10} = py:call(reentrant_demo, nested_compute, [0, 10]), io:format("nested_compute(0, 10) = ~p (expected: 10)~n", [Result10]), - io:format("Test ~s~n", [if Result5 == 5, Result10 == 10 -> "PASSED"; true -> "FAILED" end]), + io:format("Test ~s~n", [ + if + Result5 == 5, Result10 == 10 -> "PASSED"; + true -> "FAILED" + end + ]), {Result5, Result10}. %% @doc Demonstrate OOP-style reentrant callbacks. @@ -187,7 +209,12 @@ demo_processor() -> io:format("Expected: processor='test', result=(42+100)*2=284~n"), #{<<"result">> := ComputeResult} = Result, - io:format("Test ~s~n", [if ComputeResult == 284 -> "PASSED"; true -> "FAILED" end]), + io:format("Test ~s~n", [ + if + ComputeResult == 284 -> "PASSED"; + true -> "FAILED" + end + ]), Result. %% @doc Run all demos. diff --git a/examples/run_benchmark.erl b/examples/run_benchmark.erl index fd86d7d..16439d2 100644 --- a/examples/run_benchmark.erl +++ b/examples/run_benchmark.erl @@ -10,56 +10,56 @@ run() -> io:format("========================================~n~n"), %% Erlang loop callback benchmark - ErlCode = " -import asyncio -import time -from _erlang_impl import ErlangEventLoop - -async def bench(n=50000): - count = [0] - done = asyncio.Event() - loop = asyncio.get_running_loop() - def cb(): - count[0] += 1 - if count[0] < n: loop.call_soon(cb) - else: loop.call_soon(done.set) - start = time.perf_counter() - loop.call_soon(cb) - await done.wait() - return count[0] / (time.perf_counter() - start) - -erl = ErlangEventLoop() -asyncio.set_event_loop(erl) -rate = erl.run_until_complete(bench()) -erl.close() -rate -", + ErlCode = + "\n" + "import asyncio\n" + "import time\n" + "from _erlang_impl import ErlangEventLoop\n" + "\n" + "async def bench(n=50000):\n" + " count = [0]\n" + " done = asyncio.Event()\n" + " loop = asyncio.get_running_loop()\n" + " def cb():\n" + " count[0] += 1\n" + " if count[0] < n: loop.call_soon(cb)\n" + " else: loop.call_soon(done.set)\n" + " start = time.perf_counter()\n" + " loop.call_soon(cb)\n" + " await done.wait()\n" + " return count[0] / (time.perf_counter() - start)\n" + "\n" + "erl = ErlangEventLoop()\n" + "asyncio.set_event_loop(erl)\n" + "rate = erl.run_until_complete(bench())\n" + "erl.close()\n" + "rate\n", {ok, ErlRate} = py:eval(list_to_binary(ErlCode)), %% Standard loop callback benchmark - StdCode = " -import asyncio -import time - -async def bench(n=50000): - count = [0] - done = asyncio.Event() - loop = asyncio.get_running_loop() - def cb(): - count[0] += 1 - if count[0] < n: loop.call_soon(cb) - else: loop.call_soon(done.set) - start = time.perf_counter() - loop.call_soon(cb) - await done.wait() - return count[0] / (time.perf_counter() - start) - -std = asyncio.new_event_loop() -asyncio.set_event_loop(std) -rate = std.run_until_complete(bench()) -std.close() -rate -", + StdCode = + "\n" + "import asyncio\n" + "import time\n" + "\n" + "async def bench(n=50000):\n" + " count = [0]\n" + " done = asyncio.Event()\n" + " loop = asyncio.get_running_loop()\n" + " def cb():\n" + " count[0] += 1\n" + " if count[0] < n: loop.call_soon(cb)\n" + " else: loop.call_soon(done.set)\n" + " start = time.perf_counter()\n" + " loop.call_soon(cb)\n" + " await done.wait()\n" + " return count[0] / (time.perf_counter() - start)\n" + "\n" + "std = asyncio.new_event_loop()\n" + "asyncio.set_event_loop(std)\n" + "rate = std.run_until_complete(bench())\n" + "std.close()\n" + "rate\n", {ok, StdRate} = py:eval(list_to_binary(StdCode)), %% Print callback results @@ -70,106 +70,106 @@ rate io:format(" Diff: ~.1f%~n~n", [CbDiff]), %% TCP echo benchmark - Erlang - ErlTcpCode = " -import asyncio -import time -from _erlang_impl import ErlangEventLoop - -class Server(asyncio.Protocol): - def connection_made(self, t): self.t = t - def data_received(self, d): self.t.write(d) - -class Client(asyncio.Protocol): - def __init__(self, msgs, sz, fut): - self.msgs, self.sz, self.fut = msgs, sz, fut - self.sent = self.recv = 0 - self.buf = b'' - def connection_made(self, t): - self.t = t - self.start = time.perf_counter() - self._send() - def _send(self): - if self.sent < self.msgs: - self.t.write(b'x' * self.sz) - self.sent += 1 - def data_received(self, d): - self.buf += d - while len(self.buf) >= self.sz: - self.buf = self.buf[self.sz:] - self.recv += 1 - if self.recv < self.msgs: self._send() - elif self.recv == self.msgs: - self.fut.set_result(time.perf_counter() - self.start) - self.t.close() - -async def bench_tcp(messages=5000, size=64): - loop = asyncio.get_running_loop() - srv = await loop.create_server(Server, '127.0.0.1', 0, reuse_address=True) - port = srv.sockets[0].getsockname()[1] - fut = loop.create_future() - await loop.create_connection(lambda: Client(messages, size, fut), '127.0.0.1', port) - elapsed = await fut - srv.close() - await srv.wait_closed() - return messages / elapsed - -erl = ErlangEventLoop() -asyncio.set_event_loop(erl) -rate = erl.run_until_complete(bench_tcp()) -erl.close() -rate -", + ErlTcpCode = + "\n" + "import asyncio\n" + "import time\n" + "from _erlang_impl import ErlangEventLoop\n" + "\n" + "class Server(asyncio.Protocol):\n" + " def connection_made(self, t): self.t = t\n" + " def data_received(self, d): self.t.write(d)\n" + "\n" + "class Client(asyncio.Protocol):\n" + " def __init__(self, msgs, sz, fut):\n" + " self.msgs, self.sz, self.fut = msgs, sz, fut\n" + " self.sent = self.recv = 0\n" + " self.buf = b''\n" + " def connection_made(self, t):\n" + " self.t = t\n" + " self.start = time.perf_counter()\n" + " self._send()\n" + " def _send(self):\n" + " if self.sent < self.msgs:\n" + " self.t.write(b'x' * self.sz)\n" + " self.sent += 1\n" + " def data_received(self, d):\n" + " self.buf += d\n" + " while len(self.buf) >= self.sz:\n" + " self.buf = self.buf[self.sz:]\n" + " self.recv += 1\n" + " if self.recv < self.msgs: self._send()\n" + " elif self.recv == self.msgs:\n" + " self.fut.set_result(time.perf_counter() - self.start)\n" + " self.t.close()\n" + "\n" + "async def bench_tcp(messages=5000, size=64):\n" + " loop = asyncio.get_running_loop()\n" + " srv = await loop.create_server(Server, '127.0.0.1', 0, reuse_address=True)\n" + " port = srv.sockets[0].getsockname()[1]\n" + " fut = loop.create_future()\n" + " await loop.create_connection(lambda: Client(messages, size, fut), '127.0.0.1', port)\n" + " elapsed = await fut\n" + " srv.close()\n" + " await srv.wait_closed()\n" + " return messages / elapsed\n" + "\n" + "erl = ErlangEventLoop()\n" + "asyncio.set_event_loop(erl)\n" + "rate = erl.run_until_complete(bench_tcp())\n" + "erl.close()\n" + "rate\n", {ok, ErlTcpRate} = py:eval(list_to_binary(ErlTcpCode)), %% TCP echo benchmark - Standard - StdTcpCode = " -import asyncio -import time - -class Server(asyncio.Protocol): - def connection_made(self, t): self.t = t - def data_received(self, d): self.t.write(d) - -class Client(asyncio.Protocol): - def __init__(self, msgs, sz, fut): - self.msgs, self.sz, self.fut = msgs, sz, fut - self.sent = self.recv = 0 - self.buf = b'' - def connection_made(self, t): - self.t = t - self.start = time.perf_counter() - self._send() - def _send(self): - if self.sent < self.msgs: - self.t.write(b'x' * self.sz) - self.sent += 1 - def data_received(self, d): - self.buf += d - while len(self.buf) >= self.sz: - self.buf = self.buf[self.sz:] - self.recv += 1 - if self.recv < self.msgs: self._send() - elif self.recv == self.msgs: - self.fut.set_result(time.perf_counter() - self.start) - self.t.close() - -async def bench_tcp(messages=5000, size=64): - loop = asyncio.get_running_loop() - srv = await loop.create_server(Server, '127.0.0.1', 0, reuse_address=True) - port = srv.sockets[0].getsockname()[1] - fut = loop.create_future() - await loop.create_connection(lambda: Client(messages, size, fut), '127.0.0.1', port) - elapsed = await fut - srv.close() - await srv.wait_closed() - return messages / elapsed - -std = asyncio.new_event_loop() -asyncio.set_event_loop(std) -rate = std.run_until_complete(bench_tcp()) -std.close() -rate -", + StdTcpCode = + "\n" + "import asyncio\n" + "import time\n" + "\n" + "class Server(asyncio.Protocol):\n" + " def connection_made(self, t): self.t = t\n" + " def data_received(self, d): self.t.write(d)\n" + "\n" + "class Client(asyncio.Protocol):\n" + " def __init__(self, msgs, sz, fut):\n" + " self.msgs, self.sz, self.fut = msgs, sz, fut\n" + " self.sent = self.recv = 0\n" + " self.buf = b''\n" + " def connection_made(self, t):\n" + " self.t = t\n" + " self.start = time.perf_counter()\n" + " self._send()\n" + " def _send(self):\n" + " if self.sent < self.msgs:\n" + " self.t.write(b'x' * self.sz)\n" + " self.sent += 1\n" + " def data_received(self, d):\n" + " self.buf += d\n" + " while len(self.buf) >= self.sz:\n" + " self.buf = self.buf[self.sz:]\n" + " self.recv += 1\n" + " if self.recv < self.msgs: self._send()\n" + " elif self.recv == self.msgs:\n" + " self.fut.set_result(time.perf_counter() - self.start)\n" + " self.t.close()\n" + "\n" + "async def bench_tcp(messages=5000, size=64):\n" + " loop = asyncio.get_running_loop()\n" + " srv = await loop.create_server(Server, '127.0.0.1', 0, reuse_address=True)\n" + " port = srv.sockets[0].getsockname()[1]\n" + " fut = loop.create_future()\n" + " await loop.create_connection(lambda: Client(messages, size, fut), '127.0.0.1', port)\n" + " elapsed = await fut\n" + " srv.close()\n" + " await srv.wait_closed()\n" + " return messages / elapsed\n" + "\n" + "std = asyncio.new_event_loop()\n" + "asyncio.set_event_loop(std)\n" + "rate = std.run_until_complete(bench_tcp())\n" + "std.close()\n" + "rate\n", {ok, StdTcpRate} = py:eval(list_to_binary(StdTcpCode)), %% Print TCP results diff --git a/examples/semantic_search.erl b/examples/semantic_search.erl index 19e1be3..62c5d49 100644 --- a/examples/semantic_search.erl +++ b/examples/semantic_search.erl @@ -27,10 +27,11 @@ main(Args) -> io:format("~n=== Semantic Search Example ===~n~n"), %% Activate venv - VenvPath = case Args of - [Path | _] -> Path; - [] -> "/tmp/ai-venv" - end, + VenvPath = + case Args of + [Path | _] -> Path; + [] -> "/tmp/ai-venv" + end, case activate_venv(VenvPath) of ok -> ok; @@ -48,14 +49,22 @@ main(Args) -> %% Sample documents Documents = [ - {<<"doc1">>, <<"Erlang is a programming language used to build massively scalable soft real-time systems with requirements on high availability.">>}, - {<<"doc2">>, <<"Python is widely used for machine learning, data science, and artificial intelligence applications.">>}, - {<<"doc3">>, <<"The BEAM virtual machine executes Erlang and Elixir code with lightweight processes and message passing.">>}, - {<<"doc4">>, <<"Neural networks are computing systems inspired by biological neural networks that constitute animal brains.">>}, - {<<"doc5">>, <<"Distributed systems are systems whose components are located on different networked computers.">>}, - {<<"doc6">>, <<"Natural language processing enables computers to understand, interpret, and generate human language.">>}, - {<<"doc7">>, <<"Fault tolerance is the property that enables a system to continue operating properly in the event of failure.">>}, - {<<"doc8">>, <<"Deep learning is part of machine learning based on artificial neural networks with representation learning.">>} + {<<"doc1">>, + <<"Erlang is a programming language used to build massively scalable soft real-time systems with requirements on high availability.">>}, + {<<"doc2">>, + <<"Python is widely used for machine learning, data science, and artificial intelligence applications.">>}, + {<<"doc3">>, + <<"The BEAM virtual machine executes Erlang and Elixir code with lightweight processes and message passing.">>}, + {<<"doc4">>, + <<"Neural networks are computing systems inspired by biological neural networks that constitute animal brains.">>}, + {<<"doc5">>, + <<"Distributed systems are systems whose components are located on different networked computers.">>}, + {<<"doc6">>, + <<"Natural language processing enables computers to understand, interpret, and generate human language.">>}, + {<<"doc7">>, + <<"Fault tolerance is the property that enables a system to continue operating properly in the event of failure.">>}, + {<<"doc8">>, + <<"Deep learning is part of machine learning based on artificial neural networks with representation learning.">>} ], %% Build index @@ -71,14 +80,20 @@ main(Args) -> <<"understanding human text">> ], - lists:foreach(fun(Query) -> - io:format("~n--- Query: ~s ---~n", [Query]), - Results = search(Query, Index, 3), - lists:foreach(fun({Score, Id, Text}) -> - ShortText = truncate(Text, 60), - io:format(" [~.3f] ~s: ~s~n", [Score, Id, ShortText]) - end, Results) - end, Queries), + lists:foreach( + fun(Query) -> + io:format("~n--- Query: ~s ---~n", [Query]), + Results = search(Query, Index, 3), + lists:foreach( + fun({Score, Id, Text}) -> + ShortText = truncate(Text, 60), + io:format(" [~.3f] ~s: ~s~n", [Score, Id, ShortText]) + end, + Results + ) + end, + Queries + ), io:format("~n=== Done ===~n~n"), cleanup(). @@ -109,7 +124,10 @@ activate_venv(VenvPath) -> end. add_to_python_path(Dir) -> - {ok, _} = py:eval(<<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, #{path => Dir}), + {ok, _} = py:eval( + <<"(__import__('sys').path.insert(0, path) if path not in __import__('sys').path else None, True)[1]">>, + #{path => Dir} + ), ok. build_index(Documents) -> @@ -119,8 +137,10 @@ build_index(Documents) -> search(Query, Index, TopK) -> {ok, QueryEmb} = py:call(ai_helpers, embed_single, [Query]), - Scored = [{cosine_similarity(QueryEmb, Emb), Id, Text} - || {Id, Text, Emb} <- Index], + Scored = [ + {cosine_similarity(QueryEmb, Emb), Id, Text} + || {Id, Text, Emb} <- Index + ], Sorted = lists:reverse(lists:sort(Scored)), lists:sublist(Sorted, TopK). diff --git a/examples/shared_state_example.erl b/examples/shared_state_example.erl index fd943e6..c840a5a 100755 --- a/examples/shared_state_example.erl +++ b/examples/shared_state_example.erl @@ -32,26 +32,28 @@ main(_) -> timeout => 5000 }), %% Python reads using idiomatic import syntax - ok = py:exec(<<" -from erlang import state_get - -config = state_get('config') -assert config['api_key'] == 'secret123' -assert config['max_retries'] == 3 -">>), + ok = py:exec(<< + "\n" + "from erlang import state_get\n" + "\n" + "config = state_get('config')\n" + "assert config['api_key'] == 'secret123'\n" + "assert config['max_retries'] == 3\n" + >>), io:format(" Python read config successfully~n"), %% Example 2: Set from Python, read from Erlang io:format("~n2. Python -> Erlang:~n"), - ok = py:exec(<<" -from erlang import state_set - -state_set('computation_result', { - 'status': 'complete', - 'values': [1, 2, 3, 4, 5], - 'metadata': {'source': 'python', 'timestamp': 1234567890} -}) -">>), + ok = py:exec(<< + "\n" + "from erlang import state_set\n" + "\n" + "state_set('computation_result', {\n" + " 'status': 'complete',\n" + " 'values': [1, 2, 3, 4, 5],\n" + " 'metadata': {'source': 'python', 'timestamp': 1234567890}\n" + "})\n" + >>), {ok, Result} = py:state_fetch(<<"computation_result">>), io:format(" Result in Erlang: ~p~n", [Result]), @@ -65,38 +67,41 @@ state_set('computation_result', { io:format(" Erlang incr by 10: ~p~n", [Val2]), %% From Python - ok = py:exec(<<" -from erlang import state_incr, state_decr - -val = state_incr('hits', 5) -print(f' Python incr by 5: {val}') - -val = state_decr('hits', 3) -print(f' Python decr by 3: {val}') -">>), + ok = py:exec(<< + "\n" + "from erlang import state_incr, state_decr\n" + "\n" + "val = state_incr('hits', 5)\n" + "print(f' Python incr by 5: {val}')\n" + "\n" + "val = state_decr('hits', 3)\n" + "print(f' Python decr by 3: {val}')\n" + >>), {ok, FinalCount} = py:state_fetch(<<"hits">>), io:format(" Final counter value: ~p~n", [FinalCount]), %% Example 4: List all keys from Python io:format("~n4. List keys from Python:~n"), - ok = py:exec(<<" -from erlang import state_keys - -keys = state_keys() -assert 'hits' in keys -assert 'config' in keys -">>), + ok = py:exec(<< + "\n" + "from erlang import state_keys\n" + "\n" + "keys = state_keys()\n" + "assert 'hits' in keys\n" + "assert 'config' in keys\n" + >>), Keys = py:state_keys(), io:format(" Keys: ~p~n", [Keys]), %% Example 5: Delete from Python io:format("~n5. Delete from Python:~n"), - ok = py:exec(<<" -from erlang import state_delete - -state_delete('computation_result') -">>), + ok = py:exec(<< + "\n" + "from erlang import state_delete\n" + "\n" + "state_delete('computation_result')\n" + >>), case py:state_fetch(<<"computation_result">>) of {error, not_found} -> io:format(" Key deleted successfully~n"); {ok, _} -> io:format(" ERROR: Key still exists~n") diff --git a/examples/streaming_example.erl b/examples/streaming_example.erl index dd0ecf1..9465cbc 100644 --- a/examples/streaming_example.erl +++ b/examples/streaming_example.erl @@ -22,13 +22,17 @@ main(_) -> %% Stream tokens using inline generator io:format("Streaming tokens: "), - {ok, Tokens} = py:stream_eval(<<"(word + ' ' for word in 'Hello world from Python generator'.split())">>), + {ok, Tokens} = py:stream_eval( + <<"(word + ' ' for word in 'Hello world from Python generator'.split())">> + ), lists:foreach(fun(T) -> io:format("~s", [T]) end, Tokens), io:format("~n~n"), %% Fibonacci sequence using inline generator with walrus operator io:format("Fibonacci(10): "), - {ok, Fibs} = py:stream_eval(<<"(lambda: ((fib := [0, 1]), [fib.append(fib[-1] + fib[-2]) for _ in range(8)], iter(fib))[-1])()">>), + {ok, Fibs} = py:stream_eval( + <<"(lambda: ((fib := [0, 1]), [fib.append(fib[-1] + fib[-2]) for _ in range(8)], iter(fib))[-1])()">> + ), io:format("~p~n~n", [Fibs]), %% Custom range using builtin iter diff --git a/rebar.config b/rebar.config index 898a66d..a96cb3a 100644 --- a/rebar.config +++ b/rebar.config @@ -39,11 +39,37 @@ {sys_config, ["test/test.config"]} ]}. -{project_plugins, [rebar3_ex_doc]}. +{project_plugins, [ + rebar3_ex_doc, + %% Pinned: rebar3_lint changed how it resolves elvis.config within the + %% 5.0 range, and plugins are not locked. + {rebar3_lint, "5.0.4"}, + {erlfmt, "~> 1.7"} +]}. + +{erlfmt, [ + write, + {files, [ + "{src,test,include,examples,scripts}/**/*.{hrl,erl,app.src,escript}", + "rebar.config" + ]} +]}. {hex, [ {doc, ex_doc}, - {files, ["src", "include", "priv", "c_src", "do_cmake.sh", "do_build.sh", "rebar.config", "rebar.lock", "README.md", "LICENSE", "CHANGELOG.md"]} + {files, [ + "src", + "include", + "priv", + "c_src", + "do_cmake.sh", + "do_build.sh", + "rebar.config", + "rebar.lock", + "README.md", + "LICENSE", + "CHANGELOG.md" + ]} ]}. {ex_doc, [ @@ -82,7 +108,7 @@ <<"docs/glossary.md">>, <<"docs/protocols.md">>, <<"docs/state-machines.md">>, - <<"docs/contributing.md">>, + <<"CONTRIBUTING.md">>, <<"docs/decisions/overview.md">>, <<"docs/decisions/0001-one-thread-per-context.md">>, <<"docs/decisions/0002-callback-delivery-paths.md">>, @@ -134,7 +160,7 @@ <<"docs/glossary.md">>, <<"docs/protocols.md">>, <<"docs/state-machines.md">>, - <<"docs/contributing.md">>, + <<"CONTRIBUTING.md">>, <<"docs/preload.md">>, <<"docs/owngil_internals.md">>, <<"docs/event_loop_architecture.md">> diff --git a/scripts/lint_doc_snippets.escript b/scripts/lint_doc_snippets.escript index a8f528b..59fe3c2 100755 --- a/scripts/lint_doc_snippets.escript +++ b/scripts/lint_doc_snippets.escript @@ -2,8 +2,8 @@ %% -*- erlang -*- %%! -smp enable %% -%% lint_doc_snippets — verifies fenced code blocks in README.md and -%% docs/*.md. +%% lint_doc_snippets — verifies fenced code blocks in README.md, +%% CONTRIBUTING.md and docs/*.md. %% %% * ```erlang blocks: every `py:Fn(Args)` call must reference a %% function exported from py.erl at the correct arity. @@ -20,47 +20,64 @@ main(Args) -> Root = filename:dirname(filename:dirname(escript:script_name())), - EbinDir = filename:join([Root, "_build", "default", "lib", - "erlang_python", "ebin"]), + EbinDir = filename:join([ + Root, + "_build", + "default", + "lib", + "erlang_python", + "ebin" + ]), case filelib:is_dir(EbinDir) of true -> true = code:add_path(EbinDir); false -> - io:format(standard_error, - "ebin not found at ~s; run `rebar3 compile` first~n", - [EbinDir]), + io:format( + standard_error, + "ebin not found at ~s; run `rebar3 compile` first~n", + [EbinDir] + ), halt(2) end, PyExports = load_py_exports(), - Files = case Args of - [] -> default_files(Root); - _ -> Args - end, + Files = + case Args of + [] -> default_files(Root); + _ -> Args + end, Failures = lists:foldl( fun(File, Acc) -> Acc + lint_file(File, PyExports) end, - 0, Files), + 0, + Files + ), case Failures of 0 -> io:format("lint-docs: clean (~p file(s))~n", [length(Files)]), halt(0); N -> - io:format(standard_error, - "lint-docs: ~p failure(s)~n", [N]), + io:format( + standard_error, + "lint-docs: ~p failure(s)~n", + [N] + ), halt(N) end. default_files(Root) -> - Readme = filename:join(Root, "README.md"), - Docs = filelib:wildcard(filename:join([Root, "docs", "*.md"])), - [Readme | Docs]. + Top = [filename:join(Root, F) || F <- ["README.md", "CONTRIBUTING.md"]], + Docs = filelib:wildcard(filename:join([Root, "docs", "*.md"])), + Top ++ Docs. load_py_exports() -> case code:ensure_loaded(py) of {module, py} -> sets:from_list(py:module_info(exports)); Other -> - io:format(standard_error, - "could not load py.beam: ~p~n", [Other]), + io:format( + standard_error, + "could not load py.beam: ~p~n", + [Other] + ), halt(2) end. @@ -76,10 +93,15 @@ lint_file(File, PyExports) -> Blocks = collect_blocks(Numbered, <<>>, []), lists:foldl( fun(Block, Acc) -> Acc + lint_block(File, Block, PyExports) end, - 0, Blocks); + 0, + Blocks + ); {error, Reason} -> - io:format(standard_error, "~s: read failed (~p)~n", - [File, Reason]), + io:format( + standard_error, + "~s: read failed (~p)~n", + [File, Reason] + ), 1 end. @@ -95,10 +117,11 @@ collect_blocks([{_, Line} | Rest], Prev, Acc) -> Skip = is_skip_marker(Prev), {Body, RestAfter, StartLine} = consume_block(Rest, [], Skip, Lang), - NewAcc = case Skip of - true -> Acc; - false -> [{Lang, StartLine, Body} | Acc] - end, + NewAcc = + case Skip of + true -> Acc; + false -> [{Lang, StartLine, Body} | Acc] + end, collect_blocks(RestAfter, Line, NewAcc); _ -> collect_blocks(Rest, Line, Acc) @@ -113,9 +136,9 @@ classify(Line) -> case Trim of <<"```erlang">> -> {open, erlang}; <<"```python">> -> {open, python}; - <<"```py">> -> {open, python}; - <<"```">> -> close; - _ -> other + <<"```py">> -> {open, python}; + <<"```">> -> close; + _ -> other end. %% Consume lines until the closing ``` fence. Returns {BodyBin, RestLines, FirstLine}. @@ -126,11 +149,14 @@ consume_block([{LineNo, Line} | Rest], BodyAcc, _Skip, Lang) -> close -> {iolist_to_binary(lists:reverse(BodyAcc)), Rest, LineNo}; _ -> - consume_block(Rest, [<> | BodyAcc], - _Skip, Lang) + consume_block( + Rest, + [<> | BodyAcc], + _Skip, + Lang + ) end. - %%% ---------------------------------------------------------------- %%% per-block lint %%% ---------------------------------------------------------------- @@ -158,18 +184,32 @@ lint_erlang_block(File, Body, PyExports) -> %% Walk the token list looking for the pattern: %% atom(py) ':' atom(Fn) '(' ... ')' %% The counter consumes tokens up to and including the matching `)`. -check_py_calls(_File, [], _Exports) -> 0; -check_py_calls(File, [{atom, _, py}, {':', _}, {atom, Loc, Fn}, - {'(', _} | Rest], Exports) -> +check_py_calls(_File, [], _Exports) -> + 0; +check_py_calls( + File, + [ + {atom, _, py}, + {':', _}, + {atom, Loc, Fn}, + {'(', _} + | Rest + ], + Exports +) -> {Arity, After} = count_top_level_args(Rest, 1, 0, 0), - Bad = case sets:is_element({Fn, Arity}, Exports) of - true -> 0; - false -> - io:format(standard_error, - "~s:~p: undefined or wrong-arity call py:~s/~p~n", - [File, line_of(Loc), atom_to_list(Fn), Arity]), - 1 - end, + Bad = + case sets:is_element({Fn, Arity}, Exports) of + true -> + 0; + false -> + io:format( + standard_error, + "~s:~p: undefined or wrong-arity call py:~s/~p~n", + [File, line_of(Loc), atom_to_list(Fn), Arity] + ), + 1 + end, Bad + check_py_calls(File, After, Exports); check_py_calls(File, [_ | Rest], Exports) -> check_py_calls(File, Rest, Exports). @@ -191,19 +231,33 @@ count_top_level_args([{')', _} | Rest], 1, _Args, ArgsSoFar) -> {ArgsSoFar + 1, Rest}; count_top_level_args([], _Depth, ArgsSeen, ArgsSoFar) -> %% Truncated snippet; best-effort count. - {ArgsSoFar + (case ArgsSeen of 0 -> 0; _ -> 1 end), []}; -count_top_level_args([{Tok, _} | Rest], Depth, _Args, ArgsSoFar) - when Tok =:= '('; Tok =:= '['; Tok =:= '{'; Tok =:= '<<' -> + { + ArgsSoFar + + (case ArgsSeen of + 0 -> 0; + _ -> 1 + end), + [] + }; +count_top_level_args([{Tok, _} | Rest], Depth, _Args, ArgsSoFar) when + Tok =:= '('; Tok =:= '['; Tok =:= '{'; Tok =:= '<<' +-> count_top_level_args(Rest, Depth + 1, 1, ArgsSoFar); -count_top_level_args([{Tok, _} | Rest], Depth, _Args, ArgsSoFar) - when Tok =:= ')'; Tok =:= ']'; Tok =:= '}'; Tok =:= '>>' -> +count_top_level_args([{Tok, _} | Rest], Depth, _Args, ArgsSoFar) when + Tok =:= ')'; Tok =:= ']'; Tok =:= '}'; Tok =:= '>>' +-> count_top_level_args(Rest, Depth - 1, 1, ArgsSoFar); %% `fun`, `case`, `if`, `try`, `receive`, `begin` open an `end`-terminated %% block. Treat them as depth brackets so commas inside fun bodies %% (which are part of one outer arg) are not counted. -count_top_level_args([{Kw, _} | Rest], Depth, _Args, ArgsSoFar) - when Kw =:= 'fun'; Kw =:= 'case'; Kw =:= 'if'; Kw =:= 'try'; - Kw =:= 'receive'; Kw =:= 'begin' -> +count_top_level_args([{Kw, _} | Rest], Depth, _Args, ArgsSoFar) when + Kw =:= 'fun'; + Kw =:= 'case'; + Kw =:= 'if'; + Kw =:= 'try'; + Kw =:= 'receive'; + Kw =:= 'begin' +-> count_top_level_args(Rest, Depth + 1, 1, ArgsSoFar); count_top_level_args([{'end', _} | Rest], Depth, _Args, ArgsSoFar) -> count_top_level_args(Rest, Depth - 1, 1, ArgsSoFar); @@ -218,13 +272,17 @@ count_top_level_args([_Tok | Rest], Depth, _Args, ArgsSoFar) -> %% if-block, or a single line of a larger function). SyntaxError still %% fails the lint. lint_python_block(File, Body) -> - TmpDir = case os:getenv("TMPDIR") of - false -> "/tmp"; - Dir -> Dir - end, - Tmp = filename:join(TmpDir, "lint_snip_" - ++ integer_to_list(erlang:unique_integer([positive])) - ++ ".py"), + TmpDir = + case os:getenv("TMPDIR") of + false -> "/tmp"; + Dir -> Dir + end, + Tmp = filename:join( + TmpDir, + "lint_snip_" ++ + integer_to_list(erlang:unique_integer([positive])) ++ + ".py" + ), ok = file:write_file(Tmp, Body), Script = "import ast,sys\n" @@ -236,18 +294,26 @@ lint_python_block(File, Body) -> "except SyntaxError as e:\n" " print(f'SyntaxError: {e}')\n" " sys.exit(1)\n", - Cmd = "python3 -c " ++ shell_quote(Script) ++ " " ++ Tmp - ++ " 2>&1; echo __exit_$?__", + Cmd = + "python3 -c " ++ shell_quote(Script) ++ " " ++ Tmp ++ + " 2>&1; echo __exit_$?__", Out = os:cmd(Cmd), file:delete(Tmp), case re:run(Out, <<"__exit_0__\\s*$">>, [{capture, none}]) of - match -> 0; + match -> + 0; nomatch -> - Trimmed = re:replace(Out, <<"__exit_\\d+__\\s*$">>, <<>>, - [{return, list}]), - io:format(standard_error, - "~s: python snippet failed:~n~s~n", - [File, Trimmed]), + Trimmed = re:replace( + Out, + <<"__exit_\\d+__\\s*$">>, + <<>>, + [{return, list}] + ), + io:format( + standard_error, + "~s: python snippet failed:~n~s~n", + [File, Trimmed] + ), 1 end. diff --git a/src/erlang_python.app.src b/src/erlang_python.app.src index ad54ae9..dbdc172 100644 --- a/src/erlang_python.app.src +++ b/src/erlang_python.app.src @@ -11,16 +11,18 @@ {modules, []}, {licenses, ["Apache-2.0"]}, {links, [{"GitHub", "https://github.com/benoitc/erlang-python"}]}, - {files, ["rebar.config", - "do_cmake.sh", - "do_build.sh", - "README.md", - "LICENSE", - "CHANGELOG.md", - "src", - "c_src", - "priv", - "docs", - "examples", - "test"]} + {files, [ + "rebar.config", + "do_cmake.sh", + "do_build.sh", + "README.md", + "LICENSE", + "CHANGELOG.md", + "src", + "c_src", + "priv", + "docs", + "examples", + "test" + ]} ]}. diff --git a/src/erlang_python_app.erl b/src/erlang_python_app.erl index 2485d70..404833e 100644 --- a/src/erlang_python_app.erl +++ b/src/erlang_python_app.erl @@ -25,6 +25,14 @@ start(_StartType, _StartArgs) -> stop(_State) -> %% Stop pools before application shutdown to ensure proper cleanup %% of subinterpreters before NIF resources are garbage collected - try py_context_router:stop_pool(io) catch _:_ -> ok end, - try py_context_router:stop_pool(default) catch _:_ -> ok end, + try + py_context_router:stop_pool(io) + catch + _:_ -> ok + end, + try + py_context_router:stop_pool(default) + catch + _:_ -> ok + end, ok. diff --git a/src/erlang_python_sup.erl b/src/erlang_python_sup.erl index dc8f192..180f423 100644 --- a/src/erlang_python_sup.erl +++ b/src/erlang_python_sup.erl @@ -32,8 +32,11 @@ start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> - NumContexts = application:get_env(erlang_python, num_contexts, - erlang:system_info(schedulers)), + NumContexts = application:get_env( + erlang_python, + num_contexts, + erlang:system_info(schedulers) + ), ContextMode = application:get_env(erlang_python, context_mode, worker), %% Per-context memory caps hook the obmalloc arena allocator, which has to @@ -188,10 +191,20 @@ init([]) -> modules => [py_event_loop_pool] }, - Children = [CallbackSpec, ShmSpec, ThreadHandlerSpec, LoggerSpec, TracerSpec, - ContextSupSpec, SessionSupSpec, ContextRouterInitSpec, - WorkerRegistrySpec, WorkerSupSpec, EventLoopSpec, - EventLoopPoolSpec], + Children = [ + CallbackSpec, + ShmSpec, + ThreadHandlerSpec, + LoggerSpec, + TracerSpec, + ContextSupSpec, + SessionSupSpec, + ContextRouterInitSpec, + WorkerRegistrySpec, + WorkerSupSpec, + EventLoopSpec, + EventLoopPoolSpec + ], {ok, { #{strategy => one_for_all, intensity => 5, period => 10}, diff --git a/src/py.erl b/src/py.erl index c564138..f9046b5 100644 --- a/src/py.erl +++ b/src/py.erl @@ -169,12 +169,13 @@ -spec get_local_env(pid()) -> reference(). get_local_env(Ctx) when is_pid(Ctx) -> {ok, InterpId} = py_context:get_interp_id(Ctx), - Envs = case get(?LOCAL_ENV_KEY) of - undefined -> #{}; - M when is_map(M) -> M; - %% Handle legacy single-ref format (shouldn't happen but be safe) - _OldRef -> #{} - end, + Envs = + case get(?LOCAL_ENV_KEY) of + undefined -> #{}; + M when is_map(M) -> M; + %% Handle legacy single-ref format (shouldn't happen but be safe) + _OldRef -> #{} + end, case maps:get(InterpId, Envs, undefined) of undefined -> {ok, Ref} = py_context:create_local_env(Ctx), @@ -191,10 +192,11 @@ get_local_env(Ctx) when is_pid(Ctx) -> %% namespace instead of starting from an empty one. -spec put_local_env(non_neg_integer(), reference()) -> ok. put_local_env(InterpId, EnvRef) -> - Envs = case get(?LOCAL_ENV_KEY) of - M when is_map(M) -> M; - _ -> #{} - end, + Envs = + case get(?LOCAL_ENV_KEY) of + M when is_map(M) -> M; + _ -> #{} + end, put(?LOCAL_ENV_KEY, Envs#{InterpId => EnvRef}), ok. @@ -223,9 +225,10 @@ call(Module, Func, Args) -> %% @param ModuleOrFunc Python module or function name %% @param FuncOrArgs Function name or arguments list %% @param ArgsOrKwargs Arguments list or keyword arguments --spec call(pid(), py_module(), py_func(), py_args()) -> py_result() - ; (py_context_router:pool_name(), py_module(), py_func(), py_args()) -> py_result() - ; (py_module(), py_func(), py_args(), py_kwargs()) -> py_result(). +-spec call + (pid(), py_module(), py_func(), py_args()) -> py_result(); + (py_context_router:pool_name(), py_module(), py_func(), py_args()) -> py_result(); + (py_module(), py_func(), py_args(), py_kwargs()) -> py_result(). call(Ctx, Module, Func, Args) when is_pid(Ctx) -> EnvRef = get_local_env(Ctx), py_context:call(Ctx, Module, Func, Args, #{}, infinity, EnvRef); @@ -244,9 +247,10 @@ call(Module, Func, Args, Kwargs) -> %% %% Timeout is in milliseconds. Use `infinity' for no timeout. %% Rate limited via ETS-based semaphore to prevent overload. --spec call(pid(), py_module(), py_func(), py_args(), map()) -> py_result() - ; (py_context_router:pool_name(), py_module(), py_func(), py_args(), py_kwargs()) -> py_result() - ; (py_module(), py_func(), py_args(), py_kwargs(), timeout()) -> py_result(). +-spec call + (pid(), py_module(), py_func(), py_args(), map()) -> py_result(); + (py_context_router:pool_name(), py_module(), py_func(), py_args(), py_kwargs()) -> py_result(); + (py_module(), py_func(), py_args(), py_kwargs(), timeout()) -> py_result(). call(Ctx, Module, Func, Args, Opts) when is_pid(Ctx), is_map(Opts) -> Kwargs = maps:get(kwargs, Opts, #{}), Timeout = maps:get(timeout, Opts, infinity), @@ -289,8 +293,9 @@ eval(Code) -> %% %% When the first argument is a pid (context), evaluates using the new %% process-per-context architecture with process-local environment. --spec eval(pid(), string() | binary()) -> py_result() - ; (string() | binary(), map()) -> py_result(). +-spec eval + (pid(), string() | binary()) -> py_result(); + (string() | binary(), map()) -> py_result(). eval(Ctx, Code) when is_pid(Ctx) -> EnvRef = get_local_env(Ctx), py_context:eval(Ctx, Code, #{}, infinity, EnvRef); @@ -303,8 +308,9 @@ eval(Code, Locals) -> %% process-per-context architecture with process-local environment. %% %% Timeout is in milliseconds. Use `infinity' for no timeout. --spec eval(pid(), string() | binary(), map()) -> py_result() - ; (string() | binary(), map(), timeout()) -> py_result(). +-spec eval + (pid(), string() | binary(), map()) -> py_result(); + (string() | binary(), map(), timeout()) -> py_result(). eval(Ctx, Code, Locals) when is_pid(Ctx), is_map(Locals) -> EnvRef = get_local_env(Ctx), py_context:eval(Ctx, Code, Locals, infinity, EnvRef); @@ -347,8 +353,9 @@ cast(Module, Func, Args) -> cast(Module, Func, Args, #{}). %% @doc Fire-and-forget Python function call with context or kwargs. --spec cast(pid(), py_module(), py_func(), py_args()) -> ok; - (py_module(), py_func(), py_args(), py_kwargs()) -> ok. +-spec cast + (pid(), py_module(), py_func(), py_args()) -> ok; + (py_module(), py_func(), py_args(), py_kwargs()) -> ok. cast(Ctx, Module, Func, Args) when is_pid(Ctx) -> cast(Ctx, Module, Func, Args, #{}); cast(Module, Func, Args, Kwargs) -> @@ -372,8 +379,9 @@ spawn_call(Module, Func, Args) -> spawn_call(Module, Func, Args, #{}). %% @doc Spawn a Python function call with context or kwargs. --spec spawn_call(pid(), py_module(), py_func(), py_args()) -> py_ref(); - (py_module(), py_func(), py_args(), py_kwargs()) -> py_ref(). +-spec spawn_call + (pid(), py_module(), py_func(), py_args()) -> py_ref(); + (py_module(), py_func(), py_args(), py_kwargs()) -> py_ref(). spawn_call(Ctx, Module, Func, Args) when is_pid(Ctx) -> spawn_call(Ctx, Module, Func, Args, #{}); spawn_call(Module, Func, Args, Kwargs) -> @@ -640,8 +648,10 @@ async_gather(Calls) -> async_gather(Calls, Timeout) when is_list(Calls) -> Refs = [async_call(M, F, A) || {M, F, A} <- Calls], Results = [async_await(R, Timeout) || R <- Refs], - Errors = [{Idx, Reason} - || {Idx, {error, Reason}} <- lists:zip(lists:seq(1, length(Results)), Results)], + Errors = [ + {Idx, Reason} + || {Idx, {error, Reason}} <- lists:zip(lists:seq(1, length(Results)), Results) + ], case Errors of [] -> Values = [V || {ok, V} <- Results], @@ -686,26 +696,40 @@ parallel(Calls) when is_list(Calls) -> %% Spawn processes to execute calls in parallel CallsWithIdx = lists:zip(lists:seq(1, length(Calls)), Calls), - _ = [spawn(fun() -> - %% Distribute calls round-robin across contexts - CtxIdx = ((Idx - 1) rem NumContexts) + 1, - Ctx = py_context_router:get_context(CtxIdx), - Result = py_context:call(Ctx, M, F, A, #{}), - Parent ! {Ref, Idx, Result} - end) || {Idx, {M, F, A}} <- CallsWithIdx], + _ = [ + spawn(fun() -> + %% Distribute calls round-robin across contexts + CtxIdx = ((Idx - 1) rem NumContexts) + 1, + Ctx = py_context_router:get_context(CtxIdx), + Result = py_context:call(Ctx, M, F, A, #{}), + Parent ! {Ref, Idx, Result} + end) + || {Idx, {M, F, A}} <- CallsWithIdx + ], %% Collect results in order - Results = [receive - {Ref, Idx, Result} -> {Idx, Result} - after ?DEFAULT_TIMEOUT -> - {Idx, {error, timeout}} - end || {Idx, _} <- CallsWithIdx], + Results = [ + receive + {Ref, Idx, Result} -> {Idx, Result} + after ?DEFAULT_TIMEOUT -> + {Idx, {error, timeout}} + end + || {Idx, _} <- CallsWithIdx + ], %% Sort by index and extract results SortedResults = [R || {_, R} <- lists:keysort(1, Results)], %% Check if all succeeded - case lists:all(fun({ok, _}) -> true; (_) -> false end, SortedResults) of + case + lists:all( + fun + ({ok, _}) -> true; + (_) -> false + end, + SortedResults + ) + of true -> {ok, [V || {ok, V} <- SortedResults]}; false -> @@ -906,20 +930,26 @@ reload(Module) -> %% 1. Checks if module is loaded in sys.modules %% 2. If yes, reloads it with importlib.reload() %% 3. Returns the module name or None if not loaded - Code = <<"__import__('importlib').reload(__import__('sys').modules['", - ModuleBin/binary, - "']) if '", ModuleBin/binary, "' in __import__('sys').modules else None">>, + Code = + <<"__import__('importlib').reload(__import__('sys').modules['", ModuleBin/binary, + "']) if '", ModuleBin/binary, "' in __import__('sys').modules else None">>, %% Broadcast to all contexts NumContexts = py_context_router:num_contexts(), - Results = [begin - Ctx = py_context_router:get_context(N), - py_context:eval(Ctx, Code, #{}) - end || N <- lists:seq(1, NumContexts)], + Results = [ + begin + Ctx = py_context_router:get_context(N), + py_context:eval(Ctx, Code, #{}) + end + || N <- lists:seq(1, NumContexts) + ], %% Check if any failed - Errors = lists:filtermap(fun - ({ok, _}) -> false; - ({error, Reason}) -> {true, Reason} - end, Results), + Errors = lists:filtermap( + fun + ({ok, _}) -> false; + ({error, Reason}) -> {true, Reason} + end, + Results + ), case Errors of [] -> ok; _ -> {error, [{context, E} || E <- Errors]} @@ -947,36 +977,42 @@ configure_logging() -> -spec configure_logging(map()) -> ok | {error, term()}. configure_logging(Opts) -> Level = maps:get(level, Opts, debug), - LevelInt = case Level of - debug -> 10; - info -> 20; - warning -> 30; - error -> 40; - critical -> 50; - _ -> 10 - end, + LevelInt = + case Level of + debug -> 10; + info -> 20; + warning -> 30; + error -> 40; + critical -> 50; + _ -> 10 + end, Format = maps:get(format, Opts, undefined), %% Use __import__ for single-expression evaluation - Code = case Format of - undefined -> - iolist_to_binary([ - "__import__('erlang').setup_logging(", - integer_to_binary(LevelInt), - ")" - ]); - F when is_binary(F) -> - iolist_to_binary([ - "__import__('erlang').setup_logging(", - integer_to_binary(LevelInt), - ", '", py_util:escape_py_literal(F), "')" - ]); - F when is_list(F) -> - iolist_to_binary([ - "__import__('erlang').setup_logging(", - integer_to_binary(LevelInt), - ", '", py_util:escape_py_literal(iolist_to_binary(F)), "')" - ]) - end, + Code = + case Format of + undefined -> + iolist_to_binary([ + "__import__('erlang').setup_logging(", + integer_to_binary(LevelInt), + ")" + ]); + F when is_binary(F) -> + iolist_to_binary([ + "__import__('erlang').setup_logging(", + integer_to_binary(LevelInt), + ", '", + py_util:escape_py_literal(F), + "')" + ]); + F when is_list(F) -> + iolist_to_binary([ + "__import__('erlang').setup_logging(", + integer_to_binary(LevelInt), + ", '", + py_util:escape_py_literal(iolist_to_binary(F)), + "')" + ]) + end, case eval(Code) of {ok, _} -> ok; Error -> Error diff --git a/src/py_callback.erl b/src/py_callback.erl index ce25fe2..3664342 100644 --- a/src/py_callback.erl +++ b/src/py_callback.erl @@ -90,7 +90,8 @@ unregister(Name) -> ok. %% @doc Lookup a registered function. --spec lookup(Name :: binary()) -> {ok, fun((list()) -> term()) | {atom(), atom()}} | {error, not_found}. +-spec lookup(Name :: binary()) -> + {ok, fun((list()) -> term()) | {atom(), atom()}} | {error, not_found}. lookup(Name) -> NameBin = to_binary(Name), case ets:lookup(?TABLE, NameBin) of diff --git a/src/py_child.erl b/src/py_child.erl index 7b8eba4..59f440d 100644 --- a/src/py_child.erl +++ b/src/py_child.erl @@ -25,29 +25,31 @@ %%% Never: keeps state between calls. -module(py_child). --export([python_executable/1, - priv_dir/0, - sock_dir/0, - new_sock_path/1, - delete_file/1, - make_scratch_dir/1, - remove_tree/1, - listen/1, - accept/3, - tune_socket/1, - port_env/1, - check_env_opts/1, - rlimit_args/1, - cgroup_args/1, - frame/3, - send_frame/4, - parse_frame/1, - exit_reason/1, - code_reason/1, - os_pid_alive/1, - kill_os_pid/1, - to_bin/1, - to_list/1]). +-export([ + python_executable/1, + priv_dir/0, + sock_dir/0, + new_sock_path/1, + delete_file/1, + make_scratch_dir/1, + remove_tree/1, + listen/1, + accept/3, + tune_socket/1, + port_env/1, + check_env_opts/1, + rlimit_args/1, + cgroup_args/1, + frame/3, + send_frame/4, + parse_frame/1, + exit_reason/1, + code_reason/1, + os_pid_alive/1, + kill_os_pid/1, + to_bin/1, + to_list/1 +]). -include_lib("kernel/include/file.hrl"). @@ -58,20 +60,27 @@ %% embedded runtime, then `python3' from PATH. -spec python_executable(map()) -> string() | {error, term()}. python_executable(Opts) -> - Candidate = case maps:get(python, Opts, undefined) of - undefined -> - case application:get_env(erlang_python, isolated_python) of - {ok, P} -> P; - undefined -> default_python() - end; - P -> P - end, + Candidate = + case maps:get(python, Opts, undefined) of + undefined -> + case application:get_env(erlang_python, isolated_python) of + {ok, P} -> P; + undefined -> default_python() + end; + P -> + P + end, resolve_exe(to_list(Candidate)). default_python() -> case persistent_term:get({?MODULE, python}, undefined) of undefined -> - Exe = try py:python_executable() catch _:_ -> "python3" end, + Exe = + try + py:python_executable() + catch + _:_ -> "python3" + end, persistent_term:put({?MODULE, python}, Exe), Exe; Exe -> @@ -96,12 +105,13 @@ resolve_exe(Exe) -> %% relative to the VM's cwd (code added with -pa _build/...) would not resolve. -spec priv_dir() -> file:filename(). priv_dir() -> - Dir = case code:priv_dir(erlang_python) of - {error, bad_name} -> - filename:join(filename:dirname(filename:dirname(code:which(?MODULE))), "priv"); - D -> - D - end, + Dir = + case code:priv_dir(erlang_python) of + {error, bad_name} -> + filename:join(filename:dirname(filename:dirname(code:which(?MODULE))), "priv"); + D -> + D + end, filename:absname(Dir). %% @doc Private directory for the sockets of this node (mode 0700). Kept @@ -111,10 +121,11 @@ priv_dir() -> sock_dir() -> case persistent_term:get({?MODULE, sock_dir}, undefined) of undefined -> - Base = case os:getenv("TMPDIR") of - false -> "/tmp"; - T -> T - end, + Base = + case os:getenv("TMPDIR") of + false -> "/tmp"; + T -> T + end, Dir = filename:join(Base, "erlang_python_" ++ os:getpid()), ok = filelib:ensure_dir(filename:join(Dir, "x")), _ = file:change_mode(Dir, 8#700), @@ -173,8 +184,10 @@ remove_tree(Path) -> -spec new_sock_path(string()) -> file:filename(). new_sock_path(Prefix) -> - filename:join(sock_dir(), - Prefix ++ integer_to_list(erlang:unique_integer([positive])) ++ ".sock"). + filename:join( + sock_dir(), + Prefix ++ integer_to_list(erlang:unique_integer([positive])) ++ ".sock" + ). %% @doc Listening socket at Path, for one child to connect to. -spec listen(file:filename()) -> {ok, socket:socket()} | {error, term()}. @@ -185,11 +198,15 @@ listen(Path) -> case socket:bind(L, #{family => local, path => Path}) of ok -> case socket:listen(L) of - ok -> {ok, L}; - {error, _} = Err -> socket:close(L), Err + ok -> + {ok, L}; + {error, _} = Err -> + socket:close(L), + Err end; {error, _} = Err -> - socket:close(L), Err + socket:close(L), + Err end; {error, Reason} -> {error, {socket_open_failed, Reason}} @@ -219,8 +236,8 @@ accept(L, Watch, Deadline, Out) -> accept(L, Watch, Deadline, Out); {Port, {exit_status, Status}} when Watch =:= {port, Port} -> _ = socket:cancel(L, {select_info, accept, Handle}), - {error, {child_exited_at_start, exit_reason(Status), - drain_port_output(Port, Out)}}; + {error, + {child_exited_at_start, exit_reason(Status), drain_port_output(Port, Out)}}; {Port, {data, D}} when Watch =:= {port, Port} -> %% Keep it here, not in the mailbox: re-sending it would %% make this receive return at once and never time out @@ -230,10 +247,11 @@ accept(L, Watch, Deadline, Out) -> {error, {child_exited_at_start, code_reason(Code), <<>>}} after Left -> _ = socket:cancel(L, {select_info, accept, Handle}), - Output = case Watch of - {port, Port} -> drain_port_output(Port, Out); - _ -> <<>> - end, + Output = + case Watch of + {port, Port} -> drain_port_output(Port, Out); + _ -> <<>> + end, {error, {start_timeout, Output}} end; {error, Reason} -> @@ -265,28 +283,36 @@ tune_socket(S) -> -spec port_env(map()) -> [{string(), string() | false}]. port_env(Opts) -> Env = [{to_list(K), to_list(V)} || {K, V} <- maps:to_list(maps:get(env, Opts, #{}))], - Seed = case maps:get(hash_seed, Opts, random) of - random -> []; - N -> [{"PYTHONHASHSEED", integer_to_list(N)}] - end, + Seed = + case maps:get(hash_seed, Opts, random) of + random -> []; + N -> [{"PYTHONHASHSEED", integer_to_list(N)}] + end, Set = Env ++ Seed, - Clear = case maps:get(clear_env, Opts, false) of - true -> - Keep = [K || {K, _} <- Set], - lists:usort([{K, false} || KV <- os:getenv(), - K <- [hd(string:split(KV, "="))], - K =/= "", not lists:member(K, Keep)]); - false -> - [] - end, + Clear = + case maps:get(clear_env, Opts, false) of + true -> + Keep = [K || {K, _} <- Set], + lists:usort([ + {K, false} + || KV <- os:getenv(), + K <- [hd(string:split(KV, "="))], + K =/= "", + not lists:member(K, Keep) + ]); + false -> + [] + end, Clear ++ Set. %% @doc Check the options port_env/1 reads. -spec check_env_opts(map()) -> ok | {error, term()}. check_env_opts(Opts) -> case {maps:get(hash_seed, Opts, random), maps:get(clear_env, Opts, false)} of - {Seed, _} when Seed =/= random, - not (is_integer(Seed) andalso Seed >= 0 andalso Seed =< 4294967295) -> + {Seed, _} when + Seed =/= random, + not (is_integer(Seed) andalso Seed >= 0 andalso Seed =< 4294967295) + -> {error, {badarg, {hash_seed, Seed}}}; {_, Clear} when not is_boolean(Clear) -> {error, {badarg, {clear_env, Clear}}}; @@ -297,10 +323,13 @@ check_env_opts(Opts) -> -spec rlimit_args(map()) -> [string()]. rlimit_args(Opts) -> Limits = maps:get(rlimits, Opts, #{}), - lists:append([case maps:get(K, Limits, undefined) of - undefined -> []; - V when is_integer(V), V >= 0 -> ["--rlimit-" ++ atom_to_list(K), integer_to_list(V)] - end || K <- [as, cpu, nofile]]). + lists:append([ + case maps:get(K, Limits, undefined) of + undefined -> []; + V when is_integer(V), V >= 0 -> ["--rlimit-" ++ atom_to_list(K), integer_to_list(V)] + end + || K <- [as, cpu, nofile] + ]). -spec cgroup_args(map()) -> [string()]. cgroup_args(Opts) -> @@ -328,10 +357,11 @@ parse_frame(<>) -> case Body of <> -> try - Term = case Payload of - <<>> -> undefined; - _ -> binary_to_term(Payload) - end, + Term = + case Payload of + <<>> -> undefined; + _ -> binary_to_term(Payload) + end, {ok, {Id, Status, Term}, Rest} catch error:badarg -> {error, bad_etf} diff --git a/src/py_context.erl b/src/py_context.erl index 6441dc9..df97ed4 100644 --- a/src/py_context.erl +++ b/src/py_context.erl @@ -81,7 +81,6 @@ %% Used by py_context_embedded -export([register_nif_ref/1, unregister_nif_ref/0]). - %% Maps context pid -> NIF context reference. Read by interrupt/1, which must %% reach the NIF reference while the context process is blocked in a NIF and %% therefore cannot answer get_nif_ref/1. @@ -99,9 +98,6 @@ -export_type([context_mode/0, context/0]). - - - %% ============================================================================ %% API %% ============================================================================ @@ -223,8 +219,14 @@ call(Ctx, Module, Func, Args, Kwargs) -> call(Ctx, Module, Func, Args, Kwargs, infinity). %% @doc Call a Python function with timeout. --spec call(context(), atom() | binary(), atom() | binary(), list(), map(), - timeout()) -> {ok, term()} | {error, term()}. +-spec call( + context(), + atom() | binary(), + atom() | binary(), + list(), + map(), + timeout() +) -> {ok, term()} | {error, term()}. call(Ctx, Module, Func, Args, Kwargs, Timeout) when is_pid(Ctx) -> MRef = erlang:monitor(process, Ctx), ModuleBin = to_binary(Module), @@ -242,8 +244,15 @@ call(Ctx, Module, Func, Args, Kwargs, Timeout) when is_pid(Ctx) -> %% @param Timeout Timeout in milliseconds %% @param EnvRef Process-local environment reference %% @returns {ok, Result} | {error, Reason} --spec call(context(), atom() | binary(), atom() | binary(), list(), map(), - timeout(), reference()) -> {ok, term()} | {error, term()}. +-spec call( + context(), + atom() | binary(), + atom() | binary(), + list(), + map(), + timeout(), + reference() +) -> {ok, term()} | {error, term()}. call(Ctx, Module, Func, Args, Kwargs, Timeout, EnvRef) when is_pid(Ctx), is_reference(EnvRef) -> MRef = erlang:monitor(process, Ctx), ModuleBin = to_binary(Module), @@ -611,8 +620,17 @@ submit_embedded(Ctx, Module, Func, Args, Kwargs) -> case loop_ref(Ctx) of {ok, LoopRef} -> TaskRef = make_ref(), - case py_nif:submit_task(LoopRef, self(), TaskRef, - to_binary(Module), to_binary(Func), Args, Kwargs) of + case + py_nif:submit_task( + LoopRef, + self(), + TaskRef, + to_binary(Module), + to_binary(Func), + Args, + Kwargs + ) + of ok -> {ok, TaskRef}; {error, _} = Error -> Error end; @@ -631,8 +649,14 @@ submit_await(Ctx, Module, Func, Args) -> submit_await(Ctx, Module, Func, Args, Kwargs) -> submit_await(Ctx, Module, Func, Args, Kwargs, 5000). --spec submit_await(context(), atom() | binary(), atom() | binary(), list(), map(), - timeout()) -> {ok, term()} | {error, term()}. +-spec submit_await( + context(), + atom() | binary(), + atom() | binary(), + list(), + map(), + timeout() +) -> {ok, term()} | {error, term()}. submit_await(Ctx, Module, Func, Args, Kwargs, Timeout) -> case submit(Ctx, Module, Func, Args, Kwargs) of {ok, TaskRef} -> py_event_loop:await(TaskRef, Timeout); @@ -697,7 +721,8 @@ register_nif_ref(Ref) -> true = ets:insert(?REF_TAB, {self(), Ref}), ok catch - error:badarg -> ok %% table not created (library used without the app) + %% table not created (library used without the app) + error:badarg -> ok end. %% @private diff --git a/src/py_context_embedded.erl b/src/py_context_embedded.erl index dd73771..0527f1d 100644 --- a/src/py_context_embedded.erl +++ b/src/py_context_embedded.erl @@ -42,8 +42,10 @@ ref :: reference(), id :: pos_integer(), interp_id :: non_neg_integer(), - event_state = #{} :: map(), %% #{loop_ref => ref(), worker_pid => pid()} - callback_handler :: pid() | undefined, %% For thread-model callback handling + %% #{loop_ref => ref(), worker_pid => pid()} + event_state = #{} :: map(), + %% For thread-model callback handling + callback_handler :: pid() | undefined, %% Worker loop (start_loop/1): request id of the run_forever exec, the %% owner that gets {py_loop_exit, Ctx, Result}, its monitor, and the %% callers waiting in stop_loop/2 @@ -69,7 +71,11 @@ init(Parent, Id, Mode, Opts) -> init_started(Parent, Id, Ref, InterpId, Opts); {error, LimitError} -> py_context:unregister_nif_ref(), - try py_nif:context_destroy(Ref) catch _:_ -> ok end, + try + py_nif:context_destroy(Ref) + catch + _:_ -> ok + end, Parent ! {self(), {error, LimitError}} end; {error, Reason} -> @@ -96,27 +102,31 @@ init_started(Parent, Id, Ref, InterpId, Opts) -> apply_preload(Ref), %% Per-context preload from new/1 (imports the app once per worker) case maps:get(preload, Opts, undefined) of - undefined -> ok; + undefined -> + ok; PreCode when is_binary(PreCode); is_list(PreCode) -> case handle_exec_with_async(Ref, iolist_to_binary(PreCode)) of - ok -> ok; + ok -> + ok; {error, PreErr} -> error_logger:warning_msg( - "py_context ~p: preload failed: ~p~n", [InterpId, PreErr]) + "py_context ~p: preload failed: ~p~n", [InterpId, PreErr] + ) end end, %% For subinterpreters, create a dedicated event worker EventState = setup_event_worker(Ref, InterpId), %% For thread-model subinterpreters, spawn a dedicated callback handler %% because the main context process will be blocked in the NIF - CallbackHandler = case maps:get(mode, EventState, normal) of - thread_model -> - Handler = spawn_callback_handler(Ref), - ok = py_nif:context_set_callback_handler(Ref, Handler), - Handler; - _ -> - undefined - end, + CallbackHandler = + case maps:get(mode, EventState, normal) of + thread_model -> + Handler = spawn_callback_handler(Ref), + ok = py_nif:context_set_callback_handler(Ref, Handler), + Handler; + _ -> + undefined + end, Parent ! {self(), started}, State = #state{ ref = Ref, @@ -142,7 +152,8 @@ setup_event_worker(Ref, InterpId) -> {error, WorkerError} -> error_logger:warning_msg( "py_context ~p: Failed to start event worker: ~p~n", - [InterpId, WorkerError]), + [InterpId, WorkerError] + ), #{} end; {error, not_subinterp} -> @@ -155,7 +166,8 @@ setup_event_worker(Ref, InterpId) -> {error, Reason} -> error_logger:warning_msg( "py_context ~p: Failed to get event loop: ~p~n", - [InterpId, Reason]), + [InterpId, Reason] + ), #{} end. @@ -164,7 +176,9 @@ extend_erlang_module_in_context(Ref) -> PrivDir = code:priv_dir(erlang_python), Code = iolist_to_binary([ "import sys\n", - "priv_dir = '", PrivDir, "'\n", + "priv_dir = '", + PrivDir, + "'\n", "if priv_dir not in sys.path:\n", " sys.path.insert(0, priv_dir)\n", "import erlang\n", @@ -172,10 +186,12 @@ extend_erlang_module_in_context(Ref) -> " erlang._extend_erlang_module(priv_dir)\n" ]), case py_nif:context_exec(Ref, Code) of - ok -> ok; + ok -> + ok; {error, Reason} -> error_logger:warning_msg( - "py_context: Failed to extend erlang module: ~p~n", [Reason]), + "py_context: Failed to extend erlang module: ~p~n", [Reason] + ), ok end. @@ -224,123 +240,120 @@ loop(#state{ref = Ref, interp_id = InterpId, loop_req = LoopReq} = State) -> {start_loop, From, MRef, _Owner} when LoopReq =/= undefined -> From ! {MRef, {error, already_running}}, loop(State); - {start_loop, From, MRef, Owner} -> {Reply, NewState} = do_start_loop(Owner, State), From ! {MRef, Reply}, loop(NewState); - {stop_loop, From, MRef, _GraceMs} when LoopReq =:= undefined -> From ! {MRef, {error, no_loop}}, loop(State); - {stop_loop, From, MRef, GraceMs} -> loop(begin_stop_loop(From, MRef, GraceMs, State)); - {loop_ref, From, MRef} -> From ! {MRef, context_loop_ref(State)}, loop(State); - {py_result, LoopReq, Result} when LoopReq =/= undefined -> loop(loop_exited(Result, State)); - {loop_stop_deadline, LoopReq} when LoopReq =/= undefined -> %% Cooperative stop did not land: interrupt the thread _ = py_nif:context_interrupt(Ref), - erlang:send_after(?LOOP_INTERRUPT_GRACE_MS, self(), - {loop_interrupt_deadline, LoopReq}), + erlang:send_after( + ?LOOP_INTERRUPT_GRACE_MS, + self(), + {loop_interrupt_deadline, LoopReq} + ), loop(State); - {loop_interrupt_deadline, LoopReq} when LoopReq =/= undefined -> [W ! {M, {error, timeout}} || {W, M} <- State#state.loop_stop_waiters], loop(State#state{loop_stop_waiters = []}); - {loop_stop_deadline, _} -> loop(State); {loop_interrupt_deadline, _} -> loop(State); - - {'DOWN', Mon, process, _Owner, _Reason} - when Mon =:= State#state.loop_owner_mon, LoopReq =/= undefined -> + {'DOWN', Mon, process, _Owner, _Reason} when + Mon =:= State#state.loop_owner_mon, LoopReq =/= undefined + -> %% Owner is gone: nobody will hear the exit, stop the loop - loop(begin_stop_loop(undefined, undefined, 5000, - State#state{loop_owner_mon = undefined})); - + loop( + begin_stop_loop( + undefined, + undefined, + 5000, + State#state{loop_owner_mon = undefined} + ) + ); {async_result, _TaskRef, _} -> %% Result of a coroutine this process submitted (loop stop) - drop loop(State); - %% ---- while a worker loop runs, the thread is not available ---- {call, From, MRef, _, _, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {call, From, MRef, _, _, _, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {eval, From, MRef, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {eval, From, MRef, _, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {exec, From, MRef, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {exec, From, MRef, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); + From ! {MRef, {error, loop_running}}, + loop(State); {call_method, From, MRef, _, _, _} when LoopReq =/= undefined -> - From ! {MRef, {error, loop_running}}, loop(State); - + From ! {MRef, {error, loop_running}}, + loop(State); {stop, From, MRef} when LoopReq =/= undefined -> %% Get the thread out of the loop before destroying the context, %% otherwise context_destroy waits for a thread that never returns terminate(normal, stop_running_loop(State)), From ! {MRef, ok}; - - {'EXIT', _Pid, Reason} = Exit when LoopReq =/= undefined, - (Reason =:= shutdown orelse Reason =:= kill orelse - (is_tuple(Reason) andalso element(1, Reason) =:= shutdown)) -> + {'EXIT', _Pid, Reason} = Exit when + LoopReq =/= undefined, + (Reason =:= shutdown orelse Reason =:= kill orelse + (is_tuple(Reason) andalso element(1, Reason) =:= shutdown)) + -> self() ! Exit, loop(stop_running_loop(State)); - {call, From, MRef, Module, Func, Args, Kwargs} -> Result = handle_call_with_suspension(Ref, Module, Func, Args, Kwargs), From ! {MRef, Result}, loop(State); - %% Call with process-local environment (worker mode) {call, From, MRef, Module, Func, Args, Kwargs, EnvRef} -> Result = handle_call_with_suspension_and_env(Ref, Module, Func, Args, Kwargs, EnvRef), From ! {MRef, Result}, loop(State); - {eval, From, MRef, Code, Locals} -> Result = handle_eval_with_suspension(Ref, Code, Locals), From ! {MRef, Result}, loop(State); - %% Eval with process-local environment (worker mode) {eval, From, MRef, Code, Locals, EnvRef} -> Result = handle_eval_with_suspension_and_env(Ref, Code, Locals, EnvRef), From ! {MRef, Result}, loop(State); - {exec, From, MRef, Code} -> Result = handle_exec_with_async(Ref, Code), From ! {MRef, Result}, loop(State); - %% Exec with process-local environment (worker mode). %% Async dispatch with sync fallback (mirrors call/eval). {exec, From, MRef, Code, EnvRef} -> Result = handle_exec_with_async_and_env(Ref, Code, EnvRef), From ! {MRef, Result}, loop(State); - {call_method, From, MRef, ObjRef, Method, Args} -> Result = py_nif:context_call_method(Ref, ObjRef, Method, Args), From ! {MRef, Result}, loop(State); - {get_interp_id, From, MRef} -> From ! {MRef, {ok, InterpId}}, loop(State); - {is_subinterp, From, MRef} -> %% Check the interp_id to determine if this is a subinterpreter %% Subinterpreters have interp_id > 0 (main interpreter is 0) @@ -348,21 +361,17 @@ loop(#state{ref = Ref, interp_id = InterpId, loop_req = LoopReq} = State) -> IsSubinterp = is_context_subinterp(Ref), From ! {MRef, IsSubinterp}, loop(State); - {create_local_env, From, MRef} -> %% Create env inside this context's interpreter Result = py_nif:create_local_env(Ref), From ! {MRef, Result}, loop(State); - {get_nif_ref, From, MRef} -> From ! {MRef, Ref}, loop(State); - {stop, From, MRef} -> terminate(normal, State), From ! {MRef, ok}; - {'EXIT', Pid, Reason} -> %% Handle EXIT from linked processes case State#state.callback_handler of @@ -370,7 +379,8 @@ loop(#state{ref = Ref, interp_id = InterpId, loop_req = LoopReq} = State) -> %% Callback handler died - restart it for thread-model contexts error_logger:warning_msg( "py_context ~p: Callback handler died: ~p, restarting~n", - [InterpId, Reason]), + [InterpId, Reason] + ), NewHandler = spawn_callback_handler(Ref), ok = py_nif:context_set_callback_handler(Ref, NewHandler), NewState = State#state{callback_handler = NewHandler}, @@ -381,7 +391,8 @@ loop(#state{ref = Ref, interp_id = InterpId, loop_req = LoopReq} = State) -> %% Event worker died - log and continue (degraded asyncio support) error_logger:warning_msg( "py_context ~p: Event worker died: ~p~n", - [InterpId, Reason]), + [InterpId, Reason] + ), NewState = State#state{event_state = #{}}, loop(NewState); _ when Reason =:= shutdown; Reason =:= kill -> @@ -415,19 +426,33 @@ do_start_loop(Owner, #state{ref = Ref} = State) -> case context_loop_ref(State) of {ok, _} -> LoopReq = make_ref(), - case py_nif:context_call_async(Ref, self(), LoopReq, <<"erlang">>, - <<"_run_loop_forever">>, [self()], #{}) of + case + py_nif:context_call_async( + Ref, + self(), + LoopReq, + <<"erlang">>, + <<"_run_loop_forever">>, + [self()], + #{} + ) + of {enqueued, LoopReq} -> %% Wait for the loop to actually run before answering, so %% a submit right after start_loop finds it receive {py_loop_started} -> - Mon = case is_pid(Owner) of - true -> erlang:monitor(process, Owner); - false -> undefined - end, - {ok, State#state{loop_req = LoopReq, loop_owner = Owner, - loop_owner_mon = Mon, loop_stop_waiters = []}}; + Mon = + case is_pid(Owner) of + true -> erlang:monitor(process, Owner); + false -> undefined + end, + {ok, State#state{ + loop_req = LoopReq, + loop_owner = Owner, + loop_owner_mon = Mon, + loop_stop_waiters = [] + }}; {py_result, LoopReq, {error, Reason}} -> {{error, Reason}, State}; {py_result, LoopReq, Other} -> @@ -445,14 +470,22 @@ do_start_loop(Owner, #state{ref = Ref} = State) -> %% @private Ask the running loop to stop from inside, arm the interrupt %% deadline, and remember who to answer once it has exited. begin_stop_loop(From, MRef, GraceMs, #state{loop_req = LoopReq} = State) -> - Waiters = case From of - undefined -> State#state.loop_stop_waiters; - _ -> [{From, MRef} | State#state.loop_stop_waiters] - end, + Waiters = + case From of + undefined -> State#state.loop_stop_waiters; + _ -> [{From, MRef} | State#state.loop_stop_waiters] + end, case context_loop_ref(State) of {ok, LoopRef} -> - _ = py_nif:submit_task(LoopRef, self(), make_ref(), - <<"erlang">>, <<"_stop_loop">>, [], #{}); + _ = py_nif:submit_task( + LoopRef, + self(), + make_ref(), + <<"erlang">>, + <<"_stop_loop">>, + [], + #{} + ); _ -> ok end, @@ -461,8 +494,14 @@ begin_stop_loop(From, MRef, GraceMs, #state{loop_req = LoopReq} = State) -> %% @private The exec running the loop returned: tell the owner and the %% stop_loop callers, clear the loop state. -loop_exited(Result, #state{loop_owner = Owner, loop_owner_mon = Mon, - loop_stop_waiters = Waiters} = State) -> +loop_exited( + Result, + #state{ + loop_owner = Owner, + loop_owner_mon = Mon, + loop_stop_waiters = Waiters + } = State +) -> case Mon of undefined -> ok; _ -> erlang:demonitor(Mon, [flush]) @@ -472,8 +511,12 @@ loop_exited(Result, #state{loop_owner = Owner, loop_owner_mon = Mon, false -> ok end, [W ! {M, ok} || {W, M} <- Waiters], - State#state{loop_req = undefined, loop_owner = undefined, - loop_owner_mon = undefined, loop_stop_waiters = []}. + State#state{ + loop_req = undefined, + loop_owner = undefined, + loop_owner_mon = undefined, + loop_stop_waiters = [] + }. %% @private Synchronous stop used before terminate: interrupt and wait a %% bounded time for the exec to return. @@ -499,12 +542,20 @@ terminate(_Reason, #state{ref = Ref, event_state = EventState, callback_handler %% Stop the event worker first (if it exists and is still alive) case EventState of #{worker_pid := WorkerPid} -> - try gen_server:stop(WorkerPid, normal, 5000) catch _:_ -> ok end; + try + gen_server:stop(WorkerPid, normal, 5000) + catch + _:_ -> ok + end; _ -> ok end, %% Destroy the Python context - try py_nif:context_destroy(Ref) catch _:_ -> ok end, + try + py_nif:context_destroy(Ref) + catch + _:_ -> ok + end, ok. %% ============================================================================ @@ -539,25 +590,29 @@ callback_handler_loop(Ref) -> %% Executes the callback and writes the response to the callback pipe. handle_blocking_callback(Ref, FuncName, Args) -> %% Convert Args from tuple to list if needed - ArgsList = case Args of - T when is_tuple(T) -> tuple_to_list(T); - L when is_list(L) -> L; - _ -> [Args] - end, + ArgsList = + case Args of + T when is_tuple(T) -> tuple_to_list(T); + L when is_list(L) -> L; + _ -> [Args] + end, %% Execute the registered function - Response = case py_callback:execute(FuncName, ArgsList) of - {ok, Result} -> - %% Format: status_byte (2=ok, ETF) + external term format - <<2, (term_to_binary(Result))/binary>>; - {error, {not_found, Name}} -> - ErrMsg = iolist_to_binary( - io_lib:format("Function '~s' not registered", [Name])), - <<1, ErrMsg/binary>>; - {error, {Class, Reason, _Stack}} -> - ErrMsg = iolist_to_binary( - io_lib:format("~p: ~p", [Class, Reason])), - <<1, ErrMsg/binary>> - end, + Response = + case py_callback:execute(FuncName, ArgsList) of + {ok, Result} -> + %% Format: status_byte (2=ok, ETF) + external term format + <<2, (term_to_binary(Result))/binary>>; + {error, {not_found, Name}} -> + ErrMsg = iolist_to_binary( + io_lib:format("Function '~s' not registered", [Name]) + ), + <<1, ErrMsg/binary>>; + {error, {Class, Reason, _Stack}} -> + ErrMsg = iolist_to_binary( + io_lib:format("~p: ~p", [Class, Reason]) + ), + <<1, ErrMsg/binary>> + end, %% Write response to context's callback pipe py_nif:context_write_callback_response(Ref, Response). @@ -581,7 +636,6 @@ handle_call_with_suspension(Ref, Module, Func, Args, Kwargs) -> {error, Reason} end. - %% @private %% Handle eval with potential suspension for callbacks handle_eval_with_suspension(Ref, Code, Locals) -> @@ -605,7 +659,6 @@ handle_exec_with_async(Ref, Code) -> {error, Reason} end. - %% @private %% Wait for async result from worker thread %% The worker thread sends {py_result, RequestId, Result} when done. @@ -636,10 +689,13 @@ wait_for_async_result(Ref, RequestId, EnvRef) -> {py_result, RequestId, Result} -> process_async_result(Ref, Result, EnvRef); {py_callback, CallbackId, FuncName, CallbackArgs} -> - CallbackResult = handle_callback_with_nested_receive(Ref, FuncName, CallbackArgs, EnvRef), + CallbackResult = handle_callback_with_nested_receive( + Ref, FuncName, CallbackArgs, EnvRef + ), reply_inline_callback(Ref, CallbackId, CallbackResult), wait_for_async_result(Ref, RequestId, EnvRef) - after 300000 -> %% 5 minute timeout + %% 5 minute timeout + after 300000 -> {error, async_timeout} end. @@ -676,36 +732,58 @@ process_async_result(_Ref, Result, _EnvRef) -> %% Handle call with process-local environment. handle_call_with_suspension_and_env(Ref, Module, Func, Args, Kwargs, EnvRef) -> RequestId = make_ref(), - case py_nif:context_call_with_env_async(Ref, self(), RequestId, - Module, Func, Args, Kwargs, - EnvRef) of + case + py_nif:context_call_with_env_async( + Ref, + self(), + RequestId, + Module, + Func, + Args, + Kwargs, + EnvRef + ) + of {enqueued, RequestId} -> wait_for_async_result(Ref, RequestId, EnvRef); {error, Reason} -> {error, Reason} end. - %% @private %% Handle eval with process-local environment. handle_eval_with_suspension_and_env(Ref, Code, Locals, EnvRef) -> RequestId = make_ref(), - case py_nif:context_eval_with_env_async(Ref, self(), RequestId, - Code, Locals, EnvRef) of + case + py_nif:context_eval_with_env_async( + Ref, + self(), + RequestId, + Code, + Locals, + EnvRef + ) + of {enqueued, RequestId} -> wait_for_async_result(Ref, RequestId, EnvRef); {error, Reason} -> {error, Reason} end. - %% @private %% Handle exec with process-local environment via the same async-first %% path used for call/eval. handle_exec_with_async_and_env(Ref, Code, EnvRef) -> RequestId = make_ref(), - case py_nif:context_exec_with_env_async(Ref, self(), RequestId, - Code, EnvRef) of + case + py_nif:context_exec_with_env_async( + Ref, + self(), + RequestId, + Code, + EnvRef + ) + of {enqueued, RequestId} -> wait_for_async_result(Ref, RequestId, EnvRef); {error, Reason} -> @@ -726,19 +804,21 @@ is_context_subinterp(Ref) -> %% using context_call to avoid recursion through py:call. handle_schedule(Ref, <<"_execute_py">>, {Module, Func, Args, Kwargs}) -> %% schedule_py callback: call Python function via context - CallArgs = case Args of - none -> []; - undefined -> []; - List when is_list(List) -> List; - Tuple when is_tuple(Tuple) -> tuple_to_list(Tuple); - _ -> [Args] - end, - CallKwargs = case Kwargs of - none -> #{}; - undefined -> #{}; - Map when is_map(Map) -> Map; - _ -> #{} - end, + CallArgs = + case Args of + none -> []; + undefined -> []; + List when is_list(List) -> List; + Tuple when is_tuple(Tuple) -> tuple_to_list(Tuple); + _ -> [Args] + end, + CallKwargs = + case Kwargs of + none -> #{}; + undefined -> #{}; + Map when is_map(Map) -> Map; + _ -> #{} + end, handle_call_with_suspension(Ref, Module, Func, CallArgs, CallKwargs); handle_schedule(_Ref, CallbackName, CallbackArgs) when is_binary(CallbackName) -> %% Regular callback: execute via py_callback:execute @@ -769,21 +849,26 @@ handle_callback_with_nested_receive(Ref, FuncName, CallbackArgs, EnvRef) -> undefined -> ok; _ -> ok = py:put_local_env(InterpId, EnvRef) end, - Result = try - ArgsList = tuple_to_list(CallbackArgs), - case py_callback:execute(FuncName, ArgsList) of - {ok, Value} -> - {ok, <<2, (term_to_binary(Value))/binary>>}; - {error, Reason} -> - ErrMsg = iolist_to_binary(io_lib:format("~p", [Reason])), - {ok, <<1, ErrMsg/binary>>} - end - catch - Class:ExcReason:Stacktrace -> - ErrorMsg = iolist_to_binary(io_lib:format("~p:~p~n~p", - [Class, ExcReason, Stacktrace])), - {ok, <<1, ErrorMsg/binary>>} - end, + Result = + try + ArgsList = tuple_to_list(CallbackArgs), + case py_callback:execute(FuncName, ArgsList) of + {ok, Value} -> + {ok, <<2, (term_to_binary(Value))/binary>>}; + {error, Reason} -> + ErrMsg = iolist_to_binary(io_lib:format("~p", [Reason])), + {ok, <<1, ErrMsg/binary>>} + end + catch + Class:ExcReason:Stacktrace -> + ErrorMsg = iolist_to_binary( + io_lib:format( + "~p:~p~n~p", + [Class, ExcReason, Stacktrace] + ) + ), + {ok, <<1, ErrorMsg/binary>>} + end, Parent ! {callback_result, self(), Result} end), %% Wait for callback, processing nested requests @@ -796,61 +881,53 @@ wait_for_callback(Ref, CallbackPid) -> receive {callback_result, CallbackPid, Result} -> Result; - %% Handle nested py:call while waiting for callback {call, From, MRef, Module, Func, Args, Kwargs} -> NestedResult = handle_call_with_suspension(Ref, Module, Func, Args, Kwargs), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested py:call while waiting for callback (with EnvRef) {call, From, MRef, Module, Func, Args, Kwargs, EnvRef} -> - NestedResult = handle_call_with_suspension_and_env(Ref, Module, Func, Args, Kwargs, EnvRef), + NestedResult = handle_call_with_suspension_and_env( + Ref, Module, Func, Args, Kwargs, EnvRef + ), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested py:eval while waiting for callback (without EnvRef) {eval, From, MRef, Code, Locals} -> NestedResult = handle_eval_with_suspension(Ref, Code, Locals), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested py:eval while waiting for callback (with EnvRef) {eval, From, MRef, Code, Locals, EnvRef} -> NestedResult = handle_eval_with_suspension_and_env(Ref, Code, Locals, EnvRef), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested py:exec while waiting for callback {exec, From, MRef, Code} -> NestedResult = py_nif:context_exec(Ref, Code), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested py:exec while waiting for callback (with EnvRef) {exec, From, MRef, Code, EnvRef} -> NestedResult = py_nif:context_exec(Ref, Code, EnvRef), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle nested call_method while waiting for callback {call_method, From, MRef, ObjRef, Method, Args} -> NestedResult = py_nif:context_call_method(Ref, ObjRef, Method, Args), From ! {MRef, NestedResult}, wait_for_callback(Ref, CallbackPid); - %% Handle get_interp_id while waiting {get_interp_id, From, MRef} -> InterpId = py_nif:context_interp_id(Ref), From ! {MRef, {ok, InterpId}}, wait_for_callback(Ref, CallbackPid); - %% Handle create_local_env while waiting {create_local_env, From, MRef} -> Result = py_nif:create_local_env(Ref), From ! {MRef, Result}, wait_for_callback(Ref, CallbackPid); - {get_nif_ref, From, MRef} -> From ! {MRef, Ref}, wait_for_callback(Ref, CallbackPid) diff --git a/src/py_context_router.erl b/src/py_context_router.erl index eb609e5..6609490 100644 --- a/src/py_context_router.erl +++ b/src/py_context_router.erl @@ -102,7 +102,8 @@ %% Process dictionary key for bound context (pool-aware) -define(BOUND_CONTEXT_KEY(Pool), {py_bound_context, Pool}). --define(BOUND_CONTEXT_KEY, py_bound_context). %% Legacy for default pool +%% Legacy for default pool +-define(BOUND_CONTEXT_KEY, py_bound_context). %% Default pool name -define(DEFAULT_POOL, default). @@ -359,7 +360,11 @@ stop_pool(Pool) when is_atom(Pool) -> Contexts -> lists:foreach( fun(Ctx) -> - try py_context_sup:stop_context(Ctx) catch _:_ -> ok end + try + py_context_sup:stop_context(Ctx) + catch + _:_ -> ok + end end, Contexts ) @@ -369,12 +374,24 @@ stop_pool(Pool) when is_atom(Pool) -> Size = persistent_term:get(?POOL_SIZE_KEY(Pool), 0), lists:foreach( fun(N) -> - try persistent_term:erase(?POOL_CONTEXT_KEY(Pool, N)) catch _:_ -> ok end + try + persistent_term:erase(?POOL_CONTEXT_KEY(Pool, N)) + catch + _:_ -> ok + end end, lists:seq(1, Size) ), - try persistent_term:erase(?POOL_SIZE_KEY(Pool)) catch _:_ -> ok end, - try persistent_term:erase(?POOL_CONTEXTS_KEY(Pool)) catch _:_ -> ok end, + try + persistent_term:erase(?POOL_SIZE_KEY(Pool)) + catch + _:_ -> ok + end, + try + persistent_term:erase(?POOL_CONTEXTS_KEY(Pool)) + catch + _:_ -> ok + end, ok. %% @doc Check if a pool has been started and is still alive. @@ -384,7 +401,8 @@ stop_pool(Pool) when is_atom(Pool) -> -spec pool_started(pool_name()) -> boolean(). pool_started(Pool) when is_atom(Pool) -> case persistent_term:get(?POOL_SIZE_KEY(Pool), 0) of - 0 -> false; + 0 -> + false; _N -> %% Verify at least one context is actually alive case persistent_term:get(?POOL_CONTEXT_KEY(Pool, 1), undefined) of diff --git a/src/py_context_sup.erl b/src/py_context_sup.erl index f633b01..d573839 100644 --- a/src/py_context_sup.erl +++ b/src/py_context_sup.erl @@ -63,8 +63,11 @@ stop_context(Pid) when is_pid(Pid) -> %% @doc List all running context PIDs. -spec which_contexts() -> [pid()]. which_contexts() -> - [Pid || {_, Pid, _, _} <- supervisor:which_children(?MODULE), - is_pid(Pid)]. + [ + Pid + || {_, Pid, _, _} <- supervisor:which_children(?MODULE), + is_pid(Pid) + ]. %% ============================================================================ %% Supervisor callbacks diff --git a/src/py_event_loop.erl b/src/py_event_loop.erl index c074e7f..4a29c70 100644 --- a/src/py_event_loop.erl +++ b/src/py_event_loop.erl @@ -120,8 +120,16 @@ register_callbacks() -> %% {async_result, Ref, {ok, Result}} - on success %% {async_result, Ref, {error, Reason}} - on failure -spec run_async(reference(), map()) -> ok | {error, term()}. -run_async(LoopRef, #{ref := Ref, caller := Caller, module := Module, - func := Func, args := Args} = Request) -> +run_async( + LoopRef, + #{ + ref := Ref, + caller := Caller, + module := Module, + func := Func, + args := Args + } = Request +) -> Kwargs = maps:get(kwargs, Request, #{}), ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), @@ -143,8 +151,12 @@ run_async(LoopRef, #{ref := Ref, caller := Caller, module := Module, run(Module, Func, Args) -> run(Module, Func, Args, #{}). --spec run(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Opts :: map()) -> {ok, term()} | {error, term()}. +-spec run( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Opts :: map() +) -> {ok, term()} | {error, term()}. run(Module, Func, Args, Opts) -> Timeout = maps:get(timeout, Opts, 5000), Kwargs = maps:get(kwargs, Opts, #{}), @@ -161,13 +173,20 @@ run(Module, Func, Args, Opts) -> %% Ref = py_event_loop:create_task(my_module, my_async_func, [arg1]), %% %% ... do other work ... %% {ok, Result} = py_event_loop:await(Ref) --spec create_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> reference(). +-spec create_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> reference(). create_task(Module, Func, Args) -> create_task(Module, Func, Args, #{}). --spec create_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Kwargs :: map()) -> reference(). +-spec create_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Kwargs :: map() +) -> reference(). create_task(Module, Func, Args, Kwargs) -> {ok, LoopRef} = get_loop(), Ref = make_ref(), @@ -175,12 +194,15 @@ create_task(Module, Func, Args, Kwargs) -> ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), %% Check if there's a process-local env (from py:exec) and use it - ok = case get_process_env() of - undefined -> - py_nif:submit_task(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs); - EnvRef -> - py_nif:submit_task_with_env(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef) - end, + ok = + case get_process_env() of + undefined -> + py_nif:submit_task(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs); + EnvRef -> + py_nif:submit_task_with_env( + LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef + ) + end, Ref. %% @doc Get the process-local env reference if available. @@ -188,7 +210,8 @@ create_task(Module, Func, Args, Kwargs) -> -spec get_process_env() -> reference() | undefined. get_process_env() -> case get(py_local_env) of - undefined -> undefined; + undefined -> + undefined; Envs when is_map(Envs) -> %% Return any env (for __main__ lookup, any env works) case maps:values(Envs) of @@ -228,13 +251,20 @@ await(Ref, Timeout) -> %% %% Example: %% ok = py_event_loop:spawn_task(logger, log_event, [event_data]) --spec spawn_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> ok. +-spec spawn_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> ok. spawn_task(Module, Func, Args) -> spawn_task(Module, Func, Args, #{}). --spec spawn_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Kwargs :: map()) -> ok. +-spec spawn_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Kwargs :: map() +) -> ok. spawn_task(Module, Func, Args, Kwargs) -> {ok, LoopRef} = get_loop(), Ref = make_ref(), @@ -252,12 +282,15 @@ spawn_task(Module, Func, Args, Kwargs) -> ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), %% Submit task with caller's env if available - ok = case CallerEnv of - undefined -> - py_nif:submit_task(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, Kwargs); - EnvRef -> - py_nif:submit_task_with_env(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef) - end, + ok = + case CallerEnv of + undefined -> + py_nif:submit_task(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, Kwargs); + EnvRef -> + py_nif:submit_task_with_env( + LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef + ) + end, ok. %% ============================================================================ @@ -362,7 +395,9 @@ set_default_policy() -> %% Then set the event loop policy (only on Python < 3.14) Code = iolist_to_binary([ "import sys\n", - "priv_dir = '", PrivDir, "'\n", + "priv_dir = '", + PrivDir, + "'\n", "if priv_dir not in sys.path:\n", " sys.path.insert(0, priv_dir)\n", "import asyncio\n", @@ -371,10 +406,12 @@ set_default_policy() -> " asyncio.set_event_loop_policy(get_event_loop_policy())\n" ]), case py:exec(Code) of - ok -> ok; + ok -> + ok; {error, Reason} -> error_logger:warning_msg("Failed to set ErlangEventLoop policy: ~p~n", [Reason]), - ok %% Non-fatal + %% Non-fatal + ok end. %% @doc Extend the C 'erlang' module with Python event loop exports. @@ -382,15 +419,19 @@ set_default_policy() -> extend_erlang_module(PrivDir) -> Code = iolist_to_binary([ "import erlang\n", - "priv_dir = '", PrivDir, "'\n", + "priv_dir = '", + PrivDir, + "'\n", "if hasattr(erlang, '_extend_erlang_module'):\n", " erlang._extend_erlang_module(priv_dir)\n" ]), case py:exec(Code) of - ok -> ok; + ok -> + ok; {error, Reason} -> error_logger:warning_msg("Failed to extend erlang module: ~p~n", [Reason]), - ok %% Non-fatal + %% Non-fatal + ok end. handle_call(get_loop, _From, #state{loop_ref = undefined} = State) -> @@ -412,10 +453,8 @@ handle_call(get_loop, _From, #state{loop_ref = undefined} = State) -> {error, _} = Error -> {reply, Error, State} end; - handle_call(get_loop, _From, #state{loop_ref = LoopRef} = State) -> {reply, {ok, LoopRef}, State}; - handle_call(_Request, _From, State) -> {reply, {error, unknown_request}, State}. @@ -444,12 +483,17 @@ terminate(_Reason, #state{loop_ref = LoopRef, worker_pid = WorkerPid}) -> %% Skipped on Python 3.14+ since we never installed one (see %% set_default_policy/0). reset_default_policy() -> - Code = <<" -import sys, asyncio -if sys.version_info < (3, 14): - asyncio.set_event_loop_policy(None) -">>, - try py:exec(Code) catch _:_ -> ok end, + Code = << + "\n" + "import sys, asyncio\n" + "if sys.version_info < (3, 14):\n" + " asyncio.set_event_loop_policy(None)\n" + >>, + try + py:exec(Code) + catch + _:_ -> ok + end, ok. code_change(_OldVsn, State, _Extra) -> @@ -508,7 +552,9 @@ cb_dispatch_timer([LoopRef, CallbackId]) -> %% Args: [Seconds] - number of seconds (converted to non-negative ms internally) cb_sleep([Seconds]) when is_number(Seconds) -> Ms = max(0, round(Seconds * 1000)), - receive after Ms -> ok end; + receive + after Ms -> ok + end; cb_sleep(_Args) -> ok. @@ -520,19 +566,21 @@ cb_sleep(_Args) -> %% - Args: list | none - Positional arguments %% - Kwargs: map | none - Keyword arguments cb_execute_py([Module, Func, Args, Kwargs]) -> - CallArgs = case Args of - none -> []; - undefined -> []; - List when is_list(List) -> List; - Tuple when is_tuple(Tuple) -> tuple_to_list(Tuple); - _ -> [Args] - end, - CallKwargs = case Kwargs of - none -> #{}; - undefined -> #{}; - Map when is_map(Map) -> Map; - _ -> #{} - end, + CallArgs = + case Args of + none -> []; + undefined -> []; + List when is_list(List) -> List; + Tuple when is_tuple(Tuple) -> tuple_to_list(Tuple); + _ -> [Args] + end, + CallKwargs = + case Kwargs of + none -> #{}; + undefined -> #{}; + Map when is_map(Map) -> Map; + _ -> #{} + end, %% Use default pool via py:call case py:call(Module, Func, CallArgs, CallKwargs) of {ok, Result} -> Result; diff --git a/src/py_event_loop_pool.erl b/src/py_event_loop_pool.erl index bc42f29..fadf2de 100644 --- a/src/py_event_loop_pool.erl +++ b/src/py_event_loop_pool.erl @@ -70,10 +70,14 @@ %% OWN_GIL session record - maps {PID, LoopIdx} to worker/handle -record(owngil_session, { - key :: {pid(), pos_integer()}, %% {CallerPid, LoopIndex} - worker_id :: non_neg_integer(), %% Worker thread index - handle_id :: non_neg_integer(), %% Namespace handle ID - monitor_ref :: reference() %% Process monitor for cleanup + %% {CallerPid, LoopIndex} + key :: {pid(), pos_integer()}, + %% Worker thread index + worker_id :: non_neg_integer(), + %% Namespace handle ID + handle_id :: non_neg_integer(), + %% Process monitor for cleanup + monitor_ref :: reference() }). %% Persistent term keys for O(1) access @@ -88,8 +92,11 @@ -spec start_link() -> {ok, pid()} | {error, term()}. start_link() -> - PoolSize = application:get_env(erlang_python, event_loop_pool_size, - erlang:system_info(schedulers)), + PoolSize = application:get_env( + erlang_python, + event_loop_pool_size, + erlang:system_info(schedulers) + ), start_link(PoolSize). -spec start_link(pos_integer()) -> {ok, pid()} | {error, term()}. @@ -105,7 +112,8 @@ stop() -> -spec get_loop() -> {ok, reference()} | {error, not_available}. get_loop() -> case pool_size() of - 0 -> {error, not_available}; + 0 -> + {error, not_available}; N -> %% Hash PID to get consistent loop assignment Hash = erlang:phash2(self()), @@ -129,13 +137,20 @@ get_stats() -> %% Example: %% Ref = py_event_loop_pool:create_task(my_module, my_async_func, [arg1]), %% {ok, Result} = py_event_loop_pool:await(Ref) --spec create_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> reference(). +-spec create_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> reference(). create_task(Module, Func, Args) -> create_task(Module, Func, Args, #{}). --spec create_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Kwargs :: map()) -> reference(). +-spec create_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Kwargs :: map() +) -> reference(). create_task(Module, Func, Args, _Kwargs) -> %% Check if OWN_GIL mode is enabled case is_owngil_enabled() of @@ -147,8 +162,15 @@ create_task(Module, Func, Args, _Kwargs) -> Caller = self(), ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), - ok = py_nif:owngil_submit_task(WorkerId, HandleId, Caller, - Ref, ModuleBin, FuncBin, Args), + ok = py_nif:owngil_submit_task( + WorkerId, + HandleId, + Caller, + Ref, + ModuleBin, + FuncBin, + Args + ), Ref; {error, _Reason} -> %% Fall back to regular path @@ -159,8 +181,11 @@ create_task(Module, Func, Args, _Kwargs) -> end. %% @private Regular (non-OWN_GIL) task creation --spec create_task_regular(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> reference(). +-spec create_task_regular( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> reference(). create_task_regular(Module, Func, Args) -> case get_loop() of {ok, LoopRef} -> @@ -171,20 +196,27 @@ create_task_regular(Module, Func, Args) -> end. %% @doc Submit a task to a specific loop. --spec create_task_on_loop(LoopRef :: reference(), Module :: atom() | binary(), - Func :: atom() | binary(), Args :: list(), - Kwargs :: map()) -> reference(). +-spec create_task_on_loop( + LoopRef :: reference(), + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Kwargs :: map() +) -> reference(). create_task_on_loop(LoopRef, Module, Func, Args, Kwargs) -> Ref = make_ref(), Caller = self(), ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), - ok = case py_event_loop:get_process_env() of - undefined -> - py_nif:submit_task(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs); - EnvRef -> - py_nif:submit_task_with_env(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef) - end, + ok = + case py_event_loop:get_process_env() of + undefined -> + py_nif:submit_task(LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs); + EnvRef -> + py_nif:submit_task_with_env( + LoopRef, Caller, Ref, ModuleBin, FuncBin, Args, Kwargs, EnvRef + ) + end, Ref. %% @doc Blocking run of an async Python function. @@ -193,8 +225,12 @@ create_task_on_loop(LoopRef, Module, Func, Args, Kwargs) -> run(Module, Func, Args) -> run(Module, Func, Args, #{}). --spec run(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Opts :: map()) -> {ok, term()} | {error, term()}. +-spec run( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Opts :: map() +) -> {ok, term()} | {error, term()}. run(Module, Func, Args, Opts) -> Timeout = maps:get(timeout, Opts, 5000), Kwargs = maps:get(kwargs, Opts, #{}), @@ -202,13 +238,20 @@ run(Module, Func, Args, Opts) -> await(Ref, Timeout). %% @doc Fire-and-forget task execution. --spec spawn_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> ok. +-spec spawn_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> ok. spawn_task(Module, Func, Args) -> spawn_task(Module, Func, Args, #{}). --spec spawn_task(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list(), Kwargs :: map()) -> ok. +-spec spawn_task( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list(), + Kwargs :: map() +) -> ok. spawn_task(Module, Func, Args, _Kwargs) -> %% Check if OWN_GIL mode is enabled case is_owngil_enabled() of @@ -226,8 +269,15 @@ spawn_task(Module, Func, Args, _Kwargs) -> end), ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), - ok = py_nif:owngil_submit_task(WorkerId, HandleId, Receiver, - Ref, ModuleBin, FuncBin, Args), + ok = py_nif:owngil_submit_task( + WorkerId, + HandleId, + Receiver, + Ref, + ModuleBin, + FuncBin, + Args + ), ok; {error, _Reason} -> %% Fall back to regular path @@ -238,8 +288,11 @@ spawn_task(Module, Func, Args, _Kwargs) -> end. %% @private Regular (non-OWN_GIL) spawn_task --spec spawn_task_regular(Module :: atom() | binary(), Func :: atom() | binary(), - Args :: list()) -> ok. +-spec spawn_task_regular( + Module :: atom() | binary(), + Func :: atom() | binary(), + Args :: list() +) -> ok. spawn_task_regular(Module, Func, Args) -> case get_loop() of {ok, LoopRef} -> @@ -253,12 +306,15 @@ spawn_task_regular(Module, Func, Args) -> end), ModuleBin = py_util:to_binary(Module), FuncBin = py_util:to_binary(Func), - ok = case CallerEnv of - undefined -> - py_nif:submit_task(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, #{}); - EnvRef -> - py_nif:submit_task_with_env(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, #{}, EnvRef) - end, + ok = + case CallerEnv of + undefined -> + py_nif:submit_task(LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, #{}); + EnvRef -> + py_nif:submit_task_with_env( + LoopRef, Receiver, Ref, ModuleBin, FuncBin, Args, #{}, EnvRef + ) + end, ok; {error, not_available} -> py_event_loop:spawn_task(Module, Func, Args, #{}) @@ -345,7 +401,8 @@ eval(LoopRef, Expr) -> -spec get_all_loops() -> {ok, [{reference(), pid()}]} | {error, not_available}. get_all_loops() -> case pool_size() of - 0 -> {error, not_available}; + 0 -> + {error, not_available}; N -> Loops = persistent_term:get(?PT_LOOPS), {ok, [element(Idx, Loops) || Idx <- lists:seq(1, N)]} @@ -358,7 +415,8 @@ get_all_loops() -> -spec get_all_sessions() -> [{non_neg_integer(), non_neg_integer()}]. get_all_sessions() -> case get_sessions_table() of - undefined -> []; + undefined -> + []; Tid -> ets:foldl( fun(#owngil_session{worker_id = W, handle_id = H}, Acc) -> @@ -395,26 +453,30 @@ init([NumLoops]) -> OwnGilEnabled = OwnGilConfigured andalso py_nif:owngil_supported(), %% Initialize OWN_GIL infrastructure if enabled - {Sessions, OwnGilReady} = case OwnGilEnabled of - true -> - %% Start subinterpreter thread pool - case py_nif:subinterp_thread_pool_start(NumLoops) of - ok -> - %% Create sessions ETS table - Tid = ets:new(?MODULE, [ - set, public, - {keypos, #owngil_session.key}, - {read_concurrency, true} - ]), - persistent_term:put(?PT_SESSIONS, Tid), - {Tid, true}; - {error, _} -> - error_logger:warning_msg("py_event_loop_pool: OWN_GIL pool failed to start~n"), - {undefined, false} - end; - false -> - {undefined, false} - end, + {Sessions, OwnGilReady} = + case OwnGilEnabled of + true -> + %% Start subinterpreter thread pool + case py_nif:subinterp_thread_pool_start(NumLoops) of + ok -> + %% Create sessions ETS table + Tid = ets:new(?MODULE, [ + set, + public, + {keypos, #owngil_session.key}, + {read_concurrency, true} + ]), + persistent_term:put(?PT_SESSIONS, Tid), + {Tid, true}; + {error, _} -> + error_logger:warning_msg( + "py_event_loop_pool: OWN_GIL pool failed to start~n" + ), + {undefined, false} + end; + false -> + {undefined, false} + end, persistent_term:put(?PT_OWNGIL_ENABLED, OwnGilReady), @@ -469,24 +531,30 @@ handle_call(get_stats, _From, State) -> }, %% Add OWN_GIL-specific stats if enabled - Stats = case State#state.owngil_enabled of - true -> - %% Get pool stats from NIF - PoolStats = try py_nif:subinterp_thread_pool_stats() catch _:_ -> #{} end, - %% Count active sessions - ActiveSessions = case State#state.sessions of - undefined -> 0; - Tid -> ets:info(Tid, size) - end, - maps:merge(BaseStats, #{ - active_sessions => ActiveSessions, - pool_stats => PoolStats - }); - false -> - BaseStats - end, + Stats = + case State#state.owngil_enabled of + true -> + %% Get pool stats from NIF + PoolStats = + try + py_nif:subinterp_thread_pool_stats() + catch + _:_ -> #{} + end, + %% Count active sessions + ActiveSessions = + case State#state.sessions of + undefined -> 0; + Tid -> ets:info(Tid, size) + end, + maps:merge(BaseStats, #{ + active_sessions => ActiveSessions, + pool_stats => PoolStats + }); + false -> + BaseStats + end, {reply, Stats, State}; - handle_call(_Request, _From, State) -> {reply, {error, unknown_request}, State}. @@ -495,69 +563,132 @@ handle_cast(_Msg, State) -> handle_info({'EXIT', _Pid, _Reason}, State) -> {noreply, State#state{supported = false}}; - handle_info({'DOWN', MonRef, process, Pid, _Reason}, State) -> %% Process died - clean up any OWN_GIL sessions for this process case State#state.sessions of - undefined -> ok; + undefined -> + ok; Tid -> %% Find and remove all sessions for this PID using ets:foldl %% to avoid dialyzer issues with match specs and record types - ets:foldl(fun(#owngil_session{key = {SessionPid, _} = Key, - worker_id = WorkerId, - handle_id = HandleId, - monitor_ref = SessionMonRef}, Acc) -> - case SessionPid =:= Pid andalso SessionMonRef =:= MonRef of - true -> - %% Destroy session in worker - try py_nif:owngil_destroy_session(WorkerId, HandleId) catch _:_ -> ok end, - %% Remove from ETS - ets:delete(Tid, Key); - false -> - ok + ets:foldl( + fun( + #owngil_session{ + key = {SessionPid, _} = Key, + worker_id = WorkerId, + handle_id = HandleId, + monitor_ref = SessionMonRef + }, + Acc + ) -> + case SessionPid =:= Pid andalso SessionMonRef =:= MonRef of + true -> + %% Destroy session in worker + try + py_nif:owngil_destroy_session(WorkerId, HandleId) + catch + _:_ -> ok + end, + %% Remove from ETS + ets:delete(Tid, Key); + false -> + ok + end, + Acc end, - Acc - end, ok, Tid) + ok, + Tid + ) end, {noreply, State}; - handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, State) -> %% Clean up OWN_GIL sessions if enabled case State#state.sessions of - undefined -> ok; + undefined -> + ok; Tid -> %% Destroy all sessions - ets:foldl(fun(#owngil_session{worker_id = WorkerId, handle_id = HandleId}, _) -> - try py_nif:owngil_destroy_session(WorkerId, HandleId) catch _:_ -> ok end, - ok - end, ok, Tid), - try ets:delete(Tid) catch _:_ -> ok end + ets:foldl( + fun(#owngil_session{worker_id = WorkerId, handle_id = HandleId}, _) -> + try + py_nif:owngil_destroy_session(WorkerId, HandleId) + catch + _:_ -> ok + end, + ok + end, + ok, + Tid + ), + try + ets:delete(Tid) + catch + _:_ -> ok + end end, %% Stop OWN_GIL thread pool if it was started case State#state.owngil_enabled of - true -> try py_nif:subinterp_thread_pool_stop() catch _:_ -> ok end; - false -> ok + true -> + try + py_nif:subinterp_thread_pool_stop() + catch + _:_ -> ok + end; + false -> + ok end, %% Clean up regular event loops case persistent_term:get(?PT_LOOPS, {}) of - {} -> ok; + {} -> + ok; Loops -> - lists:foreach(fun({LoopRef, WorkerPid}) -> - try py_event_worker:stop(WorkerPid) catch _:_ -> ok end, - try py_nif:event_loop_release_python_loop(LoopRef) catch _:_ -> ok end, - try py_nif:event_loop_destroy(LoopRef) catch _:_ -> ok end - end, tuple_to_list(Loops)) + lists:foreach( + fun({LoopRef, WorkerPid}) -> + try + py_event_worker:stop(WorkerPid) + catch + _:_ -> ok + end, + try + py_nif:event_loop_release_python_loop(LoopRef) + catch + _:_ -> ok + end, + try + py_nif:event_loop_destroy(LoopRef) + catch + _:_ -> ok + end + end, + tuple_to_list(Loops) + ) end, - try persistent_term:erase(?PT_LOOPS) catch _:_ -> ok end, - try persistent_term:erase(?PT_NUM_LOOPS) catch _:_ -> ok end, - try persistent_term:erase(?PT_OWNGIL_ENABLED) catch _:_ -> ok end, - try persistent_term:erase(?PT_SESSIONS) catch _:_ -> ok end, + try + persistent_term:erase(?PT_LOOPS) + catch + _:_ -> ok + end, + try + persistent_term:erase(?PT_NUM_LOOPS) + catch + _:_ -> ok + end, + try + persistent_term:erase(?PT_OWNGIL_ENABLED) + catch + _:_ -> ok + end, + try + persistent_term:erase(?PT_SESSIONS) + catch + _:_ -> ok + end, ok. %%% ============================================================================ @@ -587,12 +718,14 @@ get_sessions_table() -> %% @private Get or create OWN_GIL session for calling process %% Returns {ok, {WorkerId, HandleId, LoopIdx}} or {error, Reason} --spec ensure_session() -> {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. +-spec ensure_session() -> + {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. ensure_session() -> Pid = self(), N = pool_size(), case N of - 0 -> {error, not_available}; + 0 -> + {error, not_available}; _ -> %% Hash PID to get consistent loop assignment Hash = erlang:phash2(Pid), @@ -601,7 +734,8 @@ ensure_session() -> end. %% @private Get or create session for a specific PID and loop index --spec ensure_session(pid(), pos_integer()) -> {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. +-spec ensure_session(pid(), pos_integer()) -> + {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. ensure_session(Pid, LoopIdx) -> case get_sessions_table() of undefined -> @@ -619,10 +753,13 @@ ensure_session(Pid, LoopIdx) -> end. %% @private Create a new OWN_GIL session --spec create_session(ets:tid(), pid(), pos_integer()) -> {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. +-spec create_session(ets:tid(), pid(), pos_integer()) -> + {ok, {non_neg_integer(), non_neg_integer(), pos_integer()}} | {error, term()}. create_session(Tid, Pid, LoopIdx) -> %% Create session via NIF - assigns worker and creates namespace - case py_nif:owngil_create_session(LoopIdx - 1) of %% Convert to 0-based index + + %% Convert to 0-based index + case py_nif:owngil_create_session(LoopIdx - 1) of {ok, WorkerId, HandleId} -> %% Monitor the process for cleanup on exit MonRef = erlang:monitor(process, Pid), @@ -639,7 +776,11 @@ create_session(Tid, Pid, LoopIdx) -> false -> %% Another process created the session first, destroy ours erlang:demonitor(MonRef, [flush]), - try py_nif:owngil_destroy_session(WorkerId, HandleId) catch _:_ -> ok end, + try + py_nif:owngil_destroy_session(WorkerId, HandleId) + catch + _:_ -> ok + end, %% Retry lookup case ets:lookup(Tid, {Pid, LoopIdx}) of [#owngil_session{worker_id = W, handle_id = H}] -> @@ -651,4 +792,3 @@ create_session(Tid, Pid, LoopIdx) -> {error, Reason} -> {error, Reason} end. - diff --git a/src/py_event_worker.erl b/src/py_event_worker.erl index 0f0ec19..48f2b78 100644 --- a/src/py_event_worker.erl +++ b/src/py_event_worker.erl @@ -24,8 +24,10 @@ %% TimerRef => {ErlTimerRef, LoopRef, CallbackId}. The loop is the one %% named in the start_timer message: a loop without a worker of its own %% borrows this one, so an expiry is dispatched to the loop that set it. - timers = #{} :: #{reference() | non_neg_integer() => - {reference(), reference(), non_neg_integer()}}, + timers = #{} :: #{ + reference() | non_neg_integer() => + {reference(), reference(), non_neg_integer()} + }, stats = #{select_count => 0, timer_count => 0, dispatch_count => 0} :: map() }). @@ -59,39 +61,36 @@ handle_info({select, FdRes, _Ref, ready_input}, State) -> %% Trigger event processing after FD event dispatch maybe_send_task_ready(), {noreply, State}; - handle_info({select, FdRes, _Ref, ready_output}, State) -> py_nif:handle_fd_event_and_reselect(FdRes, write), %% Trigger event processing after FD event dispatch maybe_send_task_ready(), {noreply, State}; - handle_info({start_timer, LoopRef, DelayMs, CallbackId, TimerRef}, State) -> #state{timers = Timers} = State, ErlTimerRef = erlang:send_after(DelayMs, self(), {timeout, TimerRef}), NewTimers = maps:put(TimerRef, {ErlTimerRef, LoopRef, CallbackId}, Timers), {noreply, State#state{timers = NewTimers}}; - handle_info({start_timer, DelayMs, CallbackId, TimerRef}, State) -> #state{loop_ref = LoopRef, timers = Timers} = State, ErlTimerRef = erlang:send_after(DelayMs, self(), {timeout, TimerRef}), NewTimers = maps:put(TimerRef, {ErlTimerRef, LoopRef, CallbackId}, Timers), {noreply, State#state{timers = NewTimers}}; - handle_info({cancel_timer, TimerRef}, State) -> #state{timers = Timers} = State, case maps:get(TimerRef, Timers, undefined) of - undefined -> {noreply, State}; + undefined -> + {noreply, State}; {ErlTimerRef, _LoopRef, _CallbackId} -> erlang:cancel_timer(ErlTimerRef), NewTimers = maps:remove(TimerRef, Timers), {noreply, State#state{timers = NewTimers}} end; - handle_info({timeout, TimerRef}, State) -> #state{loop_ref = OwnLoopRef, timers = Timers} = State, case maps:get(TimerRef, Timers, undefined) of - undefined -> {noreply, State}; + undefined -> + {noreply, State}; {_ErlTimerRef, LoopRef, CallbackId} -> py_nif:dispatch_timer(LoopRef, CallbackId), NewTimers = maps:remove(TimerRef, Timers), @@ -104,14 +103,12 @@ handle_info({timeout, TimerRef}, State) -> end, {noreply, State#state{timers = NewTimers}} end; - -handle_info({select, _FdRes, _Ref, cancelled}, State) -> {noreply, State}; - +handle_info({select, _FdRes, _Ref, cancelled}, State) -> + {noreply, State}; %% Re-arm request from the Python loop (see py_nif:fd_arm/2) handle_info({fd_arm, FdRes, Mode}, State) -> _ = py_nif:fd_arm(FdRes, Mode), {noreply, State}; - %% Handle task_ready wakeup from submit_task NIF. %% This is sent via enif_send when a new async task is submitted. %% Uses a drain-until-empty loop to handle tasks submitted during processing. @@ -120,13 +117,16 @@ handle_info(task_ready, #state{loop_ref = LoopRef} = State) -> put(task_ready_pending, false), drain_tasks_loop(LoopRef), {noreply, State}; - -handle_info(_Info, State) -> {noreply, State}. +handle_info(_Info, State) -> + {noreply, State}. terminate(_Reason, #state{timers = Timers}) -> - maps:foreach(fun(_TimerRef, {ErlTimerRef, _LoopRef, _CallbackId}) -> - erlang:cancel_timer(ErlTimerRef) - end, Timers), + maps:foreach( + fun(_TimerRef, {ErlTimerRef, _LoopRef, _CallbackId}) -> + erlang:cancel_timer(ErlTimerRef) + end, + Timers + ), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. diff --git a/src/py_event_worker_registry.erl b/src/py_event_worker_registry.erl index 2e8cd8f..5eacacd 100644 --- a/src/py_event_worker_registry.erl +++ b/src/py_event_worker_registry.erl @@ -39,7 +39,6 @@ handle_call({register, LoopId, WorkerPid, LoopRef}, _From, State) -> MonRef = erlang:monitor(process, WorkerPid), NewState = maps:put(WorkerPid, {LoopId, MonRef}, State), {reply, ok, NewState}; - handle_call({unregister, LoopId}, _From, State) -> case ets:lookup(?TAB, LoopId) of [{LoopId, WorkerPid, _}] -> @@ -48,12 +47,14 @@ handle_call({unregister, LoopId}, _From, State) -> {LoopId, MonRef} -> erlang:demonitor(MonRef, [flush]), {reply, ok, maps:remove(WorkerPid, State)}; - _ -> {reply, ok, State} + _ -> + {reply, ok, State} end; - [] -> {reply, ok, State} + [] -> + {reply, ok, State} end; - -handle_call(_, _, State) -> {reply, {error, unknown_request}, State}. +handle_call(_, _, State) -> + {reply, {error, unknown_request}, State}. handle_cast(_, State) -> {noreply, State}. @@ -62,9 +63,11 @@ handle_info({'DOWN', MonRef, process, WorkerPid, _Reason}, State) -> {LoopId, MonRef} -> true = ets:delete(?TAB, LoopId), {noreply, maps:remove(WorkerPid, State)}; - _ -> {noreply, State} + _ -> + {noreply, State} end; -handle_info(_, State) -> {noreply, State}. +handle_info(_, State) -> + {noreply, State}. terminate(_, _) -> ok. code_change(_, State, _) -> {ok, State}. diff --git a/src/py_event_worker_sup.erl b/src/py_event_worker_sup.erl index d97509e..cf130f8 100644 --- a/src/py_event_worker_sup.erl +++ b/src/py_event_worker_sup.erl @@ -12,7 +12,8 @@ start_worker(WorkerId, LoopRef) -> {ok, Pid} -> ok = py_event_worker_registry:register(WorkerId, Pid, LoopRef), {ok, Pid}; - {error, _} = Error -> Error + {error, _} = Error -> + Error end. stop_worker(WorkerPid) -> diff --git a/src/py_import.erl b/src/py_import.erl index b470d96..bb972a2 100644 --- a/src/py_import.erl +++ b/src/py_import.erl @@ -185,7 +185,8 @@ is_imported(Module, Func) -> ModuleBin = ensure_binary(Module), FuncBin = ensure_binary(Func), case ets:info(?IMPORT_REGISTRY) of - undefined -> false; + undefined -> + false; _ -> case ets:lookup(?IMPORT_REGISTRY, ModuleBin) of [{_, all}] -> true; @@ -249,17 +250,21 @@ clear_imports() -> import_list() -> Imports = all_imports(), %% Group by module - Map = lists:foldl(fun({Module, FuncOrAll}, Acc) -> - Existing = maps:get(Module, Acc, []), - case FuncOrAll of - all -> - %% Module-level import, don't add to function list - maps:put(Module, Existing, Acc); - Func -> - %% Function-level import - maps:put(Module, [Func | Existing], Acc) - end - end, #{}, Imports), + Map = lists:foldl( + fun({Module, FuncOrAll}, Acc) -> + Existing = maps:get(Module, Acc, []), + case FuncOrAll of + all -> + %% Module-level import, don't add to function list + maps:put(Module, Existing, Acc); + Func -> + %% Function-level import + maps:put(Module, [Func | Existing], Acc) + end + end, + #{}, + Imports + ), {ok, Map}. %%% ============================================================================ @@ -319,7 +324,8 @@ add_paths(Paths) when is_list(Paths) -> -spec all_paths() -> [binary()]. all_paths() -> case ets:info(?PATH_REGISTRY) of - undefined -> []; + undefined -> + []; _ -> %% ordered_set returns in key order (monotonic time = insertion order) [Path || {_Key, Path} <- ets:tab2list(?PATH_REGISTRY)] @@ -347,7 +353,8 @@ clear_paths() -> is_path_added(Path) -> PathBin = ensure_binary(Path), case ets:info(?PATH_REGISTRY) of - undefined -> false; + undefined -> + false; _ -> case ets:match(?PATH_REGISTRY, {'_', PathBin}) of [] -> false; @@ -396,7 +403,8 @@ apply_import_to_interpreters(ModuleBin) -> try Ref = py_context:get_nif_ref(Ctx), py_nif:interp_apply_imports(Ref, Imports) - catch _:_ -> ok + catch + _:_ -> ok end end, get_all_contexts() @@ -404,26 +412,40 @@ apply_import_to_interpreters(ModuleBin) -> %% Apply to main event loop case py_event_loop:get_loop() of {ok, LoopRef} -> - try py_nif:interp_apply_imports(LoopRef, Imports) catch _:_ -> ok end; - _ -> ok + try + py_nif:interp_apply_imports(LoopRef, Imports) + catch + _:_ -> ok + end; + _ -> + ok end, %% Apply to all pool event loops case py_event_loop_pool:get_all_loops() of {ok, Loops} -> lists:foreach( fun({LoopRef, _WorkerPid}) -> - try py_nif:interp_apply_imports(LoopRef, Imports) catch _:_ -> ok end + try + py_nif:interp_apply_imports(LoopRef, Imports) + catch + _:_ -> ok + end end, Loops ); - _ -> ok + _ -> + ok end, %% Apply to all OWN_GIL sessions (if enabled) case py_event_loop_pool:is_owngil_enabled() of true -> lists:foreach( fun({WorkerId, HandleId}) -> - try py_nif:owngil_apply_imports(WorkerId, HandleId, Imports) catch _:_ -> ok end + try + py_nif:owngil_apply_imports(WorkerId, HandleId, Imports) + catch + _:_ -> ok + end end, py_event_loop_pool:get_all_sessions() ); @@ -441,7 +463,8 @@ apply_path_to_interpreters(PathBin) -> try Ref = py_context:get_nif_ref(Ctx), py_nif:interp_apply_paths(Ref, Paths) - catch _:_ -> ok + catch + _:_ -> ok end end, get_all_contexts() @@ -449,26 +472,40 @@ apply_path_to_interpreters(PathBin) -> %% Apply to main event loop case py_event_loop:get_loop() of {ok, LoopRef} -> - try py_nif:interp_apply_paths(LoopRef, Paths) catch _:_ -> ok end; - _ -> ok + try + py_nif:interp_apply_paths(LoopRef, Paths) + catch + _:_ -> ok + end; + _ -> + ok end, %% Apply to all pool event loops case py_event_loop_pool:get_all_loops() of {ok, Loops} -> lists:foreach( fun({LoopRef, _WorkerPid}) -> - try py_nif:interp_apply_paths(LoopRef, Paths) catch _:_ -> ok end + try + py_nif:interp_apply_paths(LoopRef, Paths) + catch + _:_ -> ok + end end, Loops ); - _ -> ok + _ -> + ok end, %% Apply to all OWN_GIL sessions (if enabled) case py_event_loop_pool:is_owngil_enabled() of true -> lists:foreach( fun({WorkerId, HandleId}) -> - try py_nif:owngil_apply_paths(WorkerId, HandleId, Paths) catch _:_ -> ok end + try + py_nif:owngil_apply_paths(WorkerId, HandleId, Paths) + catch + _:_ -> ok + end end, py_event_loop_pool:get_all_sessions() ); @@ -479,6 +516,11 @@ apply_path_to_interpreters(PathBin) -> %% @private Get all context pids from all pools get_all_contexts() -> - DefaultCtxs = try py_context_router:contexts() catch _:_ -> [] end, + DefaultCtxs = + try + py_context_router:contexts() + catch + _:_ -> [] + end, %% Could add other pools here if needed DefaultCtxs. diff --git a/src/py_isolated.erl b/src/py_isolated.erl index b2b0f93..1ade85b 100644 --- a/src/py_isolated.erl +++ b/src/py_isolated.erl @@ -76,8 +76,14 @@ -export([init/4, python_executable/1]). %% gen_statem callbacks --export([callback_mode/0, init/1, handle_event/4, terminate/3, code_change/4, - format_status/1]). +-export([ + callback_mode/0, + init/1, + handle_event/4, + terminate/3, + code_change/4, + format_status/1 +]). -define(REF_TAB, py_context_refs). -define(STATUS_REQUEST, 0). @@ -138,11 +144,18 @@ scratch :: file:filename() | undefined }). --define(IS_MAIN(K), (K =:= call orelse K =:= eval orelse K =:= exec orelse - (is_tuple(K) andalso element(1, K) =:= start_loop))). - --type state() :: idle | {busy, pos_integer()} | looping | stopping_loop - | {restarting, term()} | {exited, term()}. +-define(IS_MAIN(K), + (K =:= call orelse K =:= eval orelse K =:= exec orelse + (is_tuple(K) andalso element(1, K) =:= start_loop)) +). + +-type state() :: + idle + | {busy, pos_integer()} + | looping + | stopping_loop + | {restarting, term()} + | {exited, term()}. -export_type([state/0]). %% ============================================================================ @@ -159,10 +172,13 @@ init(Parent, Id, _Mode, Opts) -> %% the embedded contexts do; only a crash of that process (non-normal %% EXIT, handled below) or a shutdown stops it. Point the parent slot at %% ourselves so gen_statem leaves the creator's exit to us. - put('$ancestors', [self() | case get('$ancestors') of - L when is_list(L) -> L; - _ -> [] - end]), + put('$ancestors', [ + self() + | case get('$ancestors') of + L when is_list(L) -> L; + _ -> [] + end + ]), ets:insert(?REF_TAB, {self(), isolated}), Data0 = #data{id = Id, parent = Parent, opts = Opts}, case start_child(Data0) of @@ -205,12 +221,13 @@ handle_event(enter, _Old, stopping_loop, _Data) -> keep_state_and_data; handle_event(enter, _Old, _State, _Data) -> keep_state_and_data; - %% ---- socket and port ------------------------------------------------------- handle_event(info, {'$socket', S, select, _}, State, #data{child = #child{sock = S}} = Data) -> result(drain_socket(State, Data, [])); -handle_event(info, {'$socket', S, abort, {_, Reason}}, State, #data{child = #child{sock = S}} = Data) -> +handle_event( + info, {'$socket', S, abort, {_, Reason}}, State, #data{child = #child{sock = S}} = Data +) -> result(socket_broken(Reason, State, Data, [])); handle_event(info, {'$socket', _, _, _}, _State, _Data) -> keep_state_and_data; @@ -221,40 +238,52 @@ handle_event(info, {Port, {exit_status, Status}}, State, #data{child = #child{po child_exited(py_child:exit_reason(Status), State, Data); handle_event(info, {Port, _}, _State, _Data) when is_port(Port) -> keep_state_and_data; -handle_event(info, {py_session_exited, OsPid, Code}, State, - #data{child = #child{port = undefined, os_pid = OsPid}} = Data) -> +handle_event( + info, + {py_session_exited, OsPid, Code}, + State, + #data{child = #child{port = undefined, os_pid = OsPid}} = Data +) -> child_exited(py_child:code_reason(Code), State, Data); handle_event(info, {py_session_exited, _, _}, _State, _Data) -> keep_state_and_data; -handle_event(state_timeout, {probe_exit, Waited}, {restarting, _} = State, - #data{child = #child{os_pid = OsPid}, opts = Opts} = Data) -> +handle_event( + state_timeout, + {probe_exit, Waited}, + {restarting, _} = State, + #data{child = #child{os_pid = OsPid}, opts = Opts} = Data +) -> case py_child:os_pid_alive(OsPid) of false -> %% Reaped. Its template reports how it died, a little later %% than the pid disappears when the machine is busy: wait for %% that report unless nobody is left to send it. - ReportExpected = case maps:get(origin, Opts, spawn) of - {fork, T} -> is_process_alive(T) andalso Waited < ?EXIT_REPORT_GRACE_MS; - _ -> false - end, + ReportExpected = + case maps:get(origin, Opts, spawn) of + {fork, T} -> is_process_alive(T) andalso Waited < ?EXIT_REPORT_GRACE_MS; + _ -> false + end, case ReportExpected of true -> - {keep_state_and_data, - [{state_timeout, ?EXIT_PROBE_MS, {probe_exit, Waited + ?EXIT_PROBE_MS}}]}; + {keep_state_and_data, [ + {state_timeout, ?EXIT_PROBE_MS, {probe_exit, Waited + ?EXIT_PROBE_MS}} + ]}; false -> child_exited({signal, 9}, State, Data) end; true when Waited >= ?EXIT_STATUS_WAIT_MS -> handle_event(state_timeout, exit_status, State, Data); true -> - {keep_state_and_data, - [{state_timeout, ?EXIT_PROBE_MS, {probe_exit, Waited + ?EXIT_PROBE_MS}}]} + {keep_state_and_data, [ + {state_timeout, ?EXIT_PROBE_MS, {probe_exit, Waited + ?EXIT_PROBE_MS}} + ]} end; handle_event(state_timeout, exit_status, {restarting, _} = State, #data{child = Child} = Data) -> - logger:error("py_context ~p (isolated): child ~p did not exit after SIGKILL", - [Data#data.id, Child#child.os_pid]), + logger:error( + "py_context ~p (isolated): child ~p did not exit after SIGKILL", + [Data#data.id, Child#child.os_pid] + ), child_exited({signal, 9}, State, Data); - %% ---- requests -------------------------------------------------------------- handle_event(info, {call, From, MRef, Module, Func, Args, Kwargs}, State, Data) -> @@ -272,21 +301,27 @@ handle_event(info, {exec, From, MRef, Code, _EnvRef}, State, Data) -> handle_event(info, {start_loop, From, MRef, Owner}, State, Data) -> request(From, MRef, {start_loop, Owner}, start_loop, State, Data); handle_event(info, {submit, From, MRef, TaskRef, Module, Func, Args, Kwargs}, State, Data) -> - request(From, MRef, {submit, TaskRef}, {submit, TaskRef, Module, Func, Args, Kwargs}, - State, Data); + request( + From, + MRef, + {submit, TaskRef}, + {submit, TaskRef, Module, Func, Args, Kwargs}, + State, + Data + ); handle_event(info, {pass_fd, From, MRef, Fd}, State, Data) -> pass_fd(From, MRef, Fd, State, Data); handle_event(info, {call_method, From, MRef, _ObjRef, _Method, _Args}, _State, _Data) -> From ! {MRef, {error, not_supported_in_isolated}}, keep_state_and_data; - %% ---- introspection --------------------------------------------------------- handle_event(info, {get_interp_id, From, MRef}, _State, #data{child = Child}) -> - Id = case Child of - #child{os_pid = P} -> P; - _ -> 0 - end, + Id = + case Child of + #child{os_pid = P} -> P; + _ -> 0 + end, From ! {MRef, {ok, Id}}, keep_state_and_data; handle_event(info, {is_subinterp, From, MRef}, _State, _Data) -> @@ -304,10 +339,11 @@ handle_event(info, {loop_ref, From, MRef}, _State, _Data) -> From ! {MRef, {error, not_supported_in_isolated}}, keep_state_and_data; handle_event(info, {child_info, From, MRef}, _State, #data{child = Child}) -> - Info = case Child of - #child{os_pid = P, info = I} -> I#{os_pid => P}; - undefined -> #{} - end, + Info = + case Child of + #child{os_pid = P, info = I} -> I#{os_pid => P}; + undefined -> #{} + end, From ! {MRef, {ok, Info}}, keep_state_and_data; handle_event(info, {cancel_ctrl, MRef}, _State, #data{pending = Pending} = Data) -> @@ -315,7 +351,6 @@ handle_event(info, {cancel_ctrl, MRef}, _State, #data{pending = Pending} = Data) %% the late reply is not delivered Drop = [Id || {Id, {_, M, _}} <- maps:to_list(Pending), M =:= MRef], {keep_state, Data#data{pending = maps:without(Drop, Pending)}}; - %% ---- interrupt, kill, stop ------------------------------------------------- handle_event(info, {interrupt, From, MRef}, State, Data) -> @@ -336,14 +371,17 @@ handle_event(info, {interrupt_request, ReqMRef}, State, #data{pending = Pending} [] -> keep_state_and_data end; handle_event({timeout, kill}, Target, State, #data{pending = Pending} = Data) -> - Still = case Target of - loop -> State =:= looping orelse State =:= stopping_loop; - Id -> maps:is_key(Id, Pending) - end, + Still = + case Target of + loop -> State =:= looping orelse State =:= stopping_loop; + Id -> maps:is_key(Id, Pending) + end, case Still andalso Data#data.child =/= undefined of true -> - logger:warning("py_context ~p (isolated): interrupt not honoured, killing child", - [Data#data.id]), + logger:warning( + "py_context ~p (isolated): interrupt not honoured, killing child", + [Data#data.id] + ), kill(killed, State, Data#data{kill_target = undefined}); false -> {keep_state, Data#data{kill_target = undefined}} @@ -360,18 +398,18 @@ handle_event(info, {kill, From, MRef}, State, Data) -> kill(killed, State, Data#data{kill_waiters = [{From, MRef} | Data#data.kill_waiters]}) end; handle_event(info, {stop, From, MRef}, _State, #data{opts = Opts} = Data) -> - How = case maps:get(session, Opts, false) of - %% The zygote (or the VM, for a spawned one) reaps the child: - %% nothing to wait for once it has SIGKILL - true -> kill_nowait; - false -> graceful - end, + How = + case maps:get(session, Opts, false) of + %% The zygote (or the VM, for a spawned one) reaps the child: + %% nothing to wait for once it has SIGKILL + true -> kill_nowait; + false -> graceful + end, Data1 = stop_child(Data, How), %% The scratch directory is removed by terminate/3, right after the %% reply: the caller does not wait for the file system From ! {MRef, ok}, {stop, normal, Data1}; - %% A session started ahead of time by its template is handed to the process %% that asked for it: that process becomes the parent (linked, its crash %% stops the session) and the template lets go. @@ -379,17 +417,18 @@ handle_event(info, {set_parent, From, MRef, NewParent}, _State, #data{parent = O link(NewParent), _ = Old =/= NewParent andalso unlink(Old), %% An EXIT from the old parent may already be queued: forget it - receive {'EXIT', Old, _} -> ok after 0 -> ok end, + receive + {'EXIT', Old, _} -> ok + after 0 -> ok + end, From ! {MRef, ok}, {keep_state, Data#data{parent = NewParent}}; - %% ---- worker loop ----------------------------------------------------------- handle_event(info, {stop_loop, From, MRef, GraceMs}, looping, #data{loop = Loop} = Data) -> _ = send_frame(Data#data.child, 0, ?STATUS_CONTROL, stop_loop), Loop1 = Loop#loop{stop_waiters = [{From, MRef} | Loop#loop.stop_waiters]}, - {next_state, stopping_loop, Data#data{loop = Loop1}, - [{state_timeout, GraceMs, interrupt}]}; + {next_state, stopping_loop, Data#data{loop = Loop1}, [{state_timeout, GraceMs, interrupt}]}; handle_event(info, {stop_loop, From, MRef, _GraceMs}, stopping_loop, #data{loop = Loop} = Data) -> Loop1 = Loop#loop{stop_waiters = [{From, MRef} | Loop#loop.stop_waiters]}, {keep_state, Data#data{loop = Loop1}}; @@ -399,18 +438,24 @@ handle_event(info, {stop_loop, From, MRef, _GraceMs}, _State, _Data) -> handle_event(state_timeout, interrupt, stopping_loop, Data) -> %% Cooperative stop did not land: interrupt, then the kill backstop result(send_interrupt(loop, stopping_loop, Data, [])); -handle_event(info, {'DOWN', Mon, process, _Owner, _Reason}, looping, - #data{loop = #loop{owner_mon = Mon} = Loop} = Data) -> +handle_event( + info, + {'DOWN', Mon, process, _Owner, _Reason}, + looping, + #data{loop = #loop{owner_mon = Mon} = Loop} = Data +) -> %% Owner is gone: nobody will hear the exit, stop the loop _ = send_frame(Data#data.child, 0, ?STATUS_CONTROL, stop_loop), Loop1 = Loop#loop{owner = undefined, owner_mon = undefined}, - {next_state, stopping_loop, Data#data{loop = Loop1}, - [{state_timeout, 5000, interrupt}]}; - + {next_state, stopping_loop, Data#data{loop = Loop1}, [{state_timeout, 5000, interrupt}]}; %% ---- callbacks (child -> Erlang) ------------------------------------------- -handle_event(info, {callback_reply, FrameId, Status, Term}, State, - #data{child = Child} = Data) when Child =/= undefined -> +handle_event( + info, + {callback_reply, FrameId, Status, Term}, + State, + #data{child = Child} = Data +) when Child =/= undefined -> case State of {restarting, _} -> keep_state_and_data; @@ -438,14 +483,16 @@ handle_event(info, {'DOWN', Mon, process, Pid, Reason}, State, #data{callbacks = error -> keep_state_and_data end; - %% ---- exits ----------------------------------------------------------------- -handle_event(info, {'EXIT', Parent, Reason}, _State, #data{parent = Parent}) when Reason =/= normal -> +handle_event(info, {'EXIT', Parent, Reason}, _State, #data{parent = Parent}) when + Reason =/= normal +-> %% Whoever started us is gone: do not leave a child without an owner {stop, Reason}; -handle_event(info, {'EXIT', _Pid, Reason}, _State, _Data) - when Reason =:= shutdown; Reason =:= kill -> +handle_event(info, {'EXIT', _Pid, Reason}, _State, _Data) when + Reason =:= shutdown; Reason =:= kill +-> {stop, Reason}; handle_event(info, {'EXIT', _Pid, {shutdown, _} = Reason}, _State, _Data) -> {stop, Reason}; @@ -455,15 +502,18 @@ handle_event(info, _Other, _State, _Data) -> keep_state_and_data. terminate(Reason, _State, #data{child = Child} = Data) -> - _ = case Child of - undefined -> Data; - _ when Reason =:= normal; Reason =:= shutdown -> - case maps:get(session, Data#data.opts, false) of - true -> stop_child(Data, kill); - false -> stop_child(Data, graceful) - end; - _ -> stop_child(Data, kill) - end, + _ = + case Child of + undefined -> + Data; + _ when Reason =:= normal; Reason =:= shutdown -> + case maps:get(session, Data#data.opts, false) of + true -> stop_child(Data, kill); + false -> stop_child(Data, graceful) + end; + _ -> + stop_child(Data, kill) + end, remove_scratch(Data), ets:delete(?REF_TAB, self()), ok. @@ -510,19 +560,21 @@ check_platform_opts(Opts) -> start_child_1(#data{opts = Opts} = St0) -> St = with_scratch(St0), - ChildOpts = case St#data.scratch of - undefined -> Opts; - Dir -> Opts#{cd => Dir} - end, - Started = case maps:get(origin, Opts, spawn) of - {fork, Template} -> - fork_child(Template, ChildOpts); - spawn -> - case python_executable(Opts) of - {error, _} = NoPython -> NoPython; - Python -> spawn_child(Python, ChildOpts) - end - end, + ChildOpts = + case St#data.scratch of + undefined -> Opts; + Dir -> Opts#{cd => Dir} + end, + Started = + case maps:get(origin, Opts, spawn) of + {fork, Template} -> + fork_child(Template, ChildOpts); + spawn -> + case python_executable(Opts) of + {error, _} = NoPython -> NoPython; + Python -> spawn_child(Python, ChildOpts) + end + end, case Started of {ok, Child} -> handshake(St#data{child = Child}); @@ -559,8 +611,13 @@ fork_child(Template, Opts) -> {ok, S} -> py_child:delete_file(Path), py_child:tune_socket(S), - {ok, #child{port = undefined, os_pid = OsPid, listener = L, - sock = S, sock_path = Path}}; + {ok, #child{ + port = undefined, + os_pid = OsPid, + listener = L, + sock = S, + sock_path = Path + }}; {error, Reason} -> py_child:delete_file(Path), socket:close(L), @@ -583,22 +640,38 @@ spawn_child(Python, Opts) -> try Script = filename:join(py_child:priv_dir(), "py_isolated_child.py"), Args = [Script, Path | py_child:rlimit_args(Opts) ++ py_child:cgroup_args(Opts)], - PortOpts = [exit_status, stderr_to_stdout, binary, use_stdio, - {args, Args}, {env, py_child:port_env(Opts)}] - ++ [{cd, Dir} || Dir <- [maps:get(cd, Opts, undefined)], - Dir =/= undefined], + PortOpts = + [ + exit_status, + stderr_to_stdout, + binary, + use_stdio, + {args, Args}, + {env, py_child:port_env(Opts)} + ] ++ + [ + {cd, Dir} + || Dir <- [maps:get(cd, Opts, undefined)], + Dir =/= undefined + ], Port = open_port({spawn_executable, Python}, PortOpts), - OsPid = case erlang:port_info(Port, os_pid) of - {os_pid, Pid} -> Pid; - _ -> 0 - end, + OsPid = + case erlang:port_info(Port, os_pid) of + {os_pid, Pid} -> Pid; + _ -> 0 + end, Timeout = maps:get(start_timeout, Opts, ?DEFAULT_START_TIMEOUT_MS), case py_child:accept(L, {port, Port}, Timeout) of {ok, S} -> py_child:delete_file(Path), py_child:tune_socket(S), - {ok, #child{port = Port, os_pid = OsPid, listener = L, - sock = S, sock_path = Path}}; + {ok, #child{ + port = Port, + os_pid = OsPid, + listener = L, + sock = S, + sock_path = Path + }}; {error, Reason} -> py_child:delete_file(Path), socket:close(L), @@ -655,10 +728,11 @@ handshake(#data{child = Child, opts = Opts} = St0) -> end. run_preload(#data{opts = Opts} = St, Timeout) -> - Code = case maps:get(preload, Opts, undefined) of - undefined -> py_preload_code(); - C -> [py_preload_code(), <<"\n">>, iolist_to_binary(C)] - end, + Code = + case maps:get(preload, Opts, undefined) of + undefined -> py_preload_code(); + C -> [py_preload_code(), <<"\n">>, iolist_to_binary(C)] + end, case iolist_to_binary(Code) of <<>> -> {ok, St}; @@ -667,8 +741,10 @@ run_preload(#data{opts = Opts} = St, Timeout) -> {{ok, _}, St1} -> {ok, St1}; {{error, Reason}, St1} -> - logger:warning("py_context ~p (isolated): preload failed: ~p", - [St#data.id, Reason]), + logger:warning( + "py_context ~p (isolated): preload failed: ~p", + [St#data.id, Reason] + ), {ok, St1} end end. @@ -719,8 +795,9 @@ sync_wait(#data{child = Child} = St, Id, Timeout) -> ok -> sync_wait(St1, Id, Timeout); {error, Reason} -> {{error, Reason}, St1} end; - {ok, {Id, Status, Term}, Child1} - when Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR -> + {ok, {Id, Status, Term}, Child1} when + Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR + -> {reply_term(Status, Term), St#data{child = Child1}}; {ok, {0, ?STATUS_EVENT, {log, Level, Msg}}, Child1} -> log_event(St, Level, Msg), @@ -755,8 +832,9 @@ recv_frame_sync(#child{buf = Buf} = Child, Timeout) -> %% Every path returns a gen_statem result. Main-thread requests (call, eval, %% exec, start_loop) are served one caller at a time; the rest is handled by %% the child's reader thread and can go in any state that has a child. -request(From, MRef, {start_loop, _}, _Term, State, _Data) - when State =:= looping; State =:= stopping_loop -> +request(From, MRef, {start_loop, _}, _Term, State, _Data) when + State =:= looping; State =:= stopping_loop +-> From ! {MRef, {error, already_running}}, keep_state_and_data; request(From, MRef, Kind, _Term, looping, _Data) when ?IS_MAIN(Kind) -> @@ -769,8 +847,9 @@ request(_From, _MRef, _Kind, _Term, {restarting, _}, _Data) -> {keep_state_and_data, [postpone]}; request(_From, _MRef, Kind, _Term, stopping_loop, _Data) when ?IS_MAIN(Kind) -> {keep_state_and_data, [postpone]}; -request(From, MRef, Kind, Term, {busy, _} = State, #data{cb_pids = CbPids} = Data) - when ?IS_MAIN(Kind) -> +request(From, MRef, Kind, Term, {busy, _} = State, #data{cb_pids = CbPids} = Data) when + ?IS_MAIN(Kind) +-> case maps:is_key(From, CbPids) of true -> %% Nested: a callback of the executing request calls back in @@ -788,7 +867,9 @@ request(From, MRef, Kind, Term, idle, Data) when ?IS_MAIN(Kind) -> request(From, MRef, Kind, Term, State, Data) -> result(dispatch(From, MRef, Kind, Term, State, Data)). -dispatch(From, MRef, Kind, Term, State, #data{child = Child, next_id = Id, pending = Pending} = Data) -> +dispatch( + From, MRef, Kind, Term, State, #data{child = Child, next_id = Id, pending = Pending} = Data +) -> case send_frame(Child, Id, ?STATUS_REQUEST, Term) of ok -> {State, Data#data{next_id = Id + 1, pending = Pending#{Id => {From, MRef, Kind}}}, []}; @@ -802,14 +883,19 @@ pass_fd(From, MRef, _Fd, {exited, Reason}, _Data) -> keep_state_and_data; pass_fd(_From, _MRef, _Fd, {restarting, _}, _Data) -> {keep_state_and_data, [postpone]}; -pass_fd(From, MRef, Fd, _State, #data{child = Child, next_id = Id, pending = Pending} = Data) - when is_integer(Fd), Fd >= 0 -> +pass_fd(From, MRef, Fd, _State, #data{child = Child, next_id = Id, pending = Pending} = Data) when + is_integer(Fd), Fd >= 0 +-> Frame = py_child:frame(Id, ?STATUS_REQUEST, term_to_binary(pass_fd)), - Msg = #{iov => [Frame], - ctrl => [#{level => socket, type => rights, data => <>}]}, + Msg = #{ + iov => [Frame], + ctrl => [#{level => socket, type => rights, data => <>}] + }, case socket:sendmsg(Child#child.sock, Msg) of ok -> - {keep_state, Data#data{next_id = Id + 1, pending = Pending#{Id => {From, MRef, pass_fd}}}}; + {keep_state, Data#data{ + next_id = Id + 1, pending = Pending#{Id => {From, MRef, pass_fd}} + }}; {error, Reason} -> From ! {MRef, {error, {pass_fd_failed, Reason}}}, keep_state_and_data @@ -865,25 +951,28 @@ process_frames(State, #data{child = #child{buf = Buf} = Child} = Data, Actions) socket_broken({malformed_frame, Reason}, State, Data, Actions) end. - -handle_frame({Id, Status, Term}, State, #data{pending = Pending} = Data, Actions) - when Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR -> +handle_frame({Id, Status, Term}, State, #data{pending = Pending} = Data, Actions) when + Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR +-> case maps:take(Id, Pending) of {{From, MRef, Kind}, Rest} -> {Data1, Actions1} = cancel_kill_timer(Id, Data#data{pending = Rest}, Actions), {Next, Data2} = deliver(Kind, From, MRef, reply_term(Status, Term), Data1), %% Only the reply of the request holding the main thread frees %% it; nested replies (callbacks calling back in) do not - State1 = case {Next, State} of - {looping, _} -> looping; - {done, {busy, Id}} -> idle; - _ -> State - end, + State1 = + case {Next, State} of + {looping, _} -> looping; + {done, {busy, Id}} -> idle; + _ -> State + end, {State1, Data2, Actions1}; error -> {State, Data, Actions} end; -handle_frame({Id, ?STATUS_CALLBACK, Term}, State, #data{callbacks = Cbs, cb_pids = CbPids} = Data, Actions) -> +handle_frame( + {Id, ?STATUS_CALLBACK, Term}, State, #data{callbacks = Cbs, cb_pids = CbPids} = Data, Actions +) -> Owner = self(), {Pid, Mon} = spawn_monitor(fun() -> {Status, Reply} = run_callback(Term), @@ -901,10 +990,11 @@ deliver(exec, From, MRef, {ok, _}, Data) -> From ! {MRef, ok}, {done, Data}; deliver({start_loop, Owner}, From, MRef, {ok, _}, Data) -> - Mon = case is_pid(Owner) of - true -> erlang:monitor(process, Owner); - false -> undefined - end, + Mon = + case is_pid(Owner) of + true -> erlang:monitor(process, Owner); + false -> undefined + end, From ! {MRef, ok}, {looping, Data#data{loop = #loop{owner = Owner, owner_mon = Mon}}}; deliver({submit, TaskRef}, From, MRef, {ok, _}, #data{tasks = Tasks} = Data) -> @@ -925,8 +1015,9 @@ on_child_event({async_result, TaskRef, Result}, State, #data{tasks = Tasks} = Da error -> {State, Data, Actions} end; -on_child_event({loop_exit, Result}, State, Data, Actions) - when State =:= looping; State =:= stopping_loop -> +on_child_event({loop_exit, Result}, State, Data, Actions) when + State =:= looping; State =:= stopping_loop +-> {Data1, Actions1} = cancel_kill_timer(loop, Data, Actions), {idle, loop_exited(Result, Data1), Actions1}; on_child_event({memory_limit, Rss}, State, Data, Actions) -> @@ -946,11 +1037,12 @@ reply_term(?STATUS_ERROR, Term) -> {error, Term}. %% --------------------------------------------------------------------------- run_callback({call, Name, Args}) -> - ArgsList = case Args of - L when is_list(L) -> L; - T when is_tuple(T) -> tuple_to_list(T); - _ -> [Args] - end, + ArgsList = + case Args of + L when is_list(L) -> L; + T when is_tuple(T) -> tuple_to_list(T); + _ -> [Args] + end, try py_callback:execute(py_child:to_bin(Name), ArgsList) of {ok, Result} -> {?STATUS_OK, Result}; @@ -964,17 +1056,22 @@ run_callback({call, Name, Args}) -> end; run_callback({send, Pid, Msg}) when is_pid(Pid) -> case node(Pid) =:= node() andalso not is_process_alive(Pid) of - true -> {?STATUS_ERROR, {noproc, Pid}}; - false -> Pid ! Msg, {?STATUS_OK, ok} + true -> + {?STATUS_ERROR, {noproc, Pid}}; + false -> + Pid ! Msg, + {?STATUS_OK, ok} end; run_callback({send, Other, _}) -> {?STATUS_ERROR, {badarg, Other}}; run_callback({whereis, Name}) -> try - Atom = if is_atom(Name) -> Name; - is_binary(Name) -> binary_to_existing_atom(Name, utf8); - is_list(Name) -> list_to_existing_atom(Name) - end, + Atom = + if + is_atom(Name) -> Name; + is_binary(Name) -> binary_to_existing_atom(Name, utf8); + is_list(Name) -> list_to_existing_atom(Name) + end, case erlang:whereis(Atom) of undefined -> {?STATUS_OK, none}; Pid -> {?STATUS_OK, Pid} @@ -985,7 +1082,6 @@ run_callback({whereis, Name}) -> run_callback(Other) -> {?STATUS_ERROR, {unknown_request, Other}}. - %% ============================================================================ %% Interrupt / kill %% ============================================================================ @@ -993,11 +1089,14 @@ run_callback(Other) -> %% What an interrupt targets: the innermost main-thread request the child %% is executing (nested requests are dispatched while the outer waits), or %% the loop. -executing_request(looping, _Data) -> loop; -executing_request(stopping_loop, _Data) -> loop; +executing_request(looping, _Data) -> + loop; +executing_request(stopping_loop, _Data) -> + loop; executing_request({busy, _}, #data{pending = Pending}) -> lists:max([Id || {Id, {_, _, Kind}} <- maps:to_list(Pending), ?IS_MAIN(Kind)]); -executing_request(_State, _Data) -> undefined. +executing_request(_State, _Data) -> + undefined. %% The child signals only if Target is what it is executing, so an %% interrupt for a request that just completed cannot hit its successor. @@ -1006,8 +1105,7 @@ send_interrupt(Target, State, #data{opts = Opts} = Data, Actions) -> case send_frame(Data#data.child, 0, ?STATUS_CONTROL, {interrupt, Target}) of ok -> After = maps:get(kill_after, Opts, ?DEFAULT_KILL_AFTER_MS), - {State, Data#data{kill_target = Target}, - [{{timeout, kill}, After, Target} | Actions]}; + {State, Data#data{kill_target = Target}, [{{timeout, kill}, After, Target} | Actions]}; {error, Reason} -> socket_broken(Reason, State, Data, Actions) end. @@ -1034,7 +1132,6 @@ kill_port(Port, OsPid) -> false -> ok end. - %% ============================================================================ %% Failure handling and restart %% ============================================================================ @@ -1045,8 +1142,10 @@ kill_port(Port, OsPid) -> socket_broken(_Reason, {restarting, _} = State, Data, Actions) -> {State, Data, Actions}; socket_broken(Reason, State, #data{child = #child{port = Port, os_pid = OsPid}} = Data, Actions) -> - logger:debug("py_context ~p (isolated): socket to child ~p broken: ~p", - [Data#data.id, OsPid, Reason]), + logger:debug( + "py_context ~p (isolated): socket to child ~p broken: ~p", + [Data#data.id, OsPid, Reason] + ), kill_port(Port, OsPid), enter_restarting({child_exited, {socket, Reason}}, State, Data, Actions). @@ -1054,31 +1153,39 @@ enter_restarting(_Reason, {restarting, _} = State, Data, Actions) -> {State, Data, Actions}; enter_restarting(Reason, _State, Data, Actions) -> %% Timers of the old child are meaningless now - {{restarting, Reason}, Data#data{kill_target = undefined}, - [{{timeout, kill}, cancel} | Actions]}. + {{restarting, Reason}, Data#data{kill_target = undefined}, [{{timeout, kill}, cancel} | Actions]}. %% The port reported the child's exit: fail what was in flight, then %% restart within the budget or stop. child_exited(Reason, State, #data{child = Child, opts = Opts} = Data0) -> close_child(Child), - FailReason = case {State, Reason} of - {{restarting, killed}, _} -> killed; - %% The memory watchdog announced the exit; our SIGKILL may win the race - {{restarting, {child_exited, {socket, {memory_limit, _} = Mem}}}, _} -> {child_exited, Mem}; - %% We killed it because the socket broke: report the socket, unless - %% the child was already dying of something more telling - {{restarting, {child_exited, {socket, _}} = SockReason}, {signal, 9}} -> SockReason; - {{restarting, {child_exited, {socket, _}}}, _} -> {child_exited, Reason}; - {{restarting, Other}, _} -> Other; - {_, _} -> {child_exited, Reason} - end, + FailReason = + case {State, Reason} of + {{restarting, killed}, _} -> + killed; + %% The memory watchdog announced the exit; our SIGKILL may win the race + {{restarting, {child_exited, {socket, {memory_limit, _} = Mem}}}, _} -> + {child_exited, Mem}; + %% We killed it because the socket broke: report the socket, unless + %% the child was already dying of something more telling + {{restarting, {child_exited, {socket, _}} = SockReason}, {signal, 9}} -> + SockReason; + {{restarting, {child_exited, {socket, _}}}, _} -> + {child_exited, Reason}; + {{restarting, Other}, _} -> + Other; + {_, _} -> + {child_exited, Reason} + end, Data1 = fail_pending(FailReason, Data0#data{child = undefined, kill_target = undefined}), case FailReason of killed -> logger:info("py_context ~p (isolated): child killed", [Data0#data.id]); _ -> - logger:warning("py_context ~p (isolated): child exited: ~p", - [Data0#data.id, FailReason]) + logger:warning( + "py_context ~p (isolated): child exited: ~p", + [Data0#data.id, FailReason] + ) end, case maps:get(session, Opts, false) of true -> @@ -1096,12 +1203,16 @@ restart_or_stop(Reason, Data0, #data{opts = Opts} = Data1) -> Data2 = Data1#data{restarts = [Now | Data1#data.restarts]}, case start_child(Data2) of {ok, Data3} -> - logger:info("py_context ~p (isolated): child restarted (pid ~p)", - [Data0#data.id, (Data3#data.child)#child.os_pid]), + logger:info( + "py_context ~p (isolated): child restarted (pid ~p)", + [Data0#data.id, (Data3#data.child)#child.os_pid] + ), result(drain_socket(idle, Data3, [{{timeout, kill}, cancel}])); {error, RestartError} -> - logger:error("py_context ~p (isolated): restart failed: ~p", - [Data0#data.id, RestartError]), + logger:error( + "py_context ~p (isolated): restart failed: ~p", + [Data0#data.id, RestartError] + ), {stop, {child_restart_failed, RestartError}, Data1} end; false -> @@ -1112,16 +1223,23 @@ restart_or_stop(Reason, Data0, #data{opts = Opts} = Data1) -> %% Postponed requests are untouched: they are served by the next child, or %% their callers get a DOWN if the process stops. fail_pending(Reason, #data{pending = Pending, tasks = Tasks} = Data) -> - maps:foreach(fun(_, {From, MRef, _Kind}) -> - From ! {MRef, {error, Reason}} - end, Pending), - maps:foreach(fun(TaskRef, Pid) -> - Pid ! {async_result, TaskRef, {error, Reason}} - end, Tasks), - Data1 = case Data#data.loop of - undefined -> Data; - _ -> loop_exited({error, Reason}, Data) - end, + maps:foreach( + fun(_, {From, MRef, _Kind}) -> + From ! {MRef, {error, Reason}} + end, + Pending + ), + maps:foreach( + fun(TaskRef, Pid) -> + Pid ! {async_result, TaskRef, {error, Reason}} + end, + Tasks + ), + Data1 = + case Data#data.loop of + undefined -> Data; + _ -> loop_exited({error, Reason}, Data) + end, Data1#data{pending = #{}, tasks = #{}}. restart_allowed(#data{restarts = Restarts, opts = Opts}) -> @@ -1131,7 +1249,6 @@ restart_allowed(#data{restarts = Restarts, opts = Opts}) -> Recent = [T || T <- Restarts, Now - T =< Period], length(Recent) < Max. - %% Graceful: ask the child to exit, wait briefly, then SIGKILL. stop_child(#data{child = undefined} = Data, _How) -> Data; @@ -1140,8 +1257,11 @@ stop_child(#data{child = #child{port = Port, os_pid = OsPid} = Child} = Data, Ho graceful -> _ = send_frame(Child, 0, ?STATUS_REQUEST, shutdown), case wait_exit(Child, ?SHUTDOWN_GRACE_MS) of - ok -> ok; - timeout -> kill_port(Port, OsPid), wait_exit(Child, 2000) + ok -> + ok; + timeout -> + kill_port(Port, OsPid), + wait_exit(Child, 2000) end; kill_nowait -> kill_port(Port, OsPid); @@ -1183,16 +1303,27 @@ close_child(#child{port = Port, sock = S, listener = L}) -> close_port(undefined) -> ok; close_port(Port) -> - try port_close(Port) catch error:badarg -> ok end, + try + port_close(Port) + catch + error:badarg -> ok + end, ok. - %% --------------------------------------------------------------------------- %% Worker loop helpers %% --------------------------------------------------------------------------- -loop_exited(Result, #data{loop = #loop{owner = Owner, owner_mon = Mon, - stop_waiters = Waiters}} = Data) -> +loop_exited( + Result, + #data{ + loop = #loop{ + owner = Owner, + owner_mon = Mon, + stop_waiters = Waiters + } + } = Data +) -> case Mon of undefined -> ok; _ -> erlang:demonitor(Mon, [flush]) @@ -1219,7 +1350,11 @@ log_output(#data{id = Id, child = #child{os_pid = OsPid}}, Data) -> ok. log_event(#data{id = Id}, Level, Msg) -> - Lvl = case Level of - error -> error; warning -> warning; debug -> debug; _ -> info - end, + Lvl = + case Level of + error -> error; + warning -> warning; + debug -> debug; + _ -> info + end, logger:log(Lvl, "py_context ~p (isolated): ~s", [Id, Msg]). diff --git a/src/py_logger.erl b/src/py_logger.erl index 9411497..fe2ae13 100644 --- a/src/py_logger.erl +++ b/src/py_logger.erl @@ -89,7 +89,6 @@ handle_info({py_log, Level, Logger, Message, Meta, _Ts}, State) -> py_meta => Meta }), {noreply, State}; - handle_info(_Msg, State) -> {noreply, State}. diff --git a/src/py_nif.erl b/src/py_nif.erl index 1069b47..9a8a3dc 100644 --- a/src/py_nif.erl +++ b/src/py_nif.erl @@ -222,18 +222,19 @@ %%% ============================================================================ load_nif() -> - PrivDir = case code:priv_dir(erlang_python) of - {error, bad_name} -> - %% Fallback for development - case code:which(?MODULE) of - Filename when is_list(Filename) -> - filename:join([filename:dirname(Filename), "..", "priv"]); - _ -> - "priv" - end; - Dir -> - Dir - end, + PrivDir = + case code:priv_dir(erlang_python) of + {error, bad_name} -> + %% Fallback for development + case code:which(?MODULE) of + Filename when is_list(Filename) -> + filename:join([filename:dirname(Filename), "..", "priv"]); + _ -> + "priv" + end; + Dir -> + Dir + end, NifPath = filename:join(PrivDir, "py_nif"), erlang:load_nif(NifPath, 0). @@ -398,8 +399,15 @@ owngil_create_session(_WorkerHint) -> %% Args: WorkerId, HandleId, CallerPid, Ref, Module, Func, Args %% The task runs in the worker's asyncio event loop. %% Result is sent to CallerPid as {async_result, Ref, Result}. --spec owngil_submit_task(non_neg_integer(), non_neg_integer(), pid(), reference(), - binary(), binary(), list()) -> ok | {error, term()}. +-spec owngil_submit_task( + non_neg_integer(), + non_neg_integer(), + pid(), + reference(), + binary(), + binary(), + list() +) -> ok | {error, term()}. owngil_submit_task(_WorkerId, _HandleId, _CallerPid, _Ref, _Module, _Func, _Args) -> ?NIF_STUB. @@ -411,7 +419,8 @@ owngil_destroy_session(_WorkerId, _HandleId) -> %% @doc Apply imports to an OWN_GIL session. %% Imports modules into the worker's sys.modules. --spec owngil_apply_imports(non_neg_integer(), non_neg_integer(), [{binary(), binary() | all}]) -> ok | {error, term()}. +-spec owngil_apply_imports(non_neg_integer(), non_neg_integer(), [{binary(), binary() | all}]) -> + ok | {error, term()}. owngil_apply_imports(_WorkerId, _HandleId, _Imports) -> ?NIF_STUB. @@ -610,7 +619,9 @@ submit_task(_LoopRef, _CallerPid, _Ref, _Module, _Func, _Args, _Kwargs) -> %% Like submit_task but includes an env resource reference. The env's globals %% dict is used for function lookup, allowing functions defined via py:exec() %% to be called from the event loop. --spec submit_task_with_env(reference(), pid(), reference(), binary(), binary(), list(), map(), reference()) -> +-spec submit_task_with_env( + reference(), pid(), reference(), binary(), binary(), list(), map(), reference() +) -> ok | {error, term()}. submit_task_with_env(_LoopRef, _CallerPid, _Ref, _Module, _Func, _Args, _Kwargs, _EnvRef) -> ?NIF_STUB. @@ -896,7 +907,8 @@ create_test_udp_socket(_Port) -> %% @doc Receive data from a UDP socket. %% Returns the data and source address: {Data, {Host, Port}}. --spec recvfrom_test_udp(integer(), integer()) -> {ok, {binary(), {binary(), integer()}}} | {error, term()}. +-spec recvfrom_test_udp(integer(), integer()) -> + {ok, {binary(), {binary(), integer()}}} | {error, term()}. recvfrom_test_udp(_Fd, _MaxSize) -> ?NIF_STUB. @@ -1028,9 +1040,10 @@ context_memory_usage(_ContextRef) -> %% @param Kwargs Map of keyword arguments %% @returns {ok, Result} | {error, Reason} | {suspended, ...} | {schedule, ...} -spec context_call(reference(), binary(), binary(), list(), map()) -> - {ok, term()} | {error, term()} | - {suspended, non_neg_integer(), reference(), {atom(), list()}} | - {schedule, binary(), tuple()}. + {ok, term()} + | {error, term()} + | {suspended, non_neg_integer(), reference(), {atom(), list()}} + | {schedule, binary(), tuple()}. context_call(_ContextRef, _Module, _Func, _Args, _Kwargs) -> ?NIF_STUB. @@ -1044,9 +1057,10 @@ context_call(_ContextRef, _Module, _Func, _Args, _Kwargs) -> %% @param EnvRef Process-local environment reference %% @returns {ok, Result} | {error, Reason} | {suspended, ...} | {schedule, ...} -spec context_call(reference(), binary(), binary(), list(), map(), reference()) -> - {ok, term()} | {error, term()} | - {suspended, non_neg_integer(), reference(), {atom(), list()}} | - {schedule, binary(), tuple()}. + {ok, term()} + | {error, term()} + | {suspended, non_neg_integer(), reference(), {atom(), list()}} + | {schedule, binary(), tuple()}. context_call(_ContextRef, _Module, _Func, _Args, _Kwargs, _EnvRef) -> ?NIF_STUB. @@ -1059,9 +1073,10 @@ context_call(_ContextRef, _Module, _Func, _Args, _Kwargs, _EnvRef) -> %% @param Locals Map of local variables %% @returns {ok, Result} | {error, Reason} | {suspended, ...} | {schedule, ...} -spec context_eval(reference(), binary(), map()) -> - {ok, term()} | {error, term()} | - {suspended, non_neg_integer(), reference(), {atom(), list()}} | - {schedule, binary(), tuple()}. + {ok, term()} + | {error, term()} + | {suspended, non_neg_integer(), reference(), {atom(), list()}} + | {schedule, binary(), tuple()}. context_eval(_ContextRef, _Code, _Locals) -> ?NIF_STUB. @@ -1073,9 +1088,10 @@ context_eval(_ContextRef, _Code, _Locals) -> %% @param EnvRef Process-local environment reference %% @returns {ok, Result} | {error, Reason} | {suspended, ...} | {schedule, ...} -spec context_eval(reference(), binary(), map(), reference()) -> - {ok, term()} | {error, term()} | - {suspended, non_neg_integer(), reference(), {atom(), list()}} | - {schedule, binary(), tuple()}. + {ok, term()} + | {error, term()} + | {suspended, non_neg_integer(), reference(), {atom(), list()}} + | {schedule, binary(), tuple()}. context_eval(_ContextRef, _Code, _Locals, _EnvRef) -> ?NIF_STUB. @@ -1154,30 +1170,67 @@ context_exec_async(_ContextRef, _CallerPid, _RequestId, _Code) -> %% @doc Async call with process-local environment. %% @private --spec context_call_with_env_async(reference(), pid(), term(), - binary(), binary(), list(), map(), - reference()) -> +-spec context_call_with_env_async( + reference(), + pid(), + term(), + binary(), + binary(), + list(), + map(), + reference() +) -> {enqueued, term()} | {error, term()}. -context_call_with_env_async(_CtxRef, _CallerPid, _RequestId, - _Module, _Func, _Args, _Kwargs, _EnvRef) -> +context_call_with_env_async( + _CtxRef, + _CallerPid, + _RequestId, + _Module, + _Func, + _Args, + _Kwargs, + _EnvRef +) -> ?NIF_STUB. %% @doc Async eval with process-local environment. %% @private --spec context_eval_with_env_async(reference(), pid(), term(), - binary(), map(), reference()) -> +-spec context_eval_with_env_async( + reference(), + pid(), + term(), + binary(), + map(), + reference() +) -> {enqueued, term()} | {error, term()}. -context_eval_with_env_async(_CtxRef, _CallerPid, _RequestId, - _Code, _Locals, _EnvRef) -> +context_eval_with_env_async( + _CtxRef, + _CallerPid, + _RequestId, + _Code, + _Locals, + _EnvRef +) -> ?NIF_STUB. %% @doc Async exec with process-local environment. %% @private --spec context_exec_with_env_async(reference(), pid(), term(), - binary(), reference()) -> +-spec context_exec_with_env_async( + reference(), + pid(), + term(), + binary(), + reference() +) -> {enqueued, term()} | {error, term()}. -context_exec_with_env_async(_CtxRef, _CallerPid, _RequestId, - _Code, _EnvRef) -> +context_exec_with_env_async( + _CtxRef, + _CallerPid, + _RequestId, + _Code, + _EnvRef +) -> ?NIF_STUB. %% @doc Call a method on a Python object in a context. @@ -1280,8 +1333,10 @@ context_write_callback_response(_ContextRef, _Data) -> %% returns {error, not_supported_in_thread_model}. Thread-model contexts use %% blocking pipe-based callbacks instead of suspension/resume. -spec context_resume(reference(), reference(), binary()) -> - {ok, term()} | {error, term()} | {error, not_supported_in_thread_model} | - {suspended, non_neg_integer(), reference(), {binary(), tuple()}}. + {ok, term()} + | {error, term()} + | {error, not_supported_in_thread_model} + | {suspended, non_neg_integer(), reference(), {binary(), tuple()}}. context_resume(_ContextRef, _StateRef, _Result) -> ?NIF_STUB. diff --git a/src/py_reactor_context.erl b/src/py_reactor_context.erl index 52fe763..e088d85 100644 --- a/src/py_reactor_context.erl +++ b/src/py_reactor_context.erl @@ -196,25 +196,32 @@ init(Parent, Id, Mode, Opts) -> %% Execute setup code if specified (e.g., set protocol factory) SetupCode = maps:get(setup_code, Opts, undefined), case SetupCode of - undefined -> ok; + undefined -> + ok; _ when is_binary(SetupCode) -> case py_nif:context_exec(Ref, SetupCode) of - ok -> ok; + ok -> + ok; {error, Reason} -> error_logger:error_msg( - "py_reactor_context setup_code failed: ~p~n", [Reason]) + "py_reactor_context setup_code failed: ~p~n", [Reason] + ) end end, %% Initialize app in Python context if specified case AppModule of - undefined -> ok; + undefined -> + ok; _ -> Code = io_lib:format( "import sys; sys.path.insert(0, '.'); " "from ~s import ~s as _reactor_app", - [binary_to_list(AppModule), - binary_to_list(AppCallable)]), + [ + binary_to_list(AppModule), + binary_to_list(AppCallable) + ] + ), py_nif:context_exec(Ref, iolist_to_binary(Code)) end, @@ -232,7 +239,6 @@ init(Parent, Id, Mode, Opts) -> Parent ! {self(), started}, loop(State); - {error, Reason} -> Parent ! {self(), {error, Reason}} end. @@ -243,28 +249,22 @@ loop(State) -> %% FD handoff from acceptor {fd_handoff, Fd, ClientInfo} -> handle_fd_handoff(Fd, ClientInfo, State); - %% Select events from BEAM scheduler {select, FdRes, _Ref, ready_input} -> handle_read_ready(FdRes, State); - {select, FdRes, _Ref, ready_output} -> handle_write_ready(FdRes, State); - %% Async completion signal from Python %% Sent when an async task (e.g., ASGI app) completes and response is ready %% Accept both atom and binary forms since Python sends binaries {write_ready, Fd} -> handle_async_write_ready(Fd, State); - {<<"write_ready">>, Fd} -> handle_async_write_ready(Fd, State); - %% Control messages {stop, From, MRef} -> cleanup(State), From ! {MRef, ok}; - {stats, From, MRef} -> Stats = #{ id => State#state.id, @@ -275,12 +275,10 @@ loop(State) -> }, From ! {MRef, Stats}, loop(State); - %% Handle EXIT signals {'EXIT', _Pid, Reason} -> cleanup(State), exit(Reason); - _Other -> loop(State) end. @@ -303,7 +301,6 @@ handle_fd_handoff(Fd, ClientInfo, State) -> %% Close the FD directly (it's just an integer here) %% The acceptor will close the socket loop(State); - false -> %% Duplicate the fd before registering to avoid conflicts with %% the tcp_inet driver on platforms like FreeBSD where kqueue @@ -347,13 +344,11 @@ register_fd(Fd, ClientInfo, State) -> total_connections = TotalConns + 1 }, loop(NewState); - {error, _Reason} -> %% Failed to init connection, close py_nif:reactor_close_fd(Ref, FdRef), loop(State) end; - {error, _Reason} -> %% Failed to register FD loop(State) @@ -376,7 +371,6 @@ handle_read_ready(FdRes, State) -> %% More data expected, re-register for read py_nif:reactor_reselect_read(FdRes), loop(State); - {ok, Action} when Action =:= <<"write_pending">>; Action =:= write_pending -> %% Response ready, switch to write mode py_nif:reactor_select_write(FdRes), @@ -384,7 +378,6 @@ handle_read_ready(FdRes, State) -> total_requests = State#state.total_requests + 1 }, loop(NewState); - {ok, Action} when Action =:= <<"async_pending">>; Action =:= async_pending -> %% Async task submitted (e.g., ASGI app running as task) %% Don't reselect - wait for {write_ready, Fd} signal from Python @@ -393,16 +386,13 @@ handle_read_ready(FdRes, State) -> total_requests = State#state.total_requests + 1 }, loop(NewState); - {ok, Action} when Action =:= <<"close">>; Action =:= close -> %% Close connection close_connection(Fd, FdRes, State); - {error, _Reason} -> %% Error, close connection close_connection(Fd, FdRes, State) end; - {error, _} -> %% FD resource invalid loop(State) @@ -425,21 +415,17 @@ handle_write_ready(FdRes, State) -> %% More data to write, re-register for write py_nif:reactor_select_write(FdRes), loop(State); - {ok, Action} when Action =:= <<"read_pending">>; Action =:= read_pending -> %% Keep-alive, switch back to read mode py_nif:reactor_reselect_read(FdRes), loop(State); - {ok, Action} when Action =:= <<"close">>; Action =:= close -> %% Close connection close_connection(Fd, FdRes, State); - {error, _Reason} -> %% Error, close connection close_connection(Fd, FdRes, State) end; - {error, _} -> %% FD resource invalid loop(State) @@ -495,9 +481,12 @@ cleanup(State) -> #state{ref = Ref, connections = Conns} = State, %% Close all connections - maps:foreach(fun(_Fd, #{fd_ref := FdRef}) -> - py_nif:reactor_close_fd(Ref, FdRef) - end, Conns), + maps:foreach( + fun(_Fd, #{fd_ref := FdRef}) -> + py_nif:reactor_close_fd(Ref, FdRef) + end, + Conns + ), %% Destroy Python context py_nif:context_destroy(Ref), diff --git a/src/py_reimport_session.erl b/src/py_reimport_session.erl index e07e998..fc55bf3 100644 --- a/src/py_reimport_session.erl +++ b/src/py_reimport_session.erl @@ -86,17 +86,25 @@ init_it(Parent, Template, Ctx, Passthrough, Mode) -> process_flag(trap_exit, true), %% Outlive a creator that exits normally, as other contexts do; its %% crash stops the session (EXIT clause below) - put('$ancestors', [self() | case get('$ancestors') of - L when is_list(L) -> L; - _ -> [] - end]), + put('$ancestors', [ + self() + | case get('$ancestors') of + L when is_list(L) -> L; + _ -> [] + end + ]), Sid = erlang:unique_integer([positive]), case py_context:call(Ctx, ?IMPL, session_open, [Sid, Passthrough]) of {ok, true} -> ets:insert(?REF_TAB, {self(), reimport_session}), Template ! {register_session, self(), Ctx, Sid}, - St = #st{ctx = Ctx, ctx_mon = erlang:monitor(process, Ctx), sid = Sid, - mode = Mode, parent = Parent}, + St = #st{ + ctx = Ctx, + ctx_mon = erlang:monitor(process, Ctx), + sid = Sid, + mode = Mode, + parent = Parent + }, Parent ! {self(), started}, gen_server:enter_loop(?MODULE, [], St); {error, Reason} -> @@ -131,7 +139,6 @@ handle_info({Tag, Reply}, #st{pending = Pending} = St) when is_map_key(Tag, Pend {{From, MRef, Kind}, Rest} = maps:take(Tag, Pending), From ! {MRef, reply(Kind, Reply)}, {noreply, St#st{pending = Rest}}; - %% ---- introspection --------------------------------------------------------- handle_info({get_interp_id, From, MRef}, #st{sid = Sid} = St) -> @@ -148,7 +155,6 @@ handle_info({create_local_env, From, MRef}, St) -> handle_info({child_info, From, MRef}, #st{ctx = Ctx, sid = Sid, mode = Mode} = St) -> From ! {MRef, {ok, #{context => Ctx, session => Sid, mode => Mode}}}, {noreply, St}; - %% ---- controls -------------------------------------------------------------- handle_info({interrupt, From, MRef}, #st{exited = undefined, ctx = Ctx} = St) -> @@ -166,8 +172,9 @@ handle_info({interrupt_request, ReqMRef}, #st{pending = Pending} = St) -> handle_info({kill, From, MRef}, St) -> From ! {MRef, {error, not_supported}}, {noreply, St}; -handle_info({Op, From, MRef, _}, St) - when Op =:= pass_fd; Op =:= start_loop -> +handle_info({Op, From, MRef, _}, St) when + Op =:= pass_fd; Op =:= start_loop +-> From ! {MRef, {error, not_supported_in_reimport}}, {noreply, St}; handle_info({stop_loop, From, MRef, _GraceMs}, St) -> @@ -184,7 +191,6 @@ handle_info({submit, From, MRef, _TaskRef, _M, _F, _A, _K}, St) -> {noreply, St}; handle_info({cancel_ctrl, _MRef}, St) -> {noreply, St}; - %% ---- lifecycle ------------------------------------------------------------- handle_info({stop, From, MRef}, St) -> @@ -199,15 +205,20 @@ handle_info({'DOWN', Mon, process, _Ctx, Reason}, #st{ctx_mon = Mon, pending = P {noreply, St#st{exited = Exited, pending = #{}}}; handle_info({'EXIT', Parent, Reason}, #st{parent = Parent} = St) when Reason =/= normal -> {stop, Reason, St}; -handle_info({'EXIT', _Pid, Reason}, St) - when Reason =:= shutdown; Reason =:= kill -> +handle_info({'EXIT', _Pid, Reason}, St) when + Reason =:= shutdown; Reason =:= kill +-> {stop, Reason, St}; handle_info(_Other, St) -> {noreply, St}. terminate(_Reason, St) -> close_session(St), - try ets:delete(?REF_TAB, self()) catch error:badarg -> ok end, + try + ets:delete(?REF_TAB, self()) + catch + error:badarg -> ok + end, ok. %% ============================================================================ @@ -222,7 +233,11 @@ forward(From, MRef, Fun, Args, #st{ctx = Ctx, sid = Sid, pending = Pending} = St %% wait for it Tag = make_ref(), Ctx ! {call, self(), Tag, ?IMPL, atom_to_binary(Fun), [Sid | Args], #{}}, - Kind = case Fun of session_exec -> exec; _ -> call end, + Kind = + case Fun of + session_exec -> exec; + _ -> call + end, {noreply, St#st{pending = Pending#{Tag => {From, MRef, Kind}}}}. %% py_context:exec/2 returns ok, not {ok, _} diff --git a/src/py_semaphore.erl b/src/py_semaphore.erl index c61c366..4e92118 100644 --- a/src/py_semaphore.erl +++ b/src/py_semaphore.erl @@ -76,7 +76,8 @@ acquire(Timeout) when is_integer(Timeout), Timeout > 0 -> StartTime = erlang:monotonic_time(millisecond), acquire_loop(Timeout, StartTime, ?BACKOFF_MS); acquire(_) -> - acquire(30000). % Default 30s timeout + % Default 30s timeout + acquire(30000). %% @doc Release a slot in the semaphore. %% Must be called after acquire/1 completes, typically in an after clause. diff --git a/src/py_session.erl b/src/py_session.erl index c37b8b2..78d421e 100644 --- a/src/py_session.erl +++ b/src/py_session.erl @@ -56,15 +56,17 @@ %%% -module(py_session). --export([template/1, - stop_template/1, - new/1, - new/2, - close/1, - run/4, - run/5, - refresh/1, - info/1]). +-export([ + template/1, + stop_template/1, + new/1, + new/2, + close/1, + run/4, + run/5, + refresh/1, + info/1 +]). -type template() :: pid(). -type session() :: pid(). @@ -109,8 +111,12 @@ new(T, Opts) -> {reimport, Ctx, Passthrough} -> %% A session over several calls: its own module dictionary in %% that context, behind a process that answers like a context - py_reimport_session:start_link(T, Ctx, Passthrough, - py_session_template:mode(T)); + py_reimport_session:start_link( + T, + Ctx, + Passthrough, + py_session_template:mode(T) + ); {error, _} = Err -> Err end. @@ -133,10 +139,20 @@ run(T, Module, Func, Args) -> run(T, Module, Func, Args, Opts) -> case py_session_template:checkout(T, maps:get(timeout, Opts, 15000)) of {reimport, Ctx, Passthrough} -> - py_context:call(Ctx, '_erlang_impl._reimport', run, - [Passthrough, py_child:to_bin(Module), py_child:to_bin(Func), - Args, maps:get(kwargs, Opts, #{})], - #{}, maps:get(timeout, Opts, infinity)); + py_context:call( + Ctx, + '_erlang_impl._reimport', + run, + [ + Passthrough, + py_child:to_bin(Module), + py_child:to_bin(Func), + Args, + maps:get(kwargs, Opts, #{}) + ], + #{}, + maps:get(timeout, Opts, infinity) + ); {ok, Ctx} -> %% taken from the warm pool, handed over as new/2 does run_in(T, Ctx, Module, Func, Args, Opts); @@ -151,8 +167,14 @@ run_in(T, Ctx, Module, Func, Args, Opts) -> {MRef, ok} -> erlang:demonitor(MRef, [flush]), try - py_context:call(Ctx, Module, Func, Args, maps:get(kwargs, Opts, #{}), - maps:get(timeout, Opts, infinity)) + py_context:call( + Ctx, + Module, + Func, + Args, + maps:get(kwargs, Opts, #{}), + maps:get(timeout, Opts, infinity) + ) after close(Ctx) end; @@ -164,8 +186,14 @@ run_new(T, Module, Func, Args, Opts) -> case new(T, Opts) of {ok, S} -> try - py_context:call(S, Module, Func, Args, maps:get(kwargs, Opts, #{}), - maps:get(timeout, Opts, infinity)) + py_context:call( + S, + Module, + Func, + Args, + maps:get(kwargs, Opts, #{}), + maps:get(timeout, Opts, infinity) + ) after close(S) end; diff --git a/src/py_session_template.erl b/src/py_session_template.erl index f374b55..f883ae8 100644 --- a/src/py_session_template.erl +++ b/src/py_session_template.erl @@ -40,12 +40,14 @@ -behaviour(gen_server). --export([start_link/1, - fork/4, - checkout/2, - refresh/1, - info/1, - mode/1]). +-export([ + start_link/1, + fork/4, + checkout/2, + refresh/1, + info/1, + mode/1 +]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). @@ -100,7 +102,8 @@ start_link(Opts) -> %% session's context process, which receives the child's exit. -spec fork(pid(), file:filename(), map(), timeout()) -> {ok, pos_integer()} | {error, term()}. fork(T, SockPath, ForkOpts, Timeout) -> - try gen_server:call(T, {fork, SockPath, ForkOpts}, Timeout) + try + gen_server:call(T, {fork, SockPath, ForkOpts}, Timeout) catch exit:{timeout, _} -> {error, fork_timeout}; exit:{noproc, _} -> {error, template_stopped}; @@ -112,7 +115,8 @@ fork(T, SockPath, ForkOpts, Timeout) -> -spec checkout(pid(), timeout()) -> {ok, pid()} | {start, map()} | {reimport, pid(), [binary()]} | {error, term()}. checkout(T, Timeout) -> - try gen_server:call(T, checkout, Timeout) + try + gen_server:call(T, checkout, Timeout) catch exit:{noproc, _} -> {error, template_stopped}; exit:{Reason, _} -> {error, {template_down, Reason}} @@ -158,13 +162,24 @@ handle_call({fork, Path, ForkOpts}, {Pid, _} = From, St) -> Term = {fork, py_child:to_bin(Path), Pid, fork_opts(ForkOpts)}, case py_child:send_frame(Z#zygote.sock, Id, ?STATUS_REQUEST, Term) of ok -> - {noreply, St#st{next = N + 1, next_id = Id + 1, - pending = Pending#{Id => {From, Pid}}}}; + {noreply, St#st{ + next = N + 1, + next_id = Id + 1, + pending = Pending#{Id => {From, Pid}} + }}; {error, Reason} -> {reply, {error, {zygote_unreachable, Reason}}, St} end; -handle_call(checkout, _From, #st{start = reimport, contexts = Cs, next = N, - passthrough = PT} = St) -> +handle_call( + checkout, + _From, + #st{ + start = reimport, + contexts = Cs, + next = N, + passthrough = PT + } = St +) -> {reply, {reimport, lists:nth(N rem length(Cs) + 1, Cs), PT}, St#st{next = N + 1}}; handle_call(checkout, _From, #st{start = fork} = St) -> {reply, {start, context_opts(St)}, St}; @@ -187,14 +202,26 @@ handle_call(refresh, _From, #st{start = fork, zygotes = Old} = St) -> handle_call(refresh, _From, #st{start = reimport, contexts = Old} = St) -> case build(St#st{contexts = []}) of {ok, #st{contexts = [New | _]} = St1} -> - [begin unlink(C), py_context:stop(C) end || C <- Old], + [ + begin + unlink(C), + py_context:stop(C) + end + || C <- Old + ], close_orphans(Old, New, St1), {reply, ok, St1}; {error, Reason} -> {reply, {error, Reason}, St} end; handle_call(refresh, _From, #st{start = spawn, warm = Warm} = St) -> - [begin unlink(C), py_context:stop(C) end || C <- Warm], + [ + begin + unlink(C), + py_context:stop(C) + end + || C <- Warm + ], self() ! fill_warm, {reply, ok, St#st{warm = []}}; handle_call(mode, _From, #st{opts = Opts} = St) -> @@ -211,8 +238,9 @@ handle_info({register_session, Pid, Ctx, Sid}, #st{rsessions = RS} = St) -> %% Watched so a session process killed without closing still frees %% its modules in the context {noreply, St#st{rsessions = RS#{erlang:monitor(process, Pid) => {Pid, Ctx, Sid}}}}; -handle_info({'DOWN', Mon, process, _Pid, _Reason}, #st{rsessions = RS} = St) - when is_map_key(Mon, RS) -> +handle_info({'DOWN', Mon, process, _Pid, _Reason}, #st{rsessions = RS} = St) when + is_map_key(Mon, RS) +-> {{_, Ctx, Sid}, Rest} = maps:take(Mon, RS), _ = spawn(fun() -> py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_close, [Sid], #{}, 5000) @@ -227,8 +255,10 @@ handle_info({'$socket', _, _, _}, St) -> %% abort: the port's exit_status follows and drives the rebuild {noreply, St}; handle_info({Port, {data, Out}}, St) when is_port(Port) -> - [logger:info("py_session template ~p: ~s", [self(), L]) - || L <- binary:split(Out, <<"\n">>, [global, trim_all])], + [ + logger:info("py_session template ~p: ~s", [self(), L]) + || L <- binary:split(Out, <<"\n">>, [global, trim_all]) + ], {noreply, St}; handle_info({Port, {exit_status, Status}}, St) when is_port(Port) -> case lists:keytake(Port, #zygote.port, St#st.zygotes) of @@ -238,14 +268,21 @@ handle_info({Port, {exit_status, Status}}, St) when is_port(Port) -> handle_info(fill_warm, #st{start = spawn, warm = Warm, opts = Opts} = St) -> case length(Warm) < maps:get(warm, Opts, 0) of true -> - case py_context:start_link(erlang:unique_integer([positive]), isolated, - context_opts(St)) of + case + py_context:start_link( + erlang:unique_integer([positive]), + isolated, + context_opts(St) + ) + of {ok, Ctx} -> self() ! fill_warm, {noreply, St#st{warm = Warm ++ [Ctx]}}; {error, Reason} -> - logger:warning("py_session template ~p: warm session failed: ~p", - [self(), Reason]), + logger:warning( + "py_session template ~p: warm session failed: ~p", + [self(), Reason] + ), {noreply, St} end; false -> @@ -257,8 +294,10 @@ handle_info({'EXIT', Pid, Reason}, #st{start = reimport, contexts = Cs} = St) -> case lists:member(Pid, Cs) of true -> %% A context of the template stopped: put a new one in its place - logger:warning("py_session template ~p: context ~p exited: ~p", - [self(), Pid, Reason]), + logger:warning( + "py_session template ~p: context ~p exited: ~p", + [self(), Pid, Reason] + ), case start_context(St#st.opts) of {ok, C} -> close_orphans([Pid], C, St), @@ -278,8 +317,10 @@ handle_info(_Msg, St) -> terminate(_Reason, #st{zygotes = Zs, warm = Warm, contexts = Cs, rsessions = RS}) -> %% Worker contexts share the main interpreter, which outlives them: %% free the modules of sessions still open before the contexts go - [py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_close, [Sid], #{}, 5000) - || {_, Ctx, Sid} <- maps:values(RS), is_process_alive(Ctx)], + [ + py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_close, [Sid], #{}, 5000) + || {_, Ctx, Sid} <- maps:values(RS), is_process_alive(Ctx) + ], [retire(Z) || Z <- Zs], [py_context:stop(C) || C <- Warm ++ Cs], ok. @@ -290,39 +331,60 @@ terminate(_Reason, #st{zygotes = Zs, warm = Warm, contexts = Cs, rsessions = RS} check_opts(Opts) -> Checks = [ - fun() -> case maps:get(start, Opts, fork) of - S when S =:= fork; S =:= spawn; S =:= reimport -> ok; - S -> {error, {badarg, {start, S}}} - end end, - fun() -> case {maps:get(start, Opts, fork), maps:get(mode, Opts, worker)} of - {reimport, M} when M =:= worker; M =:= owngil -> ok; - {reimport, M} -> {error, {badarg, {mode, M}}}; - _ -> ok - end end, - fun() -> case maps:get(contexts, Opts, 1) of - N when is_integer(N), N >= 1 -> ok; - N -> {error, {badarg, {contexts, N}}} - end end, - fun() -> case maps:get(zygotes, Opts, 1) of - N when is_integer(N), N >= 1 -> ok; - N -> {error, {badarg, {zygotes, N}}} - end end, - fun() -> case maps:get(warm, Opts, 0) of - N when is_integer(N), N >= 0 -> ok; - N -> {error, {badarg, {warm, N}}} - end end, + fun() -> + case maps:get(start, Opts, fork) of + S when S =:= fork; S =:= spawn; S =:= reimport -> ok; + S -> {error, {badarg, {start, S}}} + end + end, + fun() -> + case {maps:get(start, Opts, fork), maps:get(mode, Opts, worker)} of + {reimport, M} when M =:= worker; M =:= owngil -> ok; + {reimport, M} -> {error, {badarg, {mode, M}}}; + _ -> ok + end + end, + fun() -> + case maps:get(contexts, Opts, 1) of + N when is_integer(N), N >= 1 -> ok; + N -> {error, {badarg, {contexts, N}}} + end + end, + fun() -> + case maps:get(zygotes, Opts, 1) of + N when is_integer(N), N >= 1 -> ok; + N -> {error, {badarg, {zygotes, N}}} + end + end, + fun() -> + case maps:get(warm, Opts, 0) of + N when is_integer(N), N >= 0 -> ok; + N -> {error, {badarg, {warm, N}}} + end + end, fun() -> py_child:check_env_opts(env_opts(Opts)) end, - fun() -> case {maps:get(cgroup, Opts, undefined), os:type()} of - {undefined, _} -> ok; - {_, {unix, linux}} -> ok; - {_, {unix, Os}} -> {error, {cgroup_unsupported, Os}} - end end, - fun() -> case py_child:python_executable(Opts) of - {error, _} = Err -> Err; - _ -> ok - end end + fun() -> + case {maps:get(cgroup, Opts, undefined), os:type()} of + {undefined, _} -> ok; + {_, {unix, linux}} -> ok; + {_, {unix, Os}} -> {error, {cgroup_unsupported, Os}} + end + end, + fun() -> + case py_child:python_executable(Opts) of + {error, _} = Err -> Err; + _ -> ok + end + end ], - lists:foldl(fun(Check, ok) -> Check(); (_, Err) -> Err end, ok, Checks). + lists:foldl( + fun + (Check, ok) -> Check(); + (_, Err) -> Err + end, + ok, + Checks + ). %% Sessions see only the template's env unless it asks otherwise env_opts(Opts) -> @@ -336,10 +398,17 @@ build(#st{start = reimport, opts = Opts} = St) -> Started = [start_context(Opts) || _ <- lists:seq(1, maps:get(contexts, Opts, 1))], case [E || {error, _} = E <- Started] of [] -> - PT = lists:usort([py_child:to_bin(M) || M <- maps:get(imports, Opts, []) - ++ maps:get(passthrough, Opts, [])]), - {ok, St#st{contexts = [C || {ok, C} <- Started], passthrough = PT, - build_ms = erlang:monotonic_time(millisecond) - T0}}; + PT = lists:usort([ + py_child:to_bin(M) + || M <- + maps:get(imports, Opts, []) ++ + maps:get(passthrough, Opts, []) + ]), + {ok, St#st{ + contexts = [C || {ok, C} <- Started], + passthrough = PT, + build_ms = erlang:monotonic_time(millisecond) - T0 + }}; [Err | _] -> [py_context:stop(C) || {ok, C} <- Started], Err @@ -371,22 +440,31 @@ start_zygote(Opts) -> case py_child:listen(Path) of {ok, L} -> Script = filename:join(py_child:priv_dir(), "py_zygote.py"), - Port = open_port({spawn_executable, Python}, - [exit_status, stderr_to_stdout, binary, use_stdio, - {args, [Script, Path]}, - {env, py_child:port_env(env_opts(Opts))}]), - OsPid = case erlang:port_info(Port, os_pid) of - {os_pid, P} -> P; - _ -> 0 - end, - Result = case py_child:accept(L, {port, Port}, Timeout) of - {ok, S} -> - py_child:tune_socket(S), - Z = #zygote{port = Port, os_pid = OsPid, listener = L, sock = S}, - prepare(Z, Opts, Timeout); - {error, _} = Err -> - Err - end, + Port = open_port( + {spawn_executable, Python}, + [ + exit_status, + stderr_to_stdout, + binary, + use_stdio, + {args, [Script, Path]}, + {env, py_child:port_env(env_opts(Opts))} + ] + ), + OsPid = + case erlang:port_info(Port, os_pid) of + {os_pid, P} -> P; + _ -> 0 + end, + Result = + case py_child:accept(L, {port, Port}, Timeout) of + {ok, S} -> + py_child:tune_socket(S), + Z = #zygote{port = Port, os_pid = OsPid, listener = L, sock = S}, + prepare(Z, Opts, Timeout); + {error, _} = Err -> + Err + end, py_child:delete_file(Path), case Result of {ok, _} = Ok -> @@ -408,11 +486,21 @@ close_orphans(Dead, Via, #st{opts = Opts, rsessions = RS}) -> case maps:get(mode, Opts, worker) of worker -> Sids = [Sid || {_, Ctx, Sid} <- maps:values(RS), lists:member(Ctx, Dead)], - _ = Sids =/= [] andalso - spawn(fun() -> - [py_context:call(Via, <<"_erlang_impl._reimport">>, session_close, - [Sid], #{}, 5000) || Sid <- Sids] - end), + _ = + Sids =/= [] andalso + spawn(fun() -> + [ + py_context:call( + Via, + <<"_erlang_impl._reimport">>, + session_close, + [Sid], + #{}, + 5000 + ) + || Sid <- Sids + ] + end), ok; owngil -> ok @@ -421,23 +509,23 @@ close_orphans(Dead, Via, #st{opts = Opts, rsessions = RS}) -> %% A context for re-import runs: the paths, the imports (shared by every %% run) and the preload are applied once. start_context(Opts) -> - CtxOpts = maps:merge(#{mode => maps:get(mode, Opts, worker)}, - maps:with([preload], Opts)), + CtxOpts = maps:merge( + #{mode => maps:get(mode, Opts, worker)}, + maps:with([preload], Opts) + ), case py_context:new(CtxOpts) of {ok, C} -> Paths = [py_child:to_list(P) || P <- maps:get(paths, Opts, [])], - Setup = iolist_to_binary(io_lib:format( - "import sys, importlib -" - "for _p in reversed(~p): -" - " if _p not in sys.path: sys.path.insert(0, _p) -" - "for _m in ~p: importlib.import_module(_m) -" - "import _erlang_impl._reimport -", - [Paths, [py_child:to_list(M) || M <- maps:get(imports, Opts, [])]])), + Setup = iolist_to_binary( + io_lib:format( + "import sys, importlib\n" + "for _p in reversed(~p):\n" + " if _p not in sys.path: sys.path.insert(0, _p)\n" + "for _m in ~p: importlib.import_module(_m)\n" + "import _erlang_impl._reimport\n", + [Paths, [py_child:to_list(M) || M <- maps:get(imports, Opts, [])]] + ) + ), case py_context:exec(C, Setup) of ok -> {ok, C}; @@ -453,14 +541,24 @@ start_context(Opts) -> prepare(Z, Opts, Timeout) -> case recv_sync(Z, Timeout) of {ok, {0, ?STATUS_EVENT, {ready, Info}}, Z1} -> - Paths = [py_child:to_bin(P) || P <- py_import:all_paths()] - ++ [py_child:to_bin(P) || P <- maps:get(paths, Opts, [])], - Imports = lists:usort([py_child:to_bin(M) || {M, _} <- py_import:all_imports()] - ++ [py_child:to_bin(M) || M <- maps:get(imports, Opts, [])]), - Preload = iolist_to_binary([preload_code(), <<"\n">>, - maps:get(preload, Opts, <<>>)]), - ok = py_child:send_frame(Z1#zygote.sock, 1, ?STATUS_REQUEST, - {init, Paths, Imports, Preload}), + Paths = + [py_child:to_bin(P) || P <- py_import:all_paths()] ++ + [py_child:to_bin(P) || P <- maps:get(paths, Opts, [])], + Imports = lists:usort( + [py_child:to_bin(M) || {M, _} <- py_import:all_imports()] ++ + [py_child:to_bin(M) || M <- maps:get(imports, Opts, [])] + ), + Preload = iolist_to_binary([ + preload_code(), + <<"\n">>, + maps:get(preload, Opts, <<>>) + ]), + ok = py_child:send_frame( + Z1#zygote.sock, + 1, + ?STATUS_REQUEST, + {init, Paths, Imports, Preload} + ), case recv_sync(Z1, Timeout) of {ok, {1, ?STATUS_OK, _}, Z2} -> {ok, arm(Z2#zygote{info = Info})}; @@ -518,7 +616,11 @@ retire(#zygote{sock = S, listener = L, port = Port}) -> close_port(Port). close_port(Port) -> - try port_close(Port) catch error:badarg -> ok end, + try + port_close(Port) + catch + error:badarg -> ok + end, ok. %% ============================================================================ @@ -544,8 +646,10 @@ frames(#zygote{buf = Buf} = Z, St) -> more -> store(Z, St); {error, Reason} -> - logger:error("py_session template ~p: bad frame from zygote ~p: ~p", - [self(), Z#zygote.os_pid, Reason]), + logger:error( + "py_session template ~p: bad frame from zygote ~p: ~p", + [self(), Z#zygote.os_pid, Reason] + ), py_child:kill_os_pid(Z#zygote.os_pid), store(Z#zygote{buf = <<>>}, St) end. @@ -553,8 +657,9 @@ frames(#zygote{buf = Buf} = Z, St) -> store(Z, #st{zygotes = Zs} = St) -> St#st{zygotes = lists:keyreplace(Z#zygote.sock, #zygote.sock, Zs, Z)}. -frame({Id, Status, Term}, #st{pending = Pending, owners = Owners} = St) - when Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR -> +frame({Id, Status, Term}, #st{pending = Pending, owners = Owners} = St) when + Status =:= ?STATUS_OK; Status =:= ?STATUS_ERROR +-> case maps:take(Id, Pending) of {{From, Pid}, Rest} when Status =:= ?STATUS_OK -> gen_server:reply(From, {ok, Term}), @@ -581,8 +686,10 @@ frame(_, St) -> %% ============================================================================ zygote_exited(Z, Reason, #st{pending = Pending} = St) -> - logger:warning("py_session template ~p: zygote ~p exited: ~p", - [self(), Z#zygote.os_pid, Reason]), + logger:warning( + "py_session template ~p: zygote ~p exited: ~p", + [self(), Z#zygote.os_pid, Reason] + ), retire(Z), %% Forks it had not answered fail; the sessions it forked keep running %% and their contexts watch them by pid @@ -594,8 +701,10 @@ zygote_exited(Z, Reason, #st{pending = Pending} = St) -> true -> case start_zygote(St1#st.opts) of {ok, NewZ} -> - {noreply, St1#st{zygotes = St1#st.zygotes ++ [NewZ], - rebuilds = [Now | Recent]}}; + {noreply, St1#st{ + zygotes = St1#st.zygotes ++ [NewZ], + rebuilds = [Now | Recent] + }}; {error, Why} -> {stop, {zygote_rebuild_failed, Why}, St1} end; @@ -609,31 +718,68 @@ zygote_exited(Z, Reason, #st{pending = Pending} = St) -> %% Options of the isolated context behind each session context_opts(#st{start = fork, opts = Opts}) -> - maps:merge(maps:with([rlimits, cgroup, start_timeout, kill_after], Opts), - #{mode => isolated, session => true, restart => false, - origin => {fork, self()}}); + maps:merge( + maps:with([rlimits, cgroup, start_timeout, kill_after], Opts), + #{ + mode => isolated, + session => true, + restart => false, + origin => {fork, self()} + } + ); context_opts(#st{start = spawn, opts = Opts}) -> - maps:merge(maps:with([python, paths, preload, rlimits, cgroup, start_timeout, - kill_after], Opts), - (env_opts(Opts))#{mode => isolated, session => true, restart => false, - origin => spawn}). + maps:merge( + maps:with( + [ + python, + paths, + preload, + rlimits, + cgroup, + start_timeout, + kill_after + ], + Opts + ), + (env_opts(Opts))#{ + mode => isolated, + session => true, + restart => false, + origin => spawn + } + ). fork_opts(ForkOpts) -> - maps:fold(fun(rlimits, V, Acc) -> Acc#{rlimits => V}; - (cgroup, V, Acc) -> Acc#{cgroup => py_child:to_bin(V)}; - (cd, V, Acc) -> Acc#{cd => py_child:to_bin(V)}; - (_, _, Acc) -> Acc - end, #{}, ForkOpts). - -info_map(#st{start = Start, zygotes = Zs, owners = Owners, forks = Forks, - build_ms = BuildMs, warm = Warm, opts = Opts, contexts = Cs, - rsessions = RS}) -> - #{start => Start, - contexts => Cs, - reimport_sessions => map_size(RS), - zygotes => [Info#{os_pid => P} || #zygote{os_pid = P, info = Info} <- Zs], - sessions => map_size(Owners), - forks => Forks, - build_ms => BuildMs, - warm => length(Warm), - hash_seed => maps:get(hash_seed, Opts, random)}. + maps:fold( + fun + (rlimits, V, Acc) -> Acc#{rlimits => V}; + (cgroup, V, Acc) -> Acc#{cgroup => py_child:to_bin(V)}; + (cd, V, Acc) -> Acc#{cd => py_child:to_bin(V)}; + (_, _, Acc) -> Acc + end, + #{}, + ForkOpts + ). + +info_map(#st{ + start = Start, + zygotes = Zs, + owners = Owners, + forks = Forks, + build_ms = BuildMs, + warm = Warm, + opts = Opts, + contexts = Cs, + rsessions = RS +}) -> + #{ + start => Start, + contexts => Cs, + reimport_sessions => map_size(RS), + zygotes => [Info#{os_pid => P} || #zygote{os_pid = P, info = Info} <- Zs], + sessions => map_size(Owners), + forks => Forks, + build_ms => BuildMs, + warm => length(Warm), + hash_seed => maps:get(hash_seed, Opts, random) + }. diff --git a/src/py_shared_dict.erl b/src/py_shared_dict.erl index 8ee103b..085fca3 100644 --- a/src/py_shared_dict.erl +++ b/src/py_shared_dict.erl @@ -27,7 +27,6 @@ shared_dict_destroy/1 ]). - %% @doc Create a new process-scoped SharedDict. %% %% Creates a SharedDict owned by the calling process. The dict is automatically @@ -106,5 +105,3 @@ shared_dict_keys(Handle) -> -spec shared_dict_destroy(reference()) -> ok. shared_dict_destroy(Handle) -> py_nif:shared_dict_destroy(Handle). - - diff --git a/src/py_shm.erl b/src/py_shm.erl index d9157e6..c67df0f 100644 --- a/src/py_shm.erl +++ b/src/py_shm.erl @@ -93,8 +93,10 @@ id :: pos_integer(), handle :: term(), ring :: pos_integer(), - wpos = 0 :: non_neg_integer(), %% total bytes written - rpos = 0 :: non_neg_integer(), %% total bytes consumed + %% total bytes written + wpos = 0 :: non_neg_integer(), + %% total bytes consumed + rpos = 0 :: non_neg_integer(), closed = false :: boolean(), readers = [] :: [{gen_server:from(), non_neg_integer()}], %% Writers waiting for room: {From, Rest, TimerRef} @@ -144,7 +146,8 @@ read_only({Tag, Id, Path, Size}) when ?IS_SHM(Tag) -> -spec write(shm(), non_neg_integer(), binary()) -> ok | {error, term()}. write({Tag, Id, _, Size}, Offset, Data) when ?IS_SHM(Tag), is_binary(Data) -> case Offset + byte_size(Data) > Size of - true -> {error, out_of_bounds}; + true -> + {error, out_of_bounds}; false -> case lookup(Id) of {ok, Handle} -> iommap(pwrite, [Handle, Offset, Data]); @@ -156,7 +159,8 @@ write({Tag, Id, _, Size}, Offset, Data) when ?IS_SHM(Tag), is_binary(Data) -> -spec read(shm(), non_neg_integer(), non_neg_integer()) -> {ok, binary()} | {error, term()}. read({Tag, Id, _, Size}, Offset, Len) when ?IS_SHM(Tag) -> case Offset + Len > Size of - true -> {error, out_of_bounds}; + true -> + {error, out_of_bounds}; false -> case lookup(Id) of {ok, Handle} -> iommap(pread, [Handle, Offset, Len]); @@ -252,14 +256,16 @@ handle_buffer_state([Id]) -> %% (memory backed), else a 0700 directory under `TMPDIR'. -spec private_dir() -> string(). private_dir() -> - Base = case filelib:is_dir("/dev/shm") of - true -> "/dev/shm"; - false -> - case os:getenv("TMPDIR") of - false -> "/tmp"; - T -> T - end - end, + Base = + case filelib:is_dir("/dev/shm") of + true -> + "/dev/shm"; + false -> + case os:getenv("TMPDIR") of + false -> "/tmp"; + T -> T + end + end, Dir = filename:join(Base, "erlang_python_" ++ os:getpid()), ok = filelib:ensure_dir(filename:join(Dir, "x")), _ = file:change_mode(Dir, 8#700), @@ -275,11 +281,9 @@ init([]) -> handle_call({new, Size, Owner}, _From, State) -> {reply, create_region(Size, Owner), State}; - handle_call({close, Id}, _From, State) -> close_region(Id), {reply, ok, State}; - handle_call({buffer_new, Ring, Owner}, _From, #state{buffers = Bufs} = State) -> case create_region(?HEADER + Ring, Owner) of {ok, {'$py_shm', Id, Path, _}} -> @@ -290,7 +294,6 @@ handle_call({buffer_new, Ring, Owner}, _From, #state{buffers = Bufs} = State) -> {error, _} = Err -> {reply, Err, State} end; - handle_call({buffer_write, Id, Data, Timeout}, From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := #buf{closed = true}} -> @@ -307,7 +310,6 @@ handle_call({buffer_write, Id, Data, Timeout}, From, #state{buffers = Bufs} = St _ -> {reply, {error, closed}, State} end; - handle_call({buffer_close, Id}, _From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := Buf} -> @@ -315,13 +317,17 @@ handle_call({buffer_close, Id}, _From, #state{buffers = Bufs} = State) -> ok = write_header(Buf1), %% Readers learn about EOF; writers still waiting fail [gen_server:reply(R, {Buf1#buf.wpos, true}) || {R, _} <- Buf1#buf.readers], - [begin erlang:cancel_timer(T), gen_server:reply(W, {error, closed}) end - || {W, _, T} <- Buf1#buf.writers], + [ + begin + erlang:cancel_timer(T), + gen_server:reply(W, {error, closed}) + end + || {W, _, T} <- Buf1#buf.writers + ], {reply, ok, State#state{buffers = Bufs#{Id => Buf1#buf{readers = [], writers = []}}}}; _ -> {reply, ok, State} end; - handle_call({buffer_wait, Id, ReadPos}, From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := #buf{wpos = W, closed = C}} when W > ReadPos; C -> @@ -332,7 +338,6 @@ handle_call({buffer_wait, Id, ReadPos}, From, #state{buffers = Bufs} = State) -> _ -> {reply, {error, closed}, State} end; - handle_call({buffer_consumed, Id, N}, _From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := Buf} -> @@ -342,22 +347,26 @@ handle_call({buffer_consumed, Id, N}, _From, #state{buffers = Bufs} = State) -> _ -> {reply, {error, closed}, State} end; - handle_call({buffer_state, Id}, _From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := #buf{wpos = W, closed = C}} -> {reply, {W, C}, State}; _ -> {reply, {error, closed}, State} end; - handle_call({buffer_info, Id}, _From, #state{buffers = Bufs} = State) -> case Bufs of #{Id := #buf{wpos = W, rpos = R, closed = C, ring = Ring}} -> - {reply, {ok, #{written => W, consumed => R, closed => C, ring => Ring, - pending_writers => length((maps:get(Id, Bufs))#buf.writers)}}, State}; + {reply, + {ok, #{ + written => W, + consumed => R, + closed => C, + ring => Ring, + pending_writers => length((maps:get(Id, Bufs))#buf.writers) + }}, + State}; _ -> {reply, {error, closed}, State} end; - handle_call(_Req, _From, State) -> {reply, {error, badarg}, State}. @@ -436,7 +445,11 @@ close_region(Id) -> %% Header page: <> write_header(#buf{handle = H, wpos = W, closed = C, ring = Ring}) -> - Flag = case C of true -> 1; false -> 0 end, + Flag = + case C of + true -> 1; + false -> 0 + end, iommap(pwrite, [H, 0, <>]). %% Copy as much of Data as fits, advance wpos, wake readers. @@ -444,18 +457,20 @@ do_write(#buf{ring = Ring, wpos = W, rpos = R} = Buf, Data) -> Free = Ring - (W - R), Size = byte_size(Data), Take = min(Free, Size), - Buf1 = case Take > 0 of - true -> - <> = Data, - ok = ring_write(Buf, W, Chunk), - B = Buf#buf{wpos = W + Take}, - ok = write_header(B), - wake_readers(B); - false -> - Buf - end, + Buf1 = + case Take > 0 of + true -> + <> = Data, + ok = ring_write(Buf, W, Chunk), + B = Buf#buf{wpos = W + Take}, + ok = write_header(B), + wake_readers(B); + false -> + Buf + end, case Take =:= Size of - true -> {ok, Buf1}; + true -> + {ok, Buf1}; false -> <<_:Take/binary, Rest/binary>> = Data, {partial, Buf1, Rest} diff --git a/src/py_state.erl b/src/py_state.erl index ce71b7c..270c660 100644 --- a/src/py_state.erl +++ b/src/py_state.erl @@ -117,7 +117,8 @@ register_callbacks() -> %% @doc Fetch a value from the shared state. -spec fetch(Key :: term()) -> {ok, term()} | {error, not_found}. -fetch(?SIZE_KEY) -> {error, not_found}; +fetch(?SIZE_KEY) -> + {error, not_found}; fetch(Key) -> case ets:lookup(?TABLE, Key) of [{_, Value}] -> {ok, Value}; @@ -178,9 +179,14 @@ remove(Key) -> %% @doc Get all keys in the shared state. -spec keys() -> [term()]. keys() -> - ets:foldl(fun({?SIZE_KEY, _}, Acc) -> Acc; - ({K, _}, Acc) -> [K | Acc] - end, [], ?TABLE). + ets:foldl( + fun + ({?SIZE_KEY, _}, Acc) -> Acc; + ({K, _}, Acc) -> [K | Acc] + end, + [], + ?TABLE + ). %% @doc Clear all entries from the shared state. -spec clear() -> ok. @@ -306,12 +312,13 @@ stream_send_callback([RefHash, EventType, Value]) -> {ok, Owner} -> case fetch({<<"stream_ref">>, RefHash}) of {ok, Ref} -> - Event = case normalize_event_type(EventType) of - done -> done; - data -> {data, Value}; - error -> {error, Value}; - Other -> {error, {unknown_event, Other, Value}} - end, + Event = + case normalize_event_type(EventType) of + done -> done; + data -> {data, Value}; + error -> {error, Value}; + Other -> {error, {unknown_event, Other, Value}} + end, Owner ! {py_stream, Ref, Event}, ok; {error, not_found} -> diff --git a/src/py_stream.erl b/src/py_stream.erl index badb8f8..07be65a 100644 --- a/src/py_stream.erl +++ b/src/py_stream.erl @@ -29,7 +29,6 @@ stream_cancel/1 ]). - %% @doc Stream results from a Python generator. %% Returns a list of all yielded values. -spec stream(py:py_module(), py:py_func(), py:py_args()) -> py:py_result(). @@ -38,7 +37,7 @@ stream(Module, Func, Args) -> %% @doc Stream results from a Python generator with kwargs. -spec stream(py:py_module(), py:py_func(), py:py_args(), py:py_kwargs()) -> py:py_result(). -stream(Module, Func, Args, Kwargs) when map_size(Kwargs) == 0 -> +stream(Module, Func, Args, Kwargs) when map_size(Kwargs) =:= 0 -> %% No kwargs - use stream_start and collect results {ok, Ref} = stream_start(Module, Func, Args), collect_stream(Ref, []); @@ -50,8 +49,14 @@ stream(Module, Func, Args, Kwargs) -> KwargsCode = format_kwargs(Kwargs), ArgsCode = format_args(Args), Code = iolist_to_binary([ - <<"list(__import__('">>, ModuleBin, <<"').">>, FuncBin, - <<"(">>, ArgsCode, KwargsCode, <<"))">> + <<"list(__import__('">>, + ModuleBin, + <<"').">>, + FuncBin, + <<"(">>, + ArgsCode, + KwargsCode, + <<"))">> ]), py_context:eval(Ctx, Code, #{}). @@ -69,7 +74,8 @@ collect_stream(Ref, Acc) -> end. %% @private Format arguments for Python code -format_args([]) -> <<>>; +format_args([]) -> + <<>>; format_args(Args) -> ArgStrs = [format_arg(A) || A <- Args], iolist_to_binary(lists:join(<<", ">>, ArgStrs)). @@ -78,17 +84,28 @@ format_args(Args) -> format_arg(A) when is_integer(A) -> integer_to_binary(A); format_arg(A) when is_float(A) -> float_to_binary(A); format_arg(A) when is_binary(A) -> <<"'", (py_util:escape_py_literal(A))/binary, "'">>; -format_arg(A) when is_atom(A) -> <<"'", (py_util:escape_py_literal(atom_to_binary(A)))/binary, "'">>; +format_arg(A) when is_atom(A) -> + <<"'", (py_util:escape_py_literal(atom_to_binary(A)))/binary, "'">>; format_arg(A) when is_list(A) -> iolist_to_binary([<<"[">>, format_args(A), <<"]">>]); -format_arg(_) -> <<"None">>. +format_arg(_) -> + <<"None">>. %% @private Format kwargs for Python code -format_kwargs(Kwargs) when map_size(Kwargs) == 0 -> <<>>; +format_kwargs(Kwargs) when map_size(Kwargs) =:= 0 -> <<>>; format_kwargs(Kwargs) -> - KwList = maps:fold(fun(K, V, Acc) -> - KB = py_util:valid_py_ident(if is_atom(K) -> atom_to_binary(K); is_binary(K) -> K end), - [<> | Acc] + end, + [], + Kwargs + ), iolist_to_binary([<<", ">>, lists:join(<<", ">>, KwList)]). %% @doc Stream results from a Python generator expression. @@ -184,13 +201,19 @@ stream_run_python(ModuleBin0, FuncBin0, RefHash) -> %% Build Python code that streams values using callbacks Code = iolist_to_binary([ <<"import erlang\n">>, - <<"_rh = ">>, RefHashBin, <<"\n">>, + <<"_rh = ">>, + RefHashBin, + <<"\n">>, <<"_args = erlang.call('state_get', ('stream_args', _rh))\n">>, <<"if _args is None:\n">>, <<" _args = []\n">>, <<"try:\n">>, - <<" _mod = __import__('">>, ModuleBin, <<"')\n">>, - <<" _fn = getattr(_mod, '">>, FuncBin, <<"')\n">>, + <<" _mod = __import__('">>, + ModuleBin, + <<"')\n">>, + <<" _fn = getattr(_mod, '">>, + FuncBin, + <<"')\n">>, <<" _gen = _fn(*_args) if _args else _fn()\n">>, %% Async generators are driven on a private event loop. erlang.call is %% a blocking pipe read, so it stalls that loop between yields, which @@ -220,7 +243,8 @@ stream_run_python(ModuleBin0, FuncBin0, RefHash) -> ]), %% Execute the streaming code case py:exec(Code) of - ok -> ok; + ok -> + ok; {error, Reason} -> %% Try to notify owner of error case py_state:fetch({<<"stream_owner">>, RefHash}) of @@ -231,9 +255,11 @@ stream_run_python(ModuleBin0, FuncBin0, RefHash) -> py_state:remove({<<"stream_owner">>, RefHash}), py_state:remove({<<"stream_ref">>, RefHash}), py_state:remove({<<"stream_args">>, RefHash}); - _ -> ok + _ -> + ok end; - _ -> ok + _ -> + ok end end. @@ -252,4 +278,3 @@ stream_cancel(Ref) when is_reference(Ref) -> RefHash = erlang:phash2(Ref), py_state:store({<<"stream_cancelled_hash">>, RefHash}, true), ok. - diff --git a/src/py_thread_handler.erl b/src/py_thread_handler.erl index 756e5e0..253ce96 100644 --- a/src/py_thread_handler.erl +++ b/src/py_thread_handler.erl @@ -64,9 +64,9 @@ %% writer_fds — reverse map: WriterPid => WriteFd (fast lookup on %% 'DOWN' messages). -record(state, { - handlers = #{} :: #{non_neg_integer() => {pid(), integer()}}, + handlers = #{} :: #{non_neg_integer() => {pid(), integer()}}, async_writers = #{} :: #{integer() => {pid(), atomics:atomics_ref()}}, - writer_fds = #{} :: #{pid() => integer()} + writer_fds = #{} :: #{pid() => integer()} }). %% Bound on combined async in-flight + writer-mailbox depth. The @@ -121,15 +121,18 @@ handle_info({thread_worker_spawn, WorkerId, WriteFd}, #state{handlers = Handlers {noreply, State#state{handlers = NewHandlers}}; {error, Reason} -> %% The Python side times out and reports it; say why here - logger:error("py_thread_handler: ready signal for worker ~p (fd ~p) failed: ~p", - [WorkerId, WriteFd, Reason]), + logger:error( + "py_thread_handler: ready signal for worker ~p (fd ~p) failed: ~p", + [WorkerId, WriteFd, Reason] + ), HandlerPid ! shutdown, {noreply, State} end; - %% Handle callback request from Python thread -handle_info({thread_callback, WorkerId, CallbackId, FuncName, Args}, - #state{handlers = Handlers} = State) -> +handle_info( + {thread_callback, WorkerId, CallbackId, FuncName, Args}, + #state{handlers = Handlers} = State +) -> case maps:get(WorkerId, Handlers, undefined) of {HandlerPid, _WriteFd} -> %% Forward to the handler process @@ -139,7 +142,6 @@ handle_info({thread_callback, WorkerId, CallbackId, FuncName, Args}, ok end, {noreply, State}; - %% Handle async callback request from Python async_call(). %% %% Unlike thread_callback, this uses one shared per-interpreter pipe @@ -170,29 +172,34 @@ handle_info({async_callback, CallbackId, FuncName, Args, WriteFd}, State0) -> end) end, {noreply, State1}; - %% Linked-process exit: covers both sync handlers and async writers. %% Both are spawn_link'd so a coordinator crash takes them with it %% (no leaked writer holding the async pipe fd after the gen_server %% restarts). When THEY die independently we trap the EXIT here and %% remove the dead pid from whichever map it lives in. -handle_info({'EXIT', Pid, _Reason}, - #state{handlers = Handlers, - async_writers = Writers, - writer_fds = WriterFds} = State) -> +handle_info( + {'EXIT', Pid, _Reason}, + #state{ + handlers = Handlers, + async_writers = Writers, + writer_fds = WriterFds + } = State +) -> NewHandlers = maps:filter( fun(_WorkerId, {HandlerPid, _Fd}) -> HandlerPid =/= Pid end, - Handlers), + Handlers + ), case maps:take(Pid, WriterFds) of {WriteFd, NewWriterFds} -> NewWriters = maps:remove(WriteFd, Writers), - {noreply, State#state{handlers = NewHandlers, - async_writers = NewWriters, - writer_fds = NewWriterFds}}; + {noreply, State#state{ + handlers = NewHandlers, + async_writers = NewWriters, + writer_fds = NewWriterFds + }}; error -> {noreply, State#state{handlers = NewHandlers}} end; - handle_info(_Info, State) -> {noreply, State}. @@ -214,14 +221,11 @@ handler_loop(WorkerId, WriteFd) -> %% clause removes us from its handler map. handle_thread_callback(WriteFd, CallbackId, FuncName, Args), handler_loop(WorkerId, WriteFd); - {pipe_closed} -> %% Python thread exited, clean up ok; - shutdown -> ok; - _Other -> handler_loop(WorkerId, WriteFd) end. @@ -229,32 +233,35 @@ handler_loop(WorkerId, WriteFd) -> %% Execute a callback and write the id-prefixed response to the pipe. handle_thread_callback(WriteFd, CallbackId, FuncName, Args) -> %% Convert Args from tuple to list if needed - ArgsList = case Args of - T when is_tuple(T) -> tuple_to_list(T); - L when is_list(L) -> L; - _ -> [Args] - end, + ArgsList = + case Args of + T when is_tuple(T) -> tuple_to_list(T); + L when is_list(L) -> L; + _ -> [Args] + end, %% Execute the registered function - Response = case py_callback:execute(FuncName, ArgsList) of - {ok, Result} -> - %% Format: status_byte (2=ok, ETF) + external term format - <<2, (term_to_binary(Result))/binary>>; - {error, {not_found, Name}} -> - ErrMsg = iolist_to_binary( - io_lib:format("Function '~s' not registered", [Name])), - <<1, ErrMsg/binary>>; - {error, {Class, Reason, _Stack}} -> - ErrMsg = iolist_to_binary( - io_lib:format("~p: ~p", [Class, Reason])), - <<1, ErrMsg/binary>> - end, + Response = + case py_callback:execute(FuncName, ArgsList) of + {ok, Result} -> + %% Format: status_byte (2=ok, ETF) + external term format + <<2, (term_to_binary(Result))/binary>>; + {error, {not_found, Name}} -> + ErrMsg = iolist_to_binary( + io_lib:format("Function '~s' not registered", [Name]) + ), + <<1, ErrMsg/binary>>; + {error, {Class, Reason, _Stack}} -> + ErrMsg = iolist_to_binary( + io_lib:format("~p: ~p", [Class, Reason]) + ), + <<1, ErrMsg/binary>> + end, %% Write response to pipe; exit on failure so we are reaped. case py_nif:thread_worker_write_with_id(WriteFd, CallbackId, Response) of ok -> ok; - {error, Reason1} -> - exit({thread_worker_write_failed, Reason1}) + {error, Reason1} -> exit({thread_worker_write_failed, Reason1}) end. %% Execute the user's registered function and encode the result as a @@ -263,21 +270,24 @@ handle_thread_callback(WriteFd, CallbackId, FuncName, Args) -> %% via the same encoding shape — the sync path keeps its own copy %% close to the write call site). run_async_callback(FuncName, Args) -> - ArgsList = case Args of - T when is_tuple(T) -> tuple_to_list(T); - L when is_list(L) -> L; - _ -> [Args] - end, + ArgsList = + case Args of + T when is_tuple(T) -> tuple_to_list(T); + L when is_list(L) -> L; + _ -> [Args] + end, case py_callback:execute(FuncName, ArgsList) of {ok, Result} -> <<2, (term_to_binary(Result))/binary>>; {error, {not_found, Name}} -> ErrMsg = iolist_to_binary( - io_lib:format("Function '~s' not registered", [Name])), + io_lib:format("Function '~s' not registered", [Name]) + ), <<1, ErrMsg/binary>>; {error, {Class, Reason, _Stack}} -> ErrMsg = iolist_to_binary( - io_lib:format("~p: ~p", [Class, Reason])), + io_lib:format("~p: ~p", [Class, Reason]) + ), <<1, ErrMsg/binary>> end. @@ -291,16 +301,21 @@ run_async_callback(FuncName, Args) -> %% the next callback. Each writer gets its own atomics counter that %% bounds total in-flight async callbacks (executors + queued %% responses) on that pipe. -ensure_async_writer(WriteFd, - #state{async_writers = Writers, - writer_fds = WriterFds} = State) -> +ensure_async_writer( + WriteFd, + #state{ + async_writers = Writers, + writer_fds = WriterFds + } = State +) -> case maps:get(WriteFd, Writers, undefined) of undefined -> Counter = atomics:new(1, [{signed, false}]), Writer = spawn_link(fun() -> async_writer_loop(WriteFd) end), {Writer, Counter, State#state{ async_writers = Writers#{WriteFd => {Writer, Counter}}, - writer_fds = WriterFds#{Writer => WriteFd}}}; + writer_fds = WriterFds#{Writer => WriteFd} + }}; {Writer, Counter} -> {Writer, Counter, State} end. @@ -334,15 +349,13 @@ async_writer_loop(WriteFd) -> atomics:sub(Counter, 1, 1), case R of ok -> async_writer_loop(WriteFd); - {error, _} = Err -> - exit({async_callback_response_failed, Err}) + {error, _} = Err -> exit({async_callback_response_failed, Err}) end; {overflow, CallbackId} -> Response = <<1, "async callback queue full">>, case py_nif:async_callback_response(WriteFd, CallbackId, Response) of ok -> async_writer_loop(WriteFd); - {error, _} = Err -> - exit({async_callback_response_failed, Err}) + {error, _} = Err -> exit({async_callback_response_failed, Err}) end; shutdown -> ok; diff --git a/src/py_tracer.erl b/src/py_tracer.erl index 48d1b49..58085b4 100644 --- a/src/py_tracer.erl +++ b/src/py_tracer.erl @@ -95,17 +95,13 @@ init([]) -> handle_call(enable, _From, State) -> py_nif:set_trace_receiver(self()), {reply, ok, State#{enabled => true}}; - handle_call(disable, _From, State) -> py_nif:clear_trace_receiver(), {reply, ok, State#{enabled => false}}; - handle_call(get_spans, _From, #{completed := Completed} = State) -> {reply, {ok, lists:reverse(Completed)}, State}; - handle_call(clear, _From, State) -> {reply, ok, State#{spans => #{}, completed => []}}; - handle_call(_Request, _From, State) -> {reply, ok, State}. @@ -114,8 +110,10 @@ handle_cast(_Msg, State) -> {noreply, State}. %% @private Handle span events from Python -handle_info({span_start, SpanId, ParentId, Name, Attrs, StartTime}, - #{spans := Spans} = State) -> +handle_info( + {span_start, SpanId, ParentId, Name, Attrs, StartTime}, + #{spans := Spans} = State +) -> Span = #{ span_id => SpanId, parent_id => ParentId, @@ -125,9 +123,10 @@ handle_info({span_start, SpanId, ParentId, Name, Attrs, StartTime}, events => [] }, {noreply, State#{spans => Spans#{SpanId => Span}}}; - -handle_info({span_end, SpanId, Status, Attrs, EndTime}, - #{spans := Spans, completed := Completed} = State) -> +handle_info( + {span_end, SpanId, Status, Attrs, EndTime}, + #{spans := Spans, completed := Completed} = State +) -> case maps:take(SpanId, Spans) of {Span, NewSpans} -> Done = Span#{ @@ -140,7 +139,6 @@ handle_info({span_end, SpanId, Status, Attrs, EndTime}, error -> {noreply, State} end; - handle_info({span_event, SpanId, Name, Attrs, Time}, #{spans := Spans} = State) -> case maps:get(SpanId, Spans, undefined) of undefined -> @@ -151,7 +149,6 @@ handle_info({span_event, SpanId, Name, Attrs, Time}, #{spans := Spans} = State) NewSpan = Span#{events => [Event | Events]}, {noreply, State#{spans => Spans#{SpanId => NewSpan}}} end; - handle_info(_Msg, State) -> {noreply, State}. diff --git a/src/py_util.erl b/src/py_util.erl index 9ae86b1..2168f78 100644 --- a/src/py_util.erl +++ b/src/py_util.erl @@ -40,16 +40,22 @@ to_binary(Bin) when is_binary(Bin) -> %% @doc Escape a binary for use inside a single-quoted Python string literal. -spec escape_py_literal(binary()) -> binary(). escape_py_literal(Bin) when is_binary(Bin) -> - << <<(escape_py_byte(B))/binary>> || <> <= Bin >>. + <<<<(escape_py_byte(B))/binary>> || <> <= Bin>>. -escape_py_byte($') -> <<"\\'">>; -escape_py_byte($\\) -> <<"\\\\">>; -escape_py_byte($\n) -> <<"\\n">>; -escape_py_byte($\r) -> <<"\\r">>; -escape_py_byte($\t) -> <<"\\t">>; +escape_py_byte($') -> + <<"\\'">>; +escape_py_byte($\\) -> + <<"\\\\">>; +escape_py_byte($\n) -> + <<"\\n">>; +escape_py_byte($\r) -> + <<"\\r">>; +escape_py_byte($\t) -> + <<"\\t">>; escape_py_byte(B) when B < 16#20; B =:= 16#7f -> list_to_binary(io_lib:format("\\x~2.16.0b", [B])); -escape_py_byte(B) -> <>. +escape_py_byte(B) -> + <>. %% @private Validate a dotted Python module path (each segment an identifier). valid_py_module(Bin) when is_binary(Bin), byte_size(Bin) > 0 -> @@ -59,16 +65,24 @@ valid_py_module(Bin) when is_binary(Bin), byte_size(Bin) > 0 -> valid_py_module(Other) -> error({invalid_python_identifier, Other}). -ident_ok(<<>>, first) -> false; %% empty segment (leading/trailing/double dot) -ident_ok(<<>>, rest) -> true; -ident_ok(<>, first) - when (C >= $A andalso C =< $Z); (C >= $a andalso C =< $z); C =:= $_ -> +%% empty segment (leading/trailing/double dot) +ident_ok(<<>>, first) -> + false; +ident_ok(<<>>, rest) -> + true; +ident_ok(<>, first) when + (C >= $A andalso C =< $Z); (C >= $a andalso C =< $z); C =:= $_ +-> ident_ok(Rest, rest); -ident_ok(<>, rest) - when (C >= $A andalso C =< $Z); (C >= $a andalso C =< $z); - (C >= $0 andalso C =< $9); C =:= $_ -> +ident_ok(<>, rest) when + (C >= $A andalso C =< $Z); + (C >= $a andalso C =< $z); + (C >= $0 andalso C =< $9); + C =:= $_ +-> ident_ok(Rest, rest); -ident_ok(_, _) -> false. +ident_ok(_, _) -> + false. %% @private Validate a Python identifier ([A-Za-z_][A-Za-z0-9_]*). Crashes on a %% non-conforming value so an attacker-controlled module/func/kwarg name can't diff --git a/src/py_venv.erl b/src/py_venv.erl index 731f6cd..8b41b54 100644 --- a/src/py_venv.erl +++ b/src/py_venv.erl @@ -29,7 +29,6 @@ venv_info/0 ]). - %% @doc Ensure a virtual environment exists and activate it. %% %% Creates a venv at `Path' if it doesn't exist, installs dependencies from @@ -73,12 +72,13 @@ ensure_venv(Path, RequirementsFile, Opts) -> ReqFileStr = to_string(RequirementsFile), Force = proplists:get_bool(force, Opts), %% Create venv if needed - VenvReady = case venv_exists(PathStr) of - true when not Force -> - ok; - _ -> - create_venv(PathStr, Opts) - end, + VenvReady = + case venv_exists(PathStr) of + true when not Force -> + ok; + _ -> + create_venv(PathStr, Opts) + end, case VenvReady of ok -> %% Always install/update dependencies (pip/uv skip existing) @@ -101,10 +101,11 @@ venv_exists(Path) -> -spec create_venv(string(), list()) -> ok | {error, term()}. create_venv(Path, Opts) -> Installer = detect_installer(Opts), - Python = case proplists:get_value(python, Opts, undefined) of - undefined -> get_python_executable(); - P -> P - end, + Python = + case proplists:get_value(python, Opts, undefined) of + undefined -> get_python_executable(); + P -> P + end, case Installer of uv -> %% uv venv is faster, use --python to match the running interpreter @@ -124,13 +125,23 @@ create_venv(Path, Opts) -> python_executable() -> get_python_executable(). - -spec get_python_executable() -> string(). get_python_executable() -> %% Use a single expression to find the Python executable %% Searches for pythonX.Y, python3, python in sys.prefix/bin (Unix) %% or python.exe in sys.prefix (Windows) - Expr = <<"(lambda: (__import__('os').path.join(__import__('sys').prefix, 'python.exe') if __import__('sys').platform == 'win32' and __import__('os').path.isfile(__import__('os').path.join(__import__('sys').prefix, 'python.exe')) else next((p for p in [__import__('os').path.join(__import__('sys').prefix, 'bin', f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python3'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python')] if __import__('os').path.isfile(p)), 'python3')))()">>, + Expr = + << + "(lambda: (__import__('os').path.join(__import__('sys').prefix, 'python.exe') if " + "__import__('sys').platform == 'win32' and " + "__import__('os').path.isfile(__import__('os').path.join(__import__('sys').prefix, " + "'python.exe')) else next((p for p in " + "[__import__('os').path.join(__import__('sys').prefix, 'bin', " + "f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'), " + "__import__('os').path.join(__import__('sys').prefix, 'bin', 'python3'), " + "__import__('os').path.join(__import__('sys').prefix, 'bin', 'python')] if " + "__import__('os').path.isfile(p)), 'python3')))()" + >>, case py:eval(Expr) of {ok, Path} when is_binary(Path) -> binary_to_list(Path); _ -> "python3" @@ -144,23 +155,24 @@ install_deps(Path, RequirementsFile, Opts) -> Extras = proplists:get_value(extras, Opts, []), %% Determine file type and build the install argument list (no shell). - Args = case filename:extension(RequirementsFile) of - ".txt" -> - BaseArgs ++ ["install", "-r", RequirementsFile]; - ".toml" -> - %% pyproject.toml - install as editable. - %% filename:dirname returns "." for files without directory component - InstallPath = filename:dirname(RequirementsFile), - case Extras of - [] -> - BaseArgs ++ ["install", "-e", InstallPath]; - _ -> - ExtrasStr = string:join(Extras, ","), - BaseArgs ++ ["install", "-e", InstallPath ++ "[" ++ ExtrasStr ++ "]"] - end; - _ -> - BaseArgs ++ ["install", "-r", RequirementsFile] - end, + Args = + case filename:extension(RequirementsFile) of + ".txt" -> + BaseArgs ++ ["install", "-r", RequirementsFile]; + ".toml" -> + %% pyproject.toml - install as editable. + %% filename:dirname returns "." for files without directory component + InstallPath = filename:dirname(RequirementsFile), + case Extras of + [] -> + BaseArgs ++ ["install", "-e", InstallPath]; + _ -> + ExtrasStr = string:join(Extras, ","), + BaseArgs ++ ["install", "-e", InstallPath ++ "[" ++ ExtrasStr ++ "]"] + end; + _ -> + BaseArgs ++ ["install", "-r", RequirementsFile] + end, run_cmd(Exe, Args, PortOpts). %% @private Detect which installer to use (uv or pip) @@ -183,12 +195,13 @@ detect_installer(Opts) -> pip_command(VenvPath, uv) -> {uv_exe(), ["pip"], [{env, [{"VIRTUAL_ENV", VenvPath}]}]}; pip_command(VenvPath, pip) -> - PipExe = case os:type() of - {win32, _} -> - filename:join([VenvPath, "Scripts", "pip"]); - _ -> - filename:join([VenvPath, "bin", "pip"]) - end, + PipExe = + case os:type() of + {win32, _} -> + filename:join([VenvPath, "Scripts", "pip"]); + _ -> + filename:join([VenvPath, "bin", "pip"]) + end, {PipExe, [], []}. %% @private Full path to the uv executable (falls back to the bare name). @@ -206,8 +219,12 @@ run_cmd(Exe, Args, ExtraOpts) -> {error, _} = Err -> Err; ExeFull -> - try open_port({spawn_executable, ExeFull}, - [exit_status, stderr_to_stdout, binary, {args, Args} | ExtraOpts]) of + try + open_port( + {spawn_executable, ExeFull}, + [exit_status, stderr_to_stdout, binary, {args, Args} | ExtraOpts] + ) + of Port -> collect_port(Port, []) catch error:Reason -> {error, {spawn_failed, Exe, Reason}} @@ -242,7 +259,11 @@ collect_port(Port, Acc) -> {Port, {exit_status, Code}} -> {error, {exit_code, Code, iolist_to_binary(lists:reverse(Acc))}} after 300000 -> - try port_close(Port) catch _:_ -> ok end, + try + port_close(Port) + catch + _:_ -> ok + end, {error, timeout} end. @@ -270,7 +291,15 @@ activate_venv(VenvPath) -> VenvBin = py_util:to_binary(VenvPath), %% Find site-packages directory dynamically (venv may use different Python version) %% Uses a single expression to avoid multiline code issues - FindSitePackages = <<"(lambda vp: __import__('os').path.join(vp, 'Lib', 'site-packages') if __import__('os').path.exists(__import__('os').path.join(vp, 'Lib', 'site-packages')) else next((sp for name in (__import__('os').listdir(__import__('os').path.join(vp, 'lib')) if __import__('os').path.isdir(__import__('os').path.join(vp, 'lib')) else []) if name.startswith('python') for sp in [__import__('os').path.join(vp, 'lib', name, 'site-packages')] if __import__('os').path.isdir(sp)), None))(_venv_path)">>, + FindSitePackages = + << + "(lambda vp: __import__('os').path.join(vp, 'Lib', 'site-packages') if " + "__import__('os').path.exists(__import__('os').path.join(vp, 'Lib', 'site-packages')) else " + "next((sp for name in (__import__('os').listdir(__import__('os').path.join(vp, 'lib')) if " + "__import__('os').path.isdir(__import__('os').path.join(vp, 'lib')) else []) if " + "name.startswith('python') for sp in [__import__('os').path.join(vp, 'lib', name, " + "'site-packages')] if __import__('os').path.isdir(sp)), None))(_venv_path)" + >>, case py:eval(FindSitePackages, #{<<"_venv_path">> => VenvBin}) of {ok, SitePackages} when SitePackages =/= none, SitePackages =/= null -> activate_venv_with_site_packages(VenvBin, SitePackages); @@ -286,17 +315,26 @@ activate_venv_with_site_packages(VenvBin, SitePackages) -> case py:eval(<<"__import__('os').path.isdir(sp)">>, #{sp => SitePackages}) of {ok, true} -> %% Save original path if not already saved - {ok, _} = py:eval(<<"setattr(__import__('sys'), '_original_path', __import__('sys').path.copy()) if not hasattr(__import__('sys'), '_original_path') else None">>), + {ok, _} = py:eval( + << + "setattr(__import__('sys'), '_original_path', __import__('sys').path.copy()) if not " + "hasattr(__import__('sys'), '_original_path') else None" + >> + ), %% Set venv info {ok, _} = py:eval(<<"setattr(__import__('sys'), '_active_venv', vp)">>, #{vp => VenvBin}), - {ok, _} = py:eval(<<"setattr(__import__('sys'), '_venv_site_packages', sp)">>, #{sp => SitePackages}), + {ok, _} = py:eval(<<"setattr(__import__('sys'), '_venv_site_packages', sp)">>, #{ + sp => SitePackages + }), %% Add site-packages and process .pth files (editable installs) %% Note: We embed the site-packages path directly since exec doesn't support %% variables and sys attributes may not persist across calls in subinterpreters SitePackagesStr = binary_to_list(SitePackages), ExecCode = iolist_to_binary([ <<"import site as _site, sys as _sys\n">>, - <<"_sp = '">>, escape_python_string(SitePackagesStr), <<"'\n">>, + <<"_sp = '">>, + escape_python_string(SitePackagesStr), + <<"'\n">>, <<"_b = frozenset(_sys.path)\n">>, <<"_site.addsitedir(_sp)\n">>, <<"_sys.path[:] = [p for p in _sys.path if p not in _b] + [p for p in _sys.path if p in _b]\n">>, @@ -312,13 +350,14 @@ activate_venv_with_site_packages(VenvBin, SitePackages) -> %% @private Escape a string for embedding in Python code escape_python_string(Str) -> - lists:flatmap(fun($') -> "\\'"; - ($\\) -> "\\\\"; - (C) -> [C] - end, Str). - - - + lists:flatmap( + fun + ($') -> "\\'"; + ($\\) -> "\\\\"; + (C) -> [C] + end, + Str + ). %% @doc Deactivate the current virtual environment. %% Restores sys.path to its original state. @@ -326,12 +365,21 @@ escape_python_string(Str) -> deactivate_venv() -> case py:eval(<<"hasattr(__import__('sys'), '_original_path')">>) of {ok, true} -> - ok = py:exec(<<"import sys as _sys\n" - "_sys.path[:] = _sys._original_path\n" - "del _sys\n">>), + ok = py:exec(<< + "import sys as _sys\n" + "_sys.path[:] = _sys._original_path\n" + "del _sys\n" + >>), {ok, _} = py:eval(<<"delattr(__import__('sys'), '_original_path')">>), - {ok, _} = py:eval(<<"delattr(__import__('sys'), '_active_venv') if hasattr(__import__('sys'), '_active_venv') else None">>), - {ok, _} = py:eval(<<"delattr(__import__('sys'), '_venv_site_packages') if hasattr(__import__('sys'), '_venv_site_packages') else None">>), + {ok, _} = py:eval( + <<"delattr(__import__('sys'), '_active_venv') if hasattr(__import__('sys'), '_active_venv') else None">> + ), + {ok, _} = py:eval( + << + "delattr(__import__('sys'), '_venv_site_packages') if hasattr(__import__('sys'), " + "'_venv_site_packages') else None" + >> + ), ok; {ok, false} -> ok; @@ -344,7 +392,11 @@ deactivate_venv() -> -spec venv_info() -> {ok, map() | none} | {error, term()}. venv_info() -> %% Check both attributes exist to handle partial activation/deactivation state - Code = <<"({'active': True, 'venv_path': __import__('sys')._active_venv, 'site_packages': __import__('sys')._venv_site_packages, 'sys_path': __import__('sys').path} if (hasattr(__import__('sys'), '_active_venv') and hasattr(__import__('sys'), '_venv_site_packages')) else {'active': False})">>, + Code = + << + "({'active': True, 'venv_path': __import__('sys')._active_venv, 'site_packages': " + "__import__('sys')._venv_site_packages, 'sys_path': __import__('sys').path} if " + "(hasattr(__import__('sys'), '_active_venv') and hasattr(__import__('sys'), " + "'_venv_site_packages')) else {'active': False})" + >>, py:eval(Code). - - diff --git a/test/py_SUITE.erl b/test/py_SUITE.erl index 5163d7e..1cc62d6 100644 --- a/test/py_SUITE.erl +++ b/test/py_SUITE.erl @@ -196,14 +196,18 @@ test_eval_complex_locals(_Config) -> {ok, <<"Alice">>} = py:eval(<<"data['name']">>, #{data => #{name => <<"Alice">>, age => 30}}), %% Test eval with nested structures - {ok, 42} = py:eval(<<"config['settings']['value']">>, - #{config => #{settings => #{value => 42}}}), + {ok, 42} = py:eval( + <<"config['settings']['value']">>, + #{config => #{settings => #{value => 42}}} + ), %% Test eval with multiple complex locals using default argument capture %% Note: Python's eval() locals aren't accessible in nested scopes (lambda/comprehension) %% Use default argument to capture the value: lambda x, m=multiplier: x * m - {ok, [2, 4, 6]} = py:eval(<<"list(map(lambda x, m=multiplier: x * m, items))">>, - #{items => [1, 2, 3], multiplier => 2}), + {ok, [2, 4, 6]} = py:eval( + <<"list(map(lambda x, m=multiplier: x * m, items))">>, + #{items => [1, 2, 3], multiplier => 2} + ), %% Test eval with multiple variables {ok, 6} = py:eval(<<"a + b + c">>, #{a => 1, b => 2, c => 3}), @@ -212,8 +216,10 @@ test_eval_complex_locals(_Config) -> {ok, 3} = py:eval(<<"len(word)">>, #{word => <<"foo">>}), %% Test eval with nested map access - {ok, <<"value">>} = py:eval(<<"obj['nested']['key']">>, - #{obj => #{nested => #{key => <<"value">>}}}), + {ok, <<"value">>} = py:eval( + <<"obj['nested']['key']">>, + #{obj => #{nested => #{key => <<"value">>}}} + ), ok. @@ -221,10 +227,11 @@ test_exec(_Config) -> %% Test exec - just ensure it doesn't fail %% Note: exec runs on any worker, subsequent calls may go to different workers ok = py:exec(<<"x = 42">>), - ok = py:exec(<<" -def my_func(): - pass -">>), + ok = py:exec(<< + "\n" + "def my_func():\n" + " pass\n" + >>), ok. test_cast(_Config) -> @@ -233,8 +240,16 @@ test_cast(_Config) -> ok = py:cast(erlang, send, [Self, {<<"result">>, <<"msg1">>}]), ok = py:cast(erlang, send, [Self, {<<"result">>, <<"msg2">>}]), %% Wait for results (order may vary) - R1 = receive {<<"result">>, V1} -> V1 after 5000 -> ct:fail(timeout1) end, - R2 = receive {<<"result">>, V2} -> V2 after 5000 -> ct:fail(timeout2) end, + R1 = + receive + {<<"result">>, V1} -> V1 + after 5000 -> ct:fail(timeout1) + end, + R2 = + receive + {<<"result">>, V2} -> V2 + after 5000 -> ct:fail(timeout2) + end, true = lists:sort([R1, R2]) =:= [<<"msg1">>, <<"msg2">>], ok. @@ -386,7 +401,9 @@ test_stream_function(_Config) -> %% Fibonacci generator - compute fibonacci sequence using lambda wrapper %% (as documented pattern for inline generators) - {ok, Fib} = py:stream_eval(<<"(lambda: ((fib := [0, 1]), [fib.append(fib[-1] + fib[-2]) for _ in range(8)], iter(fib))[-1])()">>), + {ok, Fib} = py:stream_eval( + <<"(lambda: ((fib := [0, 1]), [fib.append(fib[-1] + fib[-2]) for _ in range(8)], iter(fib))[-1])()">> + ), ct:pal("Fibonacci result: ~p~n", [Fib]), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] = Fib, @@ -403,7 +420,9 @@ test_stream_function(_Config) -> [3, 4, 5] = FilterResult, %% Test batching generator (as documented in streaming.md) - {ok, Batches} = py:stream_eval(<<"(lambda data, size: (data[i:i+size] for i in range(0, len(data), size)))([1,2,3,4,5,6,7], 3)">>), + {ok, Batches} = py:stream_eval( + <<"(lambda data, size: (data[i:i+size] for i in range(0, len(data), size)))([1,2,3,4,5,6,7], 3)">> + ), ct:pal("Batches: ~p~n", [Batches]), [[1, 2, 3], [4, 5, 6], [7]] = Batches, @@ -567,26 +586,29 @@ test_erlang_import_syntax(_Config) -> py:register_function(greet, fun([Name]) -> <<"Hello, ", Name/binary>> end), %% Test basic import - will fail with AssertionError if result is wrong - ok = py:exec(<<" -from erlang import add -result = add(10, 20) -assert result == 30, f'Expected 30, got {result}' -">>), + ok = py:exec(<< + "\n" + "from erlang import add\n" + "result = add(10, 20)\n" + "assert result == 30, f'Expected 30, got {result}'\n" + >>), %% Test import with alias - ok = py:exec(<<" -from erlang import add as my_add -result = my_add(40, 60) -assert result == 100, f'Expected 100, got {result}' -">>), + ok = py:exec(<< + "\n" + "from erlang import add as my_add\n" + "result = my_add(40, 60)\n" + "assert result == 100, f'Expected 100, got {result}'\n" + >>), %% Test importing and using a string function %% Note: Erlang binary comes back as Python str (due to conversion) - ok = py:exec(<<" -from erlang import greet -result = greet('World') -assert result == 'Hello, World' or result == b'Hello, World', f'Expected \"Hello, World\", got {result}' -">>), + ok = py:exec(<< + "\n" + "from erlang import greet\n" + "result = greet('World')\n" + "assert result == 'Hello, World' or result == b'Hello, World', f'Expected \"Hello, World\", got {result}'\n" + >>), %% Cleanup py:unregister_function(add), @@ -671,7 +693,9 @@ test_parallel_execution(_Config) -> 4 = length(Results), ok; {error, Reason} -> - ct:pal("Parallel execution failed: ~p (may be expected on some setups)~n", [Reason]), + ct:pal("Parallel execution failed: ~p (may be expected on some setups)~n", [ + Reason + ]), ok end; false -> @@ -687,7 +711,9 @@ test_venv(_Config) -> TmpDir = <<"/tmp/erlang_python_test_venv">>, %% Get Python version for site-packages path - {ok, PyVer} = py:eval(<<"f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'">>), + {ok, PyVer} = py:eval( + <<"f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'">> + ), %% Create minimal venv structure using os.makedirs SitePackages = <>, @@ -726,7 +752,9 @@ test_venv_pth(_Config) -> TmpDir = <<"/tmp/erlang_python_test_venv_pth">>, PkgSrc = <<"/tmp/erlang_python_test_pth_src">>, - {ok, PyVer} = py:eval(<<"f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'">>), + {ok, PyVer} = py:eval( + <<"f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'">> + ), SitePackages = <>, %% Create fake venv with a .pth file pointing at PkgSrc @@ -802,15 +830,24 @@ test_semaphore_concurrent(_Config) -> NumProcs = 20, %% Spawn processes that each acquire, sleep, and release - Pids = [spawn_link(fun() -> - ok = py_semaphore:acquire(5000), - timer:sleep(10), - ok = py_semaphore:release(), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + ok = py_semaphore:acquire(5000), + timer:sleep(10), + ok = py_semaphore:release(), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], %% Wait for all to complete - [receive {done, Pid} -> ok after 10000 -> ct:fail({timeout, Pid}) end || Pid <- Pids], + [ + receive + {done, Pid} -> ok + after 10000 -> ct:fail({timeout, Pid}) + end + || Pid <- Pids + ], %% Current should be back to 0 (or initial state) timer:sleep(50), @@ -838,11 +875,12 @@ test_semaphore_timeout(_Config) -> Parent ! {acquire_result, Result} end), - Result = receive - {acquire_result, R} -> R - after 2000 -> - ct:fail(timeout_waiting_for_result) - end, + Result = + receive + {acquire_result, R} -> R + after 2000 -> + ct:fail(timeout_waiting_for_result) + end, %% Should have gotten error {error, max_concurrent} = Result, @@ -867,26 +905,35 @@ test_semaphore_rate_limiting(_Config) -> MaxSeen = atomics:new(1, [{signed, false}]), NumProcs = 10, - Pids = [spawn_link(fun() -> - ok = py_semaphore:acquire(10000), - atomics:add(Counter, 1, 1), - Cur = atomics:get(Counter, 1), - - %% Update max seen - OldMax = atomics:get(MaxSeen, 1), - case Cur > OldMax of - true -> atomics:put(MaxSeen, 1, Cur); - false -> ok - end, - - timer:sleep(50), - atomics:sub(Counter, 1, 1), - ok = py_semaphore:release(), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + ok = py_semaphore:acquire(10000), + atomics:add(Counter, 1, 1), + Cur = atomics:get(Counter, 1), + + %% Update max seen + OldMax = atomics:get(MaxSeen, 1), + case Cur > OldMax of + true -> atomics:put(MaxSeen, 1, Cur); + false -> ok + end, + + timer:sleep(50), + atomics:sub(Counter, 1, 1), + ok = py_semaphore:release(), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], %% Wait for all - [receive {done, Pid} -> ok after 30000 -> ct:fail({timeout, Pid}) end || Pid <- Pids], + [ + receive + {done, Pid} -> ok + after 30000 -> ct:fail({timeout, Pid}) + end + || Pid <- Pids + ], %% Check that max concurrent never exceeded limit MaxConcurrent = atomics:get(MaxSeen, 1), @@ -915,18 +962,20 @@ test_overload_protection(_Config) -> Parent ! {call_result, Result} end), - Result = receive - {call_result, R} -> R - after 2000 -> - ct:fail(timeout_waiting_for_result) - end, + Result = + receive + {call_result, R} -> R + after 2000 -> + ct:fail(timeout_waiting_for_result) + end, ct:pal("Overload result: ~p~n", [Result]), %% Should be overloaded error case Result of {error, {overloaded, _, _}} -> ok; - {error, timeout} -> ok; %% Also acceptable + %% Also acceptable + {error, timeout} -> ok; Other -> ct:fail({unexpected_result, Other}) end, @@ -942,36 +991,40 @@ test_shared_state(_Config) -> {ok, #{value := 42}} = py:state_fetch(<<"test_key">>), %% Test from Python side - set from Python, read from Erlang - ok = py:exec(<<" -from erlang import state_set -state_set('python_key', {'message': 'hello from python', 'numbers': [1, 2, 3]}) -">>), + ok = py:exec(<< + "\n" + "from erlang import state_set\n" + "state_set('python_key', {'message': 'hello from python', 'numbers': [1, 2, 3]})\n" + >>), {ok, Result} = py:state_fetch(<<"python_key">>), ct:pal("State from Python: ~p~n", [Result]), #{<<"message">> := <<"hello from python">>, <<"numbers">> := [1, 2, 3]} = Result, %% Test from Python side - read state set from Erlang ok = py:state_store(<<"erlang_key">>, #{count => 100}), - ok = py:exec(<<" -from erlang import state_get -data = state_get('erlang_key') -assert data == {'count': 100}, f'Expected {{count: 100}}, got {data}' -">>), + ok = py:exec(<< + "\n" + "from erlang import state_get\n" + "data = state_get('erlang_key')\n" + "assert data == {'count': 100}, f'Expected {{count: 100}}, got {data}'\n" + >>), %% Test state_keys from Python - ok = py:exec(<<" -from erlang import state_keys -keys = state_keys() -assert 'test_key' in keys, f'Expected test_key in {keys}' -assert 'python_key' in keys, f'Expected python_key in {keys}' -assert 'erlang_key' in keys, f'Expected erlang_key in {keys}' -">>), + ok = py:exec(<< + "\n" + "from erlang import state_keys\n" + "keys = state_keys()\n" + "assert 'test_key' in keys, f'Expected test_key in {keys}'\n" + "assert 'python_key' in keys, f'Expected python_key in {keys}'\n" + "assert 'erlang_key' in keys, f'Expected erlang_key in {keys}'\n" + >>), %% Test state_delete from Python - ok = py:exec(<<" -from erlang import state_delete -state_delete('python_key') -">>), + ok = py:exec(<< + "\n" + "from erlang import state_delete\n" + "state_delete('python_key')\n" + >>), {error, not_found} = py:state_fetch(<<"python_key">>), %% Test state_clear @@ -986,23 +1039,24 @@ state_delete('python_key') 6 = py:state_decr(<<"counter">>, 5), %% Test atomic counters from Python - ok = py:exec(<<" -from erlang import state_incr, state_decr - -# Increment -val = state_incr('py_counter') -assert val == 1, f'Expected 1, got {val}' - -val = state_incr('py_counter', 5) -assert val == 6, f'Expected 6, got {val}' - -# Decrement -val = state_decr('py_counter') -assert val == 5, f'Expected 5, got {val}' - -val = state_decr('py_counter', 3) -assert val == 2, f'Expected 2, got {val}' -">>), + ok = py:exec(<< + "\n" + "from erlang import state_incr, state_decr\n" + "\n" + "# Increment\n" + "val = state_incr('py_counter')\n" + "assert val == 1, f'Expected 1, got {val}'\n" + "\n" + "val = state_incr('py_counter', 5)\n" + "assert val == 6, f'Expected 6, got {val}'\n" + "\n" + "# Decrement\n" + "val = state_decr('py_counter')\n" + "assert val == 5, f'Expected 5, got {val}'\n" + "\n" + "val = state_decr('py_counter', 3)\n" + "assert val == 2, f'Expected 2, got {val}'\n" + >>), {ok, 2} = py:state_fetch(<<"py_counter">>), %% Cleanup @@ -1061,8 +1115,14 @@ test_process_env_isolation(_Config) -> end), %% Wait for both processes to complete - receive {proc_a, ok} -> ok after 5000 -> ct:fail("Process A timed out") end, - receive {proc_b, ok} -> ok after 5000 -> ct:fail("Process B timed out") end, + receive + {proc_a, ok} -> ok + after 5000 -> ct:fail("Process A timed out") + end, + receive + {proc_b, ok} -> ok + after 5000 -> ct:fail("Process B timed out") + end, ct:pal("Process isolation test passed~n"), ok. @@ -1115,7 +1175,8 @@ test_process_env_cleanup(_Config) -> %% Spawn a process that creates a large list spawn(fun() -> ok = py:exec(<<"big = list(range(1000000))">>), - timer:sleep(50) % Let it exist briefly + % Let it exist briefly + timer:sleep(50) end), %% Wait for the process to exit @@ -1183,8 +1244,9 @@ test_shared_dict_types(_Config) -> Retrieved = py:shared_dict_get(SD, <<"map">>), ct:pal("Map: ~p, Retrieved: ~p~n", [Map, Retrieved]), %% Note: Keys may be converted to Python strings and back - true = maps:get(<<"foo">>, Retrieved) =:= <<"bar">> orelse - maps:get(foo, Retrieved) =:= <<"bar">>, + true = + maps:get(<<"foo">>, Retrieved) =:= <<"bar">> orelse + maps:get(foo, Retrieved) =:= <<"bar">>, %% List List = [1, 2, 3, <<"four">>, 5.0], @@ -1227,11 +1289,12 @@ test_shared_dict_process_death(_Config) -> end), %% Get the SharedDict reference - SDRef = receive - {sd_ref, Ref} -> Ref - after 5000 -> - error(timeout_waiting_for_sd_ref) - end, + SDRef = + receive + {sd_ref, Ref} -> Ref + after 5000 -> + error(timeout_waiting_for_sd_ref) + end, ct:pal("Got SharedDict ref from child: ~p~n", [SDRef]), @@ -1259,28 +1322,31 @@ test_shared_dict_python_access(_Config) -> %% First, store the handle in Python's global namespace using eval %% We use eval with locals to pass the handle, then store it globally - {ok, _} = py:eval(<<"(globals().__setitem__('_sd_handle', handle), None)[-1]">>, - #{<<"handle">> => SD}), + {ok, _} = py:eval( + <<"(globals().__setitem__('_sd_handle', handle), None)[-1]">>, + #{<<"handle">> => SD} + ), %% Now execute code that uses the stored handle - Code = <<" -from erlang import SharedDict -sd = SharedDict(_sd_handle) - -# Read value set from Erlang -config = sd['config'] -result_port = config.get('port') or config.get(b'port') - -# Set a value from Python -sd['python_key'] = {'set_from': 'python', 'value': 42} - -# Test contains -has_config = 'config' in sd -has_missing = 'missing' in sd - -# Test keys -key_count = len(sd.keys()) -">>, + Code = << + "\n" + "from erlang import SharedDict\n" + "sd = SharedDict(_sd_handle)\n" + "\n" + "# Read value set from Erlang\n" + "config = sd['config']\n" + "result_port = config.get('port') or config.get(b'port')\n" + "\n" + "# Set a value from Python\n" + "sd['python_key'] = {'set_from': 'python', 'value': 42}\n" + "\n" + "# Test contains\n" + "has_config = 'config' in sd\n" + "has_missing = 'missing' in sd\n" + "\n" + "# Test keys\n" + "key_count = len(sd.keys())\n" + >>, ok = py:exec(Code), @@ -1373,14 +1439,26 @@ test_shared_dict_concurrent_same_key(_Config) -> %% Test 1: Concurrent writes to same key - verify no corruption %% Each process writes its process number repeatedly - Pids1 = [spawn_link(fun() -> - lists:foreach(fun(_) -> - ok = py:shared_dict_set(SD, <<"shared_key">>, N) - end, lists:seq(1, WritesPerProc)), - Parent ! {done_write, self()} - end) || N <- lists:seq(1, NumProcs)], + Pids1 = [ + spawn_link(fun() -> + lists:foreach( + fun(_) -> + ok = py:shared_dict_set(SD, <<"shared_key">>, N) + end, + lists:seq(1, WritesPerProc) + ), + Parent ! {done_write, self()} + end) + || N <- lists:seq(1, NumProcs) + ], - [receive {done_write, Pid} -> ok after 30000 -> ct:fail({timeout, Pid}) end || Pid <- Pids1], + [ + receive + {done_write, Pid} -> ok + after 30000 -> ct:fail({timeout, Pid}) + end + || Pid <- Pids1 + ], %% Final value should be a valid process number (1-NumProcs) FinalWrite = py:shared_dict_get(SD, <<"shared_key">>), @@ -1392,27 +1470,51 @@ test_shared_dict_concurrent_same_key(_Config) -> ok = py:shared_dict_set(SD, <<"rw_key">>, 0), %% Half writers, half readers - WriterPids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - ok = py:shared_dict_set(SD, <<"rw_key">>, I) - end, lists:seq(1, WritesPerProc)), - Parent ! {done_writer, self()} - end) || _ <- lists:seq(1, NumProcs div 2)], - - ReaderPids = [spawn_link(fun() -> - Reads = [py:shared_dict_get(SD, <<"rw_key">>) || _ <- lists:seq(1, WritesPerProc)], - %% All reads should return integers (no corruption) - true = lists:all(fun is_integer/1, Reads), - Parent ! {done_reader, self()} - end) || _ <- lists:seq(1, NumProcs div 2)], - - [receive {done_writer, Pid} -> ok after 30000 -> ct:fail({timeout, Pid}) end || Pid <- WriterPids], - [receive {done_reader, Pid} -> ok after 30000 -> ct:fail({timeout, Pid}) end || Pid <- ReaderPids], + WriterPids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + ok = py:shared_dict_set(SD, <<"rw_key">>, I) + end, + lists:seq(1, WritesPerProc) + ), + Parent ! {done_writer, self()} + end) + || _ <- lists:seq(1, NumProcs div 2) + ], + + ReaderPids = [ + spawn_link(fun() -> + Reads = [py:shared_dict_get(SD, <<"rw_key">>) || _ <- lists:seq(1, WritesPerProc)], + %% All reads should return integers (no corruption) + true = lists:all(fun is_integer/1, Reads), + Parent ! {done_reader, self()} + end) + || _ <- lists:seq(1, NumProcs div 2) + ], + + [ + receive + {done_writer, Pid} -> ok + after 30000 -> ct:fail({timeout, Pid}) + end + || Pid <- WriterPids + ], + [ + receive + {done_reader, Pid} -> ok + after 30000 -> ct:fail({timeout, Pid}) + end + || Pid <- ReaderPids + ], %% Test 3: Rapid key updates - verify latest value is consistent type - lists:foreach(fun(I) -> - ok = py:shared_dict_set(SD, <<"type_key">>, I) - end, lists:seq(1, 1000)), + lists:foreach( + fun(I) -> + ok = py:shared_dict_set(SD, <<"type_key">>, I) + end, + lists:seq(1, 1000) + ), TypeVal = py:shared_dict_get(SD, <<"type_key">>), true = is_integer(TypeVal), @@ -1429,32 +1531,43 @@ test_shared_dict_concurrent_different_keys(_Config) -> NumOps = 50, %% Spawn processes, each writing to its own key - Pids = [spawn_link(fun() -> - Key = list_to_binary("key_" ++ integer_to_list(N)), - %% Write operations - lists:foreach(fun(I) -> - ok = py:shared_dict_set(SD, Key, I) - end, lists:seq(1, NumOps)), - %% Final value should be NumOps - Final = py:shared_dict_get(SD, Key), - Parent ! {done, self(), Key, Final} - end) || N <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + Key = list_to_binary("key_" ++ integer_to_list(N)), + %% Write operations + lists:foreach( + fun(I) -> + ok = py:shared_dict_set(SD, Key, I) + end, + lists:seq(1, NumOps) + ), + %% Final value should be NumOps + Final = py:shared_dict_get(SD, Key), + Parent ! {done, self(), Key, Final} + end) + || N <- lists:seq(1, NumProcs) + ], %% Wait for all and collect results - Results = [receive - {done, Pid, Key, Final} -> {Key, Final} - after 30000 -> - ct:fail({timeout, Pid}) - end || Pid <- Pids], + Results = [ + receive + {done, Pid, Key, Final} -> {Key, Final} + after 30000 -> + ct:fail({timeout, Pid}) + end + || Pid <- Pids + ], %% Verify all keys have correct final value - lists:foreach(fun({Key, Final}) -> - case Final of - NumOps -> ok; - Other -> - ct:fail({wrong_value, Key, expected, NumOps, got, Other}) - end - end, Results), + lists:foreach( + fun({Key, Final}) -> + case Final of + NumOps -> ok; + Other -> ct:fail({wrong_value, Key, expected, NumOps, got, Other}) + end + end, + Results + ), %% Verify all keys are present Keys = py:shared_dict_keys(SD), @@ -1475,24 +1588,33 @@ test_shared_dict_concurrent_mixed(_Config) -> ok = py:shared_dict_set(SD, <<"shared_2">>, 0), %% Spawn processes that do mixed operations - Pids = [spawn_link(fun() -> - UniqueKey = list_to_binary("unique_" ++ integer_to_list(N)), - mixed_operations(SD, UniqueKey, NumOps), - Parent ! {done, self(), UniqueKey} - end) || N <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + UniqueKey = list_to_binary("unique_" ++ integer_to_list(N)), + mixed_operations(SD, UniqueKey, NumOps), + Parent ! {done, self(), UniqueKey} + end) + || N <- lists:seq(1, NumProcs) + ], %% Wait for all processes - UniqueKeys = [receive - {done, Pid, Key} -> Key - after 30000 -> - ct:fail({timeout, Pid}) - end || Pid <- Pids], + UniqueKeys = [ + receive + {done, Pid, Key} -> Key + after 30000 -> + ct:fail({timeout, Pid}) + end + || Pid <- Pids + ], %% Verify all unique keys exist with valid values - lists:foreach(fun(Key) -> - Value = py:shared_dict_get(SD, Key), - true = is_integer(Value) andalso Value >= 0 - end, UniqueKeys), + lists:foreach( + fun(Key) -> + Value = py:shared_dict_get(SD, Key), + true = is_integer(Value) andalso Value >= 0 + end, + UniqueKeys + ), %% Verify shared keys are integers (may have any value due to races) Shared1 = py:shared_dict_get(SD, <<"shared_1">>), @@ -1505,7 +1627,8 @@ test_shared_dict_concurrent_mixed(_Config) -> ok. %% Helper for mixed operations -mixed_operations(_SD, _UniqueKey, 0) -> ok; +mixed_operations(_SD, _UniqueKey, 0) -> + ok; mixed_operations(SD, UniqueKey, N) -> %% Mix of operations case N rem 4 of @@ -1530,31 +1653,40 @@ test_shared_dict_benchmark(_Config) -> {ok, SD} = py:shared_dict_new(), %% Warmup - lists:foreach(fun(I) -> - Key = list_to_binary("warmup_" ++ integer_to_list(I)), - ok = py:shared_dict_set(SD, Key, I), - I = py:shared_dict_get(SD, Key) - end, lists:seq(1, 100)), + lists:foreach( + fun(I) -> + Key = list_to_binary("warmup_" ++ integer_to_list(I)), + ok = py:shared_dict_set(SD, Key, I), + I = py:shared_dict_get(SD, Key) + end, + lists:seq(1, 100) + ), %% Single process benchmark NumOps = 1000, %% Benchmark SET operations SetStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(I) -> - Key = list_to_binary("bench_" ++ integer_to_list(I rem 100)), - ok = py:shared_dict_set(SD, Key, I) - end, lists:seq(1, NumOps)), + lists:foreach( + fun(I) -> + Key = list_to_binary("bench_" ++ integer_to_list(I rem 100)), + ok = py:shared_dict_set(SD, Key, I) + end, + lists:seq(1, NumOps) + ), SetEnd = erlang:monotonic_time(microsecond), SetDuration = SetEnd - SetStart, SetOpsPerSec = (NumOps * 1000000) div max(1, SetDuration), %% Benchmark GET operations GetStart = erlang:monotonic_time(microsecond), - lists:foreach(fun(I) -> - Key = list_to_binary("bench_" ++ integer_to_list(I rem 100)), - _ = py:shared_dict_get(SD, Key) - end, lists:seq(1, NumOps)), + lists:foreach( + fun(I) -> + Key = list_to_binary("bench_" ++ integer_to_list(I rem 100)), + _ = py:shared_dict_get(SD, Key) + end, + lists:seq(1, NumOps) + ), GetEnd = erlang:monotonic_time(microsecond), GetDuration = GetEnd - GetStart, GetOpsPerSec = (NumOps * 1000000) div max(1, GetDuration), @@ -1569,20 +1701,33 @@ test_shared_dict_benchmark(_Config) -> OpsPerProc = 500, ConcStart = erlang:monotonic_time(microsecond), - Pids = [spawn_link(fun() -> - lists:foreach(fun(I) -> - Key = list_to_binary("conc_" ++ integer_to_list(I rem 50)), - ok = py:shared_dict_set(SD, Key, I), - _ = py:shared_dict_get(SD, Key) - end, lists:seq(1, OpsPerProc)), - Parent ! {done, self()} - end) || _ <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + lists:foreach( + fun(I) -> + Key = list_to_binary("conc_" ++ integer_to_list(I rem 50)), + ok = py:shared_dict_set(SD, Key, I), + _ = py:shared_dict_get(SD, Key) + end, + lists:seq(1, OpsPerProc) + ), + Parent ! {done, self()} + end) + || _ <- lists:seq(1, NumProcs) + ], - [receive {done, Pid} -> ok after 30000 -> ct:fail({timeout, Pid}) end || Pid <- Pids], + [ + receive + {done, Pid} -> ok + after 30000 -> ct:fail({timeout, Pid}) + end + || Pid <- Pids + ], ConcEnd = erlang:monotonic_time(microsecond), ConcDuration = ConcEnd - ConcStart, - TotalConcOps = NumProcs * OpsPerProc * 2, % SET + GET per iteration + % SET + GET per iteration + TotalConcOps = NumProcs * OpsPerProc * 2, ConcOpsPerSec = (TotalConcOps * 1000000) div max(1, ConcDuration), ct:pal("~n=== SharedDict Multi-Process Benchmark (~p procs) ===~n", [NumProcs]), diff --git a/test/py_actor_SUITE.erl b/test/py_actor_SUITE.erl index 6fc44c2..899214c 100644 --- a/test/py_actor_SUITE.erl +++ b/test/py_actor_SUITE.erl @@ -31,21 +31,22 @@ test_counter_actor(_Config) -> Ctx = py:context(), %% Initialize Counter class - ok = py:exec(Ctx, <<" -class Counter: - def __init__(self): - self.value = 0 - def increment(self): - self.value += 1 - return self.value - def decrement(self): - self.value -= 1 - return self.value - def get(self): - return self.value - -counter = Counter() -">>), + ok = py:exec(Ctx, << + "\n" + "class Counter:\n" + " def __init__(self):\n" + " self.value = 0\n" + " def increment(self):\n" + " self.value += 1\n" + " return self.value\n" + " def decrement(self):\n" + " self.value -= 1\n" + " return self.value\n" + " def get(self):\n" + " return self.value\n" + "\n" + "counter = Counter()\n" + >>), %% Test increment {ok, 1} = py:eval(Ctx, <<"counter.increment()">>), @@ -99,10 +100,14 @@ test_reset_via_termination(_Config) -> ok = py:exec(Ctx, <<"reset_test = 42">>), {ok, 42} = py:eval(Ctx, <<"reset_test">>), Self ! {ready, self()}, - receive stop -> ok end + receive + stop -> ok + end end), - receive {ready, Pid1} -> ok end, + receive + {ready, Pid1} -> ok + end, %% Stop the process Pid1 ! stop, diff --git a/test/py_api_SUITE.erl b/test/py_api_SUITE.erl index 389ded9..9a1c429 100644 --- a/test/py_api_SUITE.erl +++ b/test/py_api_SUITE.erl @@ -68,13 +68,21 @@ end_per_suite(_Config) -> init_per_testcase(_TestCase, Config) -> %% Ensure fresh contexts are available for each test - try py:stop_contexts() catch _:_ -> ok end, + try + py:stop_contexts() + catch + _:_ -> ok + end, {ok, _} = py:start_contexts(), Config. end_per_testcase(_TestCase, _Config) -> %% Clean up after each test - try py:stop_contexts() catch _:_ -> ok end, + try + py:stop_contexts() + catch + _:_ -> ok + end, ok. %% ============================================================================ @@ -190,18 +198,24 @@ test_start_stop_contexts(_Config) -> true = length(Contexts1) > 0, %% All contexts should be alive - lists:foreach(fun(Ctx) -> - true = is_process_alive(Ctx) - end, Contexts1), + lists:foreach( + fun(Ctx) -> + true = is_process_alive(Ctx) + end, + Contexts1 + ), %% Stop ok = py:stop_contexts(), %% Wait for contexts to die timer:sleep(100), - lists:foreach(fun(Ctx) -> - false = is_process_alive(Ctx) - end, Contexts1), + lists:foreach( + fun(Ctx) -> + false = is_process_alive(Ctx) + end, + Contexts1 + ), %% Start with custom settings {ok, Contexts2} = py:start_contexts(#{contexts => 2}), @@ -237,13 +251,14 @@ test_explicit_bytes(_Config) -> Ctx = py:context(1), %% Define test functions - ok = py:exec(Ctx, <<" -def check_type(val): - return type(val).__name__ - -def check_bytes_value(val): - return val == b'hello' -">>), + ok = py:exec(Ctx, << + "\n" + "def check_type(val):\n" + " return type(val).__name__\n" + "\n" + "def check_bytes_value(val):\n" + " return val == b'hello'\n" + >>), %% Regular binary -> str (default UTF-8 decoding) {ok, <<"str">>} = py:eval(Ctx, <<"check_type(val)">>, #{<<"val">> => <<"hello">>}), diff --git a/test/py_async_e2e_SUITE.erl b/test/py_async_e2e_SUITE.erl index f244a37..9718991 100644 --- a/test/py_async_e2e_SUITE.erl +++ b/test/py_async_e2e_SUITE.erl @@ -49,111 +49,115 @@ end_per_testcase(_TestCase, _Config) -> %% Test basic asyncio.sleep timing test_asyncio_sleep(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import time -import erlang - -async def timed_sleep(): - start = time.monotonic() - await asyncio.sleep(0.05) - return time.monotonic() - start - -elapsed = erlang.run(timed_sleep()) -assert elapsed >= 0.04, f'Expected >= 0.04s, got {elapsed:.3f}s' -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import time\n" + "import erlang\n" + "\n" + "async def timed_sleep():\n" + " start = time.monotonic()\n" + " await asyncio.sleep(0.05)\n" + " return time.monotonic() - start\n" + "\n" + "elapsed = erlang.run(timed_sleep())\n" + "assert elapsed >= 0.04, f'Expected >= 0.04s, got {elapsed:.3f}s'\n" + >>), ok. %% Test asyncio.gather runs tasks concurrently test_asyncio_gather(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import time -import erlang - -async def task(val): - await asyncio.sleep(0.05) - return val - -async def main(): - start = time.monotonic() - r = await asyncio.gather(task(1), task(2), task(3)) - elapsed = time.monotonic() - start - assert list(r) == [1, 2, 3], f'Expected [1, 2, 3], got {list(r)}' - # Allow more time on CI (0.3s instead of 0.15s) - assert elapsed < 0.3, f'Expected < 0.3s, got {elapsed:.3f}s' - -erlang.run(main()) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import time\n" + "import erlang\n" + "\n" + "async def task(val):\n" + " await asyncio.sleep(0.05)\n" + " return val\n" + "\n" + "async def main():\n" + " start = time.monotonic()\n" + " r = await asyncio.gather(task(1), task(2), task(3))\n" + " elapsed = time.monotonic() - start\n" + " assert list(r) == [1, 2, 3], f'Expected [1, 2, 3], got {list(r)}'\n" + " # Allow more time on CI (0.3s instead of 0.15s)\n" + " assert elapsed < 0.3, f'Expected < 0.3s, got {elapsed:.3f}s'\n" + "\n" + "erlang.run(main())\n" + >>), ok. %% Test TCP echo server/client using asyncio test_asyncio_tcp_echo(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang - -async def handler(r, w): - data = await r.read(100) - w.write(data) - await w.drain() - w.close() - await w.wait_closed() - -async def test(): - srv = await asyncio.start_server(handler, '127.0.0.1', 0) - port = srv.sockets[0].getsockname()[1] - r, w = await asyncio.open_connection('127.0.0.1', port) - w.write(b'hello') - await w.drain() - resp = await r.read(100) - w.close() - await w.wait_closed() - srv.close() - await srv.wait_closed() - assert resp == b'hello', f'Expected b\"hello\", got {resp}' - -erlang.run(test()) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "\n" + "async def handler(r, w):\n" + " data = await r.read(100)\n" + " w.write(data)\n" + " await w.drain()\n" + " w.close()\n" + " await w.wait_closed()\n" + "\n" + "async def test():\n" + " srv = await asyncio.start_server(handler, '127.0.0.1', 0)\n" + " port = srv.sockets[0].getsockname()[1]\n" + " r, w = await asyncio.open_connection('127.0.0.1', port)\n" + " w.write(b'hello')\n" + " await w.drain()\n" + " resp = await r.read(100)\n" + " w.close()\n" + " await w.wait_closed()\n" + " srv.close()\n" + " await srv.wait_closed()\n" + " assert resp == b'hello', f'Expected b\"hello\", got {resp}'\n" + "\n" + "erlang.run(test())\n" + >>), ok. %% Test multiple concurrent TCP connections test_asyncio_concurrent_tcp(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang - -async def handler(r, w): - data = await r.read(100) - w.write(b're:' + data) - await w.drain() - w.close() - await w.wait_closed() - -async def req(port, msg): - r, w = await asyncio.open_connection('127.0.0.1', port) - w.write(msg) - await w.drain() - resp = await r.read(100) - w.close() - await w.wait_closed() - return resp - -async def test(): - srv = await asyncio.start_server(handler, '127.0.0.1', 0) - port = srv.sockets[0].getsockname()[1] - results = await asyncio.gather( - req(port, b'1'), - req(port, b'2'), - req(port, b'3') - ) - srv.close() - await srv.wait_closed() - assert set(results) == {b're:1', b're:2', b're:3'}, f'Expected {{b\"re:1\", b\"re:2\", b\"re:3\"}}, got {set(results)}' - -erlang.run(test()) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "\n" + "async def handler(r, w):\n" + " data = await r.read(100)\n" + " w.write(b're:' + data)\n" + " await w.drain()\n" + " w.close()\n" + " await w.wait_closed()\n" + "\n" + "async def req(port, msg):\n" + " r, w = await asyncio.open_connection('127.0.0.1', port)\n" + " w.write(msg)\n" + " await w.drain()\n" + " resp = await r.read(100)\n" + " w.close()\n" + " await w.wait_closed()\n" + " return resp\n" + "\n" + "async def test():\n" + " srv = await asyncio.start_server(handler, '127.0.0.1', 0)\n" + " port = srv.sockets[0].getsockname()[1]\n" + " results = await asyncio.gather(\n" + " req(port, b'1'),\n" + " req(port, b'2'),\n" + " req(port, b'3')\n" + " )\n" + " srv.close()\n" + " await srv.wait_closed()\n" + " assert set(results) == {b're:1', b're:2', b're:3'}, f'Expected {{b\"re:1\", b\"re:2\", b\"re:3\"}}, got {set(results)}'\n" + "\n" + "erlang.run(test())\n" + >>), ok. diff --git a/test/py_async_task_SUITE.erl b/test/py_async_task_SUITE.erl index 0646832..6b91810 100644 --- a/test/py_async_task_SUITE.erl +++ b/test/py_async_task_SUITE.erl @@ -91,7 +91,8 @@ groups() -> []. init_per_suite(Config) -> application:ensure_all_started(erlang_python), - timer:sleep(500), % Allow event loop to initialize + % Allow event loop to initialize + timer:sleep(500), Config. end_per_suite(_Config) -> @@ -176,15 +177,21 @@ test_async_with_args(_Config) -> test_async_sleep(_Config) -> %% Test multiple quick operations in sequence %% (asyncio.sleep coroutines may need special loop driving) - Results = lists:map(fun(N) -> - Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), - {N, py_event_loop:await(Ref, 5000)} - end, lists:seq(1, 10)), + Results = lists:map( + fun(N) -> + Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), + {N, py_event_loop:await(Ref, 5000)} + end, + lists:seq(1, 10) + ), ct:log("Sequential sqrt results: ~p", [Results]), %% Verify all succeeded - lists:foreach(fun({N, {ok, R}}) -> - true = abs(R - float(N)) < 0.0001 - end, Results). + lists:foreach( + fun({N, {ok, R}}) -> + true = abs(R - float(N)) < 0.0001 + end, + Results + ). test_timer_event_triggering(_Config) -> %% Test that timer events properly trigger event loop processing. @@ -214,8 +221,10 @@ test_timer_event_triggering(_Config) -> %% Test concurrent async tasks with sleep ct:log("Testing concurrent async tasks with asyncio.sleep..."), - Refs = [py_event_loop:create_task(test_async_task, task_with_args, [N, N]) - || N <- lists:seq(1, 5)], + Refs = [ + py_event_loop:create_task(test_async_task, task_with_args, [N, N]) + || N <- lists:seq(1, 5) + ], Results = [py_event_loop:await(Ref, 5000) || Ref <- Refs], ct:log("Concurrent results: ~p", [Results]), @@ -280,45 +289,69 @@ test_concurrent_tasks(_Config) -> TasksPerProc = 5, %% Spawn processes that each submit tasks - Pids = [spawn_link(fun() -> - Results = [begin - Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), - {N, py_event_loop:await(Ref, 5000)} - end || N <- lists:seq(1, TasksPerProc)], - Parent ! {self(), Results} - end) || _ <- lists:seq(1, NumProcs)], + Pids = [ + spawn_link(fun() -> + Results = [ + begin + Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), + {N, py_event_loop:await(Ref, 5000)} + end + || N <- lists:seq(1, TasksPerProc) + ], + Parent ! {self(), Results} + end) + || _ <- lists:seq(1, NumProcs) + ], %% Collect all results - AllResults = [receive {Pid, R} -> R end || Pid <- Pids], + AllResults = [ + receive + {Pid, R} -> R + end + || Pid <- Pids + ], ct:log("Concurrent results count: ~p", [length(lists:flatten(AllResults))]), %% Verify all succeeded - lists:foreach(fun(Results) -> - lists:foreach(fun({N, {ok, R}}) -> - Expected = float(N), - true = abs(R - Expected) < 0.0001 - end, Results) - end, AllResults). + lists:foreach( + fun(Results) -> + lists:foreach( + fun({N, {ok, R}}) -> + Expected = float(N), + true = abs(R - Expected) < 0.0001 + end, + Results + ) + end, + AllResults + ). test_batch_tasks(_Config) -> %% Test submitting many tasks at once (tests batching) NumTasks = 100, %% Submit all tasks - Refs = [py_event_loop:create_task(math, sqrt, [float(N)]) - || N <- lists:seq(1, NumTasks)], + Refs = [ + py_event_loop:create_task(math, sqrt, [float(N)]) + || N <- lists:seq(1, NumTasks) + ], %% Await all results - Results = [{N, py_event_loop:await(Ref, 5000)} - || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs)], + Results = [ + {N, py_event_loop:await(Ref, 5000)} + || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs) + ], ct:log("Batch tasks completed: ~p", [length(Results)]), %% Verify all succeeded - lists:foreach(fun({N, {ok, R}}) -> - Expected = math:sqrt(N), - true = abs(R - Expected) < 0.0001 - end, Results). + lists:foreach( + fun({N, {ok, R}}) -> + Expected = math:sqrt(N), + true = abs(R - Expected) < 0.0001 + end, + Results + ). test_interleaved_sync_async(_Config) -> %% Test mixing different stdlib calls @@ -388,20 +421,27 @@ test_thread_local_event_loop(_Config) -> %% We verify this by running multiple concurrent async tasks - if the %% running loop context weren't set, task creation would fail. NumTasks = 20, - Refs = [py_event_loop:create_task(math, sqrt, [float(N * N)]) - || N <- lists:seq(1, NumTasks)], + Refs = [ + py_event_loop:create_task(math, sqrt, [float(N * N)]) + || N <- lists:seq(1, NumTasks) + ], %% Await all results - this exercises the event loop processing - Results = [{N, py_event_loop:await(Ref, 5000)} - || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs)], + Results = [ + {N, py_event_loop:await(Ref, 5000)} + || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs) + ], ct:log("Thread-local context test: ~p tasks completed", [length(Results)]), %% Verify all succeeded with correct results - lists:foreach(fun({N, {ok, R}}) -> - Expected = float(N), - true = abs(R - Expected) < 0.0001 - end, Results). + lists:foreach( + fun({N, {ok, R}}) -> + Expected = float(N), + true = abs(R - Expected) < 0.0001 + end, + Results + ). %% ============================================================================ %% Per-process namespace tests @@ -424,13 +464,14 @@ test_process_namespace_eval(_Config) -> test_process_namespace_async_func(_Config) -> %% Test defining an async function and calling it via create_task - ok = py_event_loop:exec(<<" -def double(x): - return x * 2 - -def add(a, b): - return a + b -">>), + ok = py_event_loop:exec(<< + "\n" + "def double(x):\n" + " return x * 2\n" + "\n" + "def add(a, b):\n" + " return a + b\n" + >>), %% Call the sync function via create_task with __main__ module Ref1 = py_event_loop:create_task('__main__', double, [21]), @@ -492,13 +533,14 @@ test_process_namespace_reentrant(_Config) -> %% This verifies the thread-local namespace is set correctly %% Define a variable and a function that uses it - ok = py_event_loop:exec(<<" -shared_value = 100 - -def use_shared(): - # Access shared_value from namespace - return shared_value + 23 -">>), + ok = py_event_loop:exec(<< + "\n" + "shared_value = 100\n" + "\n" + "def use_shared():\n" + " # Access shared_value from namespace\n" + " return shared_value + 23\n" + >>), %% Call the function via create_task - it should access the namespace Ref = py_event_loop:create_task('__main__', use_shared, []), @@ -507,12 +549,13 @@ def use_shared(): 123 = Result, %% Test with a function that modifies namespace - ok = py_event_loop:exec(<<" -def increment_shared(): - global shared_value - shared_value += 1 - return shared_value -">>), + ok = py_event_loop:exec(<< + "\n" + "def increment_shared():\n" + " global shared_value\n" + " shared_value += 1\n" + " return shared_value\n" + >>), Ref2 = py_event_loop:create_task('__main__', increment_shared, []), {ok, 101} = py_event_loop:await(Ref2, 5000), @@ -536,13 +579,14 @@ test_env_reuse_with_exec(_Config) -> %% Create a context and define a sync function via py:exec Ctx = py:context(1), - ok = py:exec(Ctx, <<" -def multiply(a, b): - return a * b - -def greet(name): - return f'Hello, {name}!' -">>), + ok = py:exec(Ctx, << + "\n" + "def multiply(a, b):\n" + " return a * b\n" + "\n" + "def greet(name):\n" + " return f'Hello, {name}!'\n" + >>), %% Call the functions via py_event_loop:run - should find them automatically {ok, Result1} = py_event_loop:run('__main__', multiply, [6, 7]), @@ -561,22 +605,23 @@ test_env_reuse_async_function(_Config) -> %% Create a context and define an async function Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio - -async def async_add(a, b): - await asyncio.sleep(0.01) - return a + b - -async def async_process(data): - # Simulate chunked processing - chunks = [] - for i in range(0, len(data), 4): - chunk = data[i:i+4] - await asyncio.sleep(0.001) - chunks.append(chunk) - return chunks -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def async_add(a, b):\n" + " await asyncio.sleep(0.01)\n" + " return a + b\n" + "\n" + "async def async_process(data):\n" + " # Simulate chunked processing\n" + " chunks = []\n" + " for i in range(0, len(data), 4):\n" + " chunk = data[i:i+4]\n" + " await asyncio.sleep(0.001)\n" + " chunks.append(chunk)\n" + " return chunks\n" + >>), %% Call async function via py_event_loop:run {ok, Sum} = py_event_loop:run('__main__', async_add, [10, 32]), @@ -599,16 +644,17 @@ test_env_reuse_spawn_task(_Config) -> %% Create a context and define a function that writes to a shared variable Ctx = py:context(1), - ok = py:exec(Ctx, <<" -spawn_test_results = [] - -def record_value(x): - spawn_test_results.append(x) - return x - -def get_results(): - return list(spawn_test_results) -">>), + ok = py:exec(Ctx, << + "\n" + "spawn_test_results = []\n" + "\n" + "def record_value(x):\n" + " spawn_test_results.append(x)\n" + " return x\n" + "\n" + "def get_results():\n" + " return list(spawn_test_results)\n" + >>), %% Use spawn_task to call the function (fire and forget) ok = py_event_loop:spawn_task('__main__', record_value, [42]), diff --git a/test/py_asyncio_compat_SUITE.erl b/test/py_asyncio_compat_SUITE.erl index 6de5c7e..b19215f 100644 --- a/test/py_asyncio_compat_SUITE.erl +++ b/test/py_asyncio_compat_SUITE.erl @@ -201,11 +201,23 @@ test_loop_helpers(Config) -> true -> PrivDir = ?config(priv_dir, Config), {ok, Ctx} = py_context:new(#{mode => owngil}), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n", - [PrivDir, PrivDir]))), - Result = py_context:call(Ctx, 'tests.ct_runner', run_tests, - [<<"tests.test_loop_helpers">>, <<"*">>], #{}, 120000), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n", + [PrivDir, PrivDir] + ) + ) + ), + Result = py_context:call( + Ctx, + 'tests.ct_runner', + run_tests, + [<<"tests.test_loop_helpers">>, <<"*">>], + #{}, + 120000 + ), py_context:stop(Ctx), case Result of {ok, Results} -> handle_test_results("tests.test_loop_helpers", <<"*">>, Results); @@ -282,8 +294,9 @@ setup_python_path(PrivDir) -> ok = py:exec(Ctx, <<"import sys, os">>), {ok, _} = py:call(Ctx, os, chdir, [PrivDirBin]), %% Insert the priv directory at the front of sys.path if not present - Code = <<"sys.path.insert(0, '", PrivDirBin/binary, "') if '", - PrivDirBin/binary, "' not in sys.path else None">>, + Code = + <<"sys.path.insert(0, '", PrivDirBin/binary, "') if '", PrivDirBin/binary, + "' not in sys.path else None">>, {ok, _} = py:eval(Ctx, Code), ok. @@ -306,7 +319,11 @@ run_python_tests(Module, Pattern, _Config) -> PerTestTimeout = 30.0, %% Use 10 minute timeout for overall test execution - case py:call(Ctx, 'tests.async_test_runner', run_tests, [ModuleBin, Pattern, PerTestTimeout], #{timeout => 600000}) of + case + py:call(Ctx, 'tests.async_test_runner', run_tests, [ModuleBin, Pattern, PerTestTimeout], #{ + timeout => 600000 + }) + of {ok, Results} -> handle_test_results(Module, Pattern, Results); {error, Reason} -> @@ -325,8 +342,10 @@ handle_test_results(Module, Pattern, Results) -> FailureDetails = maps:get(<<"failure_details">>, Results, []), %% Log the test output - ct:log("~s (~s): ~p tests run, ~p failures, ~p errors, ~p skipped~n~n~s", - [Module, Pattern, TestsRun, Failures, Errors, Skipped, Output]), + ct:log( + "~s (~s): ~p tests run, ~p failures, ~p errors, ~p skipped~n~n~s", + [Module, Pattern, TestsRun, Failures, Errors, Skipped, Output] + ), case Success of true -> @@ -344,16 +363,19 @@ handle_test_results(Module, Pattern, Results) -> FailureDetails ), %% Include first failure in the error for compact output - FirstFail = case FailureDetails of - [First|_] -> maps:get(<<"test">>, First, <<"unknown">>); - _ -> <<"unknown">> - end, - ct:fail({tests_failed, Module, Pattern, FirstFail, #{ - tests_run => TestsRun, - failures => Failures, - errors => Errors, - skipped => Skipped - }}) + FirstFail = + case FailureDetails of + [First | _] -> maps:get(<<"test">>, First, <<"unknown">>); + _ -> <<"unknown">> + end, + ct:fail( + {tests_failed, Module, Pattern, FirstFail, #{ + tests_run => TestsRun, + failures => Failures, + errors => Errors, + skipped => Skipped + }} + ) end. %% Convert to binary diff --git a/test/py_asyncio_policy_SUITE.erl b/test/py_asyncio_policy_SUITE.erl index 2203678..6515019 100644 --- a/test/py_asyncio_policy_SUITE.erl +++ b/test/py_asyncio_policy_SUITE.erl @@ -80,8 +80,10 @@ policy_install_skipped_on_3_14_plus(_Config) -> true -> Name = policy_class_name(), true = Name =/= <<"ErlangEventLoopPolicy">>, - ct:pal("Policy on 3.14+ is ~p (not ErlangEventLoopPolicy, as expected)", - [Name]), + ct:pal( + "Policy on 3.14+ is ~p (not ErlangEventLoopPolicy, as expected)", + [Name] + ), ok end. @@ -129,8 +131,9 @@ install_raises_on_3_14_plus(_Config) -> {ok, ErrMsg} = py:eval(<<"_install_err">>), true = is_binary(ErrMsg), true = byte_size(ErrMsg) > 0, - true = binary:match(ErrMsg, <<"3.14+">>) =/= nomatch - orelse binary:match(ErrMsg, <<"loop_factory">>) =/= nomatch, + true = + binary:match(ErrMsg, <<"3.14+">>) =/= nomatch orelse + binary:match(ErrMsg, <<"loop_factory">>) =/= nomatch, ok end. diff --git a/test/py_buffer_SUITE.erl b/test/py_buffer_SUITE.erl index 46baa48..4363422 100644 --- a/test/py_buffer_SUITE.erl +++ b/test/py_buffer_SUITE.erl @@ -32,24 +32,25 @@ asyncio_read_test/1 ]). -all() -> [ - create_buffer_test, - create_buffer_with_size_test, - write_read_test, - readline_test, - readlines_test, - seek_tell_test, - find_test, - memoryview_test, - buffer_grow_pinned_test, - iterator_test, - closed_buffer_test, - empty_buffer_test, - pass_to_python_test, - gc_refcount_test, - nonblock_read_test, - asyncio_read_test -]. +all() -> + [ + create_buffer_test, + create_buffer_with_size_test, + write_read_test, + readline_test, + readlines_test, + seek_tell_test, + find_test, + memoryview_test, + buffer_grow_pinned_test, + iterator_test, + closed_buffer_test, + empty_buffer_test, + pass_to_python_test, + gc_refcount_test, + nonblock_read_test, + asyncio_read_test + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -105,10 +106,11 @@ readline_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create buffer with multiple lines and close it - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'line1\\nline2\\nline3\\n') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'line1\\nline2\\nline3\\n')\n" + "buf.close()\n" + >>), {ok, Line1} = py:eval(Ctx, <<"buf.readline()">>), <<"line1\n">> = Line1, @@ -129,10 +131,11 @@ readlines_test(_Config) -> Ctx = py:context(1), ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'a\\nb\\nc\\n') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'a\\nb\\nc\\n')\n" + "buf.close()\n" + >>), {ok, Lines} = py:eval(Ctx, <<"buf.readlines()">>), [<<"a\n">>, <<"b\n">>, <<"c\n">>] = Lines, @@ -144,10 +147,11 @@ seek_tell_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create buffer, close it, and check initial position - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'0123456789') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'0123456789')\n" + "buf.close()\n" + >>), {ok, 0} = py:eval(Ctx, <<"buf.tell()">>), %% Read 5 bytes, position should advance @@ -202,10 +206,11 @@ memoryview_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create buffer and get memoryview - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'test data') -mv = memoryview(buf) -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'test data')\n" + "mv = memoryview(buf)\n" + >>), %% Check memoryview properties {ok, 9} = py:eval(Ctx, <<"len(mv)">>), @@ -230,10 +235,11 @@ iterator_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create buffer and iterate - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'line1\\nline2\\nline3\\n') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'line1\\nline2\\nline3\\n')\n" + "buf.close()\n" + >>), {ok, Lines} = py:eval(Ctx, <<"list(buf)">>), [<<"line1\n">>, <<"line2\n">>, <<"line3\n">>] = Lines, @@ -245,10 +251,11 @@ closed_buffer_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create buffer and close it - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'data') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'data')\n" + "buf.close()\n" + >>), %% Check closed property {ok, true} = py:eval(Ctx, <<"buf.closed">>), @@ -265,10 +272,11 @@ empty_buffer_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Create empty buffer and close immediately - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'') -buf.close() -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'')\n" + "buf.close()\n" + >>), %% Read should return empty {ok, <<>>} = py:eval(Ctx, <<"buf.read()">>), @@ -298,10 +306,11 @@ pass_to_python_test(_Config) -> Ctx = py:context(1), %% Define a function that reads from a buffer - ok = py:exec(Ctx, <<" -def read_buffer(buf): - return buf.read() -">>), + ok = py:exec(Ctx, << + "\n" + "def read_buffer(buf):\n" + " return buf.read()\n" + >>), %% Call with buffer ref - py_convert.c should wrap it as PyBuffer {ok, <<"chunk1chunk2">>} = py:eval(Ctx, <<"read_buffer(buf)">>, #{<<"buf">> => Buf}), @@ -312,14 +321,18 @@ def read_buffer(buf): %% memoryview pins it (relocating the storage would dangle the view -> UAF). %% Regression for the zero-copy view_count guard in py_buffer_write. buffer_grow_pinned_test(_Config) -> - {ok, Buf} = py_buffer:new(8), %% capacity 8 bytes - ok = py_buffer:write(Buf, <<"ab">>), %% write_pos 2, within capacity + %% capacity 8 bytes + {ok, Buf} = py_buffer:new(8), + %% write_pos 2, within capacity + ok = py_buffer:write(Buf, <<"ab">>), Ctx = py:context(1), %% Python holds a memoryview pinning the buffer (kept in a persistent global). - {ok, <<"pinned">>} = py:eval(Ctx, + {ok, <<"pinned">>} = py:eval( + Ctx, <<"globals().setdefault('_keep', []).append(memoryview(buf)) or 'pinned'">>, - #{<<"buf">> => Buf}), + #{<<"buf">> => Buf} + ), %% Growing the buffer now would relocate buf->data and dangle the memoryview, %% so the write is refused (no crash) while the view is pinned. @@ -338,52 +351,53 @@ buffer_grow_pinned_test(_Config) -> %% Verifies reference counting between Erlang and Python gc_refcount_test(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import gc -from erlang import PyBuffer - -# Track if we can create many buffers without memory issues -def create_and_release_buffers(count): - '''Create many buffers and let them be GC'd.''' - for i in range(count): - buf = PyBuffer._test_create(b'x' * 1000) - buf.close() - # buf goes out of scope, should be released - gc.collect() - return True - -def test_memoryview_refcount(): - '''Test that memoryview keeps buffer alive.''' - buf = PyBuffer._test_create(b'test data') - mv = memoryview(buf) - - # Buffer should stay alive while memoryview exists - data = bytes(mv[:4]) - - # Release memoryview - mv.release() - - # Buffer should still be usable after memoryview release - buf.close() - remaining = buf.read() - - return data == b'test' and remaining == b'test data' - -def test_multiple_views(): - '''Test multiple memoryviews on same buffer.''' - buf = PyBuffer._test_create(b'hello world') - mv1 = memoryview(buf) - mv2 = memoryview(buf) - - result1 = bytes(mv1[:5]) - result2 = bytes(mv2[6:]) - - mv1.release() - mv2.release() - buf.close() - - return result1 == b'hello' and result2 == b'world' -">>), + ok = py:exec(Ctx, << + "\n" + "import gc\n" + "from erlang import PyBuffer\n" + "\n" + "# Track if we can create many buffers without memory issues\n" + "def create_and_release_buffers(count):\n" + " '''Create many buffers and let them be GC'd.'''\n" + " for i in range(count):\n" + " buf = PyBuffer._test_create(b'x' * 1000)\n" + " buf.close()\n" + " # buf goes out of scope, should be released\n" + " gc.collect()\n" + " return True\n" + "\n" + "def test_memoryview_refcount():\n" + " '''Test that memoryview keeps buffer alive.'''\n" + " buf = PyBuffer._test_create(b'test data')\n" + " mv = memoryview(buf)\n" + "\n" + " # Buffer should stay alive while memoryview exists\n" + " data = bytes(mv[:4])\n" + "\n" + " # Release memoryview\n" + " mv.release()\n" + "\n" + " # Buffer should still be usable after memoryview release\n" + " buf.close()\n" + " remaining = buf.read()\n" + "\n" + " return data == b'test' and remaining == b'test data'\n" + "\n" + "def test_multiple_views():\n" + " '''Test multiple memoryviews on same buffer.'''\n" + " buf = PyBuffer._test_create(b'hello world')\n" + " mv1 = memoryview(buf)\n" + " mv2 = memoryview(buf)\n" + "\n" + " result1 = bytes(mv1[:5])\n" + " result2 = bytes(mv2[6:])\n" + "\n" + " mv1.release()\n" + " mv2.release()\n" + " buf.close()\n" + "\n" + " return result1 == b'hello' and result2 == b'world'\n" + >>), %% Test 1: Create and release many buffers {ok, true} = py:eval(Ctx, <<"create_and_release_buffers(100)">>), @@ -420,9 +434,10 @@ nonblock_read_test(_Config) -> ok = py:exec(Ctx, <<"from erlang import PyBuffer">>), %% Test read_nonblock returns available data immediately - ok = py:exec(Ctx, <<" -buf = PyBuffer._test_create(b'hello world') -">>), + ok = py:exec(Ctx, << + "\n" + "buf = PyBuffer._test_create(b'hello world')\n" + >>), %% readable_amount should return 11 (length of 'hello world') {ok, 11} = py:eval(Ctx, <<"buf.readable_amount()">>), @@ -450,25 +465,26 @@ buf = PyBuffer._test_create(b'hello world') {ok, true} = py:eval(Ctx, <<"buf.at_eof()">>), %% Test async I/O pattern simulation - ok = py:exec(Ctx, <<" -def async_read_simulation(): - '''Simulate async I/O read pattern.''' - buf = PyBuffer._test_create(b'chunk1chunk2chunk3') - buf.close() # EOF - - chunks = [] - while not buf.at_eof(): - available = buf.readable_amount() - if available > 0: - # Read in chunks of 6 - chunk = buf.read_nonblock(6) - chunks.append(chunk) - else: - # Would yield to event loop here in real async code - break - - return chunks -">>), + ok = py:exec(Ctx, << + "\n" + "def async_read_simulation():\n" + " '''Simulate async I/O read pattern.'''\n" + " buf = PyBuffer._test_create(b'chunk1chunk2chunk3')\n" + " buf.close() # EOF\n" + "\n" + " chunks = []\n" + " while not buf.at_eof():\n" + " available = buf.readable_amount()\n" + " if available > 0:\n" + " # Read in chunks of 6\n" + " chunk = buf.read_nonblock(6)\n" + " chunks.append(chunk)\n" + " else:\n" + " # Would yield to event loop here in real async code\n" + " break\n" + "\n" + " return chunks\n" + >>), {ok, [<<"chunk1">>, <<"chunk2">>, <<"chunk3">>]} = py:eval(Ctx, <<"async_read_simulation()">>), @@ -484,32 +500,33 @@ asyncio_read_test(_Config) -> Self = self(), %% Define async reader in Python - ok = py:exec(Ctx, <<" -import asyncio - -async def async_buffer_reader(buf): - '''Read from buffer asynchronously as Erlang fills it.''' - chunks = [] - - while not buf.at_eof(): - available = buf.readable_amount() - if available > 0: - chunk = buf.read_nonblock(available) - chunks.append(chunk) - else: - # Yield to event loop - Erlang is still writing - await asyncio.sleep(0.005) - - return b''.join(chunks) - -def run_async_reader(buf): - '''Run async reader.''' - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(async_buffer_reader(buf)) - finally: - loop.close() -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def async_buffer_reader(buf):\n" + " '''Read from buffer asynchronously as Erlang fills it.'''\n" + " chunks = []\n" + "\n" + " while not buf.at_eof():\n" + " available = buf.readable_amount()\n" + " if available > 0:\n" + " chunk = buf.read_nonblock(available)\n" + " chunks.append(chunk)\n" + " else:\n" + " # Yield to event loop - Erlang is still writing\n" + " await asyncio.sleep(0.005)\n" + "\n" + " return b''.join(chunks)\n" + "\n" + "def run_async_reader(buf):\n" + " '''Run async reader.'''\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(async_buffer_reader(buf))\n" + " finally:\n" + " loop.close()\n" + >>), %% Spawn a process to write data with delays (simulating streaming) spawn_link(fun() -> @@ -528,7 +545,10 @@ def run_async_reader(buf): {ok, Result} = py:eval(Ctx, <<"run_async_reader(buf)">>, #{<<"buf">> => Buf}), %% Wait for writer to finish - receive writer_done -> ok after 1000 -> ok end, + receive + writer_done -> ok + after 1000 -> ok + end, %% Verify we got all the data <<"chunk1:chunk2:chunk3">> = Result, diff --git a/test/py_byte_channel_SUITE.erl b/test/py_byte_channel_SUITE.erl index 787deaa..1a8b26a 100644 --- a/test/py_byte_channel_SUITE.erl +++ b/test/py_byte_channel_SUITE.erl @@ -49,41 +49,42 @@ native_wait_bytes_no_leak_test/1 ]). -all() -> [ - create_byte_channel_test, - create_byte_channel_with_max_size_test, - erlang_send_bytes_test, - erlang_receive_bytes_test, - send_receive_multiple_bytes_test, - try_receive_empty_bytes_test, - close_byte_channel_test, - byte_channel_info_test, - backpressure_bytes_test, - send_bytes_to_closed_test, - %% Python tests - python_byte_channel_class_test, - python_byte_channel_send_bytes_test, - python_byte_channel_receive_bytes_test, - %% Sync blocking receive tests - sync_receive_bytes_immediate_test, - sync_receive_bytes_wait_test, - sync_receive_bytes_closed_test, - %% Large payload test - large_payload_bytes_test, - %% Async event loop dispatch test - async_receive_bytes_e2e_test, - %% create_task + async receive test - create_task_async_receive_test, - %% Close and drain tests - close_drain_bytes_erlang_test, - close_drain_bytes_python_sync_test, - close_drain_bytes_python_async_test, - close_drain_bytes_create_task_async_test, - %% Native async receive: cancel after wake-up, send then close - native_cancel_ready_bytes_test, - native_send_then_close_bytes_test, - native_wait_bytes_no_leak_test -]. +all() -> + [ + create_byte_channel_test, + create_byte_channel_with_max_size_test, + erlang_send_bytes_test, + erlang_receive_bytes_test, + send_receive_multiple_bytes_test, + try_receive_empty_bytes_test, + close_byte_channel_test, + byte_channel_info_test, + backpressure_bytes_test, + send_bytes_to_closed_test, + %% Python tests + python_byte_channel_class_test, + python_byte_channel_send_bytes_test, + python_byte_channel_receive_bytes_test, + %% Sync blocking receive tests + sync_receive_bytes_immediate_test, + sync_receive_bytes_wait_test, + sync_receive_bytes_closed_test, + %% Large payload test + large_payload_bytes_test, + %% Async event loop dispatch test + async_receive_bytes_e2e_test, + %% create_task + async receive test + create_task_async_receive_test, + %% Close and drain tests + close_drain_bytes_erlang_test, + close_drain_bytes_python_sync_test, + close_drain_bytes_python_async_test, + close_drain_bytes_create_task_async_test, + %% Native async receive: cancel after wake-up, send then close + native_cancel_ready_bytes_test, + native_send_then_close_bytes_test, + native_wait_bytes_no_leak_test + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -99,14 +100,15 @@ end_per_suite(_Config) -> init_per_testcase(async_receive_bytes_e2e_test, Config) -> %% Define the async receive helper function Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import ByteChannel - -async def receive_bytes(ch_ref): - ch = ByteChannel(ch_ref) - return await ch.async_receive_bytes() -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import ByteChannel\n" + "\n" + "async def receive_bytes(ch_ref):\n" + " ch = ByteChannel(ch_ref)\n" + " return await ch.async_receive_bytes()\n" + >>), Config; init_per_testcase(_TestCase, Config) -> Config. @@ -376,16 +378,22 @@ async_receive_bytes_e2e_test(_Config) -> Ctx = py:context(1), %% Run async receive - data is already there, should return immediately - {ok, <<"immediate_bytes">>} = py:eval(Ctx, <<"erlang.run(receive_bytes(ch))">>, - #{<<"ch">> => Ch}), + {ok, <<"immediate_bytes">>} = py:eval( + Ctx, + <<"erlang.run(receive_bytes(ch))">>, + #{<<"ch">> => Ch} + ), ct:pal("Async receive immediate data OK"), %% Test 2: Send data after async starts - tests event dispatch %% We send data first, then run async (to avoid race conditions in test) ok = py_byte_channel:send(Ch, <<"async_bytes">>), - {ok, <<"async_bytes">>} = py:eval(Ctx, <<"erlang.run(receive_bytes(ch))">>, - #{<<"ch">> => Ch}), + {ok, <<"async_bytes">>} = py:eval( + Ctx, + <<"erlang.run(receive_bytes(ch))">>, + #{<<"ch">> => Ch} + ), ct:pal("Async receive via erlang.run() OK"), ok = py_byte_channel:close(Ch). @@ -404,24 +412,26 @@ create_task_async_receive_test(_Config) -> %% Define and run the task - env reuse should make __main__ functions visible Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import ByteChannel - -async def task_receive_bytes(ch_ref, reply_pid): - '''Task that receives bytes and sends result back to Erlang.''' - try: - ch = ByteChannel(ch_ref) - data = await ch.async_receive_bytes() - erlang.send(reply_pid, ('result', data)) - except Exception as e: - erlang.send(reply_pid, ('error', str(e))) -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import ByteChannel\n" + "\n" + "async def task_receive_bytes(ch_ref, reply_pid):\n" + " '''Task that receives bytes and sends result back to Erlang.'''\n" + " try:\n" + " ch = ByteChannel(ch_ref)\n" + " data = await ch.async_receive_bytes()\n" + " erlang.send(reply_pid, ('result', data))\n" + " except Exception as e:\n" + " erlang.send(reply_pid, ('error', str(e)))\n" + >>), %% Create a task that will await on channel receive %% create_task/3 uses the global event loop internally TaskRef = py_event_loop:create_task( - "__main__", "task_receive_bytes", [Ch, self()]), + "__main__", "task_receive_bytes", [Ch, self()] + ), %% Wait for result from the task %% Note: Python tuple ('result', data) becomes {<<"result">>, data} in Erlang @@ -441,8 +451,7 @@ async def task_receive_bytes(ch_ref, reply_pid): %% Wait for task to complete case py_event_loop:await(TaskRef, 5000) of {ok, _} -> ok; - {error, AwaitErr} -> - ct:pal("Await error: ~p", [AwaitErr]) + {error, AwaitErr} -> ct:pal("Await error: ~p", [AwaitErr]) end, ok = py_byte_channel:close(Ch). @@ -492,17 +501,18 @@ close_drain_bytes_python_sync_test(_Config) -> %% Python should be able to drain all messages via iteration Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang import ByteChannel, ByteChannelClosed - -def drain_byte_channel(ch_ref): - '''Drain all chunks from byte channel, return as list.''' - ch = ByteChannel(ch_ref) - chunks = [] - for chunk in ch: - chunks.append(chunk) - return chunks -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang import ByteChannel, ByteChannelClosed\n" + "\n" + "def drain_byte_channel(ch_ref):\n" + " '''Drain all chunks from byte channel, return as list.'''\n" + " ch = ByteChannel(ch_ref)\n" + " chunks = []\n" + " for chunk in ch:\n" + " chunks.append(chunk)\n" + " return chunks\n" + >>), {ok, [<<"data1">>, <<"data2">>, <<"data3">>]} = py:eval(Ctx, <<"drain_byte_channel(ch)">>, #{<<"ch">> => Ch}), @@ -523,18 +533,19 @@ close_drain_bytes_python_async_test(_Config) -> %% Python should be able to drain all messages via async iteration Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import ByteChannel, ByteChannelClosed - -async def async_drain_byte_channel(ch_ref): - '''Async drain all chunks from byte channel, return as list.''' - ch = ByteChannel(ch_ref) - chunks = [] - async for chunk in ch: - chunks.append(chunk) - return chunks -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import ByteChannel, ByteChannelClosed\n" + "\n" + "async def async_drain_byte_channel(ch_ref):\n" + " '''Async drain all chunks from byte channel, return as list.'''\n" + " ch = ByteChannel(ch_ref)\n" + " chunks = []\n" + " async for chunk in ch:\n" + " chunks.append(chunk)\n" + " return chunks\n" + >>), {ok, [<<"part1">>, <<"part2">>, <<"part3">>]} = py:eval(Ctx, <<"erlang.run(async_drain_byte_channel(ch))">>, #{<<"ch">> => Ch}), @@ -548,26 +559,28 @@ close_drain_bytes_create_task_async_test(_Config) -> %% Define the async drain task Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import ByteChannel - -async def drain_task(ch_ref, reply_pid): - '''Task that drains byte channel and sends results back.''' - try: - ch = ByteChannel(ch_ref) - chunks = [] - async for chunk in ch: - chunks.append(chunk) - erlang.send(reply_pid, ('result', chunks)) - except Exception as e: - erlang.send(reply_pid, ('error', str(e))) -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import ByteChannel\n" + "\n" + "async def drain_task(ch_ref, reply_pid):\n" + " '''Task that drains byte channel and sends results back.'''\n" + " try:\n" + " ch = ByteChannel(ch_ref)\n" + " chunks = []\n" + " async for chunk in ch:\n" + " chunks.append(chunk)\n" + " erlang.send(reply_pid, ('result', chunks))\n" + " except Exception as e:\n" + " erlang.send(reply_pid, ('error', str(e)))\n" + >>), %% Create the task BEFORE sending any data %% This forces the task to register a waiter and wait for notifications TaskRef = py_event_loop:create_task( - "__main__", "drain_task", [Ch, self()]), + "__main__", "drain_task", [Ch, self()] + ), %% Give the task time to start and register waiter timer:sleep(100), @@ -597,8 +610,7 @@ async def drain_task(ch_ref, reply_pid): %% Wait for task to complete case py_event_loop:await(TaskRef, 5000) of {ok, _} -> ok; - {error, AwaitErr} -> - ct:pal("Await error: ~p", [AwaitErr]) + {error, AwaitErr} -> ct:pal("Await error: ~p", [AwaitErr]) end. %% A receiver cancelled after its wake-up ran, before it resumed, leaves @@ -609,29 +621,30 @@ native_cancel_ready_bytes_test(_Config) -> py_byte_channel:send(Ch, <<"payload">>) end), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -async def cancel_ready_bytes(ref): - loop = asyncio.get_running_loop() - channel = erlang.ByteChannel(ref) - before = set(loop._timers) - receiver = asyncio.create_task(channel.async_receive_bytes()) - await asyncio.sleep(0) - callbacks = set(loop._timers) - before - assert len(callbacks) == 1 - ready = loop._timers[callbacks.pop()] - erlang.call('byte_channel_regression_send') - ready._run() - receiver.cancel() - try: - await receiver - except asyncio.CancelledError: - pass - return channel.try_receive_bytes() -def run_cancel_ready_bytes(ref): - return erlang.run(cancel_ready_bytes(ref)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "async def cancel_ready_bytes(ref):\n" + " loop = asyncio.get_running_loop()\n" + " channel = erlang.ByteChannel(ref)\n" + " before = set(loop._timers)\n" + " receiver = asyncio.create_task(channel.async_receive_bytes())\n" + " await asyncio.sleep(0)\n" + " callbacks = set(loop._timers) - before\n" + " assert len(callbacks) == 1\n" + " ready = loop._timers[callbacks.pop()]\n" + " erlang.call('byte_channel_regression_send')\n" + " ready._run()\n" + " receiver.cancel()\n" + " try:\n" + " await receiver\n" + " except asyncio.CancelledError:\n" + " pass\n" + " return channel.try_receive_bytes()\n" + "def run_cancel_ready_bytes(ref):\n" + " return erlang.run(cancel_ready_bytes(ref))\n" + >>), try {ok, <<"payload">>} = py:call(Ctx, '__main__', run_cancel_ready_bytes, [Ch]) after @@ -648,23 +661,24 @@ native_send_then_close_bytes_test(_Config) -> py_byte_channel:close(Ch) end), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -async def send_then_close_bytes(ref): - channel = erlang.ByteChannel(ref) - receiver = asyncio.create_task(channel.async_receive_bytes()) - await asyncio.sleep(0) - erlang.call('byte_channel_regression_send_close') - assert await asyncio.wait_for(receiver, 1) == b'last' - try: - await asyncio.wait_for(channel.async_receive_bytes(), 1) - except erlang.ByteChannelClosed: - return True - return False -def run_send_then_close_bytes(ref): - return erlang.run(send_then_close_bytes(ref)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "async def send_then_close_bytes(ref):\n" + " channel = erlang.ByteChannel(ref)\n" + " receiver = asyncio.create_task(channel.async_receive_bytes())\n" + " await asyncio.sleep(0)\n" + " erlang.call('byte_channel_regression_send_close')\n" + " assert await asyncio.wait_for(receiver, 1) == b'last'\n" + " try:\n" + " await asyncio.wait_for(channel.async_receive_bytes(), 1)\n" + " except erlang.ByteChannelClosed:\n" + " return True\n" + " return False\n" + "def run_send_then_close_bytes(ref):\n" + " return erlang.run(send_then_close_bytes(ref))\n" + >>), try {ok, true} = py:call(Ctx, '__main__', run_send_then_close_bytes, [Ch]) after @@ -678,28 +692,29 @@ native_wait_bytes_no_leak_test(_Config) -> Chunk = binary:copy(<<"x">>, 4096), [ok = py_byte_channel:send(Ch, Chunk) || _ <- lists:seq(1, 1000)], Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import gc -import tracemalloc -import erlang -async def wait_drain_growth(ref, n): - capsule = asyncio.get_running_loop()._loop_capsule - tracemalloc.start() - try: - gc.collect() - before = tracemalloc.get_traced_memory()[0] - for i in range(n): - result = erlang._byte_channel_wait(ref, i + 1, capsule) - assert result[0] == 'ok' and len(result[1]) == 4096 - del result - gc.collect() - return tracemalloc.get_traced_memory()[0] - before - finally: - tracemalloc.stop() -def run_wait_drain_growth(ref, n): - return erlang.run(wait_drain_growth(ref, n)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import gc\n" + "import tracemalloc\n" + "import erlang\n" + "async def wait_drain_growth(ref, n):\n" + " capsule = asyncio.get_running_loop()._loop_capsule\n" + " tracemalloc.start()\n" + " try:\n" + " gc.collect()\n" + " before = tracemalloc.get_traced_memory()[0]\n" + " for i in range(n):\n" + " result = erlang._byte_channel_wait(ref, i + 1, capsule)\n" + " assert result[0] == 'ok' and len(result[1]) == 4096\n" + " del result\n" + " gc.collect()\n" + " return tracemalloc.get_traced_memory()[0] - before\n" + " finally:\n" + " tracemalloc.stop()\n" + "def run_wait_drain_growth(ref, n):\n" + " return erlang.run(wait_drain_growth(ref, n))\n" + >>), try {ok, Growth} = py:call(Ctx, '__main__', run_wait_drain_growth, [Ch, 1000]), ct:pal("traced growth after 1000 x 4 KB waits: ~p bytes", [Growth]), diff --git a/test/py_callback_encoding_SUITE.erl b/test/py_callback_encoding_SUITE.erl index 103c9d5..4c96abb 100644 --- a/test/py_callback_encoding_SUITE.erl +++ b/test/py_callback_encoding_SUITE.erl @@ -31,20 +31,21 @@ test_python_types/1 ]). -all() -> [ - test_binary_with_escapes, - test_binary_non_utf8, - test_large_binary, - test_atom_becomes_str, - test_empty_list, - test_erlang_string_is_int_list, - test_nested_containers, - test_pid_round_trip, - test_ref_round_trip, - test_float_round_trip, - test_booleans_and_none, - test_python_types -]. +all() -> + [ + test_binary_with_escapes, + test_binary_non_utf8, + test_large_binary, + test_atom_becomes_str, + test_empty_list, + test_erlang_string_is_int_list, + test_nested_containers, + test_pid_round_trip, + test_ref_round_trip, + test_float_round_trip, + test_booleans_and_none, + test_python_types + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -128,18 +129,23 @@ test_ref_round_trip(_Config) -> %% @doc Floats are exact, not routed through a decimal-formatted string. test_float_round_trip(_Config) -> - lists:foreach(fun(F) -> F = probe(F) end, - [3.14159265358979, 1.0e-300, 1.7976931348623157e308, -0.0]), + lists:foreach( + fun(F) -> F = probe(F) end, + [3.14159265358979, 1.0e-300, 1.7976931348623157e308, -0.0] + ), ok. test_booleans_and_none(_Config) -> true = probe(true), false = probe(false), <<"bool">> = probe_type(true), - lists:foreach(fun(A) -> - none = probe(A), - <<"NoneType">> = probe_type(A) - end, [undefined, nil, none]), + lists:foreach( + fun(A) -> + none = probe(A), + <<"NoneType">> = probe_type(A) + end, + [undefined, nil, none] + ), ok. %% @doc Tuples stay tuples and integers stay ints on the Python side. @@ -164,6 +170,7 @@ probe(Value) -> probe_type(Value) -> py:register_function(cbenc_probe, fun(_) -> Value end), {ok, Type} = py:eval( - <<"type(__import__('erlang').call('cbenc_probe', [])).__name__">>), + <<"type(__import__('erlang').call('cbenc_probe', [])).__name__">> + ), py:unregister_function(cbenc_probe), Type. diff --git a/test/py_channel_SUITE.erl b/test/py_channel_SUITE.erl index d814fdf..6a47186 100644 --- a/test/py_channel_SUITE.erl +++ b/test/py_channel_SUITE.erl @@ -53,45 +53,46 @@ close_drain_create_task_async_test/1 ]). -all() -> [ - create_channel_test, - create_channel_with_max_size_test, - send_receive_test, - send_receive_multiple_test, - try_receive_empty_test, - close_channel_test, - channel_info_test, - backpressure_test, - send_to_closed_test, - python_receive_test, - python_try_receive_test, - python_iterate_test, - async_receive_immediate_test, - native_none_payload_test, - native_cancel_ready_test, - native_send_then_close_test, - fallback_none_payload_test, - async_receive_wait_test, - async_iteration_test, - async_closed_channel_test, - channel_ref_roundtrip_test, - channel_ref_call_test, - %% Sync blocking receive tests - sync_receive_immediate_test, - sync_receive_wait_test, - sync_receive_closed_test, - sync_receive_multiple_waiters_test, - %% Mixed waiter rejection tests - mixed_waiter_sync_blocks_async_test, - mixed_waiter_async_blocks_sync_test, - %% Async receive with actual waiting - async_receive_wait_e2e_test, - %% Close and drain tests - close_drain_erlang_test, - close_drain_python_sync_test, - close_drain_python_async_test, - close_drain_create_task_async_test -]. +all() -> + [ + create_channel_test, + create_channel_with_max_size_test, + send_receive_test, + send_receive_multiple_test, + try_receive_empty_test, + close_channel_test, + channel_info_test, + backpressure_test, + send_to_closed_test, + python_receive_test, + python_try_receive_test, + python_iterate_test, + async_receive_immediate_test, + native_none_payload_test, + native_cancel_ready_test, + native_send_then_close_test, + fallback_none_payload_test, + async_receive_wait_test, + async_iteration_test, + async_closed_channel_test, + channel_ref_roundtrip_test, + channel_ref_call_test, + %% Sync blocking receive tests + sync_receive_immediate_test, + sync_receive_wait_test, + sync_receive_closed_test, + sync_receive_multiple_waiters_test, + %% Mixed waiter rejection tests + mixed_waiter_sync_blocks_async_test, + mixed_waiter_async_blocks_sync_test, + %% Async receive with actual waiting + async_receive_wait_e2e_test, + %% Close and drain tests + close_drain_erlang_test, + close_drain_python_sync_test, + close_drain_python_async_test, + close_drain_create_task_async_test + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -114,20 +115,21 @@ native_none_payload_test(_Config) -> py_channel:send(Ch, none) end), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -async def receive_none(ref): - value = await asyncio.wait_for(erlang.Channel(ref).async_receive(), 0.2) - assert value is None - receiver = asyncio.create_task(erlang.Channel(ref).async_receive()) - await asyncio.sleep(0) - erlang.call('channel_regression_none') - assert await asyncio.wait_for(receiver, 0.2) is None - return True -def run_receive_none(ref): - return erlang.run(receive_none(ref)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "async def receive_none(ref):\n" + " value = await asyncio.wait_for(erlang.Channel(ref).async_receive(), 0.2)\n" + " assert value is None\n" + " receiver = asyncio.create_task(erlang.Channel(ref).async_receive())\n" + " await asyncio.sleep(0)\n" + " erlang.call('channel_regression_none')\n" + " assert await asyncio.wait_for(receiver, 0.2) is None\n" + " return True\n" + "def run_receive_none(ref):\n" + " return erlang.run(receive_none(ref))\n" + >>), try {ok, true} = py:call(Ctx, '__main__', run_receive_none, [Ch]) after @@ -141,30 +143,31 @@ native_cancel_ready_test(_Config) -> py_channel:send(Ch, 42) end), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -async def cancel_ready(ref): - loop = asyncio.get_running_loop() - channel = erlang.Channel(ref) - before = set(loop._timers) - receiver = asyncio.create_task(channel.async_receive()) - await asyncio.sleep(0) - callbacks = set(loop._timers) - before - assert len(callbacks) == 1 - ready = loop._timers[callbacks.pop()] - erlang.call('channel_regression_send') - ready._run() - receiver.cancel() - try: - await receiver - except asyncio.CancelledError: - pass - assert channel.try_receive() == 42 - return True -def run_cancel_ready(ref): - return erlang.run(cancel_ready(ref)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "async def cancel_ready(ref):\n" + " loop = asyncio.get_running_loop()\n" + " channel = erlang.Channel(ref)\n" + " before = set(loop._timers)\n" + " receiver = asyncio.create_task(channel.async_receive())\n" + " await asyncio.sleep(0)\n" + " callbacks = set(loop._timers) - before\n" + " assert len(callbacks) == 1\n" + " ready = loop._timers[callbacks.pop()]\n" + " erlang.call('channel_regression_send')\n" + " ready._run()\n" + " receiver.cancel()\n" + " try:\n" + " await receiver\n" + " except asyncio.CancelledError:\n" + " pass\n" + " assert channel.try_receive() == 42\n" + " return True\n" + "def run_cancel_ready(ref):\n" + " return erlang.run(cancel_ready(ref))\n" + >>), try {ok, true} = py:call(Ctx, '__main__', run_cancel_ready, [Ch]) after @@ -181,23 +184,24 @@ native_send_then_close_test(_Config) -> py_channel:close(Ch) end), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -async def send_then_close(ref): - channel = erlang.Channel(ref) - receiver = asyncio.create_task(channel.async_receive()) - await asyncio.sleep(0) - erlang.call('channel_regression_send_close') - assert await asyncio.wait_for(receiver, 1) == 42 - try: - await asyncio.wait_for(channel.async_receive(), 1) - except erlang.ChannelClosed: - return True - return False -def run_send_then_close(ref): - return erlang.run(send_then_close(ref)) -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "async def send_then_close(ref):\n" + " channel = erlang.Channel(ref)\n" + " receiver = asyncio.create_task(channel.async_receive())\n" + " await asyncio.sleep(0)\n" + " erlang.call('channel_regression_send_close')\n" + " assert await asyncio.wait_for(receiver, 1) == 42\n" + " try:\n" + " await asyncio.wait_for(channel.async_receive(), 1)\n" + " except erlang.ChannelClosed:\n" + " return True\n" + " return False\n" + "def run_send_then_close(ref):\n" + " return erlang.run(send_then_close(ref))\n" + >>), try {ok, true} = py:call(Ctx, '__main__', run_send_then_close, [Ch]) after @@ -211,19 +215,20 @@ fallback_none_payload_test(_Config) -> ok = py_channel:send(Ch, none), ok = py_channel:send(Ch, second), Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import asyncio -import erlang -def fallback_receive_two(ref): - channel = erlang.Channel(ref) - loop = asyncio.SelectorEventLoop() - try: - first = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1)) - second = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1)) - return [first, second] - finally: - loop.close() -">>), + ok = py:exec(Ctx, << + "\n" + "import asyncio\n" + "import erlang\n" + "def fallback_receive_two(ref):\n" + " channel = erlang.Channel(ref)\n" + " loop = asyncio.SelectorEventLoop()\n" + " try:\n" + " first = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1))\n" + " second = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1))\n" + " return [first, second]\n" + " finally:\n" + " loop.close()\n" + >>), try {ok, [none, <<"second">>]} = py:call(Ctx, '__main__', fallback_receive_two, [Ch]) after @@ -384,24 +389,25 @@ async_receive_immediate_test(_Config) -> %% Run async receive via Python - data should return immediately Ctx = py:context(1), - _Code = <<" -import asyncio -from erlang import Channel - -async def test_immediate(ch_ref): - ch = Channel(ch_ref) - result = await ch.async_receive() - return result - -# Run the async function -loop = asyncio.new_event_loop() -asyncio.set_event_loop(loop) -try: - result = loop.run_until_complete(test_immediate(channel_ref)) -finally: - loop.close() -result -">>, + _Code = << + "\n" + "import asyncio\n" + "from erlang import Channel\n" + "\n" + "async def test_immediate(ch_ref):\n" + " ch = Channel(ch_ref)\n" + " result = await ch.async_receive()\n" + " return result\n" + "\n" + "# Run the async function\n" + "loop = asyncio.new_event_loop()\n" + "asyncio.set_event_loop(loop)\n" + "try:\n" + " result = loop.run_until_complete(test_immediate(channel_ref))\n" + "finally:\n" + " loop.close()\n" + "result\n" + >>, %% Set channel ref as a variable ok = py:exec(Ctx, <<"channel_ref = None">>), %% For now, test that the async methods exist @@ -624,7 +630,10 @@ mixed_waiter_sync_blocks_async_test(_Config) -> %% Clean up: send data to clear sync waiter ok = py_channel:send(Ch, <<"data">>), - receive channel_data_ready -> ok after 100 -> ok end, + receive + channel_data_ready -> ok + after 100 -> ok + end, py_nif:event_loop_destroy(Loop), ok = py_channel:close(Ch). @@ -661,19 +670,23 @@ async_receive_wait_e2e_test(_Config) -> ok = py:exec(Ctx, <<"channel_ref = None">>), %% Define async function that receives from channel - ok = py:exec(Ctx, <<" -import erlang -from erlang import Channel - -async def receive_from_channel(ch_ref): - ch = Channel(ch_ref) - data = await ch.async_receive() - return data -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import Channel\n" + "\n" + "async def receive_from_channel(ch_ref):\n" + " ch = Channel(ch_ref)\n" + " data = await ch.async_receive()\n" + " return data\n" + >>), %% Run the async receive - data is already there - {ok, <<"async_data">>} = py:eval(Ctx, <<"erlang.run(receive_from_channel(ch))">>, - #{<<"ch">> => Ch}), + {ok, <<"async_data">>} = py:eval( + Ctx, + <<"erlang.run(receive_from_channel(ch))">>, + #{<<"ch">> => Ch} + ), ct:pal("Async receive successfully received data via erlang.run()"), ok = py_channel:close(Ch). @@ -723,17 +736,18 @@ close_drain_python_sync_test(_Config) -> %% Python should be able to drain all messages via iteration Ctx = py:context(1), - ok = py:exec(Ctx, <<" -from erlang import Channel, ChannelClosed - -def drain_channel(ch_ref): - '''Drain all messages from channel, return as list.''' - ch = Channel(ch_ref) - messages = [] - for msg in ch: - messages.append(msg) - return messages -">>), + ok = py:exec(Ctx, << + "\n" + "from erlang import Channel, ChannelClosed\n" + "\n" + "def drain_channel(ch_ref):\n" + " '''Drain all messages from channel, return as list.'''\n" + " ch = Channel(ch_ref)\n" + " messages = []\n" + " for msg in ch:\n" + " messages.append(msg)\n" + " return messages\n" + >>), {ok, [<<"first">>, <<"second">>, <<"third">>]} = py:eval(Ctx, <<"drain_channel(ch)">>, #{<<"ch">> => Ch}), @@ -754,18 +768,19 @@ close_drain_python_async_test(_Config) -> %% Python should be able to drain all messages via async iteration Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import Channel, ChannelClosed - -async def async_drain_channel(ch_ref): - '''Async drain all messages from channel, return as list.''' - ch = Channel(ch_ref) - messages = [] - async for msg in ch: - messages.append(msg) - return messages -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import Channel, ChannelClosed\n" + "\n" + "async def async_drain_channel(ch_ref):\n" + " '''Async drain all messages from channel, return as list.'''\n" + " ch = Channel(ch_ref)\n" + " messages = []\n" + " async for msg in ch:\n" + " messages.append(msg)\n" + " return messages\n" + >>), {ok, [<<"alpha">>, <<"beta">>, <<"gamma">>]} = py:eval(Ctx, <<"erlang.run(async_drain_channel(ch))">>, #{<<"ch">> => Ch}), @@ -779,26 +794,28 @@ close_drain_create_task_async_test(_Config) -> %% Define the async drain task Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang -from erlang import Channel - -async def drain_task(ch_ref, reply_pid): - '''Task that drains channel and sends results back.''' - try: - ch = Channel(ch_ref) - messages = [] - async for msg in ch: - messages.append(msg) - erlang.send(reply_pid, ('result', messages)) - except Exception as e: - erlang.send(reply_pid, ('error', str(e))) -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "from erlang import Channel\n" + "\n" + "async def drain_task(ch_ref, reply_pid):\n" + " '''Task that drains channel and sends results back.'''\n" + " try:\n" + " ch = Channel(ch_ref)\n" + " messages = []\n" + " async for msg in ch:\n" + " messages.append(msg)\n" + " erlang.send(reply_pid, ('result', messages))\n" + " except Exception as e:\n" + " erlang.send(reply_pid, ('error', str(e)))\n" + >>), %% Create the task BEFORE sending any data %% This forces the task to register a waiter and wait for notifications TaskRef = py_event_loop:create_task( - "__main__", "drain_task", [Ch, self()]), + "__main__", "drain_task", [Ch, self()] + ), %% Give the task time to start and register waiter timer:sleep(100), @@ -828,6 +845,5 @@ async def drain_task(ch_ref, reply_pid): %% Wait for task to complete case py_event_loop:await(TaskRef, 5000) of {ok, _} -> ok; - {error, AwaitErr} -> - ct:pal("Await error: ~p", [AwaitErr]) + {error, AwaitErr} -> ct:pal("Await error: ~p", [AwaitErr]) end. diff --git a/test/py_context_SUITE.erl b/test/py_context_SUITE.erl index 0bec1a4..bfcc8b6 100644 --- a/test/py_context_SUITE.erl +++ b/test/py_context_SUITE.erl @@ -26,17 +26,18 @@ scheduler_affinity_test/1 ]). -all() -> [ - get_context_test, - get_specific_context_test, - state_persists_in_context_test, - contexts_are_isolated_test, - explicit_context_call_test, - explicit_context_eval_test, - explicit_context_exec_test, - implicit_routing_test, - scheduler_affinity_test -]. +all() -> + [ + get_context_test, + get_specific_context_test, + state_persists_in_context_test, + contexts_are_isolated_test, + explicit_context_call_test, + explicit_context_eval_test, + explicit_context_exec_test, + implicit_routing_test, + scheduler_affinity_test + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), diff --git a/test/py_context_async_env_SUITE.erl b/test/py_context_async_env_SUITE.erl index 893739a..f1fde15 100644 --- a/test/py_context_async_env_SUITE.erl +++ b/test/py_context_async_env_SUITE.erl @@ -65,22 +65,32 @@ env_call_does_not_dispatch_timeout(_Config) -> %% should track wall-clock and never produce {error, worker_timeout}. Ctx = py:context(1), EnvRef = py:get_local_env(Ctx), - ok = py_context:exec(Ctx, << - "import time\n" - "def _slow_round(x):\n" - " time.sleep(1.0)\n" - " return x * 2\n" - >>, EnvRef), + ok = py_context:exec( + Ctx, + << + "import time\n" + "def _slow_round(x):\n" + " time.sleep(1.0)\n" + " return x * 2\n" + >>, + EnvRef + ), Start = erlang:monotonic_time(millisecond), - {ok, 14} = py_context:call(Ctx, '__main__', '_slow_round', [7], #{}, - infinity, EnvRef), + {ok, 14} = py_context:call( + Ctx, + '__main__', + '_slow_round', + [7], + #{}, + infinity, + EnvRef + ), Elapsed = erlang:monotonic_time(millisecond) - Start, ct:pal("env-async call elapsed: ~p ms", [Elapsed]), true = Elapsed >= 900, true = Elapsed < 5000, ok. - %% A process-local env holds its objects until the process exits; then they %% are released. Each env registers an object in a WeakSet kept on `sys' %% (shared by all envs of the interpreter): it empties once they are freed. @@ -101,15 +111,22 @@ env_freed_after_process_exit_owngil(_Config) -> envs_freed(Mode) -> {ok, C} = py_context:new(#{mode => Mode}), - ok = py_context:exec(C, <<"import sys, weakref\nsys._env_probe = weakref.WeakSet()\n" - "class Held: pass\nsys._EnvHeld = Held">>), - [begin - {P, M} = spawn_monitor(fun() -> - ok = py:exec(C, <<"import sys\nheld = sys._EnvHeld()\nsys._env_probe.add(held)">>), - {ok, true} = py:eval(C, <<"held in sys._env_probe">>) - end), - receive {'DOWN', M, process, P, normal} -> ok end - end || _ <- lists:seq(1, 50)], + ok = py_context:exec(C, << + "import sys, weakref\nsys._env_probe = weakref.WeakSet()\n" + "class Held: pass\nsys._EnvHeld = Held" + >>), + [ + begin + {P, M} = spawn_monitor(fun() -> + ok = py:exec(C, <<"import sys\nheld = sys._EnvHeld()\nsys._env_probe.add(held)">>), + {ok, true} = py:eval(C, <<"held in sys._env_probe">>) + end), + receive + {'DOWN', M, process, P, normal} -> ok + end + end + || _ <- lists:seq(1, 50) + ], ok = wait_probe_empty(C, 250), py_context:stop(C). @@ -118,9 +135,14 @@ wait_probe_empty(C, 0) -> wait_probe_empty(C, N) -> gc_all(), %% the next request on the context releases what the dead envs held - case py_context:eval(C, <<"(__import__('gc').collect(), len(__import__('sys')._env_probe))[1]">>) of - {ok, 0} -> ok; - _ -> timer:sleep(20), wait_probe_empty(C, N - 1) + case + py_context:eval(C, <<"(__import__('gc').collect(), len(__import__('sys')._env_probe))[1]">>) + of + {ok, 0} -> + ok; + _ -> + timer:sleep(20), + wait_probe_empty(C, N - 1) end. %% A process still holding an owngil env when its context stops: the env is @@ -132,17 +154,33 @@ env_outlives_owngil_context(_Config) -> true -> {ok, C} = py_context:new(#{mode => owngil}), Self = self(), - Holders = [spawn(fun() -> - ok = py:exec(C, <<"blob = 'x' * 100000">>), - Self ! {ready, self()}, - receive go -> ok end - end) || _ <- lists:seq(1, 10)], - [receive {ready, H} -> ok after 5000 -> ct:fail(no_env) end || H <- Holders], + Holders = [ + spawn(fun() -> + ok = py:exec(C, <<"blob = 'x' * 100000">>), + Self ! {ready, self()}, + receive + go -> ok + end + end) + || _ <- lists:seq(1, 10) + ], + [ + receive + {ready, H} -> ok + after 5000 -> ct:fail(no_env) + end + || H <- Holders + ], ok = py_context:stop(C), Mons = [erlang:monitor(process, H) || H <- Holders], [H ! go || H <- Holders], - [receive {'DOWN', M, process, _, normal} -> ok after 5000 -> ct:fail(holder_stuck) end - || M <- Mons], + [ + receive + {'DOWN', M, process, _, normal} -> ok + after 5000 -> ct:fail(holder_stuck) + end + || M <- Mons + ], gc_all(), %% the node is fine and new owngil contexts work {ok, C2} = py_context:new(#{mode => owngil}), @@ -150,7 +188,6 @@ env_outlives_owngil_context(_Config) -> py_context:stop(C2) end. - %% The namespace a process gets on an owngil context's event loop %% (py_event_loop:exec/eval) is released when the process exits. Those %% namespaces are created in the main interpreter even on a subinterpreter @@ -162,47 +199,75 @@ loop_namespace_freed_after_process_exit_owngil(_Config) -> true -> {ok, C} = py_context:new(#{mode => owngil}), {ok, Loop} = py_context:loop_ref(C), - ok = py_event_loop:exec(Loop, <<"import sys, weakref\nsys._loop_probe = weakref.WeakSet()\n" - "class Held: pass\nsys._LoopHeld = Held">>), - [begin - {P, M} = spawn_monitor(fun() -> - ok = py_event_loop:exec(Loop, <<"import sys\nheld = sys._LoopHeld()\nsys._loop_probe.add(held)">>) - end), - receive {'DOWN', M, process, P, normal} -> ok end - end || _ <- lists:seq(1, 30)], + ok = py_event_loop:exec(Loop, << + "import sys, weakref\nsys._loop_probe = weakref.WeakSet()\n" + "class Held: pass\nsys._LoopHeld = Held" + >>), + [ + begin + {P, M} = spawn_monitor(fun() -> + ok = py_event_loop:exec( + Loop, + <<"import sys\nheld = sys._LoopHeld()\nsys._loop_probe.add(held)">> + ) + end), + receive + {'DOWN', M, process, P, normal} -> ok + end + end + || _ <- lists:seq(1, 30) + ], ok = wait_loop_probe_empty(Loop, 250), py_context:stop(C) end. wait_loop_probe_empty(Loop, 0) -> - ct:fail({loop_namespaces_not_freed, - py_event_loop:eval(Loop, <<"len(__import__('sys')._loop_probe)">>)}); + ct:fail( + {loop_namespaces_not_freed, + py_event_loop:eval(Loop, <<"len(__import__('sys')._loop_probe)">>)} + ); wait_loop_probe_empty(Loop, N) -> gc_all(), - case py_event_loop:eval(Loop, <<"(__import__('gc').collect(), len(__import__('sys')._loop_probe))[1]">>) of - {ok, 0} -> ok; - _ -> timer:sleep(20), wait_loop_probe_empty(Loop, N - 1) + case + py_event_loop:eval( + Loop, <<"(__import__('gc').collect(), len(__import__('sys')._loop_probe))[1]">> + ) + of + {ok, 0} -> + ok; + _ -> + timer:sleep(20), + wait_loop_probe_empty(Loop, N - 1) end. - %% A task submitted to the event loop from a process that has a local env %% (py_event_loop:create_task after py:exec) registers that env for the %% process. The registration used to keep the env for the loop's lifetime; %% it is dropped when the process exits. loop_task_env_freed_after_process_exit(_Config) -> - ok = py:exec(<<"import sys, weakref\nsys._task_env_probe = weakref.WeakSet()\n" - "class Held: pass\nsys._TaskHeld = Held">>), - [begin - {P, M} = spawn_monitor(fun() -> - ok = py:exec(<<"import sys\nheld = sys._TaskHeld()\nsys._task_env_probe.add(held)">>), - %% the process has an env, so the task registers it; the task - %% itself calls a library coroutine (no function defined in the - %% env, see envs_freed/1 about free-threaded builds) - Ref = py_event_loop:create_task(asyncio, sleep, [0]), - {ok, none} = py_event_loop:await(Ref, 5000) - end), - receive {'DOWN', M, process, P, normal} -> ok after 10000 -> ct:fail(task_hung) end - end || _ <- lists:seq(1, 20)], + ok = py:exec(<< + "import sys, weakref\nsys._task_env_probe = weakref.WeakSet()\n" + "class Held: pass\nsys._TaskHeld = Held" + >>), + [ + begin + {P, M} = spawn_monitor(fun() -> + ok = py:exec( + <<"import sys\nheld = sys._TaskHeld()\nsys._task_env_probe.add(held)">> + ), + %% the process has an env, so the task registers it; the task + %% itself calls a library coroutine (no function defined in the + %% env, see envs_freed/1 about free-threaded builds) + Ref = py_event_loop:create_task(asyncio, sleep, [0]), + {ok, none} = py_event_loop:await(Ref, 5000) + end), + receive + {'DOWN', M, process, P, normal} -> ok + after 10000 -> ct:fail(task_hung) + end + end + || _ <- lists:seq(1, 20) + ], ok = wait_task_probe_empty(250). wait_task_probe_empty(0) -> @@ -210,8 +275,11 @@ wait_task_probe_empty(0) -> wait_task_probe_empty(N) -> gc_all(), case py:eval(<<"(__import__('gc').collect(), len(__import__('sys')._task_env_probe))[1]">>) of - {ok, 0} -> ok; - _ -> timer:sleep(20), wait_task_probe_empty(N - 1) + {ok, 0} -> + ok; + _ -> + timer:sleep(20), + wait_task_probe_empty(N - 1) end. %% An env reference sent to a context process (py_context:exec(Ctx, Code, diff --git a/test/py_context_owngil_SUITE.erl b/test/py_context_owngil_SUITE.erl index 66f7c2d..c0bf0af 100644 --- a/test/py_context_owngil_SUITE.erl +++ b/test/py_context_owngil_SUITE.erl @@ -59,41 +59,45 @@ ]). all() -> - [{group, lifecycle}, - {group, basic_ops}, - {group, ipc}, - {group, isolation}, - {group, parallelism}, - {group, features}]. + [ + {group, lifecycle}, + {group, basic_ops}, + {group, ipc}, + {group, isolation}, + {group, parallelism}, + {group, features} + ]. groups() -> - [{lifecycle, [sequence], [ - test_owngil_context_create, - test_owngil_thread_init, - test_owngil_context_destroy - ]}, - {basic_ops, [sequence], [ - test_owngil_basic_call, - test_owngil_eval, - test_owngil_exec - ]}, - {ipc, [sequence], [ - test_owngil_type_conversions, - test_owngil_large_data, - test_owngil_binary_data - ]}, - {isolation, [sequence], [ - test_owngil_isolation, - test_owngil_interp_id - ]}, - {parallelism, [parallel], [ - test_owngil_parallel_execution, - test_owngil_concurrent_sleep - ]}, - {features, [sequence], [ - test_owngil_state_persistence, - test_owngil_module_import - ]}]. + [ + {lifecycle, [sequence], [ + test_owngil_context_create, + test_owngil_thread_init, + test_owngil_context_destroy + ]}, + {basic_ops, [sequence], [ + test_owngil_basic_call, + test_owngil_eval, + test_owngil_exec + ]}, + {ipc, [sequence], [ + test_owngil_type_conversions, + test_owngil_large_data, + test_owngil_binary_data + ]}, + {isolation, [sequence], [ + test_owngil_isolation, + test_owngil_interp_id + ]}, + {parallelism, [parallel], [ + test_owngil_parallel_execution, + test_owngil_concurrent_sleep + ]}, + {features, [sequence], [ + test_owngil_state_persistence, + test_owngil_module_import + ]} + ]. init_per_suite(Config) -> case py_nif:owngil_supported() of @@ -256,7 +260,9 @@ test_owngil_parallel_execution(_Config) -> NumContexts -> run_parallel_test(Contexts); N when N >= 2 -> - ct:pal("Only ~p of ~p contexts created, running with reduced parallelism", [N, NumContexts]), + ct:pal("Only ~p of ~p contexts created, running with reduced parallelism", [ + N, NumContexts + ]), run_parallel_test(Contexts); _ -> [py_context:stop(Ctx) || Ctx <- Contexts], @@ -266,7 +272,8 @@ test_owngil_parallel_execution(_Config) -> create_owngil_contexts(0, Acc) -> lists:reverse(Acc); create_owngil_contexts(N, Acc) -> - timer:sleep(50), %% Small delay between context creations + %% Small delay between context creations + timer:sleep(50), case py_context:start_link(N, owngil) of {ok, Ctx} -> create_owngil_contexts(N - 1, [Ctx | Acc]); @@ -287,15 +294,25 @@ run_parallel_test(Contexts) -> %% Parallel execution timing ParStart = erlang:monotonic_time(millisecond), - Pids = [spawn(fun() -> - Result = py_context:eval(Ctx, Code, #{}), - Parent ! {done, self(), Result} - end) || Ctx <- Contexts], - [receive {done, Pid, _Result} -> ok end || Pid <- Pids], + Pids = [ + spawn(fun() -> + Result = py_context:eval(Ctx, Code, #{}), + Parent ! {done, self(), Result} + end) + || Ctx <- Contexts + ], + [ + receive + {done, Pid, _Result} -> ok + end + || Pid <- Pids + ], ParTime = erlang:monotonic_time(millisecond) - ParStart, - ct:pal("Sequential: ~p ms, Parallel: ~p ms, Speedup: ~.2fx", - [SeqTime, ParTime, SeqTime / max(1, ParTime)]), + ct:pal( + "Sequential: ~p ms, Parallel: ~p ms, Speedup: ~.2fx", + [SeqTime, ParTime, SeqTime / max(1, ParTime)] + ), %% With OWN_GIL, parallel should be significantly faster %% Use a conservative check - parallel should be at least 1.3x faster @@ -321,8 +338,12 @@ test_owngil_concurrent_sleep(_Config) -> Parent ! {done, 2} end), - receive {done, _} -> ok end, - receive {done, _} -> ok end, + receive + {done, _} -> ok + end, + receive + {done, _} -> ok + end, Elapsed = erlang:monotonic_time(millisecond) - Start, ct:pal("Two 100ms sleeps completed in ~p ms", [Elapsed]), diff --git a/test/py_context_process_SUITE.erl b/test/py_context_process_SUITE.erl index e19f0e3..083eebc 100644 --- a/test/py_context_process_SUITE.erl +++ b/test/py_context_process_SUITE.erl @@ -219,28 +219,39 @@ test_multiple_contexts(Config) -> NumContexts = 4, %% Start multiple contexts - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, Mode), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, Mode), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], try %% Run calls in parallel Parent = self(), - Pids = [spawn_link(fun() -> - Results = [py_context:call(Ctx, math, sqrt, [N*N], #{}) - || N <- lists:seq(1, 10)], - Parent ! {self(), Results} - end) || Ctx <- Contexts], + Pids = [ + spawn_link(fun() -> + Results = [ + py_context:call(Ctx, math, sqrt, [N * N], #{}) + || N <- lists:seq(1, 10) + ], + Parent ! {self(), Results} + end) + || Ctx <- Contexts + ], %% Collect results - [receive - {Pid, Results} -> - %% Verify all calls succeeded - lists:foreach(fun({ok, _}) -> ok end, Results) - after 5000 -> - ct:fail("Timeout waiting for results") - end || Pid <- Pids] + [ + receive + {Pid, Results} -> + %% Verify all calls succeeded + lists:foreach(fun({ok, _}) -> ok end, Results) + after 5000 -> + ct:fail("Timeout waiting for results") + end + || Pid <- Pids + ] after [py_context:stop(Ctx) || Ctx <- Contexts] end. @@ -256,21 +267,30 @@ test_context_parallel_calls(Config) -> Parent = self(), NumCalls = 20, - Pids = [spawn_link(fun() -> - Result = py_context:call(Ctx, math, sqrt, [N*N], #{}), - Parent ! {self(), N, Result} - end) || N <- lists:seq(1, NumCalls)], - - Results = [receive - {Pid, N, Result} -> {N, Result} - after 5000 -> - ct:fail("Timeout") - end || Pid <- Pids], + Pids = [ + spawn_link(fun() -> + Result = py_context:call(Ctx, math, sqrt, [N * N], #{}), + Parent ! {self(), N, Result} + end) + || N <- lists:seq(1, NumCalls) + ], + + Results = [ + receive + {Pid, N, Result} -> {N, Result} + after 5000 -> + ct:fail("Timeout") + end + || Pid <- Pids + ], %% Verify all returned correct values - lists:foreach(fun({N, {ok, Val}}) -> - true = abs(Val - float(N)) < 0.0001 - end, Results) + lists:foreach( + fun({N, {ok, Val}}) -> + true = abs(Val - float(N)) < 0.0001 + end, + Results + ) after py_context:stop(Ctx) end. diff --git a/test/py_context_router_SUITE.erl b/test/py_context_router_SUITE.erl index 1ee1d8f..8fd941e 100644 --- a/test/py_context_router_SUITE.erl +++ b/test/py_context_router_SUITE.erl @@ -49,12 +49,20 @@ end_per_suite(_Config) -> init_per_testcase(_TestCase, Config) -> %% Ensure router is stopped before each test - try py_context_router:stop() catch _:_ -> ok end, + try + py_context_router:stop() + catch + _:_ -> ok + end, Config. end_per_testcase(_TestCase, _Config) -> %% Clean up after each test - try py_context_router:stop() catch _:_ -> ok end, + try + py_context_router:stop() + catch + _:_ -> ok + end, ok. %% ============================================================================ @@ -69,9 +77,12 @@ test_start_stop(_Config) -> true = length(Contexts) > 0, %% All contexts should be alive - lists:foreach(fun(Ctx) -> - true = is_process_alive(Ctx) - end, Contexts), + lists:foreach( + fun(Ctx) -> + true = is_process_alive(Ctx) + end, + Contexts + ), %% num_contexts should match NumContexts = py_context_router:num_contexts(), @@ -85,9 +96,12 @@ test_start_stop(_Config) -> %% Contexts should be dead after stop timer:sleep(100), - lists:foreach(fun(Ctx) -> - false = is_process_alive(Ctx) - end, Contexts), + lists:foreach( + fun(Ctx) -> + false = is_process_alive(Ctx) + end, + Contexts + ), %% num_contexts should be 0 after stop 0 = py_context_router:num_contexts(). @@ -155,16 +169,22 @@ test_cross_scheduler_distribution(_Config) -> Parent = self(), NumProcs = 100, - Pids = [spawn(fun() -> - Ctx = py_context_router:get_context(), - Parent ! {self(), Ctx} - end) || _ <- lists:seq(1, NumProcs)], - - Contexts = [receive - {Pid, Ctx} -> Ctx - after 5000 -> - ct:fail("Timeout waiting for context") - end || Pid <- Pids], + Pids = [ + spawn(fun() -> + Ctx = py_context_router:get_context(), + Parent ! {self(), Ctx} + end) + || _ <- lists:seq(1, NumProcs) + ], + + Contexts = [ + receive + {Pid, Ctx} -> Ctx + after 5000 -> + ct:fail("Timeout waiting for context") + end + || Pid <- Pids + ], %% Should have used at least one context UniqueContexts = lists:usort(Contexts), @@ -193,17 +213,20 @@ test_context_calls(_Config) -> %% @doc Test multiple start/stop cycles. test_multiple_start_stop(_Config) -> - lists:foreach(fun(_) -> - {ok, Contexts1} = py_context_router:start(#{contexts => 2}), - 2 = length(Contexts1), - - %% Make a call to verify it works - Ctx = py_context_router:get_context(), - {ok, 4.0} = py_context:call(Ctx, math, sqrt, [16], #{}), - - ok = py_context_router:stop(), - timer:sleep(50) - end, lists:seq(1, 3)). + lists:foreach( + fun(_) -> + {ok, Contexts1} = py_context_router:start(#{contexts => 2}), + 2 = length(Contexts1), + + %% Make a call to verify it works + Ctx = py_context_router:get_context(), + {ok, 4.0} = py_context:call(Ctx, math, sqrt, [16], #{}), + + ok = py_context_router:stop(), + timer:sleep(50) + end, + lists:seq(1, 3) + ). %% @doc Test with custom number of contexts. test_custom_num_contexts(_Config) -> diff --git a/test/py_erlang_sleep_SUITE.erl b/test/py_erlang_sleep_SUITE.erl index d876e98..0af3cd1 100644 --- a/test/py_erlang_sleep_SUITE.erl +++ b/test/py_erlang_sleep_SUITE.erl @@ -40,137 +40,145 @@ end_per_suite(_Config) -> %% Test that erlang.sleep is available test_erlang_sleep_available(_Config) -> - ok = py:exec(<<" -import erlang -result = hasattr(erlang, 'sleep') -assert result, 'erlang.sleep not found' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "result = hasattr(erlang, 'sleep')\n" + "assert result, 'erlang.sleep not found'\n" + >>), ct:pal("erlang.sleep is available"), ok. %% Test basic sleep functionality (sync context via callback) test_erlang_sleep_basic(_Config) -> - ok = py:exec(<<" -import erlang -# Test basic sleep in sync context - should not raise -erlang.sleep(0.01) # 10ms -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "# Test basic sleep in sync context - should not raise\n" + "erlang.sleep(0.01) # 10ms\n" + >>), ct:pal("Basic sleep completed"), ok. %% Test zero/negative delay returns immediately test_erlang_sleep_zero(_Config) -> - ok = py:exec(<<" -import erlang -import time - -start = time.time() -erlang.sleep(0) -elapsed = (time.time() - start) * 1000 -# Should return immediately (< 10ms accounting for Python overhead) -assert elapsed < 10, f'Zero sleep was slow: {elapsed}ms' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import time\n" + "\n" + "start = time.time()\n" + "erlang.sleep(0)\n" + "elapsed = (time.time() - start) * 1000\n" + "# Should return immediately (< 10ms accounting for Python overhead)\n" + "assert elapsed < 10, f'Zero sleep was slow: {elapsed}ms'\n" + >>), ct:pal("Zero sleep returned fast"), ok. %% Test sleep accuracy test_erlang_sleep_accuracy(_Config) -> - ok = py:exec(<<" -import erlang -import time - -delays = [0.01, 0.05, 0.1] # seconds -for delay in delays: - start = time.time() - erlang.sleep(delay) - elapsed = time.time() - start - # Allow wide tolerance for CI runners (can be slow/unpredictable) - assert delay * 0.5 <= elapsed <= delay * 10.0, \\ - f'{delay}s sleep took {elapsed:.3f}s' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import time\n" + "\n" + "delays = [0.01, 0.05, 0.1] # seconds\n" + "for delay in delays:\n" + " start = time.time()\n" + " erlang.sleep(delay)\n" + " elapsed = time.time() - start\n" + " # Allow wide tolerance for CI runners (can be slow/unpredictable)\n" + " assert delay * 0.5 <= elapsed <= delay * 10.0, \\\n" + " f'{delay}s sleep took {elapsed:.3f}s'\n" + >>), ct:pal("Sleep accuracy within tolerance"), ok. %% Test erlang.run() with asyncio test_erlang_run_module(_Config) -> - ok = py:exec(<<" -import erlang -import asyncio - -# Test erlang module has expected functions for event loop integration -funcs = ['run', 'new_event_loop', 'EventLoopPolicy', 'sleep'] -for f in funcs: - assert hasattr(erlang, f), f'erlang missing {f}' - -# Test run() with asyncio.sleep -async def test_sleep(): - await asyncio.sleep(0.01) # 10ms - return 'done' - -result = erlang.run(test_sleep()) -assert result == 'done', f'Expected done, got {result}' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import asyncio\n" + "\n" + "# Test erlang module has expected functions for event loop integration\n" + "funcs = ['run', 'new_event_loop', 'EventLoopPolicy', 'sleep']\n" + "for f in funcs:\n" + " assert hasattr(erlang, f), f'erlang missing {f}'\n" + "\n" + "# Test run() with asyncio.sleep\n" + "async def test_sleep():\n" + " await asyncio.sleep(0.01) # 10ms\n" + " return 'done'\n" + "\n" + "result = erlang.run(test_sleep())\n" + "assert result == 'done', f'Expected done, got {result}'\n" + >>), ct:pal("erlang.run() with asyncio works"), ok. %% Test asyncio.gather with erlang.run() test_erlang_asyncio_gather(_Config) -> - ok = py:exec(<<" -import erlang -import asyncio - -async def task(n): - await asyncio.sleep(0.01) - return n * 2 - -async def main(): - results = await asyncio.gather(task(1), task(2), task(3)) - assert results == [2, 4, 6], f'Expected [2, 4, 6], got {results}' - -erlang.run(main()) -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import asyncio\n" + "\n" + "async def task(n):\n" + " await asyncio.sleep(0.01)\n" + " return n * 2\n" + "\n" + "async def main():\n" + " results = await asyncio.gather(task(1), task(2), task(3))\n" + " assert results == [2, 4, 6], f'Expected [2, 4, 6], got {results}'\n" + "\n" + "erlang.run(main())\n" + >>), ct:pal("asyncio.gather with erlang.run() works"), ok. %% Test asyncio.wait_for with timeout test_erlang_asyncio_wait_for(_Config) -> - ok = py:exec(<<" -import erlang -import asyncio - -async def fast_task(): - await asyncio.sleep(0.01) - return 'fast' - -async def main(): - # Should complete before timeout - result = await asyncio.wait_for(fast_task(), timeout=1.0) - assert result == 'fast', f'Expected fast, got {result}' - -erlang.run(main()) -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import asyncio\n" + "\n" + "async def fast_task():\n" + " await asyncio.sleep(0.01)\n" + " return 'fast'\n" + "\n" + "async def main():\n" + " # Should complete before timeout\n" + " result = await asyncio.wait_for(fast_task(), timeout=1.0)\n" + " assert result == 'fast', f'Expected fast, got {result}'\n" + "\n" + "erlang.run(main())\n" + >>), ct:pal("asyncio.wait_for with erlang.run() works"), ok. %% Test asyncio.create_task with erlang.run() test_erlang_asyncio_create_task(_Config) -> - ok = py:exec(<<" -import erlang -import asyncio - -async def background(): - await asyncio.sleep(0.01) - return 'background_done' - -async def main(): - task = asyncio.create_task(background()) - # Do some other work - await asyncio.sleep(0.005) - # Wait for task - result = await task - assert result == 'background_done', f'Expected background_done, got {result}' - -erlang.run(main()) -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import asyncio\n" + "\n" + "async def background():\n" + " await asyncio.sleep(0.01)\n" + " return 'background_done'\n" + "\n" + "async def main():\n" + " task = asyncio.create_task(background())\n" + " # Do some other work\n" + " await asyncio.sleep(0.005)\n" + " # Wait for task\n" + " result = await task\n" + " assert result == 'background_done', f'Expected background_done, got {result}'\n" + "\n" + "erlang.run(main())\n" + >>), ct:pal("asyncio.create_task with erlang.run() works"), ok. diff --git a/test/py_event_loop_SUITE.erl b/test/py_event_loop_SUITE.erl index 86ff2dd..3487229 100644 --- a/test/py_event_loop_SUITE.erl +++ b/test/py_event_loop_SUITE.erl @@ -328,7 +328,8 @@ test_poll_events_timeout(_Config) -> %% Should have 0 events and taken ~50ms 0 = NumEvents, Elapsed = T2 - T1, - true = Elapsed >= 40, %% Allow some tolerance + %% Allow some tolerance + true = Elapsed >= 40, py_event_worker:stop(WorkerPid), py_nif:event_loop_destroy(LoopRef), @@ -357,7 +358,8 @@ test_event_loop_wakeup(_Config) -> %% Should receive quickly (not 5 seconds) receive {poll_done, Elapsed} -> - true = Elapsed < 1000 %% Should be much less than 5000ms + %% Should be much less than 5000ms + true = Elapsed < 1000 after 2000 -> ct:fail(poll_not_woken_up) end, diff --git a/test/py_event_loop_pool_SUITE.erl b/test/py_event_loop_pool_SUITE.erl index d1e39a8..e3409dc 100644 --- a/test/py_event_loop_pool_SUITE.erl +++ b/test/py_event_loop_pool_SUITE.erl @@ -147,8 +147,10 @@ test_spawn_task(_Config) -> test_concurrent_tasks(_Config) -> NumTasks = 50, - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) - || I <- lists:seq(1, NumTasks)], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) + || I <- lists:seq(1, NumTasks) + ], ct:log("Created ~p tasks", [length(Refs)]), Results = [py_event_loop_pool:await(Ref, 5000) || Ref <- Refs], @@ -166,8 +168,10 @@ test_concurrent_tasks(_Config) -> test_tasks_execute_in_order(_Config) -> %% All tasks from this process go to the same loop, so they execute in order - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I)]) - || I <- [1, 4, 9, 16, 25]], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I)]) + || I <- [1, 4, 9, 16, 25] + ], Results = [py_event_loop_pool:await(Ref, 5000) || Ref <- Refs], ct:log("Results: ~p", [Results]), @@ -189,21 +193,45 @@ test_tasks_execute_in_order(_Config) -> %% long enough to go through erlang:send_after. test_concurrent_sleeps_complete(_Config) -> TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), N = 32, SleepMs = 100, Self = self(), %% One process per task: get_loop/0 binds a loop per calling process - Pids = [spawn_link(fun() -> - {ok, Loop} = py_event_loop_pool:get_loop(), - Ref = make_ref(), - ok = py_nif:submit_task(Loop, self(), Ref, <<"py_test_pool_sleep">>, - <<"nap">>, [SleepMs], #{}), - R = receive {async_result, Ref, X} -> X after 5000 -> timeout end, - Self ! {done, self(), Loop, R} - end) || _ <- lists:seq(1, N)], - Results = [receive {done, Pid, Loop, R} -> {Loop, R} end || Pid <- Pids], + Pids = [ + spawn_link(fun() -> + {ok, Loop} = py_event_loop_pool:get_loop(), + Ref = make_ref(), + ok = py_nif:submit_task( + Loop, + self(), + Ref, + <<"py_test_pool_sleep">>, + <<"nap">>, + [SleepMs], + #{} + ), + R = + receive + {async_result, Ref, X} -> X + after 5000 -> timeout + end, + Self ! {done, self(), Loop, R} + end) + || _ <- lists:seq(1, N) + ], + Results = [ + receive + {done, Pid, Loop, R} -> {Loop, R} + end + || Pid <- Pids + ], Timeouts = [x || {_, timeout} <- Results], ct:log("results: ~p", [Results]), [] = Timeouts, @@ -240,10 +268,11 @@ test_exec_eval_namespace(_Config) -> test_exec_define_function(_Config) -> %% Define a function via exec and call it via create_task - ok = py_event_loop_pool:exec(<<" -def pool_test_multiply(a, b): - return a * b -">>), + ok = py_event_loop_pool:exec(<< + "\n" + "def pool_test_multiply(a, b):\n" + " return a * b\n" + >>), %% Call the function via create_task Ref = py_event_loop_pool:create_task('__main__', pool_test_multiply, [7, 6]), diff --git a/test/py_event_loop_pool_owngil_SUITE.erl b/test/py_event_loop_pool_owngil_SUITE.erl index db491fb..b875de7 100644 --- a/test/py_event_loop_pool_owngil_SUITE.erl +++ b/test/py_event_loop_pool_owngil_SUITE.erl @@ -41,17 +41,19 @@ all() -> [{group, owngil_tests}]. groups() -> - [{owngil_tests, [sequence], [ - test_owngil_pool_stats, - test_owngil_session_creation, - test_sync_function_call, - test_async_coroutine_call, - test_concurrent_tasks, - test_same_process_same_worker, - test_tasks_execute_in_order, - test_session_cleanup_on_process_exit, - test_true_parallel_execution - ]}]. + [ + {owngil_tests, [sequence], [ + test_owngil_pool_stats, + test_owngil_session_creation, + test_sync_function_call, + test_async_coroutine_call, + test_concurrent_tasks, + test_same_process_same_worker, + test_tasks_execute_in_order, + test_session_cleanup_on_process_exit, + test_true_parallel_execution + ]} + ]. init_per_suite(Config) -> %% Check if subinterpreters are supported @@ -84,7 +86,8 @@ wait_for_owngil_pool(Timeout) when Timeout =< 0 -> wait_for_owngil_pool(Timeout) -> Stats = py_event_loop_pool:get_stats(), case maps:get(owngil_enabled, Stats, false) of - true -> ok; + true -> + ok; false -> timer:sleep(100), wait_for_owngil_pool(Timeout - 100) @@ -154,8 +157,10 @@ test_async_coroutine_call(_Config) -> test_concurrent_tasks(_Config) -> NumTasks = 20, - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) - || I <- lists:seq(1, NumTasks)], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) + || I <- lists:seq(1, NumTasks) + ], ct:log("Created ~p tasks", [length(Refs)]), Results = [py_event_loop_pool:await(Ref, 5000) || Ref <- Refs], @@ -173,8 +178,10 @@ test_same_process_same_worker(_Config) -> %% (same process always routes to same worker due to PID hashing) %% Submit multiple tasks from this process - they all go to same worker - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) - || I <- lists:seq(1, 5)], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I * I)]) + || I <- lists:seq(1, 5) + ], Results = [py_event_loop_pool:await(Ref, 5000) || Ref <- Refs], ct:log("Results: ~p", [Results]), @@ -186,8 +193,10 @@ test_same_process_same_worker(_Config) -> test_tasks_execute_in_order(_Config) -> %% All tasks from this process go to the same worker, so they execute in order - Refs = [py_event_loop_pool:create_task(math, sqrt, [float(I)]) - || I <- [1, 4, 9, 16, 25]], + Refs = [ + py_event_loop_pool:create_task(math, sqrt, [float(I)]) + || I <- [1, 4, 9, 16, 25] + ], Results = [py_event_loop_pool:await(Ref, 5000) || Ref <- Refs], ct:log("Results: ~p", [Results]), @@ -208,20 +217,28 @@ test_session_cleanup_on_process_exit(_Config) -> NumProcs = 5, %% Spawn multiple processes that create sessions - Pids = [spawn(fun() -> - %% Create a task which creates a session - Ref = py_event_loop_pool:create_task(math, sqrt, [9.0]), - {ok, 3.0} = py_event_loop_pool:await(Ref, 5000), - Parent ! {self(), session_created}, - receive stop -> ok end - end) || _ <- lists:seq(1, NumProcs)], + Pids = [ + spawn(fun() -> + %% Create a task which creates a session + Ref = py_event_loop_pool:create_task(math, sqrt, [9.0]), + {ok, 3.0} = py_event_loop_pool:await(Ref, 5000), + Parent ! {self(), session_created}, + receive + stop -> ok + end + end) + || _ <- lists:seq(1, NumProcs) + ], %% Wait for all sessions to be created - [receive - {Pid, session_created} -> ok - after 5000 -> - ct:fail({timeout_waiting_for_session, Pid}) - end || Pid <- Pids], + [ + receive + {Pid, session_created} -> ok + after 5000 -> + ct:fail({timeout_waiting_for_session, Pid}) + end + || Pid <- Pids + ], %% Check stats after creation Stats1 = py_event_loop_pool:get_stats(), @@ -230,7 +247,8 @@ test_session_cleanup_on_process_exit(_Config) -> %% Kill all processes [Pid ! stop || Pid <- Pids], - timer:sleep(500), %% Give time for cleanup + %% Give time for cleanup + timer:sleep(500), %% Verify session count after cleanup Stats2 = py_event_loop_pool:get_stats(), @@ -255,14 +273,23 @@ test_true_parallel_execution(_Config) -> T1 = erlang:monotonic_time(millisecond), %% Run math.sqrt tasks in parallel from different processes - Pids = [spawn(fun() -> - Ref = py_event_loop_pool:create_task(math, sqrt, [float(I * I)]), - Result = py_event_loop_pool:await(Ref, 5000), - Parent ! {self(), Result} - end) || I <- lists:seq(1, NumWorkers)], + Pids = [ + spawn(fun() -> + Ref = py_event_loop_pool:create_task(math, sqrt, [float(I * I)]), + Result = py_event_loop_pool:await(Ref, 5000), + Parent ! {self(), Result} + end) + || I <- lists:seq(1, NumWorkers) + ], %% Collect results - Results = [receive {Pid, R} -> R after 5000 -> {error, timeout} end || Pid <- Pids], + Results = [ + receive + {Pid, R} -> R + after 5000 -> {error, timeout} + end + || Pid <- Pids + ], T2 = erlang:monotonic_time(millisecond), Elapsed = T2 - T1, diff --git a/test/py_import_SUITE.erl b/test/py_import_SUITE.erl index 8e3599c..fd849ee 100644 --- a/test/py_import_SUITE.erl +++ b/test/py_import_SUITE.erl @@ -57,43 +57,45 @@ all() -> [{group, import_tests}]. groups() -> - [{import_tests, [sequence], [ - import_module_test, - import_function_test, - import_main_rejected_test, - import_nonexistent_module_test, - import_nonexistent_function_test, - import_idempotent_test, - import_list_test, - import_speeds_up_calls_test, - import_multiprocess_test, - import_concurrent_stress_test, - %% Import registry tests - import_registry_test, - import_applied_to_new_context_test, - clear_imports_test, - get_imports_test, - %% Per-interpreter sharing tests - shared_interpreter_import_test, - event_loop_pool_import_test, - spawn_task_uses_import_test, - subinterp_isolation_test, - registry_applied_to_subinterp_test, - %% sys.modules verification tests - import_in_sys_modules_test, - registry_import_in_sys_modules_test, - context_import_in_sys_modules_test, - %% Path registry tests - add_path_test, - %% Immediate application tests - import_applies_to_running_interpreter_test, - path_applies_to_running_interpreter_test, - %% OWN_GIL session tests - owngil_session_import_test, - owngil_session_path_test, - %% Config initialization tests - init_from_config_test - ]}]. + [ + {import_tests, [sequence], [ + import_module_test, + import_function_test, + import_main_rejected_test, + import_nonexistent_module_test, + import_nonexistent_function_test, + import_idempotent_test, + import_list_test, + import_speeds_up_calls_test, + import_multiprocess_test, + import_concurrent_stress_test, + %% Import registry tests + import_registry_test, + import_applied_to_new_context_test, + clear_imports_test, + get_imports_test, + %% Per-interpreter sharing tests + shared_interpreter_import_test, + event_loop_pool_import_test, + spawn_task_uses_import_test, + subinterp_isolation_test, + registry_applied_to_subinterp_test, + %% sys.modules verification tests + import_in_sys_modules_test, + registry_import_in_sys_modules_test, + context_import_in_sys_modules_test, + %% Path registry tests + add_path_test, + %% Immediate application tests + import_applies_to_running_interpreter_test, + path_applies_to_running_interpreter_test, + %% OWN_GIL session tests + owngil_session_import_test, + owngil_session_path_test, + %% Config initialization tests + init_from_config_test + ]} + ]. init_per_suite(Config) -> application:ensure_all_started(erlang_python), @@ -168,7 +170,9 @@ import_nonexistent_module_test(_Config) -> %% But trying to use it fails %% Error format is {error, {ExceptionType, Message}} or {error, atom()} {error, Reason} = py:call(nonexistent_module_xyz, some_func, []), - ?assert(is_tuple(Reason) orelse is_list(Reason) orelse is_binary(Reason) orelse is_atom(Reason)), + ?assert( + is_tuple(Reason) orelse is_list(Reason) orelse is_binary(Reason) orelse is_atom(Reason) + ), ct:pal("Nonexistent module error at call time: ~p", [Reason]). @@ -246,7 +250,7 @@ import_speeds_up_calls_test(_Config) -> %% Time a cold call (module not imported) %% Using json.dumps since hashlib.md5 needs bytes encoding {ColdTime, {ok, _}} = timer:tc(fun() -> - py:call(json, dumps, [[1,2,3,4,5]]) + py:call(json, dumps, [[1, 2, 3, 4, 5]]) end), %% Pre-import the module and function @@ -255,7 +259,7 @@ import_speeds_up_calls_test(_Config) -> %% Time a warm call (module already imported) {WarmTime, {ok, _}} = timer:tc(fun() -> - py:call(json, dumps, [[1,2,3,4,5]]) + py:call(json, dumps, [[1, 2, 3, 4, 5]]) end), ct:pal("Cold call time: ~p us, Warm call time: ~p us", [ColdTime, WarmTime]), @@ -280,7 +284,7 @@ import_multiprocess_test(_Config) -> ok = py_import:ensure_imported(json), ok = py_import:ensure_imported(json, dumps), %% Verify we can use the import - {ok, _} = py:call(json, dumps, [[1,2,3]]), + {ok, _} = py:call(json, dumps, [[1, 2, 3]]), Parent ! {self(), done} end), @@ -303,8 +307,13 @@ import_multiprocess_test(_Config) -> end), %% Collect results from all 3 processes - Results = [receive {Pid, Result} -> Result after 5000 -> timeout end - || Pid <- [Pid1, Pid2, Pid3]], + Results = [ + receive + {Pid, Result} -> Result + after 5000 -> timeout + end + || Pid <- [Pid1, Pid2, Pid3] + ], %% Verify no timeouts ?assertEqual(false, lists:member(timeout, Results)), @@ -345,31 +354,43 @@ import_concurrent_stress_test(_Config) -> ok = py_import:clear_imports(), %% Spawn many processes that all try to import at the same time - Pids = [spawn_link(fun() -> - %% Each process imports a random subset of modules - MyModules = lists:sublist(Modules, 1 + (N rem length(Modules))), - Results = [{M, py_import:ensure_imported(M)} || M <- MyModules], + Pids = [ + spawn_link(fun() -> + %% Each process imports a random subset of modules + MyModules = lists:sublist(Modules, 1 + (N rem length(Modules))), + Results = [{M, py_import:ensure_imported(M)} || M <- MyModules], - %% All imports should succeed - AllOk = lists:all(fun({_, R}) -> R =:= ok end, Results), + %% All imports should succeed + AllOk = lists:all(fun({_, R}) -> R =:= ok end, Results), - %% Make a call to verify imports work - CallResult = py:call(json, dumps, [[N]]), + %% Make a call to verify imports work + CallResult = py:call(json, dumps, [[N]]), - Parent ! {self(), {AllOk, CallResult}} - end) || N <- lists:seq(1, NumProcesses)], + Parent ! {self(), {AllOk, CallResult}} + end) + || N <- lists:seq(1, NumProcesses) + ], %% Collect all results - Results = [receive {Pid, Result} -> Result after 10000 -> timeout end || Pid <- Pids], + Results = [ + receive + {Pid, Result} -> Result + after 10000 -> timeout + end + || Pid <- Pids + ], %% Verify no timeouts ?assertEqual(false, lists:member(timeout, Results)), %% Verify all processes succeeded - lists:foreach(fun({AllOk, CallResult}) -> - ?assertEqual(true, AllOk), - ?assertMatch({ok, _}, CallResult) - end, Results), + lists:foreach( + fun({AllOk, CallResult}) -> + ?assertEqual(true, AllOk), + ?assertMatch({ok, _}, CallResult) + end, + Results + ), %% Verify the global registry has all modules Count = length(py_import:all_imports()), @@ -531,11 +552,12 @@ spawn_task_uses_import_test(_Config) -> ok = py_import:ensure_imported(base64), %% Define a simple function that uses base64 - Code = <<" -def encode_test(data): - import base64 - return base64.b64encode(data.encode()).decode() -">>, + Code = << + "\n" + "def encode_test(data):\n" + " import base64\n" + " return base64.b64encode(data.encode()).decode()\n" + >>, ok = py:exec(Code), %% Use spawn_task to call our function @@ -642,10 +664,11 @@ import_in_sys_modules_test(_Config) -> %% Now check sys.modules using the same process (important!) %% We use exec to define a helper, then eval to check - ok = py:exec(<<" -import sys -_test_textwrap_in_sys = 'textwrap' in sys.modules -">>), + ok = py:exec(<< + "\n" + "import sys\n" + "_test_textwrap_in_sys = 'textwrap' in sys.modules\n" + >>), {ok, InSysModules} = py:eval(<<"_test_textwrap_in_sys">>), ?assertEqual(true, InSysModules), @@ -677,12 +700,13 @@ registry_import_in_sys_modules_test(_Config) -> {ok, _} = py:call(json, dumps, [[1, 2, 3]]), %% Verify both are in sys.modules by checking from Python - ok = py:exec(<<" -import sys -_fractions_in_sys = 'fractions' in sys.modules -_json_in_sys = 'json' in sys.modules -_sys_modules_keys = list(sys.modules.keys()) -">>), + ok = py:exec(<< + "\n" + "import sys\n" + "_fractions_in_sys = 'fractions' in sys.modules\n" + "_json_in_sys = 'json' in sys.modules\n" + "_sys_modules_keys = list(sys.modules.keys())\n" + >>), {ok, FractionsInSys} = py:eval(<<"_fractions_in_sys">>), {ok, JsonInSys} = py:eval(<<"_json_in_sys">>), @@ -712,11 +736,12 @@ context_import_in_sys_modules_test(_Config) -> %% Check if textwrap is in sys.modules of this interpreter %% Use exec then eval pattern for reliable checking - ok = py_context:exec(Ctx, <<" -import sys -_textwrap_in_sys = 'textwrap' in sys.modules -_sys_keys = list(sys.modules.keys()) -">>), + ok = py_context:exec(Ctx, << + "\n" + "import sys\n" + "_textwrap_in_sys = 'textwrap' in sys.modules\n" + "_sys_keys = list(sys.modules.keys())\n" + >>), {ok, InSysModules} = py_context:eval(Ctx, <<"_textwrap_in_sys">>), ?assertEqual(true, InSysModules), @@ -749,13 +774,15 @@ add_path_test(Config) -> %% Write a simple Python module ModulePath = filename:join(ModuleDir, "sample_module.py"), - ModuleContent = <<"def greet(name):\n" - " return f\"Hello, {name}!\"\n" - "\n" - "def add(a, b):\n" - " return a + b\n" - "\n" - "VERSION = \"1.0.0\"\n">>, + ModuleContent = << + "def greet(name):\n" + " return f\"Hello, {name}!\"\n" + "\n" + "def add(a, b):\n" + " return a + b\n" + "\n" + "VERSION = \"1.0.0\"\n" + >>, ok = file:write_file(ModulePath, ModuleContent), %% Add path diff --git a/test/py_import_owngil_SUITE.erl b/test/py_import_owngil_SUITE.erl index 7bee5fc..e0bb014 100644 --- a/test/py_import_owngil_SUITE.erl +++ b/test/py_import_owngil_SUITE.erl @@ -41,25 +41,29 @@ ]). all() -> - [{group, basic_imports}, - {group, isolation}, - {group, stress}]. + [ + {group, basic_imports}, + {group, isolation}, + {group, stress} + ]. groups() -> - [{basic_imports, [sequence], [ - owngil_import_module_test, - owngil_import_function_test, - owngil_import_main_rejected_test, - owngil_import_stats_test, - owngil_import_list_test - ]}, - {isolation, [sequence], [ - owngil_import_isolation_test, - owngil_import_parallel_contexts_test - ]}, - {stress, [sequence], [ - owngil_import_concurrent_test - ]}]. + [ + {basic_imports, [sequence], [ + owngil_import_module_test, + owngil_import_function_test, + owngil_import_main_rejected_test, + owngil_import_stats_test, + owngil_import_list_test + ]}, + {isolation, [sequence], [ + owngil_import_isolation_test, + owngil_import_parallel_contexts_test + ]}, + {stress, [sequence], [ + owngil_import_concurrent_test + ]} + ]. init_per_suite(Config) -> %% Start application first (loads NIF) @@ -147,10 +151,11 @@ owngil_import_main_rejected_test(_Config) -> Ctx = create_owngil_context(), try %% Define a function in __main__ - ok = py_context:exec(Ctx, <<" -def my_func(x): - return x * 2 -">>), + ok = py_context:exec(Ctx, << + "\n" + "def my_func(x):\n" + " return x * 2\n" + >>), %% Call the function defined in __main__ {ok, Result} = py_context:call(Ctx, '__main__', my_func, [21]), @@ -202,16 +207,18 @@ owngil_import_isolation_test(_Config) -> Ctx2 = create_owngil_context(), try %% Define a variable in Ctx1 - ok = py_context:exec(Ctx1, <<" -import json -MY_VAR = 'context1' -">>), + ok = py_context:exec(Ctx1, << + "\n" + "import json\n" + "MY_VAR = 'context1'\n" + >>), %% Define a different variable in Ctx2 - ok = py_context:exec(Ctx2, <<" -import math -MY_VAR = 'context2' -">>), + ok = py_context:exec(Ctx2, << + "\n" + "import math\n" + "MY_VAR = 'context2'\n" + >>), %% Verify isolation - Ctx1 has json but not math imported the same way {ok, R1} = py_context:eval(Ctx1, <<"MY_VAR">>), @@ -234,53 +241,69 @@ owngil_import_parallel_contexts_test(_Config) -> NumContexts = 3, %% Spawn processes, each with its own OWN_GIL context - Pids = [spawn_link(fun() -> - Ctx = create_owngil_context(), - try - %% Each context imports different modules - Modules = case N rem 3 of - 0 -> [<<"json">>, <<"base64">>]; - 1 -> [<<"math">>, <<"string">>]; - 2 -> [<<"os">>, <<"re">>] - end, - - %% Import modules - lists:foreach(fun(Mod) -> - Code = <<"import ", Mod/binary>>, - ok = py_context:exec(Ctx, Code) - end, Modules), - - %% Define context-specific state - StateCode = list_to_binary(io_lib:format("CTX_ID = ~p", [N])), - ok = py_context:exec(Ctx, StateCode), - - %% Verify state - {ok, CtxId} = py_context:eval(Ctx, <<"CTX_ID">>), - - Parent ! {self(), {ok, N, CtxId, Modules}} - catch - E:R -> - Parent ! {self(), {error, N, E, R}} - after - py_context:destroy(Ctx) - end - end) || N <- lists:seq(1, NumContexts)], + Pids = [ + spawn_link(fun() -> + Ctx = create_owngil_context(), + try + %% Each context imports different modules + Modules = + case N rem 3 of + 0 -> [<<"json">>, <<"base64">>]; + 1 -> [<<"math">>, <<"string">>]; + 2 -> [<<"os">>, <<"re">>] + end, + + %% Import modules + lists:foreach( + fun(Mod) -> + Code = <<"import ", Mod/binary>>, + ok = py_context:exec(Ctx, Code) + end, + Modules + ), + + %% Define context-specific state + StateCode = list_to_binary(io_lib:format("CTX_ID = ~p", [N])), + ok = py_context:exec(Ctx, StateCode), + + %% Verify state + {ok, CtxId} = py_context:eval(Ctx, <<"CTX_ID">>), + + Parent ! {self(), {ok, N, CtxId, Modules}} + catch + E:R -> + Parent ! {self(), {error, N, E, R}} + after + py_context:destroy(Ctx) + end + end) + || N <- lists:seq(1, NumContexts) + ], %% Collect results - Results = [receive {Pid, Result} -> Result after 10000 -> timeout end || Pid <- Pids], + Results = [ + receive + {Pid, Result} -> Result + after 10000 -> timeout + end + || Pid <- Pids + ], %% Verify all succeeded - lists:foreach(fun(Result) -> - case Result of - {ok, N, CtxId, _Modules} -> - ?assertEqual(N, CtxId), - ct:pal("Context ~p: OK", [N]); - {error, N, E, R} -> - ct:fail("Context ~p failed: ~p:~p", [N, E, R]); - timeout -> - ct:fail("Timeout waiting for context") - end - end, Results). + lists:foreach( + fun(Result) -> + case Result of + {ok, N, CtxId, _Modules} -> + ?assertEqual(N, CtxId), + ct:pal("Context ~p: OK", [N]); + {error, N, E, R} -> + ct:fail("Context ~p failed: ~p:~p", [N, E, R]); + timeout -> + ct:fail("Timeout waiting for context") + end + end, + Results + ). %% ============================================================================ %% Stress Tests @@ -293,62 +316,96 @@ owngil_import_concurrent_test(_Config) -> Modules = [<<"json">>, <<"math">>, <<"os">>, <<"string">>, <<"re">>], %% Spawn many processes with OWN_GIL contexts - Pids = [spawn_link(fun() -> - Ctx = create_owngil_context(), - try - %% Import a subset of modules - MyModules = lists:sublist(Modules, 1 + (N rem length(Modules))), - - lists:foreach(fun(Mod) -> - Code = <<"import ", Mod/binary>>, - ok = py_context:exec(Ctx, Code) - end, MyModules), - - %% Make calls to verify imports work - CallResults = lists:map(fun(Mod) -> - case Mod of - <<"json">> -> py_context:call(Ctx, json, dumps, [[N]]); - <<"math">> -> py_context:call(Ctx, math, sqrt, [float(N)]); - <<"os">> -> py_context:call(Ctx, os, getcwd, []); - <<"string">> -> py_context:call(Ctx, string, capwords, [<<"hello world">>]); - <<"re">> -> py_context:call(Ctx, re, escape, [<<"test">>]) - end - end, MyModules), - - AllOk = lists:all(fun({ok, _}) -> true; (_) -> false end, CallResults), - - Parent ! {self(), {ok, N, AllOk, length(MyModules)}} - catch - E:R:St -> - Parent ! {self(), {error, N, E, R, St}} - after - py_context:destroy(Ctx) - end - end) || N <- lists:seq(1, NumContexts)], + Pids = [ + spawn_link(fun() -> + Ctx = create_owngil_context(), + try + %% Import a subset of modules + MyModules = lists:sublist(Modules, 1 + (N rem length(Modules))), + + lists:foreach( + fun(Mod) -> + Code = <<"import ", Mod/binary>>, + ok = py_context:exec(Ctx, Code) + end, + MyModules + ), + + %% Make calls to verify imports work + CallResults = lists:map( + fun(Mod) -> + case Mod of + <<"json">> -> + py_context:call(Ctx, json, dumps, [[N]]); + <<"math">> -> + py_context:call(Ctx, math, sqrt, [float(N)]); + <<"os">> -> + py_context:call(Ctx, os, getcwd, []); + <<"string">> -> + py_context:call(Ctx, string, capwords, [<<"hello world">>]); + <<"re">> -> + py_context:call(Ctx, re, escape, [<<"test">>]) + end + end, + MyModules + ), + + AllOk = lists:all( + fun + ({ok, _}) -> true; + (_) -> false + end, + CallResults + ), + + Parent ! {self(), {ok, N, AllOk, length(MyModules)}} + catch + E:R:St -> + Parent ! {self(), {error, N, E, R, St}} + after + py_context:destroy(Ctx) + end + end) + || N <- lists:seq(1, NumContexts) + ], %% Collect results - Results = [receive {Pid, Result} -> Result after 30000 -> timeout end || Pid <- Pids], + Results = [ + receive + {Pid, Result} -> Result + after 30000 -> timeout + end + || Pid <- Pids + ], %% Count successes and failures - {Successes, Failures} = lists:partition(fun - ({ok, _, true, _}) -> true; - (_) -> false - end, Results), - - ct:pal("OWN_GIL concurrent import test: ~p successes, ~p failures", - [length(Successes), length(Failures)]), + {Successes, Failures} = lists:partition( + fun + ({ok, _, true, _}) -> true; + (_) -> false + end, + Results + ), + + ct:pal( + "OWN_GIL concurrent import test: ~p successes, ~p failures", + [length(Successes), length(Failures)] + ), %% Log any failures - lists:foreach(fun - ({error, N, E, R, _St}) -> - ct:pal("Context ~p failed: ~p:~p", [N, E, R]); - ({ok, N, false, _}) -> - ct:pal("Context ~p: calls failed", [N]); - (timeout) -> - ct:pal("Timeout"); - (_) -> - ok - end, Failures), + lists:foreach( + fun + ({error, N, E, R, _St}) -> + ct:pal("Context ~p failed: ~p:~p", [N, E, R]); + ({ok, N, false, _}) -> + ct:pal("Context ~p: calls failed", [N]); + (timeout) -> + ct:pal("Timeout"); + (_) -> + ok + end, + Failures + ), ?assertEqual(NumContexts, length(Successes)), ?assertEqual(0, length(Failures)). diff --git a/test/py_interrupt_SUITE.erl b/test/py_interrupt_SUITE.erl index ecb87aa..01c78c8 100644 --- a/test/py_interrupt_SUITE.erl +++ b/test/py_interrupt_SUITE.erl @@ -129,14 +129,16 @@ test_interrupt_idle_context(Config) -> %% around the hot loop does not swallow the interrupt. test_base_exception_not_swallowed(Config) -> Ctx = ?config(ctx, Config), - Code = <<" -def _guarded(): - while True: - try: - pass - except Exception: - pass -_guarded()">>, + Code = << + "\n" + "def _guarded():\n" + " while True:\n" + " try:\n" + " pass\n" + " except Exception:\n" + " pass\n" + "_guarded()" + >>, {error, timeout} = py_context:eval(Ctx, <<"exec('''", Code/binary, "''')">>, #{}, 500), {ok, 4} = py_context:eval(Ctx, <<"2+2">>, #{}, 5000), ok. @@ -155,14 +157,18 @@ test_no_stale_reply_in_mailbox(Config) -> %% to the next request on the same context. test_interrupt_does_not_leak_to_next_request(Config) -> Ctx = ?config(ctx, Config), - Bad = lists:foldl(fun(_, Acc) -> - %% Very short timeout so the interrupt races request completion - _ = py_context:eval(Ctx, ?BUSY, #{}, 20), - case py_context:eval(Ctx, <<"1+1">>, #{}, 5000) of - {ok, 2} -> Acc; - Other -> [Other | Acc] - end - end, [], lists:seq(1, 50)), + Bad = lists:foldl( + fun(_, Acc) -> + %% Very short timeout so the interrupt races request completion + _ = py_context:eval(Ctx, ?BUSY, #{}, 20), + case py_context:eval(Ctx, <<"1+1">>, #{}, 5000) of + {ok, 2} -> Acc; + Other -> [Other | Acc] + end + end, + [], + lists:seq(1, 50) + ), [] = Bad, ok. @@ -172,12 +178,13 @@ test_interrupt_does_not_leak_to_next_request(Config) -> test_interrupt_during_callback(Config) -> Ctx = ?config(ctx, Config), ok = py:register_function(<<"interrupt_test_echo">>, fun([X]) -> X end), - Code = <<" -import erlang -_n = 0 -while True: - _n = erlang.call('interrupt_test_echo', _n) + 1 -">>, + Code = << + "\n" + "import erlang\n" + "_n = 0\n" + "while True:\n" + " _n = erlang.call('interrupt_test_echo', _n) + 1\n" + >>, {error, timeout} = py_context:eval(Ctx, <<"exec('''", Code/binary, "''')">>, #{}, 500), {ok, 4} = py_context:eval(Ctx, <<"2+2">>, #{}, 10000), py:unregister_function(<<"interrupt_test_echo">>), @@ -189,7 +196,8 @@ while True: test_blocking_c_call_recovers(Config) -> Ctx = ?config(ctx, Config), {error, timeout} = py_context:eval( - Ctx, <<"__import__('time').sleep(2) or 1">>, #{}, 200), + Ctx, <<"__import__('time').sleep(2) or 1">>, #{}, 200 + ), %% Once the sleep finishes the context accepts work again {ok, 4} = py_context:eval(Ctx, <<"2+2">>, #{}, 10000), ok. @@ -199,6 +207,7 @@ test_blocking_c_call_recovers(Config) -> %%% ============================================================================ flush() -> - receive _ -> flush() + receive + _ -> flush() after 0 -> ok end. diff --git a/test/py_isolated_SUITE.erl b/test/py_isolated_SUITE.erl index 0b6ba29..d74d6d0 100644 --- a/test/py_isolated_SUITE.erl +++ b/test/py_isolated_SUITE.erl @@ -127,9 +127,11 @@ groups() -> test_bad_env_options, test_preload_option ], - [{worker, [], RoundTrip}, - {isolated, [], RoundTrip}, - {isolation, [], Isolation}]. + [ + {worker, [], RoundTrip}, + {isolated, [], RoundTrip}, + {isolation, [], Isolation} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -171,8 +173,10 @@ test_call_eval_exec(Config) -> test_state_persists(Config) -> C = new_ctx(Config), ok = py_context:exec(C, <<"counter = 0">>), - lists:foreach(fun(_) -> ok = py_context:exec(C, <<"counter += 1">>) end, - lists:seq(1, 10)), + lists:foreach( + fun(_) -> ok = py_context:exec(C, <<"counter += 1">>) end, + lists:seq(1, 10) + ), {ok, 10} = py_context:eval(C, <<"counter">>), stop(C). @@ -254,12 +258,15 @@ test_missing_module_and_function(Config) -> test_large_payloads(Config) -> C = new_ctx(Config), - lists:foreach(fun(Size) -> - Bin = crypto:strong_rand_bytes(Size), - {ok, Bin} = py_context:call(C, ?TEST_MOD, identity, [Bin]), - {ok, Out} = py_context:call(C, ?TEST_MOD, big_payload, [Size]), - Size = byte_size(Out) - end, [1024 * 1024, 16 * 1024 * 1024]), + lists:foreach( + fun(Size) -> + Bin = crypto:strong_rand_bytes(Size), + {ok, Bin} = py_context:call(C, ?TEST_MOD, identity, [Bin]), + {ok, Out} = py_context:call(C, ?TEST_MOD, big_payload, [Size]), + Size = byte_size(Out) + end, + [1024 * 1024, 16 * 1024 * 1024] + ), stop(C). test_callback_round_trip(Config) -> @@ -303,33 +310,44 @@ test_callback_error(Config) -> C = new_ctx(Config), py_callback:register(<<"iso_crash">>, fun(_) -> error(deliberate) end), {ok, <<"RuntimeError">>} = py_context:call(C, ?TEST_MOD, callback_error_type, [<<"iso_crash">>]), - {ok, <<"RuntimeError">>} = py_context:call(C, ?TEST_MOD, callback_error_type, [<<"iso_not_registered">>]), + {ok, <<"RuntimeError">>} = py_context:call(C, ?TEST_MOD, callback_error_type, [ + <<"iso_not_registered">> + ]), py_callback:unregister(<<"iso_crash">>), stop(C). test_send_to_pid(Config) -> C = new_ctx(Config), {ok, true} = py_context:call(C, ?TEST_MOD, send, [self(), {hello, 1}]), - receive {<<"hello">>, 1} -> ok after 2000 -> ct:fail(no_message) end, + receive + {<<"hello">>, 1} -> ok + after 2000 -> ct:fail(no_message) + end, stop(C). test_concurrent_callers(Config) -> C = new_ctx(Config), Self = self(), N = 20, - Pids = [spawn_link(fun() -> - Results = [py_context:call(C, ?TEST_MOD, add, [I, J]) || J <- lists:seq(1, 25)], - Self ! {done, I, Results} - end) || I <- lists:seq(1, N)], - lists:foreach(fun(I) -> - receive - {done, I, Results} -> - Expected = [{ok, I + J} || J <- lists:seq(1, 25)], - Expected = Results - after 30000 -> - ct:fail({timeout, I}) - end - end, lists:seq(1, N)), + Pids = [ + spawn_link(fun() -> + Results = [py_context:call(C, ?TEST_MOD, add, [I, J]) || J <- lists:seq(1, 25)], + Self ! {done, I, Results} + end) + || I <- lists:seq(1, N) + ], + lists:foreach( + fun(I) -> + receive + {done, I, Results} -> + Expected = [{ok, I + J} || J <- lists:seq(1, 25)], + Expected = Results + after 30000 -> + ct:fail({timeout, I}) + end + end, + lists:seq(1, N) + ), _ = Pids, stop(C). @@ -351,9 +369,13 @@ test_timeout_interrupts_sleep(Config) -> test_pool_of_isolated_contexts(_Config) -> {ok, Ctxs} = py_context_router:start_pool(iso_pool, 4, isolated), 4 = length(Ctxs), - Pids = lists:usort([begin - {ok, #{os_pid := P}} = py_context:child_info(Cx), P - end || Cx <- Ctxs]), + Pids = lists:usort([ + begin + {ok, #{os_pid := P}} = py_context:child_info(Cx), + P + end + || Cx <- Ctxs + ]), 4 = length(Pids), [{ok, 4} = py_context:eval(Cx, <<"2+2">>) || Cx <- Ctxs], {ok, 4.0} = py:call(iso_pool, math, sqrt, [16]), @@ -492,8 +514,10 @@ test_rlimit_as_1(Config) -> %% a limit that a regular build fits in keeps it from even importing %% the socket module. Probe = new_ctx(Config), - FreeThreaded = py_context:eval(Probe, - <<"hasattr(__import__('sys'), '_is_gil_enabled') and not __import__('sys')._is_gil_enabled()">>), + FreeThreaded = py_context:eval( + Probe, + <<"hasattr(__import__('sys'), '_is_gil_enabled') and not __import__('sys')._is_gil_enabled()">> + ), stop(Probe), case FreeThreaded of {ok, true} -> {skip, "free-threaded CPython needs an as limit far above test sizes"}; @@ -502,7 +526,9 @@ test_rlimit_as_1(Config) -> test_rlimit_as_2(Config) -> C = new_ctx(Config, #{rlimits => #{as => 1024 * 1024 * 1024}}), - Result = py_context:call(C, ?TEST_MOD, allocate_and_touch, [2 * 1024 * 1024 * 1024], #{}, 120000), + Result = py_context:call( + C, ?TEST_MOD, allocate_and_touch, [2 * 1024 * 1024 * 1024], #{}, 120000 + ), ct:log("allocate past as limit: ~p", [Result]), case {Result, rlimit_as_enforced()} of {{error, {'MemoryError', _}}, _} -> ok; @@ -525,7 +551,9 @@ test_rlimit_cpu(Config) -> test_rlimit_nofile(Config) -> C = new_ctx(Config, #{rlimits => #{nofile => 32}}), - {ok, 32} = py_context:eval(C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">>), + {ok, 32} = py_context:eval( + C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">> + ), stop(C). test_reaped_on_stop(Config) -> @@ -541,7 +569,10 @@ test_reaped_on_crash(Config) -> unlink(C), Mon = erlang:monitor(process, C), _ = py_context:call(C, ?TEST_MOD, segfault, []), - receive {'DOWN', Mon, process, C, _} -> ok after 5000 -> ct:fail(context_survived) end, + receive + {'DOWN', Mon, process, C, _} -> ok + after 5000 -> ct:fail(context_survived) + end, wait_gone(Pid), ok. @@ -613,15 +644,22 @@ test_restart_budget(Config) -> {ok, 4} = py_context:eval(C, <<"2+2">>), %% Third crash exceeds the budget _ = py_context:call(C, ?TEST_MOD, segfault, []), - receive {'DOWN', Mon, process, C, _} -> ok after 5000 -> ct:fail(budget_not_enforced) end, + receive + {'DOWN', Mon, process, C, _} -> ok + after 5000 -> ct:fail(budget_not_enforced) + end, ok. test_numpy_imports(Config) -> C = new_ctx(Config), - case py_context:eval(C, <<"__import__('importlib.util').util.find_spec('numpy') is not None">>) of + case + py_context:eval(C, <<"__import__('importlib.util').util.find_spec('numpy') is not None">>) + of {ok, true} -> {ok, 45} = py_context:call(C, ?TEST_MOD, numpy_sum, [10]), - {ok, [[1, 2], [3, 4]]} = py_context:eval(C, <<"__import__('numpy').array([[1,2],[3,4]])">>), + {ok, [[1, 2], [3, 4]]} = py_context:eval( + C, <<"__import__('numpy').array([[1,2],[3,4]])">> + ), stop(C); _ -> stop(C), @@ -661,7 +699,10 @@ test_sys_state_reflects_activity(Config) -> timer:sleep(100), {{busy, Id}, _} = sys:get_state(C), true = is_integer(Id), - receive {done, {ok, <<"x">>}} -> ok after 5000 -> ct:fail(no_reply) end, + receive + {done, {ok, <<"x">>}} -> ok + after 5000 -> ct:fail(no_reply) + end, {idle, _} = sys:get_state(C), ok = py_context:start_loop(C), {looping, _} = sys:get_state(C), @@ -681,7 +722,10 @@ test_requests_during_restart_are_served(Config) -> {crash, {error, {child_exited, {signal, Sig}}}} -> true = is_segfault_signal(Sig) after 10000 -> ct:fail(no_crash_report) end, - receive {next, {ok, 4}} -> ok after 10000 -> ct:fail(request_not_served_after_restart) end, + receive + {next, {ok, 4}} -> ok + after 10000 -> ct:fail(request_not_served_after_restart) + end, _ = Crasher, stop(C). @@ -702,7 +746,9 @@ test_kill_reply_after_restart(Config) -> test_stop_while_busy_and_looping(Config) -> C1 = new_ctx(Config), Self = self(), - spawn_link(fun() -> Self ! {busy, py_context:call(C1, ?TEST_MOD, sleep_then, [5, x], #{}, 10000)} end), + spawn_link(fun() -> + Self ! {busy, py_context:call(C1, ?TEST_MOD, sleep_then, [5, x], #{}, 10000)} + end), timer:sleep(100), ok = py_context:stop(C1), receive @@ -712,7 +758,10 @@ test_stop_while_busy_and_looping(Config) -> C2 = new_ctx(Config), ok = py_context:start_loop(C2), ok = py_context:stop(C2), - receive {py_loop_exit, C2, _} -> ok after 5000 -> ct:fail(no_loop_exit_on_stop) end, + receive + {py_loop_exit, C2, _} -> ok + after 5000 -> ct:fail(no_loop_exit_on_stop) + end, false = is_process_alive(C2), ok. @@ -729,7 +778,11 @@ test_sys_get_status(Config) -> test_context_outlives_creator(Config) -> Self = self(), spawn(fun() -> Self ! {ctx, new_ctx(Config)} end), - C = receive {ctx, X} -> X after 15000 -> ct:fail(no_ctx) end, + C = + receive + {ctx, X} -> X + after 15000 -> ct:fail(no_ctx) + end, timer:sleep(100), true = is_process_alive(C), {ok, 4} = py_context:eval(C, <<"2+2">>), @@ -761,11 +814,17 @@ test_startup_error_reported_1() -> %% child may report the failed setrlimit (startup_error), or the macOS %% watchdog may end it at once; all are loud. case py_context:new(#{mode => isolated, rlimits => #{as => 1}}) of - {error, {startup_error, _}} -> ok; - {error, {child_exited_at_start, _, _}} -> ok; - {error, {handshake_failed, _}} -> ok; - {ok, C} -> py_context:stop(C), ct:fail(limit_ignored); - Other -> ct:fail({unexpected, Other}) + {error, {startup_error, _}} -> + ok; + {error, {child_exited_at_start, _, _}} -> + ok; + {error, {handshake_failed, _}} -> + ok; + {ok, C} -> + py_context:stop(C), + ct:fail(limit_ignored); + Other -> + ct:fail({unexpected, Other}) end. %% @doc cgroups exist only on Linux: elsewhere the option is refused before @@ -782,8 +841,12 @@ test_cgroup_option_platform(_Config) -> py_context:new(#{mode => isolated, cgroup => "/sys/fs/cgroup/x"}), %% Limits still apply without cgroups {ok, C} = py_context:new(#{mode => isolated, rlimits => #{nofile => 48, cpu => 5}}), - {ok, 48} = py_context:eval(C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">>), - {ok, 5} = py_context:eval(C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_CPU)[0]">>), + {ok, 48} = py_context:eval( + C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">> + ), + {ok, 5} = py_context:eval( + C, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_CPU)[0]">> + ), stop(C) end. @@ -833,7 +896,9 @@ test_hash_seed_option(Config) -> test_bad_env_options(_Config) -> {error, {badarg, {hash_seed, -1}}} = py_context:new(#{mode => isolated, hash_seed => -1}), - {error, {badarg, {hash_seed, 1 bsl 32}}} = py_context:new(#{mode => isolated, hash_seed => 1 bsl 32}), + {error, {badarg, {hash_seed, 1 bsl 32}}} = py_context:new(#{ + mode => isolated, hash_seed => 1 bsl 32 + }), {error, {badarg, {clear_env, yes}}} = py_context:new(#{mode => isolated, clear_env => yes}), ok. @@ -856,9 +921,15 @@ new_ctx(Config, Extra) -> {ok, C} = py_context:new(Opts), case Mode of worker -> - ok = py_context:exec(C, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", - [TestDir, TestDir]))); + ok = py_context:exec( + C, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", + [TestDir, TestDir] + ) + ) + ); _ -> ok end, @@ -893,15 +964,22 @@ wait_gone(Pid, 0) -> ct:fail({child_still_present, Pid, os_pid_alive(Pid)}); wait_gone(Pid, N) -> case os_pid_alive(Pid) of - false -> ok; - _ -> timer:sleep(100), wait_gone(Pid, N - 1) + false -> + ok; + _ -> + timer:sleep(100), + wait_gone(Pid, N - 1) end. %% A sanitizer runtime (LD_PRELOAD=libasan in the ASan job) is inherited %% by the child: it aborts on a segfault and reserves terabytes of address %% space, so rlimit cases cannot mean anything there. sanitized_child() -> - Pre = case os:getenv("LD_PRELOAD") of false -> ""; P -> P end, + Pre = + case os:getenv("LD_PRELOAD") of + false -> ""; + P -> P + end, string:find(Pre, "asan") =/= nomatch orelse os:getenv("ASAN_OPTIONS") =/= false. is_segfault_signal(11) -> true; @@ -922,4 +1000,7 @@ to_list(B) when is_binary(B) -> binary_to_list(B); to_list(L) when is_list(L) -> L. flush() -> - receive _ -> flush() after 0 -> ok end. + receive + _ -> flush() + after 0 -> ok + end. diff --git a/test/py_isolated_async_SUITE.erl b/test/py_isolated_async_SUITE.erl index 02ad05c..917ce0e 100644 --- a/test/py_isolated_async_SUITE.erl +++ b/test/py_isolated_async_SUITE.erl @@ -91,8 +91,10 @@ groups() -> test_stream_via_send, test_blocked_loop_is_killed ], - [{isolated, [], Cases}, - {worker_contrast, [], [test_blocked_loop_survives_in_worker]}]. + [ + {isolated, [], Cases}, + {worker_contrast, [], [test_blocked_loop_survives_in_worker]} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -123,7 +125,10 @@ test_start_stop_loop(Config) -> ok = py_context:start_loop(C), {ok, 3} = py_context:submit_await(C, ?TEST_MOD, async_add, [1, 2]), ok = py_context:stop_loop(C), - receive {py_loop_exit, C, ok} -> ok after 2000 -> ct:fail(no_loop_exit) end, + receive + {py_loop_exit, C, ok} -> ok + after 2000 -> ct:fail(no_loop_exit) + end, {ok, 4} = py_context:eval(C, <<"2+2">>), stop(C). @@ -153,13 +158,19 @@ test_submit_idle_and_running(Config) -> test_submit_ordering(Config) -> C = new_ctx(Config), ok = py_context:start_loop(C), - Refs = [begin - {ok, R} = py_context:submit(C, ?TEST_MOD, async_add, [I, 0]), - {I, R} - end || I <- lists:seq(1, 100)], - lists:foreach(fun({I, R}) -> - {ok, I} = py_event_loop:await(R, 5000) - end, Refs), + Refs = [ + begin + {ok, R} = py_context:submit(C, ?TEST_MOD, async_add, [I, 0]), + {I, R} + end + || I <- lists:seq(1, 100) + ], + lists:foreach( + fun({I, R}) -> + {ok, I} = py_event_loop:await(R, 5000) + end, + Refs + ), ok = py_context:stop_loop(C), stop(C). @@ -187,7 +198,8 @@ test_interrupt_ends_loop(Config) -> C = new_ctx(Config), ok = py_context:start_loop(C), ok = py_context:interrupt(C), - receive {py_loop_exit, C, {error, interrupted}} -> ok + receive + {py_loop_exit, C, {error, interrupted}} -> ok after 3000 -> ct:fail(loop_not_interrupted) end, {ok, 4} = py_context:eval(C, <<"2+2">>), @@ -195,7 +207,11 @@ test_interrupt_ends_loop(Config) -> test_owner_death_stops_loop(Config) -> C = new_ctx(Config), - Owner = spawn(fun() -> receive die -> ok end end), + Owner = spawn(fun() -> + receive + die -> ok + end + end), ok = py_context:start_loop(C, #{owner => Owner}), Owner ! die, wait_until(fun() -> py_context:eval(C, <<"1">>) =:= {ok, 1} end, 5000), @@ -222,7 +238,9 @@ test_long_submitted_call(Config) -> stop(C). test_preload_before_loop(Config) -> - C = new_ctx(Config, #{preload => <<"import py_test_isolated\npy_test_isolated.counter_increment(5)">>}), + C = new_ctx(Config, #{ + preload => <<"import py_test_isolated\npy_test_isolated.counter_increment(5)">> + }), ok = py_context:start_loop(C), {ok, 5} = py_context:submit_await(C, ?TEST_MOD, counter_value, []), ok = py_context:stop_loop(C), @@ -278,7 +296,8 @@ test_adopt_accepted_fd(Config) -> {ok, ChildFd} = py_context:pass_fd(C, ConnFd), {ok, <<"adopted">>} = py_context:submit_await(C, py_test_workerloop, adopt, [ChildFd]), gen_tcp:close(Conn), - receive {client, {ok, <<"ok:adopted?">>}} -> ok + receive + {client, {ok, <<"ok:adopted?">>}} -> ok after 3000 -> ct:fail(no_reply_through_adopted_fd) end, gen_tcp:close(LSock), @@ -292,12 +311,17 @@ test_three_workers_one_listen_fd(Config) -> {ok, LSock} = gen_tcp:listen(0, [binary, {ip, ?HOST}, {active, false}, {backlog, 512}]), {ok, Port} = inet:port(LSock), {ok, LFd} = inet:getfd(LSock), - lists:foreach(fun({I, C}) -> - ok = py_context:start_loop(C), - {ok, ChildFd} = py_context:pass_fd(C, LFd), - Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), - {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [ChildFd, Tag]) - end, lists:zip(lists:seq(1, 3), Ctxs)), + lists:foreach( + fun({I, C}) -> + ok = py_context:start_loop(C), + {ok, ChildFd} = py_context:pass_fd(C, LFd), + Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), + {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [ + ChildFd, Tag + ]) + end, + lists:zip(lists:seq(1, 3), Ctxs) + ), Replies = [roundtrip(Port, <<"x">>) || _ <- lists:seq(1, 300)], 300 = length([R || R <- Replies, binary:part(R, byte_size(R) - 4, 4) =:= <<"ok:x">>]), Tags = lists:usort([binary:part(R, 0, 3) || R <- Replies]), @@ -332,7 +356,9 @@ test_call_awaits_coroutine(Config) -> test_gather_is_concurrent(Config) -> C = new_ctx(Config), T0 = erlang:monotonic_time(millisecond), - {ok, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} = py_context:call(C, ?TEST_MOD, async_sleep_gather, [10, 0.1]), + {ok, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} = py_context:call(C, ?TEST_MOD, async_sleep_gather, [ + 10, 0.1 + ]), Elapsed = erlang:monotonic_time(millisecond) - T0, ct:log("10 x sleep(0.1) gathered in ~p ms", [Elapsed]), true = Elapsed < 600, @@ -347,12 +373,20 @@ test_async_error(Config) -> test_concurrent_submitted_tasks(Config) -> C = new_ctx(Config), ok = py_context:start_loop(C), - Refs = [begin {ok, R} = py_context:submit(C, ?TEST_MOD, task_value, [I]), {I, R} end - || I <- lists:seq(1, 100)], - lists:foreach(fun({I, R}) -> - Expected = I * I, - {ok, Expected} = py_event_loop:await(R, 10000) - end, Refs), + Refs = [ + begin + {ok, R} = py_context:submit(C, ?TEST_MOD, task_value, [I]), + {I, R} + end + || I <- lists:seq(1, 100) + ], + lists:foreach( + fun({I, R}) -> + Expected = I * I, + {ok, Expected} = py_event_loop:await(R, 10000) + end, + Refs + ), ok = py_context:stop_loop(C), stop(C). @@ -381,14 +415,19 @@ test_async_calls_concurrent(Config) -> test_async_call_error(Config) -> C = new_ctx(Config), py_callback:register(<<"as_fail">>, fun(_) -> error(deliberate) end), - {ok, <<"RuntimeError">>} = py_context:call(C, ?TEST_MOD, async_erlang_call_error, [<<"as_fail">>]), + {ok, <<"RuntimeError">>} = py_context:call(C, ?TEST_MOD, async_erlang_call_error, [ + <<"as_fail">> + ]), py_callback:unregister(<<"as_fail">>), stop(C). test_send_from_coroutine(Config) -> C = new_ctx(Config), {ok, <<"sent">>} = py_context:call(C, ?TEST_MOD, async_send, [self(), coro_msg]), - receive <<"coro_msg">> -> ok after 2000 -> ct:fail(no_message) end, + receive + <<"coro_msg">> -> ok + after 2000 -> ct:fail(no_message) + end, stop(C). test_run_helper_compat(Config) -> @@ -429,7 +468,10 @@ test_blocked_loop_is_killed(Config) -> ct:log("stop_loop on a wedged loop: ~p after ~p ms", [Result, Elapsed]), ok = Result, true = Elapsed < 5000, - receive {py_loop_exit, C, _} -> ok after 2000 -> ct:fail(no_loop_exit) end, + receive + {py_loop_exit, C, _} -> ok + after 2000 -> ct:fail(no_loop_exit) + end, {ok, #{os_pid := Pid2}} = py_context:child_info(C), true = Pid1 =/= Pid2, {ok, 4} = py_context:eval(C, <<"2+2">>), @@ -447,7 +489,12 @@ test_blocked_loop_survives_in_worker(Config) -> {error, timeout} = Result, %% Wait out the sleep so the context can be stopped cleanly timer:sleep(4500), - _ = (try py_context:stop(C) catch _:_ -> ok end), + _ = + (try + py_context:stop(C) + catch + _:_ -> ok + end), ok. %%% ============================================================================ @@ -482,11 +529,15 @@ wait_until(Fun, TimeoutMs) -> wait_until_loop(Fun, Deadline) -> case Fun() of - true -> ok; + true -> + ok; _ -> case erlang:monotonic_time(millisecond) > Deadline of - true -> ct:fail(condition_not_met); - false -> timer:sleep(50), wait_until_loop(Fun, Deadline) + true -> + ct:fail(condition_not_met); + false -> + timer:sleep(50), + wait_until_loop(Fun, Deadline) end end. @@ -500,9 +551,15 @@ new_ctx(Config, Extra) -> {ok, C} = py_context:new(Opts), case Mode of worker -> - ok = py_context:exec(C, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", - [TestDir, TestDir]))); + ok = py_context:exec( + C, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", + [TestDir, TestDir] + ) + ) + ); _ -> ok end, @@ -513,4 +570,7 @@ stop(C) -> ok. flush() -> - receive _ -> flush() after 0 -> ok end. + receive + _ -> flush() + after 0 -> ok + end. diff --git a/test/py_isolated_buffer_SUITE.erl b/test/py_isolated_buffer_SUITE.erl index 5c09e80..5178959 100644 --- a/test/py_isolated_buffer_SUITE.erl +++ b/test/py_isolated_buffer_SUITE.erl @@ -54,9 +54,11 @@ groups() -> test_read_with_nested_callback, test_write_after_close ], - [{worker, [], Both}, - {isolated, [], Both}, - {isolated_only, [], [test_restart_mid_body, test_native_buffer_refused_in_isolated]}]. + [ + {worker, [], Both}, + {isolated, [], Both}, + {isolated_only, [], [test_restart_mid_body, test_native_buffer_refused_in_isolated]} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -128,9 +130,15 @@ test_read_blocks_until_write(Config) -> {ok, Buf} = py_buffer:new(#{shared => true}), Self = self(), spawn_link(fun() -> Self ! {got, py_context:call(C, ?MOD, buf_read_n, [Buf, 5], #{}, 10000)} end), - receive {got, _} -> ct:fail(read_returned_without_data) after 300 -> ok end, + receive + {got, _} -> ct:fail(read_returned_without_data) + after 300 -> ok + end, ok = py_buffer:write(Buf, <<"data!">>), - receive {got, {ok, <<"data!">>}} -> ok after 5000 -> ct:fail(read_did_not_wake) end, + receive + {got, {ok, <<"data!">>}} -> ok + after 5000 -> ct:fail(read_did_not_wake) + end, ok = py_buffer:close(Buf), stop(C). @@ -162,10 +170,13 @@ test_backpressure(Config) -> T0 = erlang:monotonic_time(millisecond), [ok = py_buffer:write(Buf, Ch) || Ch <- Chunks ++ [Last]], ok = py_buffer:close(Buf), - ct:log("wrote ~p bytes through a ~p ring in ~p ms", - [Total, Ring, erlang:monotonic_time(millisecond) - T0]), + ct:log( + "wrote ~p bytes through a ~p ring in ~p ms", + [Total, Ring, erlang:monotonic_time(millisecond) - T0] + ), Expected = {Total, checksum(All)}, - receive {read, {ok, {Got, Sum}}} -> Expected = {Got, Sum} + receive + {read, {ok, {Got, Sum}}} -> Expected = {Got, Sum} after 60000 -> ct:fail(reader_hung) end, stop(C). @@ -178,10 +189,15 @@ test_write_timeout(Config) -> {error, timeout} = py_buffer:write(Buf, <<"more">>, 300), %% Reading frees the ring and later writes succeed Self = self(), - spawn_link(fun() -> Self ! {n, py_context:call(C, ?MOD, buf_consume_len, [Buf, 4096], #{}, 10000)} end), + spawn_link(fun() -> + Self ! {n, py_context:call(C, ?MOD, buf_consume_len, [Buf, 4096], #{}, 10000)} + end), ok = py_buffer:write(Buf, <<"more">>, 5000), ok = py_buffer:close(Buf), - receive {n, {ok, 4100}} -> ok after 10000 -> ct:fail(reader_hung) end, + receive + {n, {ok, 4100}} -> ok + after 10000 -> ct:fail(reader_hung) + end, stop(C). test_large_body_throughput(Config) -> @@ -196,10 +212,15 @@ test_large_body_throughput(Config) -> T0 = erlang:monotonic_time(microsecond), [ok = py_buffer:write(Buf, Chunk) || <> <= Body], ok = py_buffer:close(Buf), - receive {read, {ok, Size}} -> ok after 120000 -> ct:fail(reader_hung) end, + receive + {read, {ok, Size}} -> ok + after 120000 -> ct:fail(reader_hung) + end, Us = erlang:monotonic_time(microsecond) - T0, - ct:log("64 MB through a shared buffer (~p): ~.1f ms, ~.1f MB/s", - [?config(mode, Config), Us / 1000, Size / ?MB / (Us / 1.0e6)]), + ct:log( + "64 MB through a shared buffer (~p): ~.1f ms, ~.1f MB/s", + [?config(mode, Config), Us / 1000, Size / ?MB / (Us / 1.0e6)] + ), ct:print("shared buffer 64 MB (~p): ~.1f ms", [?config(mode, Config), Us / 1000]), stop(C). @@ -210,7 +231,10 @@ test_close_while_reading(Config) -> spawn_link(fun() -> Self ! {got, py_context:call(C, ?MOD, buf_read_all, [Buf], #{}, 10000)} end), timer:sleep(200), ok = py_buffer:close(Buf), - receive {got, {ok, <<>>}} -> ok after 5000 -> ct:fail(read_did_not_return_on_close) end, + receive + {got, {ok, <<>>}} -> ok + after 5000 -> ct:fail(read_did_not_return_on_close) + end, stop(C). test_wsgi_input_in_environ(Config) -> @@ -229,7 +253,9 @@ test_read_with_nested_callback(Config) -> {ok, Buf} = py_buffer:new(#{shared => true}), ok = py_buffer:write(Buf, <<"headrest of the body">>), ok = py_buffer:close(Buf), - {ok, {<<"head">>, 42, 16}} = py_context:call(C, ?MOD, buf_read_with_callback, [Buf, <<"shm_double">>]), + {ok, {<<"head">>, 42, 16}} = py_context:call(C, ?MOD, buf_read_with_callback, [ + Buf, <<"shm_double">> + ]), py_callback:unregister(<<"shm_double">>), stop(C). @@ -275,9 +301,18 @@ new_ctx(Config) -> {ok, C} = py_context:new(#{mode => Mode, paths => [TestDir]}), case Mode of worker -> - ok = py_context:exec(C, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [TestDir, TestDir]))); - _ -> ok + ok = py_context:exec( + C, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [ + TestDir, TestDir + ] + ) + ) + ); + _ -> + ok end, C. diff --git a/test/py_isolated_shm_SUITE.erl b/test/py_isolated_shm_SUITE.erl index 4385c0e..219e16f 100644 --- a/test/py_isolated_shm_SUITE.erl +++ b/test/py_isolated_shm_SUITE.erl @@ -69,10 +69,12 @@ groups() -> test_restart_remaps, test_churn_no_leak ], - [{erlang, [], ErlangOnly}, - {worker, [], Both}, - {isolated, [], Both}, - {isolated_only, [], IsolatedOnly}]. + [ + {erlang, [], ErlangOnly}, + {worker, [], Both}, + {isolated, [], Both}, + {isolated_only, [], IsolatedOnly} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -138,9 +140,15 @@ test_owner_death_closes(_Config) -> Owner = spawn(fun() -> {ok, Shm} = py_shm:new(4096), Self ! {shm, Shm}, - receive die -> ok end + receive + die -> ok + end end), - Shm = receive {shm, S} -> S after 5000 -> ct:fail(no_shm) end, + Shm = + receive + {shm, S} -> S + after 5000 -> ct:fail(no_shm) + end, {'$py_shm', _, Path, _} = Shm, true = filelib:is_file(Path), Owner ! die, @@ -174,9 +182,14 @@ test_nested_in_structure(Config) -> C = new_ctx(Config), {ok, A} = py_shm:new(4096), {ok, B} = py_shm:new(8192), - {ok, [4096, 8192]} = py_context:call(C, ?MOD, shm_in_structure, - [#{regions => [A, B], label => x}]), - py_shm:close(A), py_shm:close(B), + {ok, [4096, 8192]} = py_context:call( + C, + ?MOD, + shm_in_structure, + [#{regions => [A, B], label => x}] + ), + py_shm:close(A), + py_shm:close(B), stop(C). test_python_sees_later_write(Config) -> @@ -222,7 +235,9 @@ test_mapped_once(Config) -> test_numpy(Config) -> C = new_ctx(Config), - case py_context:eval(C, <<"__import__('importlib.util').util.find_spec('numpy') is not None">>) of + case + py_context:eval(C, <<"__import__('importlib.util').util.find_spec('numpy') is not None">>) + of {ok, true} -> {ok, Shm} = py_shm:new(?MB), ok = py_shm:write(Shm, 0, binary:copy(<<3>>, 1000)), @@ -245,7 +260,8 @@ test_two_contexts_share(Config) -> {ok, 5} = py_context:call(C1, ?MOD, shm_write, [Shm, 0, {bytes, <<"hello">>}]), {ok, <<"hello">>} = py_context:call(C2, ?MOD, shm_read, [Shm, 0, 5]), py_shm:close(Shm), - stop(C1), stop(C2). + stop(C1), + stop(C2). test_mixed_pool_share(Config) -> Iso = new_ctx(Config), @@ -267,8 +283,10 @@ test_size_mismatch_refused(Config) -> {ok, {'$py_shm', Id, Path, _} = Shm} = py_shm:new(4096), Lie = {'$py_shm', Id, Path, 8192}, case py_context:call(C, ?MOD, shm_len, [Lie]) of - {error, {'RuntimeError', _}} -> ok; %% isolated: raised in the child - {error, arg_conversion_failed} -> ok %% embedded: conversion refused + %% isolated: raised in the child + {error, {'RuntimeError', _}} -> ok; + %% embedded: conversion refused + {error, arg_conversion_failed} -> ok end, py_shm:close(Shm), stop(C). @@ -296,7 +314,8 @@ test_read_only_handle(Config) -> Ro = py_shm:read_only(Rw), {ok, <<"read_only">>} = py_context:call(C, ?MOD, shm_write_readonly, [Ro]), {ok, 3} = py_context:call(C, ?MOD, shm_write, [Rw, 0, {bytes, <<"abc">>}]), - py_shm:close(Shm), py_shm:close(Rw), + py_shm:close(Shm), + py_shm:close(Rw), stop(C). test_restart_remaps(Config) -> @@ -314,12 +333,15 @@ test_churn_no_leak(Config) -> Dir = py_shm:private_dir(), Files0 = length(filelib:wildcard(filename:join(Dir, "shm_*"))), Regions0 = ets:info(py_shm_regions, size), - lists:foreach(fun(I) -> - {ok, Shm} = py_shm:new(64 * 1024), - ok = py_shm:write(Shm, 0, <>), - {ok, <>} = py_context:call(C, ?MOD, shm_read, [Shm, 0, 4]), - ok = py_shm:close(Shm) - end, lists:seq(1, 200)), + lists:foreach( + fun(I) -> + {ok, Shm} = py_shm:new(64 * 1024), + ok = py_shm:write(Shm, 0, <>), + {ok, <>} = py_context:call(C, ?MOD, shm_read, [Shm, 0, 4]), + ok = py_shm:close(Shm) + end, + lists:seq(1, 200) + ), Files1 = length(filelib:wildcard(filename:join(Dir, "shm_*"))), Files0 = Files1, Regions0 = ets:info(py_shm_regions, size), @@ -341,8 +363,11 @@ new_ctx(Config) -> add_path(Config) -> TestDir = ?config(test_dir, Config), - iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [TestDir, TestDir])). + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [TestDir, TestDir] + ) + ). stop(C) -> ok = py_context:stop(C), @@ -354,7 +379,8 @@ wait_until(Fun, TimeoutMs) -> wait_loop(Fun, Deadline) -> case Fun() of - true -> ok; + true -> + ok; false -> erlang:monotonic_time(millisecond) < Deadline orelse ct:fail(condition_not_met), timer:sleep(50), diff --git a/test/py_isolated_soak_SUITE.erl b/test/py_isolated_soak_SUITE.erl index 76fab9d..88662e3 100644 --- a/test/py_isolated_soak_SUITE.erl +++ b/test/py_isolated_soak_SUITE.erl @@ -20,12 +20,13 @@ -define(TEST_MOD, py_test_isolated). -all() -> [ - test_callback_storm_no_deadlock, - test_interrupt_kill_storm, - test_loop_start_stop_churn, - test_mixed_workload_no_leak -]. +all() -> + [ + test_callback_storm_no_deadlock, + test_interrupt_kill_storm, + test_loop_start_stop_churn, + test_mixed_workload_no_leak + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -49,14 +50,23 @@ end_per_suite(_Config) -> test_callback_storm_no_deadlock(Config) -> C = new_ctx(Config), py_callback:register(<<"soak_nested">>, fun([X]) -> - {ok, R} = py_context:call(C, ?TEST_MOD, add, [X, 1], #{}, 20000), R + {ok, R} = py_context:call(C, ?TEST_MOD, add, [X, 1], #{}, 20000), + R end), Self = self(), Workers = 16, Rounds = 40, - [spawn_link(fun() -> Self ! {done, I, storm(C, I, Rounds, [])} end) || I <- lists:seq(1, Workers)], - Failures = lists:append([receive {done, _, F} -> F after 120000 -> ct:fail(worker_hung) end - || _ <- lists:seq(1, Workers)]), + [ + spawn_link(fun() -> Self ! {done, I, storm(C, I, Rounds, [])} end) + || I <- lists:seq(1, Workers) + ], + Failures = lists:append([ + receive + {done, _, F} -> F + after 120000 -> ct:fail(worker_hung) + end + || _ <- lists:seq(1, Workers) + ]), ct:log("failures: ~p", [Failures]), [] = Failures, py_callback:unregister(<<"soak_nested">>), @@ -67,58 +77,71 @@ storm(_C, _I, 0, Acc) -> Acc; storm(C, I, N, Acc) -> Op = (I + N) rem 6, - R = case Op of - 0 -> py_context:call(C, ?TEST_MOD, add, [I, N], #{}, 20000); - 1 -> py_context:call(C, ?TEST_MOD, callback, [<<"soak_echo">>, {I, N}], #{}, 20000); - 2 -> py_context:call(C, ?TEST_MOD, callback, [<<"soak_nested">>, N], #{}, 20000); - 3 -> py_context:call(C, ?TEST_MOD, pool_calls, [<<"soak_incr">>, 4, 20], #{}, 20000); - 4 -> py_context:call(C, ?TEST_MOD, callback_error_type, [<<"soak_fail">>], #{}, 20000); - 5 -> py_context:call(C, ?TEST_MOD, thread_calls, [<<"soak_tid">>, 4, 5], #{}, 20000) - end, - Expected = case Op of - 0 -> {ok, I + N}; - 1 -> {ok, {I, N}}; - 2 -> {ok, N + 1}; - 3 -> {ok, false}; %% incr, not double: the helper compares to i*2 - 4 -> {ok, <<"RuntimeError">>}; - 5 -> {ok, {<<"ok">>, true, 20}} - end, - Acc1 = case R of - Expected -> Acc; - {ok, _} when Op =:= 3 -> Acc; %% value checked by shape only - Other -> [{I, N, Op, Other} | Acc] - end, + R = + case Op of + 0 -> py_context:call(C, ?TEST_MOD, add, [I, N], #{}, 20000); + 1 -> py_context:call(C, ?TEST_MOD, callback, [<<"soak_echo">>, {I, N}], #{}, 20000); + 2 -> py_context:call(C, ?TEST_MOD, callback, [<<"soak_nested">>, N], #{}, 20000); + 3 -> py_context:call(C, ?TEST_MOD, pool_calls, [<<"soak_incr">>, 4, 20], #{}, 20000); + 4 -> py_context:call(C, ?TEST_MOD, callback_error_type, [<<"soak_fail">>], #{}, 20000); + 5 -> py_context:call(C, ?TEST_MOD, thread_calls, [<<"soak_tid">>, 4, 5], #{}, 20000) + end, + Expected = + case Op of + 0 -> {ok, I + N}; + 1 -> {ok, {I, N}}; + 2 -> {ok, N + 1}; + %% incr, not double: the helper compares to i*2 + 3 -> {ok, false}; + 4 -> {ok, <<"RuntimeError">>}; + 5 -> {ok, {<<"ok">>, true, 20}} + end, + Acc1 = + case R of + Expected -> Acc; + %% value checked by shape only + {ok, _} when Op =:= 3 -> Acc; + Other -> [{I, N, Op, Other} | Acc] + end, storm(C, I, N - 1, Acc1). %% @doc Interrupts and kills racing with calls: nothing hangs, the context %% always answers again, and no child is left behind. test_interrupt_kill_storm(Config) -> C = new_ctx(Config, #{kill_after => 200, max_restarts => 1000}), - Pids = lists:map(fun(N) -> - {ok, #{os_pid := P}} = py_context:child_info(C), - Self = self(), - spawn_link(fun() -> - Self ! {res, py_context:call(C, ?TEST_MOD, sleep_then, [5, N], #{}, 30000)} - end), - timer:sleep(20 + N rem 30), - case N rem 3 of - 0 -> py_context:interrupt(C); - 1 -> py_context:kill(C); - 2 -> py_context:interrupt(C), py_context:kill(C) + Pids = lists:map( + fun(N) -> + {ok, #{os_pid := P}} = py_context:child_info(C), + Self = self(), + spawn_link(fun() -> + Self ! {res, py_context:call(C, ?TEST_MOD, sleep_then, [5, N], #{}, 30000)} + end), + timer:sleep(20 + N rem 30), + case N rem 3 of + 0 -> + py_context:interrupt(C); + 1 -> + py_context:kill(C); + 2 -> + py_context:interrupt(C), + py_context:kill(C) + end, + receive + {res, R} -> + case R of + {error, interrupted} -> ok; + {error, killed} -> ok; + {error, {child_exited, _}} -> ok; + {ok, N} -> ok; + Other -> ct:fail({unexpected, N, Other}) + end + after 15000 -> ct:fail({hung_after_interrupt, N}) + end, + {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 30000), + P end, - receive {res, R} -> - case R of - {error, interrupted} -> ok; - {error, killed} -> ok; - {error, {child_exited, _}} -> ok; - {ok, N} -> ok; - Other -> ct:fail({unexpected, N, Other}) - end - after 15000 -> ct:fail({hung_after_interrupt, N}) - end, - {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 30000), - P - end, lists:seq(1, 30)), + lists:seq(1, 30) + ), ok = py_context:stop(C), timer:sleep(300), Alive = [P || P <- lists:usort(Pids), py_nif:os_kill(P, 0) =:= ok], @@ -129,20 +152,26 @@ test_interrupt_kill_storm(Config) -> %% few rounds so the kill backstop runs. test_loop_start_stop_churn(Config) -> C = new_ctx(Config, #{kill_after => 200, max_restarts => 1000}), - lists:foreach(fun(N) -> - ok = py_context:start_loop(C), - {ok, 3} = py_context:submit_await(C, ?TEST_MOD, async_add, [1, 2], #{}, 30000), - case N rem 4 of - 0 -> - {ok, _} = py_context:submit(C, ?TEST_MOD, blocked_sleep, [30]), - timer:sleep(50), - ok = py_context:stop_loop(C, 100); - _ -> - ok = py_context:stop_loop(C, 2000) + lists:foreach( + fun(N) -> + ok = py_context:start_loop(C), + {ok, 3} = py_context:submit_await(C, ?TEST_MOD, async_add, [1, 2], #{}, 30000), + case N rem 4 of + 0 -> + {ok, _} = py_context:submit(C, ?TEST_MOD, blocked_sleep, [30]), + timer:sleep(50), + ok = py_context:stop_loop(C, 100); + _ -> + ok = py_context:stop_loop(C, 2000) + end, + receive + {py_loop_exit, C, _} -> ok + after 5000 -> ct:fail({no_loop_exit, N}) + end, + {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 30000) end, - receive {py_loop_exit, C, _} -> ok after 5000 -> ct:fail({no_loop_exit, N}) end, - {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 30000) - end, lists:seq(1, 24)), + lists:seq(1, 24) + ), ok = py_context:stop(C), ok. @@ -161,10 +190,17 @@ test_mixed_workload_no_leak(Config) -> ct:log("baseline: ~p", [Base]), Deadline = erlang:monotonic_time(millisecond) + Seconds * 1000, Self = self(), - Workers = [spawn_link(fun() -> Self ! {worker, I, mixed(Config, I, Deadline, 0, [])} end) - || I <- lists:seq(1, 6)], - Stats = [receive {worker, _, S} -> S after (Seconds + 120) * 1000 -> ct:fail(worker_hung) end - || _ <- Workers], + Workers = [ + spawn_link(fun() -> Self ! {worker, I, mixed(Config, I, Deadline, 0, [])} end) + || I <- lists:seq(1, 6) + ], + Stats = [ + receive + {worker, _, S} -> S + after (Seconds + 120) * 1000 -> ct:fail(worker_hung) + end + || _ <- Workers + ], Ops = lists:sum([O || {O, _} <- Stats]), Errs = lists:append([E || {_, E} <- Stats]), ct:log("ops: ~p, unexpected errors: ~p", [Ops, lists:sublist(Errs, 20)]), @@ -180,7 +216,8 @@ test_mixed_workload_no_leak(Config) -> mixed(Config, I, Deadline, Ops, Errs) -> case erlang:monotonic_time(millisecond) > Deadline of - true -> {Ops, Errs}; + true -> + {Ops, Errs}; false -> C = new_ctx(Config, #{kill_after => 300, max_restarts => 1000}), E1 = mixed_ops(C, I, 25, Errs), @@ -192,35 +229,61 @@ mixed_ops(_C, _I, 0, Errs) -> Errs; mixed_ops(C, I, N, Errs) -> Op = (I * 7 + N) rem 9, - R = case Op of - 0 -> py_context:eval(C, <<"sum(range(1000))">>, #{}, 30000); - 1 -> py_context:call(C, ?TEST_MOD, identity, [crypto:strong_rand_bytes(256 * 1024)], #{}, 30000); - 2 -> py_context:call(C, ?TEST_MOD, callback, [<<"soak_echo">>, [I, N]], #{}, 30000); - 3 -> py_context:call(C, ?TEST_MOD, async_sleep_gather, [5, 0.001], #{}, 30000); - 4 -> py_context:eval(C, <<"__import__('time').sleep(5)">>, #{}, 50); - 5 -> py_context:call(C, ?TEST_MOD, pool_calls, [<<"soak_echo">>, 4, 10], #{}, 30000); - 6 -> py_context:call(C, ?TEST_MOD, segfault, [], #{}, 30000); - 7 -> py_context:call(C, ?TEST_MOD, send, [self(), {soak, N}], #{}, 30000); - 8 -> py_context:kill(C) - end, - Ok = case {Op, R} of - {0, {ok, 499500}} -> true; - {1, {ok, B}} when is_binary(B) -> true; - {2, {ok, [I, N]}} -> true; - {3, {ok, [0, 1, 2, 3, 4]}} -> true; - {4, {error, timeout}} -> true; - {5, {ok, _}} -> true; - {6, {error, {child_exited, {signal, _}}}} -> true; - {7, {ok, true}} -> receive {<<"soak">>, N} -> true after 5000 -> false end; - {8, ok} -> true; - _ -> false - end, + R = + case Op of + 0 -> + py_context:eval(C, <<"sum(range(1000))">>, #{}, 30000); + 1 -> + py_context:call( + C, ?TEST_MOD, identity, [crypto:strong_rand_bytes(256 * 1024)], #{}, 30000 + ); + 2 -> + py_context:call(C, ?TEST_MOD, callback, [<<"soak_echo">>, [I, N]], #{}, 30000); + 3 -> + py_context:call(C, ?TEST_MOD, async_sleep_gather, [5, 0.001], #{}, 30000); + 4 -> + py_context:eval(C, <<"__import__('time').sleep(5)">>, #{}, 50); + 5 -> + py_context:call(C, ?TEST_MOD, pool_calls, [<<"soak_echo">>, 4, 10], #{}, 30000); + 6 -> + py_context:call(C, ?TEST_MOD, segfault, [], #{}, 30000); + 7 -> + py_context:call(C, ?TEST_MOD, send, [self(), {soak, N}], #{}, 30000); + 8 -> + py_context:kill(C) + end, + Ok = + case {Op, R} of + {0, {ok, 499500}} -> + true; + {1, {ok, B}} when is_binary(B) -> true; + {2, {ok, [I, N]}} -> + true; + {3, {ok, [0, 1, 2, 3, 4]}} -> + true; + {4, {error, timeout}} -> + true; + {5, {ok, _}} -> + true; + {6, {error, {child_exited, {signal, _}}}} -> + true; + {7, {ok, true}} -> + receive + {<<"soak">>, N} -> true + after 5000 -> false + end; + {8, ok} -> + true; + _ -> + false + end, %% After any op the context must answer Alive = py_context:eval(C, <<"1">>, #{}, 30000) =:= {ok, 1}, - Errs1 = case Ok andalso Alive of - true -> Errs; - false -> [{op, Op, R, alive, Alive} | Errs] - end, + Errs1 = + case Ok andalso Alive of + true -> Errs; + false -> [{op, Op, R, alive, Alive} | Errs] + end, mixed_ops(C, I, N - 1, Errs1). %%% ============================================================================ @@ -240,10 +303,14 @@ counters() -> check_no_growth(Base, After) -> Same = [processes, ports, refs, children], - lists:foreach(fun(K) -> - B = maps:get(K, Base), A = maps:get(K, After), - A =< B + 2 orelse ct:fail({leak, K, B, A}) - end, Same), + lists:foreach( + fun(K) -> + B = maps:get(K, Base), + A = maps:get(K, After), + A =< B + 2 orelse ct:fail({leak, K, B, A}) + end, + Same + ), %% fds: allow a few for CT's own logging maps:get(fds, After) =< maps:get(fds, Base) + 8 orelse ct:fail({fd_leak, maps:get(fds, Base), maps:get(fds, After)}), @@ -262,7 +329,10 @@ beam_fd_count() -> end. child_count() -> - Out = os:cmd("ps -ax -o ppid=,command= 2>/dev/null | grep py_isolated_child | grep -v grep | grep -c ' " ++ os:getpid() ++ " ' "), + Out = os:cmd( + "ps -ax -o ppid=,command= 2>/dev/null | grep py_isolated_child | grep -v grep | grep -c ' " ++ + os:getpid() ++ " ' " + ), case string:trim(Out) of "" -> 0; N -> list_to_integer(N) diff --git a/test/py_isolated_stress_SUITE.erl b/test/py_isolated_stress_SUITE.erl index ade684f..350028c 100644 --- a/test/py_isolated_stress_SUITE.erl +++ b/test/py_isolated_stress_SUITE.erl @@ -19,15 +19,16 @@ test_shared_memory_vs_copy/1 ]). -all() -> [ - test_call_latency_vs_worker, - test_callback_round_trips, - test_context_churn_no_leak, - test_startup_time, - test_payload_throughput, - test_parallel_contexts_cpu_bound, - test_shared_memory_vs_copy -]. +all() -> + [ + test_call_latency_vs_worker, + test_callback_round_trips, + test_context_churn_no_leak, + test_startup_time, + test_payload_throughput, + test_parallel_contexts_cpu_bound, + test_shared_memory_vs_copy + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -62,7 +63,10 @@ test_callback_round_trips(_Config) -> Lat = latencies(fun() -> {ok, 1} = py_context:eval(C, Code) end, 1000), ct:log("eval+callback isolated: ~s", [stats(Lat)]), %% 1000 callbacks inside one request - ok = py_context:exec(C, <<"import erlang\ndef burst(n):\n return sum(erlang.call('stress_echo', i) for i in range(n))\n">>), + ok = py_context:exec( + C, + <<"import erlang\ndef burst(n):\n return sum(erlang.call('stress_echo', i) for i in range(n))\n">> + ), T0 = erlang:monotonic_time(microsecond), {ok, 499500} = py_context:call(C, '__main__', burst, [1000]), Per = (erlang:monotonic_time(microsecond) - T0) / 1000, @@ -73,13 +77,16 @@ test_callback_round_trips(_Config) -> %% @doc 100 contexts started and stopped: no child left, RSS reported. test_context_churn_no_leak(_Config) -> - Pids = lists:map(fun(_) -> - {ok, C} = py_context:new(#{mode => isolated}), - {ok, #{os_pid := P}} = py_context:child_info(C), - {ok, 2} = py_context:eval(C, <<"1+1">>), - ok = py_context:stop(C), - P - end, lists:seq(1, 100)), + Pids = lists:map( + fun(_) -> + {ok, C} = py_context:new(#{mode => isolated}), + {ok, #{os_pid := P}} = py_context:child_info(C), + {ok, 2} = py_context:eval(C, <<"1+1">>), + ok = py_context:stop(C), + P + end, + lists:seq(1, 100) + ), timer:sleep(500), Alive = [P || P <- Pids, py_nif:os_kill(P, 0) =:= ok], ct:log("children still alive after churn: ~p", [Alive]), @@ -97,13 +104,16 @@ test_context_churn_no_leak(_Config) -> ok. test_startup_time(_Config) -> - Times = lists:map(fun(_) -> - T0 = erlang:monotonic_time(microsecond), - {ok, C} = py_context:new(#{mode => isolated}), - T = erlang:monotonic_time(microsecond) - T0, - ok = py_context:stop(C), - T - end, lists:seq(1, 20)), + Times = lists:map( + fun(_) -> + T0 = erlang:monotonic_time(microsecond), + {ok, C} = py_context:new(#{mode => isolated}), + T = erlang:monotonic_time(microsecond) - T0, + ok = py_context:stop(C), + T + end, + lists:seq(1, 20) + ), ct:log("isolated context start (spawn -> ready -> init): ~s", [stats(Times)]), ct:print("startup p50 ~p ms", [pct(Times, 50) div 1000]), ok. @@ -113,13 +123,18 @@ test_payload_throughput(_Config) -> {ok, W} = py_context:new(#{mode => worker}), ok = py_context:exec(I, <<"def ident(x): return x">>), ok = py_context:exec(W, <<"def ident(x): return x">>), - lists:foreach(fun(Size) -> - Bin = crypto:strong_rand_bytes(Size), - TI = timed(fun() -> {ok, Bin} = py_context:call(I, '__main__', ident, [Bin]) end), - TW = timed(fun() -> {ok, Bin} = py_context:call(W, '__main__', ident, [Bin]) end), - ct:log("~p MB round trip: isolated ~.1f ms (~.1f MB/s), worker ~.1f ms", - [Size div (1024 * 1024), TI / 1000, 2 * Size / 1048576 / (TI / 1.0e6), TW / 1000]) - end, [1024 * 1024, 16 * 1024 * 1024, 64 * 1024 * 1024]), + lists:foreach( + fun(Size) -> + Bin = crypto:strong_rand_bytes(Size), + TI = timed(fun() -> {ok, Bin} = py_context:call(I, '__main__', ident, [Bin]) end), + TW = timed(fun() -> {ok, Bin} = py_context:call(W, '__main__', ident, [Bin]) end), + ct:log( + "~p MB round trip: isolated ~.1f ms (~.1f MB/s), worker ~.1f ms", + [Size div (1024 * 1024), TI / 1000, 2 * Size / 1048576 / (TI / 1.0e6), TW / 1000] + ) + end, + [1024 * 1024, 16 * 1024 * 1024, 64 * 1024 * 1024] + ), py_context:stop(I), py_context:stop(W), ok. @@ -127,13 +142,25 @@ test_payload_throughput(_Config) -> %% @doc Four isolated children run CPU-bound work in parallel: the GIL is %% per process, so wall time is close to one child's time. test_parallel_contexts_cpu_bound(_Config) -> - Ctxs = [begin {ok, C} = py_context:new(#{mode => isolated}), C end || _ <- lists:seq(1, 4)], + Ctxs = [ + begin + {ok, C} = py_context:new(#{mode => isolated}), + C + end + || _ <- lists:seq(1, 4) + ], Code = <<"sum(i*i for i in range(2000000))">>, T1 = timed(fun() -> {ok, _} = py_context:eval(hd(Ctxs), Code) end), Self = self(), T4 = timed(fun() -> [spawn_link(fun() -> Self ! {done, py_context:eval(C, Code)} end) || C <- Ctxs], - [receive {done, {ok, _}} -> ok after 60000 -> ct:fail(timeout) end || _ <- Ctxs] + [ + receive + {done, {ok, _}} -> ok + after 60000 -> ct:fail(timeout) + end + || _ <- Ctxs + ] end), ct:log("cpu-bound: 1 child ~.1f ms, 4 children in parallel ~.1f ms", [T1 / 1000, T4 / 1000]), %% On a dedicated machine T4 is close to T1 (see the log). CI VMs are @@ -154,39 +181,54 @@ shared_memory_vs_copy() -> TestDir = filename:join(code:lib_dir(erlang_python), "test"), {ok, I} = py_context:new(#{mode => isolated, paths => [TestDir]}), {ok, W} = py_context:new(#{mode => worker}), - ok = py_context:exec(W, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [TestDir, TestDir]))), + ok = py_context:exec( + W, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", [TestDir, TestDir] + ) + ) + ), ok = py_context:exec(I, <<"def ident(x): return x">>), ok = py_context:exec(W, <<"def ident(x): return x">>), - lists:foreach(fun(Mb) -> - Size = Mb * 1024 * 1024, - Bin = crypto:strong_rand_bytes(Size), - {ok, Shm} = py_shm:new(Size), - %% Erlang -> Python: copy through the socket vs write into the region - %% and sum the first 4 KB through a memoryview - CopyI = timed(fun() -> {ok, _} = py_context:call(I, '__main__', ident, [Bin]) end), - ShmI = timed(fun() -> - ok = py_shm:write(Shm, 0, Bin), - {ok, _} = py_context:call(I, py_test_isolated_shm, shm_sum, [Shm, 4096]) - end), - ShmW = timed(fun() -> - ok = py_shm:write(Shm, 0, Bin), - {ok, _} = py_context:call(W, py_test_isolated_shm, shm_sum, [Shm, 4096]) - end), - %% Python -> Erlang: result through the socket vs fill the region and - %% read it with a region binary - OutI = timed(fun() -> {ok, _} = py_context:call(I, py_test_isolated, big_payload, [Size]) end), - FillI = timed(fun() -> - {ok, _} = py_context:call(I, py_test_isolated_shm, shm_fill, [Shm, 1, Size]), - _ = py_shm:binary(Shm, 0, Size) - end), - ct:log("~p MB Erlang->Python: socket ~.1f ms, shm isolated ~.1f ms, shm worker ~.1f ms~n" - " Python->Erlang: socket ~.1f ms, shm isolated ~.1f ms", - [Mb, CopyI / 1000, ShmI / 1000, ShmW / 1000, OutI / 1000, FillI / 1000]), - ct:print("~p MB: to Python socket ~.1f ms vs shm ~.1f ms; from Python socket ~.1f ms vs shm ~.1f ms", - [Mb, CopyI / 1000, ShmI / 1000, OutI / 1000, FillI / 1000]), - ok = py_shm:close(Shm) - end, [1, 16, 64]), + lists:foreach( + fun(Mb) -> + Size = Mb * 1024 * 1024, + Bin = crypto:strong_rand_bytes(Size), + {ok, Shm} = py_shm:new(Size), + %% Erlang -> Python: copy through the socket vs write into the region + %% and sum the first 4 KB through a memoryview + CopyI = timed(fun() -> {ok, _} = py_context:call(I, '__main__', ident, [Bin]) end), + ShmI = timed(fun() -> + ok = py_shm:write(Shm, 0, Bin), + {ok, _} = py_context:call(I, py_test_isolated_shm, shm_sum, [Shm, 4096]) + end), + ShmW = timed(fun() -> + ok = py_shm:write(Shm, 0, Bin), + {ok, _} = py_context:call(W, py_test_isolated_shm, shm_sum, [Shm, 4096]) + end), + %% Python -> Erlang: result through the socket vs fill the region and + %% read it with a region binary + OutI = timed(fun() -> + {ok, _} = py_context:call(I, py_test_isolated, big_payload, [Size]) + end), + FillI = timed(fun() -> + {ok, _} = py_context:call(I, py_test_isolated_shm, shm_fill, [Shm, 1, Size]), + _ = py_shm:binary(Shm, 0, Size) + end), + ct:log( + "~p MB Erlang->Python: socket ~.1f ms, shm isolated ~.1f ms, shm worker ~.1f ms~n" + " Python->Erlang: socket ~.1f ms, shm isolated ~.1f ms", + [Mb, CopyI / 1000, ShmI / 1000, ShmW / 1000, OutI / 1000, FillI / 1000] + ), + ct:print( + "~p MB: to Python socket ~.1f ms vs shm ~.1f ms; from Python socket ~.1f ms vs shm ~.1f ms", + [Mb, CopyI / 1000, ShmI / 1000, OutI / 1000, FillI / 1000] + ), + ok = py_shm:close(Shm) + end, + [1, 16, 64] + ), py_context:stop(I), py_context:stop(W), ok. @@ -209,5 +251,7 @@ pct(Sorted, P) -> stats(Sorted) -> Mean = lists:sum(Sorted) / length(Sorted), - io_lib:format("p50 ~p us, p99 ~p us, max ~p us, mean ~.1f us", - [pct(Sorted, 50), pct(Sorted, 99), lists:last(Sorted), Mean]). + io_lib:format( + "p50 ~p us, p99 ~p us, max ~p us, mean ~.1f us", + [pct(Sorted, 50), pct(Sorted, 99), lists:last(Sorted), Mean] + ). diff --git a/test/py_isolated_vm_SUITE.erl b/test/py_isolated_vm_SUITE.erl index 7572403..50b2a92 100644 --- a/test/py_isolated_vm_SUITE.erl +++ b/test/py_isolated_vm_SUITE.erl @@ -133,7 +133,11 @@ test_pid_is_pid(Config) -> test_pid_equality_and_hash(Config) -> C = new_ctx(Config), Self = self(), - Other = spawn(fun() -> receive stop -> ok end end), + Other = spawn(fun() -> + receive + stop -> ok + end + end), {ok, true} = py_context:call(C, ?TEST_MOD, pid_equal, [Self, Self]), {ok, false} = py_context:call(C, ?TEST_MOD, pid_equal, [Self, Other]), {ok, true} = py_context:call(C, ?TEST_MOD, pid_hash_equal, [Self, Self]), @@ -150,7 +154,10 @@ test_pid_in_structure(Config) -> test_send_simple(Config) -> C = new_ctx(Config), {ok, true} = py_context:call(C, ?TEST_MOD, send, [self(), <<"hello">>]), - receive <<"hello">> -> ok after 2000 -> ct:fail(no_message) end, + receive + <<"hello">> -> ok + after 2000 -> ct:fail(no_message) + end, stop(C). test_send_multiple_ordered(Config) -> @@ -175,7 +182,11 @@ test_send_complex_term(Config) -> test_send_is_nonblocking(Config) -> C = new_ctx(Config), - Sink = spawn(fun() -> receive stop -> ok end end), + Sink = spawn(fun() -> + receive + stop -> ok + end + end), {ok, Ms} = py_context:call(C, ?TEST_MOD, send_timing, [Sink, 1000]), ct:log("1000 erlang.send took ~.1f ms (~.1f us each)", [Ms, Ms]), true = Ms < 5000, @@ -198,7 +209,10 @@ test_send_bad_pid(Config) -> test_send_from_coroutine(Config) -> C = new_ctx(Config), {ok, <<"sent">>} = py_context:call(C, ?TEST_MOD, send_from_coroutine, [self(), from_coro]), - receive <<"from_coro">> -> ok after 2000 -> ct:fail(no_message) end, + receive + <<"from_coro">> -> ok + after 2000 -> ct:fail(no_message) + end, stop(C). test_whereis(Config) -> @@ -219,7 +233,9 @@ test_suspension_is_base_exception(Config) -> test_callback_inside_except_exception(Config) -> C = new_ctx(Config), py_callback:register(<<"vm_echo">>, fun([X]) -> X end), - {ok, {<<"ok">>, 42}} = py_context:call(C, ?TEST_MOD, call_inside_except_exception, [<<"vm_echo">>, 42]), + {ok, {<<"ok">>, 42}} = py_context:call(C, ?TEST_MOD, call_inside_except_exception, [ + <<"vm_echo">>, 42 + ]), py_callback:unregister(<<"vm_echo">>), stop(C). @@ -287,8 +303,10 @@ test_encoding_pid_and_ref(Config) -> test_encoding_floats(Config) -> C = new_ctx(Config), - lists:foreach(fun(F) -> F = probe(C, F) end, - [3.14159265358979, 1.0e-300, 1.7976931348623157e308, -0.0]), + lists:foreach( + fun(F) -> F = probe(C, F) end, + [3.14159265358979, 1.0e-300, 1.7976931348623157e308, -0.0] + ), stop(C). test_encoding_booleans_and_none(Config) -> @@ -296,10 +314,13 @@ test_encoding_booleans_and_none(Config) -> true = probe(C, true), false = probe(C, false), <<"bool">> = probe_type(C, true), - lists:foreach(fun(A) -> - none = probe(C, A), - <<"NoneType">> = probe_type(C, A) - end, [undefined, nil, none]), + lists:foreach( + fun(A) -> + none = probe(C, A), + <<"NoneType">> = probe_type(C, A) + end, + [undefined, nil, none] + ), stop(C). test_encoding_python_types(Config) -> @@ -316,7 +337,9 @@ test_encoding_python_types(Config) -> test_threads_call_erlang(Config) -> C = new_ctx(Config), py_callback:register(<<"vm_tid">>, fun([T, I]) -> T * 1000 + I end), - {ok, {<<"ok">>, true, 40}} = py_context:call(C, ?TEST_MOD, thread_calls, [<<"vm_tid">>, 4, 10], #{}, 30000), + {ok, {<<"ok">>, true, 40}} = py_context:call( + C, ?TEST_MOD, thread_calls, [<<"vm_tid">>, 4, 10], #{}, 30000 + ), py_callback:unregister(<<"vm_tid">>), stop(C). @@ -347,7 +370,9 @@ test_threadpool_nested(Config) -> test_threads_high_concurrency(Config) -> C = new_ctx(Config), py_callback:register(<<"vm_tid">>, fun([T, I]) -> T * 1000 + I end), - {ok, {<<"ok">>, true, 1600}} = py_context:call(C, ?TEST_MOD, thread_calls, [<<"vm_tid">>, 32, 50], #{}, 60000), + {ok, {<<"ok">>, true, 1600}} = py_context:call( + C, ?TEST_MOD, thread_calls, [<<"vm_tid">>, 32, 50], #{}, 60000 + ), py_callback:unregister(<<"vm_tid">>), stop(C). @@ -357,9 +382,12 @@ test_threads_high_concurrency(Config) -> test_counter_actor(Config) -> C = new_ctx(Config), - lists:foreach(fun(I) -> - {ok, I} = py_context:call(C, ?TEST_MOD, counter_increment, []) - end, lists:seq(1, 100)), + lists:foreach( + fun(I) -> + {ok, I} = py_context:call(C, ?TEST_MOD, counter_increment, []) + end, + lists:seq(1, 100) + ), {ok, 110} = py_context:call(C, ?TEST_MOD, counter_increment, [10]), {ok, 110} = py_context:call(C, ?TEST_MOD, counter_value, []), stop(C). @@ -403,7 +431,10 @@ test_ping_pong(Config) -> py_callback:register(<<"vm_incr">>, fun([X]) -> X + 1 end), {ok, 1000} = py_context:call(C, ?TEST_MOD, ping_pong, [<<"vm_incr">>, 1000], #{}, 60000), py_callback:unregister(<<"vm_incr">>), - receive Any -> ct:fail({unexpected_message, Any}) after 0 -> ok end, + receive + Any -> ct:fail({unexpected_message, Any}) + after 0 -> ok + end, stop(C). %% @doc Erlang feeds terms to the child through a callback it polls. @@ -412,7 +443,10 @@ test_feed_through_callback(Config) -> Feeder = spawn_link(fun() -> feeder(lists:seq(1, 200)) end), py_callback:register(<<"vm_next">>, fun([]) -> Feeder ! {next, self()}, - receive {item, I} -> I after 5000 -> none end + receive + {item, I} -> I + after 5000 -> none + end end), {ok, Items} = py_context:call(C, ?TEST_MOD, poll_feed, [<<"vm_next">>, 200], #{}, 60000), Expected = lists:seq(1, 200), @@ -422,11 +456,20 @@ test_feed_through_callback(Config) -> stop(C). feeder([]) -> - receive stop -> ok; {next, From} -> From ! {item, none}, feeder([]) end; + receive + stop -> + ok; + {next, From} -> + From ! {item, none}, + feeder([]) + end; feeder([H | T] = L) -> receive - stop -> ok; - {next, From} -> From ! {item, H}, feeder(T) + stop -> + ok; + {next, From} -> + From ! {item, H}, + feeder(T) after 10000 -> feeder(L) end. @@ -461,9 +504,15 @@ new_ctx(Config) -> {ok, C} = py_context:new(#{mode => Mode, paths => [TestDir]}), case Mode of worker -> - ok = py_context:exec(C, iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", - [TestDir, TestDir]))); + ok = py_context:exec( + C, + iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path: sys.path.insert(0, '~s')", + [TestDir, TestDir] + ) + ) + ); _ -> ok end, @@ -474,4 +523,7 @@ stop(C) -> ok. flush() -> - receive _ -> flush() after 0 -> ok end. + receive + _ -> flush() + after 0 -> ok + end. diff --git a/test/py_logging_SUITE.erl b/test/py_logging_SUITE.erl index eec67c8..d0dbcf3 100644 --- a/test/py_logging_SUITE.erl +++ b/test/py_logging_SUITE.erl @@ -88,13 +88,14 @@ test_log_levels(_Config) -> ok = py:configure_logging(#{level => warning}), %% Log at different levels using exec for multi-statement code - ok = py:exec(<<" -import logging -logging.debug('debug msg') -logging.info('info msg') -logging.warning('warning msg') -logging.error('error msg') -">>), + ok = py:exec(<< + "\n" + "import logging\n" + "logging.debug('debug msg')\n" + "logging.info('info msg')\n" + "logging.warning('warning msg')\n" + "logging.error('error msg')\n" + >>), %% Give a moment for async delivery timer:sleep(50), @@ -105,17 +106,18 @@ logging.error('error msg') test_log_from_thread(_Config) -> ok = py:configure_logging(), - ok = py:exec(<<" -import logging -import threading - -def log_in_thread(): - logging.info('message from thread') - -t = threading.Thread(target=log_in_thread) -t.start() -t.join() -">>), + ok = py:exec(<< + "\n" + "import logging\n" + "import threading\n" + "\n" + "def log_in_thread():\n" + " logging.info('message from thread')\n" + "\n" + "t = threading.Thread(target=log_in_thread)\n" + "t.start()\n" + "t.join()\n" + >>), timer:sleep(100), ok. @@ -124,11 +126,12 @@ t.join() test_trace_basic(_Config) -> ok = py:enable_tracing(), - ok = py:exec(<<" -import erlang -with erlang.Span('test-span', key='value'): - pass -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "with erlang.Span('test-span', key='value'):\n" + " pass\n" + >>), {ok, Spans} = py:get_traces(), 1 = length(Spans), @@ -143,12 +146,13 @@ with erlang.Span('test-span', key='value'): test_trace_nested(_Config) -> ok = py:enable_tracing(), - ok = py:exec(<<" -import erlang -with erlang.Span('parent'): - with erlang.Span('child'): - pass -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "with erlang.Span('parent'):\n" + " with erlang.Span('child'):\n" + " pass\n" + >>), {ok, Spans} = py:get_traces(), 2 = length(Spans), @@ -168,15 +172,16 @@ with erlang.Span('parent'): test_trace_decorator(_Config) -> ok = py:enable_tracing(), - ok = py:exec(<<" -import erlang - -@erlang.trace() -def my_traced_function(): - return 42 - -result = my_traced_function() -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "\n" + "@erlang.trace()\n" + "def my_traced_function():\n" + " return 42\n" + "\n" + "result = my_traced_function()\n" + >>), {ok, Spans} = py:get_traces(), 1 = length(Spans), @@ -190,12 +195,13 @@ result = my_traced_function() test_trace_events(_Config) -> ok = py:enable_tracing(), - ok = py:exec(<<" -import erlang -with erlang.Span('work') as span: - span.event('checkpoint', items=10) - span.event('progress', percent=50) -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "with erlang.Span('work') as span:\n" + " span.event('checkpoint', items=10)\n" + " span.event('progress', percent=50)\n" + >>), {ok, [Span]} = py:get_traces(), Events = maps:get(events, Span), @@ -212,14 +218,15 @@ with erlang.Span('work') as span: test_trace_error(_Config) -> ok = py:enable_tracing(), - ok = py:exec(<<" -import erlang -try: - with erlang.Span('failing'): - raise ValueError('intentional error') -except ValueError: - pass -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "try:\n" + " with erlang.Span('failing'):\n" + " raise ValueError('intentional error')\n" + "except ValueError:\n" + " pass\n" + >>), {ok, [Span]} = py:get_traces(), error = maps:get(status, Span), diff --git a/test/py_memory_limit_SUITE.erl b/test/py_memory_limit_SUITE.erl index d780906..11e5fcd 100644 --- a/test/py_memory_limit_SUITE.erl +++ b/test/py_memory_limit_SUITE.erl @@ -29,15 +29,16 @@ -define(CAP, (64 * 1024 * 1024)). -all() -> [ - test_cap_raises_memory_error, - test_context_survives_cap, - test_cap_rearms_after_release, - test_usage_is_reported, - test_no_cap_is_unlimited, - test_worker_mode_rejected, - test_invalid_limit_rejected -]. +all() -> + [ + test_cap_raises_memory_error, + test_context_survives_cap, + test_cap_rearms_after_release, + test_usage_is_reported, + test_no_cap_is_unlimited, + test_worker_mode_rejected, + test_invalid_limit_rejected + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), diff --git a/test/py_ml_libs_SUITE.erl b/test/py_ml_libs_SUITE.erl index 44de937..b4c5911 100644 --- a/test/py_ml_libs_SUITE.erl +++ b/test/py_ml_libs_SUITE.erl @@ -56,10 +56,11 @@ end_per_suite(_Config) -> ok. init_per_testcase(TC, Config) -> - Mode = case TC of - numpy_owngil_basic -> owngil; - _ -> worker - end, + Mode = + case TC of + numpy_owngil_basic -> owngil; + _ -> worker + end, case Mode of owngil -> case py_nif:owngil_supported() of @@ -96,11 +97,11 @@ setup_case(TC, Mode, Config) -> ct:fail({context_create_failed, Mode, Reason}) end. -required_module(numpy_basic_ops) -> "numpy"; -required_module(numpy_call_thread_affinity) -> "numpy"; -required_module(numpy_parallel_processes) -> "numpy"; -required_module(numpy_owngil_basic) -> "numpy"; -required_module(tensorflow_basic_ops) -> "tensorflow"; +required_module(numpy_basic_ops) -> "numpy"; +required_module(numpy_call_thread_affinity) -> "numpy"; +required_module(numpy_parallel_processes) -> "numpy"; +required_module(numpy_owngil_basic) -> "numpy"; +required_module(tensorflow_basic_ops) -> "tensorflow"; required_module(tensorflow_call_thread_affinity) -> "tensorflow". %% Reflect the import status into a Python variable so we can @@ -110,7 +111,9 @@ required_module(tensorflow_call_thread_affinity) -> "tensorflow". require_module(Ctx, Mod) -> Code = iolist_to_binary([ "try:\n", - " import ", Mod, "\n", + " import ", + Mod, + "\n", " _import_status = 'ok'\n", "except ImportError:\n", " _import_status = 'not_found'\n" @@ -125,8 +128,11 @@ require_module(Ctx, Mod) -> end. native_id(Ctx) -> - {ok, Tid} = py_context:eval(Ctx, - <<"__import__('threading').get_native_id()">>, #{}), + {ok, Tid} = py_context:eval( + Ctx, + <<"__import__('threading').get_native_id()">>, + #{} + ), Tid. %%% --------------------------------------------------------------------------- @@ -143,10 +149,16 @@ numpy_basic_ops(Config) -> " v = np.array(xs, dtype=np.float64)\n" " return float(np.dot(v, v))\n" >>), - {ok, 30.0} = py_context:call(Ctx, '__main__', vec_dot_self, - [[1.0, 2.0, 3.0, 4.0]]), - ok = py_context:exec(Ctx, - <<"_w = vec_dot_self([10.0, 0.0, 0.0])">>), + {ok, 30.0} = py_context:call( + Ctx, + '__main__', + vec_dot_self, + [[1.0, 2.0, 3.0, 4.0]] + ), + ok = py_context:exec( + Ctx, + <<"_w = vec_dot_self([10.0, 0.0, 0.0])">> + ), {ok, 100.0} = py_context:eval(Ctx, <<"_w">>, #{}), ok. @@ -159,9 +171,15 @@ numpy_call_thread_affinity(Config) -> " v = np.array(xs, dtype=np.float64)\n" " return (threading.get_native_id(), float(np.sum(v)))\n" >>), - Results = [py_context:call(Ctx, '__main__', numpy_with_tid, - [[float(I), float(I + 1), float(I + 2)]]) - || I <- lists:seq(1, 50)], + Results = [ + py_context:call( + Ctx, + '__main__', + numpy_with_tid, + [[float(I), float(I + 1), float(I + 2)]] + ) + || I <- lists:seq(1, 50) + ], Tids = [Tid || {ok, {Tid, _Sum}} <- Results], Sums = [Sum || {ok, {_Tid, Sum}} <- Results], 50 = length(Tids), @@ -184,27 +202,42 @@ numpy_parallel_processes(Config) -> >>), Parent = self(), N = 8, - Pids = [spawn_link(fun() -> - Xs = [float(K * J) || J <- lists:seq(1, 4)], - Ys = [float(K + J) || J <- lists:seq(1, 4)], - R = py_context:call(Ctx, '__main__', numpy_dot_with_tid, - [Xs, Ys]), - Parent ! {result, K, R} - end) || K <- lists:seq(1, N)], - Results = [receive {result, K, R} -> {K, R} after 5000 -> ct:fail(timeout) end - || _ <- Pids], + Pids = [ + spawn_link(fun() -> + Xs = [float(K * J) || J <- lists:seq(1, 4)], + Ys = [float(K + J) || J <- lists:seq(1, 4)], + R = py_context:call( + Ctx, + '__main__', + numpy_dot_with_tid, + [Xs, Ys] + ), + Parent ! {result, K, R} + end) + || K <- lists:seq(1, N) + ], + Results = [ + receive + {result, K, R} -> {K, R} + after 5000 -> ct:fail(timeout) + end + || _ <- Pids + ], %% All calls converged on one thread. Tids = [Tid || {_K, {ok, {Tid, _Sum}}} <- Results], N = length(Tids), [SingleTid] = lists:usort(Tids), true = is_integer(SingleTid), %% Each result matches the expected dot product. - lists:foreach(fun({K, {ok, {_Tid, Got}}}) -> - Xs = [float(K * J) || J <- lists:seq(1, 4)], - Ys = [float(K + J) || J <- lists:seq(1, 4)], - Expected = lists:sum([X * Y || {X, Y} <- lists:zip(Xs, Ys)]), - true = abs(Got - Expected) < 1.0e-9 - end, Results), + lists:foreach( + fun({K, {ok, {_Tid, Got}}}) -> + Xs = [float(K * J) || J <- lists:seq(1, 4)], + Ys = [float(K + J) || J <- lists:seq(1, 4)], + Expected = lists:sum([X * Y || {X, Y} <- lists:zip(Xs, Ys)]), + true = abs(Got - Expected) < 1.0e-9 + end, + Results + ), %% Drain time + mailbox sanity (no orphan results). timer:sleep(50), {messages, []} = erlang:process_info(self(), messages), @@ -220,8 +253,12 @@ numpy_owngil_basic(Config) -> " v = np.array(xs, dtype=np.float64)\n" " return float(np.dot(v, v))\n" >>), - {ok, 30.0} = py_context:call(Ctx, '__main__', vec_dot_self, - [[1.0, 2.0, 3.0, 4.0]]), + {ok, 30.0} = py_context:call( + Ctx, + '__main__', + vec_dot_self, + [[1.0, 2.0, 3.0, 4.0]] + ), {ok, 25.0} = py_context:call(Ctx, '__main__', vec_dot_self, [[5.0]]), %% Confirm the thread is stable across owngil calls. Tid1 = native_id(Ctx), @@ -255,9 +292,15 @@ tensorflow_call_thread_affinity(Config) -> " return (threading.get_native_id(),\n" " float(tf.math.reduce_sum(t).numpy()))\n" >>), - Results = [py_context:call(Ctx, '__main__', tf_sum_with_tid, - [[float(I), float(I + 1)]]) - || I <- lists:seq(1, 20)], + Results = [ + py_context:call( + Ctx, + '__main__', + tf_sum_with_tid, + [[float(I), float(I + 1)]] + ) + || I <- lists:seq(1, 20) + ], Tids = [Tid || {ok, {Tid, _Sum}} <- Results], 20 = length(Tids), [SingleTid] = lists:usort(Tids), diff --git a/test/py_owngil_features_SUITE.erl b/test/py_owngil_features_SUITE.erl index c611953..ee1d85e 100644 --- a/test/py_owngil_features_SUITE.erl +++ b/test/py_owngil_features_SUITE.erl @@ -124,102 +124,106 @@ ]). all() -> - [{group, channels}, - {group, buffers}, - {group, reentrant}, - {group, pid_send}, - {group, reactor}, - {group, async_task}, - {group, asyncio}, - {group, local_env}, - {group, erlang_api}]. + [ + {group, channels}, + {group, buffers}, + {group, reentrant}, + {group, pid_send}, + {group, reactor}, + {group, async_task}, + {group, asyncio}, + {group, local_env}, + {group, erlang_api} + ]. groups() -> - [{channels, [sequence], [ - owngil_channel_send_receive_test, - owngil_channel_sync_blocking_test, - owngil_channel_backpressure_test, - owngil_channel_async_receive_test, - owngil_channel_parallel_producers_test, - owngil_channel_parallel_consumers_test, - owngil_channel_cross_context_test, - owngil_channel_high_throughput_test - ]}, - {buffers, [sequence], [ - owngil_buffer_write_read_test, - owngil_buffer_pass_to_python_test, - owngil_buffer_async_read_test, - owngil_buffer_parallel_writers_test, - owngil_buffer_memoryview_test, - owngil_buffer_gc_test - ]}, - {reentrant, [sequence], [ - owngil_reentrant_basic_test, - owngil_reentrant_nested_test, - owngil_reentrant_concurrent_test, - owngil_reentrant_multi_stress_test, - owngil_reentrant_complex_types_test, - owngil_reentrant_thread_callback_test, - owngil_reentrant_try_except_test - ]}, - {pid_send, [sequence], [ - owngil_pid_roundtrip_test, - owngil_send_simple_test, - owngil_send_multiple_test, - owngil_send_complex_test, - owngil_suspension_not_caught_test, - owngil_send_from_coroutine_test, - owngil_send_nonblocking_test, - owngil_send_parallel_test - ]}, - {reactor, [sequence], [ - owngil_reactor_echo_protocol_test, - owngil_reactor_multiple_conn_test, - owngil_reactor_async_pending_test, - owngil_reactor_buffer_test, - owngil_reactor_isolation_test - ]}, - {async_task, [sequence], [ - owngil_async_create_await_test, - owngil_async_run_sync_test, - owngil_async_concurrent_test, - owngil_async_batch_test, - owngil_async_timeout_test, - owngil_async_error_test - ]}, - {asyncio, [sequence], [ - owngil_asyncio_basic_sleep_test, - owngil_asyncio_gather_test, - owngil_asyncio_parallel_loops_test - ]}, - {local_env, [sequence], [ - owngil_local_env_isolation_test, - owngil_local_env_call_test - ]}, - {erlang_api, [sequence], [ - owngil_whereis_basic_test, - owngil_whereis_nonexistent_test, - owngil_whereis_and_send_test, - owngil_whereis_parallel_test, - owngil_atom_basic_test, - owngil_atom_roundtrip_test, - owngil_atom_create_test, - owngil_atom_create_different_test, - owngil_atom_cache_test, - owngil_ref_roundtrip_test, - owngil_pid_operations_test, - %% Channel tests - owngil_channel_class_test, - owngil_channel_iteration_test, - owngil_channel_context_manager_test, - %% ByteChannel tests - owngil_bytechannel_send_receive_test, - owngil_bytechannel_try_receive_test, - owngil_bytechannel_iteration_test, - %% Buffer tests - owngil_buffer_read_methods_test, - owngil_buffer_at_eof_test - ]}]. + [ + {channels, [sequence], [ + owngil_channel_send_receive_test, + owngil_channel_sync_blocking_test, + owngil_channel_backpressure_test, + owngil_channel_async_receive_test, + owngil_channel_parallel_producers_test, + owngil_channel_parallel_consumers_test, + owngil_channel_cross_context_test, + owngil_channel_high_throughput_test + ]}, + {buffers, [sequence], [ + owngil_buffer_write_read_test, + owngil_buffer_pass_to_python_test, + owngil_buffer_async_read_test, + owngil_buffer_parallel_writers_test, + owngil_buffer_memoryview_test, + owngil_buffer_gc_test + ]}, + {reentrant, [sequence], [ + owngil_reentrant_basic_test, + owngil_reentrant_nested_test, + owngil_reentrant_concurrent_test, + owngil_reentrant_multi_stress_test, + owngil_reentrant_complex_types_test, + owngil_reentrant_thread_callback_test, + owngil_reentrant_try_except_test + ]}, + {pid_send, [sequence], [ + owngil_pid_roundtrip_test, + owngil_send_simple_test, + owngil_send_multiple_test, + owngil_send_complex_test, + owngil_suspension_not_caught_test, + owngil_send_from_coroutine_test, + owngil_send_nonblocking_test, + owngil_send_parallel_test + ]}, + {reactor, [sequence], [ + owngil_reactor_echo_protocol_test, + owngil_reactor_multiple_conn_test, + owngil_reactor_async_pending_test, + owngil_reactor_buffer_test, + owngil_reactor_isolation_test + ]}, + {async_task, [sequence], [ + owngil_async_create_await_test, + owngil_async_run_sync_test, + owngil_async_concurrent_test, + owngil_async_batch_test, + owngil_async_timeout_test, + owngil_async_error_test + ]}, + {asyncio, [sequence], [ + owngil_asyncio_basic_sleep_test, + owngil_asyncio_gather_test, + owngil_asyncio_parallel_loops_test + ]}, + {local_env, [sequence], [ + owngil_local_env_isolation_test, + owngil_local_env_call_test + ]}, + {erlang_api, [sequence], [ + owngil_whereis_basic_test, + owngil_whereis_nonexistent_test, + owngil_whereis_and_send_test, + owngil_whereis_parallel_test, + owngil_atom_basic_test, + owngil_atom_roundtrip_test, + owngil_atom_create_test, + owngil_atom_create_different_test, + owngil_atom_cache_test, + owngil_ref_roundtrip_test, + owngil_pid_operations_test, + %% Channel tests + owngil_channel_class_test, + owngil_channel_iteration_test, + owngil_channel_context_manager_test, + %% ByteChannel tests + owngil_bytechannel_send_receive_test, + owngil_bytechannel_try_receive_test, + owngil_bytechannel_iteration_test, + %% Buffer tests + owngil_buffer_read_methods_test, + owngil_buffer_at_eof_test + ]} + ]. init_per_suite(Config) -> case py_nif:owngil_supported() of @@ -248,12 +252,36 @@ init_per_testcase(_TestCase, Config) -> end_per_testcase(_TestCase, _Config) -> %% Cleanup registered functions - try py:unregister_function(owngil_double) catch _:_ -> ok end, - try py:unregister_function(owngil_triple) catch _:_ -> ok end, - try py:unregister_function(owngil_level) catch _:_ -> ok end, - try py:unregister_function(owngil_transform) catch _:_ -> ok end, - try py:unregister_function(owngil_get_value) catch _:_ -> ok end, - try py:unregister_function(owngil_echo) catch _:_ -> ok end, + try + py:unregister_function(owngil_double) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_triple) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_level) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_transform) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_get_value) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_echo) + catch + _:_ -> ok + end, ok. %%% ============================================================================ @@ -272,8 +300,11 @@ owngil_channel_send_receive_test(_Config) -> ok = py_channel:send(Ch, <<"hello_owngil">>), %% Receive in Python - {ok, <<"hello_owngil">>} = py_context:eval(Ctx, - <<"Channel(ch).try_receive()">>, #{<<"ch">> => Ch}), + {ok, <<"hello_owngil">>} = py_context:eval( + Ctx, + <<"Channel(ch).try_receive()">>, + #{<<"ch">> => Ch} + ), py_channel:close(Ch), py_context:stop(Ctx). @@ -294,10 +325,16 @@ owngil_channel_sync_blocking_test(_Config) -> end), %% Blocking receive should wait for data - {ok, <<"delayed_data">>} = py_context:eval(Ctx, - <<"Channel(ch).receive()">>, #{<<"ch">> => Ch}), + {ok, <<"delayed_data">>} = py_context:eval( + Ctx, + <<"Channel(ch).receive()">>, + #{<<"ch">> => Ch} + ), - receive data_sent -> ok after 1000 -> ok end, + receive + data_sent -> ok + after 1000 -> ok + end, py_channel:close(Ch), py_context:stop(Ctx). @@ -333,28 +370,32 @@ owngil_channel_async_receive_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), {ok, Ch} = py_channel:new(), - ok = py_context:exec(Ctx, <<" -import asyncio -from erlang import Channel - -async def async_receive(ch_ref): - ch = Channel(ch_ref) - return await ch.async_receive() - -def run_async(ch_ref): - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(async_receive(ch_ref)) - finally: - loop.close() -">>), + ok = py_context:exec(Ctx, << + "\n" + "import asyncio\n" + "from erlang import Channel\n" + "\n" + "async def async_receive(ch_ref):\n" + " ch = Channel(ch_ref)\n" + " return await ch.async_receive()\n" + "\n" + "def run_async(ch_ref):\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(async_receive(ch_ref))\n" + " finally:\n" + " loop.close()\n" + >>), %% Send data first ok = py_channel:send(Ch, <<"async_data">>), %% Async receive - {ok, <<"async_data">>} = py_context:eval(Ctx, <<"run_async(ch)">>, - #{<<"ch">> => Ch}), + {ok, <<"async_data">>} = py_context:eval( + Ctx, + <<"run_async(ch)">>, + #{<<"ch">> => Ch} + ), py_channel:close(Ch), py_context:stop(Ctx). @@ -366,25 +407,39 @@ owngil_channel_parallel_producers_test(_Config) -> MessagesPerProducer = 10, %% Create producer contexts - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, <<"from erlang import Channel">>), - Ctx - end || N <- lists:seq(1, NumProducers)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec(Ctx, <<"from erlang import Channel">>), + Ctx + end + || N <- lists:seq(1, NumProducers) + ], Parent = self(), %% Start parallel producers - [spawn_link(fun() -> - lists:foreach(fun(MsgNum) -> - Msg = list_to_binary(io_lib:format("ctx~p_msg~p", [CtxNum, MsgNum])), - ok = py_channel:send(Ch, Msg) - end, lists:seq(1, MessagesPerProducer)), - Parent ! {producer_done, CtxNum} - end) || {CtxNum, _Ctx} <- lists:zip(lists:seq(1, NumProducers), Contexts)], + [ + spawn_link(fun() -> + lists:foreach( + fun(MsgNum) -> + Msg = list_to_binary(io_lib:format("ctx~p_msg~p", [CtxNum, MsgNum])), + ok = py_channel:send(Ch, Msg) + end, + lists:seq(1, MessagesPerProducer) + ), + Parent ! {producer_done, CtxNum} + end) + || {CtxNum, _Ctx} <- lists:zip(lists:seq(1, NumProducers), Contexts) + ], %% Wait for all producers - [receive {producer_done, N} -> ok end || N <- lists:seq(1, NumProducers)], + [ + receive + {producer_done, N} -> ok + end + || N <- lists:seq(1, NumProducers) + ], %% Verify all messages received TotalMessages = NumProducers * MessagesPerProducer, @@ -402,27 +457,39 @@ owngil_channel_parallel_consumers_test(_Config) -> TotalMessages = 20, %% Create consumer contexts - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, <<"from erlang import Channel">>), - Ctx - end || N <- lists:seq(1, NumConsumers)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec(Ctx, <<"from erlang import Channel">>), + Ctx + end + || N <- lists:seq(1, NumConsumers) + ], %% Send all messages - [py_channel:send(Ch, list_to_binary(integer_to_list(N))) - || N <- lists:seq(1, TotalMessages)], + [ + py_channel:send(Ch, list_to_binary(integer_to_list(N))) + || N <- lists:seq(1, TotalMessages) + ], py_channel:close(Ch), Parent = self(), %% Start parallel consumers - [spawn_link(fun() -> - consume_until_closed(Ctx, Ch, Parent, CtxNum) - end) || {CtxNum, Ctx} <- lists:zip(lists:seq(1, NumConsumers), Contexts)], + [ + spawn_link(fun() -> + consume_until_closed(Ctx, Ch, Parent, CtxNum) + end) + || {CtxNum, Ctx} <- lists:zip(lists:seq(1, NumConsumers), Contexts) + ], %% Collect results - Results = [receive {consumer_result, N, Msgs} -> {N, Msgs} end - || N <- lists:seq(1, NumConsumers)], + Results = [ + receive + {consumer_result, N, Msgs} -> {N, Msgs} + end + || N <- lists:seq(1, NumConsumers) + ], %% Verify total messages consumed TotalConsumed = lists:sum([length(Msgs) || {_, Msgs} <- Results]), @@ -443,13 +510,19 @@ owngil_channel_cross_context_test(_Config) -> %% Ctx1 sends, Ctx2 receives ok = py_channel:send(Ch, <<"from_ctx1">>), - {ok, <<"from_ctx1">>} = py_context:eval(Ctx2, - <<"Channel(ch).try_receive()">>, #{<<"ch">> => Ch}), + {ok, <<"from_ctx1">>} = py_context:eval( + Ctx2, + <<"Channel(ch).try_receive()">>, + #{<<"ch">> => Ch} + ), %% Ctx2 sends (via Erlang), Ctx1 receives ok = py_channel:send(Ch, <<"from_erlang">>), - {ok, <<"from_erlang">>} = py_context:eval(Ctx1, - <<"Channel(ch).try_receive()">>, #{<<"ch">> => Ch}), + {ok, <<"from_erlang">>} = py_context:eval( + Ctx1, + <<"Channel(ch).try_receive()">>, + #{<<"ch">> => Ch} + ), py_channel:close(Ch), py_context:stop(Ctx1), @@ -461,31 +534,48 @@ owngil_channel_high_throughput_test(_Config) -> NumContexts = 4, MessagesPerContext = 100, - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, <<"from erlang import Channel">>), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec(Ctx, <<"from erlang import Channel">>), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Parent = self(), Start = erlang:monotonic_time(millisecond), %% Start parallel senders - _ = [spawn_link(fun() -> - lists:foreach(fun(M) -> - py_channel:send(Ch, <<(integer_to_binary(N))/binary, "_", - (integer_to_binary(M))/binary>>) - end, lists:seq(1, MessagesPerContext)), - Parent ! {sender_done, N} - end) || {N, _Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + _ = [ + spawn_link(fun() -> + lists:foreach( + fun(M) -> + py_channel:send(Ch, << + (integer_to_binary(N))/binary, "_", (integer_to_binary(M))/binary + >>) + end, + lists:seq(1, MessagesPerContext) + ), + Parent ! {sender_done, N} + end) + || {N, _Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], %% Wait for senders - [receive {sender_done, N} -> ok end || N <- lists:seq(1, NumContexts)], + [ + receive + {sender_done, N} -> ok + end + || N <- lists:seq(1, NumContexts) + ], Elapsed = erlang:monotonic_time(millisecond) - Start, TotalMessages = NumContexts * MessagesPerContext, - ct:pal("Sent ~p messages in ~p ms (~.2f msgs/ms)", - [TotalMessages, Elapsed, TotalMessages / max(1, Elapsed)]), + ct:pal( + "Sent ~p messages in ~p ms (~.2f msgs/ms)", + [TotalMessages, Elapsed, TotalMessages / max(1, Elapsed)] + ), %% Drain messages Messages = drain_channel(Ch, TotalMessages), @@ -509,8 +599,11 @@ owngil_buffer_write_read_test(_Config) -> ok = py_buffer:close(Buf), %% Read from Python - {ok, <<"hello owngil">>} = py_context:eval(Ctx, - <<"buf.read()">>, #{<<"buf">> => Buf}), + {ok, <<"hello owngil">>} = py_context:eval( + Ctx, + <<"buf.read()">>, + #{<<"buf">> => Buf} + ), py_context:stop(Ctx). @@ -523,13 +616,17 @@ owngil_buffer_pass_to_python_test(_Config) -> ok = py_buffer:write(Buf, <<"chunk2">>), ok = py_buffer:close(Buf), - ok = py_context:exec(Ctx, <<" -def process_buffer(buf): - return buf.read().upper() -">>), + ok = py_context:exec(Ctx, << + "\n" + "def process_buffer(buf):\n" + " return buf.read().upper()\n" + >>), - {ok, <<"CHUNK1:CHUNK2">>} = py_context:eval(Ctx, - <<"process_buffer(buf)">>, #{<<"buf">> => Buf}), + {ok, <<"CHUNK1:CHUNK2">>} = py_context:eval( + Ctx, + <<"process_buffer(buf)">>, + #{<<"buf">> => Buf} + ), py_context:stop(Ctx). @@ -539,26 +636,27 @@ owngil_buffer_async_read_test(_Config) -> {ok, Buf} = py_buffer:new(), Self = self(), - ok = py_context:exec(Ctx, <<" -import asyncio - -async def async_read(buf): - chunks = [] - while not buf.at_eof(): - available = buf.readable_amount() - if available > 0: - chunks.append(buf.read_nonblock(available)) - else: - await asyncio.sleep(0.01) - return b''.join(chunks) - -def run_async_read(buf): - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(async_read(buf)) - finally: - loop.close() -">>), + ok = py_context:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def async_read(buf):\n" + " chunks = []\n" + " while not buf.at_eof():\n" + " available = buf.readable_amount()\n" + " if available > 0:\n" + " chunks.append(buf.read_nonblock(available))\n" + " else:\n" + " await asyncio.sleep(0.01)\n" + " return b''.join(chunks)\n" + "\n" + "def run_async_read(buf):\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(async_read(buf))\n" + " finally:\n" + " loop.close()\n" + >>), %% Spawn writer spawn_link(fun() -> @@ -570,45 +668,72 @@ def run_async_read(buf): Self ! writer_done end), - {ok, <<"async1:async2">>} = py_context:eval(Ctx, - <<"run_async_read(buf)">>, #{<<"buf">> => Buf}), + {ok, <<"async1:async2">>} = py_context:eval( + Ctx, + <<"run_async_read(buf)">>, + #{<<"buf">> => Buf} + ), - receive writer_done -> ok after 1000 -> ok end, + receive + writer_done -> ok + after 1000 -> ok + end, py_context:stop(Ctx). %% @doc Multiple owngil contexts writing to buffers in parallel owngil_buffer_parallel_writers_test(_Config) -> NumContexts = 4, - Buffers = [begin {ok, B} = py_buffer:new(), B end - || _ <- lists:seq(1, NumContexts)], + Buffers = [ + begin + {ok, B} = py_buffer:new(), + B + end + || _ <- lists:seq(1, NumContexts) + ], - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Parent = self(), %% Start parallel writers (each writes to own buffer from Erlang) - [spawn_link(fun() -> - ok = py_buffer:write(Buf, <<"parallel_">>), - ok = py_buffer:write(Buf, integer_to_binary(N)), - ok = py_buffer:close(Buf), - Parent ! {writer_done, N} - end) || {N, Buf} <- lists:zip(lists:seq(1, NumContexts), Buffers)], + [ + spawn_link(fun() -> + ok = py_buffer:write(Buf, <<"parallel_">>), + ok = py_buffer:write(Buf, integer_to_binary(N)), + ok = py_buffer:close(Buf), + Parent ! {writer_done, N} + end) + || {N, Buf} <- lists:zip(lists:seq(1, NumContexts), Buffers) + ], %% Wait for writers - [receive {writer_done, N} -> ok end || N <- lists:seq(1, NumContexts)], + [ + receive + {writer_done, N} -> ok + end + || N <- lists:seq(1, NumContexts) + ], %% Read from each context - Results = [begin - {ok, Data} = py_context:eval(Ctx, <<"buf.read()">>, #{<<"buf">> => Buf}), - Data - end || {Ctx, Buf} <- lists:zip(Contexts, Buffers)], + Results = [ + begin + {ok, Data} = py_context:eval(Ctx, <<"buf.read()">>, #{<<"buf">> => Buf}), + Data + end + || {Ctx, Buf} <- lists:zip(Contexts, Buffers) + ], %% Verify results - Expected = [<<"parallel_", (integer_to_binary(N))/binary>> - || N <- lists:seq(1, NumContexts)], + Expected = [ + <<"parallel_", (integer_to_binary(N))/binary>> + || N <- lists:seq(1, NumContexts) + ], Expected = Results, [py_context:stop(Ctx) || Ctx <- Contexts], @@ -622,16 +747,20 @@ owngil_buffer_memoryview_test(_Config) -> ok = py_buffer:write(Buf, <<"memoryview test">>), ok = py_buffer:close(Buf), - ok = py_context:exec(Ctx, <<" -def test_memoryview(buf): - mv = memoryview(buf) - result = bytes(mv[:10]) - mv.release() - return result -">>), - - {ok, <<"memoryview">>} = py_context:eval(Ctx, - <<"test_memoryview(buf)">>, #{<<"buf">> => Buf}), + ok = py_context:exec(Ctx, << + "\n" + "def test_memoryview(buf):\n" + " mv = memoryview(buf)\n" + " result = bytes(mv[:10])\n" + " mv.release()\n" + " return result\n" + >>), + + {ok, <<"memoryview">>} = py_context:eval( + Ctx, + <<"test_memoryview(buf)">>, + #{<<"buf">> => Buf} + ), py_context:stop(Ctx). @@ -640,14 +769,17 @@ owngil_buffer_gc_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), %% Create many buffers from Erlang side and pass to Python - lists:foreach(fun(_) -> - {ok, Buf} = py_buffer:new(), - ok = py_buffer:write(Buf, binary:copy(<<$x>>, 100)), - ok = py_buffer:close(Buf), - %% Pass to Python for reading - {ok, Data} = py_context:eval(Ctx, <<"buf.read()">>, #{<<"buf">> => Buf}), - 100 = byte_size(Data) - end, lists:seq(1, 50)), + lists:foreach( + fun(_) -> + {ok, Buf} = py_buffer:new(), + ok = py_buffer:write(Buf, binary:copy(<<$x>>, 100)), + ok = py_buffer:close(Buf), + %% Pass to Python for reading + {ok, Data} = py_context:eval(Ctx, <<"buf.read()">>, #{<<"buf">> => Buf}), + 100 = byte_size(Data) + end, + lists:seq(1, 50) + ), %% Force Erlang GC erlang:garbage_collect(), @@ -674,8 +806,11 @@ owngil_reentrant_basic_test(_Config) -> end), %% Test callback from owngil context - {ok, 21} = py_context:eval(Ctx, - <<"__import__('erlang').call('owngil_double', 10) + 1">>, #{}), + {ok, 21} = py_context:eval( + Ctx, + <<"__import__('erlang').call('owngil_double', 10) + 1">>, + #{} + ), py_context:stop(Ctx). @@ -686,24 +821,34 @@ owngil_reentrant_nested_test(_Config) -> py:register_function(owngil_level, fun([Level, N]) -> case Level >= N of - true -> Level; + true -> + Level; false -> %% Use py:eval to go through pool for re-entry - Code = iolist_to_binary(io_lib:format( - "__import__('erlang').call('owngil_level', ~p, ~p)", - [Level + 1, N])), + Code = iolist_to_binary( + io_lib:format( + "__import__('erlang').call('owngil_level', ~p, ~p)", + [Level + 1, N] + ) + ), {ok, Result} = py:eval(Code), Result end end), %% Test 3 levels of nesting - {ok, 3} = py_context:eval(Ctx, - <<"__import__('erlang').call('owngil_level', 1, 3)">>, #{}), + {ok, 3} = py_context:eval( + Ctx, + <<"__import__('erlang').call('owngil_level', 1, 3)">>, + #{} + ), %% Test 5 levels - {ok, 5} = py_context:eval(Ctx, - <<"__import__('erlang').call('owngil_level', 1, 5)">>, #{}), + {ok, 5} = py_context:eval( + Ctx, + <<"__import__('erlang').call('owngil_level', 1, 5)">>, + #{} + ), py_context:stop(Ctx). @@ -714,10 +859,14 @@ owngil_reentrant_nested_test(_Config) -> owngil_reentrant_multi_stress_test(_Config) -> py:register_function(owngil_level, fun([Level, N]) -> case Level >= N of - true -> Level; + true -> + Level; false -> - Code = iolist_to_binary(io_lib:format( - "__import__('erlang').call('owngil_level', ~p, ~p)", [Level + 1, N])), + Code = iolist_to_binary( + io_lib:format( + "__import__('erlang').call('owngil_level', ~p, ~p)", [Level + 1, N] + ) + ), {ok, R} = py:eval(Code), R end @@ -725,43 +874,73 @@ owngil_reentrant_multi_stress_test(_Config) -> %% Kept light so it stays fast and non-flaky on slow CI hosts while still %% driving concurrent reentrant suspend/resume across distinct subinterpreters. Parent = self(), - Pids = [spawn(fun() -> - {ok, Ctx} = py_context:start_link(CtxId, owngil), - Ok = lists:all(fun(_) -> - {ok, 4} =:= py_context:eval(Ctx, - <<"__import__('erlang').call('owngil_level', 1, 4)">>, #{}) - end, lists:seq(1, 5)), - py_context:stop(Ctx), - Parent ! {self(), Ok} - end) || CtxId <- lists:seq(1, 2)], - [receive {P, true} -> ok after 120000 -> error({stress_failed, P}) end || P <- Pids], + Pids = [ + spawn(fun() -> + {ok, Ctx} = py_context:start_link(CtxId, owngil), + Ok = lists:all( + fun(_) -> + {ok, 4} =:= + py_context:eval( + Ctx, + <<"__import__('erlang').call('owngil_level', 1, 4)">>, + #{} + ) + end, + lists:seq(1, 5) + ), + py_context:stop(Ctx), + Parent ! {self(), Ok} + end) + || CtxId <- lists:seq(1, 2) + ], + [ + receive + {P, true} -> ok + after 120000 -> error({stress_failed, P}) + end + || P <- Pids + ], ok. %% @doc Concurrent callbacks from multiple owngil contexts owngil_reentrant_concurrent_test(_Config) -> NumContexts = 4, - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], py:register_function(owngil_triple, fun([X]) -> X * 3 end), Parent = self(), %% Concurrent callback calls - [spawn_link(fun() -> - Input = N * 10, - {ok, Result} = py_context:eval(Ctx, iolist_to_binary( - io_lib:format("__import__('erlang').call('owngil_triple', ~p)", [Input])), #{}), - Parent ! {done, N, Result, Input * 3} - end) || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + [ + spawn_link(fun() -> + Input = N * 10, + {ok, Result} = py_context:eval( + Ctx, + iolist_to_binary( + io_lib:format("__import__('erlang').call('owngil_triple', ~p)", [Input]) + ), + #{} + ), + Parent ! {done, N, Result, Input * 3} + end) + || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], %% Verify results - [receive - {done, N, Result, Expected} -> - Expected = Result - end || N <- lists:seq(1, NumContexts)], + [ + receive + {done, N, Result, Expected} -> + Expected = Result + end + || N <- lists:seq(1, NumContexts) + ], [py_context:stop(Ctx) || Ctx <- Contexts], ok. @@ -783,13 +962,20 @@ owngil_reentrant_complex_types_test(_Config) -> end end), - {ok, Result} = py_context:eval(Ctx, - <<"__import__('erlang').call('owngil_transform', " - "{'items': [1, 2, 3], 'count': 5})">>, #{}), - - #{<<"items">> := [3, 2, 1], - <<"count">> := 10, - <<"processed">> := true} = Result, + {ok, Result} = py_context:eval( + Ctx, + << + "__import__('erlang').call('owngil_transform', " + "{'items': [1, 2, 3], 'count': 5})" + >>, + #{} + ), + + #{ + <<"items">> := [3, 2, 1], + <<"count">> := 10, + <<"processed">> := true + } = Result, py_context:stop(Ctx). @@ -799,13 +985,15 @@ owngil_reentrant_thread_callback_test(_Config) -> py:register_function(owngil_echo, fun([X]) -> X end), - Code = <<"(lambda cf, erlang: (lambda executor: (lambda future: " - "('success', future.result()) if not future.exception() " - "else ('error', str(future.exception())))" - "(executor.submit(lambda: erlang.call('owngil_echo', 42))))" - "(cf.ThreadPoolExecutor(max_workers=1).__enter__()))" - "(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), " - "__import__('erlang'))">>, + Code = << + "(lambda cf, erlang: (lambda executor: (lambda future: " + "('success', future.result()) if not future.exception() " + "else ('error', str(future.exception())))" + "(executor.submit(lambda: erlang.call('owngil_echo', 42))))" + "(cf.ThreadPoolExecutor(max_workers=1).__enter__()))" + "(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), " + "__import__('erlang'))" + >>, {ok, Result} = py_context:eval(Ctx, Code, #{}), @@ -825,16 +1013,17 @@ owngil_reentrant_try_except_test(_Config) -> py:register_function(owngil_callback, fun([X]) -> X * 2 end), %% Test callback in try/except - ok = py_context:exec(Ctx, <<" -import erlang - -def call_with_try(): - try: - result = erlang.call('owngil_callback', 21) - return ('ok', result) - except Exception as e: - return ('error', str(e)) -">>), + ok = py_context:exec(Ctx, << + "\n" + "import erlang\n" + "\n" + "def call_with_try():\n" + " try:\n" + " result = erlang.call('owngil_callback', 21)\n" + " return ('ok', result)\n" + " except Exception as e:\n" + " return ('error', str(e))\n" + >>), {ok, {<<"ok">>, 42}} = py_context:eval(Ctx, <<"call_with_try()">>, #{}), @@ -849,8 +1038,14 @@ owngil_pid_roundtrip_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), {ok, ReturnedPid} = py_context:call(Ctx, py_test_pid_send, round_trip_pid, [Pid], #{}), @@ -863,13 +1058,20 @@ owngil_send_simple_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), {ok, true} = py_context:call(Ctx, py_test_pid_send, send_message, [Pid, <<"hello">>], #{}), - receive <<"hello">> -> ok + receive + <<"hello">> -> ok after 5000 -> ct:fail(timeout) end, @@ -880,16 +1082,36 @@ owngil_send_multiple_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), - {ok, 3} = py_context:call(Ctx, py_test_pid_send, send_multiple, - [Pid, [<<"one">>, <<"two">>, <<"three">>]], #{}), + {ok, 3} = py_context:call( + Ctx, + py_test_pid_send, + send_multiple, + [Pid, [<<"one">>, <<"two">>, <<"three">>]], + #{} + ), - receive <<"one">> -> ok after 5000 -> ct:fail(timeout_1) end, - receive <<"two">> -> ok after 5000 -> ct:fail(timeout_2) end, - receive <<"three">> -> ok after 5000 -> ct:fail(timeout_3) end, + receive + <<"one">> -> ok + after 5000 -> ct:fail(timeout_1) + end, + receive + <<"two">> -> ok + after 5000 -> ct:fail(timeout_2) + end, + receive + <<"three">> -> ok + after 5000 -> ct:fail(timeout_3) + end, py_context:stop(Ctx). @@ -898,8 +1120,14 @@ owngil_send_complex_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), {ok, true} = py_context:call(Ctx, py_test_pid_send, send_complex_term, [Pid], #{}), @@ -916,13 +1144,24 @@ owngil_suspension_not_caught_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), py:register_function(test_pid_echo, fun([X]) -> X end), - {ok, {<<"ok">>, 42}} = py_context:call(Ctx, py_test_pid_send, - suspension_not_caught_by_except_exception, [], #{}), + {ok, {<<"ok">>, 42}} = py_context:call( + Ctx, + py_test_pid_send, + suspension_not_caught_by_except_exception, + [], + #{} + ), py:unregister_function(test_pid_echo), py_context:stop(Ctx). @@ -932,14 +1171,26 @@ owngil_send_from_coroutine_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), - {ok, true} = py_context:call(Ctx, py_test_pid_send, send_from_coroutine, - [Pid, <<"async_hello">>], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + send_from_coroutine, + [Pid, <<"async_hello">>], + #{} + ), - receive <<"async_hello">> -> ok + receive + <<"async_hello">> -> ok after 5000 -> ct:fail(timeout) end, @@ -950,13 +1201,24 @@ owngil_send_nonblocking_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), Count = 100, - {ok, Elapsed} = py_context:call(Ctx, py_test_pid_send, send_is_nonblocking, - [Pid, Count], #{}), + {ok, Elapsed} = py_context:call( + Ctx, + py_test_pid_send, + send_is_nonblocking, + [Pid, Count], + #{} + ), ct:pal("Sent ~p messages in ~.6f seconds", [Count, Elapsed]), true = Elapsed < 1.0, @@ -972,27 +1234,52 @@ owngil_send_parallel_test(Config) -> MessagesPerContext = 25, TestDir = proplists:get_value(test_dir, Config), - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Parent = self(), Pid = self(), %% Parallel senders - [spawn_link(fun() -> - lists:foreach(fun(M) -> - py_context:call(Ctx, py_test_pid_send, send_message, - [Pid, {N, M}], #{}) - end, lists:seq(1, MessagesPerContext)), - Parent ! {sender_done, N} - end) || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + [ + spawn_link(fun() -> + lists:foreach( + fun(M) -> + py_context:call( + Ctx, + py_test_pid_send, + send_message, + [Pid, {N, M}], + #{} + ) + end, + lists:seq(1, MessagesPerContext) + ), + Parent ! {sender_done, N} + end) + || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], %% Wait for senders - [receive {sender_done, N} -> ok end || N <- lists:seq(1, NumContexts)], + [ + receive + {sender_done, N} -> ok + end + || N <- lists:seq(1, NumContexts) + ], %% Count messages TotalMessages = NumContexts * MessagesPerContext, @@ -1013,23 +1300,24 @@ owngil_reactor_echo_protocol_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), %% Set up the protocol factory - ok = py_context:exec(Ctx, <<" -import erlang.reactor as reactor - -class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(EchoProtocol) -">>), + ok = py_context:exec(Ctx, << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(EchoProtocol)\n" + >>), %% Verify protocol factory is set {ok, true} = py_context:eval(Ctx, <<"reactor._protocol_factory is not None">>, #{}), @@ -1041,30 +1329,31 @@ reactor.set_protocol_factory(EchoProtocol) %% @doc Multiple connections in owngil reactor owngil_reactor_multiple_conn_test(_Config) -> - SetupCode = <<" -import erlang.reactor as reactor - -class CounterProtocol(reactor.Protocol): - counter = 0 - - def connection_made(self, fd, client_info): - super().connection_made(fd, client_info) - CounterProtocol.counter += 1 - self.my_id = CounterProtocol.counter - - def data_received(self, data): - self.write_buffer.extend(str(self.my_id).encode() + b':' + data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'close' - -reactor.set_protocol_factory(CounterProtocol) -">>, + SetupCode = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class CounterProtocol(reactor.Protocol):\n" + " counter = 0\n" + "\n" + " def connection_made(self, fd, client_info):\n" + " super().connection_made(fd, client_info)\n" + " CounterProtocol.counter += 1\n" + " self.my_id = CounterProtocol.counter\n" + "\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(str(self.my_id).encode() + b':' + data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'close'\n" + "\n" + "reactor.set_protocol_factory(CounterProtocol)\n" + >>, {ok, ReactorCtx} = py_reactor_context:start_link(1, owngil, #{ setup_code => SetupCode @@ -1074,52 +1363,62 @@ reactor.set_protocol_factory(CounterProtocol) Pairs = [create_socketpair() || _ <- lists:seq(1, 3)], %% Handoff all - [begin - {ok, {Server, _}} = Pair, - Fd = get_fd(Server), - ok = py_reactor_context:handoff(ReactorCtx, Fd, #{}) - end || Pair <- Pairs], + [ + begin + {ok, {Server, _}} = Pair, + Fd = get_fd(Server), + ok = py_reactor_context:handoff(ReactorCtx, Fd, #{}) + end + || Pair <- Pairs + ], timer:sleep(100), %% Send and receive - Results = [begin - {ok, {_, Client}} = Pair, - ok = gen_tcp:send(Client, <<"test">>), - {ok, Data} = gen_tcp:recv(Client, 0, 2000), - Data - end || Pair <- Pairs], + Results = [ + begin + {ok, {_, Client}} = Pair, + ok = gen_tcp:send(Client, <<"test">>), + {ok, Data} = gen_tcp:recv(Client, 0, 2000), + Data + end + || Pair <- Pairs + ], %% Verify unique IDs [<<"1:test">>, <<"2:test">>, <<"3:test">>] = lists:sort(Results), %% Cleanup - [begin - {ok, {Server, Client}} = Pair, - gen_tcp:close(Server), - gen_tcp:close(Client) - end || Pair <- Pairs], + [ + begin + {ok, {Server, Client}} = Pair, + gen_tcp:close(Server), + gen_tcp:close(Client) + end + || Pair <- Pairs + ], py_reactor_context:stop(ReactorCtx). %% @doc async_pending pattern in owngil reactor owngil_reactor_async_pending_test(_Config) -> - SetupCode = <<" -import erlang.reactor as reactor - -class AsyncPendingProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(b'ASYNC:' + data) - reactor.signal_write_ready(self.fd) - return 'async_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'close' - -reactor.set_protocol_factory(AsyncPendingProtocol) -">>, + SetupCode = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class AsyncPendingProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(b'ASYNC:' + data)\n" + " reactor.signal_write_ready(self.fd)\n" + " return 'async_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'close'\n" + "\n" + "reactor.set_protocol_factory(AsyncPendingProtocol)\n" + >>, {ok, ReactorCtx} = py_reactor_context:start_link(1, owngil, #{ setup_code => SetupCode @@ -1146,15 +1445,16 @@ owngil_reactor_buffer_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), %% Test basic bytes operations that would be similar to ReactorBuffer - ok = py_context:exec(Ctx, <<" -data = b'reactor buffer test' -result = { - 'len': len(data), - 'startswith': data.startswith(b'reactor'), - 'find': data.find(b'buffer'), - 'slice': data[8:14] -} -">>), + ok = py_context:exec(Ctx, << + "\n" + "data = b'reactor buffer test'\n" + "result = {\n" + " 'len': len(data),\n" + " 'startswith': data.startswith(b'reactor'),\n" + " 'find': data.find(b'buffer'),\n" + " 'slice': data[8:14]\n" + "}\n" + >>), {ok, #{ <<"len">> := 19, @@ -1167,41 +1467,43 @@ result = { %% @doc Protocol factory isolation between owngil contexts owngil_reactor_isolation_test(_Config) -> - EchoSetup = <<" -import erlang.reactor as reactor - -class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'close' - -reactor.set_protocol_factory(EchoProtocol) -">>, - - UpperSetup = <<" -import erlang.reactor as reactor - -class UpperProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(bytes(data).upper()) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'close' - -reactor.set_protocol_factory(UpperProtocol) -">>, + EchoSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'close'\n" + "\n" + "reactor.set_protocol_factory(EchoProtocol)\n" + >>, + + UpperSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class UpperProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(bytes(data).upper())\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'close'\n" + "\n" + "reactor.set_protocol_factory(UpperProtocol)\n" + >>, {ok, Ctx1} = py_reactor_context:start_link(1, owngil, #{setup_code => EchoSetup}), {ok, Ctx2} = py_reactor_context:start_link(2, owngil, #{setup_code => UpperSetup}), @@ -1219,8 +1521,10 @@ reactor.set_protocol_factory(UpperProtocol) {ok, R1} = gen_tcp:recv(S1b, 0, 2000), {ok, R2} = gen_tcp:recv(S2b, 0, 2000), - gen_tcp:close(S1a), gen_tcp:close(S1b), - gen_tcp:close(S2a), gen_tcp:close(S2b), + gen_tcp:close(S1a), + gen_tcp:close(S1b), + gen_tcp:close(S2a), + gen_tcp:close(S2b), py_reactor_context:stop(Ctx1), py_reactor_context:stop(Ctx2), @@ -1252,26 +1556,35 @@ owngil_async_run_sync_test(_Config) -> %% @doc Concurrent tasks across owngil contexts owngil_async_concurrent_test(_Config) -> NumContexts = 4, - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Parent = self(), %% Submit concurrent tasks - [spawn_link(fun() -> - Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), - {ok, Result} = py_event_loop:await(Ref, 5000), - Parent ! {done, N, Result} - end) || {N, _Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + [ + spawn_link(fun() -> + Ref = py_event_loop:create_task(math, sqrt, [float(N * N)]), + {ok, Result} = py_event_loop:await(Ref, 5000), + Parent ! {done, N, Result} + end) + || {N, _Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], %% Verify results - [receive - {done, N, Result} -> - Expected = float(N), - true = abs(Result - Expected) < 0.0001 - end || N <- lists:seq(1, NumContexts)], + [ + receive + {done, N, Result} -> + Expected = float(N), + true = abs(Result - Expected) < 0.0001 + end + || N <- lists:seq(1, NumContexts) + ], [py_context:stop(Ctx) || Ctx <- Contexts], ok. @@ -1281,17 +1594,24 @@ owngil_async_batch_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), NumTasks = 50, - Refs = [py_event_loop:create_task(math, sqrt, [float(N)]) - || N <- lists:seq(1, NumTasks)], + Refs = [ + py_event_loop:create_task(math, sqrt, [float(N)]) + || N <- lists:seq(1, NumTasks) + ], - Results = [{N, py_event_loop:await(Ref, 5000)} - || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs)], + Results = [ + {N, py_event_loop:await(Ref, 5000)} + || {N, Ref} <- lists:zip(lists:seq(1, NumTasks), Refs) + ], %% Verify all succeeded - lists:foreach(fun({N, {ok, R}}) -> - Expected = math:sqrt(N), - true = abs(R - Expected) < 0.0001 - end, Results), + lists:foreach( + fun({N, {ok, R}}) -> + Expected = math:sqrt(N), + true = abs(R - Expected) < 0.0001 + end, + Results + ), py_context:stop(Ctx). @@ -1299,12 +1619,13 @@ owngil_async_batch_test(_Config) -> owngil_async_timeout_test(_Config) -> {ok, _Ctx} = py_context:start_link(1, owngil), - ok = py:exec(<<" -async def slow_async(seconds): - import asyncio - await asyncio.sleep(seconds) - return 'completed' -">>), + ok = py:exec(<< + "\n" + "async def slow_async(seconds):\n" + " import asyncio\n" + " await asyncio.sleep(seconds)\n" + " return 'completed'\n" + >>), Ref = py_event_loop:create_task('__main__', slow_async, [10.0]), {error, timeout} = py_event_loop:await(Ref, 100), @@ -1315,12 +1636,13 @@ async def slow_async(seconds): owngil_async_error_test(_Config) -> {ok, _Ctx} = py_context:start_link(1, owngil), - ok = py:exec(<<" -async def failing_async(): - import asyncio - await asyncio.sleep(0.001) - raise ValueError('test_error') -">>), + ok = py:exec(<< + "\n" + "async def failing_async():\n" + " import asyncio\n" + " await asyncio.sleep(0.001)\n" + " raise ValueError('test_error')\n" + >>), Ref = py_event_loop:create_task('__main__', failing_async, []), Result = py_event_loop:await(Ref, 5000), @@ -1338,20 +1660,21 @@ async def failing_async(): owngil_asyncio_basic_sleep_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), - ok = py_context:exec(Ctx, <<" -import asyncio - -async def sleep_test(): - await asyncio.sleep(0.01) - return 'slept' - -def run_sleep(): - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(sleep_test()) - finally: - loop.close() -">>), + ok = py_context:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def sleep_test():\n" + " await asyncio.sleep(0.01)\n" + " return 'slept'\n" + "\n" + "def run_sleep():\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(sleep_test())\n" + " finally:\n" + " loop.close()\n" + >>), {ok, <<"slept">>} = py_context:eval(Ctx, <<"run_sleep()">>, #{}), @@ -1361,24 +1684,25 @@ def run_sleep(): owngil_asyncio_gather_test(_Config) -> {ok, Ctx} = py_context:start_link(1, owngil), - ok = py_context:exec(Ctx, <<" -import asyncio - -async def task(n): - await asyncio.sleep(0.01) - return n * 2 - -async def gather_test(): - results = await asyncio.gather(task(1), task(2), task(3)) - return results - -def run_gather(): - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(gather_test()) - finally: - loop.close() -">>), + ok = py_context:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def task(n):\n" + " await asyncio.sleep(0.01)\n" + " return n * 2\n" + "\n" + "async def gather_test():\n" + " results = await asyncio.gather(task(1), task(2), task(3))\n" + " return results\n" + "\n" + "def run_gather():\n" + " loop = asyncio.new_event_loop()\n" + " try:\n" + " return loop.run_until_complete(gather_test())\n" + " finally:\n" + " loop.close()\n" + >>), {ok, [2, 4, 6]} = py_context:eval(Ctx, <<"run_gather()">>, #{}), @@ -1387,37 +1711,47 @@ def run_gather(): %% @doc Independent event loops per owngil context owngil_asyncio_parallel_loops_test(_Config) -> NumContexts = 4, - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, <<" -import asyncio - -async def loop_task(ctx_id, n): - await asyncio.sleep(0.01) - return f'ctx{ctx_id}_task{n}' - -async def gather_tasks(ctx_id): - return await asyncio.gather( - loop_task(ctx_id, 1), - loop_task(ctx_id, 2) - ) - -def run_tasks(ctx_id): - # Use asyncio.run for proper event loop management in Python 3.10+ - return asyncio.run(gather_tasks(ctx_id)) -">>), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec(Ctx, << + "\n" + "import asyncio\n" + "\n" + "async def loop_task(ctx_id, n):\n" + " await asyncio.sleep(0.01)\n" + " return f'ctx{ctx_id}_task{n}'\n" + "\n" + "async def gather_tasks(ctx_id):\n" + " return await asyncio.gather(\n" + " loop_task(ctx_id, 1),\n" + " loop_task(ctx_id, 2)\n" + " )\n" + "\n" + "def run_tasks(ctx_id):\n" + " # Use asyncio.run for proper event loop management in Python 3.10+\n" + " return asyncio.run(gather_tasks(ctx_id))\n" + >>), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Start = erlang:monotonic_time(millisecond), %% Run each context sequentially from the main process %% Each owngil context has its own dedicated thread providing parallelism - AllResults = [begin - {ok, Results} = py_context:eval(Ctx, - iolist_to_binary(io_lib:format("run_tasks(~p)", [N])), #{}), - {N, Results} - end || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + AllResults = [ + begin + {ok, Results} = py_context:eval( + Ctx, + iolist_to_binary(io_lib:format("run_tasks(~p)", [N])), + #{} + ), + {N, Results} + end + || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], Elapsed = erlang:monotonic_time(millisecond) - Start, ct:pal("Event loops completed in ~p ms", [Elapsed]), @@ -1439,11 +1773,13 @@ drain_channel(_Ch, 0, Acc) -> lists:reverse(Acc); drain_channel(Ch, N, Acc) -> case py_nif:channel_try_receive(Ch) of - {ok, Msg} -> drain_channel(Ch, N - 1, [Msg | Acc]); + {ok, Msg} -> + drain_channel(Ch, N - 1, [Msg | Acc]); {error, empty} -> timer:sleep(10), drain_channel(Ch, N, Acc); - {error, closed} -> lists:reverse(Acc) + {error, closed} -> + lists:reverse(Acc) end. consume_until_closed(Ctx, Ch, Parent, CtxNum) -> @@ -1455,7 +1791,8 @@ consume_until_closed(Ctx, Ch, Parent, CtxNum, Acc) -> %% Empty, check if closed Info = py_channel:info(Ch), case maps:get(closed, Info) of - true -> Parent ! {consumer_result, CtxNum, lists:reverse(Acc)}; + true -> + Parent ! {consumer_result, CtxNum, lists:reverse(Acc)}; false -> timer:sleep(5), consume_until_closed(Ctx, Ch, Parent, CtxNum, Acc) @@ -1468,16 +1805,19 @@ consume_until_closed(Ctx, Ch, Parent, CtxNum, Acc) -> Parent ! {consumer_result, CtxNum, lists:reverse(Acc)} end. -drain_pid_messages(0) -> ok; +drain_pid_messages(0) -> + ok; drain_pid_messages(N) -> receive {<<"msg">>, _} -> drain_pid_messages(N - 1) after 1000 -> ct:pal("Drained ~p messages, ~p remaining", [100 - N, N]), - ok %% Tolerate some loss in high-volume test + %% Tolerate some loss in high-volume test + ok end. -drain_tuple_messages(0) -> ok; +drain_tuple_messages(0) -> + ok; drain_tuple_messages(N) -> receive {_, _} -> drain_tuple_messages(N - 1) @@ -1541,7 +1881,8 @@ owngil_local_env_isolation_test(_Config) -> %% y should not exist in Env2 Result = py_nif:context_eval(CtxRef, <<"y">>, #{}, Env2), case Result of - {error, _} -> ok; %% Expected: NameError + %% Expected: NameError + {error, _} -> ok; _ -> ct:fail({unexpected_result, Result}) end, @@ -1557,17 +1898,24 @@ owngil_local_env_call_test(_Config) -> %% Define a function in the local environment %% py_nif:context_exec/3 is the with_env variant (arity overload) - ok = py_nif:context_exec(CtxRef, <<" -def double(x): - return x * 2 - -def greet(name): - return f'Hello, {name}!' -">>, Env), + ok = py_nif:context_exec( + CtxRef, + << + "\n" + "def double(x):\n" + " return x * 2\n" + "\n" + "def greet(name):\n" + " return f'Hello, {name}!'\n" + >>, + Env + ), %% Call the function using call/6 (the with_env variant by arity) {ok, 42} = py_nif:context_call(CtxRef, <<"__main__">>, <<"double">>, [21], #{}, Env), - {ok, <<"Hello, World!">>} = py_nif:context_call(CtxRef, <<"__main__">>, <<"greet">>, [<<"World">>], #{}, Env), + {ok, <<"Hello, World!">>} = py_nif:context_call( + CtxRef, <<"__main__">>, <<"greet">>, [<<"World">>], #{}, Env + ), %% Test calling imported module function {ok, 2.0} = py_nif:context_call(CtxRef, <<"math">>, <<"sqrt">>, [4.0], #{}, Env), @@ -1583,15 +1931,26 @@ owngil_whereis_basic_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Register self under a name true = register(owngil_whereis_test_proc, self()), %% Look up the process from Python - {ok, FoundPid} = py_context:call(Ctx, py_test_pid_send, whereis_basic, - [owngil_whereis_test_proc], #{}), + {ok, FoundPid} = py_context:call( + Ctx, + py_test_pid_send, + whereis_basic, + [owngil_whereis_test_proc], + #{} + ), %% Verify it matches Self = self(), @@ -1605,12 +1964,23 @@ owngil_whereis_nonexistent_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Look up a name that doesn't exist - {ok, none} = py_context:call(Ctx, py_test_pid_send, whereis_basic, - [nonexistent_proc_name_xyz], #{}), + {ok, none} = py_context:call( + Ctx, + py_test_pid_send, + whereis_basic, + [nonexistent_proc_name_xyz], + #{} + ), py_context:stop(Ctx). @@ -1619,18 +1989,30 @@ owngil_whereis_and_send_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Register self under a name true = register(owngil_whereis_send_test, self()), %% Use whereis_and_send from Python - {ok, true} = py_context:call(Ctx, py_test_pid_send, whereis_and_send, - [owngil_whereis_send_test, <<"hello_from_whereis">>], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + whereis_and_send, + [owngil_whereis_send_test, <<"hello_from_whereis">>], + #{} + ), %% Verify message received - receive <<"hello_from_whereis">> -> ok + receive + <<"hello_from_whereis">> -> ok after 5000 -> ct:fail(timeout) end, @@ -1645,24 +2027,46 @@ owngil_whereis_parallel_test(Config) -> %% Register self true = register(owngil_parallel_whereis_test, self()), - Contexts = [begin - {ok, Ctx} = py_context:start_link(N, owngil), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), - Ctx - end || N <- lists:seq(1, NumContexts)], + Contexts = [ + begin + {ok, Ctx} = py_context:start_link(N, owngil), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), + Ctx + end + || N <- lists:seq(1, NumContexts) + ], Parent = self(), %% Parallel whereis + send - [spawn_link(fun() -> - {ok, true} = py_context:call(Ctx, py_test_pid_send, whereis_and_send, - [owngil_parallel_whereis_test, {from_ctx, N}], #{}), - Parent ! {sender_done, N} - end) || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts)], + [ + spawn_link(fun() -> + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + whereis_and_send, + [owngil_parallel_whereis_test, {from_ctx, N}], + #{} + ), + Parent ! {sender_done, N} + end) + || {N, Ctx} <- lists:zip(lists:seq(1, NumContexts), Contexts) + ], %% Wait for senders to complete - [receive {sender_done, _} -> ok end || _ <- lists:seq(1, NumContexts)], + [ + receive + {sender_done, _} -> ok + end + || _ <- lists:seq(1, NumContexts) + ], %% Verify all messages received (order may vary) Messages = collect_from_ctx_messages(NumContexts, []), @@ -1681,21 +2085,42 @@ owngil_atom_basic_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test atom type - get the actual type name for debugging - {ok, TypeName} = py_context:call(Ctx, py_test_pid_send, atom_type_check, - [test_atom], #{}), + {ok, TypeName} = py_context:call( + Ctx, + py_test_pid_send, + atom_type_check, + [test_atom], + #{} + ), ct:pal("Atom type name in OWN_GIL: ~p", [TypeName]), %% Test same atoms are equal - {ok, true} = py_context:call(Ctx, py_test_pid_send, atom_equality_test, - [hello, hello], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + atom_equality_test, + [hello, hello], + #{} + ), %% Test different atoms are not equal - {ok, true} = py_context:call(Ctx, py_test_pid_send, atom_inequality_test, - [foo, bar], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + atom_inequality_test, + [foo, bar], + #{} + ), py_context:stop(Ctx). @@ -1706,13 +2131,24 @@ owngil_atom_roundtrip_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Pass atom to Python and get it back TestAtom = test_atom_owngil, - {ok, ReturnedValue} = py_context:call(Ctx, py_test_pid_send, atom_roundtrip, - [TestAtom], #{}), + {ok, ReturnedValue} = py_context:call( + Ctx, + py_test_pid_send, + atom_roundtrip, + [TestAtom], + #{} + ), %% In OWN_GIL mode, atoms become strings, so we get a binary back ExpectedBinary = atom_to_binary(TestAtom), @@ -1725,8 +2161,14 @@ owngil_atom_create_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test that erlang.atom() creates equal atoms for same name {ok, true} = py_context:call(Ctx, py_test_pid_send, atom_create_test, [], #{}), @@ -1738,8 +2180,14 @@ owngil_atom_create_different_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test that erlang.atom() creates different atoms for different names {ok, true} = py_context:call(Ctx, py_test_pid_send, atom_create_different_test, [], #{}), @@ -1751,8 +2199,14 @@ owngil_atom_cache_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test atom caching - same object returned for same name {ok, true} = py_context:call(Ctx, py_test_pid_send, atom_cache_test, [], #{}), @@ -1768,8 +2222,14 @@ owngil_ref_roundtrip_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Create refs Ref1 = make_ref(), @@ -1789,8 +2249,14 @@ owngil_pid_operations_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Pid = self(), @@ -1817,8 +2283,14 @@ owngil_channel_class_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_channel:new(), @@ -1826,8 +2298,13 @@ owngil_channel_class_test(Config) -> ok = py_channel:send(Ch, <<"test_channel_class">>), %% Receive via Channel class in Python - {ok, <<"test_channel_class">>} = py_context:call(Ctx, py_test_pid_send, - channel_receive_test, [Ch], #{}), + {ok, <<"test_channel_class">>} = py_context:call( + Ctx, + py_test_pid_send, + channel_receive_test, + [Ch], + #{} + ), py_channel:close(Ch), py_context:stop(Ctx). @@ -1837,8 +2314,14 @@ owngil_channel_iteration_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_channel:new(), @@ -1848,8 +2331,13 @@ owngil_channel_iteration_test(Config) -> ok = py_channel:send(Ch, <<"msg3">>), %% Iterate in Python - {ok, 3} = py_context:call(Ctx, py_test_pid_send, - channel_iteration_test, [Ch, 3], #{}), + {ok, 3} = py_context:call( + Ctx, + py_test_pid_send, + channel_iteration_test, + [Ch, 3], + #{} + ), py_channel:close(Ch), py_context:stop(Ctx). @@ -1859,8 +2347,14 @@ owngil_channel_context_manager_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_channel:new(), @@ -1868,8 +2362,13 @@ owngil_channel_context_manager_test(Config) -> ok = py_channel:send(Ch, <<"context_msg">>), %% Test context manager usage - {ok, true} = py_context:call(Ctx, py_test_pid_send, - channel_context_manager_test, [Ch], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + channel_context_manager_test, + [Ch], + #{} + ), py_channel:close(Ch), py_context:stop(Ctx). @@ -1883,14 +2382,25 @@ owngil_bytechannel_send_receive_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_byte_channel:new(), %% Send bytes from Python via ByteChannel - {ok, true} = py_context:call(Ctx, py_test_pid_send, - bytechannel_send_receive_test, [Ch], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + bytechannel_send_receive_test, + [Ch], + #{} + ), %% Receive raw bytes from Erlang using byte channel API {ok, <<"hello_owngil">>} = py_byte_channel:try_receive(Ch), @@ -1903,8 +2413,14 @@ owngil_bytechannel_try_receive_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_byte_channel:new(), @@ -1912,8 +2428,13 @@ owngil_bytechannel_try_receive_test(Config) -> ok = py_byte_channel:send(Ch, <<"bytes_data">>), %% Receive via ByteChannel in Python - {ok, <<"bytes_data">>} = py_context:call(Ctx, py_test_pid_send, - bytechannel_try_receive_test, [Ch], #{}), + {ok, <<"bytes_data">>} = py_context:call( + Ctx, + py_test_pid_send, + bytechannel_try_receive_test, + [Ch], + #{} + ), py_byte_channel:close(Ch), py_context:stop(Ctx). @@ -1923,8 +2444,14 @@ owngil_bytechannel_iteration_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Ch} = py_byte_channel:new(), @@ -1933,8 +2460,13 @@ owngil_bytechannel_iteration_test(Config) -> ok = py_byte_channel:send(Ch, <<"chunk2">>), %% Iterate in Python - {ok, 2} = py_context:call(Ctx, py_test_pid_send, - bytechannel_iteration_test, [Ch, 2], #{}), + {ok, 2} = py_context:call( + Ctx, + py_test_pid_send, + bytechannel_iteration_test, + [Ch, 2], + #{} + ), py_byte_channel:close(Ch), py_context:stop(Ctx). @@ -1948,8 +2480,14 @@ owngil_buffer_read_methods_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Buf} = py_buffer:new(), @@ -1957,8 +2495,13 @@ owngil_buffer_read_methods_test(Config) -> ok = py_buffer:write(Buf, <<"test_data">>), %% Test read methods from Python - {ok, Result} = py_context:call(Ctx, py_test_pid_send, - buffer_read_methods_test, [Buf], #{}), + {ok, Result} = py_context:call( + Ctx, + py_test_pid_send, + buffer_read_methods_test, + [Buf], + #{} + ), %% Verify readable amount and data #{<<"readable">> := Readable, <<"data">> := Data} = Result, @@ -1973,20 +2516,36 @@ owngil_buffer_at_eof_test(Config) -> {ok, Ctx} = py_context:start_link(1, owngil), TestDir = proplists:get_value(test_dir, Config), - ok = py_context:exec(Ctx, iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py_context:exec( + Ctx, + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), {ok, Buf} = py_buffer:new(), %% Buffer not yet at EOF (not closed) - {ok, false} = py_context:call(Ctx, py_test_pid_send, - buffer_at_eof_test, [Buf], #{}), + {ok, false} = py_context:call( + Ctx, + py_test_pid_send, + buffer_at_eof_test, + [Buf], + #{} + ), %% Close buffer ok = py_buffer:close(Buf), %% Now at EOF - {ok, true} = py_context:call(Ctx, py_test_pid_send, - buffer_at_eof_test, [Buf], #{}), + {ok, true} = py_context:call( + Ctx, + py_test_pid_send, + buffer_at_eof_test, + [Buf], + #{} + ), py_context:stop(Ctx). diff --git a/test/py_pid_send_SUITE.erl b/test/py_pid_send_SUITE.erl index 5497f3b..4ec22a0 100644 --- a/test/py_pid_send_SUITE.erl +++ b/test/py_pid_send_SUITE.erl @@ -85,13 +85,19 @@ init_per_suite(Config) -> %% Add test directory to Python path on ALL contexts %% (subinterpreters have isolated sys.path) TestDir = filename:join(code:lib_dir(erlang_python), "test"), - PathCmd = iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir])), + PathCmd = iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ), NumContexts = py_context_router:num_contexts(), - lists:foreach(fun(I) -> - Ctx = py_context_router:get_context(I), - ok = py_context:exec(Ctx, PathCmd) - end, lists:seq(1, NumContexts)), + lists:foreach( + fun(I) -> + Ctx = py_context_router:get_context(I), + ok = py_context:exec(Ctx, PathCmd) + end, + lists:seq(1, NumContexts) + ), Config. end_per_suite(_Config) -> @@ -102,7 +108,11 @@ init_per_testcase(_TestCase, Config) -> Config. end_per_testcase(_TestCase, _Config) -> - try py:unregister_function(test_pid_echo) catch _:_ -> ok end, + try + py:unregister_function(test_pid_echo) + catch + _:_ -> ok + end, ok. %%% ============================================================================ @@ -141,7 +151,11 @@ test_pid_hash(_Config) -> %% @doc Verify two different PIDs are not equal. test_pid_inequality(_Config) -> Pid1 = self(), - Pid2 = spawn(fun() -> receive stop -> ok end end), + Pid2 = spawn(fun() -> + receive + stop -> ok + end + end), {ok, true} = py:call(py_test_pid_send, pid_inequality, [Pid1, Pid2]), Pid2 ! stop, ok. @@ -163,11 +177,23 @@ test_send_simple_message(_Config) -> %% @doc Test sending multiple messages in sequence. test_send_multiple_messages(_Config) -> Pid = self(), - {ok, 3} = py:call(py_test_pid_send, send_multiple, - [Pid, [<<"one">>, <<"two">>, <<"three">>]]), - receive <<"one">> -> ok after 5000 -> ct:fail(timeout_msg_1) end, - receive <<"two">> -> ok after 5000 -> ct:fail(timeout_msg_2) end, - receive <<"three">> -> ok after 5000 -> ct:fail(timeout_msg_3) end. + {ok, 3} = py:call( + py_test_pid_send, + send_multiple, + [Pid, [<<"one">>, <<"two">>, <<"three">>]] + ), + receive + <<"one">> -> ok + after 5000 -> ct:fail(timeout_msg_1) + end, + receive + <<"two">> -> ok + after 5000 -> ct:fail(timeout_msg_2) + end, + receive + <<"three">> -> ok + after 5000 -> ct:fail(timeout_msg_3) + end. %% @doc Test sending a complex compound term. test_send_complex_term(_Config) -> @@ -188,7 +214,8 @@ test_send_bad_pid_raises(_Config) -> test_send_to_dead_process(_Config) -> %% Spawn a process that exits immediately Pid = spawn(fun() -> ok end), - timer:sleep(100), %% ensure it's dead + %% ensure it's dead + timer:sleep(100), %% erlang.send() to a dead PID should fail (enif_send returns 0) {error, _} = py:call(py_test_pid_send, send_message, [Pid, <<"dead">>]), ok. @@ -216,8 +243,11 @@ test_pid_in_complex_structure(_Config) -> {ok, [ReturnedPid]} = py:call(py_test_pid_send, round_trip_pid, [[Pid]]), Pid = ReturnedPid, %% Pass PID inside a map - {ok, #{<<"pid">> := ReturnedPid2}} = py:call(py_test_pid_send, - round_trip_pid, [#{<<"pid">> => Pid}]), + {ok, #{<<"pid">> := ReturnedPid2}} = py:call( + py_test_pid_send, + round_trip_pid, + [#{<<"pid">> => Pid}] + ), Pid = ReturnedPid2, ok. @@ -232,8 +262,11 @@ test_suspension_not_caught_by_except(_Config) -> %% Register a simple callback py:register_function(test_pid_echo, fun([X]) -> X end), %% Call Python function that wraps erlang.call in try/except Exception - {ok, {<<"ok">>, 42}} = py:call(py_test_pid_send, - suspension_not_caught_by_except_exception, []), + {ok, {<<"ok">>, 42}} = py:call( + py_test_pid_send, + suspension_not_caught_by_except_exception, + [] + ), ok. %% @doc Verify SuspensionRequired IS a subclass of BaseException. @@ -265,9 +298,18 @@ test_send_multiple_from_coroutine(_Config) -> Pid = self(), Messages = [<<"async_1">>, <<"async_2">>, <<"async_3">>], {ok, 3} = py:call(py_test_pid_send, send_multiple_from_coroutine, [Pid, Messages]), - receive <<"async_1">> -> ok after 5000 -> ct:fail(timeout_async_1) end, - receive <<"async_2">> -> ok after 5000 -> ct:fail(timeout_async_2) end, - receive <<"async_3">> -> ok after 5000 -> ct:fail(timeout_async_3) end. + receive + <<"async_1">> -> ok + after 5000 -> ct:fail(timeout_async_1) + end, + receive + <<"async_2">> -> ok + after 5000 -> ct:fail(timeout_async_2) + end, + receive + <<"async_3">> -> ok + after 5000 -> ct:fail(timeout_async_3) + end. %% @doc Test that erlang.send() is non-blocking by sending many messages quickly. %% The function returns elapsed time - it should complete in under 100ms for 1000 messages. @@ -286,9 +328,18 @@ test_send_interleaved_with_async(_Config) -> Pid = self(), Messages = [<<"interleaved_1">>, <<"interleaved_2">>, <<"interleaved_3">>], {ok, [0, 1, 2]} = py:call(py_test_pid_send, send_interleaved_with_async, [Pid, Messages]), - receive <<"interleaved_1">> -> ok after 5000 -> ct:fail(timeout_interleaved_1) end, - receive <<"interleaved_2">> -> ok after 5000 -> ct:fail(timeout_interleaved_2) end, - receive <<"interleaved_3">> -> ok after 5000 -> ct:fail(timeout_interleaved_3) end. + receive + <<"interleaved_1">> -> ok + after 5000 -> ct:fail(timeout_interleaved_1) + end, + receive + <<"interleaved_2">> -> ok + after 5000 -> ct:fail(timeout_interleaved_2) + end, + receive + <<"interleaved_3">> -> ok + after 5000 -> ct:fail(timeout_interleaved_3) + end. %%% ============================================================================ %%% erlang.whereis() Tests @@ -354,8 +405,11 @@ test_whereis_and_send(_Config) -> erlang:register(py_whereis_send_test, Self), try %% Use Python helper to look up process and send message - {ok, true} = py:call(py_test_pid_send, whereis_and_send, - [<<"py_whereis_send_test">>, {<<"hello_from_whereis">>, 42}]), + {ok, true} = py:call( + py_test_pid_send, + whereis_and_send, + [<<"py_whereis_send_test">>, {<<"hello_from_whereis">>, 42}] + ), %% Verify we received the message receive {<<"hello_from_whereis">>, 42} -> ok @@ -371,7 +425,8 @@ test_whereis_and_send(_Config) -> %%% Helper Functions %%% ============================================================================ -drain_messages(0) -> ok; +drain_messages(0) -> + ok; drain_messages(N) -> receive {<<"msg">>, _} -> drain_messages(N - 1) diff --git a/test/py_pool_SUITE.erl b/test/py_pool_SUITE.erl index 443c9c2..ec3c46d 100644 --- a/test/py_pool_SUITE.erl +++ b/test/py_pool_SUITE.erl @@ -206,9 +206,12 @@ test_pool_sizes(_Config) -> IoSize = length(IoContexts), %% All contexts should be alive - lists:foreach(fun(Ctx) -> - true = is_process_alive(Ctx) - end, DefaultContexts ++ IoContexts). + lists:foreach( + fun(Ctx) -> + true = is_process_alive(Ctx) + end, + DefaultContexts ++ IoContexts + ). %% ============================================================================ %% Registration tests diff --git a/test/py_preload_SUITE.erl b/test/py_preload_SUITE.erl index 598aba1..6bcae0a 100644 --- a/test/py_preload_SUITE.erl +++ b/test/py_preload_SUITE.erl @@ -144,13 +144,14 @@ preload_variable_inherited_test(_Config) -> preload_function_inherited_test(_Config) -> %% Set preload code with a function - ok = py_preload:set_code(<<" -def double(x): - return x * 2 - -def add(a, b): - return a + b -">>), + ok = py_preload:set_code(<< + "\n" + "def double(x):\n" + " return x * 2\n" + "\n" + "def add(a, b):\n" + " return a + b\n" + >>), %% Create context and check functions work {ok, Ctx} = py_context:new(#{mode => worker}), @@ -163,10 +164,11 @@ def add(a, b): preload_import_inherited_test(_Config) -> %% Set preload code with imports - ok = py_preload:set_code(<<" -import json -import os -">>), + ok = py_preload:set_code(<< + "\n" + "import json\n" + "import os\n" + >>), %% Create context and check imports are available {ok, Ctx} = py_context:new(#{mode => worker}), @@ -203,24 +205,31 @@ preload_isolation_test(_Config) -> preload_new_context_inherits_test(_Config) -> %% Set preload code - ok = py_preload:set_code(<<" -SHARED_CONFIG = {'debug': True, 'version': '1.0'} - -def get_config_value(key): - return SHARED_CONFIG.get(key) -">>), + ok = py_preload:set_code(<< + "\n" + "SHARED_CONFIG = {'debug': True, 'version': '1.0'}\n" + "\n" + "def get_config_value(key):\n" + " return SHARED_CONFIG.get(key)\n" + >>), %% Create multiple contexts - all should have preload - Ctxs = [begin - {ok, C} = py_context:new(#{mode => worker}), - C - end || _ <- lists:seq(1, 3)], + Ctxs = [ + begin + {ok, C} = py_context:new(#{mode => worker}), + C + end + || _ <- lists:seq(1, 3) + ], try - lists:foreach(fun(Ctx) -> - {ok, true} = py:eval(Ctx, <<"get_config_value('debug')">>), - {ok, <<"1.0">>} = py:eval(Ctx, <<"get_config_value('version')">>) - end, Ctxs) + lists:foreach( + fun(Ctx) -> + {ok, true} = py:eval(Ctx, <<"get_config_value('debug')">>), + {ok, <<"1.0">>} = py:eval(Ctx, <<"get_config_value('version')">>) + end, + Ctxs + ) after lists:foreach(fun(Ctx) -> py_context:stop(Ctx) end, Ctxs) end. diff --git a/test/py_reactor_SUITE.erl b/test/py_reactor_SUITE.erl index d48003b..48daf66 100644 --- a/test/py_reactor_SUITE.erl +++ b/test/py_reactor_SUITE.erl @@ -27,17 +27,18 @@ reactor_context_worker_isolation_test/1 ]). -all() -> [ - reactor_module_exists_test, - protocol_class_exists_test, - set_protocol_factory_test, - echo_protocol_test, - multiple_connections_test, - protocol_close_test, - async_pending_test, - reactor_buffer_test, - reactor_context_worker_isolation_test -]. +all() -> + [ + reactor_module_exists_test, + protocol_class_exists_test, + set_protocol_factory_test, + echo_protocol_test, + multiple_connections_test, + protocol_close_test, + async_pending_test, + reactor_buffer_test, + reactor_context_worker_isolation_test + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -70,146 +71,150 @@ protocol_class_exists_test(_Config) -> %% @doc Test set_protocol_factory works set_protocol_factory_test(_Config) -> %% Define a simple protocol - ok = py:exec(<<" -import erlang.reactor as reactor - -class TestProtocol(reactor.Protocol): - def data_received(self, data): - return 'continue' - def write_ready(self): - return 'close' - -reactor.set_protocol_factory(TestProtocol) -">>), + ok = py:exec(<< + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class TestProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " return 'continue'\n" + " def write_ready(self):\n" + " return 'close'\n" + "\n" + "reactor.set_protocol_factory(TestProtocol)\n" + >>), ok. %% @doc Test echo protocol with socketpair echo_protocol_test(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import socket -import erlang.reactor as reactor - -class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'read_pending' - -def run_echo_test(): - s1, s2 = socket.socketpair() - s1.setblocking(False) - s2.setblocking(False) - - reactor.set_protocol_factory(EchoProtocol) - reactor.init_connection(s1.fileno(), {'type': 'test'}) - - s2.send(b'hello') - - action = reactor.on_read_ready(s1.fileno()) - proto = reactor.get_protocol(s1.fileno()) - result = bytes(proto.write_buffer) - - reactor.close_connection(s1.fileno()) - s1.close() - s2.close() - - return result - -_echo_test_result = run_echo_test() -">>), + ok = py:exec(Ctx, << + "\n" + "import socket\n" + "import erlang.reactor as reactor\n" + "\n" + "class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'read_pending'\n" + "\n" + "def run_echo_test():\n" + " s1, s2 = socket.socketpair()\n" + " s1.setblocking(False)\n" + " s2.setblocking(False)\n" + "\n" + " reactor.set_protocol_factory(EchoProtocol)\n" + " reactor.init_connection(s1.fileno(), {'type': 'test'})\n" + "\n" + " s2.send(b'hello')\n" + "\n" + " action = reactor.on_read_ready(s1.fileno())\n" + " proto = reactor.get_protocol(s1.fileno())\n" + " result = bytes(proto.write_buffer)\n" + "\n" + " reactor.close_connection(s1.fileno())\n" + " s1.close()\n" + " s2.close()\n" + "\n" + " return result\n" + "\n" + "_echo_test_result = run_echo_test()\n" + >>), {ok, <<"hello">>} = py:eval(Ctx, <<"_echo_test_result">>). %% @doc Test multiple connections multiple_connections_test(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import socket -import erlang.reactor as reactor - -class CounterProtocol(reactor.Protocol): - counter = 0 - - def connection_made(self, fd, client_info): - super().connection_made(fd, client_info) - CounterProtocol.counter += 1 - self.my_id = CounterProtocol.counter - - def data_received(self, data): - return 'close' - - def write_ready(self): - return 'close' - -def run_multi_conn_test(): - CounterProtocol.counter = 0 - reactor.set_protocol_factory(CounterProtocol) - - pairs = [socket.socketpair() for _ in range(3)] - for s1, s2 in pairs: - s1.setblocking(False) - reactor.init_connection(s1.fileno(), {}) - - ids = [reactor.get_protocol(s1.fileno()).my_id for s1, s2 in pairs] - - for s1, s2 in pairs: - reactor.close_connection(s1.fileno()) - s1.close() - s2.close() - - return ids - -_multi_conn_result = run_multi_conn_test() -">>), + ok = py:exec(Ctx, << + "\n" + "import socket\n" + "import erlang.reactor as reactor\n" + "\n" + "class CounterProtocol(reactor.Protocol):\n" + " counter = 0\n" + "\n" + " def connection_made(self, fd, client_info):\n" + " super().connection_made(fd, client_info)\n" + " CounterProtocol.counter += 1\n" + " self.my_id = CounterProtocol.counter\n" + "\n" + " def data_received(self, data):\n" + " return 'close'\n" + "\n" + " def write_ready(self):\n" + " return 'close'\n" + "\n" + "def run_multi_conn_test():\n" + " CounterProtocol.counter = 0\n" + " reactor.set_protocol_factory(CounterProtocol)\n" + "\n" + " pairs = [socket.socketpair() for _ in range(3)]\n" + " for s1, s2 in pairs:\n" + " s1.setblocking(False)\n" + " reactor.init_connection(s1.fileno(), {})\n" + "\n" + " ids = [reactor.get_protocol(s1.fileno()).my_id for s1, s2 in pairs]\n" + "\n" + " for s1, s2 in pairs:\n" + " reactor.close_connection(s1.fileno())\n" + " s1.close()\n" + " s2.close()\n" + "\n" + " return ids\n" + "\n" + "_multi_conn_result = run_multi_conn_test()\n" + >>), {ok, [1, 2, 3]} = py:eval(Ctx, <<"_multi_conn_result">>). %% @doc Test protocol close callback protocol_close_test(_Config) -> Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import socket -import erlang.reactor as reactor - -_closed_fds = [] - -class CloseTrackProtocol(reactor.Protocol): - def data_received(self, data): - return 'close' - - def write_ready(self): - return 'close' - - def connection_lost(self): - _closed_fds.append(self.fd) - -def run_close_test(): - global _closed_fds - _closed_fds = [] - - reactor.set_protocol_factory(CloseTrackProtocol) - - s1, s2 = socket.socketpair() - s1.setblocking(False) - fd = s1.fileno() - - reactor.init_connection(fd, {}) - reactor.close_connection(fd) - - result = fd in _closed_fds - - s1.close() - s2.close() - - return result - -_close_test_result = run_close_test() -">>), + ok = py:exec(Ctx, << + "\n" + "import socket\n" + "import erlang.reactor as reactor\n" + "\n" + "_closed_fds = []\n" + "\n" + "class CloseTrackProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " return 'close'\n" + "\n" + " def write_ready(self):\n" + " return 'close'\n" + "\n" + " def connection_lost(self):\n" + " _closed_fds.append(self.fd)\n" + "\n" + "def run_close_test():\n" + " global _closed_fds\n" + " _closed_fds = []\n" + "\n" + " reactor.set_protocol_factory(CloseTrackProtocol)\n" + "\n" + " s1, s2 = socket.socketpair()\n" + " s1.setblocking(False)\n" + " fd = s1.fileno()\n" + "\n" + " reactor.init_connection(fd, {})\n" + " reactor.close_connection(fd)\n" + "\n" + " result = fd in _closed_fds\n" + "\n" + " s1.close()\n" + " s2.close()\n" + "\n" + " return result\n" + "\n" + "_close_test_result = run_close_test()\n" + >>), {ok, true} = py:eval(Ctx, <<"_close_test_result">>). %% @doc Test async_pending action for task-based async operations. @@ -219,32 +224,33 @@ _close_test_result = run_close_test() %% 3. Reactor then triggers write selection async_pending_test(_Config) -> %% Protocol factory code to run in reactor context - SetupCode = <<" -import erlang.reactor as reactor - -class AsyncPendingProtocol(reactor.Protocol): - '''Protocol that returns async_pending and signals completion.''' - - def __init__(self): - super().__init__() - self.pending_response = b'' - - def data_received(self, data): - self.pending_response = b'ASYNC:' + data - # Immediately complete the task and signal reactor - self.write_buffer.extend(self.pending_response) - reactor.signal_write_ready(self.fd) - return 'async_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(AsyncPendingProtocol) -">>, + SetupCode = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class AsyncPendingProtocol(reactor.Protocol):\n" + " '''Protocol that returns async_pending and signals completion.'''\n" + "\n" + " def __init__(self):\n" + " super().__init__()\n" + " self.pending_response = b''\n" + "\n" + " def data_received(self, data):\n" + " self.pending_response = b'ASYNC:' + data\n" + " # Immediately complete the task and signal reactor\n" + " self.write_buffer.extend(self.pending_response)\n" + " reactor.signal_write_ready(self.fd)\n" + " return 'async_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(AsyncPendingProtocol)\n" + >>, %% Start reactor context with protocol factory setup {ok, ReactorCtx} = py_reactor_context:start_link(1, worker, #{ @@ -253,47 +259,48 @@ reactor.set_protocol_factory(AsyncPendingProtocol) %% Use py:context(1) for test helpers (socket management) PyCtx = py:context(1), - ok = py:exec(PyCtx, <<" -import socket - -_async_test_state = {} - -def setup_socketpair(): - global _async_test_state - s1, s2 = socket.socketpair() - s1.setblocking(False) - s2.setblocking(False) - _async_test_state = {'s1': s1, 's2': s2, 'fd': s1.fileno()} - return s1.fileno() - -def send_test_data(): - s2 = _async_test_state['s2'] - s2.send(b'hello') - return True - -def read_response(): - s2 = _async_test_state['s2'] - s2.setblocking(True) - s2.settimeout(2.0) - try: - return s2.recv(1024) - except socket.timeout: - return b'TIMEOUT' - -def cleanup(): - s1 = _async_test_state.get('s1') - s2 = _async_test_state.get('s2') - try: - if s1: s1.close() - except: - pass - try: - if s2: s2.close() - except: - pass - _async_test_state.clear() - return True -">>), + ok = py:exec(PyCtx, << + "\n" + "import socket\n" + "\n" + "_async_test_state = {}\n" + "\n" + "def setup_socketpair():\n" + " global _async_test_state\n" + " s1, s2 = socket.socketpair()\n" + " s1.setblocking(False)\n" + " s2.setblocking(False)\n" + " _async_test_state = {'s1': s1, 's2': s2, 'fd': s1.fileno()}\n" + " return s1.fileno()\n" + "\n" + "def send_test_data():\n" + " s2 = _async_test_state['s2']\n" + " s2.send(b'hello')\n" + " return True\n" + "\n" + "def read_response():\n" + " s2 = _async_test_state['s2']\n" + " s2.setblocking(True)\n" + " s2.settimeout(2.0)\n" + " try:\n" + " return s2.recv(1024)\n" + " except socket.timeout:\n" + " return b'TIMEOUT'\n" + "\n" + "def cleanup():\n" + " s1 = _async_test_state.get('s1')\n" + " s2 = _async_test_state.get('s2')\n" + " try:\n" + " if s1: s1.close()\n" + " except:\n" + " pass\n" + " try:\n" + " if s2: s2.close()\n" + " except:\n" + " pass\n" + " _async_test_state.clear()\n" + " return True\n" + >>), %% Step 1: Create socketpair {ok, Fd} = py:eval(PyCtx, <<"setup_socketpair()">>), @@ -333,61 +340,62 @@ reactor_buffer_test(_Config) -> %% Test bytes-like operations - use exec for all assertions Ctx = py:context(1), - ok = py:exec(Ctx, <<" -import erlang - -# Test _test_create works -buf_simple = erlang.ReactorBuffer._test_create(b'hello') -assert len(buf_simple) == 5, f'simple len mismatch: {len(buf_simple)}' - -test_data = b'GET / HTTP/1.1' + bytes([13, 10]) # Use bytes for \\r\\n -buf = erlang.ReactorBuffer._test_create(test_data) - -# Test len() -assert len(buf) == 16, f'len mismatch: {len(buf)}' # 14 chars + 2 for \\r\\n - -# Test startswith() -assert buf.startswith(b'GET'), 'startswith failed' -assert not buf.startswith(b'POST'), 'startswith should fail for POST' - -# Test endswith() -assert buf.endswith(bytes([13, 10])), 'endswith failed' - -# Test indexing -assert buf[0] == ord('G'), f'index 0 mismatch: {buf[0]}' -assert buf[-1] == 10, f'index -1 mismatch' - -# Test slicing -assert buf[0:3] == b'GET', f'slice mismatch: {buf[0:3]}' - -# Test bytes() conversion -assert bytes(buf) == test_data, 'bytes conversion failed' - -# Test memoryview -mv = memoryview(buf) -assert bytes(mv) == test_data, 'memoryview failed' - -# Test find() -assert buf.find(b'HTTP') == 6, f'find mismatch: {buf.find(b\"HTTP\")}' -assert buf.find(b'HTTPS') == -1, 'find should return -1' - -# Test count() -assert buf.count(b'/') == 2, f'count mismatch: {buf.count(b\"/\")}' # '/' in path and '1.1' - -# Test 'in' operator -assert b'HTTP' in buf, 'in operator failed' -assert b'HTTPS' not in buf, 'not in operator failed' - -# Test decode() -decoded = buf.decode('utf-8') -assert decoded == 'GET / HTTP/1.1' + chr(13) + chr(10), f'decode mismatch: {decoded}' - -# Test comparison -assert buf == test_data, 'equality comparison failed' -assert buf != b'other', 'inequality comparison failed' - -_reactor_buffer_test_passed = True -">>), + ok = py:exec(Ctx, << + "\n" + "import erlang\n" + "\n" + "# Test _test_create works\n" + "buf_simple = erlang.ReactorBuffer._test_create(b'hello')\n" + "assert len(buf_simple) == 5, f'simple len mismatch: {len(buf_simple)}'\n" + "\n" + "test_data = b'GET / HTTP/1.1' + bytes([13, 10]) # Use bytes for \\r\\n\n" + "buf = erlang.ReactorBuffer._test_create(test_data)\n" + "\n" + "# Test len()\n" + "assert len(buf) == 16, f'len mismatch: {len(buf)}' # 14 chars + 2 for \\r\\n\n" + "\n" + "# Test startswith()\n" + "assert buf.startswith(b'GET'), 'startswith failed'\n" + "assert not buf.startswith(b'POST'), 'startswith should fail for POST'\n" + "\n" + "# Test endswith()\n" + "assert buf.endswith(bytes([13, 10])), 'endswith failed'\n" + "\n" + "# Test indexing\n" + "assert buf[0] == ord('G'), f'index 0 mismatch: {buf[0]}'\n" + "assert buf[-1] == 10, f'index -1 mismatch'\n" + "\n" + "# Test slicing\n" + "assert buf[0:3] == b'GET', f'slice mismatch: {buf[0:3]}'\n" + "\n" + "# Test bytes() conversion\n" + "assert bytes(buf) == test_data, 'bytes conversion failed'\n" + "\n" + "# Test memoryview\n" + "mv = memoryview(buf)\n" + "assert bytes(mv) == test_data, 'memoryview failed'\n" + "\n" + "# Test find()\n" + "assert buf.find(b'HTTP') == 6, f'find mismatch: {buf.find(b\"HTTP\")}'\n" + "assert buf.find(b'HTTPS') == -1, 'find should return -1'\n" + "\n" + "# Test count()\n" + "assert buf.count(b'/') == 2, f'count mismatch: {buf.count(b\"/\")}' # '/' in path and '1.1'\n" + "\n" + "# Test 'in' operator\n" + "assert b'HTTP' in buf, 'in operator failed'\n" + "assert b'HTTPS' not in buf, 'not in operator failed'\n" + "\n" + "# Test decode()\n" + "decoded = buf.decode('utf-8')\n" + "assert decoded == 'GET / HTTP/1.1' + chr(13) + chr(10), f'decode mismatch: {decoded}'\n" + "\n" + "# Test comparison\n" + "assert buf == test_data, 'equality comparison failed'\n" + "assert buf != b'other', 'inequality comparison failed'\n" + "\n" + "_reactor_buffer_test_passed = True\n" + >>), {ok, true} = py:eval(Ctx, <<"_reactor_buffer_test_passed">>). %%% ============================================================================ @@ -412,46 +420,48 @@ _reactor_buffer_test_passed = True %% don't properly isolate module globals (e.g., some FreeBSD configurations). reactor_context_worker_isolation_test(_Config) -> %% Context 1 with EchoProtocol - echoes data unchanged - EchoSetup = <<" -import erlang.reactor as reactor - -class EchoProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(data) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(EchoProtocol) -">>, + EchoSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class EchoProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(data)\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(EchoProtocol)\n" + >>, {ok, Ctx1} = py_reactor_context:start_link(101, worker, #{ setup_code => EchoSetup }), %% Context 2 with UpperProtocol - echoes data uppercased - UpperSetup = <<" -import erlang.reactor as reactor - -class UpperProtocol(reactor.Protocol): - def data_received(self, data): - self.write_buffer.extend(bytes(data).upper()) - return 'write_pending' - - def write_ready(self): - if not self.write_buffer: - return 'close' - written = self.write(bytes(self.write_buffer)) - del self.write_buffer[:written] - return 'continue' if self.write_buffer else 'close' - -reactor.set_protocol_factory(UpperProtocol) -">>, + UpperSetup = << + "\n" + "import erlang.reactor as reactor\n" + "\n" + "class UpperProtocol(reactor.Protocol):\n" + " def data_received(self, data):\n" + " self.write_buffer.extend(bytes(data).upper())\n" + " return 'write_pending'\n" + "\n" + " def write_ready(self):\n" + " if not self.write_buffer:\n" + " return 'close'\n" + " written = self.write(bytes(self.write_buffer))\n" + " del self.write_buffer[:written]\n" + " return 'continue' if self.write_buffer else 'close'\n" + "\n" + "reactor.set_protocol_factory(UpperProtocol)\n" + >>, {ok, Ctx2} = py_reactor_context:start_link(102, worker, #{ setup_code => UpperSetup diff --git a/test/py_reentrant_SUITE.erl b/test/py_reentrant_SUITE.erl index 599faf1..c91d38f 100644 --- a/test/py_reentrant_SUITE.erl +++ b/test/py_reentrant_SUITE.erl @@ -73,21 +73,81 @@ init_per_testcase(_TestCase, Config) -> end_per_testcase(_TestCase, _Config) -> %% Cleanup any registered functions - try py:unregister_function(double_via_python) catch _:_ -> ok end, - try py:unregister_function(triple) catch _:_ -> ok end, - try py:unregister_function(call_level) catch _:_ -> ok end, - try py:unregister_function(may_fail) catch _:_ -> ok end, - try py:unregister_function(transform) catch _:_ -> ok end, - try py:unregister_function(add_ten) catch _:_ -> ok end, - try py:unregister_function(multiply_by_two) catch _:_ -> ok end, - try py:unregister_function(subtract_five) catch _:_ -> ok end, - try py:unregister_function(async_multiply) catch _:_ -> ok end, - try py:unregister_function(test_registry_func) catch _:_ -> ok end, - try py:unregister_function(etf_probe_ok) catch _:_ -> ok end, - try py:unregister_function(etf_probe_novel) catch _:_ -> ok end, - try py:unregister_function(rs_double) catch _:_ -> ok end, - try py:unregister_function(nest_step) catch _:_ -> ok end, - try py:unregister_function(owngil_nest) catch _:_ -> ok end, + try + py:unregister_function(double_via_python) + catch + _:_ -> ok + end, + try + py:unregister_function(triple) + catch + _:_ -> ok + end, + try + py:unregister_function(call_level) + catch + _:_ -> ok + end, + try + py:unregister_function(may_fail) + catch + _:_ -> ok + end, + try + py:unregister_function(transform) + catch + _:_ -> ok + end, + try + py:unregister_function(add_ten) + catch + _:_ -> ok + end, + try + py:unregister_function(multiply_by_two) + catch + _:_ -> ok + end, + try + py:unregister_function(subtract_five) + catch + _:_ -> ok + end, + try + py:unregister_function(async_multiply) + catch + _:_ -> ok + end, + try + py:unregister_function(test_registry_func) + catch + _:_ -> ok + end, + try + py:unregister_function(etf_probe_ok) + catch + _:_ -> ok + end, + try + py:unregister_function(etf_probe_novel) + catch + _:_ -> ok + end, + try + py:unregister_function(rs_double) + catch + _:_ -> ok + end, + try + py:unregister_function(nest_step) + catch + _:_ -> ok + end, + try + py:unregister_function(owngil_nest) + catch + _:_ -> ok + end, ok. %%% ============================================================================ @@ -101,8 +161,13 @@ end_per_testcase(_TestCase, _Config) -> reentrant_test_dir() -> TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))). + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ). register_nest_step() -> py:register_function(nest_step, fun([N, D]) -> @@ -114,9 +179,12 @@ register_nest_step() -> test_call_reentrant_depths(_Config) -> reentrant_test_dir(), register_nest_step(), - lists:foreach(fun(Depth) -> - {ok, Depth} = py:call(py_test_reentrant, down, [0, Depth], #{}, 10000) - end, [1, 2, 3, 5]), + lists:foreach( + fun(Depth) -> + {ok, Depth} = py:call(py_test_reentrant, down, [0, Depth], #{}, 10000) + end, + [1, 2, 3, 5] + ), py:unregister_function(nest_step), ok. @@ -124,13 +192,14 @@ test_call_reentrant_depths(_Config) -> %%% callback calling back into the same owngil context queued behind the %%% request waiting for it and the chain hung until the timeout. --define(OWNGIL_DOWN, <<" -import erlang -def odown(ctx, n, d): - if d == 0: - return n - return erlang.call('owngil_nest', ctx, n, d) -">>). +-define(OWNGIL_DOWN, << + "\n" + "import erlang\n" + "def odown(ctx, n, d):\n" + " if d == 0:\n" + " return n\n" + " return erlang.call('owngil_nest', ctx, n, d)\n" +>>). owngil_ctx() -> {ok, C} = py_context:new(#{mode => owngil}), @@ -152,10 +221,14 @@ test_owngil_call_reentrant_depths(_Config) -> true -> register_owngil_nest(), C = owngil_ctx(), - [{ok, D} = py_context:call(C, '__main__', odown, [C, 0, D], #{}, 10000) - || D <- [1, 2, 3, 5]], - [{ok, 2} = py_context:call(C, '__main__', odown, [C, 0, 2], #{}, 10000) - || _ <- lists:seq(1, 20)], + [ + {ok, D} = py_context:call(C, '__main__', odown, [C, 0, D], #{}, 10000) + || D <- [1, 2, 3, 5] + ], + [ + {ok, 2} = py_context:call(C, '__main__', odown, [C, 0, 2], #{}, 10000) + || _ <- lists:seq(1, 20) + ], py_context:stop(C) end. @@ -168,13 +241,24 @@ test_owngil_concurrent_reentrant(_Config) -> register_owngil_nest(), Ctxs = [owngil_ctx() || _ <- lists:seq(1, 4)], Self = self(), - Pids = [spawn_link(fun() -> - C = lists:nth(I rem 4 + 1, Ctxs), - Self ! {done, [py_context:call(C, '__main__', odown, [C, 0, 3], #{}, 10000) - || _ <- lists:seq(1, 25)]} - end) || I <- lists:seq(1, 8)], - [receive {done, R} -> R = lists:duplicate(25, {ok, 3}) after 60000 -> ct:fail(timeout) end - || _ <- Pids], + Pids = [ + spawn_link(fun() -> + C = lists:nth(I rem 4 + 1, Ctxs), + Self ! + {done, [ + py_context:call(C, '__main__', odown, [C, 0, 3], #{}, 10000) + || _ <- lists:seq(1, 25) + ]} + end) + || I <- lists:seq(1, 8) + ], + [ + receive + {done, R} -> R = lists:duplicate(25, {ok, 3}) + after 60000 -> ct:fail(timeout) + end + || _ <- Pids + ], [py_context:stop(C) || C <- Ctxs], ok end. @@ -184,9 +268,12 @@ test_owngil_concurrent_reentrant(_Config) -> test_call_reentrant_repeated(_Config) -> reentrant_test_dir(), register_nest_step(), - lists:foreach(fun(I) -> - {ok, I} = py:call(py_test_reentrant, down, [I - 1, 1], #{}, 10000) - end, lists:seq(1, 20)), + lists:foreach( + fun(I) -> + {ok, I} = py:call(py_test_reentrant, down, [I - 1, 1], #{}, 10000) + end, + lists:seq(1, 20) + ), py:unregister_function(nest_step), ok. @@ -202,11 +289,14 @@ test_call_sequential_callbacks(_Config) -> {ok, R} = py:call(py_test_reentrant, minus, [X, 5], #{}, 10000), R end), - lists:foreach(fun(I) -> - %% ((I + 10) * 2) - 5 - Expected = ((I + 10) * 2) - 5, - {ok, Expected} = py:call(py_test_reentrant, chain, [I], #{}, 10000) - end, lists:seq(1, 5)), + lists:foreach( + fun(I) -> + %% ((I + 10) * 2) - 5 + Expected = ((I + 10) * 2) - 5, + {ok, Expected} = py:call(py_test_reentrant, chain, [I], #{}, 10000) + end, + lists:seq(1, 5) + ), ok. %% @doc The README "Reentrant Callbacks" example, as written there: the @@ -220,16 +310,17 @@ test_readme_reentrant_example(_Config) -> end), %% Define Python functions - ok = py:exec(<<" -def double(x): - return x * 2 - -def process(x): - from erlang import call - # This calls Erlang, which calls Python's double() - doubled = call('double_via_python', x) - return doubled + 1 -">>), + ok = py:exec(<< + "\n" + "def double(x):\n" + " return x * 2\n" + "\n" + "def process(x):\n" + " from erlang import call\n" + " # This calls Erlang, which calls Python's double()\n" + " doubled = call('double_via_python', x)\n" + " return doubled + 1\n" + >>), %% Test the full round-trip {ok, 21} = py:call('__main__', process, [10]), @@ -254,7 +345,8 @@ test_basic_reentrant(_Config) -> %% Test using py:eval: Python calls Erlang which calls Python %% The expression: call Erlang's double_via_python(10), then add 1 {ok, Result} = py:eval(<<"__import__('erlang').call('double_via_python', 10) + 1">>), - 21 = Result, %% 10 * 2 + 1 = 21 + %% 10 * 2 + 1 = 21 + 21 = Result, ok. @@ -267,12 +359,16 @@ test_reentrant_resume_stress(_Config) -> {ok, R} = py:eval(iolist_to_binary(io_lib:format("~p * 2", [X]))), R end), - Got = [begin - Code = iolist_to_binary( - io_lib:format("__import__('erlang').call('rs_double', ~p) + 1", [N])), - {ok, V} = py:eval(Code), - V - end || N <- lists:seq(1, 100)], + Got = [ + begin + Code = iolist_to_binary( + io_lib:format("__import__('erlang').call('rs_double', ~p) + 1", [N]) + ), + {ok, V} = py:eval(Code), + V + end + || N <- lists:seq(1, 100) + ], Got = [N * 2 + 1 || N <- lists:seq(1, 100)], py:unregister_function(rs_double), ok. @@ -309,7 +405,8 @@ test_etf_decode_safe(_Config) -> Marker = etf_marker(novel_atom_etf(Name)), py:register_function(etf_probe_novel, fun(_) -> Marker end), {ok, Got} = py:eval(<<"__import__('erlang').call('etf_probe_novel', [])">>), - Marker = Got, %% passed through as data, never decoded to the atom + %% passed through as data, never decoded to the atom + Marker = Got, assert_atom_absent(Name) end, lists:seq(1, N) @@ -335,7 +432,9 @@ novel_atom_etf(Name) -> assert_atom_absent(Name) -> try list_to_existing_atom(Name) of _ -> error({atom_created, Name}) - catch error:badarg -> ok end. + catch + error:badarg -> ok + end. %% @doc Test deeply nested callbacks (3+ levels). %% Tests Erlang→Python→Erlang→Python... nesting @@ -345,12 +444,16 @@ test_nested_callbacks(_Config) -> py:register_function(call_level, fun([Level, N]) -> case Level >= N of true -> - Level; % Base case + % Base case + Level; false -> %% Call back into Python which will call us again - Code = iolist_to_binary(io_lib:format( - "__import__('erlang').call('call_level', ~p, ~p)", - [Level + 1, N])), + Code = iolist_to_binary( + io_lib:format( + "__import__('erlang').call('call_level', ~p, ~p)", + [Level + 1, N] + ) + ), {ok, Result} = py:eval(Code), Result end @@ -399,29 +502,41 @@ test_concurrent_reentrant(_Config) -> %% Spawn multiple processes that do reentrant calls %% Each uses py:eval with inline function definition to ensure it works %% regardless of which worker handles the request - _Pids = [spawn_link(fun() -> - Input = N * 10, - %% Use eval to call the erlang function directly - {ok, Result} = py:eval(iolist_to_binary( - io_lib:format("__import__('erlang').call('triple', ~p)", [Input]))), - Expected = Input * 3, - Self ! {done, N, Result, Expected} - end) || N <- lists:seq(1, NumProcesses)], + _Pids = [ + spawn_link(fun() -> + Input = N * 10, + %% Use eval to call the erlang function directly + {ok, Result} = py:eval( + iolist_to_binary( + io_lib:format("__import__('erlang').call('triple', ~p)", [Input]) + ) + ), + Expected = Input * 3, + Self ! {done, N, Result, Expected} + end) + || N <- lists:seq(1, NumProcesses) + ], %% Wait for all processes to complete - Results = [receive - {done, N, Result, Expected} -> {N, Result, Expected} - after 10000 -> - ct:fail({timeout, N}) - end || N <- lists:seq(1, NumProcesses)], + Results = [ + receive + {done, N, Result, Expected} -> {N, Result, Expected} + after 10000 -> + ct:fail({timeout, N}) + end + || N <- lists:seq(1, NumProcesses) + ], %% Verify all results - lists:foreach(fun({N, Result, Expected}) -> - case Result of - Expected -> ok; - _ -> ct:fail({mismatch, N, expected, Expected, got, Result}) - end - end, Results), + lists:foreach( + fun({N, Result, Expected}) -> + case Result of + Expected -> ok; + _ -> ct:fail({mismatch, N, expected, Expected, got, Result}) + end + end, + Results + ), %% Verify all processes completed NumProcesses = length(Results), @@ -446,7 +561,9 @@ test_callback_with_complex_types(_Config) -> end), %% Test using py:eval with inline dict - {ok, Result} = py:eval(<<"__import__('erlang').call('transform', {'items': [1, 2, 3], 'count': 5})">>), + {ok, Result} = py:eval( + <<"__import__('erlang').call('transform', {'items': [1, 2, 3], 'count': 5})">> + ), %% Verify result (map with reversed items and doubled count) #{ @@ -474,17 +591,20 @@ test_multiple_sequential_callbacks(_Config) -> %% This is a single expression that makes 3 sequential callbacks. %% Test with x=5: ((5 + 10) * 2) - 5 = 25 - Code1 = <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 5))))(__import__('erlang'))">>, + Code1 = + <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 5))))(__import__('erlang'))">>, {ok, Result1} = py:eval(Code1), 25 = Result1, %% Test with x=10: ((10 + 10) * 2) - 5 = 35 - Code2 = <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 10))))(__import__('erlang'))">>, + Code2 = + <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 10))))(__import__('erlang'))">>, {ok, Result2} = py:eval(Code2), 35 = Result2, %% Test with x=0: ((0 + 10) * 2) - 5 = 15 - Code3 = <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 0))))(__import__('erlang'))">>, + Code3 = + <<"(lambda erl: erl.call('subtract_five', erl.call('multiply_by_two', erl.call('add_ten', 0))))(__import__('erlang'))">>, {ok, Result3} = py:eval(Code3), 15 = Result3, @@ -499,7 +619,8 @@ test_call_from_non_worker_thread(_Config) -> %% Use an inline lambda to test calling from a thread %% With ThreadPoolExecutor support, this should now succeed - Code = <<"(lambda cf, erlang: (lambda executor: (lambda future: ('success', future.result()) if not future.exception() else ('error', str(future.exception())))(executor.submit(lambda: erlang.call('simple_add', 1, 2))))(cf.ThreadPoolExecutor(max_workers=1).__enter__()))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erlang: (lambda executor: (lambda future: ('success', future.result()) if not future.exception() else ('error', str(future.exception())))(executor.submit(lambda: erlang.call('simple_add', 1, 2))))(cf.ThreadPoolExecutor(max_workers=1).__enter__()))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Result} = py:eval(Code), %% With ThreadPoolExecutor support, the call should succeed @@ -523,8 +644,13 @@ test_call_from_non_worker_thread(_Config) -> test_thread_callback_fd_above_fd_setsize(_Config) -> py:register_function(high_fd_add, fun([A, B]) -> A + B end), TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), try case py:call(py_test_high_fds, prepare, [1200]) of {ok, Last} when Last >= 1200 -> @@ -563,8 +689,13 @@ test_callback_with_try_except(_Config) -> %% Add test directory to Python path so we can import the test module TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test 1: Try/except that catches Exception and re-raises {ok, Result1} = py:call(py_test_middleware, call_with_try_except, [<<"a">>]), @@ -599,8 +730,13 @@ test_async_call(_Config) -> %% Add test directory to Python path TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Test single async_call {ok, Result} = py:call(py_test_async, run_single_test, []), diff --git a/test/py_ref_SUITE.erl b/test/py_ref_SUITE.erl index 853b8e6..45c8bf4 100644 --- a/test/py_ref_SUITE.erl +++ b/test/py_ref_SUITE.erl @@ -46,12 +46,20 @@ end_per_suite(_Config) -> init_per_testcase(_TestCase, Config) -> %% Start contexts for testing - try py:stop_contexts() catch _:_ -> ok end, + try + py:stop_contexts() + catch + _:_ -> ok + end, {ok, _} = py:start_contexts(#{contexts => 2}), Config. end_per_testcase(_TestCase, _Config) -> - try py:stop_contexts() catch _:_ -> ok end, + try + py:stop_contexts() + catch + _:_ -> ok + end, ok. %% ============================================================================ @@ -87,13 +95,14 @@ test_getattr(_Config) -> Ctx = py:context(), %% Create an object with attributes - ok = py:exec(Ctx, <<" -class TestObj: - def __init__(self): - self.name = 'test' - self.value = 42 -test_obj = TestObj() -">>), + ok = py:exec(Ctx, << + "\n" + "class TestObj:\n" + " def __init__(self):\n" + " self.name = 'test'\n" + " self.value = 42\n" + "test_obj = TestObj()\n" + >>), %% Get attributes via eval {ok, <<"test">>} = py:eval(Ctx, <<"test_obj.name">>, #{}), @@ -114,10 +123,13 @@ test_ref_gc(_Config) -> Ctx = py:context(), %% Create objects in a loop - lists:foreach(fun(I) -> - Code = iolist_to_binary([<<"x">>, integer_to_binary(I), <<" = [1,2,3] * 100">>]), - ok = py:exec(Ctx, Code) - end, lists:seq(1, 100)), + lists:foreach( + fun(I) -> + Code = iolist_to_binary([<<"x">>, integer_to_binary(I), <<" = [1,2,3] * 100">>]), + ok = py:exec(Ctx, Code) + end, + lists:seq(1, 100) + ), %% Force Erlang GC erlang:garbage_collect(), diff --git a/test/py_scalable_io_bench.erl b/test/py_scalable_io_bench.erl index 4f5285f..7fca91e 100644 --- a/test/py_scalable_io_bench.erl +++ b/test/py_scalable_io_bench.erl @@ -59,10 +59,12 @@ run_all(UserOpts) -> Results. safe_bench(Fun) -> - try Fun() - catch Class:Reason:Stack -> - io:format("ERROR: ~p:~p~n~p~n", [Class, Reason, Stack]), - #{error => {Class, Reason}} + try + Fun() + catch + Class:Reason:Stack -> + io:format("ERROR: ~p:~p~n~p~n", [Class, Reason, Stack]), + #{error => {Class, Reason}} end. timer_throughput_single(Opts) -> @@ -70,19 +72,20 @@ timer_throughput_single(Opts) -> WarmupN = maps:get(warmup_iterations, Opts), io:format("~n--- Timer Throughput (single worker) ---~n"), io:format("Iterations: ~p~n", [N]), - Code = <<" -import asyncio -import time -def run_timer_throughput_single(n): - async def _run(n): - for _ in range(n): - await asyncio.sleep(0) - return n - start = time.perf_counter() - count = asyncio.run(_run(n)) - elapsed = time.perf_counter() - start - return {'count': count, 'elapsed': elapsed} -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "def run_timer_throughput_single(n):\n" + " async def _run(n):\n" + " for _ in range(n):\n" + " await asyncio.sleep(0)\n" + " return n\n" + " start = time.perf_counter()\n" + " count = asyncio.run(_run(n))\n" + " elapsed = time.perf_counter() - start\n" + " return {'count': count, 'elapsed': elapsed}\n" + >>, ok = py:exec(Code), {ok, _} = py:call('__main__', run_timer_throughput_single, [WarmupN]), {_, {ok, Result}} = timer:tc(fun() -> @@ -99,44 +102,45 @@ timer_throughput_concurrent(Opts) -> Workers = maps:get(concurrent_workers, Opts), io:format("~n--- Timer Throughput (concurrent workers: ~p) ---~n", [Workers]), io:format("Iterations per worker: ~p~n", [N]), - Code = <<" -import asyncio -import time -import threading -import sys -sys.path.insert(0, 'priv') -from _erlang_impl import ErlangEventLoop - -def run_timer_throughput_concurrent(n_timers, n_workers): - results = [] - errors = [] - def run_in_thread(worker_id, num_timers): - try: - async def _run(n): - for _ in range(n): - await asyncio.sleep(0) - return n - loop = ErlangEventLoop() - asyncio.set_event_loop(loop) - try: - count = loop.run_until_complete(_run(num_timers)) - results.append(count) - finally: - loop.close() - except Exception as e: - errors.append(str(e)) - start = time.perf_counter() - threads = [] - for i in range(n_workers): - t = threading.Thread(target=run_in_thread, args=(i, n_timers)) - threads.append(t) - t.start() - for t in threads: - t.join() - elapsed = time.perf_counter() - start - total = sum(results) - return {'total': total, 'elapsed': elapsed, 'errors': len(errors), 'workers': n_workers} -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "import threading\n" + "import sys\n" + "sys.path.insert(0, 'priv')\n" + "from _erlang_impl import ErlangEventLoop\n" + "\n" + "def run_timer_throughput_concurrent(n_timers, n_workers):\n" + " results = []\n" + " errors = []\n" + " def run_in_thread(worker_id, num_timers):\n" + " try:\n" + " async def _run(n):\n" + " for _ in range(n):\n" + " await asyncio.sleep(0)\n" + " return n\n" + " loop = ErlangEventLoop()\n" + " asyncio.set_event_loop(loop)\n" + " try:\n" + " count = loop.run_until_complete(_run(num_timers))\n" + " results.append(count)\n" + " finally:\n" + " loop.close()\n" + " except Exception as e:\n" + " errors.append(str(e))\n" + " start = time.perf_counter()\n" + " threads = []\n" + " for i in range(n_workers):\n" + " t = threading.Thread(target=run_in_thread, args=(i, n_timers))\n" + " threads.append(t)\n" + " t.start()\n" + " for t in threads:\n" + " t.join()\n" + " elapsed = time.perf_counter() - start\n" + " total = sum(results)\n" + " return {'total': total, 'elapsed': elapsed, 'errors': len(errors), 'workers': n_workers}\n" + >>, ok = py:exec(Code), {ok, _} = py:call('__main__', run_timer_throughput_concurrent, [100, 2]), {_, {ok, Result}} = timer:tc(fun() -> @@ -145,11 +149,22 @@ def run_timer_throughput_concurrent(n_timers, n_workers): Total = maps:get(<<"total">>, Result), PythonElapsed = maps:get(<<"elapsed">>, Result), Errors = maps:get(<<"errors">>, Result), - TimersPerSec = case Total of 0 -> 0.0; _ -> Total / PythonElapsed end, - io:format("Time: ~.3f sec | Total timers: ~w | Errors: ~p | Timers/sec: ~w~n", - [PythonElapsed, Total, Errors, round(TimersPerSec)]), - #{workers => Workers, total_timers => Total, python_time_sec => PythonElapsed, - errors => Errors, timers_per_sec => TimersPerSec}. + TimersPerSec = + case Total of + 0 -> 0.0; + _ -> Total / PythonElapsed + end, + io:format( + "Time: ~.3f sec | Total timers: ~w | Errors: ~p | Timers/sec: ~w~n", + [PythonElapsed, Total, Errors, round(TimersPerSec)] + ), + #{ + workers => Workers, + total_timers => Total, + python_time_sec => PythonElapsed, + errors => Errors, + timers_per_sec => TimersPerSec + }. timer_latency(Opts) -> N = min(1000, maps:get(timer_iterations, Opts)), @@ -157,29 +172,30 @@ timer_latency(Opts) -> WarmupN = min(50, maps:get(warmup_iterations, Opts)), io:format("~n--- Timer Latency (target: ~pms) ---~n", [DelayMs]), io:format("Iterations: ~p~n", [N]), - Code = <<" -import asyncio -import time -import statistics -def run_timer_latency(n, delay_ms): - async def _run(n, delay_sec): - latencies = [] - for _ in range(n): - start = time.perf_counter() - await asyncio.sleep(delay_sec) - elapsed = time.perf_counter() - start - latencies.append((elapsed - delay_sec) * 1000) - latencies.sort() - return { - 'mean_ms': statistics.mean(latencies), - 'p50_ms': latencies[int(len(latencies) * 0.50)], - 'p95_ms': latencies[int(len(latencies) * 0.95)], - 'p99_ms': latencies[int(len(latencies) * 0.99)] if len(latencies) >= 100 else latencies[-1], - 'min_ms': min(latencies), - 'max_ms': max(latencies), - } - return asyncio.run(_run(n, delay_ms / 1000.0)) -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "import statistics\n" + "def run_timer_latency(n, delay_ms):\n" + " async def _run(n, delay_sec):\n" + " latencies = []\n" + " for _ in range(n):\n" + " start = time.perf_counter()\n" + " await asyncio.sleep(delay_sec)\n" + " elapsed = time.perf_counter() - start\n" + " latencies.append((elapsed - delay_sec) * 1000)\n" + " latencies.sort()\n" + " return {\n" + " 'mean_ms': statistics.mean(latencies),\n" + " 'p50_ms': latencies[int(len(latencies) * 0.50)],\n" + " 'p95_ms': latencies[int(len(latencies) * 0.95)],\n" + " 'p99_ms': latencies[int(len(latencies) * 0.99)] if len(latencies) >= 100 else latencies[-1],\n" + " 'min_ms': min(latencies),\n" + " 'max_ms': max(latencies),\n" + " }\n" + " return asyncio.run(_run(n, delay_ms / 1000.0))\n" + >>, ok = py:exec(Code), {ok, _} = py:call('__main__', run_timer_latency, [WarmupN, DelayMs]), {_, {ok, Stats}} = timer:tc(fun() -> @@ -187,9 +203,16 @@ def run_timer_latency(n, delay_ms): end), P95Ms = maps:get(<<"p95_ms">>, Stats), P99Ms = maps:get(<<"p99_ms">>, Stats), - io:format("Latency overhead (ms): mean=~.3f | p50=~.3f | p95=~.3f | p99=~.3f~n", - [maps:get(<<"mean_ms">>, Stats), maps:get(<<"p50_ms">>, Stats), P95Ms, P99Ms]), - #{iterations => N, target_delay_ms => DelayMs, p95_latency_ms => P95Ms, p99_latency_ms => P99Ms}. + io:format( + "Latency overhead (ms): mean=~.3f | p50=~.3f | p95=~.3f | p99=~.3f~n", + [maps:get(<<"mean_ms">>, Stats), maps:get(<<"p50_ms">>, Stats), P95Ms, P99Ms] + ), + #{ + iterations => N, + target_delay_ms => DelayMs, + p95_latency_ms => P95Ms, + p99_latency_ms => P99Ms + }. tcp_echo_single(Opts) -> N = maps:get(tcp_messages, Opts), @@ -198,41 +221,42 @@ tcp_echo_single(Opts) -> Timeout = maps:get(call_timeout, Opts), io:format("~n--- TCP Echo (single connection) ---~n"), io:format("Messages: ~p x ~p bytes~n", [N, MsgSize]), - Code = <<" -import asyncio -import time -def run_tcp_echo_single(n_messages, msg_size): - async def _run(n_messages, msg_size): - async def handle_client(reader, writer): - try: - while True: - data = await reader.read(msg_size) - if not data: - break - writer.write(data) - await writer.drain() - finally: - writer.close() - try: await writer.wait_closed() - except: pass - server = await asyncio.start_server(handle_client, '127.0.0.1', 0) - port = server.sockets[0].getsockname()[1] - reader, writer = await asyncio.open_connection('127.0.0.1', port) - msg = b'x' * msg_size - start = time.perf_counter() - for _ in range(n_messages): - writer.write(msg) - await writer.drain() - await reader.readexactly(msg_size) - elapsed = time.perf_counter() - start - writer.close() - try: await writer.wait_closed() - except: pass - server.close() - await server.wait_closed() - return {'count': n_messages, 'elapsed': elapsed} - return asyncio.run(_run(n_messages, msg_size)) -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "def run_tcp_echo_single(n_messages, msg_size):\n" + " async def _run(n_messages, msg_size):\n" + " async def handle_client(reader, writer):\n" + " try:\n" + " while True:\n" + " data = await reader.read(msg_size)\n" + " if not data:\n" + " break\n" + " writer.write(data)\n" + " await writer.drain()\n" + " finally:\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " server = await asyncio.start_server(handle_client, '127.0.0.1', 0)\n" + " port = server.sockets[0].getsockname()[1]\n" + " reader, writer = await asyncio.open_connection('127.0.0.1', port)\n" + " msg = b'x' * msg_size\n" + " start = time.perf_counter()\n" + " for _ in range(n_messages):\n" + " writer.write(msg)\n" + " await writer.drain()\n" + " await reader.readexactly(msg_size)\n" + " elapsed = time.perf_counter() - start\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " server.close()\n" + " await server.wait_closed()\n" + " return {'count': n_messages, 'elapsed': elapsed}\n" + " return asyncio.run(_run(n_messages, msg_size))\n" + >>, ok = py:exec(Code), {ok, _} = py:call('__main__', run_tcp_echo_single, [WarmupN, MsgSize], #{}, Timeout), {_, {ok, Result}} = timer:tc(fun() -> @@ -242,10 +266,17 @@ def run_tcp_echo_single(n_messages, msg_size): PythonElapsed = maps:get(<<"elapsed">>, Result), MsgsPerSec = Count / PythonElapsed, ThroughputMB = (Count * MsgSize) / PythonElapsed / 1024 / 1024, - io:format("Time: ~.3f sec | Messages/sec: ~w | Throughput: ~.2f MB/sec~n", - [PythonElapsed, round(MsgsPerSec), ThroughputMB]), - #{messages => N, msg_size => MsgSize, python_time_sec => PythonElapsed, - messages_per_sec => MsgsPerSec, throughput_mb_sec => ThroughputMB}. + io:format( + "Time: ~.3f sec | Messages/sec: ~w | Throughput: ~.2f MB/sec~n", + [PythonElapsed, round(MsgsPerSec), ThroughputMB] + ), + #{ + messages => N, + msg_size => MsgSize, + python_time_sec => PythonElapsed, + messages_per_sec => MsgsPerSec, + throughput_mb_sec => ThroughputMB + }. tcp_echo_concurrent(Opts) -> N = maps:get(tcp_messages, Opts) div 4, @@ -254,45 +285,46 @@ tcp_echo_concurrent(Opts) -> Timeout = maps:get(call_timeout, Opts), io:format("~n--- TCP Echo (concurrent connections: ~p) ---~n", [Connections]), io:format("Messages per connection: ~p x ~p bytes~n", [N, MsgSize]), - Code = <<" -import asyncio -import time -def run_tcp_echo_concurrent(n_messages, msg_size, n_connections): - async def _run(n_messages, msg_size, n_connections): - async def handle_client(reader, writer): - try: - while True: - data = await reader.read(msg_size) - if not data: - break - writer.write(data) - await writer.drain() - finally: - writer.close() - try: await writer.wait_closed() - except: pass - async def run_client(port, num_msgs): - reader, writer = await asyncio.open_connection('127.0.0.1', port) - msg = b'x' * msg_size - for _ in range(num_msgs): - writer.write(msg) - await writer.drain() - await reader.readexactly(msg_size) - writer.close() - try: await writer.wait_closed() - except: pass - return num_msgs - server = await asyncio.start_server(handle_client, '127.0.0.1', 0) - port = server.sockets[0].getsockname()[1] - start = time.perf_counter() - tasks = [run_client(port, n_messages) for _ in range(n_connections)] - counts = await asyncio.gather(*tasks) - elapsed = time.perf_counter() - start - server.close() - await server.wait_closed() - return {'total': sum(counts), 'elapsed': elapsed, 'connections': n_connections} - return asyncio.run(_run(n_messages, msg_size, n_connections)) -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "def run_tcp_echo_concurrent(n_messages, msg_size, n_connections):\n" + " async def _run(n_messages, msg_size, n_connections):\n" + " async def handle_client(reader, writer):\n" + " try:\n" + " while True:\n" + " data = await reader.read(msg_size)\n" + " if not data:\n" + " break\n" + " writer.write(data)\n" + " await writer.drain()\n" + " finally:\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " async def run_client(port, num_msgs):\n" + " reader, writer = await asyncio.open_connection('127.0.0.1', port)\n" + " msg = b'x' * msg_size\n" + " for _ in range(num_msgs):\n" + " writer.write(msg)\n" + " await writer.drain()\n" + " await reader.readexactly(msg_size)\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " return num_msgs\n" + " server = await asyncio.start_server(handle_client, '127.0.0.1', 0)\n" + " port = server.sockets[0].getsockname()[1]\n" + " start = time.perf_counter()\n" + " tasks = [run_client(port, n_messages) for _ in range(n_connections)]\n" + " counts = await asyncio.gather(*tasks)\n" + " elapsed = time.perf_counter() - start\n" + " server.close()\n" + " await server.wait_closed()\n" + " return {'total': sum(counts), 'elapsed': elapsed, 'connections': n_connections}\n" + " return asyncio.run(_run(n_messages, msg_size, n_connections))\n" + >>, ok = py:exec(Code), {ok, _} = py:call('__main__', run_tcp_echo_concurrent, [50, MsgSize, 2], #{}, Timeout), {_, {ok, Result}} = timer:tc(fun() -> @@ -302,11 +334,18 @@ def run_tcp_echo_concurrent(n_messages, msg_size, n_connections): PythonElapsed = maps:get(<<"elapsed">>, Result), MsgsPerSec = Total / PythonElapsed, ThroughputMB = (Total * MsgSize) / PythonElapsed / 1024 / 1024, - io:format("Time: ~.3f sec | Total msgs: ~w | Messages/sec: ~w | Throughput: ~.2f MB/sec~n", - [PythonElapsed, Total, round(MsgsPerSec), ThroughputMB]), - #{connections => Connections, total_messages => Total, msg_size => MsgSize, - python_time_sec => PythonElapsed, messages_per_sec => MsgsPerSec, - throughput_mb_sec => ThroughputMB}. + io:format( + "Time: ~.3f sec | Total msgs: ~w | Messages/sec: ~w | Throughput: ~.2f MB/sec~n", + [PythonElapsed, Total, round(MsgsPerSec), ThroughputMB] + ), + #{ + connections => Connections, + total_messages => Total, + msg_size => MsgSize, + python_time_sec => PythonElapsed, + messages_per_sec => MsgsPerSec, + throughput_mb_sec => ThroughputMB + }. tcp_connections_scaling(Opts) -> N = maps:get(tcp_messages, Opts) div 8, @@ -316,66 +355,82 @@ tcp_connections_scaling(Opts) -> io:format("~n--- TCP Connections Scaling ---~n"), io:format("Messages per connection: ~p x ~p bytes~n", [N, MsgSize]), io:format("Worker counts: ~p~n", [WorkerCounts]), - Code = <<" -import asyncio -import time -def run_tcp_scaling(n_messages, msg_size, n_workers): - async def _run(): - async def run_echo_pair(pair_id, n_msgs): - async def handle_client(reader, writer): - try: - while True: - data = await reader.read(msg_size) - if not data: - break - writer.write(data) - await writer.drain() - finally: - writer.close() - try: await writer.wait_closed() - except: pass - server = await asyncio.start_server(handle_client, '127.0.0.1', 0) - port = server.sockets[0].getsockname()[1] - reader, writer = await asyncio.open_connection('127.0.0.1', port) - msg = b'x' * msg_size - for _ in range(n_msgs): - writer.write(msg) - await writer.drain() - await reader.readexactly(msg_size) - writer.close() - try: await writer.wait_closed() - except: pass - server.close() - await server.wait_closed() - return n_msgs - start = time.perf_counter() - tasks = [run_echo_pair(i, n_messages) for i in range(n_workers)] - counts = await asyncio.gather(*tasks) - elapsed = time.perf_counter() - start - return {'total': sum(counts), 'elapsed': elapsed, 'workers': n_workers, 'errors': 0} - return asyncio.run(_run()) -">>, + Code = << + "\n" + "import asyncio\n" + "import time\n" + "def run_tcp_scaling(n_messages, msg_size, n_workers):\n" + " async def _run():\n" + " async def run_echo_pair(pair_id, n_msgs):\n" + " async def handle_client(reader, writer):\n" + " try:\n" + " while True:\n" + " data = await reader.read(msg_size)\n" + " if not data:\n" + " break\n" + " writer.write(data)\n" + " await writer.drain()\n" + " finally:\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " server = await asyncio.start_server(handle_client, '127.0.0.1', 0)\n" + " port = server.sockets[0].getsockname()[1]\n" + " reader, writer = await asyncio.open_connection('127.0.0.1', port)\n" + " msg = b'x' * msg_size\n" + " for _ in range(n_msgs):\n" + " writer.write(msg)\n" + " await writer.drain()\n" + " await reader.readexactly(msg_size)\n" + " writer.close()\n" + " try: await writer.wait_closed()\n" + " except: pass\n" + " server.close()\n" + " await server.wait_closed()\n" + " return n_msgs\n" + " start = time.perf_counter()\n" + " tasks = [run_echo_pair(i, n_messages) for i in range(n_workers)]\n" + " counts = await asyncio.gather(*tasks)\n" + " elapsed = time.perf_counter() - start\n" + " return {'total': sum(counts), 'elapsed': elapsed, 'workers': n_workers, 'errors': 0}\n" + " return asyncio.run(_run())\n" + >>, ok = py:exec(Code), - ScalingResults = lists:map(fun(Workers) -> - io:format(" Testing ~p worker(s)...~n", [Workers]), - {ok, Result} = py:call('__main__', run_tcp_scaling, [N, MsgSize, Workers], #{}, Timeout), - Total = maps:get(<<"total">>, Result), - Elapsed = maps:get(<<"elapsed">>, Result), - Errors = maps:get(<<"errors">>, Result), - MsgsPerSec = Total / Elapsed, - io:format(" -> ~w msgs in ~.3f sec (~w/sec, ~p errors)~n", - [Total, Elapsed, round(MsgsPerSec), Errors]), - #{workers => Workers, total => Total, elapsed => Elapsed, - msgs_per_sec => MsgsPerSec, errors => Errors} - end, WorkerCounts), + ScalingResults = lists:map( + fun(Workers) -> + io:format(" Testing ~p worker(s)...~n", [Workers]), + {ok, Result} = py:call( + '__main__', run_tcp_scaling, [N, MsgSize, Workers], #{}, Timeout + ), + Total = maps:get(<<"total">>, Result), + Elapsed = maps:get(<<"elapsed">>, Result), + Errors = maps:get(<<"errors">>, Result), + MsgsPerSec = Total / Elapsed, + io:format( + " -> ~w msgs in ~.3f sec (~w/sec, ~p errors)~n", + [Total, Elapsed, round(MsgsPerSec), Errors] + ), + #{ + workers => Workers, + total => Total, + elapsed => Elapsed, + msgs_per_sec => MsgsPerSec, + errors => Errors + } + end, + WorkerCounts + ), [Single | _] = ScalingResults, SingleRate = maps:get(msgs_per_sec, Single), - Efficiency = lists:map(fun(R) -> - W = maps:get(workers, R), - Rate = maps:get(msgs_per_sec, R), - Eff = (Rate / (SingleRate * W)) * 100, - {W, Eff} - end, ScalingResults), + Efficiency = lists:map( + fun(R) -> + W = maps:get(workers, R), + Rate = maps:get(msgs_per_sec, R), + Eff = (Rate / (SingleRate * W)) * 100, + {W, Eff} + end, + ScalingResults + ), io:format("Scaling efficiency: ~p~n", [Efficiency]), #{results => ScalingResults, efficiency => maps:from_list(Efficiency)}. @@ -392,35 +447,45 @@ format_results(Results) -> _ -> ok end, case maps:get(timer_latency, Results, undefined) of - #{error := _} -> io:format("Timer latency: ERROR~n"); + #{error := _} -> + io:format("Timer latency: ERROR~n"); #{p95_latency_ms := P95, p99_latency_ms := P99} -> io:format("Timer latency: p95=~.3fms p99=~.3fms~n", [P95, P99]); - _ -> ok + _ -> + ok end, case maps:get(tcp_echo_single, Results, undefined) of - #{error := _} -> io:format("TCP echo (single): ERROR~n"); + #{error := _} -> + io:format("TCP echo (single): ERROR~n"); #{messages_per_sec := M, throughput_mb_sec := MB} -> io:format("TCP echo (single): ~w msg/sec (~.2f MB/sec)~n", [round(M), MB]); - _ -> ok + _ -> + ok end, case maps:get(timer_throughput_concurrent, Results, undefined) of - #{error := _} -> io:format("Timer throughput (concurrent): ERROR~n"); + #{error := _} -> + io:format("Timer throughput (concurrent): ERROR~n"); #{timers_per_sec := CT, workers := W} -> io:format("Timer throughput (~p workers): ~w/sec~n", [W, round(CT)]); - _ -> ok + _ -> + ok end, case maps:get(tcp_echo_concurrent, Results, undefined) of - #{error := _} -> io:format("TCP echo (concurrent): ERROR~n"); + #{error := _} -> + io:format("TCP echo (concurrent): ERROR~n"); #{messages_per_sec := CM, connections := C, throughput_mb_sec := CMB} -> io:format("TCP echo (~p connections): ~w msg/sec (~.2f MB/sec)~n", [C, round(CM), CMB]); - _ -> ok + _ -> + ok end, case maps:get(tcp_connections_scaling, Results, undefined) of - #{error := _} -> io:format("TCP scaling: ERROR~n"); + #{error := _} -> + io:format("TCP scaling: ERROR~n"); #{efficiency := Eff} -> io:format("TCP scaling efficiency:~n"), maps:foreach(fun(W, E) -> io:format(" ~p workers: ~.1f%~n", [W, E]) end, Eff); - _ -> ok + _ -> + ok end, io:format("~n"). diff --git a/test/py_schedule_SUITE.erl b/test/py_schedule_SUITE.erl index 56361e7..47aea08 100644 --- a/test/py_schedule_SUITE.erl +++ b/test/py_schedule_SUITE.erl @@ -76,58 +76,64 @@ end_per_suite(_Config) -> %% Test that erlang.schedule is available test_schedule_available(_Config) -> - ok = py:exec(<<" -import erlang -assert hasattr(erlang, 'schedule'), 'erlang.schedule not found' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "assert hasattr(erlang, 'schedule'), 'erlang.schedule not found'\n" + >>), ct:pal("erlang.schedule is available"), ok. %% Test that erlang.schedule_py is available test_schedule_py_available(_Config) -> - ok = py:exec(<<" -import erlang -assert hasattr(erlang, 'schedule_py'), 'erlang.schedule_py not found' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "assert hasattr(erlang, 'schedule_py'), 'erlang.schedule_py not found'\n" + >>), ct:pal("erlang.schedule_py is available"), ok. %% Test that erlang.consume_time_slice is available test_consume_time_slice_available(_Config) -> - ok = py:exec(<<" -import erlang -assert hasattr(erlang, 'consume_time_slice'), 'erlang.consume_time_slice not found' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "assert hasattr(erlang, 'consume_time_slice'), 'erlang.consume_time_slice not found'\n" + >>), ct:pal("erlang.consume_time_slice is available"), ok. %% Test that schedule() returns a ScheduleMarker test_schedule_returns_marker(_Config) -> - ok = py:exec(<<" -import erlang -marker = erlang.schedule('_test_add', 1, 2) -assert isinstance(marker, erlang.ScheduleMarker), f'Expected ScheduleMarker, got {type(marker)}' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "marker = erlang.schedule('_test_add', 1, 2)\n" + "assert isinstance(marker, erlang.ScheduleMarker), f'Expected ScheduleMarker, got {type(marker)}'\n" + >>), ct:pal("schedule() returns ScheduleMarker"), ok. %% Test that schedule_py() returns a ScheduleMarker test_schedule_py_returns_marker(_Config) -> - ok = py:exec(<<" -import erlang -marker = erlang.schedule_py('math', 'sqrt', [16.0]) -assert isinstance(marker, erlang.ScheduleMarker), f'Expected ScheduleMarker, got {type(marker)}' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "marker = erlang.schedule_py('math', 'sqrt', [16.0])\n" + "assert isinstance(marker, erlang.ScheduleMarker), f'Expected ScheduleMarker, got {type(marker)}'\n" + >>), ct:pal("schedule_py() returns ScheduleMarker"), ok. %% Test that consume_time_slice() returns bool test_consume_time_slice_returns_bool(_Config) -> - ok = py:exec(<<" -import erlang -result = erlang.consume_time_slice(1) -assert isinstance(result, bool), f'Expected bool, got {type(result)}' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "result = erlang.consume_time_slice(1)\n" + "assert isinstance(result, bool), f'Expected bool, got {type(result)}'\n" + >>), ct:pal("consume_time_slice() returns bool"), ok. @@ -135,11 +141,12 @@ assert isinstance(result, bool), f'Expected bool, got {type(result)}' test_schedule_with_callback(_Config) -> Ctx = py:context(), %% Define the function - ok = py:exec(Ctx, <<" -def schedule_add(a, b): - import erlang - return erlang.schedule('_test_add', a, b) -">>), + ok = py:exec(Ctx, << + "\n" + "def schedule_add(a, b):\n" + " import erlang\n" + " return erlang.schedule('_test_add', a, b)\n" + >>), %% Call it - the schedule marker should be detected and callback executed {ok, Result} = py:eval(Ctx, <<"schedule_add(5, 7)">>), ct:pal("schedule() result: ~p", [Result]), @@ -150,19 +157,20 @@ def schedule_add(a, b): test_schedule_py_basic(_Config) -> Ctx = py:context(), %% Define the target function in __main__ so it's accessible via py:call - ok = py:exec(Ctx, <<" -import __main__ - -def double(x): - return x * 2 - -# Add to __main__ so it's accessible from schedule_py callback -__main__.double = double - -def schedule_double(x): - import erlang - return erlang.schedule_py('__main__', 'double', [x]) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def double(x):\n" + " return x * 2\n" + "\n" + "# Add to __main__ so it's accessible from schedule_py callback\n" + "__main__.double = double\n" + "\n" + "def schedule_double(x):\n" + " import erlang\n" + " return erlang.schedule_py('__main__', 'double', [x])\n" + >>), %% Call the scheduling function {ok, Result} = py:eval(Ctx, <<"schedule_double(5)">>), ct:pal("schedule_py() result: ~p", [Result]), @@ -172,18 +180,19 @@ def schedule_double(x): %% Test schedule_py() with multiple args test_schedule_py_with_args(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def add_three(a, b, c): - return a + b + c - -__main__.add_three = add_three - -def schedule_add_three(a, b, c): - import erlang - return erlang.schedule_py('__main__', 'add_three', [a, b, c]) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def add_three(a, b, c):\n" + " return a + b + c\n" + "\n" + "__main__.add_three = add_three\n" + "\n" + "def schedule_add_three(a, b, c):\n" + " import erlang\n" + " return erlang.schedule_py('__main__', 'add_three', [a, b, c])\n" + >>), {ok, Result} = py:eval(Ctx, <<"schedule_add_three(1, 2, 3)">>), ct:pal("schedule_py() with args result: ~p", [Result]), 6 = Result, @@ -192,18 +201,19 @@ def schedule_add_three(a, b, c): %% Test schedule_py() with kwargs test_schedule_py_with_kwargs(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def greet(name, prefix='Hello'): - return f'{prefix}, {name}!' - -__main__.greet = greet - -def schedule_greet(name, prefix): - import erlang - return erlang.schedule_py('__main__', 'greet', [name], {'prefix': prefix}) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def greet(name, prefix='Hello'):\n" + " return f'{prefix}, {name}!'\n" + "\n" + "__main__.greet = greet\n" + "\n" + "def schedule_greet(name, prefix):\n" + " import erlang\n" + " return erlang.schedule_py('__main__', 'greet', [name], {'prefix': prefix})\n" + >>), {ok, Result} = py:eval(Ctx, <<"schedule_greet('World', 'Hi')">>), ct:pal("schedule_py() with kwargs result: ~p", [Result]), <<"Hi, World!">> = Result, @@ -214,20 +224,21 @@ test_call_is_blocking(_Config) -> %% The original bug was that erlang.call() used replay mechanism which %% caused double-execution of code. With blocking mode, the call should %% only execute once even with timing-sensitive code. - ok = py:exec(<<" -import erlang -import time - -counter = [0] # Use list to avoid closure issues - -def test_call_once(): - counter[0] += 1 - erlang.call('_py_sleep', 0.05) # 50ms sleep - return counter[0] - -result = test_call_once() -assert result == 1, f'Expected 1, got {result} - call may have replayed' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "import time\n" + "\n" + "counter = [0] # Use list to avoid closure issues\n" + "\n" + "def test_call_once():\n" + " counter[0] += 1\n" + " erlang.call('_py_sleep', 0.05) # 50ms sleep\n" + " return counter[0]\n" + "\n" + "result = test_call_once()\n" + "assert result == 1, f'Expected 1, got {result} - call may have replayed'\n" + >>), ct:pal("erlang.call() is blocking (no replay)"), ok. @@ -237,38 +248,41 @@ assert result == 1, f'Expected 1, got {result} - call may have replayed' %% Test that erlang.schedule_inline is available test_schedule_inline_available(_Config) -> - ok = py:exec(<<" -import erlang -assert hasattr(erlang, 'schedule_inline'), 'erlang.schedule_inline not found' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "assert hasattr(erlang, 'schedule_inline'), 'erlang.schedule_inline not found'\n" + >>), ct:pal("erlang.schedule_inline is available"), ok. %% Test that schedule_inline() returns an InlineScheduleMarker test_schedule_inline_returns_marker(_Config) -> - ok = py:exec(<<" -import erlang -marker = erlang.schedule_inline('math', 'sqrt', args=[16.0]) -assert isinstance(marker, erlang.InlineScheduleMarker), f'Expected InlineScheduleMarker, got {type(marker)}' -">>), + ok = py:exec(<< + "\n" + "import erlang\n" + "marker = erlang.schedule_inline('math', 'sqrt', args=[16.0])\n" + "assert isinstance(marker, erlang.InlineScheduleMarker), f'Expected InlineScheduleMarker, got {type(marker)}'\n" + >>), ct:pal("schedule_inline() returns InlineScheduleMarker"), ok. %% Test schedule_inline() basic functionality - single continuation test_schedule_inline_basic(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def inline_double(x): - return x * 2 - -__main__.inline_double = inline_double - -def call_inline_double(x): - import erlang - return erlang.schedule_inline('__main__', 'inline_double', args=[x]) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def inline_double(x):\n" + " return x * 2\n" + "\n" + "__main__.inline_double = inline_double\n" + "\n" + "def call_inline_double(x):\n" + " import erlang\n" + " return erlang.schedule_inline('__main__', 'inline_double', args=[x])\n" + >>), {ok, Result} = py:eval(Ctx, <<"call_inline_double(21)">>), ct:pal("schedule_inline() basic result: ~p", [Result]), 42 = Result, @@ -277,18 +291,19 @@ def call_inline_double(x): %% Test schedule_inline() with chained continuations test_schedule_inline_chain(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def chain_step(n, acc): - import erlang - if n <= 0: - return acc - # Chain to next step via inline continuation - return erlang.schedule_inline('__main__', 'chain_step', args=[n - 1, acc + n]) - -__main__.chain_step = chain_step -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def chain_step(n, acc):\n" + " import erlang\n" + " if n <= 0:\n" + " return acc\n" + " # Chain to next step via inline continuation\n" + " return erlang.schedule_inline('__main__', 'chain_step', args=[n - 1, acc + n])\n" + "\n" + "__main__.chain_step = chain_step\n" + >>), %% Sum of 1 to 10 = 55 {ok, Result} = py:eval(Ctx, <<"chain_step(10, 0)">>), ct:pal("schedule_inline() chain result: ~p", [Result]), @@ -298,18 +313,19 @@ __main__.chain_step = chain_step %% Test schedule_inline() with multiple args test_schedule_inline_with_args(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def inline_add(a, b, c): - return a + b + c - -__main__.inline_add = inline_add - -def call_inline_add(a, b, c): - import erlang - return erlang.schedule_inline('__main__', 'inline_add', args=[a, b, c]) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def inline_add(a, b, c):\n" + " return a + b + c\n" + "\n" + "__main__.inline_add = inline_add\n" + "\n" + "def call_inline_add(a, b, c):\n" + " import erlang\n" + " return erlang.schedule_inline('__main__', 'inline_add', args=[a, b, c])\n" + >>), {ok, Result} = py:eval(Ctx, <<"call_inline_add(10, 20, 30)">>), ct:pal("schedule_inline() with args result: ~p", [Result]), 60 = Result, @@ -318,18 +334,19 @@ def call_inline_add(a, b, c): %% Test schedule_inline() with kwargs test_schedule_inline_with_kwargs(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def inline_greet(name, prefix='Hello'): - return f'{prefix}, {name}!' - -__main__.inline_greet = inline_greet - -def call_inline_greet(name, prefix): - import erlang - return erlang.schedule_inline('__main__', 'inline_greet', args=[name], kwargs={'prefix': prefix}) -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def inline_greet(name, prefix='Hello'):\n" + " return f'{prefix}, {name}!'\n" + "\n" + "__main__.inline_greet = inline_greet\n" + "\n" + "def call_inline_greet(name, prefix):\n" + " import erlang\n" + " return erlang.schedule_inline('__main__', 'inline_greet', args=[name], kwargs={'prefix': prefix})\n" + >>), {ok, Result} = py:eval(Ctx, <<"call_inline_greet('Erlang', 'Greetings')">>), ct:pal("schedule_inline() with kwargs result: ~p", [Result]), <<"Greetings, Erlang!">> = Result, @@ -340,27 +357,28 @@ test_schedule_inline_to_schedule_py(_Config) -> %% Start with schedule_inline, then transition to schedule_py %% Use explicit context to ensure consistent namespace Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -def step1(x): - import erlang - # First step uses inline continuation - return erlang.schedule_inline('__main__', 'step2', args=[x * 2]) - -def step2(x): - import erlang - # Second step switches to schedule_py (goes through Erlang messaging) - return erlang.schedule_py('__main__', 'step3', [x + 10]) - -def step3(x): - # Final step returns result - return x * 3 - -__main__.step1 = step1 -__main__.step2 = step2 -__main__.step3 = step3 -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "def step1(x):\n" + " import erlang\n" + " # First step uses inline continuation\n" + " return erlang.schedule_inline('__main__', 'step2', args=[x * 2])\n" + "\n" + "def step2(x):\n" + " import erlang\n" + " # Second step switches to schedule_py (goes through Erlang messaging)\n" + " return erlang.schedule_py('__main__', 'step3', [x + 10])\n" + "\n" + "def step3(x):\n" + " # Final step returns result\n" + " return x * 3\n" + "\n" + "__main__.step1 = step1\n" + "__main__.step2 = step2\n" + "__main__.step3 = step3\n" + >>), %% (5 * 2 + 10) * 3 = 60 {ok, Result} = py:eval(Ctx, <<"step1(5)">>), ct:pal("schedule_inline to schedule_py result: ~p", [Result]), @@ -370,11 +388,12 @@ __main__.step3 = step3 %% Test schedule_inline error handling (function not found) test_schedule_inline_error(_Config) -> Ctx = py:context(), - ok = py:exec(Ctx, <<" -def call_nonexistent(): - import erlang - return erlang.schedule_inline('__main__', 'nonexistent_function_xyz', args=[]) -">>), + ok = py:exec(Ctx, << + "\n" + "def call_nonexistent():\n" + " import erlang\n" + " return erlang.schedule_inline('__main__', 'nonexistent_function_xyz', args=[])\n" + >>), {error, Reason} = py:eval(Ctx, <<"call_nonexistent()">>), ct:pal("schedule_inline error: ~p", [Reason]), %% Should get a NameError - error comes as {ErrorType, Message} tuple or binary @@ -392,25 +411,27 @@ test_schedule_inline_captures_globals(_Config) -> %% globals and uses them for function lookup in the continuation. %% This is important for subinterpreter support. Ctx = py:context(), - ok = py:exec(Ctx, <<" -import __main__ - -# Define a helper function at module scope -def helper_multiply(x): - return x * 3 - -# Define an outer function that creates a local function reference -# and uses schedule_inline to call it -def test_captured_globals(): - import erlang - # This should capture the current globals which includes helper_multiply - return erlang.schedule_inline('__main__', 'helper_multiply', args=[7]) - -__main__.helper_multiply = helper_multiply -__main__.test_captured_globals = test_captured_globals -">>), + ok = py:exec(Ctx, << + "\n" + "import __main__\n" + "\n" + "# Define a helper function at module scope\n" + "def helper_multiply(x):\n" + " return x * 3\n" + "\n" + "# Define an outer function that creates a local function reference\n" + "# and uses schedule_inline to call it\n" + "def test_captured_globals():\n" + " import erlang\n" + " # This should capture the current globals which includes helper_multiply\n" + " return erlang.schedule_inline('__main__', 'helper_multiply', args=[7])\n" + "\n" + "__main__.helper_multiply = helper_multiply\n" + "__main__.test_captured_globals = test_captured_globals\n" + >>), %% Call the function - should work because globals are captured {ok, Result} = py:eval(Ctx, <<"test_captured_globals()">>), ct:pal("schedule_inline captures globals result: ~p", [Result]), - 21 = Result, %% 7 * 3 = 21 + %% 7 * 3 = 21 + 21 = Result, ok. diff --git a/test/py_session_SUITE.erl b/test/py_session_SUITE.erl index 7671fec..08b8522 100644 --- a/test/py_session_SUITE.erl +++ b/test/py_session_SUITE.erl @@ -7,8 +7,15 @@ -include_lib("common_test/include/ct.hrl"). --export([all/0, groups/0, init_per_suite/1, end_per_suite/1, - init_per_group/2, end_per_group/2, end_per_testcase/2]). +-export([ + all/0, + groups/0, + init_per_suite/1, + end_per_suite/1, + init_per_group/2, + end_per_group/2, + end_per_testcase/2 +]). %% logger handler used by test_print_is_logged -export([log/2]). @@ -64,8 +71,14 @@ -define(MOD, py_test_session). all() -> - [{group, fork}, {group, spawn}, {group, fork_only}, {group, spawn_only}, - {group, reimport_worker}, {group, reimport_owngil}]. + [ + {group, fork}, + {group, spawn}, + {group, fork_only}, + {group, spawn_only}, + {group, reimport_worker}, + {group, reimport_owngil} + ]. groups() -> Common = [ @@ -110,17 +123,23 @@ groups() -> test_reimport_refresh, test_reimport_bad_options ], - [{fork, [], Common}, - {spawn, [], Common}, - {fork_only, [], [test_zygote_crash_rebuilds, - test_thread_at_import_refused, - test_erlang_call_during_preload, - test_info_counts_forks, - test_late_exit_report]}, - {spawn_only, [], [test_warm_pool, - test_thread_at_import_spawned]}, - {reimport_worker, [], Reimport}, - {reimport_owngil, [], Reimport}]. + [ + {fork, [], Common}, + {spawn, [], Common}, + {fork_only, [], [ + test_zygote_crash_rebuilds, + test_thread_at_import_refused, + test_erlang_call_during_preload, + test_info_counts_forks, + test_late_exit_report + ]}, + {spawn_only, [], [ + test_warm_pool, + test_thread_at_import_spawned + ]}, + {reimport_worker, [], Reimport}, + {reimport_owngil, [], Reimport} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -166,14 +185,18 @@ end_per_testcase(_Case, _Config) -> %% sys.modules, os.environ, threads, files in its directory. test_sessions_are_isolated(Config) -> T = template(Config), - Prev = lists:foldl(fun(I, Prev) -> - {ok, S} = py_session:new(T), - Mark = integer_to_binary(I), - {ok, Prev} = py_context:call(S, ?MOD, peek, []), - {ok, Mark} = py_context:call(S, ?MOD, mark, [Mark]), - py_session:close(S), - none - end, none, lists:seq(1, 100)), + Prev = lists:foldl( + fun(I, Prev) -> + {ok, S} = py_session:new(T), + Mark = integer_to_binary(I), + {ok, Prev} = py_context:call(S, ?MOD, peek, []), + {ok, Mark} = py_context:call(S, ?MOD, mark, [Mark]), + py_session:close(S), + none + end, + none, + lists:seq(1, 100) + ), none = Prev, {ok, A} = py_session:new(T), {ok, true} = py_context:call(A, ?MOD, put_module, [<<"sess_marker">>]), @@ -248,12 +271,15 @@ test_hash_seed(Config) -> %% A forked session does not inherit the zygote's random state as is. test_random_differs(Config) -> T = template(Config), - Values = [begin - {ok, S} = py_session:new(T), - {ok, V} = py_context:call(S, ?MOD, random_value, []), - py_session:close(S), - V - end || _ <- lists:seq(1, 5)], + Values = [ + begin + {ok, S} = py_session:new(T), + {ok, V} = py_context:call(S, ?MOD, random_value, []), + py_session:close(S), + V + end + || _ <- lists:seq(1, 5) + ], 5 = length(lists:usort(Values)), ok. @@ -291,14 +317,22 @@ test_reentrance_depth(Config) -> test_concurrent_reentrance(Config) -> T = template(Config), Self = self(), - Pids = [spawn_link(fun() -> - {ok, S} = py_session:new(T), - R = [py_context:call(S, ?MOD, reenter, [5]) || _ <- lists:seq(1, 10)], - py_session:close(S), - Self ! {self(), R} - end) || _ <- lists:seq(1, 16)], - [receive {P, R} -> R = lists:duplicate(10, {ok, 5}) after 30000 -> ct:fail(timeout) end - || P <- Pids], + Pids = [ + spawn_link(fun() -> + {ok, S} = py_session:new(T), + R = [py_context:call(S, ?MOD, reenter, [5]) || _ <- lists:seq(1, 10)], + py_session:close(S), + Self ! {self(), R} + end) + || _ <- lists:seq(1, 16) + ], + [ + receive + {P, R} -> R = lists:duplicate(10, {ok, 5}) + after 30000 -> ct:fail(timeout) + end + || P <- Pids + ], ok. %% A callback of session A calls into session B. @@ -346,7 +380,10 @@ test_session_crash(Config) -> MA = erlang:monitor(process, A), [py_session:close(X) || X <- [A, B, C]], %% close/1 replies first, then the context removes its directory and exits - receive {'DOWN', MA, process, A, _} -> ok after 5000 -> ct:fail(session_not_stopped) end, + receive + {'DOWN', MA, process, A, _} -> ok + after 5000 -> ct:fail(session_not_stopped) + end, ok. test_kill_session(Config) -> @@ -375,8 +412,11 @@ wait_no_dir(Dir, 0) -> ct:fail({still_there, Dir}); wait_no_dir(Dir, N) -> case filelib:is_dir(Dir) of - false -> ok; - true -> timer:sleep(20), wait_no_dir(Dir, N - 1) + false -> + ok; + true -> + timer:sleep(20), + wait_no_dir(Dir, N - 1) end. %% A session is linked to the process that created it. @@ -387,13 +427,24 @@ test_caller_crash_stops_session(Config) -> {ok, S} = py_session:new(T), {ok, Pid} = py_context:call(S, ?MOD, pid, []), Self ! {session, S, Pid}, - receive never -> ok end + receive + never -> ok + end end), - {S, Pid} = receive {session, S0, P0} -> {S0, P0} after 10000 -> ct:fail(no_session) end, + {S, Pid} = + receive + {session, S0, P0} -> {S0, P0} + after 10000 -> ct:fail(no_session) + end, SMon = erlang:monitor(process, S), exit(Owner, crash), - receive {'DOWN', Mon, process, Owner, crash} -> ok end, - receive {'DOWN', SMon, process, S, _} -> ok after 5000 -> ct:fail(session_survived) end, + receive + {'DOWN', Mon, process, Owner, crash} -> ok + end, + receive + {'DOWN', SMon, process, S, _} -> ok + after 5000 -> ct:fail(session_survived) + end, ok = wait_gone(Pid). test_run_helper(Config) -> @@ -423,11 +474,12 @@ test_print_is_logged(Config) -> end. log(#{msg := Msg}, #{config := #{pid := Pid}}) -> - Text = case Msg of - {string, S} -> S; - {report, R} -> io_lib:format("~p", [R]); - {Format, Args} -> io_lib:format(Format, Args) - end, + Text = + case Msg of + {string, S} -> S; + {report, R} -> io_lib:format("~p", [R]); + {Format, Args} -> io_lib:format(Format, Args) + end, Pid ! {logged, unicode:characters_to_binary(Text)}, ok. @@ -447,7 +499,9 @@ wait_logged(Needle, N) -> test_rlimits_apply(Config) -> T = template(Config, #{rlimits => #{nofile => 64}}), {ok, S} = py_session:new(T), - {ok, 64} = py_context:eval(S, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">>), + {ok, 64} = py_context:eval( + S, <<"__import__('resource').getrlimit(__import__('resource').RLIMIT_NOFILE)[0]">> + ), py_session:close(S). %% refresh/1 prepares the template again: new sessions see the new code, @@ -473,7 +527,9 @@ test_bad_template_options(Config) -> Start = ?config(start, Config), {error, {badarg, {start, nope}}} = py_session:template(#{start => nope}), {error, {badarg, {hash_seed, -1}}} = py_session:template(#{start => Start, hash_seed => -1}), - {error, {python_not_found, _}} = py_session:template(#{start => Start, python => "/no/such/python"}), + {error, {python_not_found, _}} = py_session:template(#{ + start => Start, python => "/no/such/python" + }), case Start of fork -> {error, {template_failed, {init_failed, {'ModuleNotFoundError', _}}}} = @@ -507,15 +563,20 @@ test_zygote_crash_rebuilds(Config) -> %% A thread started at import would be lost in every fork: refused. test_thread_at_import_refused(Config) -> {error, {template_failed, {init_failed, {threads, [<<"import-time-thread">>]}}}} = - py_session:template(#{start => fork, paths => [?config(test_dir, Config)], - imports => [py_test_session_thread]}), + py_session:template(#{ + start => fork, + paths => [?config(test_dir, Config)], + imports => [py_test_session_thread] + }), ok. %% `erlang' can be imported by template code, but not called before a %% session exists. test_erlang_call_during_preload(Config) -> - T = template(Config, #{preload => - <<"import py_test_session\nPRELOAD_CALL = py_test_session.call_during_preload()">>}), + T = template(Config, #{ + preload => + <<"import py_test_session\nPRELOAD_CALL = py_test_session.call_during_preload()">> + }), {ok, S} = py_session:new(T), {ok, Msg} = py_context:eval(S, <<"PRELOAD_CALL">>), {match, _} = re:run(Msg, <<"not connected">>), @@ -528,14 +589,23 @@ test_late_exit_report(Config) -> T = template(Config), {ok, S} = py_session:new(T), ok = sys:suspend(T), - spawn(fun() -> timer:sleep(700), sys:resume(T) end), + spawn(fun() -> + timer:sleep(700), + sys:resume(T) + end), {error, {child_exited, {signal, 6}}} = py_context:call(S, ?MOD, abort, []), py_session:close(S). test_info_counts_forks(Config) -> T = template(Config, #{zygotes => 2}), #{start := fork, zygotes := [_, _], forks := 0} = py_session:info(T), - Ss = [begin {ok, S} = py_session:new(T), S end || _ <- lists:seq(1, 4)], + Ss = [ + begin + {ok, S} = py_session:new(T), + S + end + || _ <- lists:seq(1, 4) + ], #{forks := 4, sessions := 4} = py_session:info(T), [py_session:close(S) || S <- Ss], #{sessions := 0} = wait_sessions(T, 0), @@ -595,11 +665,19 @@ test_reimport_shares_stdlib_and_imports(Config) -> test_reimport_concurrent_runs(Config) -> T = rtemplate(Config, #{contexts => 4}), Self = self(), - Pids = [spawn_link(fun() -> - Self ! {done, [py_session:run(T, ?RMOD, bump, []) || _ <- lists:seq(1, 50)]} - end) || _ <- lists:seq(1, 8)], - [receive {done, R} -> R = lists:duplicate(50, {ok, 1}) after 60000 -> ct:fail(timeout) end - || _ <- Pids], + Pids = [ + spawn_link(fun() -> + Self ! {done, [py_session:run(T, ?RMOD, bump, []) || _ <- lists:seq(1, 50)]} + end) + || _ <- lists:seq(1, 8) + ], + [ + receive + {done, R} -> R = lists:duplicate(50, {ok, 1}) + after 60000 -> ct:fail(timeout) + end + || _ <- Pids + ], ok. %% A run calls Erlang, whose callback runs another re-import run on the @@ -611,8 +689,10 @@ test_reimport_reentrance(Config) -> N + R end), try - [{ok, 11} = py_session:run(T, ?RMOD, call_back, [10], #{timeout => 10000}) - || _ <- lists:seq(1, 10)], + [ + {ok, 11} = py_session:run(T, ?RMOD, call_back, [10], #{timeout => 10000}) + || _ <- lists:seq(1, 10) + ], {ok, 1} = py_session:run(T, ?RMOD, bump, []) after py:unregister_function(reimport_nested) @@ -697,14 +777,23 @@ test_rsession_reentrance(Config) -> test_rsession_concurrent(Config) -> T = rtemplate(Config, #{contexts => 2}), Self = self(), - Pids = [spawn_link(fun() -> - {ok, S} = py_session:new(T), - R = [py_context:call(S, ?RMOD, bump, []) || _ <- lists:seq(1, 20)], - py_session:close(S), - Self ! {done, R} - end) || _ <- lists:seq(1, 16)], + Pids = [ + spawn_link(fun() -> + {ok, S} = py_session:new(T), + R = [py_context:call(S, ?RMOD, bump, []) || _ <- lists:seq(1, 20)], + py_session:close(S), + Self ! {done, R} + end) + || _ <- lists:seq(1, 16) + ], Want = [{ok, N} || N <- lists:seq(1, 20)], - [receive {done, R} -> R = Want after 60000 -> ct:fail(timeout) end || _ <- Pids], + [ + receive + {done, R} -> R = Want + after 60000 -> ct:fail(timeout) + end + || _ <- Pids + ], 0 = wait_rsessions(T, 0, 100), ok. @@ -713,7 +802,10 @@ test_rsession_concurrent(Config) -> test_rsession_cleanup(Config) -> T = rtemplate(Config, #{contexts => 1}), #{contexts := [Ctx]} = py_session:info(T), - Count = fun() -> {ok, N} = py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_count, []), N end, + Count = fun() -> + {ok, N} = py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_count, []), + N + end, 0 = Count(), {ok, S} = py_session:new(T), 1 = Count(), @@ -723,13 +815,24 @@ test_rsession_cleanup(Config) -> {Owner, OMon} = spawn_monitor(fun() -> {ok, S1} = py_session:new(T), Self ! {session, S1}, - receive never -> ok end + receive + never -> ok + end end), - S1 = receive {session, X} -> X after 10000 -> ct:fail(no_session) end, + S1 = + receive + {session, X} -> X + after 10000 -> ct:fail(no_session) + end, SMon = erlang:monitor(process, S1), exit(Owner, crash), - receive {'DOWN', OMon, process, Owner, _} -> ok end, - receive {'DOWN', SMon, process, S1, _} -> ok after 5000 -> ct:fail(session_survived) end, + receive + {'DOWN', OMon, process, Owner, _} -> ok + end, + receive + {'DOWN', SMon, process, S1, _} -> ok + after 5000 -> ct:fail(session_survived) + end, ok = wait_count(Count, 0, 100), {ok, S2} = py_session:new(T), unlink(S2), @@ -751,7 +854,10 @@ test_rsession_timeout(Config) -> {ok, 1} = py_context:call(Other, ?RMOD, bump, [], #{}, 5000), {ok, 2} = py_context:call(S, ?RMOD, bump, []), %% no late reply left in the caller's mailbox - receive {_, {ok, <<"slept">>}} -> ct:fail(late_reply_delivered) after 200 -> ok end, + receive + {_, {ok, <<"slept">>}} -> ct:fail(late_reply_delivered) + after 200 -> ok + end, py_session:close(S), py_session:close(Other). @@ -772,7 +878,11 @@ test_rsession_context_died(Config) -> %% its modules are freed: through the replacing context on worker (the %% main interpreter outlives the context), with the interpreter on owngil #{contexts := [New]} = py_session:info(T), - Expected = case ?config(mode, Config) of worker -> Before; owngil -> 0 end, + Expected = + case ?config(mode, Config) of + worker -> Before; + owngil -> 0 + end, ok = wait_count(fun() -> session_count(New) end, Expected, 100), ok. @@ -819,24 +929,33 @@ wait_context_died(S, 0) -> py_context:call(S, ?RMOD, bump, []); wait_context_died(S, N) -> case py_context:call(S, ?RMOD, bump, []) of - {error, {context_died, _}} = E -> E; - _ -> timer:sleep(20), wait_context_died(S, N - 1) + {error, {context_died, _}} = E -> + E; + _ -> + timer:sleep(20), + wait_context_died(S, N - 1) end. wait_count(_Count, _Want, 0) -> ct:fail(session_not_freed); wait_count(Count, Want, N) -> case Count() of - Want -> ok; - _ -> timer:sleep(20), wait_count(Count, Want, N - 1) + Want -> + ok; + _ -> + timer:sleep(20), + wait_count(Count, Want, N - 1) end. wait_rsessions(T, Want, 0) -> maps:get(reimport_sessions, py_session:info(T), Want); wait_rsessions(T, Want, N) -> case py_session:info(T) of - #{reimport_sessions := Want} -> Want; - _ -> timer:sleep(20), wait_rsessions(T, Want, N - 1) + #{reimport_sessions := Want} -> + Want; + _ -> + timer:sleep(20), + wait_rsessions(T, Want, N - 1) end. test_reimport_refresh(Config) -> @@ -859,9 +978,17 @@ rtemplate(Config) -> rtemplate(Config, #{}). rtemplate(Config, Extra) -> - {ok, T} = py_session:template(maps:merge(#{start => reimport, mode => ?config(mode, Config), - contexts => 2, - paths => [?config(test_dir, Config)]}, Extra)), + {ok, T} = py_session:template( + maps:merge( + #{ + start => reimport, + mode => ?config(mode, Config), + contexts => 2, + paths => [?config(test_dir, Config)] + }, + Extra + ) + ), T. %%% ============================================================================ @@ -875,8 +1002,10 @@ template(Config, Extra) -> TestDir = ?config(test_dir, Config), Paths = [TestDir | maps:get(paths, Extra, [])], Imports = [?MOD | maps:get(imports, Extra, [])], - Opts = maps:merge(#{start => ?config(start, Config)}, - Extra#{paths => Paths, imports => Imports}), + Opts = maps:merge( + #{start => ?config(start, Config)}, + Extra#{paths => Paths, imports => Imports} + ), {ok, T} = py_session:template(Opts), T. @@ -887,8 +1016,11 @@ wait_gone(Pid, 0) -> ct:fail({still_alive, Pid}); wait_gone(Pid, N) -> case py_child:os_pid_alive(Pid) of - false -> ok; - true -> timer:sleep(20), wait_gone(Pid, N - 1) + false -> + ok; + true -> + timer:sleep(20), + wait_gone(Pid, N - 1) end. wait_new_zygote(T, Old, 0) -> @@ -896,7 +1028,9 @@ wait_new_zygote(T, Old, 0) -> wait_new_zygote(T, Old, N) -> case py_session:info(T) of #{zygotes := [#{os_pid := P}]} when P =/= Old -> P; - _ -> timer:sleep(50), wait_new_zygote(T, Old, N - 1) + _ -> + timer:sleep(50), + wait_new_zygote(T, Old, N - 1) end. wait_sessions(T, Want) -> @@ -906,14 +1040,20 @@ wait_sessions(T, _Want, 0) -> py_session:info(T); wait_sessions(T, Want, N) -> case py_session:info(T) of - #{sessions := Want} = I -> I; - _ -> timer:sleep(20), wait_sessions(T, Want, N - 1) + #{sessions := Want} = I -> + I; + _ -> + timer:sleep(20), + wait_sessions(T, Want, N - 1) end. wait_warm(T, _Want, 0) -> py_session:info(T); wait_warm(T, Want, N) -> case py_session:info(T) of - #{warm := Want} = I -> I; - _ -> timer:sleep(50), wait_warm(T, Want, N - 1) + #{warm := Want} = I -> + I; + _ -> + timer:sleep(50), + wait_warm(T, Want, N - 1) end. diff --git a/test/py_session_soak_SUITE.erl b/test/py_session_soak_SUITE.erl index 2e3b00a..022bcdd 100644 --- a/test/py_session_soak_SUITE.erl +++ b/test/py_session_soak_SUITE.erl @@ -30,36 +30,61 @@ end_per_suite(_Config) -> ok. test_session_churn_no_leak(Config) -> - Seconds = case os:getenv("PY_SESSION_SOAK_SECONDS") of - false -> 30; - S -> list_to_integer(S) - end, + Seconds = + case os:getenv("PY_SESSION_SOAK_SECONDS") of + false -> 30; + S -> list_to_integer(S) + end, TestDir = ?config(test_dir, Config), - {ok, Fork} = py_session:template(#{start => fork, zygotes => 2, paths => [TestDir], - imports => [?MOD]}), - {ok, Spawn} = py_session:template(#{start => spawn, warm => 2, paths => [TestDir], - imports => [?MOD]}), - {ok, Reimport} = py_session:template(#{start => reimport, mode => worker, contexts => 2, - paths => [TestDir]}), + {ok, Fork} = py_session:template(#{ + start => fork, + zygotes => 2, + paths => [TestDir], + imports => [?MOD] + }), + {ok, Spawn} = py_session:template(#{ + start => spawn, + warm => 2, + paths => [TestDir], + imports => [?MOD] + }), + {ok, Reimport} = py_session:template(#{ + start => reimport, + mode => worker, + contexts => 2, + paths => [TestDir] + }), timer:sleep(1000), Base = counters(), ct:print("baseline: ~p", [Base]), Deadline = erlang:monotonic_time(millisecond) + Seconds * 1000, Self = self(), - Workers = [spawn_link(fun() -> - rand:seed(exsss, {I, I * 7, I * 13}), - Self ! {done, self(), case I rem 4 of - 0 -> churn(Spawn, Deadline, 0, []); - 1 -> rchurn(Reimport, Deadline, 0, []); - _ -> churn(Fork, Deadline, 0, []) - end} - end) || I <- lists:seq(1, 12)], - Results = [receive {done, W, R} -> R after (Seconds + 120) * 1000 -> ct:fail(worker_hung) end - || W <- Workers], + Workers = [ + spawn_link(fun() -> + rand:seed(exsss, {I, I * 7, I * 13}), + Self ! + {done, self(), + case I rem 4 of + 0 -> churn(Spawn, Deadline, 0, []); + 1 -> rchurn(Reimport, Deadline, 0, []); + _ -> churn(Fork, Deadline, 0, []) + end} + end) + || I <- lists:seq(1, 12) + ], + Results = [ + receive + {done, W, R} -> R + after (Seconds + 120) * 1000 -> ct:fail(worker_hung) + end + || W <- Workers + ], Ops = lists:sum([N || {N, _} <- Results]), Errs = lists:append([E || {_, E} <- Results]), - ct:print("soak: ~p sessions in ~p s, ~p unexpected results: ~p", - [Ops, Seconds, length(Errs), lists:sublist(Errs, 5)]), + ct:print( + "soak: ~p sessions in ~p s, ~p unexpected results: ~p", + [Ops, Seconds, length(Errs), lists:sublist(Errs, 5)] + ), [] = Errs, true = Ops > 0, #{sessions := 0} = wait_idle(Fork, 100), @@ -83,7 +108,15 @@ churn(T, Deadline, N, Errs) -> {ok, S} = py_session:new(T), Got = use(rand:uniform(8), S), ok = py_session:close(S), - churn(T, Deadline, N + 1, case Got of ok -> Errs; Bad -> [Bad | Errs] end) + churn( + T, + Deadline, + N + 1, + case Got of + ok -> Errs; + Bad -> [Bad | Errs] + end + ) end. %% A re-import session: several calls on one fresh state, then closed, @@ -93,31 +126,48 @@ rchurn(T, Deadline, N, Errs) -> false -> {N, Errs}; true -> - Got = case rand:uniform(3) of - 1 -> - {ok, S} = py_session:new(T), - R = [py_context:call(S, py_test_reimport, bump, []) || _ <- lists:seq(1, 3)], - ok = py_session:close(S), - expect([{ok, 1}, {ok, 2}, {ok, 3}], R); - 2 -> - {ok, S} = py_session:new(T), - R = py_context:call(S, py_test_reimport, sleep, [0.2], #{}, 50), - {ok, 1} = py_context:call(S, py_test_reimport, bump, []), - ok = py_session:close(S), - expect({error, timeout}, R); - 3 -> - Self = self(), - {Owner, Mon} = spawn_monitor(fun() -> + Got = + case rand:uniform(3) of + 1 -> {ok, S} = py_session:new(T), + R = [ + py_context:call(S, py_test_reimport, bump, []) + || _ <- lists:seq(1, 3) + ], + ok = py_session:close(S), + expect([{ok, 1}, {ok, 2}, {ok, 3}], R); + 2 -> + {ok, S} = py_session:new(T), + R = py_context:call(S, py_test_reimport, sleep, [0.2], #{}, 50), {ok, 1} = py_context:call(S, py_test_reimport, bump, []), - Self ! {owner_ready, self()}, - exit(crash) - end), - receive {owner_ready, Owner} -> ok after 10000 -> ok end, - receive {'DOWN', Mon, process, Owner, _} -> ok end, - ok - end, - rchurn(T, Deadline, N + 1, case Got of ok -> Errs; Bad -> [Bad | Errs] end) + ok = py_session:close(S), + expect({error, timeout}, R); + 3 -> + Self = self(), + {Owner, Mon} = spawn_monitor(fun() -> + {ok, S} = py_session:new(T), + {ok, 1} = py_context:call(S, py_test_reimport, bump, []), + Self ! {owner_ready, self()}, + exit(crash) + end), + receive + {owner_ready, Owner} -> ok + after 10000 -> ok + end, + receive + {'DOWN', Mon, process, Owner, _} -> ok + end, + ok + end, + rchurn( + T, + Deadline, + N + 1, + case Got of + ok -> Errs; + Bad -> [Bad | Errs] + end + ) end. wait_freed(Ctx, 0) -> @@ -125,21 +175,31 @@ wait_freed(Ctx, 0) -> N; wait_freed(Ctx, Tries) -> case py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_count, []) of - {ok, 0} -> 0; - _ -> timer:sleep(50), wait_freed(Ctx, Tries - 1) + {ok, 0} -> + 0; + _ -> + timer:sleep(50), + wait_freed(Ctx, Tries - 1) end. -use(1, S) -> expect({ok, 3}, py_context:call(S, ?MOD, reenter, [3])); -use(2, S) -> expect({error, {child_exited, {signal, 6}}}, py_context:call(S, ?MOD, abort, [])); -use(3, S) -> expect(ok, py_context:kill(S)); -use(4, S) -> expect({error, timeout}, py_context:call(S, ?MOD, sleep, [10], #{}, 50)); +use(1, S) -> + expect({ok, 3}, py_context:call(S, ?MOD, reenter, [3])); +use(2, S) -> + expect({error, {child_exited, {signal, 6}}}, py_context:call(S, ?MOD, abort, [])); +use(3, S) -> + expect(ok, py_context:kill(S)); +use(4, S) -> + expect({error, timeout}, py_context:call(S, ?MOD, sleep, [10], #{}, 50)); use(5, S) -> %% a thread left running and a file written, then closed _ = py_context:call(S, ?MOD, start_thread, []), expect({ok, [<<"f">>]}, py_context:call(S, ?MOD, write_file, [<<"f">>, <<"x">>])); -use(6, S) -> expect({ok, none}, py_context:call(S, ?MOD, peek, [])); -use(7, S) -> expect(ok, py_context:exec(S, <<"import json; json.dumps(list(range(1000)))">>)); -use(8, _S) -> ok. +use(6, S) -> + expect({ok, none}, py_context:call(S, ?MOD, peek, [])); +use(7, S) -> + expect(ok, py_context:exec(S, <<"import json; json.dumps(list(range(1000)))">>)); +use(8, _S) -> + ok. expect(Want, Want) -> ok; expect(Want, Got) -> {Want, Got}. @@ -148,8 +208,11 @@ wait_idle(T, 0) -> py_session:info(T); wait_idle(T, N) -> case py_session:info(T) of - #{sessions := 0} = I -> I; - _ -> timer:sleep(50), wait_idle(T, N - 1) + #{sessions := 0} = I -> + I; + _ -> + timer:sleep(50), + wait_idle(T, N - 1) end. %%% ============================================================================ @@ -158,20 +221,33 @@ wait_idle(T, N) -> counters() -> erlang:garbage_collect(), - #{processes => erlang:system_info(process_count), - ports => erlang:system_info(port_count), - refs => ets:info(py_context_refs, size), - fds => beam_fd_count(), - children => session_children(), - zombies => zombies(), - scratch => length(filelib:wildcard(filename:join(py_child:sock_dir(), "sess_*")))}. + #{ + processes => erlang:system_info(process_count), + ports => erlang:system_info(port_count), + refs => ets:info(py_context_refs, size), + fds => beam_fd_count(), + children => session_children(), + zombies => zombies(), + scratch => length(filelib:wildcard(filename:join(py_child:sock_dir(), "sess_*"))) + }. check_no_growth(Base, After) -> - [begin - B = maps:get(K, Base), A = maps:get(K, After), - A =< B + Slack orelse ct:fail({leak, K, B, A}) - end || {K, Slack} <- [{processes, 5}, {ports, 0}, {refs, 0}, {children, 0}, - {zombies, 0}, {scratch, 0}, {fds, 8}]], + [ + begin + B = maps:get(K, Base), + A = maps:get(K, After), + A =< B + Slack orelse ct:fail({leak, K, B, A}) + end + || {K, Slack} <- [ + {processes, 5}, + {ports, 0}, + {refs, 0}, + {children, 0}, + {zombies, 0}, + {scratch, 0}, + {fds, 8} + ] + ], ok. beam_fd_count() -> @@ -186,11 +262,15 @@ beam_fd_count() -> %% Python processes started by this node: spawned children, zygotes and the %% sessions they forked (their command line is the zygote's) session_children() -> - Out = os:cmd("ps -ax -o command= 2>/dev/null | grep -E 'py_zygote.py|py_isolated_child.py' " - "| grep erlang_python_" ++ os:getpid() ++ " | grep -v grep | wc -l"), + Out = os:cmd( + "ps -ax -o command= 2>/dev/null | grep -E 'py_zygote.py|py_isolated_child.py' " + "| grep erlang_python_" ++ os:getpid() ++ " | grep -v grep | wc -l" + ), list_to_integer(string:trim(Out)). zombies() -> - Out = os:cmd("ps -ax -o stat=,command= 2>/dev/null | grep -E '^Z' " - "| grep -E 'python|py_zygote' | grep -v grep | wc -l"), + Out = os:cmd( + "ps -ax -o stat=,command= 2>/dev/null | grep -E '^Z' " + "| grep -E 'python|py_zygote' | grep -v grep | wc -l" + ), list_to_integer(string:trim(Out)). diff --git a/test/py_session_stress_SUITE.erl b/test/py_session_stress_SUITE.erl index b8e27e6..70d9ef8 100644 --- a/test/py_session_stress_SUITE.erl +++ b/test/py_session_stress_SUITE.erl @@ -19,13 +19,14 @@ -define(MOD, py_test_session). -all() -> [ - test_new_latency, - test_new_breakdown, - test_throughput, - test_call_overhead, - test_memory_per_session -]. +all() -> + [ + test_new_latency, + test_new_breakdown, + test_throughput, + test_call_overhead, + test_memory_per_session + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -65,12 +66,23 @@ test_new_latency(Config) -> py_context:stop(C), Us end, - Rows = [{fork, run(Session(Fork), N)}, - {spawn, run(Session(Spawn), 20)}, - %% warm: paced so the pool refills between sessions - {warm_spawn, [begin timer:sleep(80), (Session(Warm))() end || _ <- lists:seq(1, 20)]}, - {plain_isolated, run(Plain, 20)}], - [ct:print("new+call ~-15s p50 ~7.2f ms p99 ~7.2f ms", [K, p(L, 50), p(L, 99)]) || {K, L} <- Rows], + Rows = [ + {fork, run(Session(Fork), N)}, + {spawn, run(Session(Spawn), 20)}, + %% warm: paced so the pool refills between sessions + {warm_spawn, [ + begin + timer:sleep(80), + (Session(Warm))() + end + || _ <- lists:seq(1, 20) + ]}, + {plain_isolated, run(Plain, 20)} + ], + [ + ct:print("new+call ~-15s p50 ~7.2f ms p99 ~7.2f ms", [K, p(L, 50), p(L, 99)]) + || {K, L} <- Rows + ], ForkP50 = p(proplists:get_value(fork, Rows), 50), SpawnP50 = p(proplists:get_value(spawn, Rows), 50), true = ForkP50 < SpawnP50, @@ -81,9 +93,13 @@ test_new_latency(Config) -> test_new_breakdown(Config) -> T = template(Config, #{start => fork}), Samples = [breakdown(T) || _ <- lists:seq(1, 100)], - [ct:print("fork breakdown ~-8s p50 ~6.3f ms p99 ~6.3f ms", - [K, p([maps:get(K, S) || S <- Samples], 50), p([maps:get(K, S) || S <- Samples], 99)]) - || K <- [fork, accept, ready, total]], + [ + ct:print( + "fork breakdown ~-8s p50 ~6.3f ms p99 ~6.3f ms", + [K, p([maps:get(K, S) || S <- Samples], 50), p([maps:get(K, S) || S <- Samples], 99)] + ) + || K <- [fork, accept, ready, total] + ], ok. breakdown(T) -> @@ -97,7 +113,9 @@ breakdown(T) -> {ok, <<_:64/native, Len:32/native>>} = socket:recv(S, 12, 5000), {ok, _Ready} = socket:recv(S, Len, 5000), T3 = erlang:monotonic_time(microsecond), - socket:close(S), socket:close(L), file:delete(Path), + socket:close(S), + socket:close(L), + file:delete(Path), py_child:kill_os_pid(OsPid), #{fork => T1 - T0, accept => T2 - T1, ready => T3 - T2, total => T3 - T0}. @@ -105,14 +123,25 @@ breakdown(T) -> %% for one and two zygotes. test_throughput(Config) -> Secs = 3, - Rows = [begin - T = template(Config, #{start => fork, zygotes => Z}), - R = [{C, throughput(T, C, Secs)} || C <- [1, 8, 64]], - py_session:stop_template(T), - {Z, R} - end || Z <- [1, 2]], - [[ct:print("zygotes ~w callers ~2w: ~7.1f sessions/s p50 ~6.2f ms p99 ~7.2f ms", - [Z, C, length(L) / Secs, p(L, 50), p(L, 99)]) || {C, L} <- R] || {Z, R} <- Rows], + Rows = [ + begin + T = template(Config, #{start => fork, zygotes => Z}), + R = [{C, throughput(T, C, Secs)} || C <- [1, 8, 64]], + py_session:stop_template(T), + {Z, R} + end + || Z <- [1, 2] + ], + [ + [ + ct:print( + "zygotes ~w callers ~2w: ~7.1f sessions/s p50 ~6.2f ms p99 ~7.2f ms", + [Z, C, length(L) / Secs, p(L, 50), p(L, 99)] + ) + || {C, L} <- R + ] + || {Z, R} <- Rows + ], ok. throughput(T, Callers, Secs) -> @@ -132,25 +161,40 @@ throughput(T, Callers, Secs) -> end end, Pids = [spawn_link(fun() -> Self ! {done, self(), Loop([])} end) || _ <- lists:seq(1, Callers)], - lists:append([receive {done, P, L} -> L after 60000 -> ct:fail(caller_hung) end || P <- Pids]). + lists:append([ + receive + {done, P, L} -> L + after 60000 -> ct:fail(caller_hung) + end + || P <- Pids + ]). %% @doc A call in a session costs what it costs in an isolated context. test_call_overhead(Config) -> T = template(Config, #{start => fork}), {ok, S} = py_session:new(T), {ok, C} = py_context:new(#{mode => isolated, paths => [?config(test_dir, Config)]}), - Call = fun(Ctx) -> fun() -> element(1, us(fun() -> {ok, _} = py_context:call(Ctx, ?MOD, peek, []) end)) end end, - Reenter = fun(Ctx) -> fun() -> element(1, us(fun() -> {ok, 1} = py_context:call(Ctx, ?MOD, reenter, [1]) end)) end end, + Call = fun(Ctx) -> + fun() -> element(1, us(fun() -> {ok, _} = py_context:call(Ctx, ?MOD, peek, []) end)) end + end, + Reenter = fun(Ctx) -> + fun() -> element(1, us(fun() -> {ok, 1} = py_context:call(Ctx, ?MOD, reenter, [1]) end)) end + end, py:register_function(sess_reenter, fun([Ctx, N]) -> - {ok, R} = py_context:call(Ctx, ?MOD, reenter, [N - 1]), R + {ok, R} = py_context:call(Ctx, ?MOD, reenter, [N - 1]), + R end), try - Rows = [{session_call, run(Call(S), 5000)}, - {isolated_call, run(Call(C), 5000)}, - {session_reenter, run(Reenter(S), 2000)}, - {isolated_reenter, run(Reenter(C), 2000)}], - [ct:print("~-17s p50 ~6.1f us p99 ~6.1f us", [K, p(L, 50) * 1000, p(L, 99) * 1000]) - || {K, L} <- Rows], + Rows = [ + {session_call, run(Call(S), 5000)}, + {isolated_call, run(Call(C), 5000)}, + {session_reenter, run(Reenter(S), 2000)}, + {isolated_reenter, run(Reenter(C), 2000)} + ], + [ + ct:print("~-17s p50 ~6.1f us p99 ~6.1f us", [K, p(L, 50) * 1000, p(L, 99) * 1000]) + || {K, L} <- Rows + ], SessionP50 = p(proplists:get_value(session_call, Rows), 50), PlainP50 = p(proplists:get_value(isolated_call, Rows), 50), true = SessionP50 < PlainP50 * 2 @@ -163,16 +207,36 @@ test_call_overhead(Config) -> %% @doc Resident memory of 20 live sessions, forked vs spawned. A forked %% session shares the zygote's pages until it writes them. test_memory_per_session(Config) -> - Rows = [begin - T = template(Config, #{start => Start}), - Ss = [begin {ok, S} = py_session:new(T), S end || _ <- lists:seq(1, 20)], - Pids = [begin {ok, P} = py_context:call(S, ?MOD, pid, []), P end || S <- Ss], - Rss = [rss_kb(P) || P <- Pids], - [py_session:close(S) || S <- Ss], - {Start, Rss} - end || Start <- [fork, spawn]], - [ct:print("~-5s rss per session p50 ~7.1f MB (ps rss counts shared pages in full)", - [K, lists:nth(length(L) div 2 + 1, lists:sort(L)) / 1024]) || {K, L} <- Rows], + Rows = [ + begin + T = template(Config, #{start => Start}), + Ss = [ + begin + {ok, S} = py_session:new(T), + S + end + || _ <- lists:seq(1, 20) + ], + Pids = [ + begin + {ok, P} = py_context:call(S, ?MOD, pid, []), + P + end + || S <- Ss + ], + Rss = [rss_kb(P) || P <- Pids], + [py_session:close(S) || S <- Ss], + {Start, Rss} + end + || Start <- [fork, spawn] + ], + [ + ct:print( + "~-5s rss per session p50 ~7.1f MB (ps rss counts shared pages in full)", + [K, lists:nth(length(L) div 2 + 1, lists:sort(L)) / 1024] + ) + || {K, L} <- Rows + ], ok. %%% ============================================================================ @@ -180,8 +244,10 @@ test_memory_per_session(Config) -> %%% ============================================================================ template(Config, Opts) -> - {ok, T} = py_session:template(Opts#{paths => [?config(test_dir, Config)], - imports => [?MOD]}), + {ok, T} = py_session:template(Opts#{ + paths => [?config(test_dir, Config)], + imports => [?MOD] + }), T. run(F, N) -> diff --git a/test/py_stream_SUITE.erl b/test/py_stream_SUITE.erl index 57447b9..96e3afd 100644 --- a/test/py_stream_SUITE.erl +++ b/test/py_stream_SUITE.erl @@ -48,8 +48,13 @@ init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), %% Make test/py_test_agen.py importable for the async generator cases TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), Config. end_per_suite(_Config) -> diff --git a/test/py_stress_SUITE.erl b/test/py_stress_SUITE.erl index 5918a9a..8757559 100644 --- a/test/py_stress_SUITE.erl +++ b/test/py_stress_SUITE.erl @@ -33,18 +33,20 @@ all() -> [{group, stress_tests}]. groups() -> - [{stress_tests, [parallel], [ - context_churn_test, - concurrent_calls_test, - concurrent_evals_test, - callback_storm_test, - counter_balance_test, - parallel_context_operations_test - ]}, - {sequential_tests, [], [ - finalize_race_test, - rapid_start_stop_test - ]}]. + [ + {stress_tests, [parallel], [ + context_churn_test, + concurrent_calls_test, + concurrent_evals_test, + callback_storm_test, + counter_balance_test, + parallel_context_operations_test + ]}, + {sequential_tests, [], [ + finalize_race_test, + rapid_start_stop_test + ]} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -93,14 +95,22 @@ context_churn_test(_Config) -> Self = self(), %% Spawn processes that rapidly create/use/destroy contexts - Pids = [spawn_link(fun() -> - context_churn_worker(NumIterations, N), - Self ! {done, self()} - end) || N <- lists:seq(1, NumContexts)], + Pids = [ + spawn_link(fun() -> + context_churn_worker(NumIterations, N), + Self ! {done, self()} + end) + || N <- lists:seq(1, NumContexts) + ], %% Wait for all workers to complete - [receive {done, Pid} -> ok after 30000 -> ct:fail(timeout) end - || Pid <- Pids], + [ + receive + {done, Pid} -> ok + after 30000 -> ct:fail(timeout) + end + || Pid <- Pids + ], ok. @@ -117,13 +127,21 @@ concurrent_calls_test(_Config) -> NumCalls = 20, Self = self(), - Pids = [spawn_link(fun() -> - concurrent_call_worker(NumCalls), - Self ! {done, self()} - end) || _ <- lists:seq(1, NumProcesses)], - - [receive {done, Pid} -> ok after 30000 -> ct:fail(timeout) end - || Pid <- Pids], + Pids = [ + spawn_link(fun() -> + concurrent_call_worker(NumCalls), + Self ! {done, self()} + end) + || _ <- lists:seq(1, NumProcesses) + ], + + [ + receive + {done, Pid} -> ok + after 30000 -> ct:fail(timeout) + end + || Pid <- Pids + ], ok. @@ -139,13 +157,21 @@ concurrent_evals_test(_Config) -> NumEvals = 20, Self = self(), - Pids = [spawn_link(fun() -> - concurrent_eval_worker(NumEvals), - Self ! {done, self()} - end) || _ <- lists:seq(1, NumProcesses)], - - [receive {done, Pid} -> ok after 30000 -> ct:fail(timeout) end - || Pid <- Pids], + Pids = [ + spawn_link(fun() -> + concurrent_eval_worker(NumEvals), + Self ! {done, self()} + end) + || _ <- lists:seq(1, NumProcesses) + ], + + [ + receive + {done, Pid} -> ok + after 30000 -> ct:fail(timeout) + end + || Pid <- Pids + ], ok. @@ -168,9 +194,12 @@ callback_storm_test(_Config) -> %% Use py:eval with inline code - no stored state needed %% This avoids __main__ namespace conflicts in parallel tests NumCallbacks = 50, - Code = list_to_binary(io_lib:format( - "(lambda n, erl: len([erl.call('~s', i) for i in range(n)]))(~p, __import__('erlang'))", - [atom_to_list(CallbackName), NumCallbacks])), + Code = list_to_binary( + io_lib:format( + "(lambda n, erl: len([erl.call('~s', i) for i in range(n)]))(~p, __import__('erlang'))", + [atom_to_list(CallbackName), NumCallbacks] + ) + ), {ok, NumCallbacks} = py:eval(Code), @@ -198,17 +227,23 @@ do_finalize_race_test() -> %% Start some concurrent operations Self = self(), - Pids = [spawn(fun() -> - %% Each worker does some work - try - lists:foreach(fun(_) -> - py:eval(<<"1 + 1">>) - end, lists:seq(1, 10)) - catch - _:_ -> ok - end, - Self ! {done, self()} - end) || _ <- lists:seq(1, 5)], + Pids = [ + spawn(fun() -> + %% Each worker does some work + try + lists:foreach( + fun(_) -> + py:eval(<<"1 + 1">>) + end, + lists:seq(1, 10) + ) + catch + _:_ -> ok + end, + Self ! {done, self()} + end) + || _ <- lists:seq(1, 5) + ], %% Give workers a bit of time to start timer:sleep(10), @@ -217,7 +252,13 @@ do_finalize_race_test() -> ok = application:stop(erlang_python), %% Wait for workers to finish (they should handle shutdown gracefully) - [receive {done, Pid} -> ok after 5000 -> ok end || Pid <- Pids], + [ + receive + {done, Pid} -> ok + after 5000 -> ok + end + || Pid <- Pids + ], %% Restart for subsequent tests {ok, _} = application:ensure_all_started(erlang_python), @@ -229,9 +270,12 @@ do_finalize_race_test() -> counter_balance_test(_Config) -> %% Do some operations Ctx = py:context(1), - lists:foreach(fun(_) -> - {ok, _} = py:eval(Ctx, <<"1 + 1">>) - end, lists:seq(1, 100)), + lists:foreach( + fun(_) -> + {ok, _} = py:eval(Ctx, <<"1 + 1">>) + end, + lists:seq(1, 100) + ), %% Force GC erlang:garbage_collect(), @@ -278,16 +322,32 @@ parallel_context_operations_test(_Config) -> %% Spawn workers for each context - use py:eval with inline expressions %% to avoid __main__ namespace conflicts Self = self(), - Pids = [spawn_link(fun() -> - Results = [py:eval(Ctx, list_to_binary(io_lib:format("~p * ~p", [I, I]))) - || I <- lists:seq(1, NumOps)], - AllOk = lists:all(fun({ok, _}) -> true; (_) -> false end, Results), - Self ! {done, self(), AllOk} - end) || Ctx <- Contexts], + Pids = [ + spawn_link(fun() -> + Results = [ + py:eval(Ctx, list_to_binary(io_lib:format("~p * ~p", [I, I]))) + || I <- lists:seq(1, NumOps) + ], + AllOk = lists:all( + fun + ({ok, _}) -> true; + (_) -> false + end, + Results + ), + Self ! {done, self(), AllOk} + end) + || Ctx <- Contexts + ], %% Collect results - Results = [receive {done, Pid, Ok} -> Ok after 30000 -> false end - || Pid <- Pids], + Results = [ + receive + {done, Pid, Ok} -> Ok + after 30000 -> false + end + || Pid <- Pids + ], true = lists:all(fun(X) -> X end, Results), ok. @@ -304,18 +364,21 @@ rapid_start_stop_test(Config) -> do_rapid_start_stop_test() -> NumCycles = 5, - lists:foreach(fun(_) -> - %% Stop - ok = application:stop(erlang_python), - timer:sleep(50), + lists:foreach( + fun(_) -> + %% Stop + ok = application:stop(erlang_python), + timer:sleep(50), - %% Start - {ok, _} = application:ensure_all_started(erlang_python), - {ok, _} = py:start_contexts(), + %% Start + {ok, _} = application:ensure_all_started(erlang_python), + {ok, _} = py:start_contexts(), - %% Quick operation - {ok, 2} = py:eval(<<"1 + 1">>), - timer:sleep(50) - end, lists:seq(1, NumCycles)), + %% Quick operation + {ok, 2} = py:eval(<<"1 + 1">>), + timer:sleep(50) + end, + lists:seq(1, NumCycles) + ), ok. diff --git a/test/py_thread_affinity_SUITE.erl b/test/py_thread_affinity_SUITE.erl index 5dce505..9541ca7 100644 --- a/test/py_thread_affinity_SUITE.erl +++ b/test/py_thread_affinity_SUITE.erl @@ -86,12 +86,20 @@ multi_process_share_context_thread(_Config) -> setup_helper(Ctx), Parent = self(), N = 8, - Pids = [spawn(fun() -> - Tid = native_id(Ctx), - Parent ! {tid, self(), Tid} - end) || _ <- lists:seq(1, N)], - Tids = [receive {tid, Pid, T} -> T after 5000 -> ct:fail(timeout) end - || Pid <- Pids], + Pids = [ + spawn(fun() -> + Tid = native_id(Ctx), + Parent ! {tid, self(), Tid} + end) + || _ <- lists:seq(1, N) + ], + Tids = [ + receive + {tid, Pid, T} -> T + after 5000 -> ct:fail(timeout) + end + || Pid <- Pids + ], ct:pal("tids = ~p", [Tids]), [Single] = lists:usort(Tids), true = is_integer(Single), @@ -130,25 +138,40 @@ owngil_thread_affinity(_Config) -> "import threading\n" "_pta_exec_tid = threading.get_native_id()\n" >>), - {ok, ExecTid} = py_context:eval(Ctx, - <<"_pta_exec_tid">>, #{}), + {ok, ExecTid} = py_context:eval( + Ctx, + <<"_pta_exec_tid">>, + #{} + ), EvalTid = native_id(Ctx), - {ok, CallTid} = py_context:call(Ctx, - '__main__', - '_pta_get_tid', []), - ct:pal("owngil exec=~p eval=~p call=~p", - [ExecTid, EvalTid, CallTid]), + {ok, CallTid} = py_context:call( + Ctx, + '__main__', + '_pta_get_tid', + [] + ), + ct:pal( + "owngil exec=~p eval=~p call=~p", + [ExecTid, EvalTid, CallTid] + ), ExecTid = EvalTid, EvalTid = CallTid, Parent = self(), - Pids = [spawn(fun() -> - Tid = native_id(Ctx), - Parent ! {tid, self(), Tid} - end) || _ <- lists:seq(1, 4)], - Tids = [receive {tid, Pid, T} -> T - after 5000 -> ct:fail(timeout) - end || Pid <- Pids], + Pids = [ + spawn(fun() -> + Tid = native_id(Ctx), + Parent ! {tid, self(), Tid} + end) + || _ <- lists:seq(1, 4) + ], + Tids = [ + receive + {tid, Pid, T} -> T + after 5000 -> ct:fail(timeout) + end + || Pid <- Pids + ], ct:pal("owngil multi-proc tids = ~p", [Tids]), [Single] = lists:usort(Tids), Single = ExecTid, diff --git a/test/py_thread_callback_SUITE.erl b/test/py_thread_callback_SUITE.erl index 3e66492..c7af82c 100644 --- a/test/py_thread_callback_SUITE.erl +++ b/test/py_thread_callback_SUITE.erl @@ -63,14 +63,46 @@ init_per_testcase(_TestCase, Config) -> end_per_testcase(_TestCase, _Config) -> %% Cleanup any registered functions - try py:unregister_function(double_it) catch _:_ -> ok end, - try py:unregister_function(add_one) catch _:_ -> ok end, - try py:unregister_function(call_python_square) catch _:_ -> ok end, - try py:unregister_function(square_in_erlang) catch _:_ -> ok end, - try py:unregister_function(maybe_fail) catch _:_ -> ok end, - try py:unregister_function(get_id) catch _:_ -> ok end, - try py:unregister_function(async_double) catch _:_ -> ok end, - try py:unregister_function(async_blob) catch _:_ -> ok end, + try + py:unregister_function(double_it) + catch + _:_ -> ok + end, + try + py:unregister_function(add_one) + catch + _:_ -> ok + end, + try + py:unregister_function(call_python_square) + catch + _:_ -> ok + end, + try + py:unregister_function(square_in_erlang) + catch + _:_ -> ok + end, + try + py:unregister_function(maybe_fail) + catch + _:_ -> ok + end, + try + py:unregister_function(get_id) + catch + _:_ -> ok + end, + try + py:unregister_function(async_double) + catch + _:_ -> ok + end, + try + py:unregister_function(async_blob) + catch + _:_ -> ok + end, ok. %%% ============================================================================ @@ -83,7 +115,8 @@ threadpool_basic_test(_Config) -> %% Use a lambda that creates executor, submits task, gets result %% Need fromlist to properly import concurrent.futures submodule - Code = <<"(lambda cf, erl: cf.ThreadPoolExecutor(max_workers=1).__enter__().submit(lambda: erl.call('double_it', 5)).result())(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erl: cf.ThreadPoolExecutor(max_workers=1).__enter__().submit(lambda: erl.call('double_it', 5)).result())(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Result} = py:eval(Code), 10 = Result, ok. @@ -93,7 +126,8 @@ threadpool_concurrent_test(_Config) -> py:register_function(double_it, fun([X]) -> X * 2 end), %% Use executor.map to run calls in parallel - Code = <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=4).__enter__().map(lambda x: erl.call('double_it', x), range(20))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=4).__enter__().map(lambda x: erl.call('double_it', x), range(20))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Results} = py:eval(Code), Expected = [X * 2 || X <- lists:seq(0, 19)], Expected = Results, @@ -104,7 +138,8 @@ threadpool_multiple_calls_test(_Config) -> py:register_function(add_one, fun([X]) -> X + 1 end), %% Lambda that makes 3 sequential calls - Code = <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('add_one', erl.call('add_one', erl.call('add_one', x))), range(5))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('add_one', erl.call('add_one', erl.call('add_one', x))), range(5))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Results} = py:eval(Code), Expected = [X + 3 || X <- lists:seq(0, 4)], Expected = Results, @@ -119,7 +154,8 @@ threadpool_nested_callback_test(_Config) -> %% Call from thread pool, then use result in Python computation %% This tests that the result is properly returned and usable - Code = <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('square_in_erlang', x) + 1, range(5))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('square_in_erlang', x) + 1, range(5))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Results} = py:eval(Code), %% Results should be x^2 + 1 for x in 0..4 Expected = [(X * X) + 1 || X <- lists:seq(0, 4)], @@ -136,7 +172,8 @@ threadpool_error_handling_test(_Config) -> end), %% Lambda that catches exceptions - only calls maybe_fail for even numbers - Code = <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('maybe_fail', x) if x % 2 == 0 else 'error', range(4))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, + Code = + <<"(lambda cf, erl: list(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda x: erl.call('maybe_fail', x) if x % 2 == 0 else 'error', range(4))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('erlang'))">>, {ok, Results} = py:eval(Code), %% Even numbers succeed (doubled), odd numbers return 'error' [0, <<"error">>, 4, <<"error">>] = Results, @@ -147,7 +184,8 @@ threadpool_thread_reuse_test(_Config) -> py:register_function(get_id, fun([]) -> erlang:unique_integer() end), %% Get thread IDs and check that we have <= 2 unique threads - Code = <<"(lambda cf, th: len(set(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda _: th.get_ident(), range(10)))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('threading'))">>, + Code = + <<"(lambda cf, th: len(set(cf.ThreadPoolExecutor(max_workers=2).__enter__().map(lambda _: th.get_ident(), range(10)))))(__import__('concurrent.futures', fromlist=['ThreadPoolExecutor']), __import__('threading'))">>, {ok, ThreadCount} = py:eval(Code), true = (ThreadCount =< 2), ok. @@ -161,13 +199,14 @@ simple_thread_basic_test(_Config) -> py:register_function(double_it, fun([X]) -> X * 2 end), %% Create a threading.Thread subclass that stores its result - Code = <<" -(lambda: ( - __import__('threading').Thread(target=lambda: setattr(__import__('sys').modules[__name__], '_result', __import__('erlang').call('double_it', 5))).start() or - __import__('time').sleep(0.1) or - getattr(__import__('sys').modules[__name__], '_result', None) -))() -">>, + Code = << + "\n" + "(lambda: (\n" + " __import__('threading').Thread(target=lambda: setattr(__import__('sys').modules[__name__], '_result', __import__('erlang').call('double_it', 5))).start() or\n" + " __import__('time').sleep(0.1) or\n" + " getattr(__import__('sys').modules[__name__], '_result', None)\n" + "))()\n" + >>, {ok, Result} = py:eval(Code), 10 = Result, ok. @@ -177,18 +216,19 @@ simple_thread_multiple_calls_test(_Config) -> py:register_function(add_one, fun([X]) -> X + 1 end), %% Thread that makes 3 sequential calls: add_one(add_one(add_one(0))) - Code = <<" -(lambda: ( - __import__('threading').Thread(target=lambda: setattr( - __import__('sys').modules[__name__], '_result', - __import__('erlang').call('add_one', - __import__('erlang').call('add_one', - __import__('erlang').call('add_one', 0))) - )).start() or - __import__('time').sleep(0.1) or - getattr(__import__('sys').modules[__name__], '_result', None) -))() -">>, + Code = << + "\n" + "(lambda: (\n" + " __import__('threading').Thread(target=lambda: setattr(\n" + " __import__('sys').modules[__name__], '_result',\n" + " __import__('erlang').call('add_one',\n" + " __import__('erlang').call('add_one',\n" + " __import__('erlang').call('add_one', 0)))\n" + " )).start() or\n" + " __import__('time').sleep(0.1) or\n" + " getattr(__import__('sys').modules[__name__], '_result', None)\n" + "))()\n" + >>, {ok, Result} = py:eval(Code), 3 = Result, ok. @@ -198,17 +238,18 @@ simple_thread_concurrent_test(_Config) -> py:register_function(double_it, fun([X]) -> X * 2 end), %% Create 5 threads, each calling double_it with different values - Code = <<" -(lambda: ( - (threads := [__import__('threading').Thread(target=lambda x=x: setattr(t, 'result', __import__('erlang').call('double_it', x))) for x in range(5) for t in [type('T', (), {'result': None})()]]), - [setattr(threads[i], 'obj', type('T', (), {'result': None})()) for i in range(5)], - (workers := []), - [workers.append(type('Worker', (__import__('threading').Thread,), {'result': None, 'run': lambda self, x=x: setattr(self, 'result', __import__('erlang').call('double_it', x))})()) for x in range(5)], - [w.start() for w in workers], - [w.join() for w in workers], - [w.result for w in workers] -)[-1])() -">>, + Code = << + "\n" + "(lambda: (\n" + " (threads := [__import__('threading').Thread(target=lambda x=x: setattr(t, 'result', __import__('erlang').call('double_it', x))) for x in range(5) for t in [type('T', (), {'result': None})()]]),\n" + " [setattr(threads[i], 'obj', type('T', (), {'result': None})()) for i in range(5)],\n" + " (workers := []),\n" + " [workers.append(type('Worker', (__import__('threading').Thread,), {'result': None, 'run': lambda self, x=x: setattr(self, 'result', __import__('erlang').call('double_it', x))})()) for x in range(5)],\n" + " [w.start() for w in workers],\n" + " [w.join() for w in workers],\n" + " [w.result for w in workers]\n" + ")[-1])()\n" + >>, {ok, Results} = py:eval(Code), [0, 2, 4, 6, 8] = Results, ok. @@ -231,12 +272,12 @@ simple_thread_concurrent_test(_Config) -> threadpool_high_concurrency_test(_Config) -> py:register_function(add_one, fun([X]) -> X + 1 end), Code = << - "(lambda cf, erl: list(" - "cf.ThreadPoolExecutor(max_workers=8).__enter__().map(" - "lambda x: erl.call('add_one', erl.call('add_one', " - "erl.call('add_one', erl.call('add_one', erl.call('add_one', x))))), " - "range(200))))(__import__('concurrent.futures', " - "fromlist=['ThreadPoolExecutor']), __import__('erlang'))" + "(lambda cf, erl: list(" + "cf.ThreadPoolExecutor(max_workers=8).__enter__().map(" + "lambda x: erl.call('add_one', erl.call('add_one', " + "erl.call('add_one', erl.call('add_one', erl.call('add_one', x))))), " + "range(200))))(__import__('concurrent.futures', " + "fromlist=['ThreadPoolExecutor']), __import__('erlang'))" >>, Expected = [X + 5 || X <- lists:seq(0, 199)], lists:foreach( @@ -247,7 +288,8 @@ threadpool_high_concurrency_test(_Config) -> _ -> ct:fail({wrong_results_iter, I, Results}) end end, - lists:seq(1, 10)), + lists:seq(1, 10) + ), ok. %% @doc Stress the async thread-callback path (erlang.async_call from @@ -260,8 +302,13 @@ async_callback_concurrent_test(_Config) -> %% Add the existing test/ directory to sys.path so the Python %% helper module is importable. TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), %% Define a Python coroutine that gathers 50 erlang.async_call %% invocations and returns the result list. ok = py:exec(<< @@ -295,8 +342,13 @@ async_callback_large_payload_test(_Config) -> Payload = list_to_binary([($a + (I rem 26)) || I <- lists:seq(1, Size)]), py:register_function(async_blob, fun([_]) -> Payload end), TestDir = filename:join(code:lib_dir(erlang_python), "test"), - ok = py:exec(iolist_to_binary(io_lib:format( - "import sys; sys.path.insert(0, '~s')", [TestDir]))), + ok = py:exec( + iolist_to_binary( + io_lib:format( + "import sys; sys.path.insert(0, '~s')", [TestDir] + ) + ) + ), ok = py:exec(<< "import asyncio, erlang\n" "async def _gather_blobs():\n" diff --git a/test/py_venv_SUITE.erl b/test/py_venv_SUITE.erl index fa20239..2e7cb87 100644 --- a/test/py_venv_SUITE.erl +++ b/test/py_venv_SUITE.erl @@ -44,31 +44,39 @@ all() -> [{group, venv_tests}]. groups() -> - [{venv_tests, [sequence], [ - test_ensure_venv_creates_venv, - test_ensure_venv_activates_existing, - test_ensure_venv_with_requirements, - test_ensure_venv_installs_new_deps, - test_ensure_venv_force_recreate, - test_activate_venv, - test_deactivate_venv, - test_venv_info, - test_venv_path_metacharacters - ]}]. + [ + {venv_tests, [sequence], [ + test_ensure_venv_creates_venv, + test_ensure_venv_activates_existing, + test_ensure_venv_with_requirements, + test_ensure_venv_installs_new_deps, + test_ensure_venv_force_recreate, + test_activate_venv, + test_deactivate_venv, + test_venv_info, + test_venv_path_metacharacters + ]} + ]. init_per_suite(Config) -> application:ensure_all_started(erlang_python), %% Get Python executable path once for all tests - Expr = <<"(lambda: next((p for p in [__import__('os').path.join(__import__('sys').prefix, 'bin', f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python3'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python')] if __import__('os').path.isfile(p)), 'python3'))()">>, + Expr = + <<"(lambda: next((p for p in [__import__('os').path.join(__import__('sys').prefix, 'bin', f'python{__import__(\"sys\").version_info.major}.{__import__(\"sys\").version_info.minor}'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python3'), __import__('os').path.join(__import__('sys').prefix, 'bin', 'python')] if __import__('os').path.isfile(p)), 'python3'))()">>, {ok, PythonPath} = py:eval(Expr), %% Create a shared base venv once (without pip for speed) - SharedDir = filename:join(["/tmp", "py_venv_suite_" ++ integer_to_list(erlang:unique_integer([positive]))]), + SharedDir = filename:join([ + "/tmp", "py_venv_suite_" ++ integer_to_list(erlang:unique_integer([positive])) + ]), filelib:ensure_dir(filename:join(SharedDir, "dummy")), SharedVenv = filename:join(SharedDir, "shared_venv"), create_venv_fast(SharedVenv, binary_to_list(PythonPath)), - [{python_path, binary_to_list(PythonPath)}, - {shared_dir, SharedDir}, - {shared_venv, SharedVenv} | Config]. + [ + {python_path, binary_to_list(PythonPath)}, + {shared_dir, SharedDir}, + {shared_venv, SharedVenv} + | Config + ]. end_per_suite(Config) -> %% Clean up shared directory @@ -90,7 +98,9 @@ create_venv_fast(VenvPath, PythonPath) -> init_per_testcase(_TestCase, Config) -> %% Create unique temp directory for each test - TempDir = filename:join(["/tmp", "py_venv_test_" ++ integer_to_list(erlang:unique_integer([positive]))]), + TempDir = filename:join([ + "/tmp", "py_venv_test_" ++ integer_to_list(erlang:unique_integer([positive])) + ]), filelib:ensure_dir(filename:join(TempDir, "dummy")), [{temp_dir, TempDir} | Config]. diff --git a/test/py_worker_loop_SUITE.erl b/test/py_worker_loop_SUITE.erl index 3cf6e07..6dedbca 100644 --- a/test/py_worker_loop_SUITE.erl +++ b/test/py_worker_loop_SUITE.erl @@ -58,30 +58,32 @@ all() -> [{group, owngil}, {group, worker}]. groups() -> - [{owngil, [], [ - test_loop_ref_per_context, - test_start_stop_loop, - test_start_twice, - test_stop_idle, - test_calls_rejected_while_running, - test_submit_idle_and_running, - test_submit_errors_reported, - test_submit_ordering, - test_tcp_serve_on_dup_fd, - test_udp_serve_on_dup_fd, - test_adopt_accepted_fd, - test_three_workers_one_listen_fd, - test_channel_awaited_in_loop, - test_owner_death_stops_loop, - test_stop_context_while_looping, - test_interrupt_ends_loop, - test_long_call_no_30s_cap, - test_main_pool_unaffected, - test_churn_no_poll_reports, - test_preload_option, - test_bad_fd_rejected - ]}, - {worker, [], [test_worker_mode_single_loop]}]. + [ + {owngil, [], [ + test_loop_ref_per_context, + test_start_stop_loop, + test_start_twice, + test_stop_idle, + test_calls_rejected_while_running, + test_submit_idle_and_running, + test_submit_errors_reported, + test_submit_ordering, + test_tcp_serve_on_dup_fd, + test_udp_serve_on_dup_fd, + test_adopt_accepted_fd, + test_three_workers_one_listen_fd, + test_channel_awaited_in_loop, + test_owner_death_stops_loop, + test_stop_context_while_looping, + test_interrupt_ends_loop, + test_long_call_no_30s_cap, + test_main_pool_unaffected, + test_churn_no_poll_reports, + test_preload_option, + test_bad_fd_rejected + ]}, + {worker, [], [test_worker_mode_single_loop]} + ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(erlang_python), @@ -125,7 +127,8 @@ test_loop_ref_per_context(Config) -> true = L1 =/= L2, true = L1 =/= LMain, true = L2 =/= LMain, - stop_ctx(C1), stop_ctx(C2), + stop_ctx(C1), + stop_ctx(C2), ok. %% @doc start_loop returns once running; stop_loop returns once exited and @@ -135,7 +138,8 @@ test_start_stop_loop(Config) -> ok = py_context:start_loop(C), {ok, 3} = py_context:submit_await(C, py_test_workerloop, add, [1, 2]), ok = py_context:stop_loop(C), - receive {py_loop_exit, C, {ok, <<"stopped">>}} -> ok + receive + {py_loop_exit, C, {ok, <<"stopped">>}} -> ok after 2000 -> ct:fail(no_loop_exit) end, {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 5000), @@ -215,28 +219,44 @@ test_submit_ordering(Config) -> C = new_ctx(Config), ok = py_context:start_loop(C), {ok, LoopRef} = py_context:loop_ref(C), - Refs = [begin - R = make_ref(), - ok = py_nif:submit_task(LoopRef, self(), R, <<"py_test_workerloop">>, <<"add_traced">>, [I, 0], #{}), - {I, R} - end || I <- lists:seq(1, 500)], + Refs = [ + begin + R = make_ref(), + ok = py_nif:submit_task( + LoopRef, self(), R, <<"py_test_workerloop">>, <<"add_traced">>, [I, 0], #{} + ), + {I, R} + end + || I <- lists:seq(1, 500) + ], %% Collect within one overall deadline so a strand shows up as a count, %% not as a timetrap Deadline = erlang:monotonic_time(millisecond) + 30000, Results = collect_results(Refs, Deadline, #{}), - Bad = [{I, maps:get(R, Results, missing)} || {I, R} <- Refs, - maps:get(R, Results, missing) =/= {ok, I}], + Bad = [ + {I, maps:get(R, Results, missing)} + || {I, R} <- Refs, + maps:get(R, Results, missing) =/= {ok, I} + ], case Bad of - [] -> ok; - _ -> ct:log("~p of 500 tasks did not complete: ~p", [length(Bad), lists:sublist(Bad, 10)]), - ct:log("loop alive (sync): ~p", [py_context:submit_await(C, py_test_workerloop, sync_add, [1, 1])]), - ct:log("loop alive (coro): ~p", [py_context:submit_await(C, py_test_workerloop, add, [1, 1])]), - ct:log("mailbox: ~p", [erlang:process_info(self(), message_queue_len)]), - Alive = py_context:submit_await(C, py_test_workerloop, add, [1, 1]), - LoopState = py_context:submit_await(C, py_test_workerloop, loop_state, []), - ct:fail({tasks_incomplete, length(Bad), lists:sublist(Bad, 6), - {first_bad_index, element(1, hd(Bad))}, {loop_alive, Alive}, - {loop_state, LoopState}}) + [] -> + ok; + _ -> + ct:log("~p of 500 tasks did not complete: ~p", [length(Bad), lists:sublist(Bad, 10)]), + ct:log("loop alive (sync): ~p", [ + py_context:submit_await(C, py_test_workerloop, sync_add, [1, 1]) + ]), + ct:log("loop alive (coro): ~p", [ + py_context:submit_await(C, py_test_workerloop, add, [1, 1]) + ]), + ct:log("mailbox: ~p", [erlang:process_info(self(), message_queue_len)]), + Alive = py_context:submit_await(C, py_test_workerloop, add, [1, 1]), + LoopState = py_context:submit_await(C, py_test_workerloop, loop_state, []), + ct:fail( + {tasks_incomplete, length(Bad), lists:sublist(Bad, 6), + {first_bad_index, element(1, hd(Bad))}, {loop_alive, Alive}, + {loop_state, LoopState}} + ) end, ok = py_context:stop_loop(C), stop_ctx(C), @@ -296,7 +316,8 @@ test_adopt_accepted_fd(Config) -> {ok, <<"adopted">>} = py_context:submit_await(C, py_test_workerloop, adopt, [Dup]), %% Erlang gives up its copy; Python owns the dup gen_tcp:close(Conn), - receive {client, {ok, <<"ok:adopted?">>}} -> ok + receive + {client, {ok, <<"ok:adopted?">>}} -> ok after 3000 -> ct:fail(no_reply_through_adopted_fd) end, gen_tcp:close(LSock), @@ -310,12 +331,15 @@ test_three_workers_one_listen_fd(Config) -> {ok, LSock} = gen_tcp:listen(0, [binary, {ip, ?HOST}, {active, false}, {backlog, 512}]), {ok, Port} = inet:port(LSock), {ok, LFd} = inet:getfd(LSock), - lists:foreach(fun({I, C}) -> - ok = py_context:start_loop(C), - {ok, Dup} = py:dup_fd(LFd), - Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), - {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [Dup, Tag]) - end, lists:zip(lists:seq(1, 3), Ctxs)), + lists:foreach( + fun({I, C}) -> + ok = py_context:start_loop(C), + {ok, Dup} = py:dup_fd(LFd), + Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), + {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [Dup, Tag]) + end, + lists:zip(lists:seq(1, 3), Ctxs) + ), Replies = [roundtrip(Port, <<"x">>) || _ <- lists:seq(1, 300)], 300 = length([R || R <- Replies, binary:part(R, byte_size(R) - 4, 4) =:= <<"ok:x">>]), Tags = lists:usort([binary:part(R, 0, 3) || R <- Replies]), @@ -351,7 +375,11 @@ test_channel_awaited_in_loop(Config) -> test_owner_death_stops_loop(Config) -> C = new_ctx(Config), - Owner = spawn(fun() -> receive never -> ok end end), + Owner = spawn(fun() -> + receive + never -> ok + end + end), ok = py_context:start_loop(C, #{owner => Owner}), {ok, 3} = py_context:submit_await(C, py_test_workerloop, add, [1, 2]), exit(Owner, kill), @@ -369,7 +397,8 @@ test_stop_context_while_looping(Config) -> Elapsed = erlang:monotonic_time(millisecond) - T0, ct:log("stop while looping took ~p ms", [Elapsed]), true = Elapsed < 10000, - receive {py_loop_exit, C, {error, interrupted}} -> ok + receive + {py_loop_exit, C, {error, interrupted}} -> ok after 1000 -> ct:fail(no_interrupted_exit) end, false = is_process_alive(C), @@ -379,7 +408,8 @@ test_interrupt_ends_loop(Config) -> C = new_ctx(Config), ok = py_context:start_loop(C), ok = py_context:interrupt(C), - receive {py_loop_exit, C, {error, interrupted}} -> ok + receive + {py_loop_exit, C, {error, interrupted}} -> ok after 3000 -> ct:fail(no_interrupted_exit) end, {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 5000), @@ -399,10 +429,12 @@ test_long_call_no_30s_cap(Config) -> T0 = erlang:monotonic_time(millisecond), {ok, 2} = py_context:eval(Other, <<"1+1">>, #{}, 5000), true = erlang:monotonic_time(millisecond) - T0 < 1000, - receive {long, {ok, 7}} -> ok + receive + {long, {ok, 7}} -> ok after 40000 -> ct:fail(long_call_did_not_return) end, - stop_ctx(C), stop_ctx(Other), + stop_ctx(C), + stop_ctx(Other), ok. %% @doc Starting and stopping owngil contexts must not touch the main loop's @@ -426,13 +458,24 @@ test_churn_no_poll_reports(Config) -> N = 2000, Self = self(), Workers = 20, - [spawn_link(fun() -> - Fails = length([bad || _ <- lists:seq(1, N div Workers), - roundtrip(Port, <<"x">>) =/= <<"ok:x">>]), - Self ! {churn_done, Fails} - end) || _ <- lists:seq(1, Workers)], - Fails = lists:sum([receive {churn_done, F} -> F after 60000 -> N end - || _ <- lists:seq(1, Workers)]), + [ + spawn_link(fun() -> + Fails = length([ + bad + || _ <- lists:seq(1, N div Workers), + roundtrip(Port, <<"x">>) =/= <<"ok:x">> + ]), + Self ! {churn_done, Fails} + end) + || _ <- lists:seq(1, Workers) + ], + Fails = lists:sum([ + receive + {churn_done, F} -> F + after 60000 -> N + end + || _ <- lists:seq(1, Workers) + ]), 0 = Fails, timer:sleep(300), ok = py_context:stop_loop(C), @@ -445,12 +488,14 @@ test_churn_no_poll_reports(Config) -> ok. test_preload_option(Config) -> - Pre = <<"import sys, types\n" - "_m = types.ModuleType('preloaded_mod')\n" - "async def hello():\n" - " return 'hi'\n" - "_m.hello = hello\n" - "sys.modules['preloaded_mod'] = _m\n">>, + Pre = << + "import sys, types\n" + "_m = types.ModuleType('preloaded_mod')\n" + "async def hello():\n" + " return 'hi'\n" + "_m.hello = hello\n" + "sys.modules['preloaded_mod'] = _m\n" + >>, {ok, C} = py_context:new(#{mode => ?config(mode, Config), preload => Pre}), ok = py_context:start_loop(C), {ok, <<"hi">>} = py_context:submit_await(C, preloaded_mod, hello, []), @@ -484,7 +529,8 @@ test_worker_mode_single_loop(Config) -> {ok, 3} = py_context:submit_await(W1, py_test_workerloop, add, [1, 2]), {error, _} = py_context:start_loop(W2), ok = py_context:stop_loop(W1), - stop_ctx(W1), stop_ctx(W2), + stop_ctx(W1), + stop_ctx(W2), ok. %%% ============================================================================ @@ -492,11 +538,12 @@ test_worker_mode_single_loop(Config) -> %%% ============================================================================ log(#{msg := Msg}, #{config := Pid}) -> - Text = case Msg of - {string, S} -> unicode:characters_to_binary(S); - {report, R} -> unicode:characters_to_binary(io_lib:format("~p", [R])); - {Fmt, Args} -> unicode:characters_to_binary(io_lib:format(Fmt, Args)) - end, + Text = + case Msg of + {string, S} -> unicode:characters_to_binary(S); + {report, R} -> unicode:characters_to_binary(io_lib:format("~p", [R])); + {Fmt, Args} -> unicode:characters_to_binary(io_lib:format(Fmt, Args)) + end, case binary:match(Text, [<<"erts_poll">>, <<"stealing control">>]) of nomatch -> ok; _ -> Pid ! {poll_report, Text} @@ -504,7 +551,8 @@ log(#{msg := Msg}, #{config := Pid}) -> ok. collect_reports() -> - receive {poll_report, T} -> [T | collect_reports()] + receive + {poll_report, T} -> [T | collect_reports()] after 200 -> [] end. @@ -515,14 +563,22 @@ collect_reports() -> new_ctx(Config) -> {ok, C} = py_context:new(#{mode => ?config(mode, Config)}), TestDir = ?config(test_dir, Config), - Code = iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n" - "import py_test_workerloop\n", [TestDir, TestDir])), + Code = iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n" + "import py_test_workerloop\n", + [TestDir, TestDir] + ) + ), ok = py_context:exec(C, Code), C. stop_ctx(C) -> - try py_context:stop(C) catch _:_ -> ok end, + try + py_context:stop(C) + catch + _:_ -> ok + end, ok. listen_dup() -> @@ -535,10 +591,11 @@ listen_dup() -> roundtrip(Port, Data) -> {ok, S} = gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000), ok = gen_tcp:send(S, Data), - R = case gen_tcp:recv(S, 0, 5000) of - {ok, Bin} -> Bin; - Other -> Other - end, + R = + case gen_tcp:recv(S, 0, 5000) of + {ok, Bin} -> Bin; + Other -> Other + end, gen_tcp:close(S), R. @@ -562,13 +619,20 @@ wait_until(Fun, TimeoutMs) -> wait_until_loop(Fun, Deadline) -> case Fun() of - true -> ok; + true -> + ok; false -> case erlang:monotonic_time(millisecond) > Deadline of - true -> {error, timeout}; - false -> timer:sleep(50), wait_until_loop(Fun, Deadline) + true -> + {error, timeout}; + false -> + timer:sleep(50), + wait_until_loop(Fun, Deadline) end end. flush() -> - receive _ -> flush() after 0 -> ok end. + receive + _ -> flush() + after 0 -> ok + end. diff --git a/test/py_worker_loop_stress_SUITE.erl b/test/py_worker_loop_stress_SUITE.erl index b20cff6..fc9308a 100644 --- a/test/py_worker_loop_stress_SUITE.erl +++ b/test/py_worker_loop_stress_SUITE.erl @@ -34,14 +34,15 @@ -define(HOST, {127, 0, 0, 1}). -all() -> [ - test_churn_four_workers, - test_keepalive_connections_held, - test_start_stop_cycles, - test_submit_storm_under_traffic, - test_memory_cap_in_handler, - test_interrupt_wedged_loop -]. +all() -> + [ + test_churn_four_workers, + test_keepalive_connections_held, + test_start_stop_cycles, + test_submit_storm_under_traffic, + test_memory_cap_in_handler, + test_interrupt_wedged_loop + ]. init_per_suite(Config) -> case os:getenv("STRESS") of @@ -50,7 +51,8 @@ init_per_suite(Config) -> _ -> {ok, _} = application:ensure_all_started(erlang_python), case py_nif:owngil_supported() of - false -> {skip, "worker loops need OWN_GIL (Python 3.14+)"}; + false -> + {skip, "worker loops need OWN_GIL (Python 3.14+)"}; true -> TestDir = filename:dirname(code:which(?MODULE)), [{test_dir, TestDir} | Config] @@ -80,12 +82,15 @@ test_churn_four_workers(Config) -> Baseline = fd_count(), Ctxs = [new_ctx(Config) || _ <- lists:seq(1, 4)], {LSock, Port, LFd} = listen(), - lists:foreach(fun({I, C}) -> - ok = py_context:start_loop(C), - {ok, Dup} = py:dup_fd(LFd), - Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), - {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [Dup, Tag]) - end, lists:zip(lists:seq(1, 4), Ctxs)), + lists:foreach( + fun({I, C}) -> + ok = py_context:start_loop(C), + {ok, Dup} = py:dup_fd(LFd), + Tag = list_to_binary("w" ++ integer_to_list(I) ++ ":"), + {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve, [Dup, Tag]) + end, + lists:zip(lists:seq(1, 4), Ctxs) + ), N = 10000, Clients = 50, T0 = erlang:monotonic_time(millisecond), @@ -93,8 +98,10 @@ test_churn_four_workers(Config) -> Elapsed = erlang:monotonic_time(millisecond) - T0, Failed = length([R || R <- Replies, not is_binary(R)]), Tags = lists:usort([binary:part(R, 0, 3) || R <- Replies, is_binary(R)]), - ct:log("~p connections in ~p ms (~p conn/s), failed ~p, workers ~p", - [N, Elapsed, N * 1000 div max(1, Elapsed), Failed, Tags]), + ct:log( + "~p connections in ~p ms (~p conn/s), failed ~p, workers ~p", + [N, Elapsed, N * 1000 div max(1, Elapsed), Failed, Tags] + ), 0 = Failed, 4 = length(Tags), [ok = py_context:stop_loop(C) || C <- Ctxs], @@ -117,16 +124,22 @@ test_keepalive_connections_held(Config) -> {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve_keepalive, [Dup]), Ref = py_context:get_nif_ref(C), {ok, Mem0, _} = py_nif:context_memory_usage(Ref), - Socks = [begin - {ok, S} = gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000), - S - end || _ <- lists:seq(1, 1000)], + Socks = [ + begin + {ok, S} = gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000), + S + end + || _ <- lists:seq(1, 1000) + ], Rounds = 10, - lists:foreach(fun(_) -> - [ok = gen_tcp:send(S, <<"ping">>) || S <- Socks], - [{ok, <<"pong">>} = gen_tcp:recv(S, 4, 10000) || S <- Socks], - timer:sleep(2000) - end, lists:seq(1, Rounds)), + lists:foreach( + fun(_) -> + [ok = gen_tcp:send(S, <<"ping">>) || S <- Socks], + [{ok, <<"pong">>} = gen_tcp:recv(S, 4, 10000) || S <- Socks], + timer:sleep(2000) + end, + lists:seq(1, Rounds) + ), {ok, Mem1, _} = py_nif:context_memory_usage(Ref), ct:log("memory ~p -> ~p bytes with 1000 held connections", [Mem0, Mem1]), true = Mem1 < Mem0 + 256 * 1024 * 1024, @@ -146,17 +159,22 @@ test_start_stop_cycles(Config) -> Workers0 = length(supervisor:which_children(py_event_worker_sup)), Procs0 = erlang:system_info(process_count), {ok, Mem0, _} = py_nif:context_memory_usage(Ref), - lists:foreach(fun(I) -> - ok = py_context:start_loop(C), - {ok, I} = py_context:submit_await(C, py_test_workerloop, add, [I, 0]), - ok = py_context:stop_loop(C) - end, lists:seq(1, 200)), + lists:foreach( + fun(I) -> + ok = py_context:start_loop(C), + {ok, I} = py_context:submit_await(C, py_test_workerloop, add, [I, 0]), + ok = py_context:stop_loop(C) + end, + lists:seq(1, 200) + ), {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 5000), {ok, Mem1, _} = py_nif:context_memory_usage(Ref), Workers1 = length(supervisor:which_children(py_event_worker_sup)), Procs1 = erlang:system_info(process_count), - ct:log("workers ~p -> ~p, processes ~p -> ~p, memory ~p -> ~p", - [Workers0, Workers1, Procs0, Procs1, Mem0, Mem1]), + ct:log( + "workers ~p -> ~p, processes ~p -> ~p, memory ~p -> ~p", + [Workers0, Workers1, Procs0, Procs1, Mem0, Mem1] + ), Workers0 = Workers1, true = Procs1 =< Procs0 + 5, true = Mem1 < Mem0 + 64 * 1024 * 1024, @@ -173,23 +191,40 @@ test_submit_storm_under_traffic(Config) -> {ok, <<"serving">>} = py_context:submit_await(C, py_test_workerloop, serve_keepalive, [Dup]), Self = self(), Traffic = spawn_link(fun() -> - Socks = [element(2, gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000)) - || _ <- lists:seq(1, 100)], + Socks = [ + element(2, gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000)) + || _ <- lists:seq(1, 100) + ], traffic_loop(Socks, Self) end), Callers = 10, PerCaller = 1000, - [spawn_link(fun() -> - Refs = [element(2, py_context:submit(C, py_test_workerloop, add, [I, 0])) - || I <- lists:seq(1, PerCaller)], - Results = [py_event_loop:await(R, 30000) || R <- Refs], - Self ! {storm, Results} - end) || _ <- lists:seq(1, Callers)], - AllOk = lists:all(fun(Results) -> - Results =:= [{ok, I} || I <- lists:seq(1, PerCaller)] - end, [receive {storm, Rs} -> Rs after 120000 -> [] end || _ <- lists:seq(1, Callers)]), + [ + spawn_link(fun() -> + Refs = [ + element(2, py_context:submit(C, py_test_workerloop, add, [I, 0])) + || I <- lists:seq(1, PerCaller) + ], + Results = [py_event_loop:await(R, 30000) || R <- Refs], + Self ! {storm, Results} + end) + || _ <- lists:seq(1, Callers) + ], + AllOk = lists:all( + fun(Results) -> + Results =:= [{ok, I} || I <- lists:seq(1, PerCaller)] + end, + [ + receive + {storm, Rs} -> Rs + after 120000 -> [] + end + || _ <- lists:seq(1, Callers) + ] + ), Traffic ! stop, - receive {traffic_done, Exchanged} -> ct:log("traffic exchanged ~p messages", [Exchanged]) + receive + {traffic_done, Exchanged} -> ct:log("traffic exchanged ~p messages", [Exchanged]) after 30000 -> ct:fail(traffic_did_not_stop) end, true = AllOk, @@ -238,10 +273,11 @@ test_interrupt_wedged_loop(Config) -> timer:sleep(200), T0 = erlang:monotonic_time(millisecond), ok = py_context:interrupt(C), - receive {py_loop_exit, C, {error, interrupted}} -> - Elapsed = erlang:monotonic_time(millisecond) - T0, - ct:log("wedged loop interrupted after ~p ms", [Elapsed]), - true = Elapsed < 6000 + receive + {py_loop_exit, C, {error, interrupted}} -> + Elapsed = erlang:monotonic_time(millisecond) - T0, + ct:log("wedged loop interrupted after ~p ms", [Elapsed]), + true = Elapsed < 6000 after 10000 -> ct:fail(loop_not_interrupted) end, {ok, 4} = py_context:eval(C, <<"2+2">>, #{}, 5000), @@ -259,13 +295,21 @@ new_ctx(Config) -> setup_ctx(C, Config) -> TestDir = ?config(test_dir, Config), - Code = iolist_to_binary(io_lib:format( - "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n" - "import py_test_workerloop\n", [TestDir, TestDir])), + Code = iolist_to_binary( + io_lib:format( + "import sys\nif '~s' not in sys.path:\n sys.path.insert(0, '~s')\n" + "import py_test_workerloop\n", + [TestDir, TestDir] + ) + ), ok = py_context:exec(C, Code). stop_ctx(C) -> - try py_context:stop(C) catch _:_ -> ok end, + try + py_context:stop(C) + catch + _:_ -> ok + end, ok. listen() -> @@ -278,10 +322,11 @@ roundtrip(Port, Data) -> case gen_tcp:connect(?HOST, Port, [binary, {active, false}], 5000) of {ok, S} -> ok = gen_tcp:send(S, Data), - R = case gen_tcp:recv(S, 0, 5000) of - {ok, Bin} -> Bin; - Other -> Other - end, + R = + case gen_tcp:recv(S, 0, 5000) of + {ok, Bin} -> Bin; + Other -> Other + end, gen_tcp:close(S), R; Error -> @@ -291,10 +336,19 @@ roundtrip(Port, Data) -> parallel_roundtrips(Port, N, Clients) -> Self = self(), Per = N div Clients, - [spawn_link(fun() -> - Self ! {rt, [roundtrip(Port, <<"x">>) || _ <- lists:seq(1, Per)]} - end) || _ <- lists:seq(1, Clients)], - lists:append([receive {rt, L} -> L after 300000 -> [] end || _ <- lists:seq(1, Clients)]). + [ + spawn_link(fun() -> + Self ! {rt, [roundtrip(Port, <<"x">>) || _ <- lists:seq(1, Per)]} + end) + || _ <- lists:seq(1, Clients) + ], + lists:append([ + receive + {rt, L} -> L + after 300000 -> [] + end + || _ <- lists:seq(1, Clients) + ]). traffic_loop(Socks, Parent) -> traffic_loop(Socks, Parent, 0). @@ -330,11 +384,12 @@ fd_count() -> end. log(#{msg := Msg}, #{config := Pid}) -> - Text = case Msg of - {string, S} -> unicode:characters_to_binary(S); - {report, R} -> unicode:characters_to_binary(io_lib:format("~p", [R])); - {Fmt, Args} -> unicode:characters_to_binary(io_lib:format(Fmt, Args)) - end, + Text = + case Msg of + {string, S} -> unicode:characters_to_binary(S); + {report, R} -> unicode:characters_to_binary(io_lib:format("~p", [R])); + {Fmt, Args} -> unicode:characters_to_binary(io_lib:format(Fmt, Args)) + end, case binary:match(Text, [<<"erts_poll">>, <<"stealing control">>]) of nomatch -> ok; _ -> Pid ! {poll_report, Text} @@ -342,9 +397,13 @@ log(#{msg := Msg}, #{config := Pid}) -> ok. collect_reports() -> - receive {poll_report, T} -> [T | collect_reports()] + receive + {poll_report, T} -> [T | collect_reports()] after 200 -> [] end. flush() -> - receive _ -> flush() after 0 -> ok end. + receive + _ -> flush() + after 0 -> ok + end.