Skip to content
Closed
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 crates/js-component-bindgen-component/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ impl From<GenerateOptions> for TranspileConfig {
.maybe_cm_runtime_es_module(options.cm_runtime_es_module)
.maybe_cm_runtime_sync_imports(options.cm_runtime_sync_imports)
.runtime_profile(options.runtime_profile.map(Into::into).unwrap_or_default())
.perf_sync_fast_path(options.perf_sync_fast_path.unwrap_or(false))
.perf_sync_fast_path(options.perf_sync_fast_path.unwrap_or(true))
.build()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ world js-component-bindgen {
perf-strings-skip-copy-utf16-validation: option<bool>,

/// Call synchronous exports and imports without creating a task for each
/// call (they create one by default).
/// call. Defaults to true; set it to false to create a task for every call.
///
/// Applies only to a component in which that cannot be observed: one
/// component instance, with no asynchronous function, lift or lower, no
Expand Down Expand Up @@ -335,7 +335,7 @@ world js-component-bindgen {
imports: list<string>,
exports: list<tuple<string, export-type>>,
/// Why the sync fast path is not used, set only when perf-sync-fast-path
/// was set and the component is not eligible.
/// was not disabled and the component is not eligible.
sync-fast-path-blocker: option<string>,
}

Expand Down
4 changes: 4 additions & 0 deletions crates/js-component-bindgen/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ impl Files {
}
}

pub fn get(&self, name: &str) -> Option<&[u8]> {
self.files.get(name).map(Vec::as_slice)
}

pub fn get_size(&mut self, name: &str) -> Option<usize> {
self.files.get(name).map(|data| data.len())
}
Expand Down
39 changes: 39 additions & 0 deletions crates/js-component-bindgen/src/transpile_bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -988,11 +988,28 @@ impl JsBindgen<'_> {
);
}

// A composition can embed the same core module more than once. Each
// copy after the first reuses the first one's compiled module rather
// than being emitted and compiled again.
let duplicate_of = duplicate_core_modules(files, name, self.core_module_cnt);

// Setup the compilation data and compilation promises
let mut removed = BTreeSet::new();
for i in 0..self.core_module_cnt {
let local_name = format!("module{i}");
let mut name_idx = core_file_name(name, i as u32);
if let Some(original) = duplicate_of[i] {
// Leave a gap that later files fill, as for an inlined module
files.remove(&name_idx).unwrap();
if self.opts.instantiation_mode.is_none() {
assert!(removed.insert(i));
}
uwriteln!(
compilation_promises,
"const {local_name} = module{original};"
);
continue;
}
if self.opts.instantiation_mode.is_some() {
uwriteln!(
compilation_promises,
Expand Down Expand Up @@ -7507,6 +7524,28 @@ fn core_file_name(name: &str, idx: u32) -> String {
format!("{name}.core{i_str}.wasm")
}

/// For each core module, the index of the first earlier core module with the
/// same bytes, if there is one.
fn duplicate_core_modules(files: &Files, name: &str, module_count: usize) -> Vec<Option<usize>> {
let mut first_by_len: HashMap<usize, Vec<usize>> = HashMap::new();
let mut duplicate_of = Vec::with_capacity(module_count);
for index in 0..module_count {
let bytes = files
.get(&core_file_name(name, index as u32))
.expect("core module file");
let candidates = first_by_len.entry(bytes.len()).or_default();
let original = candidates
.iter()
.copied()
.find(|&candidate| files.get(&core_file_name(name, candidate as u32)) == Some(bytes));
if original.is_none() {
candidates.push(index);
}
duplicate_of.push(original);
}
duplicate_of
}

/// Encode a [`StringEncoding`] as a string that can be used in Javascript
fn string_encoding_js_literal(val: &wasmtime_environ::component::StringEncoding) -> &'static str {
match val {
Expand Down
9 changes: 5 additions & 4 deletions docs/src/advanced/performance/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,17 @@ All of these are off by default, except where noted.

### Sync fast path

Skips the per-call task state for components whose functions are all synchronous.
On by default. Skips the per-call task state for components whose functions are all synchronous.
See [Sync fast path](./sync-fast-path.md).

```sh
jco transpile component.wasm -o out --perf-sync-fast-path
# opt out
jco transpile component.wasm -o out --no-perf-sync-fast-path
```

```js
const result = await transpile(bytes, { perfSyncFastPath: true });
// Set only when the option could not apply, e.g. "call tracking is enabled"
const result = await transpile(bytes);
// Set only when the fast path could not apply, e.g. "call tracking is enabled"
console.log(result.syncFastPathBlocker);
```

Expand Down
23 changes: 12 additions & 11 deletions docs/src/advanced/performance/sync-fast-path.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ By default, every call of a component function creates Component Model task stat
thread for an export, and a subtask and a host task for an import. Asynchronous functions need that
state. A component whose functions are all synchronous pays for it without using it.

`jco transpile --perf-sync-fast-path` (`perfSyncFastPath` in the JS API) generates the synchronous
exports and imports of such a component without that state. The option is off by default.
`jco transpile` generates the synchronous exports and imports of such a component without that
state. This is on by default; `--no-perf-sync-fast-path` (`perfSyncFastPath: false` in the JS API)
creates the state for every call.

## When it applies

Expand All @@ -22,13 +23,13 @@ that is skipped:
- no import or export is asynchronous through `--async-mode jspi`;
- `--call-tracking`, `--js` and the optimized import bindings are not in use.

Any other component is generated exactly as without the option, and nothing is printed by
Any other component is generated exactly as with the option off, and nothing is printed by
default.

When the option was set but did not apply, the transpile result says which of the rules above
ruled it out. The JS API exposes `syncFastPathBlocker`. In Rust, `transpile_with_diagnostics`
When the fast path was not disabled but did not apply, the transpile result says which of the
rules above ruled it out. The JS API exposes `syncFastPathBlocker`. In Rust, `transpile_with_diagnostics`
returns the output and a `TranspileDiagnostics` value with a `sync_fast_path_blocker` field.
The field is unset when the option applied or was not set. With `JCO_DEBUG` set,
The field is unset when the fast path applied or was disabled. With `JCO_DEBUG` set,
`jco transpile` and `@bytecodealliance/jco-transpile` also log it with `console.debug`, for
example `component [calls] does not use the sync fast path (perfSyncFastPath): call tracking is
enabled`.
Expand Down Expand Up @@ -58,14 +59,14 @@ The tests of the option run the same sequences of calls with and without it and
return value, thrown error, reported trap and host callback.

One difference is known. When a host function throws `null` or `undefined` and the guest catches
it, the export fails by default with an internal error that says its task is already resolved;
on the fast path it fails with the thrown value.
it, the export fails with `--no-perf-sync-fast-path` with an internal error that says its task is
already resolved; on the fast path it fails with the thrown value.

## Measured effect

Nanoseconds per call, bindings with the runtime bundled in, Node.js 26.13 on Linux x86-64:

| case | default | `--perf-sync-fast-path` | speedup |
| case | `--no-perf-sync-fast-path` | fast path | speedup |
| --- | ---: | ---: | ---: |
| export `u32 -> u32` | 711 | 18 | 40x |
| export `f64 -> f64` | 735 | 33 | 22x |
Expand All @@ -84,8 +85,8 @@ The numbers come from `packages/jco-transpile/bench/perf`, which interleaves fre
each variant; the table keeps the fastest of four observations per case:

```sh
node gen.mjs base embedded
node gen.mjs fast embedded --perf-sync-fast-path
node gen.mjs base embedded --no-perf-sync-fast-path
node gen.mjs fast embedded
node compare.mjs --runs=4 base fast
```

Expand Down
2 changes: 1 addition & 1 deletion docs/src/transpiling.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Options include:
* `--variants-inline-cases`: Inlines WIT variant cases in their discriminated unions instead of exporting a named interface for every case. The named interfaces remain the default for backwards compatibility.
* `--use-namespace-objects`: Exports namespace objects for WIT enums, flags, and variants. This implies `--flags-as-bigint` and cannot be combined with `--variants-inline-cases`.
* `--enum-values-screaming-snake-case`: Represents WIT enum values as `SCREAMING_SNAKE_CASE` strings instead of their original kebab-case names.
* `--perf-sync-fast-path`: Call synchronous exports and imports without creating a Component Model task for each call. Applies only to a component of one instance that uses no asynchronous function, stream, future, JSPI import or export, call tracking or `--js`; other components are generated as without the option. Off by default. See [Sync fast path](./advanced/performance/sync-fast-path.md).
* `--no-perf-sync-fast-path`: Create a Component Model task for every call of a synchronous export or import. By default, a component of one instance that uses no asynchronous function, stream, future, JSPI import or export, call tracking or `--js` calls them without one; other components are generated the same either way. See [Sync fast path](./advanced/performance/sync-fast-path.md).
* `--tracing`: Emit tracing calls for all function entry and exits.
* `--call-tracking`: Emit optional invocation handles to observe selected guest execution. See [Tracking individual calls](./advanced/call-tracking.md).
* `--no-component-error-wrapping`: Throw the lifted error payload directly for a top-level `result::err` instead of wrapping it in a generated `ComponentError`. Jco preserves wrapping by default for compatibility.
Expand Down
2 changes: 1 addition & 1 deletion packages/jco-transpile/bench/perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The first argument to `gen.mjs` names the directory under `../output/perf/`.
Generating the same name again replaces its bindings. The second argument is
either `embedded` or a runtime directory relative to the current working directory.
Additional arguments go to the transpiler, e.g. `node gen.mjs debug embedded --profile=debug`,
or `node gen.mjs fast embedded --perf-sync-fast-path` to skip the task of synchronous calls.
or `node gen.mjs base embedded --no-perf-sync-fast-path` to create a task for every synchronous call.
To compare runtime revisions, build each runtime and supply its dist directory under a distinct variant name.

`compare.mjs` takes the baseline first, followed by one or more variants.
Expand Down
6 changes: 4 additions & 2 deletions packages/jco-transpile/src/transpile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ export interface TranspilationOptions {
/**
* Call synchronous exports and imports without creating a task for each call
*
* On by default; set it to `false` to create a task for every call.
*
* Applies only to a component in which that cannot be observed: one component instance,
* with no asynchronous function, lift or lower, no stream, future or error context, no
* JSPI import or export, no built-in other than those of resources, and neither call
Expand Down Expand Up @@ -245,7 +247,7 @@ interface TranspilationResult {
imports: string[];
exports: [string, 'function' | 'instance'][];
/**
* Why the sync fast path is not used, set only when `perfSyncFastPath` was requested
* Why the sync fast path is not used, set only when `perfSyncFastPath` was not disabled
* and the component is not eligible. Logged when `JCO_DEBUG` is set.
*/
syncFastPathBlocker?: string;
Expand Down Expand Up @@ -410,7 +412,7 @@ export async function transpileBytes(
strict: opts.strict === true,
perfStringsSkipCopyUtf8Validation: opts.perfStringsSkipCopyUtf8Validation === true,
perfStringsSkipCopyUtf16Validation: opts.perfStringsSkipCopyUtf16Validation === true,
perfSyncFastPath: opts.perfSyncFastPath === true,
perfSyncFastPath: opts.perfSyncFastPath !== false,
cmRuntimeEsModule: opts.cmRuntimeEsModule,
cmRuntimeSyncImports: opts.cmRuntimeSyncImports,
runtimeProfile: opts.runtimeProfile,
Expand Down
4 changes: 2 additions & 2 deletions packages/jco-transpile/test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ pnpm --filter @bytecodealliance/jco-transpile test

All test commands accept Vitest filters and options.

Set `JCO_TEST_PERF_SYNC_FAST_PATH=1` to transpile with `perfSyncFastPath`
wherever a test does not set the option itself.
Set `JCO_TEST_PERF_SYNC_FAST_PATH=0` to transpile without `perfSyncFastPath`
(or `1` to force it on) wherever a test does not set the option itself.
The option must not change behavior,
so only tests that assert on the text of generated bindings may differ.

Expand Down
66 changes: 66 additions & 0 deletions packages/jco-transpile/test/duplicate-core-modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { mkdtemp, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { expect, test } from 'vitest';

import { parse } from '../src/wasm-tools.js';
import { transpileBytes, writeFiles } from './transpilation.js';

// The counter module is embedded twice, around a different module, as a composition
// embeds a component it instantiates more than once. It has no names, so that no name
// section tells the copies apart.
const COUNTER = `(global (mut i32) (i32.const 0))
(func (export "bump") (result i32)
(global.set 0 (i32.add (global.get 0) (i32.const 1)))
(global.get 0))`;
const WAT = `(component
(core module ${COUNTER})
(core module (func (export "answer") (result i32) i32.const 42))
(core module ${COUNTER})
(core instance $first (instantiate 0))
(core instance $answer (instantiate 1))
(core instance $second (instantiate 2))
(func (export "bump-first") (result u32) (canon lift (core func $first "bump")))
(func (export "answer") (result u32) (canon lift (core func $answer "answer")))
(func (export "bump-second") (result u32) (canon lift (core func $second "bump"))))`;

test.each([
['ES module', undefined],
['instantiation', 'async'],
] as const)('%s output emits and compiles a repeated core module once', async (_name, instantiation) => {
const runtime = fileURLToPath(new URL('../../jco-cm-runtime/', import.meta.url));
const dir = await mkdtemp(join(runtime, '.duplicate-modules-test-'));
try {
const { files } = await transpileBytes(await parse(WAT), {
name: 'duplicates',
base64Cutoff: 0,
...(instantiation ? { instantiation } : {}),
});
const modules = Object.keys(files)
.filter((name) => /\.core\d*\.wasm$/.test(name))
.sort();
expect(modules).toEqual(['duplicates.core.wasm', 'duplicates.core2.wasm']);
expect(files['duplicates.core.wasm']).not.toEqual(files['duplicates.core2.wasm']);

await writeFiles(files, { baseDir: dir });
const module = await import(pathToFileURL(join(dir, 'duplicates.js')).href);
const compiled: string[] = [];
const guest = instantiation
? await module.instantiate(async (name: string) => {
compiled.push(name);
return WebAssembly.compile(files[name] as BufferSource);
}, {})
: module;
if (instantiation) {
expect(compiled.sort()).toEqual(modules);
}

// Instances of one compiled module keep their own state
expect(guest.bumpFirst()).toBe(1);
expect(guest.bumpFirst()).toBe(2);
expect(guest.bumpSecond()).toBe(1);
expect(guest.answer()).toBe(42);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ async function withProbe(check: (probe: Probe) => void) {
name: 'task-regression',
instantiation: 'sync',
cmRuntimeEsModule: defaultRuntimeUrl.href,
// The probe drives the lowering that creates a task for every call
perfSyncFastPath: false,
});
let replacements = 0;
const source = new TextDecoder()
Expand Down
2 changes: 2 additions & 0 deletions packages/jco-transpile/test/external-runtime/async-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ test.concurrent('initialization imports retire their task with named owners', as
name: 'init',
map: { host: './host.js' },
cmRuntimeEsModule: defaultRuntimeUrl.href,
// The probe drives the lowering that creates a task for every call
perfSyncFastPath: false,
});
files['init.js'] = new TextEncoder().encode(
new TextDecoder().decode(files['init.js']) +
Expand Down
15 changes: 13 additions & 2 deletions packages/jco-transpile/test/numeric-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,14 @@ const component = new TextEncoder().encode(`(component
(func (export "double") (param "n" f64) (result f64) (canon lift (core func $i "double")))
(func (export "ping") (canon lift (core func $i "ping"))))`);

test.each(['bundled', 'external'])('%s numeric exports preserve traps, coercion and stop', async (mode) => {
const CASES = [
['bundled', true],
['external', true],
['bundled', false],
['external', false],
] as const;

test.each(CASES)('%s numeric exports preserve traps, coercion and stop (fast path %s)', async (mode, fastPath) => {
// A directory inside the runtime package resolves its standard package
// name through Node's package self-reference, as a consumer would.
const runtime = fileURLToPath(new URL('../../jco-cm-runtime/', import.meta.url));
Expand All @@ -28,8 +35,11 @@ test.each(['bundled', 'external'])('%s numeric exports preserve traps, coercion
name: 'numeric',
instantiation: 'async',
cmRuntimeEsModule: mode === 'external' ? '@bytecodealliance/jco-cm-runtime' : undefined,
perfSyncFastPath: fastPath,
});
expect(new TextDecoder().decode(files['numeric.js'])).toContain('nativeNumericExports');
if (!fastPath) {
expect(new TextDecoder().decode(files['numeric.js'])).toContain('nativeNumericExports');
}
await writeFiles(files, { baseDir: dir });
const { instantiate } = await import(pathToFileURL(join(dir, 'numeric.js')).href);
const guest = await instantiate();
Expand Down Expand Up @@ -68,6 +78,7 @@ test.each(['bundled', 'external'])('%s numeric exports preserve traps, coercion
name: 'strict-numeric',
strict: true,
cmRuntimeEsModule: mode === 'external' ? '@bytecodealliance/jco-cm-runtime' : undefined,
perfSyncFastPath: fastPath,
});
await writeFiles(strict.files, { baseDir: dir });
const direct = await import(pathToFileURL(join(dir, 'strict-numeric.js')).href);
Expand Down
2 changes: 2 additions & 0 deletions packages/jco-transpile/test/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ suite('resources', () => {
extraArgs: {
cmRuntimeEsModule,
...(runtime === 'external' && { cmRuntimeSyncImports: true }),
// The shape checked below is that of a call creating a task
perfSyncFastPath: false,
},
},
},
Expand Down
11 changes: 7 additions & 4 deletions packages/jco-transpile/test/sync-fast-path/eligibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ import { join } from 'node:path';

import { assert, describe, test, vi } from 'vitest';

import { forceSyncFastPath, transpileBytes } from '../transpilation.js';
import { syncFastPathOverride, transpileBytes } from '../transpilation.js';
import { parse } from '../../src/wasm-tools.js';
import { COMPONENT_FIXTURES_DIR } from '../common.js';
import { generate, generatePair, readFixture, remove } from './helpers.js';

describe('--perf-sync-fast-path: when it applies', () => {
test('is off by default', async () => {
test('is on by default', async () => {
const wat = await readFixture('calls');
// (unless the suite itself runs with the option forced on)
const expected = await generate('calls', wat, { instantiation: 'async', perfSyncFastPath: forceSyncFastPath });
// (unless the suite itself runs with the option forced either way)
const expected = await generate('calls', wat, {
instantiation: 'async',
perfSyncFastPath: syncFastPathOverride ?? true,
});
const actual = await generate('calls', wat, { instantiation: 'async' });
try {
assert.strictEqual(actual.source, expected.source);
Expand Down
Loading
Loading