@mica-js/simulator 2.5.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { S as snapshot, _ as nextRandom, a as copyBytePayload, b as range, c as samePayload, d as captureValue, f as dataObject, g as integer, h as identity, i as simulationRuntimeTopicService, l as targetKey, m as finite, n as simulationRuntimeEventTransfer, o as copyPayload, p as externalValue, r as simulationRuntimeService, s as payloadMatches, u as bytesView, v as nonnegative, x as same, y as randomState } from "./rpc-BB5wM0QN.js";
2
2
  import { Emitter } from "@mica-js/core/lifecycle";
3
3
  import { BuildError, createJitBlockBuilder, validateBoundBlockIR, validateDeviceIR } from "@mica-js/device-model";
4
- import { RESUMABLE_RECEIVE, checkBoolean, compileBody, compileComputation, compileDirectJit, compileResumableBody, createBytes, createEnum, createRecord, equalValues, nonNull, readIndex } from "@mica-js/compiler";
4
+ import { RESUMABLE_RECEIVE, checkBoolean, compileBody, compileComputation, compileDirectJit, compileResumableBody, compileSynchronousBody, createBytes, createEnum, createRecord, equalValues, nonNull, readIndex } from "@mica-js/compiler";
5
5
  import { addTime, timePs } from "@mica-js/core";
6
6
  import { assetSrcError } from "@mica-js/document";
7
7
  import { deriveSchematicTopology, deviceMetadataSymbol, isAssetReference, parseDeviceMetadata, parseDeviceReference, parseSchematic, symbolRole } from "@mica-js/document/schematic";
@@ -273,8 +273,14 @@ function arraysEqual(first, second) {
273
273
  for (let index = 0; index < first.length; index++) if (first[index] !== second[index]) return false;
274
274
  return true;
275
275
  }
276
- function sameConfiguration(previous, component) {
277
- if (previous.edges.length !== component.edges.length) return false;
276
+ function sameConfiguration(previous, component, nodes) {
277
+ const layout = component.nodes;
278
+ if (previous.nodes.length !== layout.length || previous.edges.length !== component.edges.length) return false;
279
+ for (let index = 0; index < layout.length; index++) {
280
+ const node = layout[index];
281
+ if (previous.nodes[index] !== node) return false;
282
+ if (!Object.is(previous.references[index], nodes[node].reference)) return false;
283
+ }
278
284
  for (let index = 0; index < previous.edges.length; index++) {
279
285
  const edge = previous.edges[index];
280
286
  const other = component.edges[index];
@@ -928,20 +934,13 @@ function createElectricalNetwork(inputPins, inputNets) {
928
934
  applyLeaf(updatedSlots.length);
929
935
  return changedSlots.length === 0 ? emptySlots : changedSlots;
930
936
  }
931
- if (blocksStale) {
932
- blocksStale = false;
933
- cache = /* @__PURE__ */ new Map();
934
- topologyChanged = true;
935
- }
936
- const updates = /* @__PURE__ */ new Map();
937
- for (let position = 0; position < updatedSlots.length; position++) updates.set(updatedSlots[position], {
938
- intent: updatedIntents[position],
939
- edges: updatedEdges[position]
940
- });
937
+ if (blocksStale) topologyChanged = true;
938
+ const updated = updatedSlots.length;
941
939
  if (prepared !== void 0 && !topologyChanged && replacedEdges.length === 0) {
942
- for (const [index, update] of updates) {
943
- intents[index] = update.intent;
944
- pinEdges[index] = update.edges;
940
+ for (let position = 0; position < updated; position++) {
941
+ const index = updatedSlots[position];
942
+ intents[index] = updatedIntents[position];
943
+ pinEdges[index] = updatedEdges[position];
945
944
  }
946
945
  statistics.solves++;
947
946
  statistics.cacheHits += prepared.blocks.length;
@@ -951,18 +950,22 @@ function createElectricalNetwork(inputPins, inputNets) {
951
950
  let topology = prepared;
952
951
  let bucket;
953
952
  let restored;
953
+ /** Prospective rebuilds; committed only when the batch is accepted. */
954
+ let topologyPrepares = 0;
954
955
  const dirtyBlocks = /* @__PURE__ */ new Map();
955
956
  for (let position = 0; position < updatedEdgeSlots.length; position++) updatedEdgeLists[updatedEdgeSlots[position]] = void 0;
956
957
  updatedEdgeSlots.length = 0;
957
- for (const [index, update] of updates) {
958
- updatedEdgeLists[index] = update.edges;
958
+ for (let position = 0; position < updated; position++) {
959
+ const index = updatedSlots[position];
960
+ updatedEdgeLists[index] = updatedEdges[position];
959
961
  updatedEdgeSlots.push(index);
960
962
  }
961
963
  if (topologyChanged) {
962
964
  let hash = topologyHash;
963
965
  let spread = topologySpread;
964
- for (const [index, update] of updates) {
965
- const next = hashEdges(index, update.edges);
966
+ for (let position = 0; position < updated; position++) {
967
+ const index = updatedSlots[position];
968
+ const next = hashEdges(index, updatedEdges[position]);
966
969
  const previous = pinHashes[index];
967
970
  if (next === previous) continue;
968
971
  hash += next - previous;
@@ -973,9 +976,9 @@ function createElectricalNetwork(inputPins, inputNets) {
973
976
  if (restored !== void 0) topology = restoreTopology(restored.topology, pinEdges, updatedEdgeLists);
974
977
  else {
975
978
  const nextEdges = pinEdges.slice();
976
- for (const [index, update] of updates) nextEdges[index] = update.edges;
979
+ for (let position = 0; position < updated; position++) nextEdges[updatedSlots[position]] = updatedEdges[position];
977
980
  topology = prepareTopology(nodes, nextEdges);
978
- statistics.topologyPrepares++;
981
+ topologyPrepares++;
979
982
  }
980
983
  } else {
981
984
  const dirty = /* @__PURE__ */ new Set();
@@ -993,7 +996,7 @@ function createElectricalNetwork(inputPins, inputNets) {
993
996
  for (const block of topologyChanged ? topology.blocks : dirtyBlocks.values()) {
994
997
  const { component, key } = block;
995
998
  const previous = cache.get(key);
996
- if (previous !== void 0 && sameConfiguration(previous, component)) {
999
+ if (previous !== void 0 && sameConfiguration(previous, component, nodes)) {
997
1000
  cacheHits++;
998
1001
  (nextCache ??= /* @__PURE__ */ new Map()).set(key, previous);
999
1002
  continue;
@@ -1083,6 +1086,8 @@ function createElectricalNetwork(inputPins, inputNets) {
1083
1086
  }
1084
1087
  }
1085
1088
  const entry = {
1089
+ nodes: component.nodes,
1090
+ references: component.nodes.map((node) => nodes[node].reference),
1086
1091
  edges: component.edges,
1087
1092
  voltages: component.nodes.map((node) => voltages.get(node)),
1088
1093
  factorization
@@ -1112,11 +1117,13 @@ function createElectricalNetwork(inputPins, inputNets) {
1112
1117
  if (changedSlots.length > 1) changedSlots.sort(ascendingSlot);
1113
1118
  for (const [pin, sample] of pending) pin.sample = sample;
1114
1119
  for (const [node, voltage] of pendingVoltages) publishedVoltages[node] = voltage;
1115
- for (const [index, update] of updates) {
1116
- syncDegrees(pinEdges[index], update.edges);
1117
- intents[index] = update.intent;
1118
- pinEdges[index] = update.edges;
1119
- setPinHash(index, update.edges);
1120
+ for (let position = 0; position < updated; position++) {
1121
+ const index = updatedSlots[position];
1122
+ const edges = updatedEdges[position];
1123
+ syncDegrees(pinEdges[index], edges);
1124
+ intents[index] = updatedIntents[position];
1125
+ pinEdges[index] = edges;
1126
+ setPinHash(index, edges);
1120
1127
  }
1121
1128
  if (topologyChanged) cache = nextCache ?? /* @__PURE__ */ new Map();
1122
1129
  else {
@@ -1125,6 +1132,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1125
1132
  }
1126
1133
  prepared = topology;
1127
1134
  componentArraysOwned = false;
1135
+ blocksStale = false;
1128
1136
  if (topologyChanged) {
1129
1137
  const admitted = restored !== void 0 && topology === restored.topology ? restored : {
1130
1138
  id: restored?.id ?? nextTopologyId++,
@@ -1140,6 +1148,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1140
1148
  statistics.factorizations += factorizations;
1141
1149
  statistics.factorizationReuses += factorizationReuses;
1142
1150
  statistics.cacheHits += cacheHits;
1151
+ statistics.topologyPrepares += topologyPrepares;
1143
1152
  flushAdmissions();
1144
1153
  return changedSlots.length === 0 ? emptySlots : changedSlots;
1145
1154
  }
@@ -1811,6 +1820,12 @@ function compileObservation(target, key, path) {
1811
1820
  var compiledBodies = /* @__PURE__ */ new WeakMap();
1812
1821
  var resumablePrograms = /* @__PURE__ */ new WeakMap();
1813
1822
  var compiledComputations = /* @__PURE__ */ new WeakMap();
1823
+ /**
1824
+ * Synchronous programs are instance independent, but their static function resolution
1825
+ * belongs to one device model. The outer key prevents reusing a root region compiled
1826
+ * against another model's function table; `null` records a whole-body fallback.
1827
+ */
1828
+ var synchronousPrograms = /* @__PURE__ */ new WeakMap();
1814
1829
  var MAX_TIME = 72e14;
1815
1830
  function time(value) {
1816
1831
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new TypeError("Time must be a finite integer");
@@ -1825,6 +1840,30 @@ function body(region) {
1825
1840
  }
1826
1841
  return result;
1827
1842
  }
1843
+ /**
1844
+ * Compile one reaction body for one device model. Static callees are resolved from the
1845
+ * same declaration environment the generator uses. A compiler decline is cached as a
1846
+ * whole-body fallback; execution errors are never caught here and never replay effects.
1847
+ */
1848
+ function synchronousBody(instance, region) {
1849
+ const model = instance.entry.model;
1850
+ let cache = synchronousPrograms.get(model);
1851
+ if (cache === void 0) {
1852
+ cache = /* @__PURE__ */ new WeakMap();
1853
+ synchronousPrograms.set(model, cache);
1854
+ }
1855
+ const cached = cache.get(region);
1856
+ if (cached !== void 0) return cached ?? void 0;
1857
+ const program = compileSynchronousBody(region, {
1858
+ bindResources: true,
1859
+ resolveFunction: (name) => {
1860
+ const declaration = instance.declarations.get(name);
1861
+ return declaration?.kind === "function" ? declaration.body : void 0;
1862
+ }
1863
+ });
1864
+ cache.set(region, program ?? null);
1865
+ return program;
1866
+ }
1828
1867
  function resumable(region) {
1829
1868
  let result = resumablePrograms.get(region);
1830
1869
  if (result === void 0) {
@@ -1945,6 +1984,7 @@ var Instance = class {
1945
1984
  props = /* @__PURE__ */ new Map();
1946
1985
  constants = /* @__PURE__ */ new Map();
1947
1986
  states = /* @__PURE__ */ new Map();
1987
+ directBank;
1948
1988
  memories = /* @__PURE__ */ new Map();
1949
1989
  memoryViews = /* @__PURE__ */ new Map();
1950
1990
  memorySizes = /* @__PURE__ */ new Map();
@@ -2000,11 +2040,7 @@ var Instance = class {
2000
2040
  this.random = randomState(seed, id, override);
2001
2041
  this.host = {
2002
2042
  read: (kind, name) => this.read(kind, name),
2003
- write: (name, value) => {
2004
- const slot = this.stateSlot(name);
2005
- this.states.set(name, snapshot(value));
2006
- this.board.invalidate(slot);
2007
- },
2043
+ write: (name, value) => this.writeState(name, value, this.stateSlot(name)),
2008
2044
  sample: (ref) => {
2009
2045
  return this.readSample(ref);
2010
2046
  },
@@ -2263,7 +2299,28 @@ var Instance = class {
2263
2299
  if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);
2264
2300
  return bytes;
2265
2301
  }
2266
- /** Cached resource bookkeeping for state and memory, resolved once per declaration name. */
2302
+ /** Instance-owned numeric bank, mirrored by every non-direct state write. */
2303
+ directStateBank() {
2304
+ if (this.directBank === void 0) {
2305
+ const stateNames = [...this.states.keys()].filter((name) => {
2306
+ const declaration = this.declarations.get(name);
2307
+ return declaration.type.kind === "number" || declaration.type.kind === "bool";
2308
+ });
2309
+ this.directBank = {
2310
+ stateNames: Object.freeze(stateNames),
2311
+ states: new Map(stateNames.map((name, index) => [name, index])),
2312
+ stateValues: stateNames.map((name) => this.states.get(name))
2313
+ };
2314
+ }
2315
+ return this.directBank;
2316
+ }
2317
+ writeState(name, value, slot) {
2318
+ const captured = snapshot(value);
2319
+ this.states.set(name, captured);
2320
+ const index = this.directBank?.states.get(name);
2321
+ if (index !== void 0) this.directBank.stateValues[index] = captured;
2322
+ this.board.invalidate(slot);
2323
+ }
2267
2324
  stateSlot(name) {
2268
2325
  let slot = this.stateSlots.get(name);
2269
2326
  if (slot === void 0) {
@@ -2303,6 +2360,7 @@ var Instance = class {
2303
2360
  jit.directPrograms.clear();
2304
2361
  jit.directProgramRevision = -1;
2305
2362
  jit.directSkip = void 0;
2363
+ jit.directMisses = 0;
2306
2364
  if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;
2307
2365
  else jit.direct = void 0;
2308
2366
  }
@@ -2379,8 +2437,7 @@ var Instance = class {
2379
2437
  },
2380
2438
  write: (value) => {
2381
2439
  const current = resolve();
2382
- states.set(name, snapshot(value));
2383
- this.board.invalidate(current);
2440
+ this.writeState(name, value, current);
2384
2441
  }
2385
2442
  });
2386
2443
  }
@@ -2496,6 +2553,7 @@ var Instance = class {
2496
2553
  instance: this,
2497
2554
  declaration,
2498
2555
  previous: void 0,
2556
+ synchronousProgram: synchronousBody(this, declaration.body) ?? null,
2499
2557
  frame: void 0
2500
2558
  });
2501
2559
  }
@@ -2624,12 +2682,40 @@ var Instance = class {
2624
2682
  if (Object.hasOwn(options, "polling")) {
2625
2683
  if (!Array.isArray(options.polling)) throw new TypeError("polling must be an array");
2626
2684
  for (const item of options.polling) {
2627
- dataObject(item, ["pc", "predicate"]);
2685
+ dataObject(item, [
2686
+ "pc",
2687
+ "predicate",
2688
+ "consume",
2689
+ "wait"
2690
+ ]);
2628
2691
  const pc = finite(item.pc, "polling pc");
2629
2692
  const predicate = identity(item.predicate);
2630
2693
  const declaration = this.declarations.get(predicate);
2631
2694
  if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
2632
- polling.set(pc, predicate);
2695
+ let consume;
2696
+ if (Object.hasOwn(item, "consume")) {
2697
+ consume = identity(item.consume);
2698
+ const fn = this.declarations.get(consume);
2699
+ if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
2700
+ }
2701
+ let wait;
2702
+ if (Object.hasOwn(item, "wait")) {
2703
+ dataObject(item.wait, ["delay", "advance"]);
2704
+ const delay = identity(item.wait.delay);
2705
+ const advance = identity(item.wait.advance);
2706
+ const delayFn = this.declarations.get(delay);
2707
+ const advanceFn = this.declarations.get(advance);
2708
+ if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
2709
+ wait = Object.freeze({
2710
+ delay,
2711
+ advance
2712
+ });
2713
+ }
2714
+ polling.set(pc, Object.freeze({
2715
+ predicate,
2716
+ ...consume === void 0 ? {} : { consume },
2717
+ ...wait === void 0 ? {} : { wait }
2718
+ }));
2633
2719
  }
2634
2720
  }
2635
2721
  if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
@@ -2652,12 +2738,14 @@ var Instance = class {
2652
2738
  directProgramRevision: -1,
2653
2739
  direct: void 0,
2654
2740
  directSkip: void 0,
2741
+ directMisses: 0,
2655
2742
  pollReads: void 0,
2656
2743
  currentPc: void 0,
2657
2744
  automaticPolling: false,
2658
2745
  pollingWait: false,
2659
2746
  pollingPeriod: 0,
2660
2747
  pollingOrigin: 0,
2748
+ pollingToken: 0,
2661
2749
  active: true,
2662
2750
  stopped: false,
2663
2751
  queued: false,
@@ -2670,6 +2758,7 @@ var Instance = class {
2670
2758
  jit.active = false;
2671
2759
  jit.execution = void 0;
2672
2760
  delete jit.predicate;
2761
+ jit.pollingToken++;
2673
2762
  this.board.waitingJits.delete(jit);
2674
2763
  jit.cache.clear();
2675
2764
  jit.directPrograms.clear();
@@ -2781,6 +2870,20 @@ function isPollingInstruction(body, pc, pcName) {
2781
2870
  //#region src/runtime/jit.ts
2782
2871
  /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2783
2872
  var DIRECT_SHARD_SIZE = 8;
2873
+ /**
2874
+ * Program size above which whole-program rebuilds are amortized instead of immediate.
2875
+ *
2876
+ * Translation only ever adds cache entries, so a compiled program stays valid for every PC it
2877
+ * already contains; only a missing PC needs a rebuild. Rebuilding on every new block is
2878
+ * quadratic, and that dominated warm-up on a real firmware image (411 blocks: 43 rebuilds and
2879
+ * ~1.7 s before any simulated time). Small programs rebuild in milliseconds, so they keep the
2880
+ * exact behaviour; only larger ones switch to a stride that grows with the program.
2881
+ */
2882
+ var DIRECT_REBUILD_LINEAR_LIMIT = 16;
2883
+ /** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */
2884
+ var DIRECT_REBUILD_MIN_BLOCKS = 64;
2885
+ /** A PC that keeps falling back buys an early rebuild instead of waiting out a full stride. */
2886
+ var DIRECT_REBUILD_PATIENCE = 512;
2784
2887
  var barriers = /* @__PURE__ */ new WeakMap();
2785
2888
  function directBarriers(jit) {
2786
2889
  let entry = barriers.get(jit);
@@ -2797,6 +2900,7 @@ function directStats(jit) {
2797
2900
  const counted = jit;
2798
2901
  return counted.directStats ??= {
2799
2902
  directCompiles: 0,
2903
+ directShards: 0,
2800
2904
  directCalls: 0,
2801
2905
  directFallbacks: 0,
2802
2906
  directDeadlines: 0,
@@ -2865,7 +2969,9 @@ function directHost(board, instance, frame) {
2865
2969
  },
2866
2970
  intent: (pin, value) => {
2867
2971
  publishTime();
2972
+ const changed = instance.pin(pin).intent !== value;
2868
2973
  instance.host.intent(pin, value);
2974
+ if (changed) frame.publishPending = true;
2869
2975
  },
2870
2976
  resistor: (pin, resistance) => {
2871
2977
  publishTime();
@@ -2889,13 +2995,32 @@ function directHost(board, instance, frame) {
2889
2995
  }
2890
2996
  };
2891
2997
  }
2892
- function createDirectFrame(board, instance, stateNames, memoryNames, program, barrier) {
2998
+ /** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */
2999
+ function directLayout(jit) {
3000
+ if (jit.directLayout !== void 0) return jit.directLayout;
3001
+ const instance = jit.instance;
3002
+ const bank = instance.directStateBank();
3003
+ const memoryNames = [...instance.memories.keys()];
3004
+ const memories = new Map(memoryNames.map((name, index) => [name, index]));
3005
+ const memoryBanks = memoryNames.map((name) => instance.memory(name));
3006
+ const memoryViews = memoryBanks.map((memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength));
3007
+ jit.directLayout = {
3008
+ ...bank,
3009
+ memoryNames: Object.freeze(memoryNames),
3010
+ memories,
3011
+ memoryBanks: Object.freeze(memoryBanks),
3012
+ memoryViews: Object.freeze(memoryViews)
3013
+ };
3014
+ return jit.directLayout;
3015
+ }
3016
+ function createDirectFrame(board, instance, layout, program, barrier) {
2893
3017
  const frame = {
2894
- states: new Array(stateNames.length),
2895
- memories: memoryNames.map((name) => instance.memory(name)),
3018
+ states: layout.stateValues,
3019
+ memories: [...layout.memoryBanks],
3020
+ memoryViews: layout.memoryViews,
2896
3021
  locals: new Array(program.localCount),
2897
- stateDirty: new Array(Math.ceil(stateNames.length / 32)).fill(0),
2898
- memoryDirty: new Array(Math.ceil(memoryNames.length / 32)).fill(0),
3022
+ stateDirty: new Array(Math.ceil(layout.stateNames.length / 32)).fill(0),
3023
+ memoryDirty: new Array(Math.ceil(layout.memoryNames.length / 32)).fill(0),
2899
3024
  time: board.time,
2900
3025
  due: board.time,
2901
3026
  resume: 0
@@ -2914,63 +3039,85 @@ function runDirect(board, jit, hookReads) {
2914
3039
  refreshDirectGuards(jit, hookReads);
2915
3040
  if (jit.directSkip === pc) return false;
2916
3041
  if (jit.directRevision !== jit.revision) {
2917
- if (jit.directProgramRevision !== jit.revision) {
2918
- jit.directPrograms.clear();
2919
- jit.directProgramRevision = jit.revision;
2920
- }
2921
- const key = JSON.stringify([...jit.delays.keys()].sort((left, right) => left - right));
2922
- const cached = jit.directPrograms.get(key);
2923
- if (cached) {
2924
- jit.direct = cached;
2925
- jit.directRevision = jit.revision;
3042
+ const compiled = jit.direct?.pcs.size ?? 0;
3043
+ const stale = jit.revision - jit.directRevision;
3044
+ const stride = compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);
3045
+ const covered = jit.direct?.pcs.has(pc) === true;
3046
+ if (!(jit.direct === void 0 || stale >= stride || !covered && jit.directMisses >= DIRECT_REBUILD_PATIENCE)) {
3047
+ if (!covered) {
3048
+ const stats = directStats(jit);
3049
+ stats.directCalls++;
3050
+ stats.directFallbacks++;
3051
+ jit.directMisses += 1;
3052
+ return false;
3053
+ }
2926
3054
  } else {
2927
- const stateNames = [...instance.states.keys()].filter((name) => {
2928
- const declaration = instance.declarations.get(name);
2929
- return declaration.type.kind === "number" || declaration.type.kind === "bool";
2930
- });
2931
- const memoryNames = [...instance.memories.keys()];
2932
- const states = new Map(stateNames.map((name, index) => [name, index]));
2933
- const memories = new Map(memoryNames.map((name, index) => [name, index]));
3055
+ if (jit.directProgramRevision !== jit.revision) {
3056
+ if (jit.directProgramRevision === -1 && jit.directCache !== void 0) compileDirectJit.clearCache(jit.directCache);
3057
+ jit.directPrograms.clear();
3058
+ jit.directProgramRevision = jit.revision;
3059
+ }
3060
+ const layout = directLayout(jit);
2934
3061
  const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !jit.polling.has(instruction.pc));
2935
3062
  /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
2936
3063
  const delayLoops = /* @__PURE__ */ new Map();
2937
- for (const [pc, delay] of jit.delays) {
2938
- const counter = states.get(delay.counter);
2939
- if (counter !== void 0) delayLoops.set(pc, {
3064
+ for (const [headPc, delay] of jit.delays) {
3065
+ const counter = layout.states.get(delay.counter);
3066
+ if (counter === void 0) continue;
3067
+ const pending = delay.pending === void 0 ? void 0 : {
3068
+ state: layout.states.get(delay.pending.state),
3069
+ period: layout.states.get(delay.pending.period),
3070
+ active: layout.states.get(delay.pending.active)
3071
+ };
3072
+ delayLoops.set(headPc, pending !== void 0 && pending.state !== void 0 && pending.period !== void 0 && pending.active !== void 0 ? {
3073
+ counter,
3074
+ cycles: delay.cycles,
3075
+ pending
3076
+ } : {
2940
3077
  counter,
2941
3078
  cycles: delay.cycles
2942
3079
  });
2943
3080
  }
2944
- const program = compileDirectJit(instructions, {
2945
- states,
2946
- memories,
2947
- pc: {
2948
- name: jit.options.pc,
2949
- index: states.get(jit.options.pc)
2950
- },
2951
- host: true,
2952
- split: true,
2953
- shardSize: DIRECT_SHARD_SIZE,
2954
- delayLoops
2955
- });
2956
- jit.directRevision = jit.revision;
2957
- if (program) directStats(jit).directCompiles++;
2958
- const barrier = directBarriers(jit);
2959
- barrier.stateIndex = states;
2960
- barrier.memoryIndex = memories;
2961
- barrier.stateMask.length = Math.ceil(stateNames.length / 32);
2962
- barrier.memoryMask.length = Math.ceil(memoryNames.length / 32);
2963
- syncDirectBarriers(jit);
2964
- jit.direct = program ? {
2965
- program,
2966
- stateReads: program.readStates.map((name) => [name, states.get(name)]),
2967
- stateWrites: program.writeStates.map((name) => [name, states.get(name)]),
2968
- memoryWrites: program.writeMemories.map((name) => [name, memories.get(name)]),
2969
- revision: jit.revision,
2970
- frame: createDirectFrame(board, instance, stateNames, memoryNames, program, barrier)
2971
- } : void 0;
2972
- if (!jit.direct) jit.directPrograms.delete(key);
2973
- else jit.directPrograms.set(key, jit.direct);
3081
+ const key = JSON.stringify([...delayLoops].sort(([left], [right]) => left - right));
3082
+ const cached = jit.directPrograms.get(key);
3083
+ if (cached) {
3084
+ jit.direct = cached;
3085
+ jit.directRevision = jit.revision;
3086
+ } else {
3087
+ const { states, memories } = layout;
3088
+ const cache = jit.directCache ??= compileDirectJit.createCache();
3089
+ const program = compileDirectJit(instructions, {
3090
+ states,
3091
+ memories,
3092
+ pc: {
3093
+ name: jit.options.pc,
3094
+ index: states.get(jit.options.pc)
3095
+ },
3096
+ host: true,
3097
+ split: true,
3098
+ shardSize: DIRECT_SHARD_SIZE,
3099
+ delayLoops
3100
+ }, cache);
3101
+ jit.directRevision = jit.revision;
3102
+ jit.directMisses = 0;
3103
+ const stats = directStats(jit);
3104
+ stats.directShards = program?.shards ?? 0;
3105
+ if (program) stats.directCompiles++;
3106
+ const barrier = directBarriers(jit);
3107
+ barrier.stateIndex = states;
3108
+ barrier.memoryIndex = memories;
3109
+ barrier.stateMask.length = Math.ceil(layout.stateNames.length / 32);
3110
+ barrier.memoryMask.length = Math.ceil(layout.memoryNames.length / 32);
3111
+ syncDirectBarriers(jit);
3112
+ jit.direct = program ? {
3113
+ program,
3114
+ pcs: new Set(program.pcs),
3115
+ revision: jit.revision,
3116
+ frame: createDirectFrame(board, instance, layout, program, barrier)
3117
+ } : void 0;
3118
+ if (!jit.direct) jit.directPrograms.delete(key);
3119
+ else jit.directPrograms.set(key, jit.direct);
3120
+ }
2974
3121
  }
2975
3122
  }
2976
3123
  if (!jit.direct) return false;
@@ -2978,7 +3125,6 @@ function runDirect(board, jit, hookReads) {
2978
3125
  const direct = jit.direct;
2979
3126
  const frame = direct.frame;
2980
3127
  if (pending) frame.stopAfterInstruction = true;
2981
- for (const [name, index] of direct.stateReads) frame.states[index] = instance.states.get(name);
2982
3128
  frame.time = board.time;
2983
3129
  frame.stateDirty.fill(0);
2984
3130
  frame.memoryDirty.fill(0);
@@ -2991,19 +3137,34 @@ function runDirect(board, jit, hookReads) {
2991
3137
  reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
2992
3138
  } finally {
2993
3139
  board.time = frame.time;
2994
- for (const [name, index] of direct.stateWrites) if ((frame.stateDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2995
- instance.host.write(name, frame.states[index]);
2996
- wrote = true;
3140
+ frame.publishPending = false;
3141
+ const layout = jit.directLayout;
3142
+ for (let word = 0; word < frame.stateDirty.length; word++) {
3143
+ let bits = frame.stateDirty[word];
3144
+ while (bits !== 0) {
3145
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3146
+ instance.host.write(layout.stateNames[slot], frame.states[slot]);
3147
+ bits &= bits - 1;
3148
+ wrote = true;
3149
+ }
2997
3150
  }
2998
- for (const [name, index] of direct.memoryWrites) if ((frame.memoryDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2999
- instance.memoryChanged(name);
3000
- wrote = true;
3151
+ for (let word = 0; word < frame.memoryDirty.length; word++) {
3152
+ let bits = frame.memoryDirty[word];
3153
+ while (bits !== 0) {
3154
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3155
+ instance.memoryChanged(layout.memoryNames[slot]);
3156
+ bits &= bits - 1;
3157
+ wrote = true;
3158
+ }
3001
3159
  }
3002
3160
  }
3003
3161
  if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
3004
3162
  if (reason === "fallback") {
3005
- stats.directFallbacks++;
3006
- jit.directSkip = finite(instance.states.get(jit.options.pc), "pc");
3163
+ const nextPc = finite(instance.states.get(jit.options.pc), "pc");
3164
+ if (!(jit.polling.has(nextPc) || jit.cache.get(nextPc)?.polling)) {
3165
+ stats.directFallbacks++;
3166
+ jit.directSkip = nextPc;
3167
+ }
3007
3168
  if (board.time === start && board.time < board.executionEnd) return false;
3008
3169
  } else if (reason === "stopped") {
3009
3170
  stats.directStopped++;
@@ -3026,6 +3187,33 @@ function pollingDependencies(jit, dependencies) {
3026
3187
  for (const slot of [instance.stateResources.get(jit.options.pc), instance.memoryResources.get(jit.options.code)]) result.set(slot, slot.version);
3027
3188
  return result;
3028
3189
  }
3190
+ /** Park a polling JIT and, when requested, schedule the next device time event. */
3191
+ function waitForPolling(board, jit, dependencies, duration, advance) {
3192
+ jit.dependencies = dependencies;
3193
+ jit.pollingWait = true;
3194
+ jit.pollingPeriod = 0;
3195
+ board.waitingJits.add(jit);
3196
+ const token = ++jit.pollingToken;
3197
+ board.boundary();
3198
+ if (duration === 0 || advance === void 0) return;
3199
+ const due = time(board.time + duration);
3200
+ board.events.push(due, () => {
3201
+ if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit)) return;
3202
+ const pending = jit.dependencies;
3203
+ jit.pollingWait = false;
3204
+ delete jit.dependencies;
3205
+ board.waitingJits.delete(jit);
3206
+ jit.pollingToken++;
3207
+ board.current = jit.instance;
3208
+ if (!jit.instance.dependenciesCurrent(pending)) {
3209
+ board.queueJit(jit);
3210
+ return;
3211
+ }
3212
+ jit.instance.syncCall(advance, [duration]);
3213
+ board.boundary();
3214
+ board.queueJit(jit);
3215
+ });
3216
+ }
3029
3217
  function jitSignal(board, jit, signal) {
3030
3218
  if (signal.kind === "elapse") {
3031
3219
  const duration = time(signal.duration);
@@ -3109,17 +3297,18 @@ function runJit(board, jit) {
3109
3297
  }
3110
3298
  const pc = finite(jit.instance.states.get(jit.options.pc), "pc");
3111
3299
  if (board.execution === "throughput") {
3112
- const predicate = jit.polling.get(pc);
3113
- if (predicate) {
3114
- const checked = jit.instance.evaluate(() => jit.instance.syncCall(predicate));
3300
+ const declaration = jit.polling.get(pc);
3301
+ if (declaration) {
3302
+ const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));
3115
3303
  if (checked.value !== true) {
3116
- jit.dependencies = pollingDependencies(jit, new Map([...hookReads ?? [], ...checked.dependencies]));
3117
- jit.pollingWait = true;
3118
- jit.pollingPeriod = 0;
3119
- board.waitingJits.add(jit);
3120
- board.boundary();
3304
+ const dependencies = new Map([...hookReads ?? [], ...checked.dependencies]);
3305
+ let duration = 0;
3306
+ const wait = declaration.wait;
3307
+ if (wait) duration = time(jit.instance.evaluate(() => jit.instance.syncCall(wait.delay), dependencies).value);
3308
+ waitForPolling(board, jit, pollingDependencies(jit, dependencies), duration, wait?.advance);
3121
3309
  return;
3122
3310
  }
3311
+ if (declaration.consume) jit.instance.syncCall(declaration.consume);
3123
3312
  }
3124
3313
  if (!hookPending && board.jits.length === 1 && runDirect(board, jit, hookReads)) return;
3125
3314
  }
@@ -3409,7 +3598,13 @@ var BoardRuntime = class {
3409
3598
  source: chain.plan.source,
3410
3599
  comparison: chain.plan.comparison
3411
3600
  }))),
3412
- skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry })))
3601
+ skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry }))),
3602
+ reactions: Object.freeze(this.instances.flatMap((instance) => instance.reactions.map((reaction) => Object.freeze({
3603
+ instance: instance.id,
3604
+ name: reaction.declaration.name,
3605
+ mode: reaction.synchronousProgram === void 0 ? "pending" : reaction.synchronousProgram === null ? "generic" : reaction.synchronous !== void 0 && reaction.synchronous !== null ? "sync" : "ready",
3606
+ functions: reaction.synchronousProgram?.functions.length ?? 0
3607
+ }))))
3413
3608
  });
3414
3609
  }
3415
3610
  /**
@@ -3577,6 +3772,15 @@ var BoardRuntime = class {
3577
3772
  this.readyJits.push(jit);
3578
3773
  }
3579
3774
  }
3775
+ /**
3776
+ * Fail-closed admission for staying inside generated code after a publication checkpoint.
3777
+ * The JIT must be the only direct owner, all same-time scheduler stages must be empty,
3778
+ * and no event may be due through the requested horizon. The target time is exclusive:
3779
+ * code must not resume at `executionEnd`.
3780
+ */
3781
+ canContinueDirect(jit, horizon) {
3782
+ return this.status === "ready" && this.phase === "execute" && !this.isFaulted && this.execution === "throughput" && this.jits.length === 1 && this.jits[0] === jit && jit.active && !jit.stopped && !jit.queued && this.readyJits.length === 0 && this.models.length === 0 && this.waitingJits.size === 0 && this.time < this.executionEnd && horizon >= this.time && horizon < this.executionEnd && this.events.time > horizon;
3783
+ }
3580
3784
  invalidate(slot) {
3581
3785
  slot.version++;
3582
3786
  if (slot.subscribers.size === 0) return;
@@ -3713,27 +3917,36 @@ var BoardRuntime = class {
3713
3917
  applyChange(observation, previous, current) {
3714
3918
  if (observation.declaration.kind === "reaction") {
3715
3919
  const reaction = observation;
3716
- reaction.frame = {
3920
+ const frame = reaction.frame;
3921
+ if (frame === void 0) reaction.frame = {
3717
3922
  previous,
3718
3923
  current,
3719
3924
  captures: []
3720
3925
  };
3926
+ else {
3927
+ frame.previous = previous;
3928
+ frame.current = current;
3929
+ frame.captures.length = 0;
3930
+ }
3721
3931
  this.reactionBatch.push(reaction);
3722
3932
  } else this.enqueue(observation);
3723
3933
  }
3724
3934
  recordChange(observation, previous, current) {
3725
- const list = this.changeObservations;
3726
- let at = list.length;
3935
+ this.insertOrderedChange(this.changeObservations, this.changePrevious, this.changeCurrent, observation, previous, current);
3936
+ }
3937
+ /** Shared stable insertion; receivers are few, so in-place insertion beats a sort. */
3938
+ insertOrderedChange(receivers, previous, current, observation, before, after) {
3939
+ let at = receivers.length;
3727
3940
  const order = observation.order;
3728
- while (at > 0 && list[at - 1].order > order) at--;
3729
- if (at === list.length) {
3730
- list.push(observation);
3731
- this.changePrevious.push(previous);
3732
- this.changeCurrent.push(current);
3941
+ while (at > 0 && receivers[at - 1].order > order) at--;
3942
+ if (at === receivers.length) {
3943
+ receivers.push(observation);
3944
+ previous.push(before);
3945
+ current.push(after);
3733
3946
  } else {
3734
- list.splice(at, 0, observation);
3735
- this.changePrevious.splice(at, 0, previous);
3736
- this.changeCurrent.splice(at, 0, current);
3947
+ receivers.splice(at, 0, observation);
3948
+ previous.splice(at, 0, before);
3949
+ current.splice(at, 0, after);
3737
3950
  }
3738
3951
  }
3739
3952
  boundary() {
@@ -3746,42 +3959,79 @@ var BoardRuntime = class {
3746
3959
  changes.length = 0;
3747
3960
  this.changePrevious.length = 0;
3748
3961
  this.changeCurrent.length = 0;
3749
- try {
3750
- const batch = this.observations.take();
3751
- for (let index = 0; index < batch.length; index++) {
3752
- const observation = batch[index];
3753
- if ("plan" in observation) {
3754
- this.collectChain(observation);
3755
- continue;
3756
- }
3757
- const current = observation.readSource();
3758
- if (same(observation.previous, current)) continue;
3759
- const previous = observation.previous;
3760
- observation.previous = current;
3761
- if (changes.length) this.recordChange(observation, previous, current);
3762
- else this.applyChange(observation, previous, current);
3763
- }
3764
- const count = changes.length;
3765
- if (count) {
3766
- for (let index = 0; index < count; index++) this.applyChange(changes[index], this.changePrevious[index], this.changeCurrent[index]);
3767
- changes.length = 0;
3768
- this.changePrevious.length = 0;
3769
- this.changeCurrent.length = 0;
3770
- }
3771
- if (!reactions.length) return;
3772
- for (const reaction of reactions) if (reaction.declaration.captures.length) reaction.frame = {
3773
- ...reaction.frame,
3774
- captures: reaction.declaration.captures.map((capture) => snapshot(computation(capture.value, reaction.instance.host)))
3775
- };
3776
- for (const reaction of reactions) {
3777
- this.current = reaction.instance;
3778
- reaction.execute ??= body(reaction.declaration.body);
3779
- if (!reaction.execute(reaction.instance.host, [], reaction.frame).next().done) throw new TypeError("Reaction cannot suspend");
3962
+ const batch = this.observations.take();
3963
+ for (let index = 0; index < batch.length; index++) {
3964
+ const observation = batch[index];
3965
+ if ("plan" in observation) {
3966
+ this.collectChain(observation);
3967
+ continue;
3780
3968
  }
3781
- } finally {
3782
- for (const reaction of reactions) reaction.frame = void 0;
3969
+ const current = observation.readSource();
3970
+ if (same(observation.previous, current)) continue;
3971
+ const previous = observation.previous;
3972
+ observation.previous = current;
3973
+ if (changes.length) this.recordChange(observation, previous, current);
3974
+ else this.applyChange(observation, previous, current);
3975
+ }
3976
+ const count = changes.length;
3977
+ if (count) {
3978
+ for (let index = 0; index < count; index++) this.applyChange(changes[index], this.changePrevious[index], this.changeCurrent[index]);
3979
+ changes.length = 0;
3980
+ this.changePrevious.length = 0;
3981
+ this.changeCurrent.length = 0;
3982
+ }
3983
+ if (reactions.length) this.runBoundaryReactions(reactions);
3984
+ else return;
3985
+ }
3986
+ }
3987
+ /** Shared capture barrier and ordered body runner for generic and static boundaries. */
3988
+ runBoundaryReactions(reactions) {
3989
+ try {
3990
+ for (const reaction of reactions) if (reaction.declaration.captures.length) {
3991
+ const frame = reaction.frame;
3992
+ frame.captures = reaction.declaration.captures.map((capture) => snapshot(computation(capture.value, reaction.instance.host)));
3993
+ }
3994
+ for (const reaction of reactions) {
3995
+ this.current = reaction.instance;
3996
+ this.runReaction(reaction);
3783
3997
  }
3998
+ } finally {
3999
+ this.clearReactionFrames(reactions);
4000
+ }
4001
+ }
4002
+ clearReactionFrames(reactions) {
4003
+ for (const reaction of reactions) {
4004
+ const frame = reaction.frame;
4005
+ if (frame === void 0) continue;
4006
+ frame.previous = void 0;
4007
+ frame.current = void 0;
4008
+ frame.captures.length = 0;
4009
+ }
4010
+ }
4011
+ /**
4012
+ * Execute one synchronous boundary reaction. The capture barrier already froze every
4013
+ * frame before this method runs. Admission is whole-body: a compiler decline selects
4014
+ * the generator path before any effect, while bind/execution errors propagate without
4015
+ * a catch-and-replay fallback.
4016
+ */
4017
+ runReaction(reaction) {
4018
+ const instance = reaction.instance;
4019
+ let program = reaction.synchronousProgram;
4020
+ if (program === void 0) {
4021
+ program = synchronousBody(instance, reaction.declaration.body) ?? null;
4022
+ reaction.synchronousProgram = program;
4023
+ }
4024
+ if (program !== null) {
4025
+ let runner = reaction.synchronous;
4026
+ if (runner === void 0 || runner === null) {
4027
+ runner = program.bind(instance.host);
4028
+ reaction.synchronous = runner;
4029
+ }
4030
+ runner(void 0, reaction.frame);
4031
+ return;
3784
4032
  }
4033
+ reaction.execute ??= body(reaction.declaration.body);
4034
+ if (!reaction.execute(instance.host, [], reaction.frame).next().done) throw new TypeError("Reaction cannot suspend");
3785
4035
  }
3786
4036
  drive(process, value) {
3787
4037
  const program = process.resumable;
@@ -3933,6 +4183,7 @@ var BoardRuntime = class {
3933
4183
  if (lastStart < 72e14 && lastStart < end) {
3934
4184
  if (lastStart === this.time) {
3935
4185
  jit.pollingWait = false;
4186
+ jit.pollingToken++;
3936
4187
  delete jit.dependencies;
3937
4188
  this.waitingJits.delete(jit);
3938
4189
  this.queueJit(jit);
@@ -3943,6 +4194,7 @@ var BoardRuntime = class {
3943
4194
  }
3944
4195
  if (jit.pollingWait) {
3945
4196
  jit.pollingWait = false;
4197
+ jit.pollingToken++;
3946
4198
  delete jit.dependencies;
3947
4199
  this.waitingJits.delete(jit);
3948
4200
  const remainder = jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;
@@ -4150,6 +4402,7 @@ async function prepareSimulation(input, importer, assertActive) {
4150
4402
  symbol: symbol.id,
4151
4403
  device: devices.get(symbol.device)
4152
4404
  })),
4405
+ ...input.execution === void 0 ? {} : { execution: input.execution },
4153
4406
  description: {
4154
4407
  instances: symbols.map((symbol) => ({
4155
4408
  id: symbol.id,
@@ -4377,7 +4630,7 @@ function buildLoadedRuntime(prepared, publishObserved) {
4377
4630
  ...instance,
4378
4631
  props: Object.fromEntries(Object.entries(instance.props ?? {}).map(([key, value]) => [key, value instanceof Uint8Array ? new Uint8Array(value) : value]))
4379
4632
  }))
4380
- });
4633
+ }, prepared.execution === void 0 ? {} : { execution: prepared.execution });
4381
4634
  const project = (diagnostic, fatal) => {
4382
4635
  found.push({
4383
4636
  code: fatal ? diagnostic.phase === "topic" ? "device/input-failed" : diagnostic.phase === "sync" ? "device/output-failed" : "board/error" : "board/diagnostic",
@@ -4489,7 +4742,8 @@ function registerSimulationRuntimeServices(rpc, runtime, topicRpc) {
4489
4742
  const serviceRegistration = rpc.register(simulationRuntimeService, service, { transfer: simulationRuntimeEventTransfer });
4490
4743
  const topicRegistration = topicRpc === void 0 ? void 0 : topicRpc.register(simulationRuntimeTopicService, {
4491
4744
  deliver: service.deliver,
4492
- onDidPublish: service.onDidPublish
4745
+ onDidPublish: service.onDidPublish,
4746
+ async flushPublishes() {}
4493
4747
  }, { transfer: simulationRuntimeEventTransfer });
4494
4748
  let disposed = false;
4495
4749
  return { dispose() {