Server-run engine: review fixes

The review of track T2 found these; each has a test in tests/mp-sim-*.

- Built-ins: an arg, array entry or draft that is '__proto__', 'constructor'
  or 'prototype' is refused by the envelope check and again by the realm
  (free text may still say them). After every realm call the trampoline
  checks the realm's built-ins against what they were at load; a realm
  whose built-ins changed answers {srvErr, polluted} and is replaced from
  the worker's mark like one that timed out. S as one JSON per key is a
  null-prototype object, so the epilogue's for…in never reads a prototype.
- A realm that cannot be built again is never used again: rebuild() tries
  once more without the packed R, and when that fails too the network is
  dropped (NO_REALM), and the engine tells the host (opts.onLost).
- A mark that fails or runs out of time changes nothing: it clears the old
  mark first, the realm is built again from its own save, never from an
  older mark, and the reply names the mark. A day rebuilds only from its
  own attempt's mark.
- A day whose alone or nets is not a list is refused whole (ERR); a throw
  in a load or day step answers that call, never ends the worker.
- An exit counts against the session the worker was running (the worker
  says so before each job and step), else as before. Workers of their own
  are capped (opts.maxOwn, 4): past that a session is given up.
- A worker that exits before it is ready is started again after a pause
  that doubles; after 5 in a row every call answers SIM_DOWN.
- The game text is read and compiled once, in createEngine: a src/ that
  does not compile throws there, and every worker, also one started after
  an exit, runs the game engine.simId names.
- A damaged route memory never breaks a save that loads (routed from
  nothing, logged), and only a server network loads (S.mp.sim, Normal).
- Routing memory (UI.rk, UI.rkR) is kept by the in-place restore and
  carried in rt (rk), so a reloaded or rolled-back network skips the same
  routings as the one that kept going.
- A fresh realm takes over the fx of the one it replaces (the mark's after
  a failed call, all of them after a read): badges, windows and toasts
  waiting for a page are not lost to a timeout.
- Windows: the stand-in elements answer querySelector from what was
  written (a [data-x] marker) and have a working classList, never the
  inert proxy that said every window is open. A request's ctx may name the
  open window, ctx.win = {k, ui} (mp-sim-acts.js WINDOWS: bstd, routing,
  charter, ops, pie), with the view state only the page holds (the
  intern's POP, the pie window's tab and POP), checked in the realm. This
  is an addition to the contract of design 5.8 that the page (T4) sends.
  The stand-in is hidden again after an act.
- xpBuild's via is a TEXT arg (256): a six-span express fits.
- actDone, askDone and pulled carry ms, the worker time of the call;
  engine.mem() and engine.has(code, nid) are public; prefs() passes a
  realm's err through; after close() every call rejects CLOSED.
- The fake engine fails as the engine does (NO_REALM, ERR, a load without
  a save, a day of an unknown session or naming an unloaded network,
  GAVE_UP, SIM_DOWN, CLOSED, onLost), its greet says its one-shots once and
  never 'told'; a test runs the same edge calls on both.
- SIM_DRAFT is built from DRAFT_TYPES.
This commit is contained in:
jvanvik 2026-11-09 22:16:52 +01:00
parent 3b8c331556
commit 9597d89079
11 changed files with 879 additions and 211 deletions

View file

@ -12,7 +12,9 @@ const { lit } = require('../scripts/lib/js-literal');
const A = require('../scripts/lib/mp-sim-acts');
const { createEngine } = require('../scripts/lib/mp-sim-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const { TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, checked, differs } = require('./lib/mp-sim-play');
const { MP, TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, checked, differs } = require('./lib/mp-sim-play');
// A local game made a server network, as the host's import does (5.2): the session's marks, then the save path.
const STAMP = `S.mp={...${JSON.stringify(MP)},seq:0,sim:1};`;
const E = createEngine({ workers: 1, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
@ -44,7 +46,7 @@ function pieCo() {
P.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e11;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500");
P.ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});S.nextFail=1e9;S.nextEvent=1e9;compute()");
P.ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute();checkGoals();");
P.ev("ACT.buildPop({city:'sin'});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});S.pie.stock=400;closeModal();S.rng=99;uidN=1000;S=migrate(JSON.parse(JSON.stringify(S)));compute();");
P.ev("ACT.buildPop({city:'sin'});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});S.pie.stock=400;closeModal();S.rng=99;uidN=1000;" + STAMP + "S=migrate(JSON.parse(JSON.stringify(S)));compute();");
return P;
}
// A small network with one transit port, Auto-TE and a script slot: a cap on that transit drops most of its traffic
@ -52,13 +54,13 @@ function pieCo() {
function oneUp() {
const P = page();
P.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=3000");
P.ev("ACT.buyTransit({city:'fra',net:NETS.filter(n=>sellsAt(n,'fra')&&n.price)[0].id,tier:1});ACT.coreUp();ACT.coreUp();S.te={on:true,day:S.day,script:''};closeModal();S.rng=99;uidN=1000;S=migrate(JSON.parse(JSON.stringify(S)));compute();");
P.ev("ACT.buyTransit({city:'fra',net:NETS.filter(n=>sellsAt(n,'fra')&&n.price)[0].id,tier:1});ACT.coreUp();ACT.coreUp();S.te={on:true,day:S.day,script:''};closeModal();S.rng=99;uidN=1000;" + STAMP + "S=migrate(JSON.parse(JSON.stringify(S)));compute();");
P.cap = `cap transit ${P.ev('NETS.find(n=>n.id===S.transit[0].net).name')} at 5 gbps`;
return P;
}
// A Hong Kong and a Shanghai POP and a mainland license: a link between them crosses the border, and may cross it premium.
const CROSS = "S.cnLic={state:'ok'};for(const c of ['hkg','sha'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S=migrate(JSON.parse(JSON.stringify(S)));compute();";
const loadInto = async (code, nid, P) => checked((await E.load(code, [{ nid, env: { s: P.ev('JSON.stringify(S)'), uidN: +P.ev('uidN'), rt: null }, lang: 'en', prefs: {} }]))[0]);
const loadInto = async (code, nid, P) => { const L = checked((await E.load(code, [{ nid, env: { s: P.ev('JSON.stringify(S)'), uidN: +P.ev('uidN'), rt: null }, lang: 'en', prefs: {} }]))[0]); assert.equal(L.err, undefined, L.err); return L; };
test('two-click buttons: the first click arms SRV_ARM\'s key (or waits for ok), and confirmed:true on the server is both clicks', async (t) => {
const P = rich();
@ -122,9 +124,11 @@ test('repayLoan: armed by its id, repaid by the second click (a network small en
});
/* The UI values an act reads, recorded while it runs (its redraw, after(), and windows left out: they read the page's
own state to draw it). Every page-held value it reads must be one of its DRAFTS; each of its DRAFTS is read on one of
the paths played here. */
const PAGE_HELD = [...new Set([...Object.keys(A.DRAFT_TYPES), 'lmode', 'dfMode', 'drag', 'snap', 'hover', 'vp', 'nf', 'dtab'])];
own state to draw it). Every page-held value it reads must be one of its DRAFTS, or the view state of a window (ctx.win,
WINDOWS: the window it redraws reads it); each of its DRAFTS is read on one of the paths played here. Page-held: what
the drafts are, what only LOCAL acts write (the windows' view state, the PNI sheet's plan), and the map's own. */
const WIN_UI = [...new Set(Object.values(A.WINDOWS).flatMap((w) => w.ui || []))];
const PAGE_HELD = [...new Set([...Object.keys(A.DRAFT_TYPES), ...WIN_UI, 'pniAll', 'lmode', 'dfMode', 'drag', 'snap', 'hover', 'vp', 'nf', 'dtab'])];
test('DRAFTS: the page-held UI values each act reads, all of them', (t) => {
const P = rich();
t.after(() => P.close());
@ -158,7 +162,7 @@ test('DRAFTS: the page-held UI values each act reads, all of them', (t) => {
reads[act] = new Set([...(reads[act] || []), ...JSON.parse(ev('JSON.stringify(__unspy())'))]);
ev('[after,openModal,renderAll,renderPanel,renderLeft,renderHUD,renderHint,renderDash,renderBank]=__keep;closeModal();');
}
const extra = [...reads[act]].filter((k) => PAGE_HELD.includes(k) && !A.DRAFTS[act].includes(k));
const extra = [...reads[act]].filter((k) => PAGE_HELD.includes(k) && !A.DRAFTS[act].includes(k) && !WIN_UI.includes(k));
assert.deepEqual(extra, [], `${act} reads page-held UI that is not in its DRAFTS`);
}
for (const act of Object.keys(A.DRAFTS)) {
@ -213,6 +217,65 @@ test('drafts and texts: the server\'s run of each draft and text act leaves the
assert.equal(T.ev("S.log.slice(0,3).some(x=>/AI apologises/.test(x.t))"), true, 'the slop path');
assert.deepEqual(T.errors, []);
});
/* A click inside a window (the page sends it with ctx.modal, and ctx.win names the window): the server redraws that
window as the page does, never another one (a stand-in that said every window is open had a rocket company's click
answer with the routing window, and the intern's with the build standard), with the view state only the page holds
(the intern's POP, the pie window's tab and POP). Every sent button in the windows: the window the page shows after
its own click against the act's ui.modal or ui.closed, and the network after it. */
test('a click inside a window: the server answers with the window the page shows, its view state and all', async (t) => {
const P = rich(), Q = pieCo();
t.after(() => { P.close(); Q.close(); });
await loadInto('W1NDW5', 'wind0001', P);
await loadInto('P1EW1N', 'piew0001', Q);
const lastPop = "Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).at(-1)";
const sets = [
[P, 'W1NDW5', 'wind0001', [['opsOpen', {}, ''], ['opsOpen', {}, `ACT.opsCity({v:${lastPop}})`], ['utilities', { city: 'fra' }, ''], ['bstdOpen', {}, ''],
['pniAllOpen', { net: null }, ''], ['salesOpen', {}, ''], ['routingOpen', {}, ''], ['models', {}, ''], ['teEdit', {}, ''], ['ip4Open', {}, '']]],
[Q, 'P1EW1N', 'piew0001', ['traffic', 'co', 'fly', 'dish'].map((tab) => ['pieOpen', {}, `ACT.pieTab({t:'${tab}'});ACT.pieCity({v:${lastPop}})`])],
];
const kind = (h) => (/data-routing/.test(h) ? 'routing' : /data-sheet="bstd"/.test(h) ? 'bstd' : (/<h2[^>]*>([^<]{0,40})/.exec(h) || [, '?'])[1].trim());
let n = 0;
const wins = new Set(), seenUi = new Set();
for (const [X, code, nid, openers] of sets) {
const { ev } = X;
ev("window.__mh=null;{const om=openModal;openModal=function(h,c){__mh=String(h);return om.apply(this,arguments);};}");
const open = (o, x, setup) => ev(`closeModal();UI.confirm=null;ACT[${JSON.stringify(o)}](${JSON.stringify(x)});${setup};__mh=null;`);
for (const [o, x, setup] of openers) {
open(o, x, setup);
if (ev("$('modal').hidden")) continue;
const seen = new Set();
const btns = JSON.parse(ev("JSON.stringify([...$('modal').querySelectorAll('[data-act],[data-chg]')].map(el=>{const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){}if(el.dataset.chg)a={...a,v:el.value};return [act,a];}))"));
for (const [act, args] of btns) {
// (Two-click, draft and text acts have their own tests: a text button reads its field, which the page sends.)
if (!A.SEND.includes(act) || A.CONFIRM[act] || A.DRAFTS[act] || (A.TEXT[act] && Object.keys(A.TEXT[act]).some((k) => !(k in args))) || seen.has(act)) continue;
seen.add(act);
open(o, x, setup);
const ctx = ctxOf(ev, { modal: true });
if (ctx.win) { wins.add(ctx.win.k); for (const k of Object.keys(ctx.win.ui || {})) seenUi.add(k); }
try { ev(`ACT[${JSON.stringify(act)}](${JSON.stringify(args)})`); } catch (e) { /* compared all the same */ }
const pageWin = ev("$('modal').hidden") ? 'closed' : ev('__mh') || 'unchanged';
const r = checked(await E.act(code, nid, msg(act, args, { ctx })));
const ui = r.upd ? JSON.parse(r.upd).acts[0].ui : {};
const srvWin = ui.modal ? ui.modal.h : ui.closed ? 'closed' : 'unchanged';
n++;
const name = (w) => (w === 'closed' || w === 'unchanged' ? w : kind(w));
assert.ok(srvWin === pageWin, `${o} → ${act} ${JSON.stringify(args)}: the page shows ${name(pageWin)}, the server ${name(srvWin)}${name(pageWin) === name(srvWin) ? ' (another drawing of it)' : ''}`);
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
assert.ok(want === got, `${act}:\n${want === got ? '' : differs(want, got)}`);
}
}
// The stand-in is no window once the act is done.
assert.deepEqual((await E.eval(code, nid, "return [$('modal').hidden,$('modal').className,$('modalCard').innerHTML]")).value, [true, '', '']);
assert.deepEqual(X.errors, []);
}
t.diagnostic(`${n} buttons inside windows sent`);
assert.ok(n >= 30, `${n} buttons`);
assert.deepEqual([...wins].sort(), ['bstd', 'ops', 'pie', 'routing'], 'the windows the page named');
assert.deepEqual([...seenUi].sort(), [...WIN_UI].sort(), 'and their view state');
// Every view state a window carries is checked in the realm before it is set.
assert.deepEqual((await E.eval('W1NDW5', 'wind0001', 'return Object.keys(SIM_WINOK).sort()')).value, [...WIN_UI].sort());
});
async function play(code, nid, ev, plays) {
for (const [act, args, before, ui] of plays) {
ev(before);