Skip to content
Open
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
141 changes: 141 additions & 0 deletions ci/scripts/r_wasm_test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

// Smoke-test and run the testthat suite for the arrow R package under webR.
//
// This script is called by r_wasm_test.sh after it sets up the CRAN-like
// repo and installs the webr npm package.
//
// Environment variables:
// ARROW_WASM_REPO_DIR - path to the local CRAN-like repo containing
// the arrow wasm binary package

const { WebR } = require("webr");
const http = require("http");
const fs = require("fs");
const path = require("path");

const repoDir = process.env.ARROW_WASM_REPO_DIR;
if (!repoDir) {
console.error("ERROR: ARROW_WASM_REPO_DIR not set");
process.exit(1);
}

async function main() {
// Serve the local repo over HTTP so webR (Emscripten) can access it.
// webR's R runs in an Emscripten sandbox and cannot access the host
// filesystem directly — it fetches packages over HTTP instead.
const server = http.createServer((req, res) => {
const filePath = path.join(repoDir, decodeURIComponent(req.url));
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end();
} else {
res.writeHead(200);
res.end(data);
}
});
});
server.listen(8080);
console.log("✓ Repo server on :8080");

const webR = new WebR({
RArgs: ["--quiet"],
interactive: false,
});

await webR.init();
console.log("✓ webR initialized");

// Install the arrow Wasm package, put localhost:8080 before repo.r-wasm.org
// (which is used for deps)
await webR.installPackages(["arrow"], {
repos: ["http://localhost:8080", "https://repo.r-wasm.org"],
quiet: false,
mount: false,
});
console.log("✓ arrow installed");

// Install test deps. TOOD: This is flakey. We could parse the DESCRIPTION
// file to be more robust.
await webR.installPackages(
["testthat", "tibble", "dplyr", "withr", "pillar"],
{
repos: ["https://repo.r-wasm.org"],
quiet: false,
mount: false,
},
);
console.log("✓ test dependencies installed");

// Test the package loads and functions basically
const loadResult = await webR.evalRString(`
library(arrow)
cat("arrow loaded\\n")
cat("R.version$os =", R.version$os, "\\n")
use_threads <- getOption("arrow.use_threads")
cat("arrow.use_threads =", use_threads, "\\n")
stopifnot(identical(use_threads, FALSE))
tab <- arrow::as_arrow_table(data.frame(x = 1:10, y = letters[1:10]))
stopifnot(nrow(tab) == 10L)
cat("Created Arrow table with", nrow(tab), "rows\\n")
"PASS"
`);

if (loadResult !== "PASS") {
console.error("Package load test FAILED");
await webR.close();
server.close();
process.exit(1);
}
console.log("✓ Package loads and works correctly");

// Run tests
console.log("Running testthat suite under webR...");

const testResult = await webR.evalRString(`
library(testthat)
library(arrow)
results <- testthat::test_package("arrow", reporter = "summary", stop_on_failure = FALSE)
df <- as.data.frame(results)
n_pass <- sum(df$passed)
n_skip <- sum(df$skipped)
n_fail <- sum(df$failed)
n_error <- sum(df$error)
cat(sprintf("Results: %d passed, %d skipped, %d failed, %d errors\\n",
n_pass, n_skip, n_fail, n_error))
if (n_fail > 0 || n_error > 0) "FAIL" else "PASS"
`);

if (testResult !== "PASS") {
console.error("testthat suite FAILED");
await webR.close();
server.close();
process.exit(1);
}
console.log("✓ testthat suite passed");

console.log("✓ All tests passed!");
await webR.close();
server.close();
}

main().catch((e) => {
console.error("FAILED:", e);
process.exit(1);
});
80 changes: 80 additions & 0 deletions ci/scripts/r_wasm_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

# Test the arrow R package built for WebAssembly.
#
# This script is intended to run inside the ghcr.io/r-universe-org/build-wasm
# Docker container after rwasm::build() has produced a .tgz binary. It:
# 1. Sets up a CRAN-like repo structure from the built .tgz
# 2. Installs the npm webr package (Node.js webR runtime)
# 3. Boots webR, installs arrow from the local repo, and verifies:
# - The package can be installed and loaded
# - Multithreading is disabled (arrow.use_threads == FALSE)
# - The testthat test suite runs
#
# Tests that require threading are automatically skipped via
# skip_if_not(CanRunWithCapturedR()) since CanRunWithCapturedR() returns
# FALSE under Emscripten.
#
# Usage:
# r_wasm_test.sh <path-to-arrow-r-dir>
#
# Example:
# r_wasm_test.sh /work
#
# The arrow .tgz file(s) should already exist in <path-to-arrow-r-dir>.

set -euxo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
arrow_r_dir="${1:-.}"

# Set up a fake CRAN-like repo so we can install the package
tgz_file=$(ls "${arrow_r_dir}"/arrow_*.tgz 2>/dev/null | head -1)
if [ -z "${tgz_file}" ]; then
echo "ERROR: No arrow_*.tgz found in ${arrow_r_dir}" >&2
exit 1
fi
echo "Found Wasm binary: ${tgz_file}"

repo_dir=$(mktemp -d)
# TODO: Not sure if we need this
# Cover multiple R minor versions in case the npm webr package
# uses a different R version than the Docker image's build R.
for r_ver in 4.4 4.5 4.6; do
contrib_dir="${repo_dir}/bin/emscripten/contrib/${r_ver}"
mkdir -p "${contrib_dir}"
cp "${tgz_file}" "${contrib_dir}/"
# type=mac.binary matches .tgz file extension
R -q -e "tools::write_PACKAGES('${contrib_dir}', type = 'mac.binary')"
done

echo "Repo structure:"
find "${repo_dir}" -type f

# Install webr in a temporary node project
work_dir=$(mktemp -d)
cd "${work_dir}"
npm init -y > /dev/null 2>&1
npm install --silent webr 2>/dev/null

# Run our test script
ARROW_WASM_REPO_DIR="${repo_dir}" node "${SCRIPT_DIR}/r_wasm_test.cjs"

# Cleanup temp dirs
rm -rf "${work_dir}" "${repo_dir}"
11 changes: 10 additions & 1 deletion dev/tasks/r/github.linux.r-wasm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

jobs:
r-universe-wasm:
name: "R-universe Wasm build"
name: "R-universe Wasm build and test"
runs-on: ubuntu-latest
timeout-minutes: 60

Expand Down Expand Up @@ -56,6 +56,15 @@ jobs:
2>&1 | tee build-wasm.log
'

- name: Smoke-test arrow in webR
shell: bash
run: |
docker run --rm \
-v "${PWD}/arrow:/arrow" \
-w /tmp \
ghcr.io/r-universe-org/build-wasm:latest \
bash /arrow/ci/scripts/r_wasm_test.sh /arrow/r

- name: List generated artifacts
if: always()
shell: bash
Expand Down
5 changes: 5 additions & 0 deletions r/R/arrow-package.R
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ s3_finalizer <- new.env(parent = emptyenv())
# needs the C++ library loaded
create_binding_cache()

if (identical(R.version$os, "emscripten")) {
# Disable multithreading on Wasm/Emscripten
options(arrow.use_threads = FALSE)
}

if (tolower(Sys.info()[["sysname"]]) == "windows") {
# Disable multithreading on Windows
# See https://issues.apache.org/jira/browse/ARROW-8379
Expand Down
11 changes: 10 additions & 1 deletion r/src/safe-call-into-r-impl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,16 @@ bool SetEnableSignalStopSource(bool enabled) {
}

// [[arrow::export]]
bool CanRunWithCapturedR() { return MainRThread::GetInstance().Executor() == nullptr; }
bool CanRunWithCapturedR() {
#ifdef __EMSCRIPTEN__
// Threading is not supported under Emscripten/WASM. Always take the
// synchronous path to avoid attempting pthread_create which will fail
// with "thread constructor failed: Not supported".
return false;
#else
return MainRThread::GetInstance().Executor() == nullptr;
#endif
Comment on lines +48 to +56
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is it possible to add a test (or maybe it's that we actually need to run the tests under wasm(???) to catch this?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It looks like maybe we can at least run some R code in the container if not run the test suite. I'll report back.

}

// [[arrow::export]]
std::string TestSafeCallIntoR(cpp11::function r_fun_that_returns_a_string,
Expand Down