Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,61 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' TArrayDeque fix: removing elements through an
* {@code ArrayDeque}'s iterator, as the game's particle groups do every tick. TeaVM's iterator
* skipped the element after one it removed and then returned null past the end, so the first
* particle to expire in a world crashed the game. Checks every removal pattern of up to ten
* elements, with the deque's contents wrapped around its array at several offsets. Prints
* "probe passed" when every deque holds what's left in order.
*/
public final class ArrayDequeProbe {
private ArrayDequeProbe() {}
public static void main(String[] args) {
String failure = null;
for (int size = 1; size <= 10 && failure == null; size++) {
for (int removed = 0; removed < 1 << size && failure == null; removed++) {
for (int offset = 0; offset < 5 && failure == null; offset++) {
failure = check(size, removed, offset);
}
}
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
/** Null if removing the elements whose bits are set in {@code removed} works, else what went wrong. */
private static String check(int size, int removed, int offset) {
ArrayDeque<Integer> deque = new ArrayDeque<>(8);
for (int i = 0; i < offset; i++) {
deque.add(-1);
}
for (int i = 0; i < offset; i++) {
deque.poll();
}
List<Integer> expected = new ArrayList<>();
for (int i = 0; i < size; i++) {
deque.add(i);
if ((removed & 1 << i) == 0) {
expected.add(i);
}
}
List<Integer> seen = new ArrayList<>();
for (Iterator<Integer> iterator = deque.iterator(); iterator.hasNext(); ) {
Integer value = iterator.next();
seen.add(value);
if (value != null && (removed & 1 << value) != 0) {
iterator.remove();
}
}
List<Integer> left = new ArrayList<>(deque);
if (seen.size() != size || seen.contains(null) || !left.equals(expected)) {
return "size " + size + ", removing " + Integer.toBinaryString(removed) + ", offset " + offset
+ ": iterated " + seen + ", left " + left;
}
return null;
}
}
@@ -0,0 +1,33 @@
import com.viaversion.viaversion.api.minecraft.item.HashedStructuredItem;
import com.viaversion.viaversion.api.minecraft.item.Item;
import com.viaversion.viaversion.api.minecraft.item.StructuredItem;
/**
* Regression probe for Via's StructuredItemRewriter: it tells a data component's value
* apart with {@code value instanceof Item[]}. Prints "probe passed" when arrays of other element
* types (and an interface array of another interface) don't answer true, and real item arrays do.
*/
public final class ArrayInstanceOfProbe {
interface Other {}
private ArrayInstanceOfProbe() {}
public static void main(String[] args) {
Object items = new StructuredItem[] {StructuredItem.empty()};
Object itemIface = new Item[] {StructuredItem.empty()};
Object hashed = new HashedStructuredItem[] {HashedStructuredItem.empty()};
Object others = new Other[] {new Other() {}};
Object strings = new String[] {"a"};
Object objects = new Object[] {"a"};
Object nested = new StructuredItem[][] {{StructuredItem.empty()}};
Object ints = new int[1];
Object intsNested = new int[1][1];
String more = "" + (nested instanceof Item[][]) + (nested instanceof Item[]) + (nested instanceof Other[][])
+ (ints instanceof int[]) + (ints instanceof Object[]) + (intsNested instanceof int[][])
+ (intsNested instanceof Item[][]) + (strings instanceof Object[]) + (null instanceof Item[]);
String result = "" + (items instanceof Item[]) + (itemIface instanceof Item[]) + (hashed instanceof Item[])
+ (others instanceof Item[]) + (strings instanceof Item[]) + (objects instanceof Item[]);
System.out.println((result + more).equals("truetruefalsefalsefalsefalse" + "truefalsefalsetruefalsetruefalsetruefalse") ? "probe passed" : "probe failed: " + result + " " + more);
}
}
@@ -0,0 +1,99 @@
import java.nio.ByteBuffer;
import org.teavm.jso.JSBody;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Measures how bytes cross between Java arrays and JavaScript buffers in the WebAssembly GC build:
* TeaVM's {@code Int8Array.copyFromJavaArray} / {@code copyToJavaArray}, against a route through a
* direct buffer in linear memory, which JavaScript can view and slice. Every message between the
* page and singleplayer's server worker (packets, file changes) crosses this way. Prints the times
* and "probe passed" when both routes agree on the bytes.
*/
public final class ByteCopyProbe {
private ByteCopyProbe() {}
public static void main(String[] args) {
int size = 1 << 20;
byte[] source = new byte[size];
for (int i = 0; i < size; i++) {
source[i] = (byte) (i * 31 + (i >>> 8));
}
ByteBuffer direct = ByteBuffer.allocateDirect(size);
int rounds = 20;
// Warm up both routes.
for (int i = 0; i < 3; i++) {
Int8Array.copyFromJavaArray(source);
viaLinear(source, direct);
}
double start = now();
Int8Array teavm = null;
for (int i = 0; i < rounds; i++) {
teavm = Int8Array.copyFromJavaArray(source);
}
double teavmOut = (now() - start) / rounds;
start = now();
ArrayBuffer linear = null;
for (int i = 0; i < rounds; i++) {
linear = viaLinear(source, direct);
}
double linearOut = (now() - start) / rounds;
start = now();
byte[] back = null;
for (int i = 0; i < rounds; i++) {
back = teavm.copyToJavaArray();
}
double teavmIn = (now() - start) / rounds;
start = now();
byte[] backLinear = null;
for (int i = 0; i < rounds; i++) {
backLinear = fromLinear(linear, direct);
}
double linearIn = (now() - start) / rounds;
boolean same = java.util.Arrays.equals(back, source) && java.util.Arrays.equals(backLinear, source)
&& same(teavm.getBuffer(), linear);
System.out.println("ByteCopyProbe: 1 MiB to JavaScript: copyFromJavaArray " + teavmOut
+ " ms, through linear memory " + linearOut + " ms; back: copyToJavaArray " + teavmIn
+ " ms, through linear memory " + linearIn + " ms");
System.out.println(same ? "probe passed" : "probe failed: the bytes differ");
}
private static ArrayBuffer viaLinear(byte[] source, ByteBuffer direct) {
direct.clear();
direct.put(source, 0, source.length);
return sliceOf(Int8Array.fromJavaBuffer(direct), source.length);
}
private static byte[] fromLinear(ArrayBuffer buffer, ByteBuffer direct) {
int length = buffer.getByteLength();
setInto(Int8Array.fromJavaBuffer(direct), buffer);
byte[] out = new byte[length];
direct.get(0, out, 0, length);
return out;
}
@JSBody(
params = {"view", "length"},
script = "return view.buffer.slice(view.byteOffset, view.byteOffset + length);")
private static native ArrayBuffer sliceOf(Int8Array view, int length);
@JSBody(
params = {"view", "buffer"},
script = "view.set(new Int8Array(buffer));")
private static native void setInto(Int8Array view, ArrayBuffer buffer);
@JSBody(
params = {"a", "b"},
script = "var x = new Int8Array(a), y = new Int8Array(b); if (x.length !== y.length) return false;"
+ "for (var i = 0; i < x.length; i++) if (x[i] !== y[i]) return false; return true;")
private static native boolean same(ArrayBuffer a, ArrayBuffer b);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,35 @@
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.local.LocalChannel;
/**
* {@code Bootstrap.channel(Class)} in the browser build: it works for a channel class whose
* constructor tools/webbuild's ReflectionDeclarations declares, and throws for one it doesn't, as
* it did for PlatformSocketChannel in the server list's legacy ping (which crashed the game).
*/
public final class ChannelClassProbe {
private ChannelClassProbe() {}
/** Public, with a public no-arg constructor, like PlatformSocketChannel; not declared. */
public static final class Undeclared extends LocalChannel {
public Undeclared() {}
}
public static void main(String[] args) {
System.setProperty("io.netty.noUnsafe", "true");
try {
new Bootstrap().channel(LocalChannel.class);
System.out.println("channel(Class) accepted a declared class");
} catch (Throwable t) {
System.out.println("probe failed: channel(Class) threw for a declared class: " + t);
return;
}
try {
new Bootstrap().channel(Undeclared.class);
System.out.println("probe failed: channel(Class) accepted an undeclared class");
} catch (Throwable t) {
System.out.println("channel(Class) threw " + t);
System.out.println("probe passed");
}
}
}
@@ -0,0 +1,413 @@
/**
* Measures what TeaVM's coroutine transformation costs ordinary code in the browser build: the same
* workload compiled twice, once as plain functions and once as coroutines, timed in one module.
*
* <p>The workload looks like the game's hot paths: a loop over objects calling through interfaces
* with several implementations (as block, shape and entity code does), and a small open-addressing
* table whose lookups call the keys' {@code hashCode} and {@code equals} (as every {@code Map.get}
* does). In the game those virtual calls are suspension points because one implementation somewhere
* can block (ADR 0027), so the coroutine copy puts one blocking implementation into each call site's
* reach, never called. Everything else is the same code, duplicated by hand: shared code would merge
* the two copies in TeaVM's flow analysis. Prints nanoseconds per item for each copy, and "probe
* passed".
*
* <p>Each copy has one extra implementation at each call that the loops never call: blocking in
* the coroutine copy, harmless in the plain one, so both call sites are equally polymorphic.
*
* <p>What it found (2026-10-05, release build, Chrome on the desktop): with coroutines the
* coroutine copy takes 8.3 to 8.7 ns an item against 5.5 to 5.9 ns, about 1.5 times as long; in the
* Fast build ({@code -Pteavm.fast}, no coroutines) the two take the same, 5.3 to 5.7 ns. Only the
* callers ({@code coroutineWork}, {@code CTable.get}) are coroutines here; the shapes and keys stay
* plain.
* That's about 0.7 ns for each call through a suspension point, from the coroutine's prologue, the
* check after each call, and locals kept alive and nullable for the save path.
*/
public final class CoroutineCostProbe {
private static final int ITEMS = 200_000;
private static final int ROUNDS = 7;
/** Never true; lets the coroutine copy's blocking implementations suspend. */
static volatile boolean suspend;
static volatile long sink;
static void maybeSleep() {
if (suspend) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
// ----- Plain copy -----
interface PShape {
double value(int i, PVec v);
}
static final class PVec {
double x;
double y;
double z;
PVec(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static final class PBox implements PShape {
final double size;
PBox(double size) {
this.size = size;
}
@Override
public double value(int i, PVec v) {
return v.x * size + v.y - (i & 3);
}
}
static final class PSlab implements PShape {
@Override
public double value(int i, PVec v) {
return v.z * 0.5 + (i & 7);
}
}
static final class PStair implements PShape {
final PShape inner;
PStair(PShape inner) {
this.inner = inner;
}
@Override
public double value(int i, PVec v) {
return inner.value(i + 1, v) * 0.25 + v.y;
}
}
static class PKey {
final int a;
final int b;
PKey(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return a * 31 + b;
}
@Override
public boolean equals(Object o) {
return o instanceof PKey k && k.a == a && k.b == b;
}
}
/** As CBlocking, without the blocking: the same number of implementations at each call. */
static final class PExtra implements PShape {
@Override
public double value(int i, PVec v) {
sink++;
return 0;
}
}
/** As CBlockingKey, without the blocking. */
static final class PExtraKey extends PKey {
PExtraKey() {
super(-1, -1);
}
@Override
public int hashCode() {
sink++;
return 7;
}
@Override
public boolean equals(Object o) {
sink++;
return false;
}
}
static final class PKey2 extends PKey {
PKey2(int a, int b) {
super(a, b);
}
@Override
public int hashCode() {
return a * 17 ^ b;
}
}
static final class PTable {
final Object[] keys = new Object[1024];
final int[] values = new int[1024];
void put(Object key, int value) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null && !keys[slot].equals(key)) {
slot = (slot + 1) & 1023;
}
keys[slot] = key;
values[slot] = value;
}
int get(Object key) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null) {
if (keys[slot].equals(key)) {
return values[slot];
}
slot = (slot + 1) & 1023;
}
return -1;
}
}
static double plainWork(PShape[] shapes, PVec[] vecs, PTable table, Object[] keys) {
double acc = 0;
for (int i = 0; i < ITEMS; i++) {
PVec v = vecs[i & 63];
acc += shapes[i & 7].value(i, v);
acc += table.get(keys[i & 255]);
}
return acc;
}
// ----- Coroutine copy: the same, with one blocking implementation in reach -----
interface CShape {
double value(int i, CVec v);
}
static final class CVec {
double x;
double y;
double z;
CVec(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static final class CBox implements CShape {
final double size;
CBox(double size) {
this.size = size;
}
@Override
public double value(int i, CVec v) {
return v.x * size + v.y - (i & 3);
}
}
static final class CSlab implements CShape {
@Override
public double value(int i, CVec v) {
return v.z * 0.5 + (i & 7);
}
}
static final class CStair implements CShape {
final CShape inner;
CStair(CShape inner) {
this.inner = inner;
}
@Override
public double value(int i, CVec v) {
return inner.value(i + 1, v) * 0.25 + v.y;
}
}
/** Never in the timed loop's array slots it reads; only makes the calls suspension points. */
static final class CBlocking implements CShape {
@Override
public double value(int i, CVec v) {
maybeSleep();
return 0;
}
}
static class CKey {
final int a;
final int b;
CKey(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return a * 31 + b;
}
@Override
public boolean equals(Object o) {
return o instanceof CKey k && k.a == a && k.b == b;
}
}
static final class CKey2 extends CKey {
CKey2(int a, int b) {
super(a, b);
}
@Override
public int hashCode() {
return a * 17 ^ b;
}
}
/** As the game's one blocking toString makes every Object method a suspension point. */
static final class CBlockingKey extends CKey {
CBlockingKey() {
super(-1, -1);
}
@Override
public int hashCode() {
maybeSleep();
return 7;
}
@Override
public boolean equals(Object o) {
maybeSleep();
return false;
}
}
static final class CTable {
final Object[] keys = new Object[1024];
final int[] values = new int[1024];
void put(Object key, int value) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null && !keys[slot].equals(key)) {
slot = (slot + 1) & 1023;
}
keys[slot] = key;
values[slot] = value;
}
int get(Object key) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null) {
if (keys[slot].equals(key)) {
return values[slot];
}
slot = (slot + 1) & 1023;
}
return -1;
}
}
static double coroutineWork(CShape[] shapes, CVec[] vecs, CTable table, Object[] keys) {
double acc = 0;
for (int i = 0; i < ITEMS; i++) {
CVec v = vecs[i & 63];
acc += shapes[i & 7].value(i, v);
acc += table.get(keys[i & 255]);
}
return acc;
}
public static void main(String[] args) throws InterruptedException {
// Threads must exist for TeaVM to compile anything as a coroutine.
Thread other = new Thread(() -> sink++);
other.start();
other.join();
PShape[] pShapes = new PShape[9];
CShape[] cShapes = new CShape[9];
for (int i = 0; i < 8; i++) {
pShapes[i] = switch (i % 3) {
case 0 -> new PBox(i);
case 1 -> new PSlab();
default -> new PStair(new PBox(i + 1));
};
cShapes[i] = switch (i % 3) {
case 0 -> new CBox(i);
case 1 -> new CSlab();
default -> new CStair(new CBox(i + 1));
};
}
cShapes[8] = new CBlocking();
pShapes[8] = new PExtra();
PVec[] pVecs = new PVec[64];
CVec[] cVecs = new CVec[64];
for (int i = 0; i < 64; i++) {
pVecs[i] = new PVec(i, i * 0.5, i * 0.25);
cVecs[i] = new CVec(i, i * 0.5, i * 0.25);
}
PTable pTable = new PTable();
CTable cTable = new CTable();
Object[] pKeys = new Object[257];
Object[] cKeys = new Object[257];
for (int i = 0; i < 256; i++) {
pKeys[i] = (i & 1) == 0 ? new PKey(i, i >> 2) : new PKey2(i, i >> 2);
cKeys[i] = (i & 1) == 0 ? new CKey(i, i >> 2) : new CKey2(i, i >> 2);
pTable.put(pKeys[i], i);
cTable.put(cKeys[i], i);
}
cKeys[256] = new CBlockingKey();
pKeys[256] = new PExtraKey();
// The blocking ones reach the same call sites, as in the game, but are never called in the
// timed loops (they index & 7 and & 255).
if (suspend) {
cTable.put(cKeys[256], 0);
sink += (long) cShapes[8].value(0, cVecs[0]);
pTable.put(pKeys[256], 0);
sink += (long) pShapes[8].value(0, pVecs[0]);
}
for (int round = 0; round < ROUNDS; round++) {
// Alternate which copy runs first, so neither gains from going second.
double a;
double b;
long plain;
long coroutine;
if ((round & 1) == 0) {
long t0 = System.nanoTime();
a = plainWork(pShapes, pVecs, pTable, pKeys);
long t1 = System.nanoTime();
b = coroutineWork(cShapes, cVecs, cTable, cKeys);
plain = t1 - t0;
coroutine = System.nanoTime() - t1;
} else {
long t0 = System.nanoTime();
b = coroutineWork(cShapes, cVecs, cTable, cKeys);
long t1 = System.nanoTime();
a = plainWork(pShapes, pVecs, pTable, pKeys);
coroutine = t1 - t0;
plain = System.nanoTime() - t1;
}
sink += (long) (a + b);
System.out.println("round " + round + ": plain " + String.format("%.2f", plain / (double) ITEMS)
+ " ns/item, coroutine " + String.format("%.2f", coroutine / (double) ITEMS)
+ " ns/item, ratio " + String.format("%.2f", coroutine / (double) plain)
+ (a == b ? "" : " (results differ!)"));
}
System.out.println("probe passed");
}
}
@@ -0,0 +1,100 @@
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
/**
* Round-trips data through the browser build's deflate and inflate streams, written the way the
* game writes chunks and NBT files (a DataOutputStream over a BufferedOutputStream over the
* compressor: single bytes, short and long runs). TeaVM's own DeflaterOutputStream failed partway
* through with zlib's "no progress" (-5), and singleplayer's saved chunks didn't read back. Half
* the trials read back the way a chunk scan does, skipping runs between reads: TeaVM's
* InflaterInputStream.skip overwrote its own compressed input.
*/
public class DeflateProbe {
private static final int TRIALS = 60;
public static void main(String[] args) throws Exception {
Random random = new Random(26);
int failures = 0;
for (int trial = 0; trial < TRIALS; trial++) {
int size = 1 + random.nextInt(trial % 10 == 0 ? 500_000 : 60_000);
byte[] data = new byte[size];
for (int i = 0; i < size; i++) {
data[i] = (byte) (random.nextInt(5) == 0 ? random.nextInt(256) : i % 37);
}
boolean gzip = trial % 3 == 0;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
OutputStream compressor = gzip ? new GZIPOutputStream(bytes) : new DeflaterOutputStream(bytes);
try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(compressor))) {
int position = 0;
while (position < size) {
int kind = random.nextInt(4);
if (kind == 0) {
out.writeByte(data[position++]);
} else {
int length = Math.min(size - position, 1 + random.nextInt(kind == 1 ? 16 : 20_000));
out.write(data, position, length);
position += length;
}
if (random.nextInt(50) == 0) {
out.flush();
}
}
}
byte[] back;
try (InputStream in = gzip
? new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray()))
: new InflaterInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
ByteArrayOutputStream collected = new ByteArrayOutputStream();
byte[] buffer = new byte[1 + random.nextInt(8192)];
boolean skipping = trial % 2 == 1;
int n;
while (true) {
if (skipping && random.nextBoolean()) {
// Skipped bytes are compared as zeros: the expected data gets the same.
int length = random.nextInt(3000);
long skipped = in.skip(length);
int start = collected.size();
for (long k = 0; k < skipped; k++) {
collected.write(0);
}
Arrays.fill(data, Math.min(start, data.length), Math.min(start + (int) skipped, data.length), (byte) 0);
if (skipped < length) {
break;
}
continue;
}
if ((n = in.read(buffer)) <= 0) {
break;
}
collected.write(buffer, 0, n);
}
back = collected.toByteArray();
} catch (Exception e) {
failures++;
System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") failed to read: " + e);
continue;
}
if (!Arrays.equals(back, data)) {
failures++;
System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") came back as " + back.length
+ " different bytes");
}
}
if (failures == 0) {
System.out.println(TRIALS + " deflate round trips came back whole");
System.out.println("probe passed");
} else {
System.out.println("probe failed: " + failures + " of " + TRIALS + " round trips");
}
}
}
@@ -0,0 +1,33 @@
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' Heap fix: direct buffers of a whole number of
* 64 KiB pages, allocated once the heap's last record is in use. TeaVM grew the heap by exactly the
* request, which left the new free record a header too small, and threw OutOfMemoryError with the
* memory far from full: the game's 256x256 colour maps failed to load as soon as the heap's layout
* put an allocated record last. Keeps every buffer (half a gigabyte), so each one lands at the end
* of the heap. Prints "probe passed" when they all fit.
*/
public final class DirectAllocationProbe {
private DirectAllocationProbe() {}
public static void main(String[] args) {
List<ByteBuffer> kept = new ArrayList<>();
try {
// Each odd-sized buffer grows the heap by whole pages and leaves the rest of the last
// page free, a remainder 8 bytes different each time, so one of them fits exactly and
// leaves the last record allocated; the page-sized buffer after it then needs the fix.
for (int k = 0; k < 4096; k++) {
kept.add(ByteBuffer.allocateDirect(65536 - 8 * (k + 1)));
kept.add(ByteBuffer.allocateDirect(65536));
}
} catch (OutOfMemoryError e) {
System.out.println("probe failed: OutOfMemoryError after " + kept.size() + " buffers");
return;
}
System.out.println("probe passed");
}
}
@@ -0,0 +1,178 @@
import io.netty.channel.EventLoop;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalIoHandler;
import java.util.Arrays;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
/**
* Measures how long a task the page's main thread hands to a Netty local event loop (as the
* browser's connections run on) waits before it runs, when the main thread then works for a while
* and waits for the next animation frame, as the game does each frame. Prints the wait's median,
* 95th percentile and max in ms, the frame interval for scale, and "probe passed".
*
* <p>What it found (2026-11-15, headless Chrome, Compatible build): the task ran as soon as the main
* thread stopped for the frame, 6.2 ms after it was handed over with 6 ms of work in between, every
* time. The hop to the loop costs no frame of its own.
*/
public final class EventLoopHopProbe {
private EventLoopHopProbe() {}
static volatile double ranAt;
public static void main(String[] args) throws Exception {
// As app-web's LibraryDefaults sets them.
System.setProperty("io.netty.allocator.type", "unpooled");
System.setProperty("io.netty.noUnsafe", "true");
System.setProperty("io.netty.leakDetection.level", "disabled");
System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01");
System.setProperty("io.netty.processId", "1");
MultiThreadIoEventLoopGroup group = new MultiThreadIoEventLoopGroup(
1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory());
EventLoop loop = group.next();
loop.submit(() -> {}).sync();
// Other threads parked as the game's are (more event loops, timers), each in LockSupport.
MultiThreadIoEventLoopGroup others = new MultiThreadIoEventLoopGroup(
0, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe other"), LocalIoHandler.newFactory());
int parked = 0;
for (io.netty.util.concurrent.EventExecutor other : others) {
other.submit(() -> {}).sync();
parked++;
}
System.out.println("EventLoopHopProbe: " + parked + " other loops parked, "
+ Runtime.getRuntime().availableProcessors() + " processors");
int frames = 240;
for (int pass = 0; pass < 3; pass++) {
boolean slots = pass >= 1;
setSlotEnd(pass == 2 ? 1000 / 60.0 + 1 : 1000 / 60.0 - 2);
// Pass 1 adds the background pool's idle slot as the page has it: after each frame, a
// message that keeps the page busy until 2 ms before the next frame is due.
setIdleSlots(slots);
double[] waits = new double[frames];
double[] ran = new double[frames];
Arrays.fill(ran, -1);
for (int i = 0; i < frames; i++) {
nextFrame();
int index = i;
double handedAt = now();
waits[i] = handedAt;
loop.execute(() -> ran[index] = now());
// The frame's own work: a few ms on the main thread, no yielding.
busy(6);
}
for (int i = 0; i < 30; i++) {
nextFrame();
}
setIdleSlots(false);
for (int i = 0; i < frames; i++) {
waits[i] = ran[i] < 0 ? 1e9 : ran[i] - waits[i];
}
Arrays.sort(waits);
System.out.println("EventLoopHopProbe: " + (pass == 0 ? "no idle slots" : pass == 1 ? "idle slots ending 2 ms before the frame" : "idle slots running 1 ms past the frame")
+ ", hand-off to run, ms: median " + waits[frames / 2] + " p95 " + waits[frames * 95 / 100]
+ " max " + waits[frames - 1]);
}
// As the game since its network wake: the main thread waits for a frame or a message, a
// page callback (a stand-in for the socket's onmessage) wakes it, and it hands the message
// to the loop from there before waiting again.
setIdleSlots(true);
setSlotEnd(1000 / 60.0 - 2);
double[] woken = new double[frames];
double[] wokenRan = new double[frames];
Arrays.fill(wokenRan, -1);
int handed = 0;
startMessages();
while (handed < frames) {
if (!frameOrMessage()) {
int index = handed++;
woken[index] = now();
loop.execute(() -> wokenRan[index] = now());
} else {
busy(6);
}
}
stopMessages();
for (int i = 0; i < 30; i++) {
nextFrame();
}
setIdleSlots(false);
for (int i = 0; i < frames; i++) {
woken[i] = wokenRan[i] < 0 ? 1e9 : wokenRan[i] - woken[i];
}
Arrays.sort(woken);
System.out.println("EventLoopHopProbe: handed over from a wake by a page callback, ms: median "
+ woken[frames / 2] + " p95 " + woken[frames * 95 / 100] + " max " + woken[frames - 1]);
group.shutdownGracefully();
others.shutdownGracefully();
System.out.println("probe passed");
}
private static void busy(double millis) {
double end = now() + millis;
while (now() < end) {
// spin
}
}
@Async
private static native Boolean nextFrame();
private static void nextFrame(AsyncCallback<Boolean> callback) {
requestFrame(() -> callback.complete(true));
}
@Async
private static native Boolean frameOrMessage();
private static void frameOrMessage(AsyncCallback<Boolean> callback) {
waitFrameOrMessage(frame -> callback.complete(frame));
}
@JSFunctor
interface FrameOrMessage extends JSObject {
void run(boolean frame);
}
@JSBody(
params = "callback",
script = "var w = window.__hopWait || (window.__hopWait = { waiter: null, pending: false });"
+ "w.waiter = callback; if (!w.pending) { w.pending = true; requestAnimationFrame(function() {"
+ " w.pending = false; var c = w.waiter; w.waiter = null; if (c) c(true); }); }")
private static native void waitFrameOrMessage(FrameOrMessage callback);
@JSBody(
script = "window.__hopTimer = setInterval(function() { var w = window.__hopWait;"
+ " if (w && w.waiter) { var c = w.waiter; w.waiter = null; c(false); } }, 7);")
private static native void startMessages();
@JSBody(script = "clearInterval(window.__hopTimer);")
private static native void stopMessages();
@JSFunctor
interface Frame extends JSObject {
void run();
}
@JSBody(params = "frame", script = "requestAnimationFrame(function() { frame(); });")
private static native void requestFrame(Frame frame);
@JSBody(
params = "on",
script = "window.__hopSlots = on; if (!on || window.__hopSlotsStarted) return; window.__hopSlotsStarted = true;"
+ "var ch = new MessageChannel(); var last = 0;"
+ "ch.port1.onmessage = function() { var end = last + (window.__hopSlotEnd || 14);"
+ " while (performance.now() < end) {} };"
+ "function frame(t) { if (window.__hopSlots) { last = t; ch.port2.postMessage(0); } requestAnimationFrame(frame); }"
+ "requestAnimationFrame(frame);")
private static native void setIdleSlots(boolean on);
@JSBody(params = "millis", script = "window.__hopSlotEnd = millis;")
private static native void setSlotEnd(double millis);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,69 @@
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
/**
* Whether Netty's event loop knows its own thread in the browser build: {@code inEventLoop()} from
* a task on the loop, and a channel connected through a {@code ChannelInitializer}, as singleplayer's
* server end does. Netty asserts both ({@code DefaultChannelPipeline.invokeHandlerAddedIfNeeded}),
* so a false there fails every connection with an AssertionError.
*/
public final class EventLoopProbe {
private EventLoopProbe() {}
public static void main(String[] args) throws Exception {
// As app-web's LibraryDefaults sets them.
System.setProperty("io.netty.allocator.type", "unpooled");
System.setProperty("io.netty.noUnsafe", "true");
System.setProperty("io.netty.leakDetection.level", "disabled");
System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01");
System.setProperty("io.netty.processId", "1");
boolean assertions = false;
assert assertions = true;
System.out.println("assertions enabled: " + assertions);
EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory());
var loop = group.next();
System.out.println("inEventLoop from main: " + loop.inEventLoop());
boolean[] inside = new boolean[1];
loop.submit(() -> inside[0] = loop.inEventLoop()).sync();
System.out.println("inEventLoop from a task: " + inside[0]);
LocalAddress address = new LocalAddress("probe");
new ServerBootstrap()
.group(group)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {}
})
.bind(address)
.sync();
try {
Channel channel = new Bootstrap()
.group(group)
.channel(LocalChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
System.out.println("initChannel ran, inEventLoop " + channel.eventLoop().inEventLoop());
}
})
.connect(address)
.sync()
.channel();
System.out.println("connected: " + channel.isActive());
System.out.println("probe passed");
} catch (Throwable e) {
System.out.println("probe failed: " + e);
}
}
}
@@ -0,0 +1,71 @@
import java.io.IOException;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
/**
* A failed download, reported to a suspended coroutine from a promise's rejection handler: the
* caller catches it and carries on, and the page doesn't crash.
*
* <p>Reporting it through {@code AsyncCallback.error} crashes the page: TeaVM's WebAssembly GC
* runtime resumes the caller, which catches the exception, and then also rethrows it out of the
* JavaScript callback, where it's an unhandled rejection. The page crashed this way on a missing
* asset index (in the screenshot harness). So {@code incari.app.web.Fetch} and
* {@code WebAudioDecoder} complete with a value that says it failed and throw in Java, as this
* probe does; set {@link #USE_ERROR} to see TeaVM's behavior.
*/
public final class FetchFailureProbe {
/** True to report the failure through {@code AsyncCallback.error}, which crashes the page. */
private static final boolean USE_ERROR = false;
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
@JSBody(
params = {"failed"},
script = "Promise.reject(new Error('HTTP 404')).then(null, function(e) { failed(String(e)); });")
private static native void start(Failed failed);
@Async
private static native String fetch() throws IOException;
private static void fetch(AsyncCallback<String> callback) {
start(message -> {
if (USE_ERROR) {
callback.error(new IOException("Couldn't fetch: " + message));
} else {
callback.complete("failed: " + message);
}
});
}
private static void fetchOrThrow() throws IOException {
String outcome = fetch();
if (outcome.startsWith("failed: ")) {
throw new IOException("Couldn't fetch: " + outcome.substring("failed: ".length()));
}
}
public static void main(String[] args) throws InterruptedException {
try {
fetchOrThrow();
System.out.println("probe failed: no exception");
return;
} catch (IOException e) {
System.out.println("caught " + e.getMessage());
}
try {
fetchOrThrow();
} catch (IOException e) {
System.out.println("caught again " + e.getMessage());
}
// A crash would come as the page's unhandled rejection, after the callback returns.
Thread.sleep(2000);
System.out.println("probe passed");
}
}
@@ -0,0 +1,44 @@
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Regression probe for web-classlib's FileInputStreamAdditions, and for RandomAccessFile's own
* read() since TeaVM 0.16.0: TeaVM's single-byte {@code read()} returned bytes signed, so a byte of
* 0x80 or more read as the end of the file, and the game's {@code NbtIo.read(Path)} (a
* DataInputStream straight over the file) lost {@code servers.dat}. Prints "probe passed" when every
* byte reads back unsigned.
*/
public final class FileReadProbe {
private FileReadProbe() {}
public static void main(String[] args) throws IOException {
File file = new File("/probe.dat");
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0x00, 0x01});
}
StringBuilder problems = new StringBuilder();
try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
int first = in.readUnsignedByte();
int second = in.readUnsignedShort();
short third = in.readShort();
if (first != 0x0A || second != 0xC8FF || third != 1) {
problems.append(" stream: ").append(first).append(',').append(second).append(',').append(third);
}
if (in.read() != -1) {
problems.append(" stream end");
}
}
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
raf.seek(1);
if (raf.read() != 0xC8 || raf.readUnsignedByte() != 0xFF) {
problems.append(" random access");
}
}
System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems);
}
}
@@ -0,0 +1,108 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Regression probe for tools/teavm-patches' TTemplateCollections hashing (ADR 0034): the sets and
* maps {@code Set.of}, {@code Set.copyOf}, {@code Map.of} and {@code Map.ofEntries} make for more
* than two elements. Lookups now probe a table of indices; this checks they answer as a
* {@code HashSet} or {@code HashMap} would, for hits and misses, with colliding hashes, for every
* size up to 40, and that duplicates still throw (of) or are dropped (copyOf). Prints
* "probe passed" when every answer agrees.
*/
public final class ImmutableCollectionsProbe {
private ImmutableCollectionsProbe() {}
/** A key whose hash is chosen, so keys can collide. */
private record Key(int id, int hash) {
@Override
public boolean equals(Object o) {
return o instanceof Key k && k.id == id;
}
@Override
public int hashCode() {
return hash;
}
}
public static void main(String[] args) {
String failure = null;
for (int size = 0; size <= 40 && failure == null; size++) {
for (int spread = 1; spread <= 3 && failure == null; spread++) {
failure = check(size, spread);
}
}
if (failure == null) {
failure = duplicates();
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
/** Keys 0..size-1 whose hashes are id / spread (several share one when spread > 1). */
private static String check(int size, int spread) {
List<Key> keys = new ArrayList<>();
for (int i = 0; i < size; i++) {
keys.add(new Key(i, i / spread));
}
Set<Key> copied = Set.copyOf(keys);
Set<Key> of = Set.of(keys.toArray(new Key[0]));
@SuppressWarnings("unchecked")
Map.Entry<Key, Integer>[] entries = new Map.Entry[size];
for (int i = 0; i < size; i++) {
entries[i] = Map.entry(keys.get(i), i * 10);
}
Map<Key, Integer> map = Map.ofEntries(entries);
Map<Key, Integer> mapCopy = Map.copyOf(new HashMap<>(map));
Set<Key> reference = new HashSet<>(keys);
if (copied.size() != size || of.size() != size || map.size() != size || mapCopy.size() != size) {
return "size " + size + " spread " + spread + ": sizes " + copied.size() + ", " + of.size() + ", " + map.size();
}
if (!new HashSet<>(copied).equals(reference) || !new HashSet<>(of).equals(reference)
|| !new HashSet<>(map.keySet()).equals(reference)) {
return "size " + size + " spread " + spread + ": iteration";
}
// Hits, and misses: ids past the end, some with a hash a present key has.
for (int id = 0; id < size + 20; id++) {
Key probe = new Key(id, id / spread);
boolean present = id < size;
Integer value = present ? id * 10 : null;
if (copied.contains(probe) != present || of.contains(probe) != present
|| map.containsKey(probe) != present || mapCopy.containsKey(probe) != present
|| !java.util.Objects.equals(map.get(probe), value)
|| !java.util.Objects.equals(mapCopy.get(probe), value)
|| map.entrySet().contains(Map.entry(probe, id * 10)) != present
|| (present && map.entrySet().contains(Map.entry(probe, -1)))) {
return "size " + size + " spread " + spread + ": lookup of " + id;
}
}
if (copied.contains("not a key") || map.containsKey("not a key") || map.get("not a key") != null) {
return "size " + size + ": a key of another type";
}
return null;
}
private static String duplicates() {
try {
Set.of(new Key(1, 0), new Key(2, 0), new Key(1, 0));
return "Set.of accepted a duplicate";
} catch (IllegalArgumentException expected) {
// As the JDK's.
}
try {
Map.of(new Key(1, 0), 1, new Key(2, 0), 2, new Key(1, 0), 3);
return "Map.of accepted a duplicate key";
} catch (IllegalArgumentException expected) {
// As the JDK's.
}
Set<Key> copied = Set.copyOf(List.of(new Key(1, 0), new Key(2, 0), new Key(1, 0), new Key(3, 7)));
if (copied.size() != 3 || !copied.contains(new Key(3, 7)) || copied.contains(new Key(4, 7))) {
return "Set.copyOf kept " + copied.size() + " of a list with a duplicate";
}
return null;
}
}
@@ -0,0 +1,135 @@
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Measures inflating packets the way the game's decoder does (one inflater, input and output as
* buffers, a reset after each) in the browser build, against the route before web-classlib's
* Inflater: a new zlib stream per packet (what TeaVM's reset did) and new input and output arrays
* per call (InflaterAdditions). A server's mix of sizes over the compression threshold. Prints
* microseconds per packet and "probe passed" when both routes read the packets back whole.
*
* <p>What it found (2026-11-15, headless Chrome, Compatible build, best of six alternated
* rounds): inflating, 14.2 us a packet with a new stream and arrays each, 11.2 us reset in place;
* deflating, 74.5 us and 60.4 us.
*/
public final class InflatePacketProbe {
private InflatePacketProbe() {}
public static void main(String[] args) throws DataFormatException {
Random random = new Random(26);
int packets = 2000;
byte[][] plain = new byte[packets][];
byte[][] compressed = new byte[packets][];
Deflater deflater = new Deflater();
byte[] buffer = new byte[8192];
for (int i = 0; i < packets; i++) {
// Mostly entity and block updates just over the threshold, some chunks.
int size = i % 25 == 0 ? 20_000 + random.nextInt(60_000) : 256 + random.nextInt(1500);
byte[] data = new byte[size];
for (int j = 0; j < size; j++) {
data[j] = (byte) ((j / 37) % 4 == 0 ? random.nextInt(256) : (j & 7));
}
plain[i] = data;
deflater.setInput(data);
deflater.finish();
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
while (!deflater.finished()) {
out.write(buffer, 0, deflater.deflate(buffer));
}
deflater.reset();
compressed[i] = out.toByteArray();
}
boolean same = true;
for (int round = 0; round < 2; round++) {
same &= asBefore(plain, compressed) && asNow(plain, compressed);
}
// Alternated, best of each, so neither route gains from running second.
double before = Double.MAX_VALUE;
double after = Double.MAX_VALUE;
double deflateNew = Double.MAX_VALUE;
double deflateReset = Double.MAX_VALUE;
for (int round = 0; round < 6; round++) {
double start = now();
same &= asBefore(plain, compressed);
before = Math.min(before, (now() - start) * 1000 / packets);
start = now();
same &= asNow(plain, compressed);
after = Math.min(after, (now() - start) * 1000 / packets);
start = now();
deflateEach(plain, true);
deflateNew = Math.min(deflateNew, (now() - start) * 1000 / packets);
start = now();
deflateEach(plain, false);
deflateReset = Math.min(deflateReset, (now() - start) * 1000 / packets);
}
System.out.println("InflatePacketProbe: inflate per packet: a new stream and arrays each " + before
+ " us, reset in place " + after + " us; deflate per packet: a new stream each " + deflateNew
+ " us, reset in place " + deflateReset + " us");
System.out.println(same ? "probe passed" : "probe failed: a packet didn't read back");
}
/** As before: a new stream per packet, input and output copied through new arrays. */
private static boolean asBefore(byte[][] plain, byte[][] compressed) throws DataFormatException {
boolean same = true;
for (int i = 0; i < plain.length; i++) {
Inflater inflater = new Inflater();
ByteBuffer input = ByteBuffer.wrap(compressed[i]);
byte[] in = new byte[input.remaining()];
input.get(in);
inflater.setInput(in);
ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length);
byte[] out = new byte[output.remaining()];
int written = inflater.inflate(out);
output.put(out, 0, written);
inflater.end();
same &= written == plain[i].length && check(output, plain[i]);
}
return same;
}
/** As the game's decoder now runs: one inflater, the buffer forms, a reset after each. */
private static boolean asNow(byte[][] plain, byte[][] compressed) throws DataFormatException {
boolean same = true;
Inflater inflater = new Inflater();
for (int i = 0; i < plain.length; i++) {
inflater.setInput(ByteBuffer.wrap(compressed[i]));
ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length);
int written = inflater.inflate(output);
inflater.reset();
same &= written == plain[i].length && check(output, plain[i]);
}
inflater.end();
return same;
}
/** As the game's encoder: input array, a kept output array, then a reset (or a new stream, as before). */
private static void deflateEach(byte[][] plain, boolean newEach) {
byte[] buffer = new byte[8192];
Deflater deflater = new Deflater();
for (byte[] data : plain) {
if (newEach) {
deflater.end();
deflater = new Deflater();
}
deflater.setInput(data, 0, data.length);
deflater.finish();
while (!deflater.finished()) {
deflater.deflate(buffer);
}
deflater.reset();
}
deflater.end();
}
private static boolean check(ByteBuffer output, byte[] expected) {
int n = expected.length;
return output.get(0) == expected[0] && output.get(n / 2) == expected[n / 2] && output.get(n - 1) == expected[n - 1];
}
@org.teavm.jso.JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,56 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Regression probe for tools/teavm-patches' ClassInitializerInsertionTransformer fix: a
* class's static initializer runs after its superclass's (JLS 12.4.2). TeaVM ran a subclass's first
* when the first use was {@code new Sub()}. The game numbers entity data by class this way
* ({@code SynchedEntityData.defineId} counts on from the superclass's last id), so creating the
* player on joining a server failed with "Duplicate id value for 0!". Prints "probe passed" when
* ids count up from the root class, as on the JVM.
*/
public final class InitOrderProbe {
static final List<String> ORDER = new ArrayList<>();
static final Map<Class<?>, Integer> LAST_IDS = new HashMap<>();
private InitOrderProbe() {}
/** The next id for {@code type}, after its own or its nearest superclass's last one. */
static int define(Class<?> type) {
Integer last = LAST_IDS.get(type);
Class<?> current = type;
while (last == null && (current = current.getSuperclass()) != Object.class) {
last = LAST_IDS.get(current);
}
int id = last == null ? 0 : last + 1;
LAST_IDS.put(type, id);
ORDER.add(type.getSimpleName() + "=" + id);
return id;
}
static class Root {
static final int FIRST = define(Root.class);
static final int SECOND = define(Root.class);
}
static class Middle extends Root {
static final int THIRD = define(Middle.class);
}
/** No initializer of its own between two classes that have one. */
static class Plain extends Middle {}
static final class Leaf extends Plain {
static final int FOURTH = define(Leaf.class);
}
public static void main(String[] args) {
new Leaf();
String expected = "[Root=0, Root=1, Middle=2, Leaf=3]";
String actual = ORDER.toString();
System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual);
}
}
@@ -0,0 +1,52 @@
import java.util.concurrent.locks.LockSupport;
/**
* Regression probe for tools/teavm-patches' TObject fix: a thread interrupted in
* {@code wait()} holds the monitor again when the InterruptedException arrives, so it leaves its
* {@code synchronized} block normally. TeaVM threw without the monitor, and the block's exit threw
* IllegalMonitorStateException: the game's sound thread, parked through web-classlib's
* {@code LockSupport} and interrupted when the sound engine stops (joining a world), crashed the
* game this way. Prints "probe passed" when both a plain wait and a park end cleanly.
*/
public final class InterruptedWaitProbe {
private static final Object LOCK = new Object();
private static volatile String waitResult = "not run";
private static volatile String parkResult = "not run";
private InterruptedWaitProbe() {}
public static void main(String[] args) throws InterruptedException {
Thread waiter = new Thread(() -> {
try {
synchronized (LOCK) {
try {
LOCK.wait();
waitResult = "woke without an interrupt";
} catch (InterruptedException e) {
waitResult = Thread.holdsLock(LOCK) ? "ok" : "interrupted without the monitor";
}
}
} catch (IllegalMonitorStateException e) {
waitResult = "IllegalMonitorStateException leaving the block";
}
});
Thread parker = new Thread(() -> {
try {
LockSupport.park();
parkResult = Thread.currentThread().isInterrupted() ? "ok" : "returned without the interrupt";
} catch (IllegalMonitorStateException e) {
parkResult = "IllegalMonitorStateException in park";
}
});
waiter.start();
parker.start();
Thread.sleep(50);
waiter.interrupt();
parker.interrupt();
waiter.join();
parker.join();
boolean passed = waitResult.equals("ok") && parkResult.equals("ok");
System.out.println(passed ? "probe passed" : "probe failed: wait " + waitResult + ", park " + parkResult);
}
}
@@ -0,0 +1,124 @@
/**
* Checks that Java threads behave the same in the Fast build (fibers on JSPI, {@code -Pteavm.fast})
* as with TeaVM's coroutines in the Compatible build: sleeping, waiting and notifying, joining,
* exceptions thrown after a thread resumed and caught across the frames that waited, and
* {@code Thread.currentThread()} after each wait. Times a wait/notify ping-pong between two threads, the cost of a thread switch. Prints
* "probe passed" or "probe failed: ...". Run it in both builds.
*/
public final class JspiProbe {
private static final int PING_PONGS = 2000;
static final Object LOCK = new Object();
static int turn;
static volatile String failure;
static void check(boolean condition, String what) {
if (!condition && failure == null) {
failure = what;
}
}
static int sleepThenThrow(int depth) throws InterruptedException {
if (depth == 0) {
Thread.sleep(1);
throw new IllegalStateException("after the sleep");
}
return sleepThenThrow(depth - 1) + 1;
}
public static void main(String[] args) throws InterruptedException {
Thread main = Thread.currentThread();
long t0 = System.currentTimeMillis();
Thread.sleep(20);
long slept = System.currentTimeMillis() - t0;
check(slept >= 15, "slept only " + slept + " ms");
check(Thread.currentThread() == main, "the main thread changed over a sleep");
try {
sleepThenThrow(20);
check(false, "no exception after the sleep");
} catch (IllegalStateException e) {
check("after the sleep".equals(e.getMessage()), "wrong exception: " + e);
}
check(Thread.currentThread() == main, "the main thread changed over a throw");
// Three threads, each sleeping and counting, joined.
int[] counts = new int[3];
Thread[] workers = new Thread[3];
for (int i = 0; i < 3; i++) {
int index = i;
workers[i] = new Thread(() -> {
Thread self = Thread.currentThread();
for (int n = 0; n < 5; n++) {
try {
Thread.sleep(1 + index);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
check(Thread.currentThread() == self, "worker " + index + " resumed as another thread");
counts[index]++;
}
}, "worker-" + i);
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
check(Thread.currentThread() == main, "the main thread changed over joins");
for (int i = 0; i < 3; i++) {
check(counts[i] == 5, "worker " + i + " counted " + counts[i]);
}
// Ping-pong: two threads hand a turn back and forth through wait/notify.
Thread pong = new Thread(() -> {
for (int n = 0; n < PING_PONGS; n++) {
synchronized (LOCK) {
while (turn != 1) {
try {
LOCK.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
turn = 0;
LOCK.notifyAll();
}
}
}, "pong");
pong.start();
long p0 = System.nanoTime();
for (int n = 0; n < PING_PONGS; n++) {
synchronized (LOCK) {
turn = 1;
LOCK.notifyAll();
while (turn != 0) {
LOCK.wait();
}
}
}
long p1 = System.nanoTime();
pong.join();
check(Thread.currentThread() == main, "the main thread changed over the ping-pong");
System.out.println("ping-pong: " + String.format("%.1f", (p1 - p0) / 1000.0 / PING_PONGS / 2)
+ " us a switch over " + PING_PONGS + " round trips");
// An uncaught exception in a thread goes to its handler, and the program goes on.
Throwable[] uncaught = new Throwable[1];
Thread thrower = new Thread(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
throw new IllegalArgumentException("uncaught");
});
thrower.setUncaughtExceptionHandler((t, e) -> uncaught[0] = e);
thrower.start();
thrower.join();
check(uncaught[0] instanceof IllegalArgumentException, "uncaught exception not handled: " + uncaught[0]);
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
}
@@ -0,0 +1,60 @@
/**
* Probe for tools/webbuild's {@code MathIntrinsics}: {@code Math.floor}, {@code ceil} and
* {@code sqrt} compiled to WebAssembly's own instructions give Java's answers, signed zeros,
* infinities and NaN included. Prints "probe passed" when every case matches its bits (any NaN
* matches any NaN).
*/
public final class MathProbe {
private MathProbe() {}
private static final double[] INPUTS = {
0.0, -0.0, 0.5, -0.5, 1.5, -1.5, 2.0, -2.0, 1e300, -1e300, 4503599627370495.5, -4503599627370495.5,
Double.MIN_VALUE, -Double.MIN_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN, 2.0,
1e-300, 0.1
};
// Java's answers for INPUTS, in order: floor, ceil, sqrt.
private static final double[][] EXPECTED = {
{0.0, 0.0, 0.0},
{-0.0, -0.0, -0.0},
{0.0, 1.0, 0.7071067811865476},
{-1.0, -0.0, Double.NaN},
{1.0, 2.0, 1.224744871391589},
{-2.0, -1.0, Double.NaN},
{2.0, 2.0, 1.4142135623730951},
{-2.0, -2.0, Double.NaN},
{1e300, 1e300, 1e150},
{-1e300, -1e300, Double.NaN},
{4503599627370495.0, 4503599627370496.0, 6.710886399999999e7},
{-4503599627370496.0, -4503599627370495.0, Double.NaN},
{0.0, 1.0, 2.2227587494850775e-162},
{-1.0, -0.0, Double.NaN},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY},
{Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN},
{Double.NaN, Double.NaN, Double.NaN},
{2.0, 2.0, 1.4142135623730951},
{0.0, 1.0, 1e-150},
{0.0, 1.0, 0.31622776601683794},
};
public static void main(String[] args) {
int failures = 0;
for (int i = 0; i < INPUTS.length; i++) {
double x = INPUTS[i];
double[] got = {Math.floor(x), Math.ceil(x), Math.sqrt(x)};
for (int k = 0; k < 3; k++) {
if (!same(got[k], EXPECTED[i][k])) {
failures++;
System.out.println("probe mismatch: " + new String[] {"floor", "ceil", "sqrt"}[k] + "(" + x
+ ") = " + got[k] + ", expected " + EXPECTED[i][k]);
}
}
}
System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " mismatches");
}
private static boolean same(double a, double b) {
return Double.isNaN(a) ? Double.isNaN(b) : Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b);
}
}
@@ -0,0 +1,33 @@
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Regression probe for tools/webbuild's TypeCaptures: a Netty encoder decides which
* messages it takes from its superclass's type argument, read by reflection. The browser build
* kept no generic superclasses for Netty's handlers, so every encoder took every message: the
* game's {@code PacketEncoder} ({@code MessageToByteEncoder<Packet<T>>}) was handed its pipeline's
* configuration messages and failed with a ClassCastException. Prints "probe passed" when an
* encoder of the same shape takes its own messages and passes others by.
*/
public final class MessageTypeProbe {
/** A generic message, like the game's {@code Packet<T>}. */
interface Box<T> {}
static final class StringBox implements Box<String> {}
static final class BoxEncoder<T> extends MessageToByteEncoder<Box<T>> {
@Override
protected void encode(ChannelHandlerContext ctx, Box<T> message, ByteBuf out) {}
}
private MessageTypeProbe() {}
public static void main(String[] args) throws Exception {
BoxEncoder<String> encoder = new BoxEncoder<>();
boolean takesBox = encoder.acceptOutboundMessage(new StringBox());
boolean takesOther = encoder.acceptOutboundMessage("not a box");
System.out.println(takesBox && !takesOther ? "probe passed" : "probe failed: " + takesBox + ", " + takesOther);
}
}
@@ -0,0 +1,15 @@
/**
* Regression probe for web-classlib's {@code Module} and {@code ModuleLayer}: the check the
* game's {@code JvmProfiler} makes in its static initializer, which the first packet sent reaches.
* Without them the survey's rules turned the calls into nulls and the initializer threw, so the
* handshake never left. Prints "probe passed" when the check runs and finds no {@code jdk.jfr}.
*/
public final class ModuleProbe {
private ModuleProbe() {}
public static void main(String[] args) {
boolean jfr = Runtime.class.getModule().getLayer().findModule("jdk.jfr").isPresent();
System.out.println(!jfr ? "probe passed" : "probe failed: jdk.jfr found");
}
}
@@ -0,0 +1,246 @@
import java.util.ArrayDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Measures what handing a packet to the game's thread costs in the browser build (the lead in ADR
* 0032's "Not done"). The game decodes each packet on the network's thread and calls its handler
* there; the handler's first line ({@code PacketUtils.ensureRunningOnSameThread}) queues the packet
* for the game's thread and throws a shared, stack-less {@code RunningOnDifferentThreadException},
* which {@code Connection.channelRead0} catches. In the page's profiles that function's own time was
* 2.5% of combat's samples, and the profile can't say whether it's the throw or the queueing.
*
* <p>Times, per packet, each part on its own, through three calls as in the game (the handoff's
* check, the packet's {@code handle}, the connection's dispatch), the calls made through
* interfaces with two implementations each so they stay calls: the call path alone; the thread
* check; the queueing (an {@code ArrayDeque}, and a {@code ConcurrentLinkedQueue} as the game's
* {@code PacketProcessor} has); the throw and catch; and all of it, as the game does it. Each also
* through frames compiled as coroutines (most of the game's packet handlers are: a call that could
* suspend, never made); from the stack's bottom and 30 calls up; on the page's main thread, in a
* thread that slept first, and in one that never suspended. Prints the figures and "probe passed".
*
* <p>What it found (2026-10-03, Chrome on the desktop, development and release builds alike): the
* throw and catch is most of the handoff, 65 to 100 ns on the page's main thread, and 640 to
* 860 ns on any other thread, slept or not, against 5 to 15 ns for the calls and 20 to 30 ns for
* either queue. The stack's depth doesn't matter. The game's network runs on another thread, so
* every packet pays the dear throw.
*/
public final class PacketHandoffProbe {
private static final int PACKETS = 50_000;
private static final int ROUNDS = 5;
/** As the game's exception: shared, no stack trace. */
static final class Handoff extends RuntimeException {
static final Handoff INSTANCE = new Handoff();
private Handoff() {
setStackTrace(new StackTraceElement[0]);
}
@Override
public synchronized Throwable fillInStackTrace() {
setStackTrace(new StackTraceElement[0]);
return this;
}
}
record Queued(Object listener, Object packet) {}
/**
* What the handoff does: 0 nothing, 1 check, 2 queue (an ArrayDeque), 3 queue (a
* ConcurrentLinkedQueue, as the game's PacketProcessor), 4 throw, 5 check + queue + throw as the
* game (the concurrent queue).
*/
static int mode;
/** Never true; makes the coroutine variants' methods able to suspend. */
static volatile boolean suspend;
static final ArrayDeque<Queued> QUEUE = new ArrayDeque<>();
static final ConcurrentLinkedQueue<Queued> CONCURRENT = new ConcurrentLinkedQueue<>();
static Thread gameThread;
static volatile long sink;
interface Handler {
void handle(Object packet);
}
interface Dispatch {
void read(Handler handler, Object packet);
}
static void handoff(Object listener, Object packet) {
switch (mode) {
case 1 -> {
if (Thread.currentThread() == gameThread) {
sink++;
}
}
case 2 -> QUEUE.add(new Queued(listener, packet));
case 3 -> CONCURRENT.add(new Queued(listener, packet));
case 4 -> throw Handoff.INSTANCE;
case 5 -> {
if (Thread.currentThread() != gameThread) {
CONCURRENT.add(new Queued(listener, packet));
throw Handoff.INSTANCE;
}
}
default -> {}
}
}
static void maybeSuspend() {
if (suspend) {
Thread.yield();
}
}
static final class PlainHandler implements Handler {
@Override
public void handle(Object packet) {
handoff(this, packet);
sink += packet.hashCode();
}
}
static final class OtherHandler implements Handler {
@Override
public void handle(Object packet) {
sink -= packet.hashCode();
}
}
static final class CoroutineHandler implements Handler {
@Override
public void handle(Object packet) {
maybeSuspend();
handoff(this, packet);
maybeSuspend();
sink += packet.hashCode();
}
}
static final class PlainDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
try {
handler.handle(packet);
} catch (Handoff e) {
sink++;
}
}
}
static final class OtherDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
sink--;
}
}
static final class CoroutineDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
maybeSuspend();
try {
handler.handle(packet);
} catch (Handoff e) {
sink++;
}
maybeSuspend();
}
}
private PacketHandoffProbe() {}
public static void main(String[] args) {
// The game's thread is another: the check fails, as on the network's thread.
gameThread = new Thread(() -> {});
StringBuilder report = new StringBuilder("PacketHandoffProbe, ns a packet (best of " + ROUNDS + "):\n");
// From the stack's bottom, and from deep in it, as the game's network pipeline is.
for (int depth : new int[] {0, 30}) {
report.append(deep(depth, depth));
}
// Depth -1: a thread that slept first; -2: a thread that never suspended.
// And in a thread that has suspended and resumed, as the network's event loop has: it
// waits for each message.
StringBuilder resumed = new StringBuilder();
Thread network = new Thread(() -> {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
resumed.append(measure(-1));
});
network.start();
try {
network.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
report.append(resumed);
// A thread that never suspended, to tell the thread from the suspension.
StringBuilder fresh = new StringBuilder();
Thread plain = new Thread(() -> fresh.append(measure(-2)));
plain.start();
try {
plain.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
report.append(fresh);
System.out.println(report);
System.out.println("probe passed");
}
/** Measures {@code depth} calls down the stack. */
static String deep(int remaining, int depth) {
if (remaining > 0) {
String result = deep(remaining - 1, depth);
sink += result.length();
return result;
}
return measure(depth);
}
static String measure(int depth) {
Object packet = new Object();
Handler[] handlers = {new PlainHandler(), new OtherHandler(), new CoroutineHandler()};
Dispatch[] dispatches = {new PlainDispatch(), new OtherDispatch(), new CoroutineDispatch()};
String[] modes = {"call path only", "thread check", "ArrayDeque add", "concurrent add", "throw and catch", "as the game (all)"};
StringBuilder report = new StringBuilder();
for (int variant = 0; variant < 2; variant++) {
Handler handler = handlers[variant == 0 ? 0 : 2];
Dispatch dispatch = dispatches[variant == 0 ? 0 : 2];
// The other implementations, called once, so neither interface has a single target.
dispatches[1].read(handlers[1], packet);
handlers[1].handle(packet);
for (int m = 0; m < modes.length; m++) {
mode = m;
double best = Double.MAX_VALUE;
for (int round = 0; round < ROUNDS + 1; round++) {
QUEUE.clear();
CONCURRENT.clear();
long start = System.nanoTime();
for (int i = 0; i < PACKETS; i++) {
dispatch.read(handler, packet);
if ((i & 1023) == 0) {
QUEUE.clear();
// As the game's thread drains it each frame.
while (CONCURRENT.poll() != null) {}
}
}
double ns = (System.nanoTime() - start) / (double) PACKETS;
if (round > 0) {
best = Math.min(best, ns);
}
}
report.append(String.format(
" depth %3d %-10s %-18s %8.1f%n",
depth, variant == 0 ? "plain" : "coroutine", modes[m], best));
}
}
return report.toString();
}
}
@@ -0,0 +1,49 @@
# Probes
Small programs compiled alone with TeaVM against the browser build's class library and run in
headless Chromium, in seconds rather than the full build's ten minutes (`app-web/README.md`,
Experiments). Regression probes guard a fix in `tools/teavm-patches`, `tools/webbuild` or
`web-classlib` and print "probe passed". Measurements print the cost an ADR relied on; checks confirm a behaviour the build depends on.
```sh
app-web/probes/run.sh <Name> [Gradle options] # for example -Pteavm.fast, -Pbrowser.gpu=webgpu
```
| Probe | Kind | What it checks |
| --- | --- | --- |
| `ArrayDequeProbe` | Regression | tools/teavm-patches' TArrayDeque fix |
| `ArrayInstanceOfProbe` | Regression | Via's StructuredItemRewriter |
| `ByteCopyProbe` | Measurement | How bytes cross between Java arrays and JavaScript buffers |
| `ChannelClassProbe` | Check | `Bootstrap.channel(Class)` throws for a channel class ReflectionDeclarations doesn't declare |
| `CoroutineCostProbe` | Measurement | What TeaVM's coroutine transformation costs ordinary code (ADR 0036) |
| `DeflateProbe` | Check | The build's deflate and inflate streams, used as the game writes chunks and NBT |
| `DirectAllocationProbe` | Regression | Heap growth (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `EventLoopProbe` | Regression | Netty's event loop and a channel's pipeline setup under TeaVM (its assertions hold; the catalog's Netty must be the game's) |
| `EventLoopHopProbe` | Measurement | How long a task handed to a Netty local event loop waits when the main thread then ends its frame |
| `FetchFailureProbe` | Check | A failed download reported to a suspended coroutine is caught, and the page doesn't crash |
| `FileReadProbe` | Regression | web-classlib's FileInputStreamAdditions, and `RandomAccessFile.read` (fixed in TeaVM 0.16.0) |
| `ImmutableCollectionsProbe` | Regression | tools/teavm-patches' TTemplateCollections hashing (ADR 0034) |
| `InflatePacketProbe` | Measurement | Inflating and deflating packets with a reset in place, against a new zlib stream each (ADR 0075) |
| `InitOrderProbe` | Regression | tools/teavm-patches' ClassInitializerInsertionTransformer fix |
| `InterruptedWaitProbe` | Regression | tools/teavm-patches' TObject fix |
| `JspiProbe` | Check | Java threads behave the same in the Fast build (JSPI) as in the Compatible build |
| `MathProbe` | Check | tools/webbuild's `MathIntrinsics`: `Math.floor`, `ceil` and `sqrt` as WebAssembly instructions |
| `MessageTypeProbe` | Regression | tools/webbuild's TypeCaptures |
| `ModuleProbe` | Regression | web-classlib's `Module` and `ModuleLayer` |
| `PacketHandoffProbe` | Measurement | What handing a packet to the game's thread costs (ADR 0033) |
| `ReloadLeakProbe` | Check | Memory held across page reloads in one tab (read with a CDP script) |
| `SharableProbe` | Regression | tools/webbuild's RemovalTransformer |
| `SocketDeliveryProbe` | Measurement | What handing one WebSocket message from the page's queue to Java costs |
| `StorageProbe` | Regression | platform-web's file system (ADR 0011) under TeaVM's own java.io and java.nio.file |
| `SuppressedProbe` | Regression | Suppressed exceptions (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `SuspendingReflectionProbe` | Regression | tools/teavm-patches' CoroutineTransformation fix for non-nullable locals |
| `SuspendingTernaryProbe` | Regression | A suspending `c ? a : b` (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `ThreadLocalProbe` | Check | web-classlib's `ThreadLocal` across thread switches |
| `ThrowCensusProbe` | Check | The throw census, `-Pteavm.throwCensus` (ADR 0033) |
| `ViaPipelineUtilProbe` | Regression | web-classlib's substitute for Via's `PipelineUtil` |
| `ViaTypeTokenProbe` | Regression | TypeCaptures' entry for Via's bundled Gson |
| `WaitRoutingProbe` | Regression | tools/webbuild's MonitorElision routing every `Object.wait` through web-classlib's `Waits` |
| `WeakQueueProbe` | Check | References polled from a ReferenceQueue keep their own class's methods |
| `WebGpuCallProbe` | Measurement | What one WebGPU call costs from Java (`docs/webgpu-backend.md`) |
| `WrapIntProbe` | Check | `int`s reach JavaScript as the same Numbers (tools/webbuild's `JsoIntrinsics`) |
| `ZipFileProbe` | Regression | tools/teavm-patches' TZipFile fix |
@@ -0,0 +1,39 @@
/**
* Holds 50 MB and parks a thread on a monitor for good, then prints "probe ready". Loaded several
* times in one tab (tools: a CDP script reloading it and reading the heap after a collection), it
* shows whether a reloaded page's module, its objects and its suspended threads are freed. With
* the Fast build (JSPI, {@code -Pteavm.fast}) a thread parked forever is a suspended engine stack.
*
* <p>What it found (2026-10-05, Chromium 151 and 153): the coroutine build's heap stayed under
* 2 MB over five loads (its parked thread holds nothing the engine sees), the JSPI build's grew
* 50 MB a load: V8 never frees a suspended stack, so every earlier page stayed whole. Ending the
* fibers on {@code pagehide} (jspi.ts) keeps it at the one live page's 51 MB.
*/
public final class ReloadLeakProbe {
static final Object LOCK = new Object();
static byte[][] held;
public static void main(String[] args) throws InterruptedException {
held = new byte[50][];
for (int i = 0; i < held.length; i++) {
held[i] = new byte[1 << 20];
held[i][i] = (byte) i;
}
Thread parked = new Thread(() -> {
synchronized (LOCK) {
while (true) {
try {
LOCK.wait();
} catch (InterruptedException e) {
return;
}
}
}
}, "parked");
parked.setDaemon(true);
parked.start();
Thread.sleep(50);
System.out.println("probe ready " + held[7][7]);
}
}
@@ -0,0 +1,28 @@
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Regression probe for tools/webbuild's RemovalTransformer: Netty's {@code @Sharable} check
* reads the annotation at run time, through a class TeaVM generates for it
* ({@code ChannelHandler$Sharable$$_impl}). The removal step took that class for a missing one,
* since it doesn't exist until after transformers run, and replaced it with a throwing reference
* under the catch-all Netty rule: adding any handler to a pipeline threw. Prints "probe passed"
* when a sharable handler reads as sharable and another doesn't.
*/
public final class SharableProbe {
@ChannelHandler.Sharable
static final class Shared extends ChannelInboundHandlerAdapter {}
static final class NotShared extends ChannelInboundHandlerAdapter {}
private SharableProbe() {}
public static void main(String[] args) {
ChannelHandlerAdapter shared = new Shared();
ChannelHandlerAdapter notShared = new NotShared();
boolean passed = shared.isSharable() && !notShared.isSharable();
System.out.println(passed ? "probe passed" : "probe failed: " + shared.isSharable() + ", " + notShared.isSharable());
}
}
@@ -0,0 +1,136 @@
import java.nio.ByteBuffer;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Measures what delivering one WebSocket message from the page's queue to Java costs in the
* WebAssembly GC build (platform-web's {@code WebSocketNetwork}), for a server's mix of packet
* sizes: the route as it was (each entry's type read as a string, its time, its buffer wrapped in a
* new Int8Array, then copied) against an entry's type as a number and the copy made from a view the
* page built when the message came. Prints microseconds per message and "probe passed" when all
* routes read the same bytes.
*/
public final class SocketDeliveryProbe {
private SocketDeliveryProbe() {}
public static void main(String[] args) {
int messages = 20_000;
JSObject queue = fill(messages);
long expected = 0;
for (int round = 0; round < 3; round++) {
expected = asBefore(queue, messages);
numbered(queue, messages);
}
int rounds = 10;
double start = now();
long before = 0;
for (int i = 0; i < rounds; i++) {
before = asBefore(queue, messages);
}
double beforeMicros = (now() - start) * 1000 / rounds / messages;
start = now();
long after = 0;
for (int i = 0; i < rounds; i++) {
after = numbered(queue, messages);
}
double afterMicros = (now() - start) * 1000 / rounds / messages;
start = now();
long copyOnly = 0;
for (int i = 0; i < rounds; i++) {
copyOnly = copyOnly(queue, messages);
}
double copyMicros = (now() - start) * 1000 / rounds / messages;
System.out.println("SocketDeliveryProbe: per message (mean " + meanSize(queue, messages) + " B): as before "
+ beforeMicros + " us, numbered types and kept views " + afterMicros + " us, the copy alone "
+ copyMicros + " us");
boolean same = expected == before && before == after && after == copyOnly;
System.out.println(same ? "probe passed" : "probe failed: the routes read different bytes");
}
private static long asBefore(JSObject queue, int count) {
long sum = 0;
double now = now();
double longest = 0;
for (int i = 0; i < count; i++) {
longest = Math.max(longest, now - queuedTime(queue, i));
switch (queuedType(queue, i)) {
case "message" -> {
byte[] message = new Int8Array(queuedData(queue, i)).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
default -> {}
}
}
return sum + (longest < 0 ? 1 : 0);
}
private static long numbered(JSObject queue, int count) {
long sum = 0;
double now = now();
double longest = 0;
for (int i = 0; i < count; i++) {
longest = Math.max(longest, now - queuedTime(queue, i));
if (kind(queue, i) == 1) {
byte[] message = view(queue, i).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
}
return sum + (longest < 0 ? 1 : 0);
}
private static long copyOnly(JSObject queue, int count) {
long sum = 0;
for (int i = 0; i < count; i++) {
byte[] message = view(queue, i).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
return sum;
}
private static long checksum(ByteBuffer buffer) {
int n = buffer.remaining();
return n == 0 ? 0 : n * 31L + buffer.get(0) + buffer.get(n - 1);
}
private static int meanSize(JSObject queue, int count) {
long total = 0;
for (int i = 0; i < count; i++) {
total += view(queue, i).getLength();
}
return (int) (total / count);
}
// A server's mix: mostly small (movement, entity motion), some medium, a few chunks.
@JSBody(
params = "count",
script = "var q = [], t = [], n = [], v = []; var seed = 26;"
+ "function rnd() { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; }"
+ "for (var i = 0; i < count; i++) { var r = rnd();"
+ " var size = r < 0.8 ? 8 + (rnd() * 40 | 0) : r < 0.97 ? 100 + (rnd() * 900 | 0) : 4000 + (rnd() * 20000 | 0);"
+ " var b = new ArrayBuffer(size); var a = new Int8Array(b);"
+ " for (var j = 0; j < size; j += 7) a[j] = (i + j) & 127;"
+ " q.push(['message', b]); t.push(performance.now()); n.push(1); v.push(a); }"
+ "return {q: q, t: t, n: n, v: v};")
private static native JSObject fill(int count);
@JSBody(params = {"s", "i"}, script = "return s.q[i][0];")
private static native String queuedType(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.q[i][1];")
private static native ArrayBuffer queuedData(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.t[i];")
private static native double queuedTime(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.n[i];")
private static native int kind(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.v[i];")
private static native Int8Array view(JSObject s, int i);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,94 @@
import incari.platform.web.storage.WebFileSystem;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Stream;
/**
* Regression probe for platform-web's file system (ADR 0011) under TeaVM's own java.io and
* java.nio.file: installs it, as WebMain does, and uses files the ways the game does (directories
* made with Files.createDirectories, the server list's temporary file and rename, a channel opened
* with CREATE, RandomAccessFile keeping its bytes, listing and walking), then flushes to the
* storage worker. Run it twice: the second run also finds what the first stored. Prints
* "probe passed" when everything reads back as written.
*/
public final class StorageProbe {
private StorageProbe() {}
public static void main(String[] args) throws IOException {
WebFileSystem files = WebFileSystem.install(List.of("/incari/dropped"));
StringBuilder problems = new StringBuilder();
Path game = Path.of("/incari/game");
Path marker = game.resolve("probe-runs.txt");
int runs = Files.exists(marker) ? Integer.parseInt(Files.readString(marker).trim()) : 0;
System.out.println("[probe] earlier runs stored: " + runs + " (backend " + files.backend() + ")");
Path downloads = game.resolve("downloads");
Files.createDirectories(downloads);
if (!Files.isDirectory(downloads) || Files.exists(Path.of("/incari/game/incari"))) {
problems.append(" createDirectories");
}
try (FileChannel log = FileChannel.open(
downloads.resolve("log.json"), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
log.write(ByteBuffer.wrap("{}\n".getBytes(StandardCharsets.UTF_8)));
}
// ServerList.save: a temporary file, then Util.safeReplaceFile's renames.
Path temporary = Files.createTempFile(game, "servers", ".dat");
Files.write(temporary, new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0});
Path servers = game.resolve("servers.dat");
if (Files.exists(servers)) {
Files.move(servers, game.resolve("servers.dat_old"), StandardCopyOption.REPLACE_EXISTING);
}
Files.move(temporary, servers, StandardCopyOption.REPLACE_EXISTING);
try (InputStream in = Files.newInputStream(servers);
DataInputStream data = new DataInputStream(in)) {
if (data.readUnsignedByte() != 0x0A || data.readUnsignedShort() != 0xC8FF) {
problems.append(" servers.dat");
}
}
File region = game.resolve("r.0.0.mca").toFile();
// TeaVM's RandomAccessFile doesn't create a missing file in "rw" mode, as the JDK's does;
// the game opens its region files through FileChannel, which does (web-classlib).
region.createNewFile();
try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) {
raf.write("0123456789".getBytes(StandardCharsets.US_ASCII));
}
try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) {
raf.seek(4);
raf.write('x');
}
if (!Files.readString(region.toPath()).equals("0123x56789")) {
problems.append(" random access: ").append(Files.readString(region.toPath()));
}
Files.writeString(game.resolve("options.txt"), "fov:1.0\n");
try (Stream<Path> walk = Files.walk(game)) {
long count = walk.count();
if (count < 6) {
problems.append(" walk ").append(count);
}
}
if (!new File("/incari/classpath").exists() && new File("/tmp").isDirectory()) {
// Nothing mounted in a probe; /tmp is there.
} else if (!new File("/tmp").isDirectory()) {
problems.append(" /tmp");
}
Files.writeString(marker, Integer.toString(runs + 1));
files.flush();
System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems);
}
}
@@ -0,0 +1,20 @@
/**
* Regression probe for tools/teavm-patches' TThrowable fix: {@code getSuppressed} and
* {@code addSuppressed} on a fresh exception. TeaVM's class library left the suppressed array
* null, so both threw NullPointerException; Netty's {@code DefaultPromise.syncUninterruptibly}
* calls {@code getSuppressed} on every failure it rethrows, which hid why a connection failed.
* Prints "probe passed" when an exception starts with none and keeps the one added.
*/
public final class SuppressedProbe {
private SuppressedProbe() {}
public static void main(String[] args) {
RuntimeException failure = new RuntimeException("failure");
int before = failure.getSuppressed().length;
failure.addSuppressed(new IllegalStateException("suppressed"));
Throwable[] after = failure.getSuppressed();
boolean passed = before == 0 && after.length == 1 && after[0].getMessage().equals("suppressed");
System.out.println(passed ? "probe passed" : "probe failed: " + before + ", " + after.length);
}
}
@@ -0,0 +1,74 @@
import io.netty.util.ReferenceCounted;
import java.lang.reflect.Method;
/**
* Regression probe for tools/teavm-patches' CoroutineTransformation fix for non-nullable locals
*: a method called through reflection that takes two or more arguments and suspends. TeaVM
* generates a caller for it that keeps the argument array's data in a non-nullable local, and the
* coroutine transformation's save and restore code read that local where WebAssembly doesn't count
* it as set: the module failed to validate ("uninitialized local").
*
* <p>The method is the one that showed it, Netty's {@code ReferenceCountUtil.touch(Object, Object)},
* which the browser build's reflection policy (tools/webbuild ReflectionDeclarations) already
* declares. It calls {@link ReferenceCounted#touch(Object)}, which suspends here, as it can in the
* game's build, so its reflection caller is a coroutine. Prints "probe passed" when the call
* reaches the object and returns it.
*/
public final class SuspendingReflectionProbe {
/** A reference-counted object whose {@code touch} suspends. */
static final class Touched implements ReferenceCounted {
String hint = "";
@Override
public ReferenceCounted touch(Object hint) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
this.hint = String.valueOf(hint);
return this;
}
@Override
public ReferenceCounted touch() {
return touch(null);
}
@Override
public int refCnt() {
return 1;
}
@Override
public ReferenceCounted retain() {
return this;
}
@Override
public ReferenceCounted retain(int increment) {
return this;
}
@Override
public boolean release() {
return false;
}
@Override
public boolean release(int decrement) {
return false;
}
}
private SuspendingReflectionProbe() {}
public static void main(String[] args) throws ReflectiveOperationException {
Method touch = Class.forName("io.netty.util.ReferenceCountUtil").getMethod("touch", Object.class, Object.class);
Touched message = new Touched();
Object result = touch.invoke(null, message, "hint");
boolean passed = result == message && message.hint.equals("hint");
System.out.println(passed ? "probe passed" : "probe failed: " + result + ", hint " + message.hint);
}
}
@@ -0,0 +1,126 @@
import java.util.ArrayList;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' CoroutineTransformation fix: a conditional
* expression whose one branch suspends, left on the operand stack as an argument of a call that
* suspends too. The two branches build different subclasses of the declared result type, the else
* branch's being the narrower one. Before the fix, the coroutine transformation typed the restore
* block after the conditional with the else branch's class, and the module failed to validate
* ("type error in branch"): the shape of the game's {@code Connection.configureSerialization}
* with Netty's pipeline. Prints "probe passed" when the handlers arrive in order.
*/
public final class SuspendingTernaryProbe {
interface Handler {
String id();
}
abstract static class Base implements Handler {}
static class Wide extends Base {
@Override
public String id() {
return "wide";
}
}
static final class Narrow extends Wide {
@Override
public String id() {
return "narrow";
}
}
/** A handler whose constructor suspends, so the conditional that makes it does too. */
static final class Suspending extends Base {
private final int value;
Suspending(int value) {
this.value = value;
pause();
}
@Override
public String id() {
return "suspending" + value;
}
}
/** An interface call that suspends, with the conditional's value among its arguments. */
interface Pipeline {
Pipeline add(String name, Handler handler);
Pipeline add(Handler... handlers);
}
static final class ListPipeline implements Pipeline {
final List<String> names = new ArrayList<>();
@Override
public Pipeline add(String name, Handler handler) {
pause();
names.add(name + "=" + handler.id());
return this;
}
@Override
public Pipeline add(Handler... handlers) {
for (Handler handler : handlers) {
add("anonymous", handler);
}
return this;
}
}
enum Flow {
IN,
OUT;
Flow opposite() {
return this == IN ? OUT : IN;
}
}
private static final Integer INITIAL = 7;
private SuspendingTernaryProbe() {}
private static void pause() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private static String name(boolean configure) {
return configure ? "configured" : "unconfigured";
}
private static Handler framing(boolean local) {
return local ? new Wide() : new Narrow();
}
static void configure(Pipeline pipeline, Flow inbound, boolean local) {
Flow outbound = inbound.opposite();
boolean configureInbound = inbound == Flow.OUT;
boolean configureOutbound = outbound == Flow.OUT;
pipeline.add("splitter", framing(local))
.add(new Wide())
.add(name(configureInbound), configureInbound ? new Suspending(INITIAL) : new Narrow())
.add("prepender", framing(local))
.add(name(configureOutbound), configureOutbound ? new Suspending(INITIAL) : new Narrow());
}
public static void main(String[] args) {
ListPipeline pipeline = new ListPipeline();
configure(pipeline, Flow.IN, false);
configure(pipeline, Flow.OUT, true);
String expected = "[splitter=narrow, anonymous=wide, unconfigured=narrow, prepender=narrow,"
+ " configured=suspending7, splitter=wide, anonymous=wide, configured=suspending7,"
+ " prepender=wide, unconfigured=narrow]";
String actual = pipeline.names.toString();
System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual);
}
}
@@ -0,0 +1,53 @@
/**
* web-classlib's {@code ThreadLocal} in the browser: four threads take turns through sleeps (each
* wait switches threads, so each thread-local's remembered last thread keeps changing), each
* setting and reading its own value, with {@code withInitial}'s value per thread and after
* {@code remove}. Prints "probe passed". Run it in both builds.
*/
public final class ThreadLocalProbe {
private static final ThreadLocal<String> NAME = new ThreadLocal<>();
private static final ThreadLocal<int[]> COUNTER = ThreadLocal.withInitial(() -> new int[1]);
static volatile String failure;
private ThreadLocalProbe() {}
static void check(boolean condition, String what) {
if (!condition && failure == null) {
failure = what;
}
}
public static void main(String[] args) throws InterruptedException {
NAME.set("main");
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
String name = "worker-" + i;
threads[i] = new Thread(() -> {
check(NAME.get() == null, name + " saw another thread's value");
NAME.set(name);
for (int n = 0; n < 50; n++) {
COUNTER.get()[0]++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
check(name.equals(NAME.get()), name + " read " + NAME.get() + " after a switch");
}
check(COUNTER.get()[0] == 50, name + " counted " + COUNTER.get()[0]);
NAME.remove();
check(NAME.get() == null, name + " still had a value after remove");
}, name);
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
check("main".equals(NAME.get()), "main read " + NAME.get());
check(COUNTER.get()[0] == 0, "main's counter was " + COUNTER.get()[0]);
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
}
@@ -0,0 +1,49 @@
/**
* Checks the throw census (`-Pteavm.throwCensus`, ADR 0033): throws a known number of times on the
* main thread and on another, across one census report, then prints "probe passed". Run with the
* census on and read the "[Incari] Throws" lines: the main thread's site counts 1000 on it, the
* other thread's 3000 off it.
*/
public final class ThrowCensusProbe {
static int caught;
private ThrowCensusProbe() {}
static void fail(int i) {
throw new IllegalStateException("throw " + i);
}
static void failElsewhere(int i) {
throw new UnsupportedOperationException("throw " + i);
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
try {
fail(i);
} catch (IllegalStateException e) {
caught++;
}
}
Thread other = new Thread(() -> {
for (int i = 0; i < 3000; i++) {
try {
failElsewhere(i);
} catch (UnsupportedOperationException e) {
caught++;
}
}
});
other.start();
other.join();
// The census reports at the first throw ten seconds after its first.
Thread.sleep(10_500);
try {
fail(-1);
} catch (IllegalStateException e) {
caught++;
}
System.out.println(caught == 4001 ? "probe passed" : "probe failed: caught " + caught);
}
}
@@ -0,0 +1,29 @@
import com.viaversion.viaversion.util.PipelineUtil;
/**
* Regression probe for web-classlib's substitute for Via's {@code PipelineUtil}: Via's own
* looks up Netty's codec methods reflectively when it loads, which the browser can't do, so the
* class failed to initialize, and Via's checks for a cancelled packet ({@code containsCause})
* failed with it: the first packet Via dropped on purpose (the game's Login Acknowledged, for a
* 1.8 server) ended the connection. Prints "probe passed" when a cause is found inside a wrapper.
*/
public final class ViaPipelineUtilProbe {
private ViaPipelineUtilProbe() {}
public static void main(String[] args) {
Thread thread = new Thread(ViaPipelineUtilProbe::run, "probe");
thread.start();
}
private static void run() {
try {
// Via's own cancel exceptions need a running Via; any cause shows the class loads.
RuntimeException wrapped = new RuntimeException(new java.io.IOException("cancelled"));
boolean found = PipelineUtil.containsCause(wrapped, java.io.IOException.class);
System.out.println(found ? "probe passed" : "probe failed: the cancel wasn't found");
} catch (Throwable t) {
System.out.println("probe failed: " + t);
}
}
}
@@ -0,0 +1,34 @@
import com.viaversion.viaversion.libs.gson.Gson;
import com.viaversion.viaversion.libs.gson.reflect.TypeToken;
import java.util.Map;
/**
* Regression probe for TypeCaptures' entry for Via's bundled Gson: Via reads its 1.12-to-
* 1.13 block ids as {@code Map<String, String[]>} through an anonymous {@code TypeToken}, which
* reads its type argument from its generic superclass. TeaVM keeps no generic signatures unless
* TypeCaptures records them; without the entry, Via's 1.13 data failed to load and no server older
* than 1.13 could be joined. Prints "probe passed" when the map's values come back as arrays.
*/
public final class ViaTypeTokenProbe {
private ViaTypeTokenProbe() {}
public static void main(String[] args) {
Thread thread = new Thread(ViaTypeTokenProbe::run, "probe");
thread.start();
}
private static void run() {
try {
Map<String, String[]> map = new Gson()
.fromJson("{\"stone\": [\"minecraft:stone\", \"minecraft:granite\"]}",
new TypeToken<Map<String, String[]>>() {}.getType());
String[] ids = map.get("stone");
System.out.println(ids != null && ids.length == 2 && ids[1].equals("minecraft:granite")
? "probe passed"
: "probe failed: " + map);
} catch (Throwable t) {
System.out.println("probe failed: " + t);
}
}
}
@@ -0,0 +1,48 @@
/**
* Regression probe for tools/webbuild's MonitorElision routing every {@code Object.wait} through
* web-classlib's {@code Waits}, which times the render thread's waits: plain, timed and
* nanosecond waits still wait, wake on a notify from another thread, and time out; a join and a
* CompletableFuture's join (which wait underneath) still return. The first build that routed waits
* also routed Object's own wait(long) call to wait(long, int), which recursed until the stack ran
* out at start. Prints "probe passed".
*/
public final class WaitRoutingProbe {
private static final Object LOCK = new Object();
private static boolean ready;
private WaitRoutingProbe() {}
public static void main(String[] args) throws Exception {
// A timed wait that times out.
long start = System.currentTimeMillis();
synchronized (LOCK) {
LOCK.wait(30);
LOCK.wait(5, 500);
}
long waited = System.currentTimeMillis() - start;
// A wait that another thread's notify ends.
Thread notifier = new Thread(() -> {
synchronized (LOCK) {
ready = true;
LOCK.notifyAll();
}
});
notifier.start();
synchronized (LOCK) {
while (!ready) {
LOCK.wait();
}
}
notifier.join();
// A future completed on another thread, joined here.
java.util.concurrent.CompletableFuture<String> future = new java.util.concurrent.CompletableFuture<>();
new Thread(() -> future.complete("done")).start();
String joined = future.join();
if (waited >= 30 && ready && joined.equals("done")) {
System.out.println("probe passed");
} else {
System.out.println("probe failed: waited " + waited + " ms, ready " + ready + ", joined " + joined);
}
}
}
@@ -0,0 +1,58 @@
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
/**
* References polled from a ReferenceQueue keep their own class's methods. TeaVM's analysis took
* everything poll() returns for a plain WeakReference, so a method only ever called on polled
* references (Guava's WeakValueReference.getEntry, when a weak-value map reclaims an entry) had
* no code in the subclass, and the call trapped ("dereferencing a null pointer"). Makes garbage
* until the browser collects some referents and the queue hands their references back.
*/
public class WeakQueueProbe {
/** Called through an interface, as Guava calls WeakValueReference.getEntry(). */
interface HasTag {
int tag();
}
static class Tagged extends WeakReference<Object> implements HasTag {
private final int tag;
Tagged(Object referent, ReferenceQueue<Object> queue, int tag) {
super(referent, queue);
this.tag = tag;
}
/** Called only on references that came back from the queue. */
@Override
public int tag() {
return tag;
}
}
public static void main(String[] args) throws Exception {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Tagged[] kept = new Tagged[20_000];
for (int i = 0; i < kept.length; i++) {
kept[i] = new Tagged(new int[64], queue, i + 1);
}
long sum = 0;
int polled = 0;
Object[] churn = new Object[1024];
for (int round = 0; round < 400 && polled == 0; round++) {
for (int i = 0; i < 200_000; i++) {
churn[i & 1023] = new int[32];
}
// Lets the page's event loop run, where the finalization callbacks come.
Thread.sleep(20);
Reference<?> reference;
while ((reference = queue.poll()) != null) {
sum += ((HasTag) reference).tag();
polled++;
}
}
System.out.println("polled " + polled + " references, tags summing to " + sum);
System.out.println(polled > 0 && sum > 0 ? "probe passed" : "probe failed: nothing came back from the queue");
}
}
@@ -0,0 +1,303 @@
import org.teavm.interop.Async;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.JSProperty;
import org.teavm.jso.typedarrays.Int32Array;
import org.teavm.jso.typedarrays.Uint32Array;
import org.teavm.jso.webgl.WebGL2RenderingContext;
import org.teavm.jso.webgl.WebGLUniformLocation;
import org.teavm.jso.webgpu.GPUBindGroup;
import org.teavm.jso.webgpu.GPUDevice;
import org.teavm.jso.webgpu.GPURenderPassEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
/**
* What one WebGPU call costs from Java (docs/webgpu-backend.md, the W0 spike's open question):
* the same frame of draws, each with its own uniform (a dynamic offset), encoded five ways and timed
* on the CPU. Through TeaVM's JSO, a call per command, as a Java backend would; in one JavaScript
* loop, the floor any language could reach; Java writing commands into linear memory and one
* JavaScript call replaying them, the TypeScript layer a backend could fall back on; a render bundle
* recorded once; and WebGL2's uniform and draw per object through JSO, as {@code render-webgl2}
* draws what it doesn't multi-draw. Needs a WebGPU adapter: {@code app-web/probes/run.sh
* WebGpuCallProbe -Pbrowser.gpu=webgpu} (Linux Chrome gives WebGPU only on Vulkan). Prints
* microseconds a draw and "probe passed".
*/
public final class WebGpuCallProbe {
private static final int DRAWS = 2000;
private static final int WARMUP_FRAMES = 20;
private static final int FRAMES = 100;
/** Command codes for the replay route: one int code, then its arguments. */
private static final int SET_BIND_GROUP = 1;
private static final int DRAW_INDEXED = 2;
private WebGpuCallProbe() {}
/**
* TeaVM's render pass, plus the dynamic-offset overload that takes a range of the offsets array,
* which TeaVM's binding lacks: without it each draw would allocate a subarray.
*/
interface Pass extends GPURenderPassEncoder {
void setBindGroup(int index, GPUBindGroup group, Uint32Array offsets, int start, int length);
}
/** What {@link #setUp} made: the pipeline, buffers, bind group and target, and a recorded bundle. */
interface Scene extends JSObject {
@JSProperty
GPUBindGroup bindGroup();
@JSProperty
Uint32Array offsets();
@JSProperty
WebGL2RenderingContext gl();
@JSProperty
WebGLUniformLocation glOffset();
}
@JSFunctor
interface Done extends JSObject {
void done(JSObject value);
}
public static void main(String[] args) {
GPUDevice device = (GPUDevice) requestDevice();
if (device == null) {
System.out.println("probe failed: no WebGPU adapter (" + adapterNote() + ")");
return;
}
System.out.println("WebGpuCallProbe: adapter " + adapterNote() + ", " + DRAWS + " draws a frame, "
+ FRAMES + " frames");
Scene scene = setUp(device, DRAWS);
IntBuffer commands = ByteBuffer.allocateDirect(DRAWS * 8 * 4).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
// An Int32Array over the same linear memory, made once: the replay reads it in place.
Int32Array commandView = Int32Array.fromJavaBuffer(commands);
String[] names = {"JSO, a call per command", "one JavaScript loop", "replayed from linear memory",
"render bundle", "WebGL2 through JSO"};
double[] totals = new double[names.length];
for (int frame = 0; frame < WARMUP_FRAMES + FRAMES; frame++) {
for (int route = 0; route < names.length; route++) {
double start = now();
switch (route) {
case 0 -> {
Pass pass = beginPass(device, scene);
GPUBindGroup group = scene.bindGroup();
Uint32Array offsets = scene.offsets();
for (int i = 0; i < DRAWS; i++) {
pass.setBindGroup(0, group, offsets, i, 1);
pass.drawIndexed(3, 1, 0, 0, 0);
}
endPass(device, scene);
}
case 1 -> {
Pass pass = beginPass(device, scene);
drawAllInJs(pass, scene, DRAWS);
endPass(device, scene);
}
case 2 -> {
Pass pass = beginPass(device, scene);
commands.clear();
for (int i = 0; i < DRAWS; i++) {
commands.put(SET_BIND_GROUP).put(i);
commands.put(DRAW_INDEXED).put(3).put(0).put(0);
}
replay(pass, scene, commandView, commands.position());
endPass(device, scene);
}
case 3 -> {
Pass pass = beginPass(device, scene);
executeBundle(pass, scene);
endPass(device, scene);
}
default -> {
WebGL2RenderingContext gl = scene.gl();
WebGLUniformLocation offset = scene.glOffset();
prepareGl(scene);
for (int i = 0; i < DRAWS; i++) {
gl.uniform4f(offset, (i % 50) * 0.04f - 1, (i / 50) * 0.04f - 1, 0, 0);
gl.drawElements(WebGL2RenderingContext.TRIANGLES, 3, WebGL2RenderingContext.UNSIGNED_SHORT, 0);
}
gl.flush();
}
}
double elapsed = now() - start;
if (frame >= WARMUP_FRAMES) {
totals[route] += elapsed;
}
// Untimed: let the GPU catch up, so the next frame's calls don't wait on a full queue.
if (route == names.length - 1) {
glFinish(scene);
} else {
workDone(device);
}
}
}
for (int route = 0; route < names.length; route++) {
double frameMillis = totals[route] / FRAMES;
System.out.println(String.format(" %-28s %7.3f ms a frame, %6.3f us a draw", names[route], frameMillis,
frameMillis * 1000 / DRAWS));
}
String error = takeError(scene);
System.out.println(error == null ? "probe passed" : "probe failed: " + error);
}
@Async
private static native JSObject requestDevice();
private static void requestDevice(org.teavm.interop.AsyncCallback<JSObject> callback) {
requestDevice(value -> callback.complete(value));
}
@JSBody(
params = "done",
script = "if (!navigator.gpu) { done(null); return; }"
+ "navigator.gpu.requestAdapter().then(function(a) {"
+ " if (!a) return null;"
+ " globalThis.probeAdapter = a.info.vendor + '/' + a.info.architecture"
+ " + (a.info.isFallbackAdapter ? ' (fallback)' : '');"
+ " return a.requestDevice();"
+ "}).then(function(d) { done(d || null); }, function() { done(null); });")
private static native void requestDevice(Done done);
@JSBody(script = "return globalThis.probeAdapter || (navigator.gpu ? 'none' : 'no navigator.gpu');")
private static native String adapterNote();
@Async
private static native JSObject workDone(GPUDevice device);
private static void workDone(GPUDevice device, org.teavm.interop.AsyncCallback<JSObject> callback) {
workDone(device, value -> callback.complete(value));
}
@JSBody(
params = {"device", "done"},
script = "device.queue.onSubmittedWorkDone().then(function() { done(null); });")
private static native void workDone(GPUDevice device, Done done);
/**
* A pipeline drawing one small triangle per draw, moved by a uniform read at a dynamic offset
* (256 bytes apart, WebGPU's minimum); a 256x256 target; the same draws recorded as a bundle;
* and a WebGL2 program doing the same on an OffscreenCanvas.
*/
@JSBody(
params = {"device", "draws"},
script = "var s = {};"
+ "var code = 'struct U { offset: vec4f };'"
+ " + '@group(0) @binding(0) var<uniform> u: U;'"
+ " + '@vertex fn vs(@location(0) p: vec2f) -> @builtin(position) vec4f {'"
+ " + ' return vec4f(p * 0.02 + u.offset.xy, 0.0, 1.0); }'"
+ " + '@fragment fn fs() -> @location(0) vec4f { return vec4f(1.0, 0.5, 0.0, 1.0); }';"
+ "device.pushErrorScope('validation');"
+ "var module = device.createShaderModule({ code: code });"
+ "var layout = device.createBindGroupLayout({ entries: [{ binding: 0,"
+ " visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform', hasDynamicOffset: true } }] });"
+ "s.pipeline = device.createRenderPipeline({"
+ " layout: device.createPipelineLayout({ bindGroupLayouts: [layout] }),"
+ " vertex: { module: module, entryPoint: 'vs', buffers: [{ arrayStride: 8,"
+ " attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] },"
+ " fragment: { module: module, entryPoint: 'fs', targets: [{ format: 'rgba8unorm' }] },"
+ " primitive: { topology: 'triangle-list' } });"
+ "var uniforms = new Float32Array(draws * 64);"
+ "for (var i = 0; i < draws; i++) {"
+ " uniforms[i * 64] = (i % 50) * 0.04 - 1; uniforms[i * 64 + 1] = Math.floor(i / 50) * 0.04 - 1; }"
+ "var ubuf = device.createBuffer({ size: uniforms.byteLength,"
+ " usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(ubuf, 0, uniforms);"
+ "s.bindGroup = device.createBindGroup({ layout: layout,"
+ " entries: [{ binding: 0, resource: { buffer: ubuf, size: 16 } }] });"
+ "s.offsets = new Uint32Array(draws);"
+ "for (var i = 0; i < draws; i++) s.offsets[i] = i * 256;"
+ "s.vbuf = device.createBuffer({ size: 24, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(s.vbuf, 0, new Float32Array([0, 0, 1, 0, 0, 1]));"
+ "s.ibuf = device.createBuffer({ size: 8, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(s.ibuf, 0, new Uint16Array([0, 1, 2, 0]));"
+ "s.view = device.createTexture({ size: [256, 256], format: 'rgba8unorm',"
+ " usage: GPUTextureUsage.RENDER_ATTACHMENT }).createView();"
+ "var b = device.createRenderBundleEncoder({ colorFormats: ['rgba8unorm'] });"
+ "b.setPipeline(s.pipeline); b.setVertexBuffer(0, s.vbuf); b.setIndexBuffer(s.ibuf, 'uint16');"
+ "for (var i = 0; i < draws; i++) { b.setBindGroup(0, s.bindGroup, s.offsets, i, 1);"
+ " b.drawIndexed(3, 1, 0, 0, 0); }"
+ "s.bundle = b.finish();"
+ "device.popErrorScope().then(function(e) { if (e) s.error = e.message; });"
+ "device.onuncapturederror = function(e) { s.error = s.error || e.error.message; };"
+ "var gl = new OffscreenCanvas(256, 256).getContext('webgl2');"
+ "function shader(type, src) { var sh = gl.createShader(type); gl.shaderSource(sh, src);"
+ " gl.compileShader(sh); return sh; }"
+ "var p = gl.createProgram();"
+ "gl.attachShader(p, shader(gl.VERTEX_SHADER, '#version 300 es\\nin vec2 p; uniform vec4 offset;'"
+ " + ' void main() { gl_Position = vec4(p * 0.02 + offset.xy, 0.0, 1.0); }'));"
+ "gl.attachShader(p, shader(gl.FRAGMENT_SHADER, '#version 300 es\\nprecision mediump float;'"
+ " + ' out vec4 c; void main() { c = vec4(1.0, 0.5, 0.0, 1.0); }'));"
+ "gl.bindAttribLocation(p, 0, 'p'); gl.linkProgram(p);"
+ "if (!gl.getProgramParameter(p, gl.LINK_STATUS)) s.error = 'WebGL2 link: ' + gl.getProgramInfoLog(p);"
+ "s.glProgram = p; s.glOffset = gl.getUniformLocation(p, 'offset');"
+ "var vao = gl.createVertexArray(); gl.bindVertexArray(vao);"
+ "var vb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vb);"
+ "gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1]), gl.STATIC_DRAW);"
+ "gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);"
+ "var ib = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib);"
+ "gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0]), gl.STATIC_DRAW);"
+ "s.gl = gl;"
+ "return s;")
private static native Scene setUp(GPUDevice device, int draws);
@JSBody(
params = {"device", "s"},
script = "s.encoder = device.createCommandEncoder();"
+ "var pass = s.encoder.beginRenderPass({ colorAttachments: [{ view: s.view,"
+ " loadOp: 'clear', storeOp: 'store', clearValue: [0, 0, 0, 1] }] });"
+ "pass.setPipeline(s.pipeline); pass.setVertexBuffer(0, s.vbuf); pass.setIndexBuffer(s.ibuf, 'uint16');"
+ "s.pass = pass; return pass;")
private static native Pass beginPass(GPUDevice device, Scene scene);
/** Ends the pass {@link #beginPass} began and submits its commands. */
@JSBody(
params = {"device", "s"},
script = "s.pass.end(); device.queue.submit([s.encoder.finish()]);")
private static native void endPass(GPUDevice device, Scene scene);
@JSBody(
params = {"pass", "s", "draws"},
script = "var g = s.bindGroup, o = s.offsets;"
+ "for (var i = 0; i < draws; i++) { pass.setBindGroup(0, g, o, i, 1); pass.drawIndexed(3, 1, 0, 0, 0); }")
private static native void drawAllInJs(Pass pass, Scene scene, int draws);
@JSBody(
params = {"pass", "s", "view", "length"},
script = "var g = s.bindGroup, o = s.offsets, i = 0;"
+ "while (i < length) {"
+ " var op = view[i];"
+ " if (op === 1) { pass.setBindGroup(0, g, o, view[i + 1], 1); i += 2; }"
+ " else { pass.drawIndexed(view[i + 1], 1, view[i + 2], view[i + 3], 0); i += 4; } }")
private static native void replay(Pass pass, Scene scene, Int32Array view, int length);
@JSBody(params = {"pass", "s"}, script = "pass.executeBundles([s.bundle]);")
private static native void executeBundle(Pass pass, Scene scene);
@JSBody(
params = "s",
script = "var gl = s.gl; gl.useProgram(s.glProgram); gl.viewport(0, 0, 256, 256);"
+ "gl.clear(gl.COLOR_BUFFER_BIT);")
private static native void prepareGl(Scene scene);
@JSBody(params = "s", script = "s.gl.finish();")
private static native void glFinish(Scene scene);
@JSBody(
params = "s",
script = "var e = s.error || null; if (!e && s.gl.getError() !== 0) e = 'WebGL2 error ' + s.gl.getError();"
+ " return e;")
private static native String takeError(Scene scene);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,51 @@
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
/**
* {@code int}s handed to JavaScript arrive as the same Numbers (tools/webbuild's {@code
* JsoIntrinsics}: an i31 where the value fits, else TeaVM's import): each side of the i31 range's
* edges, the int range's ends, and values from a loop, so they aren't constants; through a
* {@code @JSBody} argument and through a JSO interface method's. Prints "probe passed".
*/
public final class WrapIntProbe {
private WrapIntProbe() {}
/** A JavaScript object whose method reports what it got, as a JSO interface call reaches it. */
interface Checker extends JSObject {
String check(int value, String expected);
}
public static void main(String[] args) {
int[] values = {0, 1, -1, 7, 36160, (1 << 30) - 1, 1 << 30, -(1 << 30), -(1 << 30) - 1,
Integer.MAX_VALUE, Integer.MIN_VALUE, 0x7fff_fffe, 123_456_789, -987_654_321};
Checker checker = checker();
String failure = null;
for (int round = 0; round < 3 && failure == null; round++) {
for (int value : values) {
// Not a constant the compiler could fold: a value read from the array, shifted and back.
int v = (value ^ round) ^ round;
String expected = Integer.toString(v);
String body = describe(v, expected);
String method = checker.check(v, expected);
if (body != null || method != null) {
failure = body != null ? body : method;
break;
}
}
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
@JSBody(
params = {"value", "expected"},
script = "return typeof value === 'number' && String(value) === expected ? null"
+ " : '@JSBody got ' + typeof value + ' ' + value + ', expected ' + expected;")
private static native String describe(int value, String expected);
@JSBody(
script = "return { check: function(value, expected) {"
+ " return typeof value === 'number' && String(value) === expected ? null"
+ " : 'a method got ' + typeof value + ' ' + value + ', expected ' + expected; } };")
private static native Checker checker();
}
@@ -0,0 +1,62 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Regression probe for tools/teavm-patches' TZipFile fix: TeaVM's ZipFile gave its raw
* inflater exactly an entry's compressed bytes, and InflaterInputStream threw EOFException when
* the inflater still asked for input at their end, as it can for a whole entry (638 textures of a
* community resource pack). The JDK's ZipFile adds a dummy byte; the patch does too. Writes entries
* of many sizes and kinds, reads each back to its end, and prints "probe passed" when all match.
*/
public final class ZipFileProbe {
private ZipFileProbe() {}
public static void main(String[] args) throws IOException {
Random random = new Random(5);
byte[][] contents = new byte[400][];
File file = new File("/probe.zip");
try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file))) {
for (int i = 0; i < contents.length; i++) {
byte[] data = new byte[random.nextInt(4000)];
// Some random (incompressible), some patterned, some mixed: PNG-like variety.
for (int j = 0; j < data.length; j++) {
data[j] = (byte) (i % 3 == 0 ? random.nextInt() : i % 3 == 1 ? j / 7 : (j % 13) * random.nextInt(3));
}
contents[i] = data;
zip.putNextEntry(new ZipEntry("entry" + i));
zip.write(data);
zip.closeEntry();
}
}
int failures = 0;
String first = "";
try (ZipFile zip = new ZipFile(file)) {
for (int i = 0; i < contents.length; i++) {
try (InputStream in = zip.getInputStream(zip.getEntry("entry" + i))) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
}
if (!Arrays.equals(out.toByteArray(), contents[i])) {
failures++;
first = first.isEmpty() ? "entry" + i + " differs" : first;
}
} catch (IOException e) {
failures++;
first = first.isEmpty() ? "entry" + i + ": " + e : first;
}
}
}
System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " entries, first " + first);
}
}
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Compiles one probe (app-web/probes/<Name>.java) with TeaVM against the browser build's class
# library and runs it in headless Chromium until it prints "probe passed" (see README.md,
# Experiments). Takes seconds, not the full build's ten minutes.
#
# app-web/probes/run.sh SuspendingTernaryProbe
# app-web/probes/run.sh WebGpuCallProbe -Pbrowser.gpu=webgpu -Pteavm.fast (more Gradle options)
set -euo pipefail
name="${1:?usage: app-web/probes/run.sh <ProbeName>}"
root="$(cd "$(dirname "$0")/../.." && pwd)"
classes="$root/app-web/build/probes/$name"
rm -rf "$classes"
# Probes may use the Netty the browser build keeps (the teavm task puts it on TeaVM's class path);
# javac finds the pinned version in Gradle's cache, which any build of the repo has filled.
netty="$(sed -n 's/^netty = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")"
netty_jars=""
for module in netty-common netty-buffer netty-transport netty-codec-base; do
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$netty.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may call TeaVM's interop and JSO APIs, as the page's own code does.
teavm="$(sed -n 's/^teavm = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")"
for module in teavm-interop teavm-jso teavm-jso-apis; do
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$teavm.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may use the Via the browser build compiles in.
for library in viaversion viabackwards; do
version="$(sed -n "s/^$library = \"\(.*\)\"/\1/p" "$root/gradle/libs.versions.toml")"
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$library-common-$version.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may also use Incari's platform classes (StorageProbe installs the file system).
cd "$root"
./gradlew -q :platform-web:classes
# Probes compile for Java 25, as the game does; a newer javac must be told.
javac --release 25 -cp "${netty_jars#:}:$root/platform-web/build/classes/java/main" -d "$classes" \
"$root/app-web/probes/$name.java"
./gradlew :app-web:browserCheck -Pteavm.main="$name" -Pteavm.classpath="$classes" \
"-Pbrowser.expect=probe (passed|failed.*)" -Pbrowser.count=1 -Pbrowser.seconds=60 "${@:2}" \
| tee "$root/app-web/build/probes/$name.log"
grep -q "probe passed" "$root/app-web/build/probes/$name.log"