Initial RPS CUDA implementation

This commit is contained in:
Skeleton bootstrap 2026-11-26 09:07:21 +03:00
commit 8d583036d0
33 changed files with 2968 additions and 0 deletions

103
tests/contracts.cpp Normal file
View file

@ -0,0 +1,103 @@
#include "wire.hpp"
static void transitions() {
constexpr int orders[6][3] = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3},
{2, 3, 1}, {3, 1, 2}, {3, 2, 1}};
for (auto &order : orders)
for (int state = 0; state < 4; ++state)
for (int mask = 0; mask < 8; ++mask) {
const auto seen = [mask](int species) {
return bool(mask & (1 << (species - 1)));
};
int expected = state;
if (state == 0) {
for (auto species : order)
if (seen(species)) {
expected = species;
break;
}
} else if (seen(state % 3 + 1))
expected = state % 3 + 1;
bool a = state & 1, b = state & 2, empty = !a && !b;
bool wins =
(a && !b && seen(2)) || (!a && b && seen(3)) || (a && b && seen(1));
bool candidates[4]{}, higher = false;
for (auto species : order) {
candidates[species] = seen(species) && !higher;
higher |= seen(species);
}
bool low = (a ^ (wins && (a ^ b))) ||
(empty && (candidates[1] || candidates[3]));
bool high =
(b ^ (wins && a)) || (empty && (candidates[2] || candidates[3]));
require((int(low) + 2 * high) == expected && (!state || expected),
"transition equation or occupancy invariant");
}
}
int main(int argc, char **argv) {
transitions();
auto raw = readConfig(argv[1]);
auto c = parse(raw);
require(c.seed == 42 && c.bytes() == 786432, "example");
for (auto [seed, p] : std::vector<std::pair<u64, int>>{
{0, 5}, {1, 0}, {42, 4}, {12345, 0}, {UINT64_MAX, 3}})
require(priority(seed) == p, "EVP vector");
for (auto [seed, hash] :
std::vector<std::pair<u64, u64>>{{0, 0x6674f8e1bf06b711ULL},
{1, 0x6dfadca188a614c0ULL},
{2, 0xc7e589e42b2fc13dULL},
{4, 0x6db8b412fa32d5d4ULL},
{5, 0x32deeebde34fa78fULL},
{8, 0x2873390fd319c916ULL},
{42, 0x7c62b6526f730efaULL},
{12345, 0xafab81b606544998ULL},
{UINT64_MAX, 0x88e38984a5df2ff7ULL}})
require(hash64(seed) == hash, "exact EVP digest prefix");
auto reject = [](std::string s) {
try {
parse(s);
} catch (const std::exception &) {
return;
}
throw std::runtime_error("invalid config accepted");
};
reject("{\"protocol_version\":1," + raw.substr(raw.find('{') + 1));
for (auto seed : {"01", "-1", "18446744073709551616", "42 "}) {
auto j = Json::parse(raw);
j["simulation"]["seed"] = seed;
reject(j.dump());
}
auto j = Json::parse(raw);
j["view"]["roi"]["x"] = UINT32_MAX;
reject(j.dump());
j = Json::parse(raw);
j["simulation"]["width"] = 1024.0;
reject(j.dump());
j = Json::parse(raw);
j["simulation"]["seed"] = 42;
reject(j.dump());
j = Json::parse(raw);
j["snapshots"]["fps"] = 3;
reject(j.dump());
reject(raw + std::string(1, char(0)) + "suffix");
for (auto [path, value] : std::vector<std::pair<const char *, Json>>{
{"/simulation/width", 0},
{"/simulation/width", 1025},
{"/simulation/height", 49},
{"/simulation/neighbors", 6},
{"/simulation/generations", 0},
{"/simulation/max_generations_per_second", 241},
{"/protocol_version", 2},
{"/view/aggregation_side", 3},
{"/view/roi/x", 1},
{"/view/roi/width", 0},
{"/view/roi/height", -1},
{"/view/palette", nullptr},
{"/view/aggregation_side", 1}}) {
auto bad = Json::parse(raw);
bad[Json::json_pointer(path)] = value;
reject(bad.dump());
}
Bytes b;
put(b, UINT64_C(0x0123456789abcdef), 8);
require(b == Bytes{1, 35, 69, 103, 137, 171, 205, 239}, "wire order");
}

182
tests/cuda_check.cpp Normal file
View file

@ -0,0 +1,182 @@
#include "gpu.hpp"
#include "wire.hpp"
#include <array>
#include <iostream>
using Cells = std::vector<unsigned char>;
static u32 mix(u32 x) {
x ^= x >> 16;
x *= 0x7feb352d;
x ^= x >> 15;
x *= 0x846ca68b;
return x ^ (x >> 16);
}
static Cells initial(const Config &c) {
Cells cells(size_t(c.w) * c.h);
u32 l = c.seed, h = c.seed >> 32;
for (u32 i = 0; i < cells.size() / 32; ++i) {
u32 a = mix(l ^ i ^ (h * 0x9e3779b9u) ^ 0xa341316cu),
b = mix(h ^ i ^ (l * 0x85ebca6bu) ^ 0xc8013ea4u);
for (int j = 0; j < 32; ++j)
cells[size_t(i) * 32 + j] = ((a >> j) & 1) + 2 * ((b >> j) & 1);
}
return cells;
}
// One byte per cell, direct species comparisons. Split off the two wraparound
// lanes so the compiler can vectorize the interior without modulus operations.
template <int N> static Cells step(const Cells &src, const Config &c, int p) {
static constexpr unsigned order[][3] = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3},
{2, 3, 1}, {3, 1, 2}, {3, 2, 1}};
Cells dst(src.size());
for (u32 y = 0; y < c.h; ++y) {
auto row = src.data() + size_t(y) * c.w;
auto up = src.data() + size_t(y == 0 ? c.h - 1 : y - 1) * c.w;
auto down = src.data() + size_t(y + 1 == c.h ? 0 : y + 1) * c.w;
auto out = dst.data() + size_t(y) * c.w;
auto update = [&](u32 x, u32 left, u32 right) {
auto present = [&](unsigned species) {
bool found = (row[left] == species) | (row[right] == species) |
(up[x] == species) | (down[x] == species);
if constexpr (N == 8)
found |= (up[left] == species) | (up[right] == species) |
(down[left] == species) | (down[right] == species);
return found;
};
bool rock = present(1), paper = present(2), scissors = present(3);
auto claim = [&](unsigned s) {
return s == 1 ? rock : s == 2 ? paper : scissors;
};
unsigned empty = claim(order[p][0]) ? order[p][0]
: claim(order[p][1]) ? order[p][1]
: claim(order[p][2]) ? order[p][2]
: 0;
out[x] = row[x] == 0 ? empty
: row[x] == 1 ? 1 + paper
: row[x] == 2 ? 2 + scissors
: rock ? 1
: 3;
};
update(0, c.w - 1, 1);
for (u32 x = 1; x < c.w - 1; ++x)
update(x, x - 1, x + 1);
update(c.w - 1, c.w - 2, 0);
}
return dst;
}
static Cells reference(const Cells &cells, const Config &c, int p) {
return c.n == 4 ? step<4>(cells, c, p) : step<8>(cells, c, p);
}
static void checkImage(const unsigned char *pixels, const Cells &cells,
const Config &c) {
static const int bgra[][3] = {
{0, 0, 0}, {70, 70, 230}, {230, 150, 70}, {120, 210, 80}};
for (u32 y = 0; y < c.ah(); ++y)
for (u32 x = 0; x < c.aw(); ++x) {
int sum[3]{};
for (u32 j = 0; j < c.k; ++j)
for (u32 i = 0; i < c.k; ++i) {
auto s = cells[size_t(c.y + y * c.k + j) * c.w + c.x + x * c.k + i];
for (int b = 0; b < 3; ++b)
sum[b] += bgra[s][b];
}
auto p = pixels + 4 * (size_t(y) * c.aw() + x);
auto area = c.k * c.k;
for (int b = 0; b < 3; ++b)
require(p[b] == (sum[b] + area / 2) / area, "pixel channel mismatch");
require(p[3] == 255, "alpha mismatch");
}
}
int main(int argc, char **argv) try {
u32 width = argc > 1 ? std::stoul(argv[1]) : 1024,
height = argc > 2 ? std::stoul(argv[2]) : 48;
for (u32 n : {4, 8})
for (u64 seed : {0, 1, 2, 4, 5, 8}) {
Config c{width, height, n, 128, 240, 16, 16, 32, 32, 1, seed};
for (u32 k : {1, 2, 4, 8, 16}) {
c.k = k;
GPU gpu(c, priority(seed));
auto cells = initial(c);
require(gpu.snapshot(true), "initial snapshot");
checkImage(gpu.pixels(), cells, c);
gpu.ack();
require(!gpu.snapshot(false), "unchanged snapshot");
if (k != 1)
continue;
for (int t = 0; t <= 128; ++t) {
if (t <= 3 || t == 10 || t == 128)
require(gpu.unpack() == cells, "CPU/GPU cell mismatch");
if (t == 128)
break;
cells = reference(cells, c, priority(seed));
gpu.step();
}
require(gpu.snapshot(true), "final snapshot");
checkImage(gpu.pixels(), cells, c);
}
}
// Place 32 disjoint neighbourhoods in one row for every kernel variant.
for (u32 n : {4, 8})
for (int p = 0; p < 6; ++p) {
Config c{1024, 48, n, 1, 240, 0, 0, 32, 32, 1, 42};
GPU gpu(c, p);
Cells grid(c.w * c.h);
for (int state = 0; state < 4; ++state)
for (int mask = 0; mask < 8; ++mask) {
size_t center = c.w * 2 + (state * 8 + mask) * 4 + 1;
grid[center] = state;
grid[center - 1] = (mask & 1) ? 1 : 0;
grid[center + 1] = (mask & 2) ? 2 : 0;
grid[center + c.w] = (mask & 4) ? 3 : 0;
}
gpu.loadTestCells(grid);
gpu.step();
require(gpu.unpack() == reference(grid, c, p),
"192 exhaustive transitions");
}
// Uniform states, single objects, corners, diagonal-only contacts and seams.
for (u32 n : {4, 8}) {
Config c{2048, 48, n, 1, 240, 2016, 16, 32, 32, 2, 42};
GPU gpu(c, priority(c.seed));
for (int pattern = 0; pattern < 7; ++pattern) {
Cells cells(c.w * c.h, pattern < 4 ? pattern : 0);
if (pattern == 4)
cells[0] = 1;
if (pattern == 5) {
for (u32 x : {0, 31, 32, 1023, 1024, 2047}) {
cells[x] = 1;
cells[c.w + ((x + 1) % c.w)] = 2;
cells[(c.h - 1) * c.w + x] = 3;
}
}
if (pattern == 6)
for (size_t i = 0; i < cells.size(); ++i)
cells[i] = 1 + ((i % 31 + i / c.w) % 3);
gpu.loadTestCells(cells);
gpu.snapshot(true);
checkImage(gpu.pixels(), cells, c);
gpu.ack();
auto expected = reference(cells, c, priority(c.seed));
gpu.step();
require(gpu.unpack() == expected, "manual torus fixture");
if (pattern < 4)
require(!gpu.snapshot(false), "fixed point changed");
}
Cells cells(c.w * c.h);
auto i = size_t(c.y) * c.w + c.x;
cells[i] = 1;
cells[i + 1] = 2;
gpu.loadTestCells(cells);
gpu.snapshot(true);
gpu.ack();
std::swap(cells[i], cells[i + 1]);
gpu.loadTestCells(cells);
require(!gpu.snapshot(false), "aggregation permutation");
cells[i] = 0;
gpu.loadTestCells(cells);
require(gpu.snapshot(false), "single changed pixel");
gpu.ack();
}
std::cout << "CPU/CUDA fields and BGRA snapshots match\n";
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}

82
tests/headless.py Normal file
View file

@ -0,0 +1,82 @@
"""Run against the real server through the local OpenSSH dynamic forward."""
from contextlib import contextmanager
import argparse
import json
import socket
import ssl
import struct
import time
from pathlib import Path
def exact(stream, n):
result = bytearray()
while len(result) < n:
chunk = stream.recv(n - len(result))
if not chunk:
raise EOFError("truncated message")
result.extend(chunk)
return result
def send(stream, kind, data):
stream.sendall(struct.pack(">4sHHQ", b"RPS1", 1, kind, len(data)) + data)
def receive(stream):
magic, version, kind, n = struct.unpack(">4sHHQ", exact(stream, 16))
assert (magic, version) == (b"RPS1", 1) and n <= 33554464
data = exact(stream, n)
if kind == 6:
raise ValueError(data[4:].decode())
return kind, data
@contextmanager
def connection(ca, port=11080, hostname="infra-gpu"):
ctx = ssl.create_default_context(cafile=ca)
ctx.minimum_version = ctx.maximum_version = ssl.TLSVersion.TLSv1_3
with socket.create_connection(("127.0.0.1", port), timeout=120) as sock:
sock.sendall(bytes.fromhex("05 01 00"))
assert exact(sock, 2) == bytes.fromhex("05 00")
sock.sendall(bytes.fromhex("05 01 00 01 7f 00 00 01") + struct.pack(">H", 7443))
assert exact(sock, 4) == bytes.fromhex("05 00 00 01")
exact(sock, 6)
with ctx.wrap_socket(sock, server_hostname=hostname) as tls:
yield tls
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--ca", required=True)
parser.add_argument("--config", required=True)
parser.add_argument("--delay", type=float, default=0)
parser.add_argument("--socks-port", type=int, default=11080)
args = parser.parse_args()
raw = Path(args.config).read_bytes()
config = json.loads(raw)
g = config["simulation"]["generations"]
view = config["view"]
k = view["aggregation_side"]
aw, ah = (view["roi"][key] // k for key in ("width", "height"))
with connection(args.ca,args.socks_port) as tls:
send(tls, 1, raw)
assert receive(tls) == (2, raw)
last = -1
count = 0
while last < g:
kind, data = receive(tls)
frame, gen, w, h, side, fmt = struct.unpack_from(">QQIIII", data)
assert kind == 3 and frame == count + 1 and last < gen <= g
assert count or gen == 0
assert (w, h, side, fmt) == (aw, ah, k, 1) and len(data) == 32 + w*h*4
assert all(alpha == 255 for alpha in data[35::4])
time.sleep(args.delay)
send(tls, 4, struct.pack(">Q", frame))
count, last = frame, gen
assert receive(tls) == (5, struct.pack(">QI", g, 0))
print(f"PASS generation={last} frames={count}")
if __name__ == "__main__":
main()

59
tests/metal_render.mm Normal file
View file

@ -0,0 +1,59 @@
#include "renderer.hpp"
#include <array>
#include <cstdio>
int main() {
@autoreleasepool {
auto device = MTLCreateSystemDefaultDevice();
auto queue = [device newCommandQueue];
auto pipeline = buildPipeline(device);
if (!queue || !pipeline)
return 1;
auto texture = [&](int w, int h, MTLTextureUsage usage) {
auto desc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:w
height:h
mipmapped:NO];
desc.usage = usage;
desc.storageMode = MTLStorageModeShared;
return [device newTextureWithDescriptor:desc];
};
// BGRA in little-endian memory. Distinct corners detect axis inversions.
const std::array<uint32_t, 4> corners{0xffff0000u, 0xff00ff00u, 0xff0000ffu,
0xffffffffu};
auto input = texture(2, 2, MTLTextureUsageShaderRead);
[input replaceRegion:MTLRegionMake2D(0, 0, 2, 2)
mipmapLevel:0
withBytes:corners.data()
bytesPerRow:8];
auto target = texture(8, 4, MTLTextureUsageRenderTarget);
auto pass = [MTLRenderPassDescriptor renderPassDescriptor];
auto dst = pass.colorAttachments[0];
dst.texture = target;
dst.loadAction = MTLLoadActionClear;
dst.storeAction = MTLStoreActionStore;
dst.clearColor = MTLClearColorMake(0, 0, 0, 1);
auto cmd = [queue commandBuffer];
if (!encodeImage(cmd, pass, input, pipeline))
return 1;
[cmd commit];
[cmd waitUntilCompleted];
if (cmd.status != MTLCommandBufferStatusCompleted)
return 1;
std::array<uint32_t, 32> actual{};
[target getBytes:actual.data()
bytesPerRow:32
fromRegion:MTLRegionMake2D(0, 0, 8, 4)
mipmapLevel:0];
for (int y = 0; y < 4; ++y)
for (int x = 0; x < 8; ++x) {
uint32_t expected =
x < 2 || x >= 6 ? 0xff000000u : corners[y / 2 * 2 + (x - 2) / 2];
if (actual[y * 8 + x] != expected) {
fprintf(stderr, "pixel mismatch at %d,%d\n", x, y);
return 1;
}
}
puts("PASS Metal BGRA pixels, nearest filtering, aspect and orientation");
}
}

92
tests/protocol.py Normal file
View file

@ -0,0 +1,92 @@
"""Protocol errors, slow consumer, TLS identity and recovery on the live server."""
from pathlib import Path
import json
import ssl
import struct
import sys
import time
from headless import connection, exact, send, receive
ca = sys.argv[1]
config = json.loads(Path(sys.argv[2]).read_bytes())
config["simulation"].update(width=1024, height=48, generations=15, max_generations_per_second=240)
config["view"]["roi"].update(width=1024, height=48)
raw = json.dumps(config).encode()
def header(kind, n):
return struct.pack(">4sHHQ", b"RPS1", 1, kind, n)
def error(tls):
try:
receive(tls)
except ValueError as e:
assert str(e)
return
raise AssertionError("expected server ERROR")
def begin(tls):
msg = header(1, len(raw)) + raw
for i in range(0, len(msg), 3):
tls.sendall(msg[i:i+3])
assert receive(tls) == (2, raw)
typ, payload = receive(tls)
assert typ == 3 and struct.unpack_from(">QQ", payload) == (1, 0)
for invalid in (header(1, 65537), header(4, 8), header(0, 0), b"FAIL"+header(1, 1)[4:],
header(1, 1)[:4]+b"\0\2"+header(1, 1)[6:]):
with connection(ca) as tls:
tls.sendall(invalid)
error(tls)
with connection(ca) as tls:
send(tls, 1, raw[:-1])
error(tls)
with connection(ca) as tls:
tls.sendall(header(1, len(raw))+raw + header(4, 8)+struct.pack(">Q", 1))
assert receive(tls) == (2, raw)
error(tls)
# The RTX 3080 cannot fit both states for this valid grid. The server
# rejects the session before launching a simulation or writing CONFIG_ACCEPTED.
large = json.loads(raw)
large["simulation"]["width"] = 2**31
with connection(ca) as tls:
send(tls, 1, json.dumps(large).encode())
error(tls)
# Drop the transport inside the first frame, then reconnect to the same listener.
with connection(ca) as tls:
send(tls, 1, raw)
assert receive(tls) == (2, raw)
assert exact(tls, 16)[:8] == header(3, 0)[:8]
exact(tls, 33)
for reply in ((4, struct.pack(">Q", 2)), (1, raw)):
with connection(ca) as tls:
begin(tls)
send(tls, *reply)
error(tls)
with connection(ca) as tls:
begin(tls)
tls.sendall((header(4, 8)+struct.pack(">Q", 1))*2)
error(tls)
with connection(ca) as tls:
tls.sendall(header(1, len(raw))+raw[:4])
try:
with connection(ca, hostname="wrong-name.invalid"):
raise AssertionError("host verification missing")
except ssl.SSLCertVerificationError:
pass
with connection(ca) as tls:
begin(tls)
time.sleep(0.4)
send(tls, 4, struct.pack(">Q", 1))
typ, final = receive(tls)
assert typ == 3 and struct.unpack_from(">QQ", final) == (2, 15)
send(tls, 4, struct.pack(">Q", 2))
assert receive(tls) == (5, struct.pack(">QI", 15, 0))
print("PASS protocol errors and recovery; slow consumer saw generations 0 and 15")

View file

@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Independent scalar verification of RPS CUDA MVP mathematical contracts.
No NVIDIA/CUDA, OpenSSL C++ or macOS dependencies; Python 3.10+.
This validates *math* only; it does not claim to validate the actual CUDA binary.
"""
from __future__ import annotations
import hashlib
from itertools import product
from random import Random
MASK32 = (1 << 32) - 1
ORDERS = ('RPS', 'RSP', 'PRS', 'PSR', 'SRP', 'SPR')
LUTS = ((0xF2, 0x0E), (0xFA, 0x0E), (0x32, 0xCE),
(0x32, 0xEE), (0xFA, 0xAE), (0xBA, 0xEE))
COLORS = ((0,0,0), (230,70,70), (70,150,230), (80,210,120))
def lop3_bit(a: int, b: int, c: int, lut: int) -> int:
return (lut >> ((a << 2) | (b << 1) | c)) & 1
def scalar_step(code: int, nr: int, np: int, ns: int, priority: int) -> int:
if code == 1:
return 2 if np else 1
if code == 2:
return 3 if ns else 2
if code == 3:
return 1 if nr else 3
present = {'R': nr, 'P': np, 'S': ns}
for kind in ORDERS[priority]:
if present[kind]:
return {'R': 1, 'P': 2, 'S': 3}[kind]
return 0
def bit_logic_step(code: int, nr: int, np: int, ns: int, priority: int) -> int:
a = code & 1
b = (code >> 1) & 1
x = lop3_bit(b, nr, np, 0xCA)
w = lop3_bit(a, x, ns, 0xCA)
ao = lop3_bit(a, b, w, 0xD8)
bo = lop3_bit(a, b, w, 0x6C)
lut_a, lut_b = LUTS[priority]
fa = lop3_bit(nr, np, ns, lut_a)
fb = lop3_bit(nr, np, ns, lut_b)
e = lop3_bit(a, b, w, 0x03)
an = lop3_bit(ao, e, fa, 0xF8)
bn = lop3_bit(bo, e, fb, 0xF8)
return an | (bn << 1)
def test_luts() -> None:
n = 0
for code, nr, np, ns, priority in product(range(4), range(2), range(2), range(2), range(6)):
assert bit_logic_step(code, nr, np, ns, priority) == scalar_step(code, nr, np, ns, priority)
n += 1
assert n == 192
print('PASS: all 192 transition/LUT combinations')
def test_shf() -> None:
r = Random(20261118)
for _ in range(10000):
prev, center, nxt = (r.getrandbits(32) for _ in range(3))
left = ((center << 1) | (prev >> 31)) & MASK32
right = ((center >> 1) | (nxt << 31)) & MASK32
# Scalar expected: left neighbor for local bit k is center[k-1],
# except k=0, which is previous[31]. Right is symmetric.
for k in range(32):
exp_l = ((prev >> 31) & 1) if k == 0 else ((center >> (k-1)) & 1)
exp_r = (nxt & 1) if k == 31 else ((center >> (k+1)) & 1)
assert ((left >> k) & 1) == exp_l
assert ((right >> k) & 1) == exp_r
print('PASS: 10,000 pairs of SHF neighborhood boundaries (32 bits each)')
def test_priority() -> None:
vectors = {
0: ('6674f8e1bf06b711', 5),
1: ('6dfadca188a614c0', 0),
2: ('c7e589e42b2fc13d', 3),
4: ('6db8b412fa32d5d4', 4),
5: ('32deeebde34fa78f', 1),
8: ('2873390fd319c916', 2),
42: ('7c62b6526f730efa', 4),
12345: ('afab81b606544998', 0),
(1 << 64)-1: ('88e38984a5df2ff7', 3),
}
prefix = b'RPS-PRIORITY-v1\x00'
assert len(prefix) == 16
for seed, (hex64, rem) in vectors.items():
msg = prefix + seed.to_bytes(8, 'big')
assert len(msg) == 24
actual = hashlib.sha256(msg).digest()
assert actual[:8].hex() == hex64
assert int.from_bytes(actual[:8], 'big') % 6 == rem
print(f'PASS: {len(vectors)} SHA-256 / priority vectors')
def mix32(x: int) -> int:
x &= MASK32
x ^= x >> 16
x = (x * 0x7FEB352D) & MASK32
x ^= x >> 15
x = (x * 0x846CA68B) & MASK32
x ^= x >> 16
return x
def init_word(seed: int, i: int) -> tuple[int,int]:
sl, sh = seed & MASK32, (seed >> 32) & MASK32
lo = mix32(sl ^ i ^ ((sh * 0x9E3779B9) & MASK32) ^ 0xA341316C)
hi = mix32(sh ^ i ^ ((sl * 0x85EBCA6B) & MASK32) ^ 0xC8013EA4)
return lo, hi
def test_init() -> None:
assert init_word(42, 0) == init_word(42, 0)
assert init_word(42, 0) != init_word(42, 1)
assert init_word(0, 0) != init_word(42, 0)
print('PASS: deterministic init-v1 smoke checks')
for seed in (0, 42, (1 << 64)-1):
print(f' GOLDEN init-v1 seed={seed} word[0] low/high = '
f'{init_word(seed, 0)[0]:08x}/{init_word(seed, 0)[1]:08x}')
def test_aggregation() -> None:
for k in (1,2,4,8,16):
for counts in ((k*k,0,0,0),(0,k*k,0,0),(0,0,k*k,0),(0,0,0,k*k)):
a = k*k
rgb = tuple((sum(counts[s] * COLORS[s][channel] for s in range(4)) + a//2)//a
for channel in range(3))
nonzero = next(i for i,c in enumerate(counts) if c)
assert rgb == COLORS[nonzero]
# 2x2: one pixel each kind. R/G/B sums: (380,430,420); round +2 before /4.
counts = (1,1,1,1)
r,g,b = tuple((sum(counts[s]*COLORS[s][channel] for s in range(4))+2)//4 for channel in range(3))
assert (r,g,b) == (95,108,105)
assert (b,g,r,255) == (105,108,95,255)
print('PASS: integer aggregation and BGRA color order')
if __name__ == '__main__':
test_luts()
test_shf()
test_priority()
test_init()
test_aggregation()
print('PASS: standalone mathematical verifier (not CUDA execution)')

44
tests/view_fixture.py Normal file
View file

@ -0,0 +1,44 @@
"""Two known corner colours for an on-screen orientation and ACK smoke test."""
import argparse
import json
import socket
import ssl
import struct
from headless import receive, send
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cert", required=True)
parser.add_argument("--key", required=True)
parser.add_argument("--port", type=int, default=7444)
args = parser.parse_args()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.minimum_version = ctx.maximum_version = ssl.TLSVersion.TLSv1_3
ctx.load_cert_chain(args.cert, args.key)
with socket.create_server(("127.0.0.1", args.port)) as listener:
listener.settimeout(120)
peer, _ = listener.accept()
with peer, ctx.wrap_socket(peer, server_side=True) as tls:
kind, raw = receive(tls)
assert kind == 1
send(tls, 2, raw)
cfg = json.loads(raw)
view = cfg["view"]
g = cfg["simulation"]["generations"]
k = view["aggregation_side"]
w, h = (view["roi"][key] // k for key in ("width", "height"))
for frame, gen in ((1, 0), (2, g)):
prefix = struct.pack(">QQIIII", frame, gen, w, h, k, 1)
left, right = bytes((0, 0, 255, 255)), bytes((255, 0, 0, 255))
row = left*(w//2) + right*(w-w//2)
pixels = row*(h//2) + bytes((0, 255, 0, 255))*w*(h-h//2)
send(tls, 3, prefix + pixels)
assert receive(tls) == (4, struct.pack(">Q", frame))
send(tls, 5, struct.pack(">QI", g, 0))
print("PASS two presented frames acknowledged", flush=True)
if __name__ == "__main__":
main()

58
tests/wire_pixels.py Normal file
View file

@ -0,0 +1,58 @@
"""Compare the real TLS frame payload against independent plain-cell evolution."""
from pathlib import Path
import json
import struct
import sys
from headless import connection, send, receive
from verify_rps_mvp_math import COLORS, init_word, scalar_step
cfg = json.loads(Path(sys.argv[2]).read_bytes())
width, height = 1024, 48
cfg["simulation"].update(width=width, height=height, seed="42", generations=4,
max_generations_per_second=60)
cells = bytearray()
for i in range(width * height // 32):
a, b = init_word(42, i)
cells.extend(((a >> j) & 1) | (((b >> j) & 1) << 1) for j in range(32))
initial = cells
for neighbors in (4, 8):
cells = initial
cfg["simulation"]["neighbors"] = neighbors
k = neighbors // 2
cfg["view"]["aggregation_side"] = k
roi = {"x": 992, "y": 16, "width": 32, "height": 32}
cfg["view"]["roi"] = roi
raw = json.dumps(cfg).encode()
gen = 0
with connection(sys.argv[1], int(sys.argv[3]) if len(sys.argv) > 3 else 11080) as tls:
send(tls, 1, raw)
assert receive(tls) == (2, raw)
while True:
kind, data = receive(tls)
assert kind == 3
frame, target, w, h, side, fmt = struct.unpack_from(">QQIIII", data)
assert (w, h, side, fmt) == (32//k, 32//k, k, 1)
while gen < target:
new = bytearray(len(cells))
for y in range(height):
for x in range(width):
present = {cells[((y+dy)%height)*width + (x+dx)%width]
for dy in (-1, 0, 1) for dx in (-1, 0, 1)
if (dx or dy) and (neighbors == 8 or not(dx and dy))}
i = y*width + x
new[i] = scalar_step(cells[i], 1 in present, 2 in present, 3 in present, 4)
cells = new
gen += 1
expected = bytearray()
for y in range(roi["y"], height, k):
for x in range(roi["x"], width, k):
colors = [COLORS[cells[(y+j)*width+x+i]] for j in range(k) for i in range(k)]
rgb = [(sum(channel)+k*k//2)//(k*k) for channel in zip(*colors)]
expected.extend([*reversed(rgb), 255])
assert expected == data[32:]
send(tls, 4, struct.pack(">Q", frame))
if gen == 4:
assert receive(tls) == (5, struct.pack(">QI", gen, 0))
break
print(f"PASS all transmitted BGRA pixels, neighbors={neighbors}")