ruvector/crates/ruvector-math-wasm
rUv eafba64fa5
fix(security): RUSTSEC advisories + clippy hardening in RuVector (#504)
* fix(security): RUSTSEC advisories + clippy hardening in RuVector

- Replace all bare `partial_cmp().unwrap()` calls on f32/f64 with
  `.unwrap_or(Ordering::Equal)` to prevent panics on NaN values in
  sorting/max-by operations across ruvllm, ruvector-dag, prime-radiant,
  and rvagent-wasm (12 sites in production code).
- Add input validation guards to the HTTP search endpoint: reject k=0,
  k > 10_000, empty vectors, and vectors exceeding 65_536 dimensions,
  preventing memory exhaustion via unbounded allocations.
- Harden LocalFsBackend::execute in rvagent-cli with env_clear() +
  safe-env allowlist (SEC-005), deadline-based timeout enforcement, and
  1 MB output truncation, matching the security posture of LocalShellBackend.
- Remove 129 occurrences of the deprecated `unused_unit = "allow"` lint
  and 3 occurrences of the removed `clippy::match_on_vec_items` lint from
  Cargo.toml files workspace-wide; both are no-ops in current Rust/Clippy.
- All 653+ tests across ruvector-core, ruvector-server, ruvector-dag,
  rvagent-cli, and prime-radiant pass with zero failures.

Note: `bytes` is already at 1.11.1 (>= 1.10.0); `paste` 1.0.15 is a
transitive dependency with no semver fix available upstream; `cargo audit`
returns clean.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(ci): cargo fmt + restore workspace unused_unit lint allow

- Run cargo fmt --all across all 9 files that drifted from rustfmt style
  (prime-radiant/energy.rs, ruvector-dag/bottleneck.rs+reasoning_bank.rs,
   ruvector-server/points.rs, ruvllm/pretrain_pipeline.rs+report.rs+registry.rs,
   rvagent-cli/app.rs, rvagent-wasm/gallery.rs)
- Add [workspace.lints.clippy] unused_unit = "allow" to root Cargo.toml;
  the per-crate entries removed in the security commit were still needed —
  moving to workspace-level is cleaner and restores -D warnings CI pass

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(ci): remove unneeded unit return type in ruvix bench

Removes `-> ()` from the Fn bound in run_benchmark_with_kernel
(crates/ruvix/benches/src/ruvix.rs:50) — triggers clippy::unused_unit
under -D warnings. Clippy prefers `Fn(&mut Kernel)` without explicit
unit return.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(ci): resolve rustfmt and clippy unused_unit failures

- Run cargo fmt --all to fix long closure formatting in 9 files
  (energy.rs, bottleneck.rs, reasoning_bank.rs, points.rs,
  pretrain_pipeline.rs, report.rs, registry.rs, app.rs, gallery.rs)
- Add unused_unit = "allow" to [lints.clippy] in ruvix-bench and
  ruvector-mincut Cargo.toml files to suppress the unused_unit lint
  that was previously suppressed globally and now fires on two
  Fn(&mut T) -> () and FnMut() -> () function bounds

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 05:40:24 -04:00
..
src style: apply rustfmt across entire codebase 2026-01-28 17:00:26 +00:00
Cargo.toml fix(security): RUSTSEC advisories + clippy hardening in RuVector (#504) 2026-05-23 05:40:24 -04:00
README.md fix: Update ruvector-math-wasm to use @ruvector/math-wasm scoped package 2026-01-11 17:21:16 +00:00

@ruvector/math-wasm

npm version crates.io License WASM

High-performance WebAssembly bindings for advanced mathematical algorithms in vector search and AI.

Brings Optimal Transport, Information Geometry, and Product Manifolds to the browser with near-native performance.

Features

  • 🚀 Optimal Transport - Sliced Wasserstein, Sinkhorn, Gromov-Wasserstein distances
  • 📐 Information Geometry - Fisher Information Matrix, Natural Gradient, K-FAC
  • 🌐 Product Manifolds - E^n × H^n × S^n (Euclidean, Hyperbolic, Spherical)
  • SIMD Optimized - Vectorized operations where available
  • 🔒 Type-Safe - Full TypeScript definitions included
  • 📦 Zero Dependencies - Pure Rust compiled to WASM

Installation

npm install @ruvector/math-wasm
# or
yarn add ruvector-math-wasm
# or
pnpm add ruvector-math-wasm

Quick Start

Browser (ES Modules)

import init, {
  WasmSlicedWasserstein,
  WasmSinkhorn,
  WasmProductManifold
} from '@ruvector/math-wasm';

// Initialize WASM module
await init();

// Compute Sliced Wasserstein distance
const sw = new WasmSlicedWasserstein(100); // 100 projections
const source = new Float64Array([0, 0, 1, 1, 2, 2]); // 3 points in 2D
const target = new Float64Array([0.5, 0.5, 1.5, 1.5, 2.5, 2.5]);
const distance = sw.distance(source, target, 2);
console.log(`Wasserstein distance: ${distance}`);

Node.js

const { WasmSlicedWasserstein } = require('@ruvector/math-wasm');

const sw = new WasmSlicedWasserstein(100);
const dist = sw.distance(source, target, 2);

Use Cases

1. Distribution Comparison in ML

Compare probability distributions for generative models, anomaly detection, or data drift monitoring.

// Compare embedding distributions
const sw = new WasmSlicedWasserstein(200).withPower(2); // W2 distance

const trainEmbeddings = new Float64Array(/* ... */);
const testEmbeddings = new Float64Array(/* ... */);

const drift = sw.distance(trainEmbeddings, testEmbeddings, 768);
if (drift > threshold) {
  console.warn('Data drift detected!');
}

Use product manifolds for hierarchical and semantic search.

const manifold = new WasmProductManifold({
  euclidean_dim: 256,
  hyperbolic_dim: 128,
  spherical_dim: 128,
  curvature_h: -1.0,
  curvature_s: 1.0
});

// Compute distance in mixed-curvature space
const dist = manifold.distance(queryVector, documentVector);

3. Optimal Transport for Image Comparison

const sinkhorn = new WasmSinkhorn(0.01, 100); // regularization, max_iters

// Compare image histograms
const result = sinkhorn.solveTransport(
  costMatrix,
  sourceWeights,
  targetWeights,
  n, m
);

console.log(`Transport cost: ${result.cost}`);
console.log(`Converged: ${result.converged}`);

4. Natural Gradient Optimization

const fisher = new WasmFisherInformation(512);

// Compute Fisher Information Matrix
const fim = fisher.compute(activations);

// Apply natural gradient
const naturalGrad = fisher.naturalGradientStep(gradient, 0.01);

API Reference

Optimal Transport

Class Description
WasmSlicedWasserstein Fast approximation via random projections
WasmSinkhorn Entropy-regularized optimal transport
WasmGromovWasserstein Cross-space structural comparison

Information Geometry

Class Description
WasmFisherInformation Fisher Information Matrix computation
WasmNaturalGradient Natural gradient descent optimizer

Product Manifolds

Class Description
WasmProductManifold E^n × H^n × S^n mixed-curvature space
WasmSphericalSpace Spherical geometry operations

Performance

Benchmarked on M1 MacBook Pro (WASM in Chrome):

Operation Dimension Time
Sliced Wasserstein (100 proj) 1000 points × 128D 2.3ms
Sinkhorn (100 iter) 500 × 500 8.7ms
Product Manifold distance 512D 0.04ms

TypeScript Support

Full TypeScript definitions are included:

import { WasmSlicedWasserstein, WasmSinkhornConfig } from '@ruvector/math-wasm';

const sw: WasmSlicedWasserstein = new WasmSlicedWasserstein(100);
const distance: number = sw.distance(source, target, dim);

Building from Source

# Install wasm-pack
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

# Build
cd crates/ruvector-math-wasm
wasm-pack build --target web --release

# Test
wasm-pack test --headless --chrome

License

MIT OR Apache-2.0