Files
patriothacks/e2e/assemblyPartition.e2e.mjs

302 lines
13 KiB
JavaScript

// ma-assembly WebRTC partition-and-heal acceptance test (plan todo 23).
//
// Self-contained Playwright runner. It starts a local y-webrtc signaling
// server and a Vite dev server, opens TWO isolated browser contexts (the two
// "devices"), and for each QA scenario:
// 1. connects both sides over real WebRTC and proves the live transport
// works (a warmup vote genuinely propagates side->side),
// 2. PARTITIONS the two sides for real - setOffline(true) on both contexts,
// blocks the signaling WebSocket route, AND tears the established
// RTCDataChannels (provider.disconnect) so peerCount drops to 0,
// 3. casts an independent vote on each side and ASSERTS non-propagation for
// a window (this is the genuine-partition proof: if the sides were
// secretly still syncing, the counts would move and the test fails),
// 4. HEALS - setOffline(false), unblocks signaling, reconnects - and asserts
// both sides converge to the identical final tally.
//
// Why not setOffline alone: over loopback, Chromium host candidates
// (127.0.0.1) bypass network emulation, so setOffline(true) does NOT cut an
// already-established data channel (empirically verified). Genuinely severing
// the transport + asserting non-propagation is what makes the partition real
// rather than cosmetic.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { spawn } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const SIG_PORT = 40000 + Math.floor(Math.random() * 20000);
const VITE_PORT = 41000 + Math.floor(Math.random() * 20000);
const SIG = `ws://127.0.0.1:${SIG_PORT}`;
const PAGE = `http://127.0.0.1:${VITE_PORT}/demo/assembly-sync.html`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, label, timeoutMs = 20000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (await fn()) return;
await sleep(200);
}
throw new Error(`timeout waiting for: ${label}`);
}
function startSignaling() {
return new Promise((resolvePromise, reject) => {
const child = spawn("node", ["node_modules/y-webrtc/bin/server.js"], {
cwd: ROOT,
env: { ...process.env, PORT: String(SIG_PORT) },
stdio: ["ignore", "pipe", "pipe"],
});
const to = setTimeout(() => reject(new Error("signaling start timeout")), 10000);
child.stdout.on("data", (b) => {
if (String(b).includes("Signaling server running")) {
clearTimeout(to);
resolvePromise(child);
}
});
child.stderr.on("data", (b) => process.stderr.write(`[sig] ${b}`));
child.on("exit", (code) => reject(new Error(`signaling exited early: ${code}`)));
});
}
async function runScenario(browser, { name, partitionVotes, assertConverged }) {
const ctxA = await browser.newContext();
const ctxB = await browser.newContext();
const state = { blockSig: false };
for (const ctx of [ctxA, ctxB]) {
await ctx.routeWebSocket(new RegExp(`127\\.0\\.0\\.1:${SIG_PORT}`), (ws) => {
if (state.blockSig) {
ws.close();
return;
}
ws.connectToServer();
});
}
const a = await ctxA.newPage();
const b = await ctxB.newPage();
const room = `${name}-${Math.random().toString(36).slice(2)}`;
const evidence = { scenario: name, room, steps: {} };
try {
await a.goto(PAGE);
await b.goto(PAGE);
const initArg = { room, signaling: [SIG] };
await a.evaluate((o) => window.commons.init(o), initArg);
await b.evaluate((o) => window.commons.init(o), initArg);
// 1. connect + prove the live transport actually works
await waitFor(() => a.evaluate(() => window.commons.peerCount() > 0), "A connects");
await waitFor(() => b.evaluate(() => window.commons.peerCount() > 0), "B connects");
await a.evaluate(() => window.commons.vote("prop", "warmup-voter", "yes"));
await waitFor(() => b.evaluate(() => window.commons.voteCount() >= 1), "warmup propagates to B");
evidence.steps.transportProven = {
peersA: await a.evaluate(() => window.commons.peerCount()),
peersB: await b.evaluate(() => window.commons.peerCount()),
bSawWarmupVote: (await b.evaluate(() => window.commons.voteCount())) >= 1,
};
// 2. genuine partition
state.blockSig = true;
await ctxA.setOffline(true);
await ctxB.setOffline(true);
await a.evaluate(() => window.commons.setConnected(false));
await b.evaluate(() => window.commons.setConnected(false));
await waitFor(() => a.evaluate(() => window.commons.peerCount() === 0), "A isolated");
await waitFor(() => b.evaluate(() => window.commons.peerCount() === 0), "B isolated");
const countBeforeA = await a.evaluate(() => window.commons.voteCount());
const countBeforeB = await b.evaluate(() => window.commons.voteCount());
// 3. independent votes while partitioned
await a.evaluate((v) => window.commons.vote(v.proposalId, v.voterId, v.choice), partitionVotes.a);
await b.evaluate((v) => window.commons.vote(v.proposalId, v.voterId, v.choice), partitionVotes.b);
// assert non-propagation across the partition window (the genuine-partition proof)
let leaked = false;
for (let i = 0; i < 15; i++) {
const ac = await a.evaluate(() => window.commons.voteCount());
const bc = await b.evaluate(() => window.commons.voteCount());
if (ac > countBeforeA + 1 || bc > countBeforeB + 1) {
leaked = true;
break;
}
await sleep(200);
}
evidence.steps.partition = {
offlineA: await a.evaluate(() => navigator.onLine) === false,
offlineB: await b.evaluate(() => navigator.onLine) === false,
peersA: await a.evaluate(() => window.commons.peerCount()),
peersB: await b.evaluate(() => window.commons.peerCount()),
signalingRouteBlocked: true,
leakedDuringPartition: leaked,
};
if (leaked) throw new Error(`${name}: votes LEAKED during partition - not genuinely partitioned`);
if (evidence.steps.partition.peersA !== 0 || evidence.steps.partition.peersB !== 0) {
throw new Error(`${name}: peers still connected during partition`);
}
// 4. heal + converge
state.blockSig = false;
await ctxA.setOffline(false);
await ctxB.setOffline(false);
await a.evaluate(() => window.commons.setConnected(true));
await b.evaluate(() => window.commons.setConnected(true));
const tally = await assertConverged(a, b, waitFor);
evidence.steps.healed = tally;
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await ctxA.close();
await ctxB.close();
}
}
async function main() {
const sig = await startSignaling();
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const results = {};
let failed = false;
try {
// HAPPY: two non-conflicting votes from each side merge to show both.
try {
results.happy = await runScenario(browser, {
name: "happy",
partitionVotes: {
a: { proposalId: "prop", voterId: "bob", choice: "yes" },
b: { proposalId: "prop", voterId: "carol", choice: "no" },
},
assertConverged: async (a, b, wf) => {
await wf(() => a.evaluate(() => window.commons.voteCount() >= 3), "A converges");
await wf(() => b.evaluate(() => window.commons.voteCount() >= 3), "B converges");
const tA = await a.evaluate(() => window.commons.tally("prop"));
const tB = await b.evaluate(() => window.commons.tally("prop"));
if (JSON.stringify(tA) !== JSON.stringify(tB)) {
throw new Error(`happy: tallies differ A=${JSON.stringify(tA)} B=${JSON.stringify(tB)}`);
}
if (tA.total !== 3 || tA.yes !== 2 || tA.no !== 1) {
throw new Error(`happy: expected union tally yes2/no1/total3, got ${JSON.stringify(tA)}`);
}
return { tallyA: tA, tallyB: tB, identical: true };
},
});
} catch (e) {
failed = true;
results.happy = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
// CONFLICT: both sides vote the SAME proposal with the SAME voter
// differently while partitioned -> reconnect yields ONE deterministic
// resolved vote (CRDT same-key resolution), not a crash or data loss.
try {
results.conflict = await runScenario(browser, {
name: "conflict",
partitionVotes: {
a: { proposalId: "prop", voterId: "dave", choice: "yes" },
b: { proposalId: "prop", voterId: "dave", choice: "no" },
},
assertConverged: async (a, b, wf) => {
await wf(() => a.evaluate(() => window.commons.voteCount() >= 2), "A converges");
await wf(() => b.evaluate(() => window.commons.voteCount() >= 2), "B converges");
// let any residual sync settle, then confirm stability + agreement
await sleep(500);
const tA = await a.evaluate(() => window.commons.tally("prop"));
const tB = await b.evaluate(() => window.commons.tally("prop"));
const vcA = await a.evaluate(() => window.commons.voteCount());
const vcB = await b.evaluate(() => window.commons.voteCount());
if (JSON.stringify(tA) !== JSON.stringify(tB)) {
throw new Error(`conflict: non-deterministic resolution A=${JSON.stringify(tA)} B=${JSON.stringify(tB)}`);
}
if (vcA !== vcB || vcA !== 2) {
throw new Error(`conflict: expected exactly 2 surviving votes (warmup+1 resolved dave), got A=${vcA} B=${vcB}`);
}
if (tA.total !== 2 || tA.yes + tA.no + tA.abstain !== 2) {
throw new Error(`conflict: data loss or double-count, tally=${JSON.stringify(tA)}`);
}
const resolvedDave = tA.yes === 2 ? "yes" : "no";
return { tallyA: tA, tallyB: tB, identical: true, surviving_dave_choice: resolvedDave };
},
});
} catch (e) {
failed = true;
results.conflict = e.evidence ?? { scenario: "conflict", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
sig.kill("SIGKILL");
}
// Write evidence artifacts
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
const mechanism =
"genuine partition: setOffline(true) on both contexts + signaling WebSocket route blocked + provider.disconnect() tears established RTCDataChannels (peerCount->0); partition proven by asserting votes do NOT propagate across the window";
writeFileSync(
resolve(evDir, "task-23-the-commons-hollow.json"),
JSON.stringify(
{
task: "23. ma-assembly partition-heal demo (problem 7, layer 2)",
qa: "happy",
description: "Two non-conflicting votes (one per side) cast while partitioned; reconnect merges to show both.",
tool: "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
run_command: "node e2e/assemblyPartition.e2e.mjs",
partition_mechanism: mechanism,
timestamp: now,
result: results.happy,
pass: Boolean(results.happy && results.happy.pass),
},
null,
2,
),
);
writeFileSync(
resolve(evDir, "task-23-the-commons-hollow-conflict.json"),
JSON.stringify(
{
task: "23. ma-assembly partition-heal demo (problem 7, layer 2)",
qa: "failure/conflict",
description:
"Both sides vote the SAME proposal with the SAME voter differently while partitioned; reconnect yields ONE deterministic resolved vote (CRDT same-key resolution), identical on both sides - no crash, no silent data loss.",
tool: "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
run_command: "node e2e/assemblyPartition.e2e.mjs",
partition_mechanism: mechanism,
timestamp: now,
result: results.conflict,
pass: Boolean(results.conflict && results.conflict.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(results, null, 2));
const happyOk = Boolean(results.happy && results.happy.pass);
const conflictOk = Boolean(results.conflict && results.conflict.pass);
console.log(`\nSUMMARY: happy=${happyOk ? "PASS" : "FAIL"} conflict=${conflictOk ? "PASS" : "FAIL"}`);
if (failed || !happyOk || !conflictOk) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});