@mica-js/simulator 2.2.0 → 2.4.0

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,4 +1,4 @@
1
- import { a as copyBytePayload, c as samePayload, i as simulationRuntimeTopicService, l as targetKey, n as simulationRuntimeEventTransfer, o as copyPayload, r as simulationRuntimeService, s as payloadMatches } from "./rpc-D-9O3TZf.js";
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
4
  import { RESUMABLE_RECEIVE, checkBoolean, compileBody, compileComputation, compileDirectJit, compileResumableBody, createBytes, createEnum, createRecord, equalValues, nonNull, readIndex } from "@mica-js/compiler";
@@ -32,8 +32,22 @@ var ElectricalError = class extends Error {
32
32
  function validateResistance(resistance, location = {}) {
33
33
  if (!Number.isFinite(resistance) || resistance < .001 || resistance > 1e9) throw new ElectricalError("INVALID_ELECTRICAL_PARAMETER", "Resistance must be finite and in [0.001, 1000000000] ohms.", location);
34
34
  }
35
- var topologyTransitionLimit = 8;
35
+ /**
36
+ * Descriptors and admitted graphs share these buckets. The budget covers a whole-board
37
+ * working set: a 288-pin board steps through roughly 1.2k distinct shapes in 300 ms, so
38
+ * the former limit of eight discarded every descriptor before its second observation could
39
+ * ever admit a graph.
40
+ */
41
+ var topologyTransitionLimit = 4096;
42
+ /** Compiled reference programs cost far more per entry than a graph descriptor. */
43
+ var referenceProgramLimit = 8;
36
44
  var topologySnapshotLimit = 65536;
45
+ /** FNV-1a over the pin slot and its ordered endpoints: the key without the 288 strings. */
46
+ function hashEdges(slot, edges) {
47
+ let hash = Math.imul(2166136261 ^ slot, 16777619);
48
+ for (let index = 0; index < edges.length; index++) hash = Math.imul(hash ^ edges[index].to, 16777619);
49
+ return Math.imul(hash ^ edges.length, 16777619) >>> 0;
50
+ }
37
51
  function topologyCost(topology) {
38
52
  let cost = 0;
39
53
  const physicals = /* @__PURE__ */ new Set();
@@ -52,7 +66,7 @@ function rebindBlock(block, pinEdges, updates) {
52
66
  let edges;
53
67
  for (let index = 0; index < block.component.edges.length; index++) {
54
68
  const edge = block.component.edges[index];
55
- const next = (updates.get(edge.pin)?.edges ?? pinEdges[edge.pin])[edge.index];
69
+ const next = (updates[edge.pin] ?? pinEdges[edge.pin])[edge.index];
56
70
  if (edge.from === next.from && edge.to === next.to && edge.resistance === next.resistance) continue;
57
71
  edges ??= block.component.edges.slice();
58
72
  edges[index] = next;
@@ -66,6 +80,11 @@ function rebindBlock(block, pinEdges, updates) {
66
80
  }
67
81
  };
68
82
  }
83
+ /**
84
+ * Every block edge is re-read from the committed pin edges. A bucket key records
85
+ * connectivity only, so a resistance-only change keeps its key and still has to be
86
+ * repaired in blocks that no pin of this solve touches.
87
+ */
69
88
  function restoreTopology(topology, pinEdges, updates) {
70
89
  let blocks;
71
90
  for (let index = 0; index < topology.blocks.length; index++) {
@@ -86,10 +105,6 @@ function prepareBlock(component) {
86
105
  key: component.nodes.join(",")
87
106
  };
88
107
  }
89
- /** Ordered endpoint list per pin; multiplicity stays visible without hashing. */
90
- function describeEdges(edges) {
91
- return edges.map((edge) => edge.to).join(",");
92
- }
93
108
  function prepareTopology(nodes, pinEdges) {
94
109
  const topology = new DisjointSet(nodes.length);
95
110
  for (const edges of pinEdges) for (const edge of edges) topology.join(edge.from, edge.to);
@@ -459,30 +474,50 @@ function createElectricalNetwork(inputPins, inputNets) {
459
474
  let cache = /* @__PURE__ */ new Map();
460
475
  const referencePrograms = [];
461
476
  let prepared;
462
- let snapshot;
463
477
  let nextTopologyId = 0;
464
- const transitionAges = /* @__PURE__ */ new Map();
465
- let transitionClock = 0;
466
478
  const transitions = /* @__PURE__ */ new Map();
467
- let pinDescriptions = new Array(pins.length).fill("");
468
- const rememberTransition = (key, target) => {
469
- if (target.cost > topologySnapshotLimit) return;
470
- const repeated = transitions.has(key);
471
- transitionAges.set(key, ++transitionClock);
472
- if (!repeated) transitions.set(key, void 0);
473
- else if (transitions.get(key) !== target) transitions.set(key, target);
474
- if (transitions.size > topologyTransitionLimit) {
475
- let oldest;
476
- let oldestAge = Infinity;
477
- for (const candidate of transitionAges.keys()) {
478
- const age = transitionAges.get(candidate);
479
- if (age < oldestAge) {
480
- oldest = candidate;
481
- oldestAge = age;
482
- }
483
- }
479
+ /**
480
+ * Per-pin endpoint hash. Their exact integer summary is the bucket key, so a repeated
481
+ * shape costs one hash per dirty pin instead of a 288-entry string join.
482
+ */
483
+ const pinHashes = new Uint32Array(pins.length);
484
+ let topologyHash = 0;
485
+ let topologySpread = 0;
486
+ for (let slot = 0; slot < pins.length; slot++) {
487
+ const hash = hashEdges(slot, []);
488
+ pinHashes[slot] = hash;
489
+ topologyHash += hash;
490
+ topologySpread ^= hash;
491
+ }
492
+ const setPinHash = (slot, edges) => {
493
+ const hash = hashEdges(slot, edges);
494
+ const previous = pinHashes[slot];
495
+ if (hash === previous) return;
496
+ pinHashes[slot] = hash;
497
+ topologyHash += hash - previous;
498
+ topologySpread ^= previous ^ hash;
499
+ };
500
+ /** Confirms a bucket hit against the exact hashes the stored graph was built from. */
501
+ const lookupTransition = (key, updated) => {
502
+ const candidate = transitions.get(key);
503
+ if (candidate === void 0) return void 0;
504
+ const hashes = candidate.hashes;
505
+ if (hashes.length !== pinHashes.length) return void 0;
506
+ for (let slot = 0; slot < hashes.length; slot++) {
507
+ const edges = updated[slot];
508
+ const hash = edges === void 0 ? pinHashes[slot] : hashEdges(slot, edges);
509
+ if (hashes[slot] !== hash) return void 0;
510
+ }
511
+ return candidate;
512
+ };
513
+ const rememberTransition = (key, admitted) => {
514
+ if (admitted.cost > topologySnapshotLimit) return;
515
+ if (!transitions.has(key)) transitions.set(key, void 0);
516
+ else if (transitions.get(key) !== admitted) transitions.set(key, admitted);
517
+ while (transitions.size > topologyTransitionLimit) {
518
+ const oldest = transitions.keys().next().value;
519
+ if (oldest === void 0) break;
484
520
  transitions.delete(oldest);
485
- transitionAges.delete(oldest);
486
521
  }
487
522
  };
488
523
  const publishedVoltages = new Array(nodes.length);
@@ -494,13 +529,16 @@ function createElectricalNetwork(inputPins, inputNets) {
494
529
  const updatedSlots = [];
495
530
  const updatedIntents = [];
496
531
  const updatedEdges = [];
532
+ /** Dirty edges indexed by slot, so rebinding avoids a Map lookup per block edge. */
533
+ const updatedEdgeLists = new Array(pins.length);
534
+ const updatedEdgeSlots = [];
497
535
  const replacedEdges = [];
498
536
  const pendingPins = [];
499
537
  const pendingSamples = [];
500
538
  const seenSlots = new Int32Array(pins.length);
501
539
  let seenStamp = 0;
502
- let preparedStale = false;
503
- let descriptorsStale = false;
540
+ /** Only the matrix partition is out of date; component arrays and buckets stay valid. */
541
+ let blocksStale = false;
504
542
  /** Component arrays are copied before a local update mutates them, because admitted
505
543
  * topology snapshots keep referencing the arrays they were created with. */
506
544
  let componentArraysOwned = false;
@@ -522,7 +560,8 @@ function createElectricalNetwork(inputPins, inputNets) {
522
560
  factorizationReuses: 0,
523
561
  cacheHits: 0,
524
562
  leafPlans: 0,
525
- leafPropagations: 0
563
+ leafPropagations: 0,
564
+ topologyPrepares: 0
526
565
  };
527
566
  const emptySlots = Object.freeze([]);
528
567
  /** Dirty slots supplied by the caller, deduplicated in place without an iterator per pin. */
@@ -570,7 +609,7 @@ function createElectricalNetwork(inputPins, inputNets) {
570
609
  * Records `(pin, target, resistance)` once the general path proved the shape: one branch
571
610
  * from a leaf node straight onto a fixed reference. Replays are only allowed while the
572
611
  * intent still names that branch, the pin still has one incident edge, the pin node is
573
- * still an unknown leaf and the target component is still uniformly referenced.
612
+ * still an unknown leaf and the target node still carries a fixed potential.
574
613
  */
575
614
  const pinLevel = (pin, voltage) => pin.low === void 0 ? "unknown" : voltage <= pin.low ? "low" : voltage >= pin.high ? "high" : "unknown";
576
615
  /**
@@ -626,8 +665,7 @@ function createElectricalNetwork(inputPins, inputNets) {
626
665
  pendingAdmissions.length = 0;
627
666
  };
628
667
  const matchLeaf = (slot, intent) => {
629
- const topology = prepared;
630
- if (topology === void 0 || intent.length !== 1) return void 0;
668
+ if (prepared === void 0 || intent.length !== 1) return void 0;
631
669
  const plans = leafPlans[slot];
632
670
  if (plans === void 0) return void 0;
633
671
  const previous = pinEdges[slot];
@@ -638,7 +676,7 @@ function createElectricalNetwork(inputPins, inputNets) {
638
676
  for (let index = 0; index < plans.length; index++) {
639
677
  const plan = plans[index];
640
678
  if (plan.targetPin !== branch.to || plan.resistance !== branch.resistance) continue;
641
- return topology.nodeUniform[plan.target] === 1 ? plan : void 0;
679
+ return nodes[plan.target].reference === void 0 ? void 0 : plan;
642
680
  }
643
681
  };
644
682
  /**
@@ -717,9 +755,11 @@ function createElectricalNetwork(inputPins, inputNets) {
717
755
  nodeDegree[target] = nodeDegree[target] + 1;
718
756
  }
719
757
  intents[slot] = leafIntents[position];
720
- pinEdges[slot] = leafEdges[position];
758
+ const edges = leafEdges[position];
759
+ pinEdges[slot] = edges;
760
+ setPinHash(slot, edges);
721
761
  }
722
- preparedStale = true;
762
+ blocksStale = true;
723
763
  statistics.solves++;
724
764
  statistics.leafPropagations++;
725
765
  };
@@ -792,7 +832,7 @@ function createElectricalNetwork(inputPins, inputNets) {
792
832
  function runSolve(input) {
793
833
  const initial = prepared === void 0;
794
834
  pendingAdmissions.length = 0;
795
- if (prepared !== void 0 && !preparedStale && input !== void 0 && input.length === 0) {
835
+ if (prepared !== void 0 && !blocksStale && input !== void 0 && input.length === 0) {
796
836
  statistics.solves++;
797
837
  statistics.cacheHits += prepared.blocks.length;
798
838
  return emptySlots;
@@ -876,13 +916,6 @@ function createElectricalNetwork(inputPins, inputNets) {
876
916
  updatedIntents.push(intent);
877
917
  updatedEdges.push(edges);
878
918
  }
879
- if (leafSwitch && topologyChanged) {
880
- const nodeUniform = prepared.nodeUniform;
881
- for (let position = 0; position < updatedSlots.length; position++) if (nodeUniform[updatedEdges[position][0].to] !== 1) {
882
- leafSwitch = false;
883
- break;
884
- }
885
- }
886
919
  if (leafSwitch && topologyChanged) {
887
920
  for (let position = 0; position < updatedSlots.length; position++) {
888
921
  leafSlots[position] = updatedSlots[position];
@@ -895,15 +928,9 @@ function createElectricalNetwork(inputPins, inputNets) {
895
928
  applyLeaf(updatedSlots.length);
896
929
  return changedSlots.length === 0 ? emptySlots : changedSlots;
897
930
  }
898
- if (preparedStale) {
899
- prepared = void 0;
900
- preparedStale = false;
901
- descriptorsStale = true;
902
- snapshot = void 0;
931
+ if (blocksStale) {
932
+ blocksStale = false;
903
933
  cache = /* @__PURE__ */ new Map();
904
- transitions.clear();
905
- transitionAges.clear();
906
- transitionClock = 0;
907
934
  topologyChanged = true;
908
935
  }
909
936
  const updates = /* @__PURE__ */ new Map();
@@ -922,25 +949,33 @@ function createElectricalNetwork(inputPins, inputNets) {
922
949
  return emptySlots;
923
950
  }
924
951
  let topology = prepared;
925
- let transitionKey;
926
- let nextDescriptions;
952
+ let bucket;
927
953
  let restored;
928
954
  const dirtyBlocks = /* @__PURE__ */ new Map();
955
+ for (let position = 0; position < updatedEdgeSlots.length; position++) updatedEdgeLists[updatedEdgeSlots[position]] = void 0;
956
+ updatedEdgeSlots.length = 0;
957
+ for (const [index, update] of updates) {
958
+ updatedEdgeLists[index] = update.edges;
959
+ updatedEdgeSlots.push(index);
960
+ }
929
961
  if (topologyChanged) {
930
- if (descriptorsStale) {
931
- descriptorsStale = false;
932
- nextDescriptions = pinEdges.map((edges, index) => describeEdges(updates.get(index)?.edges ?? edges));
933
- } else {
934
- nextDescriptions = pinDescriptions.slice();
935
- for (const [index, update] of updates) nextDescriptions[index] = describeEdges(update.edges);
962
+ let hash = topologyHash;
963
+ let spread = topologySpread;
964
+ for (const [index, update] of updates) {
965
+ const next = hashEdges(index, update.edges);
966
+ const previous = pinHashes[index];
967
+ if (next === previous) continue;
968
+ hash += next - previous;
969
+ spread ^= previous ^ next;
936
970
  }
937
- transitionKey = nextDescriptions.join(";");
938
- restored = transitions.get(transitionKey);
939
- if (restored !== void 0) topology = restoreTopology(restored.topology, pinEdges, updates);
971
+ bucket = `${hash}:${spread}`;
972
+ restored = lookupTransition(bucket, updatedEdgeLists);
973
+ if (restored !== void 0) topology = restoreTopology(restored.topology, pinEdges, updatedEdgeLists);
940
974
  else {
941
975
  const nextEdges = pinEdges.slice();
942
976
  for (const [index, update] of updates) nextEdges[index] = update.edges;
943
977
  topology = prepareTopology(nodes, nextEdges);
978
+ statistics.topologyPrepares++;
944
979
  }
945
980
  } else {
946
981
  const dirty = /* @__PURE__ */ new Set();
@@ -948,9 +983,9 @@ function createElectricalNetwork(inputPins, inputNets) {
948
983
  const index = topology.edgeBlocks[edge.pin]?.[edge.index];
949
984
  if (index !== void 0) dirty.add(index);
950
985
  }
951
- for (const index of dirty) dirtyBlocks.set(index, rebindBlock(topology.blocks[index], pinEdges, updates));
986
+ for (const index of dirty) dirtyBlocks.set(index, rebindBlock(topology.blocks[index], pinEdges, updatedEdgeLists));
952
987
  }
953
- const nextCache = /* @__PURE__ */ new Map();
988
+ let nextCache;
954
989
  const pendingVoltages = /* @__PURE__ */ new Map();
955
990
  let factorizations = 0;
956
991
  let factorizationReuses = 0;
@@ -960,7 +995,7 @@ function createElectricalNetwork(inputPins, inputNets) {
960
995
  const previous = cache.get(key);
961
996
  if (previous !== void 0 && sameConfiguration(previous, component)) {
962
997
  cacheHits++;
963
- nextCache.set(key, previous);
998
+ (nextCache ??= /* @__PURE__ */ new Map()).set(key, previous);
964
999
  continue;
965
1000
  }
966
1001
  const voltages = new Map(component.nodes.map((node) => [node, nodes[node].reference ?? null]));
@@ -1004,7 +1039,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1004
1039
  referenceProgram = compileReferenceProgram(unknown, component.edges, slots, nodes);
1005
1040
  if (referenceProgram !== void 0) {
1006
1041
  referencePrograms.push(referenceProgram);
1007
- if (referencePrograms.length > topologyTransitionLimit) referencePrograms.shift();
1042
+ if (referencePrograms.length > referenceProgramLimit) referencePrograms.shift();
1008
1043
  }
1009
1044
  }
1010
1045
  }
@@ -1047,11 +1082,12 @@ function createElectricalNetwork(inputPins, inputNets) {
1047
1082
  });
1048
1083
  }
1049
1084
  }
1050
- nextCache.set(key, {
1085
+ const entry = {
1051
1086
  edges: component.edges,
1052
1087
  voltages: component.nodes.map((node) => voltages.get(node)),
1053
1088
  factorization
1054
- });
1089
+ };
1090
+ (nextCache ??= /* @__PURE__ */ new Map()).set(key, entry);
1055
1091
  for (const [node, voltage] of voltages) if (publishedVoltages[node] !== voltage) pendingVoltages.set(node, voltage);
1056
1092
  }
1057
1093
  const pending = /* @__PURE__ */ new Map();
@@ -1080,22 +1116,23 @@ function createElectricalNetwork(inputPins, inputNets) {
1080
1116
  syncDegrees(pinEdges[index], update.edges);
1081
1117
  intents[index] = update.intent;
1082
1118
  pinEdges[index] = update.edges;
1119
+ setPinHash(index, update.edges);
1083
1120
  }
1084
- if (topologyChanged) cache = nextCache;
1121
+ if (topologyChanged) cache = nextCache ?? /* @__PURE__ */ new Map();
1085
1122
  else {
1086
- for (const [key, value] of nextCache) cache.set(key, value);
1123
+ if (nextCache !== void 0) for (const [key, value] of nextCache) cache.set(key, value);
1087
1124
  for (const [index, block] of dirtyBlocks) topology.blocks[index] = block;
1088
1125
  }
1089
1126
  prepared = topology;
1090
1127
  componentArraysOwned = false;
1091
1128
  if (topologyChanged) {
1092
- pinDescriptions = nextDescriptions;
1093
- snapshot = restored !== void 0 && topology === restored.topology ? restored : {
1129
+ const admitted = restored !== void 0 && topology === restored.topology ? restored : {
1094
1130
  id: restored?.id ?? nextTopologyId++,
1095
1131
  cost: restored?.cost ?? topologyCost(topology),
1096
- topology
1132
+ topology,
1133
+ hashes: restored?.hashes ?? pinHashes.slice()
1097
1134
  };
1098
- rememberTransition(transitionKey, snapshot);
1135
+ rememberTransition(bucket, admitted);
1099
1136
  }
1100
1137
  statistics.solves++;
1101
1138
  statistics.components = topology.components;
@@ -1220,169 +1257,6 @@ var Fifo = class {
1220
1257
  }
1221
1258
  };
1222
1259
  //#endregion
1223
- //#region src/values.ts
1224
- function dataObject(value, fields) {
1225
- if (value === null || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("Expected a plain data object");
1226
- for (const key of Reflect.ownKeys(value)) {
1227
- if (!("value" in Object.getOwnPropertyDescriptor(value, key))) throw new TypeError("Accessor properties are not allowed");
1228
- if (typeof key !== "string" || fields && !fields.includes(key)) throw new TypeError(`Unknown field ${String(key)}`);
1229
- }
1230
- }
1231
- function finite(value, name = "value") {
1232
- if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError(`${name} must be finite`);
1233
- return value;
1234
- }
1235
- function integer(value, name = "value") {
1236
- if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError(`${name} must be a safe integer`);
1237
- return value;
1238
- }
1239
- function nonnegative(value, name = "value") {
1240
- const n = integer(value, name);
1241
- if (n < 0) throw new RangeError(`${name} must be nonnegative`);
1242
- return n;
1243
- }
1244
- function identity(value) {
1245
- if (typeof value !== "string" || value.length === 0) throw new TypeError("Expected a nonempty identifier");
1246
- return value;
1247
- }
1248
- function range(memory, offset, length) {
1249
- const at = nonnegative(offset, "offset");
1250
- const size = nonnegative(length, "length");
1251
- if (at > memory.length || size > memory.length - at) throw new RangeError("Memory range is out of bounds");
1252
- return at;
1253
- }
1254
- function same(a, b) {
1255
- if (a === b || typeof a === "number" && typeof b === "number" && Number.isNaN(a) && Number.isNaN(b)) return true;
1256
- if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
1257
- const left = Object.keys(a), right = Object.keys(b);
1258
- return left.length === right.length && left.every((key) => Object.hasOwn(b, key) && same(a[key], b[key]));
1259
- }
1260
- function snapshot(value) {
1261
- if (value === null || typeof value !== "object") return value;
1262
- if (value instanceof Uint8Array) return value.slice();
1263
- if (Array.isArray(value)) return Object.freeze(value.map(snapshot));
1264
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item)])));
1265
- }
1266
- function bytesView(bytes, check = () => {}) {
1267
- const target = Object.freeze({
1268
- get length() {
1269
- check();
1270
- return bytes.length;
1271
- },
1272
- get byteLength() {
1273
- check();
1274
- return bytes.length;
1275
- },
1276
- slice(start, end) {
1277
- check();
1278
- return bytes.slice(start, end);
1279
- },
1280
- *[Symbol.iterator]() {
1281
- for (let i = 0; i < bytes.length; i++) {
1282
- check();
1283
- yield bytes[i];
1284
- }
1285
- check();
1286
- }
1287
- });
1288
- return new Proxy(target, {
1289
- get(object, key, receiver) {
1290
- check();
1291
- if (typeof key === "string" && /^(0|[1-9]\d*)$/.test(key)) return bytes[Number(key)];
1292
- return Reflect.get(object, key, receiver);
1293
- },
1294
- set() {
1295
- throw new TypeError("Bytes are read-only");
1296
- },
1297
- defineProperty() {
1298
- throw new TypeError("Bytes are read-only");
1299
- }
1300
- });
1301
- }
1302
- function captureValue(type, value, declarations, property = false) {
1303
- if (type.kind === "optional") {
1304
- if (value === null) return null;
1305
- return captureValue(type.inner, value, declarations, property);
1306
- }
1307
- switch (type.kind) {
1308
- case "number":
1309
- if (typeof value !== "number") throw new TypeError("Expected number");
1310
- if (property && !Number.isFinite(value)) throw new TypeError("Property must be finite");
1311
- return value;
1312
- case "bool":
1313
- if (typeof value !== "boolean") throw new TypeError("Expected boolean");
1314
- return value;
1315
- case "string":
1316
- if (typeof value !== "string") throw new TypeError("Expected string");
1317
- return value;
1318
- case "bytes":
1319
- if (!(value instanceof Uint8Array)) throw new TypeError("Expected Uint8Array");
1320
- return value.slice();
1321
- case "enum": {
1322
- const members = type.name === "Logic" ? [
1323
- "low",
1324
- "high",
1325
- "unknown"
1326
- ] : type.name === "SampleStatus" ? ["valid", "floating"] : type.name === "Overflow" ? [
1327
- "drop_new",
1328
- "drop_oldest",
1329
- "error"
1330
- ] : declarations.get(type.name)?.members;
1331
- if (typeof value !== "string" || !members?.includes(value)) throw new TypeError(`Invalid ${type.name} member`);
1332
- return value;
1333
- }
1334
- case "record": {
1335
- dataObject(value);
1336
- const declaration = declarations.get(type.name);
1337
- return Object.freeze(Object.fromEntries(declaration.fields.map((field) => [field.name, captureValue({ kind: field.type }, value[field.name], declarations)])));
1338
- }
1339
- case "sample":
1340
- case "intent": return value;
1341
- }
1342
- }
1343
- function externalValue(value) {
1344
- if (value instanceof Uint8Array) return bytesView(value.slice());
1345
- return snapshot(value);
1346
- }
1347
- function randomState(seed, id, override) {
1348
- if (override !== void 0) {
1349
- if (!Array.isArray(override) || override.length !== 4) throw new TypeError("randomState must contain four words");
1350
- for (const word of override) {
1351
- integer(word);
1352
- if (word < 0 || word > 4294967295) throw new RangeError("randomState word out of range");
1353
- }
1354
- if (!override.some(Boolean)) throw new RangeError("randomState cannot be zero");
1355
- return Uint32Array.from(override);
1356
- }
1357
- let h = 2166136261;
1358
- const encoded = new TextEncoder().encode(id);
1359
- const source = new Uint8Array(4 + encoded.length);
1360
- new DataView(source.buffer).setUint32(0, seed, true);
1361
- source.set(encoded, 4);
1362
- for (const byte of source) h = Math.imul(h ^ byte, 16777619) >>> 0;
1363
- const result = /* @__PURE__ */ new Uint32Array(4);
1364
- for (let i = 0; i < 4; i++) {
1365
- h = h + 2654435769 >>> 0;
1366
- let z = Math.imul(h ^ h >>> 16, 2246822507) >>> 0;
1367
- z = Math.imul(z ^ z >>> 13, 3266489909) >>> 0;
1368
- result[i] = (z ^ z >>> 16) >>> 0;
1369
- }
1370
- if (!result.some(Boolean)) result[0] = 1;
1371
- return result;
1372
- }
1373
- function nextRandom(s) {
1374
- const rot = (x, k) => (x << k | x >>> 32 - k) >>> 0;
1375
- const result = Math.imul(rot(Math.imul(s[1], 5), 7), 9) >>> 0;
1376
- const t = s[1] << 9;
1377
- s[2] = s[2] ^ s[0];
1378
- s[3] = s[3] ^ s[1];
1379
- s[1] = s[1] ^ s[2];
1380
- s[0] = s[0] ^ s[3];
1381
- s[2] = s[2] ^ t;
1382
- s[3] = rot(s[3], 11);
1383
- return result / 4294967296;
1384
- }
1385
- //#endregion
1386
1260
  //#region src/observations.ts
1387
1261
  var unaryOperators = {
1388
1262
  positive: "+",
@@ -2733,6 +2607,7 @@ var Instance = class {
2733
2607
  "pc",
2734
2608
  "beforeInstruction",
2735
2609
  "polling",
2610
+ "delays",
2736
2611
  "translate"
2737
2612
  ]);
2738
2613
  identity(options.entry);
@@ -2757,6 +2632,7 @@ var Instance = class {
2757
2632
  polling.set(pc, predicate);
2758
2633
  }
2759
2634
  }
2635
+ if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
2760
2636
  const jit = {
2761
2637
  instance: this,
2762
2638
  options: Object.freeze({
@@ -2765,6 +2641,7 @@ var Instance = class {
2765
2641
  }),
2766
2642
  cache: /* @__PURE__ */ new Map(),
2767
2643
  polling,
2644
+ delays: options.delays ?? /* @__PURE__ */ new Map(),
2768
2645
  revision: 0,
2769
2646
  directRevision: -1,
2770
2647
  directObserverRevision: -1,
@@ -2892,6 +2769,44 @@ function isPollingInstruction(body, pc, pcName) {
2892
2769
  //#region src/runtime/jit.ts
2893
2770
  /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2894
2771
  var DIRECT_SHARD_SIZE = 8;
2772
+ var barriers = /* @__PURE__ */ new WeakMap();
2773
+ function directBarriers(jit) {
2774
+ let entry = barriers.get(jit);
2775
+ if (entry === void 0) {
2776
+ entry = {
2777
+ stateMask: [],
2778
+ memoryMask: []
2779
+ };
2780
+ barriers.set(jit, entry);
2781
+ }
2782
+ return entry;
2783
+ }
2784
+ function directStats(jit) {
2785
+ const counted = jit;
2786
+ return counted.directStats ??= {
2787
+ directCompiles: 0,
2788
+ directCalls: 0,
2789
+ directFallbacks: 0,
2790
+ directDeadlines: 0,
2791
+ directStopped: 0
2792
+ };
2793
+ }
2794
+ /** Publish the current guard sets into the masks the compiled blocks test at entry. */
2795
+ function syncDirectBarriers(jit) {
2796
+ const entry = directBarriers(jit);
2797
+ const { stateIndex, memoryIndex } = entry;
2798
+ if (stateIndex === void 0 || memoryIndex === void 0) return;
2799
+ const fill = (mask, index, guards) => {
2800
+ mask.fill(0);
2801
+ for (const name of guards) {
2802
+ const slot = index.get(name);
2803
+ if (slot === void 0) continue;
2804
+ mask[slot >>> 5] = (mask[slot >>> 5] ?? 0) | 1 << (slot & 31);
2805
+ }
2806
+ };
2807
+ fill(entry.stateMask, stateIndex, jit.directStateGuards);
2808
+ fill(entry.memoryMask, memoryIndex, jit.directMemoryGuards);
2809
+ }
2895
2810
  function refreshDirectGuards(jit, hookReads) {
2896
2811
  let changed = false;
2897
2812
  const instance = jit.instance;
@@ -2914,8 +2829,7 @@ function refreshDirectGuards(jit, hookReads) {
2914
2829
  changed = true;
2915
2830
  }
2916
2831
  if (changed) {
2917
- jit.direct = void 0;
2918
- jit.directRevision = -1;
2832
+ syncDirectBarriers(jit);
2919
2833
  jit.directSkip = void 0;
2920
2834
  }
2921
2835
  }
@@ -2963,7 +2877,7 @@ function directHost(board, instance, frame) {
2963
2877
  }
2964
2878
  };
2965
2879
  }
2966
- function createDirectFrame(board, instance, stateNames, memoryNames, program) {
2880
+ function createDirectFrame(board, instance, stateNames, memoryNames, program, barrier) {
2967
2881
  const frame = {
2968
2882
  states: new Array(stateNames.length),
2969
2883
  memories: memoryNames.map((name) => instance.memory(name)),
@@ -2975,6 +2889,8 @@ function createDirectFrame(board, instance, stateNames, memoryNames, program) {
2975
2889
  resume: 0
2976
2890
  };
2977
2891
  frame.host = directHost(board, instance, frame);
2892
+ frame.blockedStates = barrier.stateMask;
2893
+ frame.blockedMemories = barrier.memoryMask;
2978
2894
  return frame;
2979
2895
  }
2980
2896
  function runDirect(board, jit, hookReads) {
@@ -2990,7 +2906,7 @@ function runDirect(board, jit, hookReads) {
2990
2906
  jit.directPrograms.clear();
2991
2907
  jit.directProgramRevision = jit.revision;
2992
2908
  }
2993
- const key = JSON.stringify([[...jit.directStateGuards].sort(), [...jit.directMemoryGuards].sort()]);
2909
+ const key = JSON.stringify([...jit.delays.keys()].sort((left, right) => left - right));
2994
2910
  const cached = jit.directPrograms.get(key);
2995
2911
  if (cached) {
2996
2912
  jit.direct = cached;
@@ -3004,6 +2920,15 @@ function runDirect(board, jit, hookReads) {
3004
2920
  const states = new Map(stateNames.map((name, index) => [name, index]));
3005
2921
  const memories = new Map(memoryNames.map((name, index) => [name, index]));
3006
2922
  const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !jit.polling.has(instruction.pc));
2923
+ /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
2924
+ const delayLoops = /* @__PURE__ */ new Map();
2925
+ for (const [pc, delay] of jit.delays) {
2926
+ const counter = states.get(delay.counter);
2927
+ if (counter !== void 0) delayLoops.set(pc, {
2928
+ counter,
2929
+ cycles: delay.cycles
2930
+ });
2931
+ }
3007
2932
  const program = compileDirectJit(instructions, {
3008
2933
  states,
3009
2934
  memories,
@@ -3011,26 +2936,29 @@ function runDirect(board, jit, hookReads) {
3011
2936
  name: jit.options.pc,
3012
2937
  index: states.get(jit.options.pc)
3013
2938
  },
3014
- blockedStates: jit.directStateGuards,
3015
- blockedMemories: jit.directMemoryGuards,
3016
2939
  host: true,
3017
2940
  split: true,
3018
- shardSize: DIRECT_SHARD_SIZE
2941
+ shardSize: DIRECT_SHARD_SIZE,
2942
+ delayLoops
3019
2943
  });
3020
2944
  jit.directRevision = jit.revision;
2945
+ if (program) directStats(jit).directCompiles++;
2946
+ const barrier = directBarriers(jit);
2947
+ barrier.stateIndex = states;
2948
+ barrier.memoryIndex = memories;
2949
+ barrier.stateMask.length = Math.ceil(stateNames.length / 32);
2950
+ barrier.memoryMask.length = Math.ceil(memoryNames.length / 32);
2951
+ syncDirectBarriers(jit);
3021
2952
  jit.direct = program ? {
3022
2953
  program,
3023
2954
  stateReads: program.readStates.map((name) => [name, states.get(name)]),
3024
2955
  stateWrites: program.writeStates.map((name) => [name, states.get(name)]),
3025
2956
  memoryWrites: program.writeMemories.map((name) => [name, memories.get(name)]),
3026
2957
  revision: jit.revision,
3027
- frame: createDirectFrame(board, instance, stateNames, memoryNames, program)
2958
+ frame: createDirectFrame(board, instance, stateNames, memoryNames, program, barrier)
3028
2959
  } : void 0;
3029
2960
  if (!jit.direct) jit.directPrograms.delete(key);
3030
- else {
3031
- if (jit.directPrograms.size >= 8) jit.directPrograms.delete(jit.directPrograms.keys().next().value);
3032
- jit.directPrograms.set(key, jit.direct);
3033
- }
2961
+ else jit.directPrograms.set(key, jit.direct);
3034
2962
  }
3035
2963
  }
3036
2964
  if (!jit.direct) return false;
@@ -3044,18 +2972,29 @@ function runDirect(board, jit, hookReads) {
3044
2972
  frame.memoryDirty.fill(0);
3045
2973
  const start = board.time;
3046
2974
  let reason;
2975
+ let wrote = false;
2976
+ const stats = directStats(jit);
2977
+ stats.directCalls++;
3047
2978
  try {
3048
2979
  reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
3049
2980
  } finally {
3050
2981
  board.time = frame.time;
3051
- for (const [name, index] of direct.stateWrites) if ((frame.stateDirty[index >>> 5] & 1 << (index & 31)) !== 0) instance.host.write(name, frame.states[index]);
3052
- for (const [name, index] of direct.memoryWrites) if ((frame.memoryDirty[index >>> 5] & 1 << (index & 31)) !== 0) instance.memoryChanged(name);
2982
+ for (const [name, index] of direct.stateWrites) if ((frame.stateDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2983
+ instance.host.write(name, frame.states[index]);
2984
+ wrote = true;
2985
+ }
2986
+ for (const [name, index] of direct.memoryWrites) if ((frame.memoryDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2987
+ instance.memoryChanged(name);
2988
+ wrote = true;
2989
+ }
3053
2990
  }
3054
- board.boundary();
2991
+ if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
3055
2992
  if (reason === "fallback") {
2993
+ stats.directFallbacks++;
3056
2994
  jit.directSkip = finite(instance.states.get(jit.options.pc), "pc");
3057
2995
  if (board.time === start && board.time < board.executionEnd) return false;
3058
2996
  } else if (reason === "stopped") {
2997
+ stats.directStopped++;
3059
2998
  jit.stopped = true;
3060
2999
  return true;
3061
3000
  } else if (reason === "invalidated") {
@@ -3064,7 +3003,7 @@ function runDirect(board, jit, hookReads) {
3064
3003
  jit.direct = void 0;
3065
3004
  jit.directRevision = -1;
3066
3005
  }
3067
- }
3006
+ } else stats.directDeadlines++;
3068
3007
  if (frame.resume && frame.due > board.time) board.events.push(frame.due, () => board.queueJit(jit));
3069
3008
  else board.queueJit(jit);
3070
3009
  return true;
@@ -3296,6 +3235,8 @@ var BoardRuntime = class {
3296
3235
  errors = new Emitter();
3297
3236
  diagnostics = new Emitter();
3298
3237
  listeners = /* @__PURE__ */ new Set();
3238
+ /** Owner-less listeners of the shared set: the host's direct subscriptions on `topics`. */
3239
+ hostListeners = 0;
3299
3240
  models = new Fifo();
3300
3241
  events = new EventQueue();
3301
3242
  readyJits = new Fifo();
@@ -3554,7 +3495,11 @@ var BoardRuntime = class {
3554
3495
  this.fault(this.error("REPORTED_ERROR", cause instanceof Error ? cause.message : String(cause), instance, cause, "report"));
3555
3496
  }
3556
3497
  topicBridge(owner) {
3498
+ const hostListenerCount = () => this.hostListeners;
3557
3499
  return Object.freeze({
3500
+ get hostListenerCount() {
3501
+ return hostListenerCount();
3502
+ },
3558
3503
  onDidReceive: ((listener, thisArgs, disposables) => {
3559
3504
  this.guard(owner);
3560
3505
  const entry = {
@@ -3562,17 +3507,19 @@ var BoardRuntime = class {
3562
3507
  call: (message) => listener.call(thisArgs, message)
3563
3508
  };
3564
3509
  this.listeners.add(entry);
3510
+ if (!owner) this.hostListeners++;
3565
3511
  let active = true;
3566
3512
  const disposable = { dispose: () => {
3567
3513
  if (active) {
3568
3514
  active = false;
3569
- this.listeners.delete(entry);
3515
+ if (this.listeners.delete(entry) && !owner) this.hostListeners--;
3570
3516
  }
3571
3517
  } };
3572
3518
  disposables?.push(disposable);
3573
3519
  owner?.resources.push(disposable);
3574
3520
  return disposable;
3575
3521
  }),
3522
+ assertCanPublish: () => this.guard(owner),
3576
3523
  publish: (topic, payload) => {
3577
3524
  this.guard(owner);
3578
3525
  if (typeof topic !== "string") throw new TypeError("Topic must be a string");
@@ -4070,6 +4017,7 @@ var BoardRuntime = class {
4070
4017
  this.changeCurrent.length = 0;
4071
4018
  this.sampleSlots.clear();
4072
4019
  this.listeners.clear();
4020
+ this.hostListeners = 0;
4073
4021
  this.errors.dispose();
4074
4022
  this.diagnostics.dispose();
4075
4023
  this.status = "disposed";
@@ -4269,10 +4217,9 @@ function createSimulationRuntime(options = {}) {
4269
4217
  if (disposed) throw new SimulationRuntimeError("disposed", "Simulation runtime has been disposed");
4270
4218
  };
4271
4219
  const flush = (loaded) => {
4272
- for (const output of loaded.outputs.splice(0)) {
4273
- const topic = loaded.prepared.instances.find((entry) => entry.symbol === output.symbol).device.topics.get(output.port);
4274
- const key = targetKey(output.symbol, output.port);
4275
- if (topic.delivery === "level") {
4220
+ if (publishes.hasListeners) for (const output of loaded.outputs.splice(0)) {
4221
+ if (output.delivery === "level") {
4222
+ const key = targetKey(output.symbol, output.port);
4276
4223
  if (published.has(key) && samePayload(published.get(key), output.payload)) continue;
4277
4224
  if (publishes.hasListeners) published.set(key, copyPayload(output.payload));
4278
4225
  }
@@ -4281,10 +4228,11 @@ function createSimulationRuntime(options = {}) {
4281
4228
  symbol: output.symbol,
4282
4229
  port: output.port
4283
4230
  },
4284
- payload: copyPayload(output.payload),
4231
+ payload: output.payload,
4285
4232
  simTime
4286
4233
  });
4287
4234
  }
4235
+ else loaded.outputs.length = 0;
4288
4236
  for (const diagnostic of loaded.diagnostics.splice(0)) diagnostics.fire(diagnostic.runtimeCode === void 0 ? {
4289
4237
  ...diagnostic,
4290
4238
  simTime
@@ -4321,12 +4269,12 @@ function createSimulationRuntime(options = {}) {
4321
4269
  const prepared = await prepareSimulation(input, options.importer ?? importBlobModule, assertActive);
4322
4270
  assertActive();
4323
4271
  if (current !== generation) return;
4324
- install(buildLoadedRuntime(prepared));
4272
+ install(buildLoadedRuntime(prepared, () => publishes.hasListeners));
4325
4273
  },
4326
4274
  async reset() {
4327
4275
  assertActive();
4328
4276
  ++generation;
4329
- if (active !== void 0) install(buildLoadedRuntime(active.prepared));
4277
+ if (active !== void 0) install(buildLoadedRuntime(active.prepared, () => publishes.hasListeners));
4330
4278
  else {
4331
4279
  pending.length = 0;
4332
4280
  published.clear();
@@ -4389,7 +4337,7 @@ function createSimulationRuntime(options = {}) {
4389
4337
  }
4390
4338
  };
4391
4339
  }
4392
- function buildLoadedRuntime(prepared) {
4340
+ function buildLoadedRuntime(prepared, publishObserved) {
4393
4341
  const outputs = [];
4394
4342
  const found = [];
4395
4343
  const inputs = /* @__PURE__ */ new Map();
@@ -4400,7 +4348,7 @@ function buildLoadedRuntime(prepared) {
4400
4348
  model: instance.device.model,
4401
4349
  create: (context) => instance.device.create({
4402
4350
  ...context,
4403
- topics: scopeTopics(context.topics, instance, outputs, found)
4351
+ topics: scopeTopics(context.topics, instance, outputs, found, publishObserved)
4404
4352
  })
4405
4353
  };
4406
4354
  })), {
@@ -4429,19 +4377,47 @@ function buildLoadedRuntime(prepared) {
4429
4377
  subscriptions: [board.onDidError((event) => project(event, true)), board.onDidDiagnostic((event) => project(event, false))]
4430
4378
  };
4431
4379
  }
4432
- /** Board topics are opaque global strings; this boundary gives each factory local port names. */
4433
- function scopeTopics(bridge, instance, outputs, diagnostics) {
4380
+ /**
4381
+ * Board topics are opaque global strings; this boundary gives each factory local port names.
4382
+ *
4383
+ * Exported for the fan-out regression test, which drives it against a real `Board`: every accepted
4384
+ * output must still reach `board.topics` listeners even when the instance has no scoped subscriber.
4385
+ *
4386
+ * `publishObserved` reports whether anything outside the board consumes published messages; with no
4387
+ * scoped subscriber, no owner-less bridge listener and no consumer, an accepted output is dropped
4388
+ * before it is copied, fanned out or queued, while `assertCanPublish` keeps the publish guards.
4389
+ */
4390
+ function scopeTopics(bridge, instance, outputs, diagnostics, publishObserved) {
4434
4391
  const prefix = `${encodeURIComponent(instance.symbol)}/`;
4392
+ let scopedListeners = 0;
4393
+ const unobserved = () => scopedListeners === 0 && bridge.hostListenerCount === 0 && !publishObserved();
4435
4394
  return {
4436
- onDidReceive: ((listener, thisArgs, disposables) => bridge.onDidReceive((message) => {
4437
- if (!message.topic.startsWith(prefix)) return;
4438
- const port = message.topic.slice(prefix.length);
4439
- if (instance.device.topics.get(port)?.direction !== "input") return;
4440
- return listener.call(thisArgs, {
4441
- topic: port,
4442
- payload: copyPayload(message.payload)
4443
- });
4444
- }, void 0, disposables)),
4395
+ get hostListenerCount() {
4396
+ return bridge.hostListenerCount;
4397
+ },
4398
+ onDidReceive: ((listener, thisArgs, disposables) => {
4399
+ const subscription = bridge.onDidReceive((message) => {
4400
+ if (!message.topic.startsWith(prefix)) return;
4401
+ const port = message.topic.slice(prefix.length);
4402
+ if (instance.device.topics.get(port)?.direction !== "input") return;
4403
+ return listener.call(thisArgs, {
4404
+ topic: port,
4405
+ payload: copyPayload(message.payload)
4406
+ });
4407
+ }, void 0, void 0);
4408
+ scopedListeners++;
4409
+ let active = true;
4410
+ const disposable = { dispose: () => {
4411
+ if (active) {
4412
+ active = false;
4413
+ scopedListeners--;
4414
+ subscription.dispose();
4415
+ }
4416
+ } };
4417
+ disposables?.push(disposable);
4418
+ return disposable;
4419
+ }),
4420
+ assertCanPublish: () => bridge.assertCanPublish(),
4445
4421
  publish(port, payload) {
4446
4422
  const topic = instance.device.topics.get(port);
4447
4423
  if (topic?.direction !== "output" || !payloadMatches(topic.type, payload)) {
@@ -4454,12 +4430,17 @@ function scopeTopics(bridge, instance, outputs, diagnostics) {
4454
4430
  });
4455
4431
  return;
4456
4432
  }
4433
+ if (unobserved()) {
4434
+ bridge.assertCanPublish();
4435
+ return;
4436
+ }
4457
4437
  const snapshot = copyPayload(payload);
4458
4438
  bridge.publish(scopedTopic(instance.symbol, port), snapshot);
4459
4439
  outputs.push({
4460
4440
  symbol: instance.symbol,
4461
4441
  port,
4462
- payload: snapshot
4442
+ payload: snapshot,
4443
+ delivery: topic.delivery
4463
4444
  });
4464
4445
  }
4465
4446
  };