Unverified Commit 4811e49e authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

test(turbo-tasks): run the wasm tests with a Node wasi host (#97789)

### What?

Adds a Node host so `wasm32-wasip1-threads` test binaries can run, and
wires the `turbo-rcstr`, `turbo-tasks`, and `turbo-tasks-backend`
library tests into the WASI CI job.

It also provides the WASI allocation symbols expected by the `lz4-sys`
dependency introduced by the base PR, allowing those test binaries to
link.

### Why?

The Rust test binaries require host functionality that stock WASI
runners do not provide. Turbopack stores its link-time task registries
in WebAssembly custom sections and imports a host callback to read them.
Its multithreaded runtime also requires shared memory and thread
spawning through Node Workers.

The base PR replaces `lzzzz` with `lz4`. `lz4-sys 1.11.1` compiles its C
sources against custom allocation shims on `wasm32-wasi*`, but excludes
the Rust implementations when the target OS is WASI. Without equivalent
symbols supplied by the consuming crate, test links fail on unresolved
malloc, calloc, and free shims.

Running these suites in CI gives the remaining WASI layers direct
regression coverage instead of relying on native-only tests.

### How?

The Node cargo target runner provides WASI preview1, imported shared
memory, and the complete two-phase [`link-section` custom-section
protocol](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm).


[`@emnapi/wasi-threads`](https://github.com/toyobayashi/emnapi/tree/main/packages/wasi-threads)
supplies Worker lifecycle, compiled-module transfer, load/start
ordering, and cleanup for the
[`wasi.thread-spawn`](https://github.com/WebAssembly/wasi-threads)
import that Node's WASI runtime does not provide. The module is compiled
once, then the structured-cloneable `WebAssembly.Module` and shared
memory are sent to Workers. A small adapter around the package's
lower-level `ThreadManager` and `ThreadMessageHandler` APIs preserves
Rust's original one-argument ABI: the high-level `WASIThreads` wrapper
requires guest `malloc`/`free` exports for that ABI, and Rust test
binaries do not export them. Worker identifiers come from a shared
atomic counter because Tokio Workers can spawn additional Workers while
the main WebAssembly thread is parked.

On WASI, `turbo-persistence` supplies the three allocation symbols
required by liblz4 and forwards them to WASI libc, keeping allocation
and deallocation within the same allocator. Native builds do not compile
these wrappers.

Tests that depend on unavailable platform behavior remain visible as
WASI-only ignored tests with explicit reasons. Native runs keep the full
test set enabled. A following stacked PR replaces the unsupported
`parking_lot` parker and re-enables the corresponding contention tests.

The workflow installs and builds the workspace before running the host
because both the package dependency and compiled production support used
by a later stack layer must be available.

### Verification

- Node 20 host unit tests: 9/9
- Exact combined WASI CI command: `turbo-rcstr` 12 passed / 1 ignored;
`turbo-tasks` 68 / 44; `turbo-tasks-backend` 65 / 35
- Full 111-test `turbo-tasks` binary through the package-managed host:
95 passed / 16 ignored
- No Worker-side `WebAssembly.compile`; the compiled module is
transferred by `ThreadManager`
- `pnpm install --lockfile-only --offline` with a frozen lockfile

<!-- NEXT_JS_LLM -->

<!-- fleet b6d0486f-97c7-42a7-bdaf-3490774cdec3 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent c418b7aa
...@@ -40,6 +40,8 @@ rustflags = [ ...@@ -40,6 +40,8 @@ rustflags = [
"-Zthreads=8", "-Zthreads=8",
# Unlock nightly-only options # Unlock nightly-only options
"-Zunstable-options", "-Zunstable-options",
# Keep warnings fatal for every target instead of relying on per-job CI overrides.
"-Dwarnings",
] ]
# macOS: use rust-lld (ld64.lld) for faster linking and enable ICF. # macOS: use rust-lld (ld64.lld) for faster linking and enable ICF.
...@@ -83,6 +85,17 @@ rustflags = [ ...@@ -83,6 +85,17 @@ rustflags = [
[target.'cfg(all(target_os = "linux", target_env = "musl"))'] [target.'cfg(all(target_os = "linux", target_env = "musl"))']
rustflags = ["-Ctarget-feature=-crt-static"] rustflags = ["-Ctarget-feature=-crt-static"]
# WASI threads: make the imported shared-memory contract explicit. Keep these byte values in sync
# with the page counts in scripts/wasi-test-host and packages/next/src/build/swc/wasi-runtime.ts.
[target.wasm32-wasip1-threads]
rustflags = [
"-Dlinker-messages",
# 512 MiB
"-Clink-arg=--initial-memory=536870912",
# 4 GiB
"-Clink-arg=--max-memory=4294967296",
]
# WASM: configure getrandom to use the wasm_js backend (Math.random / crypto). # WASM: configure getrandom to use the wasm_js backend (Math.random / crypto).
[target.wasm32-unknown-unknown] [target.wasm32-unknown-unknown]
rustflags = [ rustflags = [
......
...@@ -639,6 +639,12 @@ jobs: ...@@ -639,6 +639,12 @@ jobs:
stepName: 'test-next-swc-wasm' stepName: 'test-next-swc-wasm'
secrets: inherit secrets: inherit
# Guards that Turbopack keeps compiling for wasm, so the wasm fallback Next.js loads when the
# native bindings are unavailable can eventually support Turbopack and not just SWC.
# See https://github.com/vercel/next.js/issues/96960.
#
# This compiles the bindings and runs the wasm test suites with the pinned emnapi v2 prerelease.
# A linked build is gated by the first stack layer that provides every required runtime hook.
test-next-napi-bindings-wasi: test-next-napi-bindings-wasi:
name: test next-swc wasi name: test next-swc wasi
needs: ['optimize-ci', 'changes', 'build-next'] needs: ['optimize-ci', 'changes', 'build-next']
...@@ -650,14 +656,31 @@ jobs: ...@@ -650,14 +656,31 @@ jobs:
uses: ./.github/workflows/build_reusable.yml uses: ./.github/workflows/build_reusable.yml
with: with:
needsRust: 'yes' needsRust: 'yes'
skipInstallBuild: 'yes'
skipNativeBuild: 'yes' skipNativeBuild: 'yes'
skipNativeInstall: 'yes' skipNativeInstall: 'yes'
afterBuild: | afterBuild: |
set -euo pipefail set -euo pipefail
# Provisions the wasi-sdk, emnapi and the cross-compilation env. Shared with local
# builds so the two cannot drift; see contributing/core/building-wasm.md.
source scripts/setup-wasi-env.sh source scripts/setup-wasi-env.sh
cargo check -p next-napi-bindings --target wasm32-wasip1-threads
# swc's plugin host is gated off for wasm (see turbopack-ecmascript-plugins and
# next-napi-bindings), so nothing needs patching here: the wasm32 plugin path that does not
# compile is simply never built.
cargo build -p next-napi-bindings --target wasm32-wasip1-threads
# Run the crates whose tests can execute on wasm. This needs a host that supplies the
# `env.read_custom_section` import turbo-tasks' link-time registries depend on; no stock
# runtime provides it. See scripts/wasi-test-host/README.md, which also lists the platform
# limitations behind the tests that are `ignore`d on wasm.
export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node $PWD/scripts/wasi-test-host/run.mjs"
cargo test \
-p turbo-rcstr \
-p turbo-tasks \
-p turbo-tasks-backend \
--lib \
--target wasm32-wasip1-threads
stepName: 'test-next-napi-bindings-wasi' stepName: 'test-next-napi-bindings-wasi'
secrets: inherit secrets: inherit
......
...@@ -118,6 +118,7 @@ ...@@ -118,6 +118,7 @@
"@babel/plugin-transform-object-rest-spread": "7.25.9", "@babel/plugin-transform-object-rest-spread": "7.25.9",
"@babel/preset-react": "7.26.3", "@babel/preset-react": "7.26.3",
"@edge-runtime/jest-environment": "4.0.0", "@edge-runtime/jest-environment": "4.0.0",
"@emnapi/wasi-threads": "2.1.0",
"@emotion/cache": "11.11.0", "@emotion/cache": "11.11.0",
"@emotion/react": "11.11.1", "@emotion/react": "11.11.1",
"@eslint/compat": "1.4.0", "@eslint/compat": "1.4.0",
......
...@@ -97,6 +97,9 @@ importers: ...@@ -97,6 +97,9 @@ importers:
'@edge-runtime/jest-environment': '@edge-runtime/jest-environment':
specifier: 4.0.0 specifier: 4.0.0
version: 4.0.0 version: 4.0.0
'@emnapi/wasi-threads':
specifier: 2.1.0
version: 2.1.0
'@emotion/cache': '@emotion/cache':
specifier: 11.11.0 specifier: 11.11.0
version: 11.11.0 version: 11.11.0
...@@ -3067,6 +3070,9 @@ packages: ...@@ -3067,6 +3070,9 @@ packages:
'@emnapi/wasi-threads@1.2.2': '@emnapi/wasi-threads@1.2.2':
resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
'@emnapi/wasi-threads@2.1.0':
resolution: {integrity: sha512-DM18NXgQ5coifswrwhFgrqeW/UiFRaLj0aLKU0cp0FoYjEfP/hj/yUeF+Hz754ViG+jQmG2HIeDCUeQsPnRwOA==}
'@emotion/babel-plugin@11.11.0': '@emotion/babel-plugin@11.11.0':
resolution: {integrity: sha512-m4HEDZleaaCH+XgDDsPF15Ht6wTLsgDTeR3WYj9Q/k76JtWhrJjcP4+/XlG8LGT/Rol9qUfOIztXeA84ATpqPQ==} resolution: {integrity: sha512-m4HEDZleaaCH+XgDDsPF15Ht6wTLsgDTeR3WYj9Q/k76JtWhrJjcP4+/XlG8LGT/Rol9qUfOIztXeA84ATpqPQ==}
...@@ -20209,6 +20215,10 @@ snapshots: ...@@ -20209,6 +20215,10 @@ snapshots:
tslib: 2.8.1 tslib: 2.8.1
optional: true optional: true
'@emnapi/wasi-threads@2.1.0':
dependencies:
tslib: 2.8.1
'@emotion/babel-plugin@11.11.0': '@emotion/babel-plugin@11.11.0':
dependencies: dependencies:
'@babel/helper-module-imports': 7.25.9 '@babel/helper-module-imports': 7.25.9
# wasi-test-host
Runs `wasm32-wasip1-threads` test binaries that link `turbo-tasks`.
## Why this exists
Those binaries compile, but no off-the-shelf WASI runtime can start them:
```
Error: unknown import: `env::read_custom_section` has not been defined
```
`turbo-tasks` gathers its task registries at link time with the `link-section` crate. On wasm there
are no section start/stop symbols, so the crate stores each registry in a **custom section** and
expects the embedder to hand it back through an `env.read_custom_section` import — data the guest
cannot reach on its own. The exact guest/host contract is in the
[`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm).
`wasmtime` cannot inject host imports from the CLI (`--preload env=…` does not satisfy core-module
imports), so without a host like this one nothing in the `turbo-tasks` family can be tested on wasm.
The other missing host feature is
[`wasi.thread-spawn`](https://github.com/WebAssembly/wasi-threads). V8 implements shared WebAssembly
memory and atomics, but Node's `WASI#getImportObject()` exposes only `wasi_snapshot_preview1`, not the
proposal's `wasi` namespace. `@emnapi/wasi-threads` bridges that import to Node Workers.
The same hook will be needed by the Next.js wasm loader for Turbopack itself, so the
`read_custom_section` implementation here is a first cut of that work rather than test-only
scaffolding.
## Usage
```sh
pnpm install
export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node scripts/wasi-test-host/run.mjs"
cargo test -p turbo-tasks --lib --target wasm32-wasip1-threads
cargo test -p turbo-tasks-backend --lib --target wasm32-wasip1-threads
```
Building for that target also needs a WASI C toolchain, because `lz4-sys` and `zstd-sys` have C build
scripts — see the `test-next-napi-bindings-wasi` job in `.github/workflows/build_and_test.yml` for the
wasi-sdk setup.
## What it provides
| Import | Source |
|---|---|
| `wasi_snapshot_preview1.*` | `node:wasi` |
| `wasi.thread-spawn` | `@emnapi/wasi-threads` over `node:worker_threads` (`spawn.mjs`) |
| `env.memory` | a shared `WebAssembly.Memory` matching the explicit linker limits in `.cargo/config.toml` |
| `env.read_custom_section` | `WebAssembly.Module.customSections` (`lib.mjs`) |
`@emnapi/wasi-threads` owns Worker lifecycle, compiled-module transfer, load/start ordering, and
cleanup. A small local adapter remains because Rust imports the original one-argument
`thread-spawn` ABI but does not export the `malloc`/`free` functions the package's high-level wrapper
uses for that ABI.
The imported shared memory uses 8,192 initial pages (512 MiB) and 65,536 maximum pages (4 GiB).
Those values are also explicit `wasm32-wasip1-threads` linker flags in `.cargo/config.toml`; keep the
host constants and linker byte values in sync. A shared WebAssembly memory must declare a maximum,
and 65,536 pages is the wasm32 architectural ceiling.
### `read_custom_section`
A two-phase contract, per the
[`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm):
- section not found → return `0`;
- `targetLength` too small → return the required size and copy nothing;
- otherwise → copy into guest memory and return the number of bytes.
Returning `0` unconditionally is not a shortcut: the registries then come up empty. `link-section`'s
pre-main constructor notices and aborts, which is at least loud, but the correct sections are what
make the module usable. `registry::tests::registries_are_populated` guards this from the Rust side.
### Threads
Each thread is a Worker running the same module over the same shared memory, entered through the
module's `wasi_thread_start` export. Three details are worth knowing:
- **The module is compiled once.** `@emnapi/wasi-threads` sends the compiled, structured-cloneable
`WebAssembly.Module` to Workers. Each Worker instantiates it over the shared memory; it does not
recompile the Turbopack binary.
- **Workers spawn workers directly.** A Tokio multi-thread runtime spawns threads from its worker
threads, and the main thread is usually parked in `Atomics.wait` inside wasm, so it cannot service
a request to spawn on someone else's behalf. Thread ids come from one `Atomics.add` counter in
shared memory so they stay unique across all of them.
- **`wasi.initialize()` refuses a module exporting `_start`**, since that marks a command whose
`_start` must run exactly once, on the main thread. A spawned thread hides that export to get the
WASI binding, then calls `wasi_thread_start` itself.
## Tests that cannot run on wasm
Some tests are marked `#[cfg_attr(target_family = "wasm", ignore = "…")]`, so they show up as
`ignored, <reason>` rather than disappearing. Each reason is a real platform limitation, not a
workaround for this host:
| Reason | Why |
|---|---|
| `no unwinding on wasm` | wasm is `panic = abort`, so `catch_unwind` never catches and a panic takes the whole instance down. Affects `#[should_panic]` tests and tests asserting panic isolation. |
| `parking_lot cannot block on wasm` | `parking_lot_core` only has a working thread parker behind its `nightly` feature, and the pinned version cannot compile it on current nightly. Blocking on a contended lock panics with "Parking not supported on this platform". |
| `no temp directory on WASI` | `std::env::temp_dir()` is unsupported on WASI preview1, so anything using `TempDir` panics. |
The `parking_lot` limitation is worth calling out: it is not only a test problem. Until it is fixed,
any contended lock panics on wasm, which Turbopack itself would hit. The no-unwinding limitation is
similar — `turbo-tasks` uses `catch_unwind` in production to keep a panicking task from taking down
the process, and that protection is inert on wasm.
/**
* Host support for running `wasm32-wasip1-threads` test binaries that link `turbo-tasks`.
*
* Such a binary cannot be run by a stock WASI runtime, because `turbo-tasks` gathers its task
* registries with the `link-section` crate, which on wasm stores them in **custom sections** and
* requires the embedder to hand them back through an `env.read_custom_section` import. See the
* [`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm);
* the implementation below is that contract.
*
* Worker lifecycle and compiled-module transfer come from `@emnapi/wasi-threads`; this file contains
* only the Turbopack-specific custom-section hook and shared-memory contract.
*/
const WASM_PAGE_SIZE_BYTES = 65_536
// 512 MiB. Keep in sync with --initial-memory in .cargo/config.toml.
export const WASI_MEMORY_INITIAL_PAGES = 536_870_912 / WASM_PAGE_SIZE_BYTES
// 4 GiB. Keep in sync with --max-memory in .cargo/config.toml.
export const WASI_MEMORY_MAXIMUM_PAGES = 4_294_967_296 / WASM_PAGE_SIZE_BYTES
/** Create the imported shared memory configured by the wasm32-wasip1-threads linker flags. */
export function createImportedMemory() {
return new WebAssembly.Memory({
initial: WASI_MEMORY_INITIAL_PAGES,
maximum: WASI_MEMORY_MAXIMUM_PAGES,
shared: true,
})
}
/**
* Implements the `env.read_custom_section` import that `link-section` requires on wasm. The exact
* guest/host contract is documented in the
* [`link-section` wasm preamble](https://github.com/mmastrac/linktime/blob/ae29e51d94a955df2442ed6418b8a712c1f2bfb3/link-section/docs/PREAMBLE.md#wasm).
*
* The protocol is two-phase, so the guest can ask for the size before allocating:
*
* - the section does not exist -> return 0, copy nothing;
* - `targetLength` is too small -> return the size needed, copy nothing;
* - otherwise -> copy the section into guest memory and return how many bytes were written.
*
* Returning 0 unconditionally would let a module instantiate with **empty** registries, which fails
* later in confusing ways rather than at the point of the mistake, so the real sections are read.
*
* @param {WebAssembly.Module} module
* @param {WebAssembly.Memory} memory
* @returns {(namePtr: number, nameLength: number, targetPtr: number, targetLength: number) => number}
*/
export function createReadCustomSection(module, memory) {
const decoder = new TextDecoder()
return (namePtr, nameLength, targetPtr, targetLength) => {
const nameBytes = new Uint8Array(memory.buffer, namePtr, nameLength)
// The name has to be copied out before decoding: a shared growable buffer can be detached.
const sectionName = decoder.decode(new Uint8Array(nameBytes))
const sections = WebAssembly.Module.customSections(module, sectionName)
if (sections.length === 0) return 0
const section = new Uint8Array(sections[0])
if (targetLength < section.byteLength) {
// Report the required size; the guest will call again with a large enough buffer.
return section.byteLength
}
new Uint8Array(memory.buffer, targetPtr, section.byteLength).set(section)
return section.byteLength
}
}
#!/usr/bin/env node
/**
* Cargo target runner for `wasm32-wasip1-threads` test binaries that link `turbo-tasks`.
*
* export CARGO_TARGET_WASM32_WASIP1_THREADS_RUNNER="node scripts/wasi-test-host/run.mjs"
* cargo test -p turbo-tasks --lib --target wasm32-wasip1-threads
*
* See ./README.md for why this exists. In short: `turbo-tasks` needs an `env.read_custom_section`
* host import that no stock runtime provides, so the binaries build but cannot be executed.
*/
import { WASI } from 'node:wasi'
import { readFileSync } from 'node:fs'
import process from 'node:process'
import { createImportedMemory, createReadCustomSection } from './lib.mjs'
import { createThreadRuntime } from './spawn.mjs'
const [wasmPath, ...testArgs] = process.argv.slice(2)
if (!wasmPath) {
console.error('usage: run.mjs <binary.wasm> [test args...]')
process.exit(2)
}
const bytes = readFileSync(wasmPath)
const module = await WebAssembly.compile(bytes)
const memory = createImportedMemory()
// argv[0] is the program name, as a C `main` expects.
const args = [wasmPath, ...testArgs]
const wasi = new WASI({
version: 'preview1',
args,
env: process.env,
// Tests may touch the filesystem (tempfiles, fixtures); expose the working directory only.
preopens: { '/': process.cwd() },
returnOnExit: true,
})
/**
* Thread ids, allocated from one counter in shared memory so that ids stay unique no matter which
* thread does the spawning. The main thread is 0.
*/
const threadIds = new Int32Array(new SharedArrayBuffer(4))
const { threadSpawn } = createThreadRuntime({
module,
memory,
threadIds,
args,
env: process.env,
cwd: process.cwd(),
onError: (error, threadId) => {
// A thread that dies takes the process with it, like a real aborted thread would.
const suffix = threadId === undefined ? '' : ` ${threadId}`
console.error(`wasi thread${suffix} failed:`, error)
process.exit(1)
},
})
const instance = await WebAssembly.instantiate(module, {
...wasi.getImportObject(),
env: {
memory,
read_custom_section: createReadCustomSection(module, memory),
},
wasi: {
'thread-spawn': threadSpawn,
},
})
// `wasi.start` runs `_start` and returns the exit code (`returnOnExit`).
const exitCode = wasi.start(instance)
process.exit(exitCode ?? 0)
/**
* `wasi.thread-spawn` over `node:worker_threads`.
*
* V8 supports shared WebAssembly memory and atomics, but Node's WASI implementation only supplies
* `wasi_snapshot_preview1`; it does not implement the `wasi.thread-spawn` host import from the
* wasi-threads proposal. `@emnapi/wasi-threads` supplies the Worker lifecycle and transfers the
* already-compiled module to each Worker.
*
* Spec: https://github.com/WebAssembly/wasi-threads
*/
import { ThreadManager } from '@emnapi/wasi-threads'
import { Worker } from 'node:worker_threads'
import { fileURLToPath } from 'node:url'
const THREAD_WORKER = fileURLToPath(new URL('./thread.mjs', import.meta.url))
/**
* Allocate thread ids from one shared counter so ids stay unique across every thread that spawns.
*
* A plain JS variable would not do: each Worker has its own module instance, so each would hand out
* ids starting from the same value. `Atomics.add` on shared memory is the only counter all of them
* can see.
*
* @param {Int32Array} threadIds a one-element `Int32Array` over a `SharedArrayBuffer`
*/
export function nextThreadId(threadIds) {
if (
threadIds.length !== 1 ||
!(threadIds.buffer instanceof SharedArrayBuffer)
) {
throw new TypeError('threadIds must be a one-element shared Int32Array')
}
// Main thread is 0; spawned threads start at 1.
const threadId = Atomics.add(threadIds, 0, 1) + 1
if (threadId <= 0) {
throw new RangeError('wasi thread id counter overflowed')
}
return threadId
}
/**
* Build a `wasi.thread-spawn` implementation and Worker manager for one instance.
*
* Rust currently imports the proposal's original one-argument ABI, which returns the new thread id
* directly. `WASIThreads` supports that ABI by calling guest `malloc`/`free`, but Rust test binaries
* do not export those functions. The lower-level manager and handler do not impose that requirement,
* so this small adapter preserves the original ABI while delegating module transfer, load/start
* ordering, cleanup, and Worker lifecycle to `@emnapi/wasi-threads`.
*
* Every Worker creates a local manager because a Tokio worker may itself spawn a thread while the
* main wasm thread is parked in `Atomics.wait`. All managers allocate IDs from the same shared
* counter.
*
* @param {{ module: WebAssembly.Module, memory: WebAssembly.Memory, threadIds: Int32Array, args: string[], env: Record<string, string>, cwd: string, onError: (error: Error, threadId: number | undefined) => void, workerPath?: string, WorkerClass?: typeof Worker, ThreadManagerClass?: typeof ThreadManager }} context
*/
export function createThreadRuntime(context) {
const {
module,
memory,
threadIds,
args,
env,
cwd,
onError,
workerPath = THREAD_WORKER,
WorkerClass = Worker,
ThreadManagerClass = ThreadManager,
} = context
class SharedIdThreadManager extends ThreadManagerClass {
markId(worker) {
if (worker.__emnapi_tid !== undefined) return worker.__emnapi_tid
const threadId = nextThreadId(threadIds)
this.pthreads[threadId] = worker
worker.__emnapi_tid = threadId
return threadId
}
}
const manager = new SharedIdThreadManager({
reuseWorker: false,
onCreateWorker: () =>
new WorkerClass(workerPath, {
workerData: { threadIds, args, env, cwd },
// Inherit stdio so panics and test output from threads reach the terminal.
stdout: false,
stderr: false,
}),
printErr: (message) => onError(new Error(String(message)), undefined),
})
manager.init()
// `ThreadManager` posts these structured-cloneable values in its `load` message. In particular,
// Workers receive the compiled module rather than the original bytes, so they only instantiate.
manager.setup(module, memory)
const threadSpawn = (startArg) => {
try {
const worker = manager.getNewWorker()
if (!worker) return -1
const threadId = manager.markId(worker)
worker.postMessage({
__emnapi__: {
type: 'start',
payload: { tid: threadId, arg: startArg },
},
})
worker.unref()
return threadId
} catch (error) {
onError(
error instanceof Error ? error : new Error(String(error)),
undefined
)
return -1
}
}
// The package calls this callback if a child-mode handler asks its owner to spawn. Our workers
// normally own local managers instead, but keeping the callback set makes the manager complete.
manager.threadSpawn = threadSpawn
return { threadSpawn, manager }
}
/**
* Worker body for one `wasi.thread-spawn`ed thread.
*
* `@emnapi/wasi-threads` sends the compiled module and shared memory in a `load` message, then queues
* the `start` message until instantiation finishes. No Worker recompiles the wasm bytes.
*/
import { ThreadMessageHandler } from '@emnapi/wasi-threads'
import process from 'node:process'
import { WASI } from 'node:wasi'
import { parentPort, workerData } from 'node:worker_threads'
import { createReadCustomSection } from './lib.mjs'
import { createThreadRuntime } from './spawn.mjs'
const { threadIds, args, env, cwd } = workerData
const handler = new ThreadMessageHandler({
postMessage: (message) => parentPort.postMessage(message),
onError: (error, type) => {
console.error(`wasi thread failed during ${type}:`, error)
process.exit(1)
},
async onLoad({ wasmModule, wasmMemory }) {
const wasi = new WASI({
version: 'preview1',
args,
env,
preopens: { '/': cwd },
returnOnExit: true,
})
// A Tokio worker may itself spawn blocking workers. Give every instance a local manager so that
// nested spawning does not depend on the main JS event loop while the main wasm thread is parked.
const { threadSpawn } = createThreadRuntime({
module: wasmModule,
memory: wasmMemory,
threadIds,
args,
env,
cwd,
onError: (error, threadId) => {
const suffix = threadId === undefined ? '' : ` ${threadId}`
console.error(`wasi thread${suffix} failed:`, error)
process.exit(1)
},
})
const instance = await WebAssembly.instantiate(wasmModule, {
...wasi.getImportObject(),
env: {
memory: wasmMemory,
read_custom_section: createReadCustomSection(wasmModule, wasmMemory),
},
wasi: {
'thread-spawn': threadSpawn,
},
})
// Bind preview1 imports without invoking the command's `_start`; ThreadMessageHandler enters the
// instance through `wasi_thread_start` when it processes the queued `start` message.
const threadExports = { ...instance.exports }
delete threadExports._start
wasi.initialize({ exports: threadExports })
return { module: wasmModule, instance }
},
})
parentPort.on('message', (data) => handler.handle({ data }))
#![cfg_attr(target_os = "wasi", feature(wasi_ext))] #![cfg_attr(target_os = "wasi", feature(wasi_ext))]
#![feature(once_cell_try)] #![feature(once_cell_try)]
#![feature(sync_unsafe_cell)] #![feature(sync_unsafe_cell)]
// Miri compiles a reduced test subset, leaving helpers from disabled tests intentionally unused.
#![cfg_attr(miri, allow(dead_code, unused_imports))]
mod arc_bytes; mod arc_bytes;
pub(crate) mod be; pub(crate) mod be;
......
...@@ -73,7 +73,6 @@ turbo-persistence = { workspace = true, default-features = false } ...@@ -73,7 +73,6 @@ turbo-persistence = { workspace = true, default-features = false }
[dev-dependencies] [dev-dependencies]
async-trait = { workspace = true } async-trait = { workspace = true }
criterion = { workspace = true, features = ["async_tokio"] }
futures = { workspace = true } futures = { workspace = true }
indoc = { workspace = true } indoc = { workspace = true }
regex = { workspace = true } regex = { workspace = true }
...@@ -87,6 +86,12 @@ turbo-tasks-testing = { workspace = true } ...@@ -87,6 +86,12 @@ turbo-tasks-testing = { workspace = true }
# normal builds of this crate get the default (disabled) turbo-tasks. # normal builds of this crate get the default (disabled) turbo-tasks.
turbo-tasks = { workspace = true, features = ["inline_execution_stats"] } turbo-tasks = { workspace = true, features = ["inline_execution_stats"] }
# Only used by the benchmarks, which don't run on wasm. Gated by target so that
# `cargo test -p turbo-tasks-backend --lib --target wasm32-wasip1-threads` can build: criterion pulls
# in rayon, which refuses to compile for wasi, and cargo resolves dev-dependencies even for `--lib`.
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
criterion = { workspace = true, features = ["async_tokio"] }
[[bench]] [[bench]]
name = "mod" name = "mod"
......
...@@ -2393,6 +2393,7 @@ mod cell_data_tracking_tests { ...@@ -2393,6 +2393,7 @@ mod cell_data_tracking_tests {
// `evict_after_snapshot` uses `parallel::for_each`/`map_collect`, which call // `evict_after_snapshot` uses `parallel::for_each`/`map_collect`, which call
// `block_in_place` internally and require a multi-threaded Tokio runtime. // `block_in_place` internally and require a multi-threaded Tokio runtime.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn skip_never_cell_survives_eviction_without_modified_flag() { async fn skip_never_cell_survives_eviction_without_modified_flag() {
// A Skip + evict="never" cell must be retained in memory by // A Skip + evict="never" cell must be retained in memory by
// `drop_partial` (which keys on Evictability, not the modified flag), so // `drop_partial` (which keys on Evictability, not the modified flag), so
......
...@@ -392,6 +392,7 @@ mod tests { ...@@ -392,6 +392,7 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn snapshot_waits_for_ops_to_drain() { fn snapshot_waits_for_ops_to_drain() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new()); let coord = Arc::new(SnapshotCoordinator::<Op>::new());
...@@ -420,6 +421,7 @@ mod tests { ...@@ -420,6 +421,7 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn new_operation_blocks_during_snapshot() { fn new_operation_blocks_during_snapshot() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new()); let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let phase = coord.begin_snapshot(); let phase = coord.begin_snapshot();
...@@ -463,6 +465,7 @@ mod tests { ...@@ -463,6 +465,7 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn suspend_point_lets_snapshot_proceed() { fn suspend_point_lets_snapshot_proceed() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new()); let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let g = coord.begin_operation(); let g = coord.begin_operation();
...@@ -543,6 +546,7 @@ mod tests { ...@@ -543,6 +546,7 @@ mod tests {
/// fast-path missed-wakeup race when `OperationGuard::drop` does NOT /// fast-path missed-wakeup race when `OperationGuard::drop` does NOT
/// take the state mutex. /// take the state mutex.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn stress_no_missed_wakeups() { fn stress_no_missed_wakeups() {
run_with_timeout("stress_no_missed_wakeups", Duration::from_secs(60), || { run_with_timeout("stress_no_missed_wakeups", Duration::from_secs(60), || {
let coord = Arc::new(SnapshotCoordinator::<Op>::new()); let coord = Arc::new(SnapshotCoordinator::<Op>::new());
...@@ -611,6 +615,10 @@ mod tests { ...@@ -611,6 +615,10 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(
target_family = "wasm",
ignore = "parking_lot cannot block on wasm under this test's high contention"
)]
fn many_concurrent_ops_and_snapshots() { fn many_concurrent_ops_and_snapshots() {
// Stress test: hammer the protocol from many threads. // Stress test: hammer the protocol from many threads.
// The coordinator does not serialize concurrent snapshotters (callers // The coordinator does not serialize concurrent snapshotters (callers
...@@ -659,6 +667,7 @@ mod tests { ...@@ -659,6 +667,7 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn operations_waiting_tracks_blocked_operations() { fn operations_waiting_tracks_blocked_operations() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new()); let coord = Arc::new(SnapshotCoordinator::<Op>::new());
......
...@@ -1201,6 +1201,7 @@ mod tests { ...@@ -1201,6 +1201,7 @@ mod tests {
// `end_snapshot` uses `parallel::for_each` which calls `block_in_place` internally, // `end_snapshot` uses `parallel::for_each` which calls `block_in_place` internally,
// requiring a multi-threaded Tokio runtime. // requiring a multi-threaded Tokio runtime.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn modify_during_snapshot_clears_live_modified_flags() { async fn modify_during_snapshot_clears_live_modified_flags() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1273,6 +1274,7 @@ mod tests { ...@@ -1273,6 +1274,7 @@ mod tests {
/// unmodified-before-snapshot category is still the pre-snapshot state), clears pre-snapshot /// unmodified-before-snapshot category is still the pre-snapshot state), clears pre-snapshot
/// flags, and promotes `data_modified_during_snapshot → data_modified`. /// flags, and promotes `data_modified_during_snapshot → data_modified`.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn modify_different_category_during_snapshot() { async fn modify_different_category_during_snapshot() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1332,6 +1334,7 @@ mod tests { ...@@ -1332,6 +1334,7 @@ mod tests {
/// persisted rather than retaining it until the whole snapshot is written. Either way the /// persisted rather than retaining it until the whole snapshot is written. Either way the
/// entry must be gone from the map by the time the snapshot is consumed. /// entry must be gone from the map by the time the snapshot is consumed.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn drain_entries_removes_entry_from_map() { async fn drain_entries_removes_entry_from_map() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1368,6 +1371,7 @@ mod tests { ...@@ -1368,6 +1371,7 @@ mod tests {
/// In drain mode, fully consuming the iterators should release each drained shard's table /// In drain mode, fully consuming the iterators should release each drained shard's table
/// allocation entirely (reset-to-empty in `SnapshotShardIter::drop`), not just shrink it. /// allocation entirely (reset-to-empty in `SnapshotShardIter::drop`), not just shrink it.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn drain_entries_releases_drained_shards() { async fn drain_entries_releases_drained_shards() {
// dashmap requires at least 2 shards. // dashmap requires at least 2 shards.
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
...@@ -1415,6 +1419,7 @@ mod tests { ...@@ -1415,6 +1419,7 @@ mod tests {
/// the map is already empty when `take_snapshot` returns, and only the modified task is /// the map is already empty when `take_snapshot` returns, and only the modified task is
/// yielded. /// yielded.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn drain_entries_removes_unmodified_during_take_snapshot() { async fn drain_entries_removes_unmodified_during_take_snapshot() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let modified_id = non_transient_task(1); let modified_id = non_transient_task(1);
...@@ -1457,6 +1462,7 @@ mod tests { ...@@ -1457,6 +1462,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn undo_non_snapshot_reverses_flag_and_counter() { async fn undo_non_snapshot_reverses_flag_and_counter() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1481,6 +1487,7 @@ mod tests { ...@@ -1481,6 +1487,7 @@ mod tests {
/// A second track on an already-modified category returns `NoChange`; undoing it is a no-op and /// A second track on an already-modified category returns `NoChange`; undoing it is a no-op and
/// must NOT clear the real modification recorded by the first track. /// must NOT clear the real modification recorded by the first track.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn undo_nochange_preserves_prior_modification() { async fn undo_nochange_preserves_prior_modification() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1502,6 +1509,7 @@ mod tests { ...@@ -1502,6 +1509,7 @@ mod tests {
/// Undo only reverses the category it tracked: tracking Data then Meta, undoing only the Meta /// Undo only reverses the category it tracked: tracking Data then Meta, undoing only the Meta
/// outcome must leave Data modified and the shard counter still non-zero. /// outcome must leave Data modified and the shard counter still non-zero.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn undo_only_reverses_its_own_category() { async fn undo_only_reverses_its_own_category() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1525,6 +1533,7 @@ mod tests { ...@@ -1525,6 +1533,7 @@ mod tests {
/// snapshot, inserts a `None` marker into `snapshots` and sets the `_during_snapshot` bit. /// snapshot, inserts a `None` marker into `snapshots` and sets the `_during_snapshot` bit.
/// Undo must remove the marker and clear the bit. /// Undo must remove the marker and clear the bit.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn undo_during_snapshot_true_false_removes_marker() { async fn undo_during_snapshot_true_false_removes_marker() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
...@@ -1558,6 +1567,7 @@ mod tests { ...@@ -1558,6 +1567,7 @@ mod tests {
/// the `_during_snapshot` bit, while leaving the pre-existing `modified` flag intact (it /// the `_during_snapshot` bit, while leaving the pre-existing `modified` flag intact (it
/// belongs to the snapshot, not to this call). /// belongs to the snapshot, not to this call).
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn undo_during_snapshot_true_true_removes_copy_preserves_modified() { async fn undo_during_snapshot_true_true_removes_copy_preserves_modified() {
let storage = Storage::new(2, true); let storage = Storage::new(2, true);
let task_id = non_transient_task(1); let task_id = non_transient_task(1);
......
...@@ -1082,6 +1082,8 @@ impl<K: IsTransient + Hash + Eq, V: IsTransient, const I: usize> DropPartial for ...@@ -1082,6 +1082,8 @@ impl<K: IsTransient + Hash + Eq, V: IsTransient, const I: usize> DropPartial for
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
// Only used by `test_schema_size`, which is 64-bit only.
#[cfg(target_pointer_width = "64")]
use std::mem::size_of; use std::mem::size_of;
use turbo_tasks::{CellId, TaskId}; use turbo_tasks::{CellId, TaskId};
......
...@@ -273,6 +273,7 @@ mod tests { ...@@ -273,6 +273,7 @@ mod tests {
#[rstest] #[rstest]
#[case::not_ci(false, &["mock-version", "other-dir-0"])] #[case::not_ci(false, &["mock-version", "other-dir-0"])]
#[case::ci(true, &["mock-version"])] #[case::ci(true, &["mock-version"])]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_only_most_recently_used_other_version_is_retained( fn test_only_most_recently_used_other_version_is_retained(
#[case] is_ci: bool, #[case] is_ci: bool,
#[case] expected: &[&str], #[case] expected: &[&str],
...@@ -300,6 +301,7 @@ mod tests { ...@@ -300,6 +301,7 @@ mod tests {
/// A version that hasn't been used within the TTL is evicted, even with the retention slot /// A version that hasn't been used within the TTL is evicted, even with the retention slot
/// free. /// free.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_ttl_evicts_unused_version() { fn test_ttl_evicts_unused_version() {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let base_path = tmp_dir.path(); let base_path = tmp_dir.path();
...@@ -321,6 +323,7 @@ mod tests { ...@@ -321,6 +323,7 @@ mod tests {
#[rstest] #[rstest]
#[case::empty(false)] #[case::empty(false)]
#[case::with_recent_data_file(true)] #[case::with_recent_data_file(true)]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_version_without_stamp_is_evicted(#[case] with_data_file: bool) { fn test_version_without_stamp_is_evicted(#[case] with_data_file: bool) {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let base_path = tmp_dir.path(); let base_path = tmp_dir.path();
...@@ -344,6 +347,7 @@ mod tests { ...@@ -344,6 +347,7 @@ mod tests {
#[rstest] #[rstest]
#[case::old_u32_format(&0u32.to_be_bytes())] #[case::old_u32_format(&0u32.to_be_bytes())]
#[case::garbage(b"not json")] #[case::garbage(b"not json")]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_unparsable_current_falls_back_to_mtime(#[case] contents: &[u8]) { fn test_unparsable_current_falls_back_to_mtime(#[case] contents: &[u8]) {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let base_path = tmp_dir.path(); let base_path = tmp_dir.path();
...@@ -367,6 +371,7 @@ mod tests { ...@@ -367,6 +371,7 @@ mod tests {
ttl_from_days(DEFAULT_OTHER_DB_VERSION_TTL_DAYS) + Duration::from_secs(60), ttl_from_days(DEFAULT_OTHER_DB_VERSION_TTL_DAYS) + Duration::from_secs(60),
&["mock-version"], &["mock-version"],
)] )]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_current_with_unknown_fields_uses_its_commit_time( fn test_current_with_unknown_fields_uses_its_commit_time(
#[case] committed_ago: Duration, #[case] committed_ago: Duration,
#[case] expected: &[&str], #[case] expected: &[&str],
...@@ -396,6 +401,7 @@ mod tests { ...@@ -396,6 +401,7 @@ mod tests {
/// The age of an unparsable `CURRENT` comes from its mtime, so it's a real age that the TTL /// The age of an unparsable `CURRENT` comes from its mtime, so it's a real age that the TTL
/// can act on — not [`Duration::MAX`], which would evict it unconditionally. /// can act on — not [`Duration::MAX`], which would evict it unconditionally.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_unparsable_current_is_aged_by_mtime() { fn test_unparsable_current_is_aged_by_mtime() {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let legacy = tmp_dir.path().join("legacy-version"); let legacy = tmp_dir.path().join("legacy-version");
...@@ -419,6 +425,7 @@ mod tests { ...@@ -419,6 +425,7 @@ mod tests {
/// On CI every other version is evicted regardless of age, so the mtime fallback doesn't buy a /// On CI every other version is evicted regardless of age, so the mtime fallback doesn't buy a
/// legacy-format database a reprieve there. /// legacy-format database a reprieve there.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_ci_evicts_unreadable_current() { fn test_ci_evicts_unreadable_current() {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let base_path = tmp_dir.path(); let base_path = tmp_dir.path();
...@@ -434,6 +441,7 @@ mod tests { ...@@ -434,6 +441,7 @@ mod tests {
} }
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
fn test_cleanup_of_prefixed_items() { fn test_cleanup_of_prefixed_items() {
let tmp_dir = TempDir::new().unwrap(); let tmp_dir = TempDir::new().unwrap();
let base_path = tmp_dir.path(); let base_path = tmp_dir.path();
......
...@@ -589,6 +589,7 @@ mod tests { ...@@ -589,6 +589,7 @@ mod tests {
/// This is a lower-level test that verifies the database layer correctly handles /// This is a lower-level test that verifies the database layer correctly handles
/// the case where multiple task IDs are stored under the same hash key. /// the case where multiple task IDs are stored under the same hash key.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
async fn test_hash_collision_returns_multiple_candidates() -> Result<()> { async fn test_hash_collision_returns_multiple_candidates() -> Result<()> {
let tempdir = tempfile::tempdir()?; let tempdir = tempfile::tempdir()?;
let path = tempdir.path(); let path = tempdir.path();
...@@ -623,6 +624,7 @@ mod tests { ...@@ -623,6 +624,7 @@ mod tests {
// This test is too slow to run under Miri. // This test is too slow to run under Miri.
#[cfg(not(miri))] #[cfg(not(miri))]
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
async fn test_batch_write_with_flush_and_reopen() -> Result<()> { async fn test_batch_write_with_flush_and_reopen() -> Result<()> {
let tempdir = tempfile::tempdir()?; let tempdir = tempfile::tempdir()?;
let path = tempdir.path(); let path = tempdir.path();
...@@ -683,6 +685,7 @@ mod tests { ...@@ -683,6 +685,7 @@ mod tests {
/// single id it deletes, so anything else in the bucket is untouched whether or not this /// single id it deletes, so anything else in the bucket is untouched whether or not this
/// commit knows about it. /// commit knows about it.
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
#[cfg_attr(target_family = "wasm", ignore = "no temp directory on WASI")]
async fn test_save_snapshot_delete_tombstones_task() -> Result<()> { async fn test_save_snapshot_delete_tombstones_task() -> Result<()> {
let tempdir = tempfile::tempdir()?; let tempdir = tempfile::tempdir()?;
let path = tempdir.path(); let path = tempdir.path();
......
...@@ -231,6 +231,7 @@ mod tests { ...@@ -231,6 +231,7 @@ mod tests {
// This test is too slow to run under Miri. // This test is too slow to run under Miri.
#[cfg(not(miri))] #[cfg(not(miri))]
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn stress_deadlock() { fn stress_deadlock() {
const N: usize = 100000; const N: usize = 100000;
const THREADS: usize = 20; const THREADS: usize = 20;
......
#![feature(arbitrary_self_types)] #![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(unexpected_cfgs)] #![allow(unexpected_cfgs)]
#[turbo_tasks::value_trait] #[turbo_tasks::value_trait]
......
...@@ -184,6 +184,9 @@ mod tests { ...@@ -184,6 +184,9 @@ mod tests {
#[test] #[test]
#[should_panic(expected = "Max id limit (overflow)")] #[should_panic(expected = "Max id limit (overflow)")]
// wasm has no unwinding (panic = abort), so a panic aborts the process instead of being caught
// and `#[should_panic]` can never pass. See the `wasi-test-host` README.
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn test_overflow_detection() { fn test_overflow_detection() {
let factory = IdFactory::new(NonZeroU8::MIN, NonZeroU8::MAX); let factory = IdFactory::new(NonZeroU8::MIN, NonZeroU8::MAX);
assert_eq!(factory.get(), NonZeroU8::new(1).unwrap()); assert_eq!(factory.get(), NonZeroU8::new(1).unwrap());
...@@ -195,6 +198,7 @@ mod tests { ...@@ -195,6 +198,7 @@ mod tests {
#[test] #[test]
#[should_panic(expected = "Max id limit (overflow)")] #[should_panic(expected = "Max id limit (overflow)")]
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn test_overflow_detection_near_u64_max() { fn test_overflow_detection_near_u64_max() {
let factory = IdFactory::new(NonZeroU64::try_from(u64::MAX - 5).unwrap(), NonZeroU64::MAX); let factory = IdFactory::new(NonZeroU64::try_from(u64::MAX - 5).unwrap(), NonZeroU64::MAX);
for _ in 0..=6 { for _ in 0..=6 {
......
...@@ -298,6 +298,7 @@ mod tests { ...@@ -298,6 +298,7 @@ mod tests {
use super::*; use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_for_each() { async fn test_parallel_for_each() {
let input = vec![1, 2, 3, 4, 5]; let input = vec![1, 2, 3, 4, 5];
let sum = AtomicI32::new(0); let sum = AtomicI32::new(0);
...@@ -308,6 +309,7 @@ mod tests { ...@@ -308,6 +309,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_try_for_each() { async fn test_parallel_try_for_each() {
let input = vec![1, 2, 3, 4, 5]; let input = vec![1, 2, 3, 4, 5];
let result = try_for_each(&input, |&x| { let result = try_for_each(&input, |&x| {
...@@ -322,6 +324,9 @@ mod tests { ...@@ -322,6 +324,9 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
// Without a working parker the scope does not wait for every chunk, so this fails with
// *incomplete* results rather than a panic.
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_try_for_each_mut() { async fn test_parallel_try_for_each_mut() {
let mut input = vec![1, 2, 3, 4, 5]; let mut input = vec![1, 2, 3, 4, 5];
let result = try_for_each_mut(&mut input, |x| { let result = try_for_each_mut(&mut input, |x| {
...@@ -338,6 +343,7 @@ mod tests { ...@@ -338,6 +343,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_for_each_owned() { async fn test_parallel_for_each_owned() {
let input = vec![1, 2, 3, 4, 5]; let input = vec![1, 2, 3, 4, 5];
let sum = AtomicI32::new(0); let sum = AtomicI32::new(0);
...@@ -348,6 +354,7 @@ mod tests { ...@@ -348,6 +354,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_map_collect() { async fn test_parallel_map_collect() {
let input = vec![1, 2, 3, 4, 5]; let input = vec![1, 2, 3, 4, 5];
let result: Vec<_> = map_collect(&input, |&x| x * 2); let result: Vec<_> = map_collect(&input, |&x| x * 2);
...@@ -355,6 +362,7 @@ mod tests { ...@@ -355,6 +362,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_map_collect_owned() { async fn test_parallel_map_collect_owned() {
let input = vec![1, 2, 3, 4, 5]; let input = vec![1, 2, 3, 4, 5];
let result: Vec<_> = map_collect_owned(input, |x| x * 2); let result: Vec<_> = map_collect_owned(input, |x| x * 2);
...@@ -362,6 +370,7 @@ mod tests { ...@@ -362,6 +370,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_parallel_map_collect_owned_many() { async fn test_parallel_map_collect_owned_many() {
let input = vec![1; 1000]; let input = vec![1; 1000];
let result: Vec<_> = map_collect_owned(input, |x| x * 2); let result: Vec<_> = map_collect_owned(input, |x| x * 2);
...@@ -369,6 +378,8 @@ mod tests { ...@@ -369,6 +378,8 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
// Relies on `catch_unwind` catching, which needs unwinding; wasm is panic = abort.
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
async fn test_panic_in_scope() { async fn test_panic_in_scope() {
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
let mut input = vec![1; 1000]; let mut input = vec![1; 1000];
......
...@@ -699,6 +699,7 @@ mod tests { ...@@ -699,6 +699,7 @@ mod tests {
#[cfg(not(miri))] #[cfg(not(miri))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_cpu_bound_tasks() { async fn test_cpu_bound_tasks() {
struct ExecutorImpl; struct ExecutorImpl;
...@@ -751,6 +752,7 @@ mod tests { ...@@ -751,6 +752,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_cpu_bound_with_yield_tasks() { async fn test_cpu_bound_with_yield_tasks() {
struct ExecutorImpl; struct ExecutorImpl;
...@@ -804,6 +806,7 @@ mod tests { ...@@ -804,6 +806,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_waiting_tasks() { async fn test_waiting_tasks() {
struct ExecutorImpl; struct ExecutorImpl;
...@@ -855,6 +858,7 @@ mod tests { ...@@ -855,6 +858,7 @@ mod tests {
/// Each task waits on two barriers (start, finish). The release sequence /// Each task waits on two barriers (start, finish). The release sequence
/// controls execution order deterministically. /// controls execution order deterministically.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn test_mixed_cpu_bound_and_waiting_tasks() { fn test_mixed_cpu_bound_and_waiting_tasks() {
tokio::runtime::Builder::new_multi_thread() tokio::runtime::Builder::new_multi_thread()
.worker_threads(2) .worker_threads(2)
......
...@@ -305,3 +305,25 @@ pub fn get_trait(id: TraitTypeId) -> &'static TraitType { ...@@ -305,3 +305,25 @@ pub fn get_trait(id: TraitTypeId) -> &'static TraitType {
pub fn validate_trait_type_id(id: TraitTypeId) -> Option<Error> { pub fn validate_trait_type_id(id: TraitTypeId) -> Option<Error> {
validate_id(&TRAITS, id) validate_id(&TRAITS, id)
} }
#[cfg(test)]
mod tests {
use super::*;
/// The registries are gathered at link time by `link-section`. On wasm it stores them in custom
/// sections and requires the embedder to hand them back through an `env.read_custom_section`
/// import (see `scripts/wasi-test-host/`).
///
/// If that import is missing or returns nothing the slices come up **empty**, and everything
/// still links and runs — task lookups just quietly find nothing. Assert the bootstrap actually
/// delivered data, so that failure mode is loud instead of silent.
#[test]
fn registries_are_populated() {
assert!(
!FUNCTIONS.is_empty(),
"no native functions registered: the link-section bootstrap produced nothing"
);
assert!(!VALUES.is_empty(), "no value types registered");
assert!(!TRAITS.is_empty(), "no trait types registered");
}
}
...@@ -288,6 +288,7 @@ mod tests { ...@@ -288,6 +288,7 @@ mod tests {
/// no helper can be scheduled; we assert the scope still finishes well before that deadline. /// no helper can be scheduled; we assert the scope still finishes well before that deadline.
/// The deadline also guarantees the test fails cleanly instead of hanging. /// The deadline also guarantees the test fails cleanly instead of hanging.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_scope_worker_threads_occupied() { async fn test_scope_worker_threads_occupied() {
const WORKER_THREADS: usize = 2; const WORKER_THREADS: usize = 2;
const JOBS: usize = 64; const JOBS: usize = 64;
...@@ -340,6 +341,7 @@ mod tests { ...@@ -340,6 +341,7 @@ mod tests {
/// On a `current_thread` runtime no helpers can be spawned and `block_in_place` is not allowed, /// On a `current_thread` runtime no helpers can be spawned and `block_in_place` is not allowed,
/// so the calling thread must drain the queue inline rather than panicking or hanging. /// so the calling thread must drain the queue inline rather than panicking or hanging.
#[tokio::test(flavor = "current_thread")] #[tokio::test(flavor = "current_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_scope_current_thread_runtime() { async fn test_scope_current_thread_runtime() {
let results = tokio::task::spawn_blocking(|| { let results = tokio::task::spawn_blocking(|| {
scope_bounded(16, |scope| { scope_bounded(16, |scope| {
...@@ -360,6 +362,7 @@ mod tests { ...@@ -360,6 +362,7 @@ mod tests {
/// Helpers must actually add parallelism when threads are available: jobs that each block /// Helpers must actually add parallelism when threads are available: jobs that each block
/// briefly should complete in far less than their serial sum. /// briefly should complete in far less than their serial sum.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_scope_runs_in_parallel() { async fn test_scope_runs_in_parallel() {
const JOBS: usize = 16; const JOBS: usize = 16;
const PER_JOB: Duration = Duration::from_millis(50); const PER_JOB: Duration = Duration::from_millis(50);
...@@ -388,6 +391,7 @@ mod tests { ...@@ -388,6 +391,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_scope() { async fn test_scope() {
let results = scope_bounded(1000, |scope| { let results = scope_bounded(1000, |scope| {
for i in 0..1000 { for i in 0..1000 {
...@@ -402,6 +406,7 @@ mod tests { ...@@ -402,6 +406,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_empty_scope() { async fn test_empty_scope() {
let results = scope_bounded(0, |scope| { let results = scope_bounded(0, |scope| {
if false { if false {
...@@ -412,6 +417,7 @@ mod tests { ...@@ -412,6 +417,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_single_task() { async fn test_single_task() {
let results = scope_bounded(1, |scope| { let results = scope_bounded(1, |scope| {
scope.spawn(|| 42); scope.spawn(|| 42);
...@@ -421,6 +427,7 @@ mod tests { ...@@ -421,6 +427,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_task_finish_before_scope() { async fn test_task_finish_before_scope() {
let results = scope_bounded(1, |scope| { let results = scope_bounded(1, |scope| {
scope.spawn(|| 42); scope.spawn(|| 42);
...@@ -431,6 +438,7 @@ mod tests { ...@@ -431,6 +438,7 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_task_finish_after_scope() { async fn test_task_finish_after_scope() {
let results = scope_bounded(1, |scope| { let results = scope_bounded(1, |scope| {
scope.spawn(|| { scope.spawn(|| {
...@@ -443,6 +451,8 @@ mod tests { ...@@ -443,6 +451,8 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
// Relies on `catch_unwind` catching, which needs unwinding; wasm is panic = abort.
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
async fn test_panic_in_scope_factory() { async fn test_panic_in_scope_factory() {
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
let _results = scope_bounded(1000, |scope| { let _results = scope_bounded(1000, |scope| {
...@@ -461,6 +471,8 @@ mod tests { ...@@ -461,6 +471,8 @@ mod tests {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
// Relies on `catch_unwind` catching, which needs unwinding; wasm is panic = abort.
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
async fn test_panic_in_scope_task() { async fn test_panic_in_scope_task() {
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
let _results = scope_bounded(1000, |scope| { let _results = scope_bounded(1000, |scope| {
......
...@@ -508,6 +508,7 @@ mod tests { ...@@ -508,6 +508,7 @@ mod tests {
/// A single `run` call enqueues a large batch of leaves; every one must be processed. /// A single `run` call enqueues a large batch of leaves; every one must be processed.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_wide_burst_of_leaves() { async fn test_unbounded_wide_burst_of_leaves() {
const CHILDREN: usize = 1000; const CHILDREN: usize = 1000;
let processed = Arc::new(AtomicUsize::new(0)); let processed = Arc::new(AtomicUsize::new(0));
...@@ -532,6 +533,7 @@ mod tests { ...@@ -532,6 +533,7 @@ mod tests {
/// A slow seeding iterator must not let the scope finish early. /// A slow seeding iterator must not let the scope finish early.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_slow_seeding_iterator_completes() { async fn test_unbounded_slow_seeding_iterator_completes() {
const SEEDS: usize = 16; const SEEDS: usize = 16;
let processed = Arc::new(AtomicUsize::new(0)); let processed = Arc::new(AtomicUsize::new(0));
...@@ -566,6 +568,7 @@ mod tests { ...@@ -566,6 +568,7 @@ mod tests {
/// Aborting in the middle of a deep, still-growing cascade must terminate rather than hang: /// Aborting in the middle of a deep, still-growing cascade must terminate rather than hang:
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_abort_during_cascade() { async fn test_unbounded_abort_during_cascade() {
// Each item spawns two children until the id exceeds the bound, so the queue is still // Each item spawns two children until the id exceeds the bound, so the queue is still
// growing when the abort lands. // growing when the abort lands.
...@@ -602,6 +605,7 @@ mod tests { ...@@ -602,6 +605,7 @@ mod tests {
/// `remaining_tasks` without queueing it would never reach zero, so this hangs rather than /// `remaining_tasks` without queueing it would never reach zero, so this hangs rather than
/// fails. /// fails.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_spawn_after_abort_is_dropped() { async fn test_unbounded_spawn_after_abort_is_dropped() {
let processed = Arc::new(AtomicUsize::new(0)); let processed = Arc::new(AtomicUsize::new(0));
let processed_clone = processed.clone(); let processed_clone = processed.clone();
...@@ -630,6 +634,7 @@ mod tests { ...@@ -630,6 +634,7 @@ mod tests {
/// Abort on a `current_thread` runtime, where the calling thread is the only drainer. /// Abort on a `current_thread` runtime, where the calling thread is the only drainer.
#[tokio::test(flavor = "current_thread")] #[tokio::test(flavor = "current_thread")]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_abort_current_thread_runtime() { async fn test_unbounded_abort_current_thread_runtime() {
let processed = Arc::new(AtomicUsize::new(0)); let processed = Arc::new(AtomicUsize::new(0));
let processed_clone = processed.clone(); let processed_clone = processed.clone();
...@@ -650,6 +655,7 @@ mod tests { ...@@ -650,6 +655,7 @@ mod tests {
/// swallowed by the wind-down: the abort's queue-clear races the panic's unwind through /// swallowed by the wind-down: the abort's queue-clear races the panic's unwind through
/// `catch_unwind` -> `on_item_finished`. /// `catch_unwind` -> `on_item_finished`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_abort_then_panic() { async fn test_unbounded_abort_then_panic() {
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
scope_unbounded(0..1000usize, |_spawner, item| { scope_unbounded(0..1000usize, |_spawner, item| {
...@@ -671,6 +677,7 @@ mod tests { ...@@ -671,6 +677,7 @@ mod tests {
/// queued. A fixed seed set can drain completely before its first item panics, making it unable /// queued. A fixed seed set can drain completely before its first item panics, making it unable
/// to distinguish a missed abort from valid scheduling. /// to distinguish a missed abort from valid scheduling.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_panic_propagates_and_abandons_queue() { async fn test_unbounded_panic_propagates_and_abandons_queue() {
const MAX_ID: usize = 1 << 14; const MAX_ID: usize = 1 << 14;
let processed = Arc::new(AtomicUsize::new(0)); let processed = Arc::new(AtomicUsize::new(0));
...@@ -708,6 +715,7 @@ mod tests { ...@@ -708,6 +715,7 @@ mod tests {
/// The accumulator must be per-drainer, not shared: collecting into a `Vec` and merging by /// The accumulator must be per-drainer, not shared: collecting into a `Vec` and merging by
/// concatenation must preserve every element even with several drainers running. /// concatenation must preserve every element even with several drainers running.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_with_collects_all_values() { async fn test_unbounded_with_collects_all_values() {
const ITEMS: usize = 500; const ITEMS: usize = 500;
let mut collected = tokio::task::spawn_blocking(|| { let mut collected = tokio::task::spawn_blocking(|| {
...@@ -733,6 +741,7 @@ mod tests { ...@@ -733,6 +741,7 @@ mod tests {
/// With no items, no drainer builds an accumulator, so the result is exactly one `init()` — /// With no items, no drainer builds an accumulator, so the result is exactly one `init()` —
/// not a fold of one per drainer that happened to start. /// not a fold of one per drainer that happened to start.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_with_empty_returns_init() { async fn test_unbounded_with_empty_returns_init() {
let total = tokio::task::spawn_blocking(|| { let total = tokio::task::spawn_blocking(|| {
scope_unbounded_with( scope_unbounded_with(
...@@ -766,6 +775,7 @@ mod tests { ...@@ -766,6 +775,7 @@ mod tests {
/// Aborting returns the results accumulated up to that point rather than discarding them — /// Aborting returns the results accumulated up to that point rather than discarding them —
/// only the abandoned items are missing. The run must still terminate cleanly. /// only the abandoned items are missing. The run must still terminate cleanly.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_with_abort_returns_partial_results() { async fn test_unbounded_with_abort_returns_partial_results() {
let processed = tokio::task::spawn_blocking(|| { let processed = tokio::task::spawn_blocking(|| {
scope_unbounded_with( scope_unbounded_with(
...@@ -794,6 +804,7 @@ mod tests { ...@@ -794,6 +804,7 @@ mod tests {
/// A panic must propagate through the fold path without deadlocking the join, which drainers /// A panic must propagate through the fold path without deadlocking the join, which drainers
/// reach only after their merge. /// reach only after their merge.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_with_panic_propagates() { async fn test_unbounded_with_panic_propagates() {
let result = catch_unwind(AssertUnwindSafe(|| { let result = catch_unwind(AssertUnwindSafe(|| {
scope_unbounded_with( scope_unbounded_with(
...@@ -816,6 +827,7 @@ mod tests { ...@@ -816,6 +827,7 @@ mod tests {
/// The accumulator may borrow `'env` data (it is not `'static`), mirroring how `run` may. /// The accumulator may borrow `'env` data (it is not `'static`), mirroring how `run` may.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn test_unbounded_with_borrowed_accumulator() { fn test_unbounded_with_borrowed_accumulator() {
let label = String::from("item"); let label = String::from("item");
let count = with_runtime(4, move || { let count = with_runtime(4, move || {
...@@ -852,6 +864,7 @@ mod tests { ...@@ -852,6 +864,7 @@ mod tests {
/// worker has certainly timed out — so reaching the second item at all exercises the respawn /// worker has certainly timed out — so reaching the second item at all exercises the respawn
/// path rather than a still-live worker. /// path rather than a still-live worker.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_worker_respawns_after_going_idle() { async fn test_unbounded_worker_respawns_after_going_idle() {
let inits = Arc::new(AtomicUsize::new(0)); let inits = Arc::new(AtomicUsize::new(0));
let counted = inits.clone(); let counted = inits.clone();
...@@ -895,6 +908,7 @@ mod tests { ...@@ -895,6 +908,7 @@ mod tests {
/// A scope that never has queued work must not occupy a worker at all. /// A scope that never has queued work must not occupy a worker at all.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_empty_spawns_no_workers() { async fn test_unbounded_empty_spawns_no_workers() {
let inits = Arc::new(AtomicUsize::new(0)); let inits = Arc::new(AtomicUsize::new(0));
let counted = inits.clone(); let counted = inits.clone();
...@@ -919,6 +933,7 @@ mod tests { ...@@ -919,6 +933,7 @@ mod tests {
// This test is too slow to run under Miri. // This test is too slow to run under Miri.
#[cfg(not(miri))] #[cfg(not(miri))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
async fn test_unbounded_busy_queue_does_not_churn_workers() { async fn test_unbounded_busy_queue_does_not_churn_workers() {
const ITEMS: usize = 20_000; const ITEMS: usize = 20_000;
let inits = Arc::new(AtomicUsize::new(0)); let inits = Arc::new(AtomicUsize::new(0));
...@@ -954,6 +969,7 @@ mod tests { ...@@ -954,6 +969,7 @@ mod tests {
/// The join must not depend on tokio scheduling, even when every runtime thread is contended /// The join must not depend on tokio scheduling, even when every runtime thread is contended
/// and workers are still mid-drain. /// and workers are still mid-drain.
#[test] #[test]
#[cfg_attr(target_family = "wasm", ignore = "parking_lot cannot block on wasm")]
fn test_unbounded_join_under_thread_starvation() { fn test_unbounded_join_under_thread_starvation() {
let runtime = tokio::runtime::Builder::new_multi_thread() let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2) .worker_threads(2)
......
...@@ -975,6 +975,7 @@ mod tests { ...@@ -975,6 +975,7 @@ mod tests {
#[test] #[test]
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
#[should_panic(expected = "TaskId exceeds 31 bits")] #[should_panic(expected = "TaskId exceeds 31 bits")]
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn task_output_panics_on_out_of_range_task_id() { fn task_output_panics_on_out_of_range_task_id() {
// `TASK_ID_MAX + 1` is the first value that sets bit 31. // `TASK_ID_MAX + 1` is the first value that sets bit 31.
// SAFETY: non-zero. // SAFETY: non-zero.
...@@ -985,6 +986,7 @@ mod tests { ...@@ -985,6 +986,7 @@ mod tests {
#[test] #[test]
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
#[should_panic(expected = "TaskId exceeds 31 bits")] #[should_panic(expected = "TaskId exceeds 31 bits")]
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn task_cell_panics_on_out_of_range_task_id() { fn task_cell_panics_on_out_of_range_task_id() {
// SAFETY: non-zero. // SAFETY: non-zero.
let task = unsafe { TaskId::new_unchecked(TASK_ID_MAX + 1) }; let task = unsafe { TaskId::new_unchecked(TASK_ID_MAX + 1) };
...@@ -995,6 +997,7 @@ mod tests { ...@@ -995,6 +997,7 @@ mod tests {
#[test] #[test]
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
#[should_panic(expected = "exceeds")] #[should_panic(expected = "exceeds")]
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn cell_id_panics_on_out_of_range_type_id() { fn cell_id_panics_on_out_of_range_type_id() {
// SAFETY: `MAX_VALUE_TYPE_ID + 1` is non-zero. // SAFETY: `MAX_VALUE_TYPE_ID + 1` is non-zero.
let type_id = unsafe { ValueTypeId::new_unchecked(CellId::MAX_VALUE_TYPE_ID + 1) }; let type_id = unsafe { ValueTypeId::new_unchecked(CellId::MAX_VALUE_TYPE_ID + 1) };
...@@ -1003,6 +1006,7 @@ mod tests { ...@@ -1003,6 +1006,7 @@ mod tests {
#[test] #[test]
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
#[should_panic(expected = "exceeds")] #[should_panic(expected = "exceeds")]
#[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
fn cell_id_panics_on_out_of_range_index() { fn cell_id_panics_on_out_of_range_index() {
let type_id = unsafe { ValueTypeId::new_unchecked(1) }; let type_id = unsafe { ValueTypeId::new_unchecked(1) };
let _ = CellId::new(type_id, CellId::MAX_CELL_INDEX + 1); let _ = CellId::new(type_id, CellId::MAX_CELL_INDEX + 1);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment