A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(aot): the handshake becomes two numbers, each with a fix attached
yhh110913f94768
diff --git a/compiler/src/abi.ts b/compiler/src/abi.tsindex 0735360a6..6553ae720 100644--- a/compiler/src/abi.ts+++ b/compiler/src/abi.ts@@ -18,23 +18,23 @@* Field offsets come from PTR_LAYOUTS via builtins.ts — the same EHT* table the engine and the SDK's accessors already agree on.*/-import { ehtStamp, resourceNames } from './builtins';+import {+ CMD_WORDS as CMD_WORDS_, CMD_DESPAWN as CMD_DESPAWN_, CMD_REMOVE as CMD_REMOVE_,+ QUERYROWS_WORDS as QUERYROWS_WORDS_, SYSCTX_WORDS as SYSCTX_WORDS_,+ engineAbiDigest, projectShapeDigest, type ShapeDigestInput,+} from '../../sdk/src/ecs/aot/abiDigest';+import { resourceNames } from './builtins';import { encBytes, type CompShape, type EirSystem, type EirType, type LeafEnc, type QueryArg } from './eir';import { runSystemOn, type EirHost, type Fns } from './interp';-/** One command record: 16 bytes, four u32 (docs/REARCH_AOT_ABI.md §2.3). */-export const CMD_WORDS = 4;-export const CMD_DESPAWN = 1;-export const CMD_REMOVE = 2;-/**- * Words in `SysCtx` and in `QueryRows` (docs/REARCH_AOT_ABI.md §2.1, §2.2).- * Exported because three things count them — this host, the code generator and- * the handshake hash — and a field count with three authors is the drift this- * file prevents. §6.3 makes the first a number that needs a reason to grow.+ * The struct sizes and command kinds, from the SDK's `abiDigest.ts` — the one+ * author both sides read, so a field count cannot have two answers. Re-exported+ * because the code generator and this host both name them.*/-export const SYSCTX_WORDS = 6;-export const QUERYROWS_WORDS = 2;+export {+ CMD_WORDS, CMD_DESPAWN, CMD_REMOVE, SYSCTX_WORDS, QUERYROWS_WORDS,+} from '../../sdk/src/ecs/aot/abiDigest';/*** Where a field lives and HOW it is encoded, both from the shape, which got them@@ -88,7 +88,7 @@ export class AbiMemory {this.u32 = new Uint32Array(this.buffer);this.u8 = new Uint8Array(this.buffer);this.scratchNext = bytes;- this.cmdBuf = this.alloc(this.cmdCap * CMD_WORDS * 4);+ this.cmdBuf = this.alloc(this.cmdCap * CMD_WORDS_ * 4);}private alloc(size: number): number {@@ -245,7 +245,7 @@ export interface AbiCall {*/export function materialize(mem: AbiMemory, plan: SysPlan): AbiCall {mem.beginCall();- const queryTable = mem.scratch(Math.max(1, plan.queries.length) * QUERYROWS_WORDS * 4);+ const queryTable = mem.scratch(Math.max(1, plan.queries.length) * QUERYROWS_WORDS_ * 4);plan.queries.forEach((args, k) => {const stride = 1 + args.length;const matched: number[] = [];@@ -256,8 +256,8 @@ export function materialize(mem: AbiMemory, plan: SysPlan): AbiCall {}const rows = mem.scratch(Math.max(4, matched.length * 4));for (let i = 0; i < matched.length; i++) mem.u32[(rows >> 2) + i] = matched[i]!;- mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS] = rows;- mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS + 1] = matched.length / stride;+ mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS_] = rows;+ mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS_ + 1] = matched.length / stride;});const resTable = mem.scratch(Math.max(4, plan.resources.length * 4));@@ -266,7 +266,7 @@ export function materialize(mem: AbiMemory, plan: SysPlan): AbiCall {const cmdCount = mem.scratch(4);mem.u32[cmdCount >> 2] = 0;- const ctx = mem.scratch(SYSCTX_WORDS * 4);+ const ctx = mem.scratch(SYSCTX_WORDS_ * 4);const w = ctx >> 2;mem.u32[w] = queryTable;mem.u32[w + 1] = resTable;@@ -299,8 +299,8 @@ export function abiHost(mem: AbiMemory, layout: AbiLayout, plan: SysPlan, call:*rows(args: readonly QueryArg[]) {const k = plan.queries.indexOf(args);if (k < 0) throw new Error(`ABI: '${plan.system}' walks a query it did not declare`);- const rows = mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS]!;- const count = mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS + 1]!;+ const rows = mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS_]!;+ const count = mem.u32[(queryTable >> 2) + k * QUERYROWS_WORDS_ + 1]!;const stride = 1 + args.length;for (let i = 0; i < count; i++) {const at = (rows >> 2) + i * stride;@@ -323,8 +323,8 @@ export function abiHost(mem: AbiMemory, layout: AbiLayout, plan: SysPlan, call:emit(record, args) {const n = mem.u32[call.cmdCount >> 2]!;if (n >= cmdCap) throw new Error('ABI: command buffer overflow');- const at = (cmdBuf >> 2) + n * CMD_WORDS;- mem.u32[at] = record === 'despawn' ? CMD_DESPAWN : CMD_REMOVE;+ const at = (cmdBuf >> 2) + n * CMD_WORDS_;+ mem.u32[at] = record === 'despawn' ? CMD_DESPAWN_ : CMD_REMOVE_;mem.u32[at + 1] = args[0] as number;mem.u32[at + 2] = 0;mem.u32[at + 3] = 0;@@ -345,8 +345,8 @@ export function flushCommands(mem: AbiMemory, call: AbiCall): void {const n = mem.u32[call.cmdCount >> 2]!;const at = mem.cmdBuf >> 2;for (let i = 0; i < n; i++) {- const kind = mem.u32[at + i * CMD_WORDS]!;- if (kind === CMD_DESPAWN) mem.despawn(mem.u32[at + i * CMD_WORDS + 1]!);+ const kind = mem.u32[at + i * CMD_WORDS_]!;+ if (kind === CMD_DESPAWN_) mem.despawn(mem.u32[at + i * CMD_WORDS_ + 1]!);}mem.u32[call.cmdCount >> 2] = 0;}@@ -363,33 +363,37 @@ export function runOnAbi(sys: EirSystem, mem: AbiMemory, layout: AbiLayout, fns:}/**- * The §2.5 handshake: EHT's offsets, the shape of the three structs, and every- * system's parameter order, in one number the loader compares before it maps- * anything. A mismatch is a read of a DIFFERENT FIELD, not a wrong answer, so it- * is refused. FNV-1a, as `mkbc` and the asset hashes use; not a new mechanism.+ * The §2.5 handshake, as TWO numbers because the fixes differ: `engineAbi` means+ * rebuild the module against this engine, `projectShapes` means rebuild the+ * project. Parameter order is in neither — the manifest DRIVES the layout at run+ * time, so it is followed rather than compared.*/-export function abiHash(layout: AbiLayout, plans: readonly SysPlan[]): string {- const parts: string[] = [- `eht=${ehtStamp()}`,- `sysctx=${SYSCTX_WORDS} queryrows=${QUERYROWS_WORDS} cmd=${CMD_WORDS}`,- ];- const table = (kind: string, m: ReadonlyMap<string, FieldOffsets>): void => {- for (const [name, f] of m) {- const leaves = [...f.leaves].map(([p, l]) => `${p}@${l.byteOffset}:${l.enc}`).join(',');- parts.push(`${kind} ${name} stride=${f.stride} ${leaves}`);- }- };- table('comp', layout.comps);- table('res', layout.resources);- for (const p of plans) {- const qs = p.queries.map((q) => q.map((a) => (a.mut ? `mut ${a.comp}` : a.comp)).join('+')).join('|');- // The ORDER parameters were declared in, not just what they were: two- // systems taking a Query and a Res differ only here, and a loader that- // could not tell them apart would read the row array as the resource.- const order = [...p.slots.values()].map((s) => `${s.table}${s.slot}`).join(',');- parts.push(`sys ${p.system} order=${order} q=${qs} r=${p.resources.join('|')} c=${p.channels.join('|')}`);+export interface AbiHandshake {+ readonly engineAbi: string;+ readonly projectShapes: string;+}++export function abiHandshake(+ comps: ReadonlyMap<string, CompShape>,+ plans: readonly SysPlan[],+ addressBytes: 4 | 8 = 4,+): AbiHandshake {+ // Scoped to the components the compiled systems NAME: adding an unrelated+ // component to a project must not invalidate a module that never reads it.+ const named = new Set<string>();+ for (const p of plans) for (const q of p.queries) for (const a of q) named.add(a.comp);++ const shapes: ShapeDigestInput[] = [];+ for (const name of named) {+ const shape = comps.get(name);+ // Engine components are covered by `engineAbi`, from EHT's own table.+ if (!shape || shape.storage !== 'host') continue;+ shapes.push({ name, fields: [...shape.fields.keys()] });}- return fnv1a64(parts.join('\n'));+ return {+ engineAbi: engineAbiDigest(addressBytes),+ projectShapes: projectShapeDigest(shapes),+ };}/**@@ -404,16 +408,6 @@ export function abiHashFor(contract: string, addrBytes: 4 | 8): string {return mixed.toString(16).padStart(16, '0');}-function fnv1a64(text: string): string {- const MASK = (1n << 64n) - 1n;- let h = 0xcbf29ce484222325n;- for (let i = 0; i < text.length; i++) {- h = (h ^ BigInt(text.charCodeAt(i) & 0xff)) & MASK;- h = (h * 0x100000001b3n) & MASK;- }- return h.toString(16).padStart(16, '0');-}-/*** Byte offsets for every shape: leaves in declaration order, at the width the* SHAPE declares. Nothing here asks what a name means — `engine` shapes are thediff --git a/compiler/src/codegen.ts b/compiler/src/codegen.tsindex 46e995fdb..b030dd498 100644--- a/compiler/src/codegen.ts+++ b/compiler/src/codegen.ts@@ -29,7 +29,7 @@*/import {CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS, CMD_DESPAWN, CMD_REMOVE,- abiHash, planFor,+ abiHandshake, planFor,type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,} from './abi';import {@@ -64,8 +64,11 @@ export interface CModule {readonly source: string;/** Exported symbols, one per compiled system. */readonly symbols: readonly string[];- /** The §2.5 handshake constant, also emitted into the source. */- readonly hash: string;+ /**+ * The §2.5 handshake: what this module baked in about the ENGINE and about+ * the PROJECT, each so a loader can say which one moved.+ */+ readonly handshake: { readonly engineAbi: string; readonly projectShapes: string };}// =============================================================================@@ -674,7 +677,7 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei});const manifest = emitManifest(systems, plans);- const hash = abiHash(layout, plans);+ const handshake = abiHandshake(module.comps, plans);const macros = [...offsets].sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => `#define ${k} ${v}u`);const offsetsHeader = ['/* GENERATED by @estella/compiler — do not edit. */',@@ -695,14 +698,14 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei'#include "estella_abi.h"','#include "estella_offsets.h"','',- '/* §2.5: the loader compares this before it maps anything. A mismatch is',- ' not a wrong answer, it is a read of a different field.',- ' The address width belongs to the MACHINE, not to the contract, so it',- ' mixes in here rather than in the compiler: one hash per (contract,',- ' width) pair, and a 32-bit artifact cannot load into a 64-bit host. */',- `#define ES_ABI_CONTRACT_HASH 0x${hash}ULL`,+ '/* §2.5: what this module baked in about the engine it was built for. A',+ ' host compares before it maps anything — a mismatch is not a wrong',+ ' answer, it is a read of a different field. The address width belongs',+ ' to the MACHINE, so it mixes in here rather than in the compiler and a',+ ' 32-bit artifact cannot load into a 64-bit host. */',+ `#define ES_ABI_ENGINE_DIGEST 0x${handshake.engineAbi}ULL`,'const uint64_t es_abi_hash =',- ` ES_ABI_CONTRACT_HASH ^ (${ADDR_MIX}ULL * (uint64_t)sizeof(es_addr_t));`,+ ` ES_ABI_ENGINE_DIGEST ^ (${ADDR_MIX}ULL * (uint64_t)sizeof(es_addr_t));`,'',...bodies,...manifest,@@ -713,7 +716,7 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Eioffsets: offsetsHeader,source,symbols: systems.map((s) => cSymbol(s.name)),- hash,+ handshake,};}diff --git a/compiler/src/index.ts b/compiler/src/index.tsindex b9c0ce8f0..3ca2bcc73 100644--- a/compiler/src/index.ts+++ b/compiler/src/index.ts@@ -10,9 +10,10 @@ export { verifySystem, type VerifyError } from './verify';export { runSystem, type EirWorld, type Fns, type Row } from './interp';export { inlineModule, inlineSystem } from './inline';export {- AbiMemory, abiHash, abiHashFor, abiHost, flushCommands, materialize, packLayout, planFor, runOnAbi,+ AbiMemory, abiHandshake, abiHashFor, abiHost, flushCommands, materialize, packLayout, planFor,+ runOnAbi,CMD_DESPAWN, CMD_REMOVE, CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS,- type AbiCall, type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,+ type AbiCall, type AbiHandshake, type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,} from './abi';export { ADDR_MIX, CFLAGS, RUNTIME_H, cSymbol, emitC, type CModule } from './codegen';export { builtinShapes } from './builtins';diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.tsindex 69709bbdf..b2a567912 100644--- a/compiler/tests/codegen.test.ts+++ b/compiler/tests/codegen.test.ts@@ -42,7 +42,7 @@ import { AbiMemory, flushCommands, materialize, packLayout, planFor, runOnAbi }import { CFLAGS, cSymbol, emitC, type CModule } from '../src/codegen';import { abiHashFor } from '../src/abi';import type { AbiLayout } from '../src/abi';-import type { EirSystem } from '../src/eir';+import { F64, type EirSystem } from '../src/eir';import type { Row } from '../src/interp';import { moveSystem } from '../../examples/ecs-basics/src/systems/move';@@ -504,16 +504,46 @@ describe('the emitted C says what the interpreter says', () => {expect(undef, 'a compiled system may not call the engine').toEqual([]);});- it('the handshake constant moves when the parameter order does', () => {+ it('the artifact carries what it baked in about the engine', () => {+ const layout = packLayout(shipped.module.comps);+ const c = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);+ expect(c.source).toContain(`#define ES_ABI_ENGINE_DIGEST 0x${c.handshake.engineAbi}ULL`);+ expect(c.handshake.engineAbi).toMatch(/^[0-9a-f]{16}$/);+ expect(c.handshake.projectShapes).toMatch(/^[0-9a-f]{16}$/);+ });++ it('the project digest follows the shapes the systems NAME, and only those', () => {const layout = packLayout(shipped.module.comps);const move = systemOf(shipped, 'MoveSystem');- const a = emitC(shipped.module, layout, [move]);- expect(a.source).toContain(`#define ES_ABI_CONTRACT_HASH 0x${a.hash}ULL`);+ const before = emitC(shipped.module, layout, [move]).handshake;++ // A component nobody compiled against must not invalidate the module.+ const extra = new Map(shipped.module.comps);+ extra.set('Unrelated', {+ name: 'Unrelated', storage: 'host',+ fields: new Map([['x', { type: F64, enc: 'f64', offset: null } as const]]),+ });+ const widened = emitC({ ...shipped.module, comps: extra }, packLayout(extra), [move]);+ expect(widened.handshake.projectShapes).toBe(before.projectShapes);++ // A component it DOES name, with a field added, must.+ const changed = new Map(shipped.module.comps);+ const mover = changed.get('Mover')!;+ changed.set('Mover', {+ ...mover,+ fields: new Map([...mover.fields, ['drag', { type: F64, enc: 'f64', offset: null } as const]]),+ });+ const moved = emitC({ ...shipped.module, comps: changed }, packLayout(changed), [move]);+ expect(moved.handshake.projectShapes).not.toBe(before.projectShapes);+ });- // The same system with its parameters swapped reads the ctx tables in- // the other order, so the loader has to refuse it. §2.5.- const swapped: EirSystem = { ...move, params: [...move.params].reverse() };- expect(emitC(shipped.module, layout, [swapped]).hash).not.toBe(a.hash);+ it('parameter order is in the MANIFEST, which is why it is not in a digest', () => {+ // A digest could only say "something moved". The order is what the host+ // follows when it fills the ctx, so it is carried rather than compared.+ const layout = packLayout(shipped.module.comps);+ const { source } = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);+ expect(source).toContain('{ "Transform", "Mover" }');+ expect(source).toContain('{ "Time" }');});it('what the artifact exports is what a host computes, at both widths', () => {@@ -549,7 +579,7 @@ describe('the emitted C says what the interpreter says', () => {const [got, width] = execFileSync(exe, { encoding: 'utf8' }).trim().split(' ');// 8 only where the platform's pointers are; a 32-bit host would say 4// and the assertion below would then be about the width it really has.- expect(abiHashFor(c.hash, Number(width) as 4 | 8)).toBe(got);+ expect(abiHashFor(c.handshake.engineAbi, Number(width) as 4 | 8)).toBe(got);if (flags.length > 0) expect(Number(width)).toBe(bytes);}});diff --git a/compiler/tests/generated.test.ts b/compiler/tests/generated.test.tsindex 918054706..e4759f6b6 100644--- a/compiler/tests/generated.test.ts+++ b/compiler/tests/generated.test.ts@@ -74,7 +74,7 @@ describe('the C artifacts the engine builds against', () => {artifact(join(ROOT, 'tests/aot/generated/move_system_hash.h'), ['/* GENERATED by @estella/compiler — do not edit. */','/* The contract half of the handshake. The width half is the harness. */',- `#define ES_EXPECTED_CONTRACT_HASH 0x${c.hash}ULL`,+ `#define ES_EXPECTED_CONTRACT_HASH 0x${c.handshake.engineAbi}ULL`,'',].join('\n'));});diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.tsindex c4473162c..8e0228d48 100644--- a/pipeline/src/bundle/buildCompiledSystems.ts+++ b/pipeline/src/bundle/buildCompiledSystems.ts@@ -48,8 +48,13 @@ export interface CompiledSystemInfo {}export interface CompiledSystemsManifest {- /** The §2.5 contract hash. The loader refuses a module that disagrees. */- contractHash: string;+ /**+ * What this module baked in, so a loader can say WHICH one moved: the engine+ * it was built against, and the project's own component shapes. The fixes+ * differ — rebuild the module, or rebuild the project — so the numbers do too.+ */+ engineAbi: string;+ projectShapes: string;systems: CompiledSystemInfo[];}@@ -185,7 +190,8 @@ export async function buildCompiledSystems(}const manifest: CompiledSystemsManifest = {- contractHash: c.hash,+ engineAbi: c.handshake.engineAbi,+ projectShapes: c.handshake.projectShapes,systems: inlined.map((sys) => {const plan = planFor(sys);return {diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.tsindex f19927925..6d21a45e4 100644--- a/pipeline/tests/build-compiled-systems.test.ts+++ b/pipeline/tests/build-compiled-systems.test.ts@@ -143,7 +143,8 @@ describe('the AOT build step', () => {queries: [[{ comp: 'Transform', mut: true }, { comp: 'Mover', mut: false }]],resources: ['Time'],}]);- expect(out.manifest!.contractHash).toMatch(/^[0-9a-f]{16}$/);+ expect(out.manifest!.engineAbi).toMatch(/^[0-9a-f]{16}$/);+ expect(out.manifest!.projectShapes).toMatch(/^[0-9a-f]{16}$/);});it.skipIf(!EMCC)('rebuilding is not additive: the cache is what this build made', async () => {diff --git a/sdk/src/ecs/aot/AotContext.ts b/sdk/src/ecs/aot/AotContext.tsindex 1fdc4669c..b7940e121 100644--- a/sdk/src/ecs/aot/AotContext.ts+++ b/sdk/src/ecs/aot/AotContext.ts@@ -19,18 +19,14 @@*/import type { PoolBlock, PoolMemory } from '../ScriptPool';--/**- * Sizes of the three structs, in 32-bit words: wasm32 is the only place this- * host runs, so an address is four bytes. The compiler is the author- * (`compiler/src/abi.ts`) and this is the SDK's copy, because a shipped engine- * may not import a build tool — `pool-layout.test.ts` holds the two together.- */-export const SYSCTX_WORDS = 6;-export const QUERYROWS_WORDS = 2;-export const CMD_WORDS = 4;-export const CMD_DESPAWN = 1;-export const CMD_REMOVE = 2;+import { CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS } from './abiDigest';++// The struct sizes and the command kinds have one author, and it is not this+// file: `abiDigest.ts`, which the compiler reads too. Re-exported so call sites+// name the ABI rather than the digest.+export {+ SYSCTX_WORDS, QUERYROWS_WORDS, CMD_WORDS, CMD_DESPAWN, CMD_REMOVE,+} from './abiDigest';/** One record the compiled code appended (§2.3). */export interface AotCommand {diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.tsindex 836413290..9c1ab7e3a 100644--- a/sdk/src/ecs/aot/AotSystems.ts+++ b/sdk/src/ecs/aot/AotSystems.ts@@ -16,6 +16,7 @@*/import type { AnyComponentDef } from '../component';+import { engineAbiDigest, projectShapeDigest, type ShapeDigestInput } from './abiDigest';/** One system's declaration, as the build wrote it beside the module. */export interface AotSystemDecl {@@ -27,7 +28,11 @@ export interface AotSystemDecl {}export interface AotManifest {- readonly contractHash: string;+ /** The engine the module was built against (EHT offsets, resource shapes,+ * struct sizes, address width). */+ readonly engineAbi: string;+ /** The project's own component shapes, scoped to the ones it names. */+ readonly projectShapes: string;readonly systems: readonly AotSystemDecl[];}@@ -52,23 +57,32 @@ export class AotSystems {}/**- * Take a built module. `expectedHash` is what this SDK's own contract- * computes; a module that disagrees is refused.+ * Take a built module, after checking what it baked in against what is here.** `resolve` turns a component NAME into the definition this world uses,* because the manifest carries names — a build cannot know a runtime's ids.+ * It is also how the project digest is recomputed: the shapes the module+ * named, as this runtime has them now.*/install(manifest: AotManifest,exports: Readonly<Record<string, unknown>>,- expectedHash: string,resolve: (name: string) => AnyComponentDef | undefined,): void {- if (manifest.contractHash !== expectedHash) {+ // Two questions with two fixes, so two answers rather than one that can+ // only say "something moved".+ const engine = engineAbiDigest(4);+ if (manifest.engineAbi !== engine) {throw new Error(- `AOT module refused: contract ${manifest.contractHash} but this engine has `- + `${expectedHash}. The offsets would not line up, and a wrong offset reads a `- + 'different field rather than failing.');+ `AOT module refused: built for engine ${manifest.engineAbi}, this is ${engine}. `+ + 'Rebuild the module against this engine — a wrong offset reads a different '+ + 'field rather than failing.');+ }+ const shapes = projectShapeDigest(scriptShapes(manifest, resolve));+ if (manifest.projectShapes !== shapes) {+ throw new Error(+ `AOT module refused: built for components ${manifest.projectShapes}, this project `+ + `has ${shapes}. Rebuild the project — a component's fields moved under it.`);}for (const decl of manifest.systems) {const call = exports[decl.symbol];@@ -94,3 +108,30 @@ export class AotSystems {this.byName.clear();}}++/**+ * The script-component shapes a manifest names, as this runtime has them. Engine+ * components are covered by the engine digest, from EHT's own table, so they are+ * skipped here rather than counted twice.+ */+function scriptShapes(+ manifest: AotManifest,+ resolve: (name: string) => AnyComponentDef | undefined,+): ShapeDigestInput[] {+ const seen = new Set<string>();+ const out: ShapeDigestInput[] = [];+ for (const decl of manifest.systems) {+ for (const query of decl.queries) {+ for (const arg of query) {+ if (seen.has(arg.comp)) continue;+ seen.add(arg.comp);+ const def = resolve(arg.comp);+ if (!def || def._builtin) continue;+ const shape = (def as { _default?: unknown })._default;+ if (shape === null || typeof shape !== 'object') continue;+ out.push({ name: arg.comp, fields: Object.keys(shape as object) });+ }+ }+ }+ return out;+}diff --git a/sdk/src/ecs/aot/abiDigest.ts b/sdk/src/ecs/aot/abiDigest.tsnew file mode 100644index 000000000..7a336070d--- /dev/null+++ b/sdk/src/ecs/aot/abiDigest.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file abiDigest.ts+ * @brief What a compiled module baked in, as two numbers it can be asked for.+ *+ * @details A compiled system reads memory at offsets fixed when it was built. It+ * reads the WRONG THING — not an error, a different field — if anything+ * those offsets came from has changed since. So a loader compares.+ *+ * Two digests, not one, because the mismatches have different fixes:+ *+ * - `engineAbi` is everything about the ENGINE the module baked in:+ * EHT's struct offsets, the resource shapes, the sizes of the three+ * ABI structs and the width of an address. A mismatch means rebuild+ * the module against this engine.+ * - `projectShapes` is the `defineComponent` shapes it compiled+ * against, scoped to the components it actually names. A mismatch+ * means the project's components changed — rebuild the project.+ *+ * A system's PARAMETER ORDER is deliberately in neither. It cannot+ * drift: the manifest is what drives the layout at run time, so it is+ * the instruction being followed rather than an input to compare.+ *+ * This file is the ONE author, imported by the SDK that checks and by+ * the compiler that writes. It has only leaf imports for that reason —+ * a build tool reads it without pulling in the engine.+ */++import { PTR_LAYOUTS } from '../../wasm/ptrLayouts.generated';+import { RESOURCE_SHAPES } from '../resourceShapes';++/** Sizes of the three ABI structs, in address-wide words (§2.1–2.3). */+export const SYSCTX_WORDS = 6;+export const QUERYROWS_WORDS = 2;+/** A command is four u32 at every address width. */+export const CMD_WORDS = 4;++export const CMD_DESPAWN = 1;+export const CMD_REMOVE = 2;++/** How wide an address is where the module runs: 4 on wasm32, 8 on a 64-bit host. */+export type AddressBytes = 4 | 8;++/** One component's flat shape, in the form both sides can produce. */+export interface ShapeDigestInput {+ readonly name: string;+ /** Field names in DECLARATION order, which is the layout. */+ readonly fields: readonly string[];+}++/**+ * Everything about the engine the module baked in. Recomputable by the SDK from+ * what it ships, which is what makes this the check that can actually run.+ */+export function engineAbiDigest(addressBytes: AddressBytes): string {+ const parts: string[] = [+ `addr=${addressBytes}`,+ `sysctx=${SYSCTX_WORDS} rows=${QUERYROWS_WORDS} cmd=${CMD_WORDS}`,+ `cmdkinds=${CMD_DESPAWN},${CMD_REMOVE}`,+ ];+ // EHT's table: every field of every engine component, at the offset the C+++ // struct puts it. This is the half that changes when the engine is rebuilt.+ for (const [name, layout] of Object.entries(PTR_LAYOUTS)) {+ const fields = layout.fields.map((f) => {+ const members = f.members+ ? `{${f.members.map((m) => `${m.name}:${m.type}@${m.offset}`).join(',')}}`+ : '';+ return `${f.name}:${f.type}@${f.offset}${members}`;+ });+ parts.push(`comp ${name}=${fields.join(',')}`);+ }+ for (const [name, shape] of Object.entries(RESOURCE_SHAPES)) {+ parts.push(`res ${name}=${Object.keys(shape).join(',')}`);+ }+ return fnv1a64(parts.join('\n'));+}++/**+ * The project's own component shapes, scoped to the ones a module names. Scoped+ * on purpose: adding an unrelated component to a project must not invalidate a+ * module that never reads it.+ */+export function projectShapeDigest(shapes: readonly ShapeDigestInput[]): string {+ const sorted = [...shapes].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+ return fnv1a64(sorted.map((s) => `${s.name}=${s.fields.join(',')}`).join('\n'));+}++/** FNV-1a, as `mkbc` and the asset hashes already use; not a new mechanism. */+export function fnv1a64(text: string): string {+ const MASK = (1n << 64n) - 1n;+ let h = 0xcbf29ce484222325n;+ for (let i = 0; i < text.length; i++) {+ h = (h ^ BigInt(text.charCodeAt(i) & 0xff)) & MASK;+ h = (h * 0x100000001b3n) & MASK;+ }+ return h.toString(16).padStart(16, '0');+}diff --git a/sdk/tests/aot-dispatch.test.ts b/sdk/tests/aot-dispatch.test.tsindex 0143183a0..29691d7a0 100644--- a/sdk/tests/aot-dispatch.test.ts+++ b/sdk/tests/aot-dispatch.test.ts@@ -29,12 +29,16 @@ import { AotContext } from '../src/ecs/aot/AotContext';import { AotSystems, type AotManifest } from '../src/ecs/aot/AotSystems';import type { AotAddresses, AotRuntime } from '../src/ecs/aot/AotRuntime';import type { AnyComponentDef } from '../src/ecs/component';+import { engineAbiDigest, projectShapeDigest } from '../src/ecs/aot/abiDigest';import type { Entity } from '../src/types';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');const N = 20;const FRAMES = 10;-const HASH = 'aabbccdd00112233';+/** What a build for THIS engine would have written into the manifest. */+const ENGINE = engineAbiDigest(4);+const DECAY_FIELDS = ['remaining', 'rate'];+const SHAPES = projectShapeDigest([{ name: 'Decay', fields: DECAY_FIELDS }]);function findEmcc(): string | null {const at = path.join(ROOT, 'tools/emsdk/upstream/emscripten',@@ -181,14 +185,15 @@ describe('the scheduler and its compiled twin', () => {(exports['_initialize'] as (() => void) | undefined)?.();const manifest: AotManifest = {- contractHash: HASH,+ engineAbi: ENGINE,+ projectShapes: SHAPES,systems: [{name: 'Decay', symbol: 'es_sys_Decay',queries: [[{ comp: 'Decay', mut: true }]], resources: [],}],};const systems = new AotSystems();- systems.install(manifest, exports, HASH, (name) => (name === 'Decay' ? b.Decay : undefined));+ systems.install(manifest, exports, (name) => (name === 'Decay' ? b.Decay : undefined));const addresses: AotAddresses = {componentNamed: (name) => (name === 'Decay' ? b.Decay : undefined),@@ -234,12 +239,13 @@ describe('the scheduler and its compiled twin', () => {(exports['_initialize'] as (() => void) | undefined)?.();const systems = new AotSystems();systems.install({- contractHash: HASH,+ engineAbi: ENGINE,+ projectShapes: SHAPES,systems: [{name: 'Decay', symbol: 'es_sys_Decay',queries: [[{ comp: 'Decay', mut: true }]], resources: [],}],- }, exports, HASH, (name) => (name === 'Decay' ? w.Decay : undefined));+ }, exports, (name) => (name === 'Decay' ? w.Decay : undefined));w.runner.useAot({systems,addresses: {@@ -266,21 +272,58 @@ describe('the scheduler and its compiled twin', () => {expect(compiled).toEqual(interpreted);});- it('a module whose contract disagrees is refused, not warned about', () => {+ it('a module built for another ENGINE is refused, and says which', () => {const systems = new AotSystems();- const manifest: AotManifest = { contractHash: 'deadbeefdeadbeef', systems: [] };- expect(() => systems.install(manifest, {}, HASH, () => undefined))- .toThrow(/contract deadbeefdeadbeef but this engine has/);+ const manifest: AotManifest = {+ engineAbi: 'deadbeefdeadbeef', projectShapes: SHAPES, systems: [],+ };+ // The message has to name the fix, and the fix for this one is to rebuild+ // the module — not the project.+ expect(() => systems.install(manifest, {}, () => undefined))+ .toThrow(/Rebuild the module against this engine/);expect(systems.size).toBe(0);});+ it('a module built for other COMPONENT SHAPES is refused, and says which', () => {+ const w = makeWorld();+ const systems = new AotSystems();+ const manifest: AotManifest = {+ engineAbi: ENGINE,+ // What a build would have written before someone added a field.+ projectShapes: projectShapeDigest([{ name: 'Decay', fields: ['remaining'] }]),+ systems: [{+ name: 'Decay', symbol: 'es_sys_Decay',+ queries: [[{ comp: 'Decay', mut: true }]], resources: [],+ }],+ };+ expect(() => systems.install(manifest, { es_sys_Decay: () => { /* */ } },+ (name) => (name === 'Decay' ? w.Decay : undefined)))+ .toThrow(/Rebuild the project/);+ });++ it('a component nobody compiled against does not invalidate a module', () => {+ const w = makeWorld();+ // Declared in this project and named by no compiled system: the digest is+ // scoped to what the module reads, so this must not refuse it.+ defineComponent('Unrelated', { whatever: 1 });+ const systems = new AotSystems();+ systems.install({+ engineAbi: ENGINE, projectShapes: SHAPES,+ systems: [{+ name: 'Decay', symbol: 'es_sys_Decay',+ queries: [[{ comp: 'Decay', mut: true }]], resources: [],+ }],+ }, { es_sys_Decay: () => { /* */ } }, (name) => (name === 'Decay' ? w.Decay : undefined));+ expect(systems.size).toBe(1);+ });+it('a manifest naming a symbol the module lacks is refused too', () => {const systems = new AotSystems();const manifest: AotManifest = {- contractHash: HASH,+ engineAbi: ENGINE, projectShapes: projectShapeDigest([]),systems: [{ name: 'Ghost', symbol: 'es_sys_Ghost', queries: [], resources: [] }],};- expect(() => systems.install(manifest, {}, HASH, () => undefined))+ expect(() => systems.install(manifest, {}, () => undefined)).toThrow(/exports no 'es_sys_Ghost'/);});});diff --git a/tests/aot/generated/move_system.c b/tests/aot/generated/move_system.cindex 28a954100..cddff8329 100644--- a/tests/aot/generated/move_system.c+++ b/tests/aot/generated/move_system.c@@ -3,14 +3,14 @@#include "estella_abi.h"#include "estella_offsets.h"-/* §2.5: the loader compares this before it maps anything. A mismatch is- not a wrong answer, it is a read of a different field.- The address width belongs to the MACHINE, not to the contract, so it- mixes in here rather than in the compiler: one hash per (contract,- width) pair, and a 32-bit artifact cannot load into a 64-bit host. */-#define ES_ABI_CONTRACT_HASH 0x52ced52de3f13ce2ULL+/* §2.5: what this module baked in about the engine it was built for. A+ host compares before it maps anything — a mismatch is not a wrong+ answer, it is a read of a different field. The address width belongs+ to the MACHINE, so it mixes in here rather than in the compiler and a+ 32-bit artifact cannot load into a 64-bit host. */+#define ES_ABI_ENGINE_DIGEST 0x36cbaec9128499cdULLconst uint64_t es_abi_hash =- ES_ABI_CONTRACT_HASH ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));+ ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));void es_sys_MoveSystem(es_addr_t es_ctx) {const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.hindex 1cbc4e9ab..6f5a2d0fc 100644--- a/tests/aot/generated/move_system_hash.h+++ b/tests/aot/generated/move_system_hash.h@@ -1,3 +1,3 @@/* GENERATED by @estella/compiler — do not edit. *//* The contract half of the handshake. The width half is the harness. */-#define ES_EXPECTED_CONTRACT_HASH 0x52ced52de3f13ce2ULL+#define ES_EXPECTED_CONTRACT_HASH 0x36cbaec9128499cdULL