The intern and customers' promises counted once per network: ports, caches and PNIs in one pass, shared searches

The game plays exactly as before.

* The NOC intern plans every POP in one pass: portsAt() counts router ports for all cities at once (routers, ports
  and cache orders; the ports job keeps ports in use and reserved by city between two jobs), cachePlan() sorts the
  boxes by POP once and cityShSum() sums a city's shares once per table, pniFlows() reads every POP's flows from
  routing's columns (R.flc) in one pass and pniWant() gives the weekly PNI round its sort key from typed columns.
  pniBatchRun() lets a frame through every few networks; pniQuote() looks existing PNIs and ports up from the batch.
* A dark fiber's capacity asks optG() once per run of identical optics (dfLit()); linkDown() and ownGlass() ask
  dfOn(), whether it carries anything for you, without the sum unless an optic is out or managed waves are sold on
  it. terrIslands() tests !l.sub first.
* Latency: latGraph() lists each city's links once in S.links order (typed arrays), latRun() is the same search with
  the same sums, latPairs() searches once per city for a boutique's finance routes and the latency offers.
* Diverse paths: divGraph()/divOn() number the cities and risks once; promiseCheck() shares a diversity graph, the
  land islands and one latency search per origin across every customer when the intern weighs taking a fiber out,
  and spots0() shares the graph for sovereign offers.

Tests: day-steps (cache planner, ports at every POP and flows from columns equal the old ways; the PNI round through
pniBatchRun), fiber-lit-and-latency (with failed optics and managed waves), shared-promise-checks, intern-personas.
This commit is contained in:
Antoine 2026-11-07 22:21:22 +01:00
parent d03dde6fcd
commit 44116103be
No known key found for this signature in database
GPG key ID: 728FF1CE15732B05
16 changed files with 373 additions and 66 deletions

View file

@ -1,7 +1,8 @@
// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the
// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day.
// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day. Also: the standing
// orders' cache planner, now linear, plans the same boxes as the old formula.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
@ -200,7 +201,7 @@ test('a customer dropped while a sales trial routes: the trial runs again on the
test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
// The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
const pb=pniBatchRun;pniBatchRun=function*(...a){const b=yield* pb(...a);window.__b=b;return b;};
window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
window.__n=S.pni.length-n0;`;
@ -239,3 +240,61 @@ test('an incident repaired while its routing runs: the failure and the monkey st
assert.equal(p.ev('typeof __c.impact'), 'number');
assert.deepEqual(p.errors, []);
});
test('the cache planner plans what the old formula planned, city by city', (t) => {
const h = open(t, 777);
h.ev(SETUP);
// The formula as it was: the total share summed again for every network, the boxes filtered again for each.
h.ev(`window.oldDem=(c,id)=>{const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;};
window.oldPlan=city=>{const p=S.pops[city],sites=p.site2?['a','b']:['a'],add=[],have={};
for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;}
for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&oldDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0);
sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}});
const dem=oldDem(city,n.id),nb=cacheBox(city);
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
return add;};`);
// Some boxes gone, so there is something to plan; Russia, China and Korea's exit rule have tables of their own.
h.ev("S.caches=S.caches.filter((c,i)=>i%3);S.krExit=true;for(const c of ['mos','pek','icn'])if(!S.pops[c])S.pops[c]={day:0,bb:{d:1},boost:0,down:0,routers:2,gen:true,rgen:0,site2:true};compute();");
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
let boxes = 0;
for (const c of cities) {
const got = h.ev(`JSON.stringify(utilityCaches('${c}').add)`);
assert.equal(got, h.ev(`JSON.stringify(oldPlan('${c}'))`), c);
boxes += JSON.parse(got).length;
for (const id of JSON.parse(h.ev('JSON.stringify(NETS.map(n=>n.id))'))) if (h.ev(`cacheDem('${c}','${id}')!==oldDem('${c}','${id}')`)) assert.fail(`cacheDem ${c} ${id}`);
}
assert.ok(boxes > 50, `boxes planned: ${boxes}`);
assert.deepEqual(h.errors, []);
});
test('ports counted for every POP at once, and flows summed from the columns, are what each POP counted alone', (t) => {
const h = open(t, 777);
h.ev(SETUP);
// The old ways: one pass over the whole network per POP, and the flows as objects (R.fl).
h.ev(`window.oldPorts=(c,g)=>{let u=0;
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);}
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
if(S.myIx[c])u+=1;
u+=cachePorts(c,[],g)+(S.nni||[]).filter(x=>x.city===c).length;return u;};
window.oldFlows=c=>{const m={};for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}return m;};`);
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
for (const g of ['undefined', '0', 'RG.length-1']) {
const all = JSON.parse(h.ev(`JSON.stringify([...portsAt(Object.keys(S.pops),${g})])`));
assert.deepEqual(all, cities.map((c) => [c, h.ev(`oldPorts('${c}',${g})`)]), `ports, router model ${g}`);
}
assert.ok(h.ev('Object.keys(S.pops).some(c=>portsUsed(c)>10)'));
for (const c of cities) assert.equal(h.ev(`JSON.stringify(pniFlows('${c}'))`), h.ev(`JSON.stringify(oldFlows('${c}'))`), `flows from ${c}`);
assert.ok(h.ev('Object.keys(S.pops).some(c=>Object.keys(pniFlows(c)).length>5)'));
// The intern's weekly PNI round reads only pniVal()'s want, from typed columns (pniWant()): the very same numbers, for
// every network at every POP (and 0 where no flow goes).
const odd = h.ev(`(()=>{const bad=[];let n=0;for(const c in S.pops)for(const id of NET_IDS){const v=pniVal(id,c).want,w=pniWant(c,id);if(v>0)n++;
if(!Object.is(v,w))bad.push(c+'/'+id+' '+v+' '+w);}return JSON.stringify({n,bad:bad.slice(0,5)});})()`);
const r = JSON.parse(odd);
assert.deepEqual(r.bad, [], 'pniWant() is pniVal().want');
assert.ok(r.n > 50, `pairs with traffic: ${r.n}`);
assert.deepEqual(h.errors, []);
});

View file

@ -0,0 +1,69 @@
// A fiber's capacity added up per run of identical optics, "is this fiber lit?" answered without adding it up
// (dfOn(), linkDown()), and latency searches over one list of each city's links (latGraph(), latRun(), latPairs():
// bestLat(), the boutique's routes, latency offers). Same answers as before: the old ways are written out here.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// The fixture's links as the player's own dark fiber (it has none), lit with 2 to 40 channels of one or two optics.
const GLASS = "S.links.forEach((l,i)=>{l.kind='df';l.own=true;l.sys='roadm';l.ready=0;l.regen=3;const o=['zr4','zr8','tp16','tp32'][i%4];l.ch=Array.from({length:2+i%39},(_,j)=>i%5===0&&j%3===0?'zr4':o);delete l.tier;})";
// Before: every channel's optG() added up, and the search that walked every link for every city it reached.
const OLD = `window.oldCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,Math.max(0,g)-mwG(l));};
window.oldLat=(a,b,f)=>{const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};`;
// Seeded trouble on the fibers: cuts, a failed optic (named or not, over or not, maybe the only one), equipment down, still building,
// channels taken out or mixed, a subsea upgrade in service, managed waves sold on it (sometimes more than it carries).
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
for(const l of S.links){const r=rnd();if(r<.06)l.cut=D+5;else if(r<.14){if(rnd()<.4)l.ch=l.ch.slice(0,1);l.chFail={o:rnd()<.5&&l.ch.length?l.ch[l.ch.length-1]:rnd()<.5?'tp32':null,until:rnd()<.8?D+3:D-1};}
else if(r<.18)l.eqDown=D+2;else if(r<.22)l.ready=D+4;else if(r<.28)l.ch=l.ch.slice(0,Math.floor(rnd()*3));else if(r<.32)l.ch=l.ch.map((c,i)=>i%2?c:'zr8');
else if(r<.36){l.sub=true;l.km=2000+Math.floor(rnd()*9000);if(rnd()<.5)l.subterminal=D-1;if(rnd()<.5)l.subengineering=D-1;}
if(rnd()<.15)S.biz.push({type:'mwave',link:l.id,slots:1+Math.floor(rnd()*30),g:rnd()<.5?100:400});}})()`;
test('a fiber is lit, and carries, what adding up every channel said', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${GLASS};${OLD}`);
let lit0 = 0, dark = 0;
for (let v = 0; v < 6; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(v)};S.day+=${v}`);
const r = JSON.parse(ev(`JSON.stringify(S.links.map(l=>[oldCap(l),dfCap(l),dfOn(l),linkDown(l),l.cut>S.day]))`));
for (const [want, cap, on, down, cut] of r) {
assert.equal(cap, want);
assert.equal(on, want > 0);
assert.equal(down, cut || !(want > 0));
if (on) lit0++; else dark++;
}
}
assert.ok(lit0 > 600 && dark > 30, `lit ${lit0}, dark ${dark}`);
assert.deepEqual(errors, []);
});
test('latency searches give what walking every link gave: bestLat, every pair at once, the boutique\'s routes', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
const P = "Object.keys(S.pops).slice(0,25).concat(FIN.filter(c=>S.pops[c]))";
const check = (f) => JSON.parse(ev(`(()=>{const P=${P},f=${f},bad=[];let n=0;
for(let i=0;i<P.length;i++)for(let j=i+1;j<P.length;j++){const w=oldLat(P[i],P[j],f);if(bestLat(P[i],P[j],f)!==w)bad.push(P[i]+'-'+P[j]);if(isFinite(w))n++;}
for(const [a,b,ms] of latPairs(P,f))if(ms!==oldLat(a,b,f))bad.push('pairs '+a+'-'+b);return JSON.stringify({n,bad:bad.slice(0,5)});})()`));
// Leased waves, then some cut, then the player's own glass in trouble.
let r = check('null');
assert.deepEqual(r.bad, []);
assert.ok(r.n > 150, `pairs with a path: ${r.n}`);
ev("S.links.forEach((l,i)=>{if(i%4===0)l.cut=S.day+3;})");
r = check("l=>l.kind!=='vxc'");
assert.deepEqual(r.bad, []);
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(2)};S.mode='normal';delete S.scn;S.charter='boutique'`);
r = check('ownGlass');
assert.deepEqual(r.bad, []);
assert.ok(r.n > 50, `pairs over own glass: ${r.n}`);
// The boutique's routes: each financial pair, its own glass against the best leased latency. In trouble, then not.
const SOL = `(()=>{const f=FIN.filter(c=>S.pops[c]),v=[];for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=oldLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}return JSON.stringify(v);})()`;
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), ev(SOL));
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};S.mode='normal';delete S.scn;S.charter='boutique'`);
const want = ev(SOL);
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), want);
assert.ok(JSON.parse(want).length >= 1, `routes that beat leased: ${want}`);
assert.deepEqual(errors, []);
});

View file

@ -37,7 +37,7 @@ test('Annie peers every day and orders PNIs twice a week; the others weekly', t
ev("S.ops.on.ix=true;S.day=15;opsDay(S.day)");
assert.equal(ev('Object.keys(S.rs).length>0'), want, `${id} on a Tuesday`);
// How often the PNI order looks for networks to order from, over one week.
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};if(typeof pniBatchRun==='function')pniBatchRun=function*(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
assert.equal(ev('__pb'), want ? 2 : 1, `${id}: PNI rounds a week`);
assert.deepEqual(errors, []);
}

View file

@ -0,0 +1,88 @@
// Diverse paths, a land path and a latency budget asked for many pairs on one network: the offers spotted for
// sovereign clouds (spots0()) and the intern's check before taking a wave out (opsDecomSafe()) build one graph per
// network and ask it for every pair (divGraph()/divOn(), promiseCheck()). Same answers as before: the old ways are
// written out here.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// Before: each question filtered the links again and built both searches' graphs from lists.
const OLD = `window.oldDiv=(a,b)=>{const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));
const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));};
window.oldLand=(a,b)=>{const adj={};for(const l of S.links.filter(l=>!l.sub&&!linkDown(l))){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;};
window.oldLat=(a,b)=>{const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}
if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};
window.oldSafe=l=>{const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}};`;
// Seeded trouble: cuts, POPs down, trenches shared by several links, a VXC to a city with no POP.
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
for(const l of S.links)if(rnd()<.1)l.cut=D+3;for(const c in S.pops)if(rnd()<.06)S.pops[c].down=D+2;
const ls=S.links.filter(l=>!l.sub);for(let i=${v};i<ls.length;i+=6)ls[i].trench='shared'+(i%3);
const p=FABS.find(f=>f.cities.some(c=>S.pops[c])&&f.cities.some(c=>!S.pops[c]));if(p&&${v}%2){const a=p.cities.find(c=>S.pops[c]),b=p.cities.find(c=>!S.pops[c]);
S.links.push({id:'vx'+${v},a,b,kind:'vxc',prov:p.id,vt:'1g',km:kmBetween(a,b),sub:isSub(a,b),mo:1,cut:0,day:0});}})()`;
test('diverse paths: one graph for every pair answers like a search per pair, and spots the same sovereign clouds', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
let yes = 0, no = 0;
for (let v = 0; v < 6; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''}`);
const r = JSON.parse(ev(`(()=>{const C=Object.keys(S.pops).filter((c,i)=>i%3===0).concat(S.links.filter(l=>l.kind==='vxc').map(l=>l.b),['nowhere']),g=divGraph(),bad=[];let y=0,n=0;
for(const a of C)for(const b of C){const w=oldDiv(a,b);if(diversePaths(a,b)!==w||divOn(g,a,b)!==w)bad.push(a+'-'+b);w?y++:n++;}
const by={};for(const c of Object.keys(S.pops).filter(bizCity))(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);const sov=[];
for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(oldDiv(cs[i],cs[j]))sov.push(cs[i]+'-'+cs[j]);
const got=spots0(0).filter(s=>s.t==='sov').map(s=>s.a+'-'+s.b);return JSON.stringify({y,n,bad:bad.slice(0,5),sov,got});})()`));
assert.deepEqual(r.bad, [], `state ${v}`);
assert.deepEqual(r.got, r.sov, `sovereign clouds, state ${v}`);
yes += r.y; no += r.n;
}
assert.ok(yes > 300 && no > 1000, `diverse ${yes}, not ${no}`);
assert.deepEqual(errors, []);
});
test('taking a wave out: the shared check refuses what asking customer by customer refused, for each promise', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
// Customers between linked POPs: diverse paths, afraid of sharks, a latency budget just above today's best.
const BIZ = `(()=>{const ls=S.links.filter(l=>S.pops[l.a]&&S.pops[l.b]);let n=0;for(let i=0;i<ls.length;i+=2){const l=ls[i],k=['diverse','sharks','lat'][n%3],b={id:'pc'+n++,city:l.a,city2:l.b,type:'l2',bw:1,reqs:[k]};
if(k==='lat')b.latMax=+(bestLat(l.a,l.b)+0.02).toFixed(2);if(k!=='lat'||isFinite(b.latMax))S.biz.push(b);}})()`;
const refused = { diverse: 0, sharks: 0, lat: 0 };
for (let v = 0; v < 4; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''};${BIZ}`);
// From a few hubs to every POP: several customers of one city, some served and some not.
const hub = JSON.parse(ev(`(()=>{const P=Object.keys(S.pops),H=P.filter((c,i)=>i%25===0);let n=0;for(const a of H)for(const b of P)if(a!==b)for(const k of ['diverse','sharks','lat']){const o={id:'hb'+n++,city:a,city2:b,type:'l2',bw:1,reqs:[k]};
if(k==='lat')o.latMax=n%2?oldLat(a,b):oldLat(a,b)*0.995;S.biz.push(o);}
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
const pc=promiseCheck(),bz=S.biz.filter(b=>/^hb/.test(b.id)),w=bz.map(chk);S.biz=S.biz.filter(b=>!/^hb/.test(b.id));
return JSON.stringify({bad:bz.filter((b,i)=>pc(b)!==w[i]).map(b=>b.id).slice(0,5),yes:w.filter(Boolean).length,n:w.length});})()`));
assert.deepEqual(hub.bad, [], `hubs, state ${v}`);
assert.ok(hub.yes > 50 && hub.n - hub.yes > 50, JSON.stringify(hub));
const r = JSON.parse(ev(`(()=>{const bad=[],why=[],all=S.biz;for(const l of S.links.slice(0,60)){const w=oldSafe(l);if(opsDecomSafe(l)!==w)bad.push(l.id);
if(!w)for(const k of ['diverse','sharks','lat']){S.biz=all.filter(b=>/^pc/.test(b.id)&&b.reqs[0]===k);if(!oldSafe(l))why.push(k);S.biz=all;}}
return JSON.stringify({bad,why});})()`));
assert.deepEqual(r.bad, [], `state ${v}`);
for (const k of r.why) refused[k]++;
}
for (const k in refused) assert.ok(refused[k] >= 2, `refused for ${k}: ${JSON.stringify(refused)}`);
assert.deepEqual(errors, []);
});
test('latency searches at the edges: a city with no link, the same city twice, a city nobody reaches', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();`);
const r = JSON.parse(ev(`(()=>{const lone=CITIES.find(c=>!S.links.some(l=>l.a===c.id||l.b===c.id)).id,p=S.links[0].a,g=latGraph(),d=latRun(g,p);
return JSON.stringify([bestLat(lone,lone),bestLat(p,p),bestLat(lone,p),bestLat(p,lone),latRun(g,lone),latAt(g,d,p,p),latAt(g,d,p,lone),latAt(g,null,lone,p),
latPairs([lone,p,lone]).map(x=>x[2])]);})()`));
assert.deepEqual(r, [0, 0, null, null, null, 0, null, null, [null, 0, null]]);
assert.deepEqual(errors, []);
});