seriesoftubes/tests/lib/mp-sim-play.js
jvanvik c5c7ea9508 Server-run engine: a restored network plays on exactly as before
A network loaded from its checkpoint drifted from the one that never stopped:
after a checkpoint on day 1, 2 or 5 its R differed at once (bizDem at Ashburn
6426 against 26, then cityDem, citySrv, tNet), and from the next day S too
(cash, eyeball growth). Three causes, each shown by a probe:

- R after a day is the R of the day's last routing, made before the day's end
  changed S (customers who left or signed, moods, bills, transit history) and
  routed from the memory of the R before it. srvLoad routed the saved S again
  from R's own memory: another R, which the next day reads (sfOf for eyeball
  growth, the peering share). Every compute() in the realm now keeps, for the
  R it makes, S as it routed it (one JSON per top-level key, 0.8 ms big) and
  the memory it started from. rt carries that routing point (pt: the memory,
  the keys that changed since, the keys S did not have then), and srvLoad
  routes that S again from it: the same R, byte for byte. The old restore test
  checkpointed after day 10, where a failure or event routed again at the end
  of the day and nothing changed after it: it passed by luck.
- The sales desk's tried offers (UI.slTried, an offer that did not fit waits a
  week) live outside S. A fresh realm forgot them and the desk tried other
  offers. rt carries them (sl); a day mark keeps them and the in-place restore
  after a throw puts them back (before, a parsed S dropped them).
- A save and a reload give some keys back in another key order (a customer's
  defaults go last, the intern's week tally in its own order), and the week's
  report lists the tally in that order. At a checkpoint rt carries the live
  text of each such key (ord, srvGate's round trip, about 8 ms), taken on load
  only where it holds what sanitize() made of the save. A fresh realm after a
  timeout takes the mark's own text the same way (live).

The plain game drifts across a save and a reload too (jsdom: from the first
day after it; the page routes a reloaded S with an empty R and keeps no desk
memory): a game property, so the engine carries what is missing.

The envelope keeps its shape {s, uidN, rt, last, day}; rt keeps R's own route
memory, so an older checkpoint loads as before (close, not exact). Big network:
the checkpoint grows from about 42-49 KB gzip to 54-79 KB (rt 7-29 KB; the
whole R would be 375 KB), srvSave from 2-2.5 ms to 7-8 ms, a load by one
routing. A day with its mark costs the same (big 39.8 -> 37.8 ms, busy
90.0 -> 88.8 ms, within noise: the day mark joins per-key JSON now, which pays
for the routing point).

Tests: the restore test checkpoints after days 1, 2, 5 and 10 of the scenic big
network and of the same network busy (intern on every order, the desk signing
on its own, failures, events, an attack), those after days 2 and 10 right after
an action and a what-if (sent to the copies too), each compared byte for byte
at once and 10 days later (SIM_LONG: after every day to 30, 60 checkpoints). It
fails on the old engine, and without any one of the three parts. The retry test
plays busy networks (fails without the desk memory in srvRestore). The market
checkpoint compares bytes too; canon() is gone.
2026-11-09 20:16:38 +01:00

80 lines
4.9 KiB
JavaScript

// What the engine's tests share (tests/mp-sim-engine.test.js, mp-sim-determinism.test.js, mp-sim-acts.test.js): the
// networks they play, the requests a page sends, and the page's side of a comparison, run in jsdom by the click path.
//
// page({save}) a jsdom page holding a network as the server's realm holds it (pinned clock, seeded): {ev, …}
// bigScenic() the big fixture as a server network (session marks, dice, its L2 customers on scenic routes),
// as live S text; the route-memory problem only shows with scenic circuits (design 4.7, 11)
// msg(act, args, more) an act or ask request as a page sends it (envelope-checked, ctx clamped)
// ctxOf(ev) the page's ctx: its selection, tab and left list, a desktop viewport
// begin(nid, o) a new network's begin entry for engine.load()
// RSIG R with its lazy parts read out, attacks by id (as tests/route-worker.test.js reads it)
// checked(r) r, after checkWorker (and checkEvent of the upd/snap inside) found nothing
// differs(a, b) the first differing top-level keys of two JSON texts (compare texts, never a deep-equal)
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const { load } = require('../harness');
const { lit } = require('../../scripts/lib/js-literal');
const { simId } = require('../../scripts/lib/page');
const A = require('../../scripts/lib/mp-sim-acts');
const { checkWorker, checkEvent } = require('./mp-sim-shape');
const CODE = 'K7Q2XD', PID = 'abcd1234', DEV = '9f8e7d6c', T0 = 1.7e12, STEP = 2500;
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
const TEST = { seed: 4242, now: T0, step: STEP };
// Time limits for engines whose tests inject no timeout: a busy machine (every test file at once) must not time out a
// big network's day or action that takes 40 ms when it is quiet. The tests of timeouts use the engine's own limits.
const ROOMY = { day: 20000, act: 20000, ask: 20000, pull: 20000, save: 20000, mark: 20000, small: 20000 };
let SIM;
const sim = () => SIM || (SIM = simId());
const BIG = path.join(__dirname, '..', 'fixtures', 'big-network.json');
// A jsdom page whose clock and dice are the realm's (TEST): a day there is __t+=STEP; dayTick(); and the day's end render.
function page({ save, uidN = 1000 } = {}) {
const h = load({ seed: TEST.seed });
h.ev(`window.__t=${T0};Date.now=()=>__t;UI.started=true;UI.pitched=true;UI.speed=0;closeModal();`);
if (save) h.ev(`S=migrate(JSON.parse(${lit(save)}));uidN=${uidN};R=emptyR();compute();`);
h.day = () => h.ev('__t+=' + STEP + ';dayTick();UI.ticking=true;renderHUD();UI.ticking=false;');
h.close = () => h.dom.window.close();
return h;
}
let BIGS = null;
function bigScenic() {
if (BIGS) return BIGS;
const h = load({ seed: TEST.seed });
h.ev(`S=migrate(JSON.parse(${lit(fs.readFileSync(BIG, 'utf8'))}));S.rng=${MP.seed};S.mp={...${JSON.stringify(MP)},seq:0,sim:1};
for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';`);
BIGS = h.ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))))');
h.dom.window.close();
return BIGS;
}
let n = 0;
function msg(act, args = {}, more = {}) {
const body = JSON.parse(JSON.stringify({ rid: 'r' + (++n).toString(36).padStart(8, '0'), dev: DEV, sim: sim(), act, args, ...more }));
const r = A.checkEnvelope(A.ASK.includes(act) ? 'ask' : 'act', body, { sim: sim() });
assert.ok(r.ok, `${act}: the page would not send this (${r.error})`);
return body;
}
const ctxOf = (ev, o = {}) => ({ sel: JSON.parse(ev('JSON.stringify(UI.sel)')), tab: ev('UI.tab'), left: ev('UI.left'), modal: false, w: 1024, h: 768, coarse: false, ...o });
const begin = (nid, o = {}) => ({ nid, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: MP.asn, mp: { ...MP, pid: nid }, tut: false, ...o }, lang: 'en', prefs: {} });
const RSIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";
function checked(r) {
const p = checkWorker(r);
assert.deepEqual(p, [], `${r && r.t}: ${p.join('; ')}`);
if (r && typeof r.upd === 'string') assert.deepEqual(checkEvent(JSON.parse(r.upd)), [], 'the update');
return r;
}
// The first top-level keys whose JSON differs, with a glimpse of each side: for a failing comparison's message.
function differs(a, b) {
const A2 = JSON.parse(a), B2 = JSON.parse(b);
return Object.keys({ ...A2, ...B2 }).filter((k) => JSON.stringify(A2[k]) !== JSON.stringify(B2[k]))
.slice(0, 4).map((k) => `${k}: ${String(JSON.stringify(A2[k])).slice(0, 300)} ≠ ${String(JSON.stringify(B2[k])).slice(0, 300)}`).join('\n');
}
module.exports = { CODE, PID, DEV, MP, T0, STEP, TEST, ROOMY, sim, page, bigScenic, msg, ctxOf, begin, RSIG, checked, differs };