Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix binding generation for lists; add cli test #46

Merged
merged 3 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "componentize-py"
version = "0.7.0"
version = "0.7.1"
edition = "2021"
exclude = ["cpython"]

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ Next, create or download the WIT world you'd like to target, e.g.:

```shell
cat >hello.wit <<EOF
package example:hello
package example:hello;
world hello {
export hello: func() -> string
export hello: func() -> string;
}
EOF
```
Expand Down
35 changes: 35 additions & 0 deletions examples/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Example: `cli`

This is an example of how to use [componentize-py] and [Wasmtime] to build and
run a Python-based component targetting the [wasi-cli] `command` world.

Note that, as of this writing, `wasi-cli` has not yet stabilized. Here we use a
snapshot, which may differ from later revisions.

[componentize-py]: https://github.com/bytecodealliance/componentize-py
[Wasmtime]: https://github.com/bytecodealliance/wasmtime
[wasi-cli]: https://github.com/WebAssembly/wasi-cli

## Prerequisites

* `Wasmtime` 15.0.1 (later versions may use a different, incompatible `wasi-cli` snapshot)
* `componentize-py` 0.7.1

Below, we use [Rust](https://rustup.rs/)'s `cargo` to install `Wasmtime` since,
as of this writing, 15.0.1 has not yet been released. Once it has been
released, you'll be able to download and install from
https://github.com/bytecodealliance/wasmtime/releases/tag/v15.0.1.

```
cargo install --locked --git https://github.com/bytecodealliance/wasmtime --branch release-15.0.0 wasmtime-cli
pip install componentize-py
```

## Running the demo

```
componentize-py -d ../../wit -w wasi:cli/command@0.2.0-rc-2023-11-10 componentize app -o cli.wasm
wasmtime run --wasm component-model cli.wasm
```

The `wasmtime run` command above should print "Hello, world!".
5 changes: 5 additions & 0 deletions examples/cli/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from command import exports

class Run(exports.Run):
def run(self):
print("Hello, world!")
6 changes: 3 additions & 3 deletions examples/http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ which may differ from later revisions.

## Prerequisites

* `Wasmtime` 14.0.3 (later versions may use a different, incompatible `wasi-http` snapshot)
* `componentize-py` 0.7.0
* `Wasmtime` 15.0.0 (later versions may use a different, incompatible `wasi-http` snapshot)
* `componentize-py` 0.7.1

Below, we use [Rust](https://rustup.rs/)'s `cargo` to install `Wasmtime`. If
you don't have `cargo`, you can download and install from
Expand All @@ -30,7 +30,7 @@ pip install componentize-py
First, build the app and run it:

```
componentize-py -d wit -w wasi:http/proxy@0.2.0-rc-2023-11-10 componentize app -o http.wasm
componentize-py -d ../../wit -w wasi:http/proxy@0.2.0-rc-2023-11-10 componentize app -o http.wasm
wasmtime serve http.wasm
```

Expand Down
18 changes: 0 additions & 18 deletions examples/http/wit/deps/cli/environment.wit

This file was deleted.

22 changes: 0 additions & 22 deletions examples/http/wit/test.wit

This file was deleted.

46 changes: 46 additions & 0 deletions examples/matrix-math/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Example: `matrix-math`

This is an example of how to use [componentize-py] to build a CLI app that does
matrix multiplication using [NumPy] inside a sandboxed environment. This
demonstrates using a non-trivial Python package containing native extensions
within a guest component.

[componentize-py]: https://github.com/bytecodealliance/componentize-py
[NumPy]: https://numpy.org

## Prerequisites

* `wasmtime` 15.0.1 (later versions may use a different, incompatible `wasi-cli` snapshot)
* `componentize-py` 0.7.1
* `NumPy`, built for WASI

Note that we use an unofficial build of NumPy since the upstream project does
not yet publish WASI builds.

Below, we use [Rust](https://rustup.rs/)'s `cargo` to install `Wasmtime` since,
as of this writing, 15.0.1 has not yet been released. Once it has been
released, you'll be able to download and install from
https://github.com/bytecodealliance/wasmtime/releases/tag/v15.0.1.

```
cargo install --locked --git https://github.com/bytecodealliance/wasmtime --branch release-15.0.0 wasmtime-cli
pip install componentize-py
curl -OL https://github.com/dicej/wasi-wheels/releases/download/canary/numpy-wasi.tar.gz
tar xf numpy-wasi.tar.gz
```

## Running the demo

```
componentize-py -d wit -w matrix-math componentize app -o matrix-math.wasm

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
componentize-py -d wit -w matrix-math componentize app -o matrix-math.wasm
componentize-py -d ../../wit -w matrix-math componentize app -o matrix-math.wasm

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dicej when I run this I get the following error:

$ componentize-py -d ../../wit -w matrix-math componentize app -o matrix-math.wasm
thread '<unnamed>' panicked at src/summary.rs:1183:89:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Traceback (most recent call last):
  File "/opt/homebrew/bin/componentize-py", line 8, in <module>
    sys.exit(script())
             ^^^^^^^^
pyo3_runtime.PanicException: called `Option::unwrap()` on a `None` value

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's part of what this PR fixes. You'll either need to build componentize-py from the branch this PR intends to merge, or wait until it's merged and I've published v0.7.1 to PyPI.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll merge this and do a release once CI finishes.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

v0.7.1 is live: https://pypi.org/project/componentize-py/
If you install that, plus Wasmtime from the release-15.0.0 branch (e.g. cargo install --locked --git https://github.com/bytecodealliance/wasmtime --branch release-15.0.0 wasmtime-cli), you should be able to run either of the CLI examples.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @dicej, sorry for the delay in testing this out. I was able to test it out again and running the matrix-math example, I get the following error:

$ wasmtime run --wasm component-model matrix-math.wasm '[[1, 2], [4, 5], [6, 7]]' '[[1, 2, 3], [4, 5, 6]]'

Error: failed to run main module `matrix-math.wasm`

Caused by:
    0: import `wasi:random/insecure@0.2.0-rc-2023-11-10` has the wrong type
    1: instance export `get-insecure-random-bytes` has the wrong type
    2: expected func found nothing

I'm pretty sure I updated all my deps to the latest. Any ideas?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does wasmtime --version report? It needs to be 15.0.1 (or later), which includes bytecodealliance/wasmtime#7613, which addresses this issue.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doh you're right! I was still using v15.0.0. I did the cargo install for the new version, but forgot that I had originally installed via bash, so cargo did install the new version but my path was using the bash installed version.

After upgrading this all worked. Thanks for being so patient and for getting this working! =)

wasmtime run --wasm component-model matrix-math.wasm '[[1, 2], [4, 5], [6, 7]]' '[[1, 2, 3], [4, 5, 6]]'
```

The second command above should print the following:

```
matrix_multiply received arguments [[1, 2], [4, 5], [6, 7]] and [[1, 2, 3], [4, 5, 6]]
[[9, 12, 15], [24, 33, 42], [34, 47, 60]]
```

If you run into any problems, please file an issue!
23 changes: 23 additions & 0 deletions examples/matrix-math/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# This app can either be used as a library (by calling `matrix-math#multiply`)
# or a CLI command (by calling `wasi:cli/run#run`)

import sys
import numpy
import matrix_math
from matrix_math import exports
from matrix_math.types import Err

class MatrixMath(matrix_math.MatrixMath):
def multiply(self, a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
print(f"matrix_multiply received arguments {a} and {b}")
return numpy.matmul(a, b).tolist()

class Run(exports.Run):
def run(self):
args = sys.argv[1:]
if len(args) != 2:
print(f"usage: matrix-math <matrix> <matrix> (got {args})", file=sys.stderr)
exit(-1)

print(MatrixMath().multiply(eval(args[0]), eval(args[1])))

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ features = ["pyo3/extension-module"]

[project]
name = "componentize-py"
version = "0.7.0"
version = "0.7.1"
description = "Tool to package Python applications as WebAssembly components"
readme = "README.md"
license = { file = "LICENSE" }
Expand Down
40 changes: 31 additions & 9 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use {
ffi::c_void,
mem::{self, MaybeUninit},
ptr, slice, str,
sync::Once,
},
wasi::cli::environment,
};
Expand All @@ -41,6 +42,7 @@ static ERR_CONSTRUCTOR: OnceCell<PyObject> = OnceCell::new();
static FINALIZE: OnceCell<PyObject> = OnceCell::new();
static DROP_RESOURCE: OnceCell<PyObject> = OnceCell::new();
static SEED: OnceCell<PyObject> = OnceCell::new();
static ARGV: OnceCell<Py<PyList>> = OnceCell::new();

const DISCRIMINANT_FIELD_INDEX: i32 = 0;
const PAYLOAD_FIELD_INDEX: i32 = 1;
Expand Down Expand Up @@ -335,6 +337,18 @@ fn do_init(app_name: String, symbols: Symbols) -> Result<()> {
SEED.set(py.import("random")?.getattr("seed")?.into())
.unwrap();

let argv = py
.import("sys")?
.getattr("argv")?
.downcast::<PyList>()
.unwrap();

for i in 0..argv.len() {
argv.del_item(i)?;
}

ARGV.set(argv.into()).unwrap();

Ok(())
})
}
Expand Down Expand Up @@ -388,16 +402,24 @@ pub unsafe extern "C" fn componentize_py_dispatch(
// todo: is this sound, or do we need to `.into_iter().map(MaybeUninit::assume_init).collect()` instead?
let params_lifted = mem::transmute::<Vec<MaybeUninit<&PyAny>>, Vec<&PyAny>>(params_lifted);

// We must call directly into the host to get the runtime environment since libc's version will only
// contain the build-time pre-init snapshot.
let environ = ENVIRON.get().unwrap().as_ref(py);
for (k, v) in environment::get_environment() {
environ.set_item(k, v).unwrap();
}
static ONCE: Once = Once::new();
ONCE.call_once(|| {
// We must call directly into the host to get the runtime environment since libc's version will only
// contain the build-time pre-init snapshot.
let environ = ENVIRON.get().unwrap().as_ref(py);
for (k, v) in environment::get_environment() {
environ.set_item(k, v).unwrap();
}

// Likewise for CLI arguments.
for arg in environment::get_arguments() {
ARGV.get().unwrap().as_ref(py).append(arg).unwrap();
}

// Call `random.seed()` to ensure we get a fresh seed rather than the one that got baked in during
// pre-init.
SEED.get().unwrap().call0(py).unwrap();
// Call `random.seed()` to ensure we get a fresh seed rather than the one that got baked in during
// pre-init.
SEED.get().unwrap().call0(py).unwrap();
});

let export = &EXPORTS.get().unwrap()[export];
let result = match export {
Expand Down
6 changes: 3 additions & 3 deletions src/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1554,7 +1554,6 @@ class {camel}(Protocol):
self.has_imported_and_exported_resource(Type::Id(*resource))
}
TypeDefKind::Enum(_) | TypeDefKind::Flags(_) => false,
TypeDefKind::Option(ty) => self.has_imported_and_exported_resource(*ty),
TypeDefKind::Result(result) => {
result
.ok
Expand All @@ -1569,8 +1568,9 @@ class {camel}(Protocol):
.types
.iter()
.any(|ty| self.has_imported_and_exported_resource(*ty)),
TypeDefKind::List(_) => true,
TypeDefKind::Type(ty) => self.has_imported_and_exported_resource(*ty),
TypeDefKind::Option(ty) | TypeDefKind::List(ty) | TypeDefKind::Type(ty) => {
self.has_imported_and_exported_resource(*ty)
}
TypeDefKind::Resource => {
let empty = &ResourceInfo::default();
let info = self.resource_info.get(&id).unwrap_or(empty);
Expand Down
File renamed without changes.
File renamed without changes.
2 changes: 0 additions & 2 deletions wit/deps/cli/environment.wit
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
package wasi:cli@0.2.0-rc-2023-11-10;

interface environment {
/// Get the POSIX-style environment variables.
///
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 5 additions & 0 deletions wit/matrix-math.wit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
world matrix-math {
include wasi:cli/command@0.2.0-rc-2023-11-10;

export multiply: func(a: list<list<float64>>, b: list<list<float64>>) -> result<list<list<float64>>, string>;
}
Loading