diff --git a/apps/server/src/arrival-placement.ts b/apps/server/src/arrival-placement.ts index 876d24907..112c957b4 100644 --- a/apps/server/src/arrival-placement.ts +++ b/apps/server/src/arrival-placement.ts @@ -6,18 +6,18 @@ // standing spot in the open area out to the world's bounds, else the nearest spot of the largest pocket; the birth then // carries it as the existing birth-near/1 hint {at, first:true}, so the event records the exact place and replay never // searches. Refused (birth.arrival-unavailable) only when the world has no standing ground at all. -import { probeNativeHumanBirth, type ArrivalPocket, type ArrivalSpot } from '@souls/engine-mars'; -import type { BirthNearV1, HumanBirthProbe } from '@souls/engine-contract'; +import { nativeBirthPlacement, type ArrivalPocket, type ArrivalSpot, type NativeBirthPlacement } from '@souls/engine-mars'; +import type { BirthNearV1 } from '@souls/engine-contract'; import type { WorldHost } from './world.ts'; type ArrivalEngine = { arrivalSearchV1?(label?: string): ArrivalSpot | null; arrivalPocketV1?(p: [number, number], label?: string): ArrivalPocket; arrivalBlockedV1?(): boolean }; export type BirthIdentity = { id: string; label: string; soul: string }; -export type BirthPlan = { probe: HumanBirthProbe; near?: { at: [number, number]; first: true } }; +export type BirthPlan = { probe: NativeBirthPlacement; near?: { at: [number, number]; first: true } }; const engineOf = (host: WorldHost) => host.engine as unknown as ArrivalEngine; /** The spot the arrival search would use instead of the default, or undefined when the default stands (see header). */ -function searchFor(host: WorldHost, who: BirthIdentity, probe: HumanBirthProbe): { at: [number, number]; first: true } | 'none' | undefined { +function searchFor(host: WorldHost, who: BirthIdentity, probe: NativeBirthPlacement): { at: [number, number]; first: true } | 'none' | undefined { const e = engineOf(host); if (!e.arrivalSearchV1 || !e.arrivalPocketV1) return undefined; let pocket: ArrivalPocket | undefined; if (probe.outcome === 'ready') { @@ -31,14 +31,14 @@ function searchFor(host: WorldHost, who: BirthIdentity, probe: HumanBirthProbe): return { at: s.at, first: true }; } -/** Probe a native birth, moving it off a blocked arrival point when needed. Read-only (detached checkpoints). */ +/** Place a native birth, moving it off a blocked arrival point when needed. Read-only (on the live engine, A13). */ export function planNativeBirth(host: WorldHost, who: BirthIdentity): BirthPlan { - const first = probeNativeHumanBirth(host.engine, host.factory, who); + const first = nativeBirthPlacement(host.engine, host.factory, who); if (first.outcome !== 'ready' && !(first.outcome === 'unavailable' && first.diagnostic.code === 'birth.arrival-unavailable')) return { probe: first }; const near = searchFor(host, who, first); if (near === undefined) return { probe: first }; if (near === 'none') return { probe: first.outcome === 'unavailable' ? { ...first, diagnostic: { code: 'birth.arrival-unavailable', message: 'no free walkable ground in this world' } } : first }; - return { probe: probeNativeHumanBirth(host.engine, host.factory, { ...who, near: near satisfies BirthNearV1 }), near }; + return { probe: nativeBirthPlacement(host.engine, host.factory, { ...who, near: near satisfies BirthNearV1 }), near }; } /** A direct create's birth-near/1 hint at the arrival point itself, without `first` (MarsEngine.arrivalCrowdV1): in a world diff --git a/apps/server/src/birth-placement-eden.test.ts b/apps/server/src/birth-placement-eden.test.ts new file mode 100644 index 000000000..95f01cac3 --- /dev/null +++ b/apps/server/src/birth-placement-eden.test.ts @@ -0,0 +1,54 @@ +// A13 (#2621): on Eden 2026, the birth path's live placement (placeNativeHumanBirth: spawnHuman's own search on the live +// engine) agrees with the detached probe it replaced (probeNativeHumanBirth: a full-world snapshot and restore) on every +// birth: the same spot, or a refusal for the same reason. Births one after another at the arrival point while a body +// walks, then the arrival point crowded until its rings are full, with the hinted forms the server sends then. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { probeNativeHumanBirth, placeNativeHumanBirth, livePlacementExact } from '@souls/engine-mars'; +import type { Engine, EngineFactory } from '@souls/engine-contract'; +import { bootEden } from '../test/eden-capabilities-timing.ts'; + +const NO_EDEN = existsSync(new URL('../../../worlds/templates/eden-2026.json', import.meta.url)) ? false : 'needs worlds/templates/eden-2026.json (lane/engine content)'; +type Request = { id: string; label: string; soul: string; near?: { at: [number, number]; first?: boolean } }; + +/** The navigation's epoch and whole-ground window: derived state the state hash cannot see (#2624 review). */ +const navOf = (e: Engine) => { const sp = (e as unknown as { rt: { services: { spatial: { epoch: number; ground?: { window?: unknown } } } } }).rt.services.spatial; return JSON.stringify({ epoch: sp.epoch, window: sp.ground?.window ?? null }); }; +function agrees(e: Engine, f: EngineFactory, raw: Request) { + const hash = e.stateHash(), tick = e.world.tick; + const { contract: _c, base: _b, ...probe } = probeNativeHumanBirth(e, f, raw), nav = navOf(e), placed = placeNativeHumanBirth(e, raw); + assert.deepEqual(placed, probe, JSON.stringify(raw)); + assert.equal(e.stateHash(), hash); assert.equal(e.world.tick, tick); assert.equal(navOf(e), nav, 'the live placement moved the navigation'); + return placed; +} + +test('A13 oracle on Eden 2026: the live birth placement equals the detached probe, plain and crowded', { timeout: 900_000, skip: NO_EDEN }, async (t) => { + const w = await bootEden(); + t.after(() => w.close()); + w.brain.quiesce(); + const e = w.host.engine, f = w.host.factory, ana = e.world.entities[w.soul.entityId]!, at: [number, number] = [ana.pose.p[0], ana.pose.p[2]]; + assert.equal(livePlacementExact(e), true, 'Eden 2026 is on paged ground: births place on the live engine'); + const walk = e.perform({ actor: w.soul.entityId, label: 'walk', steps: [{ verb: 'walk_to', params: { to: [at[0] + 12, 0, at[1] + 8] } }] } as never) as { ok: boolean }; + assert.equal(walk.ok, true); + const counts: Record = {}; + const born = (req: Request) => { + const p = agrees(e, f, req); counts[p.outcome] = (counts[p.outcome] ?? 0) + 1; + if (p.outcome === 'ready') { e.spawnHuman(req); assert.deepEqual(e.world.entities[req.id]!.pose.p, p.position); } + for (let i = 0; i < 2; i++) e.step(); + return p; + }; + // plain: births one after another at the arrival point, the first Soul walking away + for (let i = 0; i < 16; i++) born({ id: `h_a13_${i}`, label: `Joiner ${i}`, soul: `s_a13_${i}` }); + // crowded: bodies stand on the rings until a birth there is refused, then the hinted forms + let refused = 0; + for (let i = 16; i < 140 && refused < 2; i++) { + const req = { id: `h_a13_${i}`, label: `Joiner ${i}`, soul: `s_a13_${i}` }, p = i % 6 === 0 ? born(req) : placeNativeHumanBirth(e, req); + if (p.outcome === 'ready' && !e.world.entities[req.id]) e.spawnHuman(req); + if (p.outcome === 'unavailable') { refused++; if (i % 6 !== 0) born(req); } + } + for (const [k, near] of [{ at }, { at: [at[0] + 6, at[1] - 4] as [number, number], first: true }].entries()) + born({ id: `h_a13_hint_${k}`, label: `Hinted ${k}`, soul: `s_a13_hint_${k}`, near }); + t.diagnostic(JSON.stringify(counts)); + assert.ok((counts.ready ?? 0) >= 16 && (counts.unavailable ?? 0) >= 1, JSON.stringify(counts)); + assert.deepEqual(e.runtime.violations, []); +}); diff --git a/apps/server/src/lifecycle-runner.test.ts b/apps/server/src/lifecycle-runner.test.ts index 582ebf6ba..54e601584 100644 --- a/apps/server/src/lifecycle-runner.test.ts +++ b/apps/server/src/lifecycle-runner.test.ts @@ -178,32 +178,41 @@ test('old histories replay unchanged: a birth with lane PB\'s {at} hint (births assert.deepEqual(restart.engine.world.entities.h_old?.pose.p,f.host.engine.world.entities.h_old?.pose.p); }); -// lane srv-join-stall (2026-10-31): each detached birth probe is a full world snapshot + restore on the tick thread +// lane srv-join-stall (2026-10-31): each detached birth probe was a full world snapshot + restore on the tick thread // (eden2 Stage B: ~2 s each, three per Soul, so a 4-Soul join burst held main for 30 s+ and the launcher restarted the -// world as wedged). One admission now probes twice: the plan (pump) and the guard under the write lock; the journal link -// in that same transaction re-checks identity only. -test('one lifecycle admission restores the detached probe engine twice, not three times',async t=>{ +// world as wedged); that lane cut it to two (the plan in pump, the guard under the write lock). A13 (#2621): both now +// place on the live engine, so an admission restores none; SIM_BIRTH_PROBE=1 (the probe deciding: the A/B off arm) +// still runs the two. +const withProbeMode=async(mode:string|undefined,run:()=>Promise)=>{ + const was=process.env.SIM_BIRTH_PROBE;if(mode===undefined)delete process.env.SIM_BIRTH_PROBE;else process.env.SIM_BIRTH_PROBE=mode; + try{return await run();}finally{if(was===undefined)delete process.env.SIM_BIRTH_PROBE;else process.env.SIM_BIRTH_PROBE=was;} +}; +const fourBirths=(mode:string|undefined)=>withProbeMode(mode,async()=>{ const counted=await marsFactory({...GREEN_FIELD_WORLD,safeCrewRemoval:true});let restores=0; const restore=counted.restore.bind(counted);(counted as {restore:typeof restore}).restore=(s:Parameters[0])=>{restores++;return restore(s);}; - const f=fixture(':memory:',counted);t.after(()=>f.db.close()); - const before=restores;f.journal.acceptCreate(scope,requestId,input,()=>true);await settle(f); - assert.equal(f.journal.get(scope,requestId)!.state,'complete');assert.equal(f.runner.faults.size,0); - assert.equal(restores-before,2); + const f=fixture(':memory:',counted); + try{ + const ids=[0,1,2,3].map(i=>({scope:{...scope,soulId:'s_J'+i,entityId:'h_J'+i},requestId:'lc_'+(0xa0+i).toString(16).padStart(32,'0'),name:'Joiner '+i})); + for(const j of ids)f.journal.acceptCreate(j.scope,j.requestId,{...input,name:j.name},()=>true); + const perCall:number[]=[];const wrap=(o:{[k:string]:unknown},k:string)=>{const fn=o[k] as ()=>void;o[k]=()=>{const b=restores;try{fn.call(o);}finally{perCall.push(restores-b);}};}; + wrap(f.host as unknown as {[k:string]:unknown},'drainInputs');wrap(f.runner as unknown as {[k:string]:unknown},'pump'); + const before=restores;await settle(f,10); + assert.equal(f.runner.faults.size,0); + for(const j of ids)assert.equal(f.journal.get(j.scope,j.requestId)!.state,'complete',j.name); + const events=f.db.events(worldId).map(e=>({seq:e.seq,tick:e.tick,kind:e.kind,author:e.author,payload:e.payload})); + return {ids,restores:restores-before,perCall,events,hash:f.host.engine.stateHash(),kernel:kernelHash(f.host.kernel), + poses:ids.map(j=>f.host.engine.world.entities[j.scope.entityId]!.pose.p)}; + }finally{f.db.close();} +}); +test('four pending births are admitted one at a time with no detached probe; the probe arm runs two per admission, one per call',async()=>{ + for(const [mode,want] of [[undefined,0],['1',8]] as const){ + const r=await fourBirths(mode); + assert.equal(r.restores,want,String(mode));assert.ok(Math.max(...r.perCall)<=1,`a single call ran ${Math.max(...r.perCall)} probes`); + assert.deepEqual(r.events.filter(e=>e.kind==='birth').map(e=>(e.payload as {soulId:string}).soulId),r.ids.map(j=>j.scope.soulId)); + } }); -test('four pending births are admitted one at a time: no single drainInputs or pump runs more than one detached probe',async t=>{ - const counted=await marsFactory({...GREEN_FIELD_WORLD,safeCrewRemoval:true});let restores=0; - const restore=counted.restore.bind(counted);(counted as {restore:typeof restore}).restore=(s:Parameters[0])=>{restores++;return restore(s);}; - const f=fixture(':memory:',counted);t.after(()=>f.db.close()); - const ids=[0,1,2,3].map(i=>({scope:{...scope,soulId:'s_J'+i,entityId:'h_J'+i},requestId:'lc_'+(0xa0+i).toString(16).padStart(32,'0'),name:'Joiner '+i})); - for(const j of ids)f.journal.acceptCreate(j.scope,j.requestId,{...input,name:j.name},()=>true); - const perCall:number[]=[];const wrap=(o:{[k:string]:unknown},k:string)=>{const fn=o[k] as ()=>void;o[k]=()=>{const b=restores;try{fn.call(o);}finally{perCall.push(restores-b);}};}; - wrap(f.host as unknown as {[k:string]:unknown},'drainInputs');wrap(f.runner as unknown as {[k:string]:unknown},'pump'); - const before=restores;await settle(f,10); - assert.equal(f.runner.faults.size,0); - for(const j of ids)assert.equal(f.journal.get(j.scope,j.requestId)!.state,'complete',j.name); - assert.equal(f.db.events(worldId).filter(e=>e.kind==='birth').length,4); - assert.equal(restores-before,8);assert.ok(Math.max(...perCall)<=1,`a single call ran ${Math.max(...perCall)} probes`); - const births=f.db.events(worldId).filter(e=>e.kind==='birth').map(e=>(e.payload as {soulId:string}).soulId); - assert.deepEqual(births,ids.map(j=>j.scope.soulId)); +test('A13: lifecycle births are the same facts and the same world with the live placement off, on and under the oracle',async()=>{ + const off=await fourBirths('1'),on=await fourBirths(undefined),oracle=await fourBirths('oracle'); + for(const r of [on,oracle]){assert.deepEqual(r.events,off.events);assert.deepEqual(r.poses,off.poses);assert.equal(r.hash,off.hash);assert.equal(r.kernel,off.kernel);} }); diff --git a/apps/server/src/lifecycle-runner.ts b/apps/server/src/lifecycle-runner.ts index 98a3113f5..4243af730 100644 --- a/apps/server/src/lifecycle-runner.ts +++ b/apps/server/src/lifecycle-runner.ts @@ -1,6 +1,6 @@ // Internal opt-in native producer. Production bootstrap/HTTP do not install it. import { TERMINAL } from '@souls/engine-contract'; -import { probeNativeHumanBirth } from '@souls/engine-mars'; +import { nativeBirthPlacement } from '@souls/engine-mars'; import { planNativeBirth } from './arrival-placement.ts'; import { soulLifecycleSchema, ownerLifecycleListSchema, type SoulLifecycle } from '@souls/protocol'; import { LifecycleJournal, type LifecycleOperation, type LifecycleScope } from './lifecycle-journal.ts'; @@ -67,7 +67,9 @@ export class LifecycleRunner { private inflight=new Set(); /** Births queued and not yet settled (lane srv-join-stall). Each birth costs a full detached-world probe when * planned and again under the host writer lock; with every pending birth queued at once, one drainInputs ran - * every guard back to back (4 joins ~ 8 s of one tick on eden2) and /healthz missed its 5 s answer. */ + * every guard back to back (4 joins ~ 8 s of one tick on eden2) and /healthz missed its 5 s answer. A13 (#2621): the + * placement now runs on the live engine (nativeBirthPlacement: spawnHuman's own search, a route plan or two), with no + * snapshot or restore; the one-at-a-time pacing below is kept as it was. */ private births=new Set(); /** A detached probe already ran in this macrotask. pump plans no further birth while it is set; the host's guard itself * always runs. Cleared by whichever of setImmediate / setTimeout(0) fires first: either is a later macrotask, after @@ -165,7 +167,7 @@ export class LifecycleRunner { checks(); this.spendProbe(); const {probe:preview,near}=planNativeBirth(this.host,who); - const probe=()=>{checks();this.spendProbe();return probeNativeHumanBirth(this.host.engine,this.host.factory,{...who,...(near?{near}:{})});}; + const probe=()=>{checks();this.spendProbe();return nativeBirthPlacement(this.host.engine,this.host.factory,{...who,...(near?{near}:{})});}; if(preview.outcome==='deferred')return; if(preview.outcome==='unavailable'&&preview.diagnostic.code==='birth.arrival-unavailable'){ this.journal.refuseArrival(s,op.requestId,()=>{ diff --git a/changes/2621-birth-on-live-engine.md b/changes/2621-birth-on-live-engine.md new file mode 100644 index 000000000..4ccd35b84 --- /dev/null +++ b/changes/2621-birth-on-live-engine.md @@ -0,0 +1,4 @@ +--- +type: perf +--- +A busy world no longer stalls for seconds each time a new Soul arrives, so a burst of joins doesn't restart it. diff --git a/docs/architecture/engine-contract.md b/docs/architecture/engine-contract.md index e37a295c1..be470522f 100644 --- a/docs/architecture/engine-contract.md +++ b/docs/architecture/engine-contract.md @@ -413,6 +413,10 @@ The Mars engine is hard-forked under `mars/viewer/engine`. `load.ts` imports tha strict gate's offer for the act in the same synchronous turn. `SIM_PLAN_ONCE=0` turns both off; `SIM_PLAN_ONCE_ORACLE=1` compares every reuse with a fresh computation and logs `[plan-once-oracle]` on a difference. The viewer's engine does not keep routes. +- **Birth placement (#2621).** A lifecycle birth is placed on the live engine (`nativeBirthPlacement`: `spawnHuman`'s + own search, no snapshot or restore); a world on whole (non-paged) ground keeps the detached probe. `SIM_BIRTH_PROBE=1` + decides by the probe again (the rollback); `SIM_BIRTH_PROBE=oracle` checks every placement against it and throws on a + difference. - **Broadcast.** Moving bodies send two-point keyframe paths every 5 ticks; activity and seat changes are field changes. - **Snapshot** format `sim-mars-snapshot/1`: Mars's own snapshot plus the adapter's programs and world configuration. A program whose actions cannot be serialized defers the checkpoint; replay of the logged suffix continues it. diff --git a/packages/engine-mars/src/birth.test.ts b/packages/engine-mars/src/birth.test.ts index fe9f448ac..4f3d92a11 100644 --- a/packages/engine-mars/src/birth.test.ts +++ b/packages/engine-mars/src/birth.test.ts @@ -1,7 +1,10 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { marsFactory, GREEN_FIELD_WORLD } from './engine.ts'; -import { probeNativeHumanBirth } from './birth.ts'; +import { marsFactory, GREEN_FIELD_WORLD, EDEN_COMMONS_WORLD, EDEN_SAFE_COMMONS_WORLD } from './engine.ts'; +import { probeNativeHumanBirth, placeNativeHumanBirth, nativeBirthPlacement } from './birth.ts'; +import { groundFact } from './ground-bridge.ts'; +import { loadMars } from './load.ts'; +import { emptyGround } from '../../ground/src/index.ts'; import type { Engine } from '@souls/engine-contract'; const factory=await marsFactory(GREEN_FIELD_WORLD); const request={id:'h_new',label:'New',soul:'s_new'}; @@ -64,3 +67,86 @@ test('checkpoint corruption and unexpected native faults propagate instead of be const original=e.snapshot.bind(e);e.snapshot=()=>{throw new Error('isolated unexpected codec invariant');}; assert.throws(()=>probeNativeHumanBirth(e,factory,request),/unexpected codec invariant/);assert.deepEqual(saved(e),before);e.snapshot=original; }); + +// A13 (#2621): the birth path places on the live engine (placeNativeHumanBirth); the detached probe is its oracle. +type Request={id:string;label:string;soul:string;near?:{at:[number,number];first?:boolean}}; +/** The navigation's epoch and ground windows: derived state the state hash cannot see (#2624 review). */ +const navOf=(e:Engine)=>{const sp=(e as unknown as {rt:{services:{spatial:{epoch:unknown;ground?:{window?:unknown;windows?:unknown}}}}}).rt.services.spatial; + return JSON.stringify({epoch:sp.epoch,window:sp.ground?.window??null});}; +/** The live placement equals the probe's outcome (placement or refusal, same diagnostic), neither changes the world, and + * the live placement leaves the navigation as it found it once synced (the probe's own snapshot syncs the live scene to + * the world, as any step does; a fresh world's first sync moves the epoch 0 -> 1). */ +function agrees(e:Engine,f:typeof factory,raw:Request){ + const hash=e.stateHash(),tick=e.world.tick; + const {contract:_c,base:_b,...probe}=probeNativeHumanBirth(e,f,raw),nav=navOf(e); + const placed=placeNativeHumanBirth(e,raw); + assert.deepEqual(placed,probe,JSON.stringify(raw));assert.equal(e.stateHash(),hash);assert.equal(e.world.tick,tick);assert.equal(navOf(e),nav,'navigation moved'); + return placed; +} +test('A13 oracle: the live placement equals the detached probe on every birth while a crowd fills the arrival point',async t=>{ + for(const [name,cfg] of [['green field',GREEN_FIELD_WORLD],['commons',EDEN_COMMONS_WORLD],['safe commons',EDEN_SAFE_COMMONS_WORLD]] as const){ + const f=await marsFactory(cfg),e=f.create(f.genesis('oracle-'+name));let ready=0,refused=0,hinted=0; + for(let i=0;i<110&&refused<4;i++){ + const req={id:'h_'+i,label:'Resident '+i,soul:'s_'+i},p=agrees(e,f,req); + if(p.outcome==='ready'){e.spawnHuman(req);assert.deepEqual(e.world.entities[req.id].pose.p,p.position);ready++;} + else{ + refused++; + // the hinted forms the server sends once the rings are full: the arrival point itself, and a searched start + for(const near of [{at:[cfg.arrival[0],cfg.arrival[1]] as [number,number]},{at:[cfg.arrival[0]+6,cfg.arrival[1]-4] as [number,number],first:true}]){ + const q={...req,near},h=agrees(e,f,q); + if(h.outcome==='ready'&&!e.world.entities[req.id]){e.spawnHuman(q);assert.deepEqual(e.world.entities[req.id].pose.p,h.position);hinted++;} + } + } + // two bodies keep walking between births: the live engine is mid-action, as a served world is + if(i===4)for(const a of ['h_0','h_1'])assert.equal(e.perform({actor:a,label:'walk',steps:[{verb:'walk_to',params:{to:[cfg.arrival[0]+10,0,cfg.arrival[1]+6]}}]}).ok,true); + for(let t=0;t<3;t++)e.step(); + } + t.diagnostic(`${name}: ${ready} ready, ${refused} refused, ${hinted} hinted`);assert.ok(ready>=10&&refused>=1&&hinted>=1,name); + } +}); + +test('A13 oracle: existing, conflicting and deferred births answer as the probe does',async()=>{ + const e=factory.create(factory.genesis('oracle-identity'));e.spawnHuman(request); + assert.equal(agrees(e,factory,request).outcome,'existing'); + assert.equal(agrees(e,factory,{...request,soul:'s_else'}).outcome,'unavailable'); + const f=await marsFactory({scene:'eden-camp',arrival:[16,-10],arrivalPlace:'bunkhouse',reference:[16,-9],grounds:{id:'grounds',name:'grounds'}}); + const s=f.create(f.genesis('oracle-sleeping'));s.spawnHuman({id:'h_A',label:'Alice',soul:'s_A'}); + assert.equal(s.perform({actor:'h_A',label:'sleep',steps:[{verb:'mars:sleep',params:{mat:'mat-1',duration:600}}]}).ok,true); + for(let i=0;i<1800&&s.world.entities.h_A.human!.activity!=='sleep';i++)s.step(); + assert.equal(agrees(s,f,request).outcome,'deferred'); +}); + +test('A13: the birth path never snapshots or restores; SIM_BIRTH_PROBE=1 decides by the probe, =oracle throws on a difference',()=>{ + const was=process.env.SIM_BIRTH_PROBE;let restores=0,snapshots=0; + const counted={...factory,restore:(s:Parameters[0])=>{restores++;return factory.restore(s);}}; + const e=factory.create(factory.genesis('oracle-modes'));e.spawnHuman({id:'h_A',label:'Alice',soul:'s_A'}); + const snap=e.snapshot.bind(e);e.snapshot=()=>{snapshots++;return snap();}; + const m=e as unknown as {birthPlacementV1:(r:unknown)=>unknown},own=m.birthPlacementV1; + try{ + delete process.env.SIM_BIRTH_PROBE;const p=nativeBirthPlacement(e,counted,request);assert.equal(p.outcome,'ready');assert.equal(restores+snapshots,0); + process.env.SIM_BIRTH_PROBE='1';assert.deepEqual(nativeBirthPlacement(e,counted,request),p);assert.equal(restores,1); + process.env.SIM_BIRTH_PROBE='oracle';assert.deepEqual(nativeBirthPlacement(e,counted,request),p);assert.equal(restores,2); + m.birthPlacementV1=()=>({ok:true,p:[9,0,9]});assert.throws(()=>nativeBirthPlacement(e,counted,request),/differs from the detached probe/); + }finally{if(was===undefined)delete process.env.SIM_BIRTH_PROBE;else process.env.SIM_BIRTH_PROBE=was;e.snapshot=snap;m.birthPlacementV1=own;} +}); + +// #2624 review: on whole (non-paged) ground the live search grew the ground window to an arrival point far from every +// body and moved the epoch, so a later far walk was refused live (ground.too-far) and admitted on replay. Such a world +// keeps the probe, and its navigation and later walks are those of a world that never placed a birth. +test('A13: on whole (non-paged) ground the birth decides by the probe and leaves the navigation as it was',async()=>{ + const m=await loadMars(),f=await marsFactory({...GREEN_FIELD_WORLD,arrival:[300,0],reference:[302,0]}),fact=groundFact(emptyGround(1000),4,{paged:false}); + const mk=()=>{const w=f.genesis('a13-whole') as {entities:Record};w.entities.h_home=m.human('h_home',0,0,{label:'Home'}); + const e=f.create(w as never) as Engine&{installGroundV1(f:unknown):unknown};e.installGroundV1(fact);for(let t=0;t<3;t++)e.step();return e;}; + const a=mk(),b=mk(),nav=navOf(a),was=process.env.SIM_BIRTH_PROBE; + try{ + for(const mode of [undefined,'oracle']){ + if(mode===undefined)delete process.env.SIM_BIRTH_PROBE;else process.env.SIM_BIRTH_PROBE=mode; + const {contract:_c,base:_b,...probe}=probeNativeHumanBirth(a,f,request);assert.deepEqual(nativeBirthPlacement(a,f,request),probe); + } + }finally{if(was===undefined)delete process.env.SIM_BIRTH_PROBE;else process.env.SIM_BIRTH_PROBE=was;} + assert.throws(()=>placeNativeHumanBirth(a,request),/needs paged ground or none/); + assert.equal(navOf(a),nav);assert.equal(navOf(a),navOf(b)); + for(const e of [a,b])assert.equal(e.perform({actor:'h_home',label:'walk',steps:[{verb:'walk_to',params:{to:[-100,0,0]}}]}).ok,true); + for(let t=0;t<20;t++){a.step();b.step();} + assert.equal(a.stateHash(),b.stateHash()); +}); diff --git a/packages/engine-mars/src/birth.ts b/packages/engine-mars/src/birth.ts index a20e284e1..5210ee520 100644 --- a/packages/engine-mars/src/birth.ts +++ b/packages/engine-mars/src/birth.ts @@ -1,5 +1,5 @@ import type { MarsEngine } from './engine.ts'; -import { humanBirthRequestSchema, type Engine, type EngineFactory, type HumanBirthProbe } from '@souls/engine-contract'; +import { humanBirthRequestSchema, type Engine, type EngineFactory, type HumanBirthProbe, type HumanBirthRequest, type Vec3 } from '@souls/engine-contract'; /** Run the existing native placer in an exact detached checkpoint. This never * accepts a birth, advances live time, reserves capacity or repairs old logs. @@ -39,3 +39,51 @@ export function probeNativeHumanBirth(engine:Engine,factory:EngineFactory,raw:un if(engine.stateHash()!==base.stateHash||engine.world.tick!==base.tick)throw new Error('Native birth probe changed the authoritative world'); } } + +/** A13 (#2621): a native birth's outcome read on the live engine. The same answer as probeNativeHumanBirth (placement or + * refusal, for the same reasons), without its full-world snapshot and restore: placement is spawnHuman's own search + * (MarsEngine.birthPlacementV1), so the lifecycle guard that runs it in drainInputs, just before the birth applies with + * no engine change between, answers for the very state the birth lands in. */ +export type NativeBirthPlacement = {request:HumanBirthRequest} & ( + | {outcome:'ready'|'existing';position:Vec3} + | {outcome:'deferred'|'unavailable';diagnostic:{code:string;message:string}} +); +export function placeNativeHumanBirth(engine:Engine,raw:unknown):NativeBirthPlacement { + const request=humanBirthRequestSchema.parse(raw); + if(!engine.rulesVersion.startsWith('sim-mars/1+'))throw new Error('Native birth placement requires a native engine'); + const existing=engine.world.entities[request.id]; + if(existing){ + if(existing.kind==='human'&&existing.human?.soul===request.soul&&existing.label===request.label) + return {request,outcome:'existing',position:[...existing.pose.p]}; + return {request,outcome:'unavailable',diagnostic:{code:'birth.identity-conflict',message:'The entity id already belongs to a different body identity.'}}; + } + // As the probe: a birth waits out native activity that has no exact resumable checkpoint (no rule change here). + if(!engine.canSnapshot?.())return {request,outcome:'deferred',diagnostic:{code:'birth.checkpoint-required',message:'Current native activity has no exact resumable checkpoint.'}}; + if(!livePlacementExact(engine))throw new Error('Live birth placement needs paged ground or none: whole ground grows its window to the search'); + const r=(engine as unknown as MarsEngine).birthPlacementV1(request); + return r.ok?{request,outcome:'ready',position:[...r.p]}:{request,outcome:'unavailable',diagnostic:{code:r.diagnostic.code,message:r.diagnostic.message}}; +} + +/** The live search leaves the navigation as it found it (its epoch, its ground window) only on a world with no ground or + * with paged ground (#2624 review): whole (non-paged) ground grows its one window to cover the trial body, moving the + * epoch, and a later walk could then be planned differently live than on replay. Those worlds keep the probe. */ +export function livePlacementExact(engine:Engine):boolean { + const ground=(engine.world as {groundV1?:{nav?:string}}).groundV1;return !ground||ground.nav==='paged/1'; +} + +/** The birth path's one entry. SIM_BIRTH_PROBE=1 decides by the detached probe instead (the A/B "off" arm); + * SIM_BIRTH_PROBE=oracle decides on the live engine and throws on any difference from the probe. Read per call. + * A world on whole (non-paged) ground always decides by the probe (livePlacementExact). */ +export function nativeBirthPlacement(engine:Engine,factory:EngineFactory,raw:unknown):NativeBirthPlacement { + const mode=process.env.SIM_BIRTH_PROBE; + if(mode==='1'||!livePlacementExact(engine))return withoutBase(probeNativeHumanBirth(engine,factory,raw)); + const live=placeNativeHumanBirth(engine,raw); + if(mode==='oracle'){ + const probe=withoutBase(probeNativeHumanBirth(engine,factory,raw)); + if(JSON.stringify(probe)!==JSON.stringify(live))throw new Error(`native birth placement differs from the detached probe: ${JSON.stringify(live)} vs ${JSON.stringify(probe)}`); + } + return live; +} +function withoutBase(p:HumanBirthProbe):NativeBirthPlacement { + const {contract:_contract,base:_base,...rest}=p;return rest; +} diff --git a/packages/engine-mars/src/engine.ts b/packages/engine-mars/src/engine.ts index 4c35ce5b6..42760e59e 100644 --- a/packages/engine-mars/src/engine.ts +++ b/packages/engine-mars/src/engine.ts @@ -2244,6 +2244,35 @@ export class MarsEngine implements Engine { } spawnHuman({ id, label, soul, near }: { id: string; label: string; soul: string; near?: BirthNearV1 }): string { if (this.ents[id]) return id; + const { spot, body } = this.birthSpotV1(id, label, near); + if (!spot) throw new Error('no free standing room at the arrival point'); + const e = this.m.human(id, spot[0], spot[1], { label, provenance: { origin: 'simulation', confidence: 'hypothetical' } }); + if(this.rt.world.groundV1){const g=(this.rt.services.spatial as Spatial).ground!;e.pose.p[1]=standOn(g,spot[0],spot[1]);} + e.human.soul = soul; if(body)e.body=body; + this.ents[id] = e; this.m.canonicalEntityOrder(this.rt.world); + this.out.changes.push([this.rt.tick, id, 'present', e]); + return id; + } + /** A13 (#2621): where spawnHuman would stand a new body now, and the verdict the detached birth probe gives there + * (humanBirthIssue), without creating it: the search the apply runs, on the live engine. It puts a trial body on each + * ring spot it plans from, removed before the next (a new id, so the table's order is unchanged), and syncs the + * navigation to it. With no ground or paged ground that sync leaves the epoch and the windows as they were; whole + * (non-paged) ground grows its one window and moves the epoch, so the caller (livePlacementExact in birth.ts) keeps the + * probe there. Replaces a full-world snapshot and restore per birth (probeNativeHumanBirth, kept as the test oracle). */ + birthPlacementV1({ id, label, near }: { id: string; label: string; near?: BirthNearV1 }): { ok: true; p: [number, number, number] } | { ok: false; diagnostic: Diag } { + if (this.ents[id]) throw new Error('birth placement is for a new body'); + const { spot, body } = this.birthSpotV1(id, label, near); + if (!spot) return { ok: false, diagnostic: { code: 'birth.arrival-unavailable', message: 'no free standing room at the arrival point' } }; + const spatial = this.rt.services.spatial as Spatial; + const p: [number, number, number] = [spot[0], this.rt.world.groundV1 ? standOn(spatial.ground!, spot[0], spot[1]) : 0, spot[1]]; + // humanBirthIssue, for the body spawnHuman would make (level 0, its body's radius) + spatial.sync(this.rt.world); + const grid = spatial.levelAt(0, [p[0], p[2]]), radius = body?.family === 'floater' ? body.radius : HUMAN_RADIUS; + if (!grid || clearanceAt(grid, [p[0], p[2]]) < radius) return { ok: false, diagnostic: { code: 'birth.arrival-unavailable', message: 'No safe standing room at the arrival point.' } }; + return { ok: true, p }; + } + /** spawnHuman's placement search, changing nothing (see birthPlacementV1). */ + private birthSpotV1(id: string, label: string, near?: BirthNearV1): { spot: [number, number] | null; body?: { family: string; model: string; radius: number; hoverHeight: number } } { const [ax, az] = this.rt.world.groundV1 ? groundArrival(this.rt, this.cfg.arrival) : this.cfg.arrival; const body=this.cfg.scene==='littlemartians'&&['Verdelis','Kalama','Kweku','Mycos','Ada','Shuijing','Nyx'].includes(label)?{family:'floater',model:label.toLowerCase(),radius:.35,hoverHeight:1.45}:undefined; const people = listEntities(this.ents).filter((e: any) => e.kind === 'human').map((e: any) => [e.pose.p[0], e.pose.p[2]] as [number, number]); @@ -2272,13 +2301,7 @@ export class MarsEngine implements Engine { // birth-near/1: a built-over arrival no longer refuses the birth: the nearest clear standing ground to the // arrival point, else to the hinted start. Events without `near` keep the original refusal. if (!spot && near) spot = this.freeStandingNearV1([ax, az], body?.radius ?? HUMAN_RADIUS) ?? (near.first ? null : this.freeStandingNearV1(near.at, body?.radius ?? HUMAN_RADIUS)); - if (!spot) throw new Error('no free standing room at the arrival point'); - const e = this.m.human(id, spot[0], spot[1], { label, provenance: { origin: 'simulation', confidence: 'hypothetical' } }); - if(this.rt.world.groundV1){const g=(this.rt.services.spatial as Spatial).ground!;e.pose.p[1]=standOn(g,spot[0],spot[1]);} - e.human.soul = soul; if(body)e.body=body; - this.ents[id] = e; this.m.canonicalEntityOrder(this.rt.world); - this.out.changes.push([this.rt.tick, id, 'present', e]); - return id; + return { spot, body }; } /** arrival-search/1 (lane ARR): the standing geometry a new body of `label` reads (see arrival-search.ts). Read-only. */ private arrivalGroundV1(label?: string): { g: ArrivalGround; at: [number, number] } {