Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions apps/server/src/arrival-placement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand All @@ -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
Expand Down
54 changes: 54 additions & 0 deletions apps/server/src/birth-placement-eden.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, number> = {};
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, []);
});
55 changes: 32 additions & 23 deletions apps/server/src/lifecycle-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(mode:string|undefined,run:()=>Promise<T>)=>{
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<typeof restore>[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<typeof restore>[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);}
});
8 changes: 5 additions & 3 deletions apps/server/src/lifecycle-runner.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -67,7 +67,9 @@ export class LifecycleRunner {
private inflight=new Set<string>();
/** 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<string>();
/** 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
Expand Down Expand Up @@ -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,()=>{
Expand Down
4 changes: 4 additions & 0 deletions changes/2621-birth-on-live-engine.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions docs/architecture/engine-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading