@mica-js/simulator 2.6.0 → 2.7.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
@@ -350,10 +350,6 @@ function substitute(factorization, right, fail) {
350
350
  }
351
351
  return solution;
352
352
  }
353
- /** Changed pins publish in ascending board slot order; slots are already that order. */
354
- function ascendingSlot(first, second) {
355
- return first - second;
356
- }
357
353
  function sumPair(first, second) {
358
354
  first = 0 + first;
359
355
  const total = first + second;
@@ -524,8 +520,6 @@ function createElectricalNetwork(inputPins, inputNets) {
524
520
  const updatedEdgeLists = new Array(pins.length);
525
521
  const updatedEdgeSlots = [];
526
522
  const replacedEdges = [];
527
- const pendingPins = [];
528
- const pendingSamples = [];
529
523
  const seenSlots = new Int32Array(pins.length);
530
524
  let seenStamp = 0;
531
525
  /** Only the matrix partition is out of date; component arrays and buckets stay valid. */
@@ -554,8 +548,14 @@ function createElectricalNetwork(inputPins, inputNets) {
554
548
  const emptySlots = Object.freeze([]);
555
549
  /** Dirty slots supplied by the caller, deduplicated in place without an iterator per pin. */
556
550
  const inputSlots = [];
557
- /** Changed pin slots of the last solve in ascending board order. */
551
+ /**
552
+ * Changed pin slots of the last solve, valid in `[0, changedCount)`. The leaf path
553
+ * collects them in visit order and orders them only for the entries that return an
554
+ * array; the board publication sink is a slot bitmap. The array keeps its high-water
555
+ * length so a new batch never pays for clearing it.
556
+ */
558
557
  const changedSlots = [];
558
+ let changedCount = 0;
559
559
  /** Admitted leaf shapes per pin slot; a pin normally alternates between two references. */
560
560
  const leafPlans = new Array(pins.length);
561
561
  /** Last topology check for the single-slot entry, independent of intent identity. */
@@ -685,16 +685,35 @@ function createElectricalNetwork(inputPins, inputNets) {
685
685
  }
686
686
  };
687
687
  /**
688
- * Inserts into an ascending list. A touched batch holds a handful of pins, so an
689
- * in-place insertion beats a comparator sort of the published slot order.
688
+ * Appends one changed slot. A whole corrected batch is ordered once, after collecting,
689
+ * so each leaf contributes its pins without paying for an insertion pass per pin.
690
690
  */
691
- const pushOrdered = (list, slot) => {
692
- let position = list.length;
693
- while (position > 0 && list[position - 1] > slot) {
694
- list[position] = list[position - 1];
695
- position--;
691
+ const pushChanged = (slot) => {
692
+ changedSlots[changedCount++] = slot;
693
+ };
694
+ /** Restores the ascending board order the public entries promise; callers opt in. */
695
+ const sortChanged = () => {
696
+ for (let index = 1; index < changedCount; index++) {
697
+ const slot = changedSlots[index];
698
+ let position = index;
699
+ while (position > 0 && changedSlots[position - 1] > slot) {
700
+ changedSlots[position] = changedSlots[position - 1];
701
+ position--;
702
+ }
703
+ changedSlots[position] = slot;
696
704
  }
697
- list[position] = slot;
705
+ };
706
+ /** Hands every published slot to the board. The consumer is a slot bitmap. */
707
+ const emitChanged = (publish) => {
708
+ for (let index = 0; index < changedCount; index++) publish(changedSlots[index]);
709
+ };
710
+ /** A fresh ascending copy for the public solve entries; the buffer is reused. */
711
+ const copyChanged = () => {
712
+ if (changedCount === 0) return emptySlots;
713
+ sortChanged();
714
+ const result = new Array(changedCount);
715
+ for (let index = 0; index < changedCount; index++) result[index] = changedSlots[index];
716
+ return result;
698
717
  };
699
718
  const commitLeafEdges = (slot, target, voltage, intent, edges, precomputedHash) => {
700
719
  const previousTarget = pinEdges[slot][0].to;
@@ -725,68 +744,49 @@ function createElectricalNetwork(inputPins, inputNets) {
725
744
  */
726
745
  const applySingleLeaf = (slot, intent, plan) => {
727
746
  const { node, target, voltage } = plan;
728
- let result = emptySlots;
747
+ changedCount = 0;
729
748
  if (publishedVoltages[node] !== voltage) {
730
749
  const planPins = plan.pins;
731
750
  const planSamples = plan.samples;
732
- if (planPins.length === 1) {
733
- const pin = planPins[0];
734
- const sample = planSamples[0];
735
- if (pin.sample !== sample) {
736
- pin.sample = sample;
737
- result = plan.slots;
738
- }
739
- } else {
740
- let all = true;
741
- let changed = 0;
742
- for (let index = 0; index < planPins.length; index++) {
743
- const pin = planPins[index];
744
- const sample = planSamples[index];
745
- if (pin.sample === sample) {
746
- all = false;
747
- continue;
748
- }
749
- pin.sample = sample;
750
- changedSlots[changed++] = plan.slots[index];
751
- }
752
- if (all) result = plan.slots;
753
- else if (changed !== 0) {
754
- changedSlots.length = changed;
755
- result = changedSlots;
756
- }
751
+ const planSlots = plan.slots;
752
+ for (let index = 0; index < planPins.length; index++) {
753
+ const pin = planPins[index];
754
+ const sample = planSamples[index];
755
+ if (pin.sample === sample) continue;
756
+ pin.sample = sample;
757
+ changedSlots[changedCount++] = planSlots[index];
757
758
  }
758
759
  }
759
760
  commitLeafEdges(slot, target, voltage, intent, plan.edges, plan.edgeHash);
760
761
  finishLeaf();
761
- return result;
762
762
  };
763
763
  /**
764
- * Publishes the accepted leaf batch: every pin on a touched node gets the reference
765
- * voltage, samples are committed as one batch, then intents, edges and degrees follow.
766
- * No pin, sample, intent or degree changes before the whole batch is accepted.
764
+ * Publishes the accepted leaf batch. The caller has already matched every dirty slot to
765
+ * an admitted shape (or proven the shapes below through the general solver), so each
766
+ * pin's sample is an independent function of its node's fixed reference: committing them
767
+ * in place is atomic. Slots are collected in visit order and ordered only when a public
768
+ * entry asks for the ascending array.
767
769
  */
768
770
  const applyLeaf = (count) => {
769
- changedSlots.length = 0;
770
- pendingPins.length = 0;
771
- pendingSamples.length = 0;
771
+ changedCount = 0;
772
772
  for (let position = 0; position < count; position++) {
773
773
  const node = pinNodes[leafSlots[position]];
774
- const target = leafTargets[position];
775
774
  const plan = leafPayloads[position];
776
775
  if (plan !== void 0) {
777
776
  if (publishedVoltages[node] === plan.voltage) continue;
778
777
  const planSlots = plan.slots;
778
+ const planPins = plan.pins;
779
+ const planSamples = plan.samples;
779
780
  for (let at = 0; at < planSlots.length; at++) {
780
- const pinned = plan.pins[at];
781
- const sample = plan.samples[at];
781
+ const pinned = planPins[at];
782
+ const sample = planSamples[at];
782
783
  if (pinned.sample === sample) continue;
783
- pushOrdered(changedSlots, planSlots[at]);
784
- pendingPins.push(pinned);
785
- pendingSamples.push(sample);
784
+ pinned.sample = sample;
785
+ pushChanged(planSlots[at]);
786
786
  }
787
787
  continue;
788
788
  }
789
- const voltage = nodes[target].reference;
789
+ const voltage = nodes[leafTargets[position]].reference;
790
790
  if (publishedVoltages[node] === voltage) continue;
791
791
  const slots = nodeSlots[node];
792
792
  for (let at = 0; at < slots.length; at++) {
@@ -794,14 +794,11 @@ function createElectricalNetwork(inputPins, inputNets) {
794
794
  const pin = pins[slot];
795
795
  const level = pin.low === void 0 ? "unknown" : voltage <= pin.low ? "low" : voltage >= pin.high ? "high" : "unknown";
796
796
  const previous = pin.sample;
797
- if (previous.voltage !== voltage || previous.level !== level || previous.status !== "valid") {
798
- pushOrdered(changedSlots, slot);
799
- pendingPins.push(pin);
800
- pendingSamples.push(sampleFor(voltage, level));
801
- }
797
+ if (previous.voltage === voltage && previous.level === level && previous.status === "valid") continue;
798
+ pin.sample = sampleFor(voltage, level);
799
+ pushChanged(slot);
802
800
  }
803
801
  }
804
- for (let position = 0; position < pendingPins.length; position++) pendingPins[position].sample = pendingSamples[position];
805
802
  for (let position = 0; position < count; position++) {
806
803
  const slot = leafSlots[position];
807
804
  const target = leafTargets[position];
@@ -809,7 +806,8 @@ function createElectricalNetwork(inputPins, inputNets) {
809
806
  }
810
807
  finishLeaf();
811
808
  };
812
- function solveSlot(slot) {
809
+ /** One complete single-slot dirty batch; leaves the publication buffer filled. */
810
+ function solveSingleSlot(slot) {
813
811
  const plans = leafPlans[slot];
814
812
  if (plans !== void 0) {
815
813
  const intent = pins[slot].intent;
@@ -817,69 +815,119 @@ function createElectricalNetwork(inputPins, inputNets) {
817
815
  if (leafEpochs[slot] === leafEpoch) {
818
816
  const first = plans[0];
819
817
  const plan = first.intent === intent ? first : plans[1];
820
- if (plan?.intent === intent) return applySingleLeaf(slot, intent, plan);
818
+ if (plan?.intent === intent) {
819
+ applySingleLeaf(slot, intent, plan);
820
+ return;
821
+ }
821
822
  }
822
823
  const plan = matchLeaf(slot, intent);
823
824
  if (plan !== void 0) {
824
825
  leafEpochs[slot] = leafEpoch;
825
- return applySingleLeaf(slot, intent, plan);
826
+ applySingleLeaf(slot, intent, plan);
827
+ return;
826
828
  }
827
829
  }
828
830
  }
829
831
  inputSlots[0] = slot;
830
832
  inputSlots.length = 1;
831
- return runSolve(inputSlots);
833
+ runSolve(inputSlots);
834
+ }
835
+ /**
836
+ * One admitted-shape probe over `slots[0, length)`. A slot whose shape this epoch already
837
+ * proved resolves through the same two-plan pointer comparison as `solveSingleSlot`; only
838
+ * the first switch of a shape pays for `matchLeaf`. Any slot without an admitted shape
839
+ * hands the whole batch to the general solver, which repeats the match.
840
+ */
841
+ function solveBatch(slots, length) {
842
+ if (prepared !== void 0) {
843
+ const stamp = nextStamp();
844
+ let count = 0;
845
+ let complete = true;
846
+ for (let position = 0; position < length; position++) {
847
+ const slot = slots[position];
848
+ if (seenSlots[slot] === stamp) continue;
849
+ seenSlots[slot] = stamp;
850
+ const intent = pins[slot].intent;
851
+ if (intent === intents[slot]) continue;
852
+ let plan;
853
+ if (leafEpochs[slot] === leafEpoch) {
854
+ const plans = leafPlans[slot];
855
+ const first = plans[0];
856
+ const cached = first.intent === intent ? first : plans[1];
857
+ if (cached?.intent === intent) plan = cached;
858
+ }
859
+ if (plan === void 0) {
860
+ plan = matchLeaf(slot, intent);
861
+ if (plan === void 0) {
862
+ complete = false;
863
+ break;
864
+ }
865
+ leafEpochs[slot] = leafEpoch;
866
+ }
867
+ leafSlots[count] = slot;
868
+ leafIntents[count] = intent;
869
+ leafEdges[count] = plan.edges;
870
+ leafTargets[count] = plan.target;
871
+ leafPayloads[count] = plan;
872
+ count++;
873
+ }
874
+ if (complete) {
875
+ if (count === 0) {
876
+ fillInput(slots, length);
877
+ runSolve(inputSlots);
878
+ return;
879
+ }
880
+ applyLeaf(count);
881
+ return;
882
+ }
883
+ }
884
+ fillInput(slots, length);
885
+ runSolve(inputSlots);
886
+ }
887
+ /** Board-facing single-slot entry: solves and publishes without an intermediate array. */
888
+ function solveSlotInto(slot, publish) {
889
+ solveSingleSlot(slot);
890
+ if (publish !== void 0 && changedCount !== 0) emitChanged(publish);
891
+ }
892
+ /** Board-facing batch entry: solves and publishes without an intermediate array. */
893
+ function solveSlotBatchInto(slots, count, publish) {
894
+ solveBatch(slots, count);
895
+ if (publish !== void 0 && changedCount !== 0) emitChanged(publish);
832
896
  }
833
897
  return {
834
898
  get stats() {
835
899
  return Object.freeze({ ...statistics });
836
900
  },
837
901
  solve(changedPins) {
838
- const changed = runSolve(gatherPins(changedPins));
839
- if (changed.length === 0) return unchangedPins;
902
+ runSolve(gatherPins(changedPins));
903
+ if (changedCount === 0) return unchangedPins;
904
+ sortChanged();
840
905
  const published = [];
841
- for (let position = 0; position < changed.length; position++) published.push(pins[changed[position]]);
906
+ for (let position = 0; position < changedCount; position++) published.push(pins[changedSlots[position]]);
842
907
  return Object.freeze(published);
843
908
  },
844
- solveSlot,
909
+ solveSlot(slot) {
910
+ solveSingleSlot(slot);
911
+ return copyChanged();
912
+ },
913
+ solveSlotInto,
914
+ solveSlotBatchInto,
845
915
  solveSlots(changedSlotNumbers) {
846
- if (typeof changedSlotNumbers === "number") return solveSlot(changedSlotNumbers);
847
- if (changedSlotNumbers === void 0) return runSolve(void 0);
848
- const reusable = changedSlotNumbers instanceof Set || Array.isArray(changedSlotNumbers) || ArrayBuffer.isView(changedSlotNumbers) && Symbol.iterator in changedSlotNumbers;
849
- if (!reusable) {
850
- inputSlots.length = 0;
851
- for (const slot of changedSlotNumbers) inputSlots.push(slot);
916
+ if (typeof changedSlotNumbers === "number") {
917
+ solveSingleSlot(changedSlotNumbers);
918
+ return copyChanged();
852
919
  }
853
- const probe = reusable ? changedSlotNumbers : inputSlots;
854
- const gathered = () => reusable ? gatherSlots(changedSlotNumbers) : inputSlots;
855
- if (prepared !== void 0) {
856
- const stamp = nextStamp();
857
- let count = 0;
858
- let complete = true;
859
- for (const slot of probe) {
860
- if (seenSlots[slot] === stamp) continue;
861
- seenSlots[slot] = stamp;
862
- const intent = pins[slot].intent;
863
- if (intent === intents[slot]) continue;
864
- const plan = matchLeaf(slot, intent);
865
- if (plan === void 0) {
866
- complete = false;
867
- break;
868
- }
869
- leafSlots[count] = slot;
870
- leafIntents[count] = intent;
871
- leafEdges[count] = plan.edges;
872
- leafTargets[count] = plan.target;
873
- leafPayloads[count] = plan;
874
- count++;
875
- }
876
- if (complete) {
877
- if (count === 0) return runSolve(gathered());
878
- applyLeaf(count);
879
- return changedSlots.length === 0 ? emptySlots : changedSlots;
880
- }
920
+ if (changedSlotNumbers === void 0) {
921
+ runSolve(void 0);
922
+ return copyChanged();
881
923
  }
882
- return runSolve(gathered());
924
+ inputSlots.length = 0;
925
+ if (Array.isArray(changedSlotNumbers) || ArrayBuffer.isView(changedSlotNumbers) && Symbol.iterator in changedSlotNumbers) {
926
+ const indexed = changedSlotNumbers;
927
+ for (let position = 0; position < indexed.length; position++) inputSlots.push(indexed[position]);
928
+ } else for (const slot of changedSlotNumbers) inputSlots.push(slot);
929
+ solveBatch(inputSlots, inputSlots.length);
930
+ return copyChanged();
883
931
  }
884
932
  };
885
933
  function gatherPins(changedPins) {
@@ -888,15 +936,14 @@ function createElectricalNetwork(inputPins, inputNets) {
888
936
  for (const pin of changedPins) inputSlots.push(requirePin(pin));
889
937
  return inputSlots;
890
938
  }
891
- function gatherSlots(changedSlotNumbers) {
892
- if (changedSlotNumbers === void 0) return void 0;
893
- inputSlots.length = 0;
894
- for (const slot of changedSlotNumbers) inputSlots.push(slot);
895
- return inputSlots;
939
+ /** Places a caller-supplied batch into the solver input buffer without allocating. */
940
+ function fillInput(slots, length) {
941
+ inputSlots.length = length;
942
+ for (let position = 0; position < length; position++) inputSlots[position] = slots[position];
896
943
  }
897
944
  /**
898
945
  * One atomically published solve over `input` (dirty slots) or, when it is omitted, over
899
- * every pin. Returns the changed slots in ascending board order.
946
+ * every pin. The published slots end up in the ascending buffer.
900
947
  */
901
948
  function runSolve(input) {
902
949
  if (++leafEpoch === 2147483647) {
@@ -905,10 +952,11 @@ function createElectricalNetwork(inputPins, inputNets) {
905
952
  }
906
953
  const initial = prepared === void 0;
907
954
  pendingAdmissions.length = 0;
955
+ changedCount = 0;
908
956
  if (prepared !== void 0 && !blocksStale && input !== void 0 && input.length === 0) {
909
957
  statistics.solves++;
910
958
  statistics.cacheHits += prepared.blocks.length;
911
- return emptySlots;
959
+ return;
912
960
  }
913
961
  updatedSlots.length = 0;
914
962
  updatedIntents.length = 0;
@@ -939,7 +987,7 @@ function createElectricalNetwork(inputPins, inputNets) {
939
987
  }
940
988
  if (count > 0) {
941
989
  applyLeaf(count);
942
- return changedSlots.length === 0 ? emptySlots : changedSlots;
990
+ return;
943
991
  }
944
992
  stamp = nextStamp();
945
993
  }
@@ -1000,7 +1048,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1000
1048
  }
1001
1049
  flushAdmissions();
1002
1050
  applyLeaf(updatedSlots.length);
1003
- return changedSlots.length === 0 ? emptySlots : changedSlots;
1051
+ return;
1004
1052
  }
1005
1053
  if (blocksStale) topologyChanged = true;
1006
1054
  const updated = updatedSlots.length;
@@ -1013,7 +1061,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1013
1061
  statistics.solves++;
1014
1062
  statistics.cacheHits += prepared.blocks.length;
1015
1063
  flushAdmissions();
1016
- return emptySlots;
1064
+ return;
1017
1065
  }
1018
1066
  let topology = prepared;
1019
1067
  let bucket;
@@ -1164,7 +1212,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1164
1212
  for (const [node, voltage] of voltages) if (publishedVoltages[node] !== voltage) pendingVoltages.set(node, voltage);
1165
1213
  }
1166
1214
  const pending = /* @__PURE__ */ new Map();
1167
- changedSlots.length = 0;
1215
+ changedCount = 0;
1168
1216
  for (const [node, voltage] of pendingVoltages) {
1169
1217
  const slots = nodeSlots[node];
1170
1218
  for (let at = 0; at < slots.length; at++) {
@@ -1174,7 +1222,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1174
1222
  const status = voltage === null ? "floating" : "valid";
1175
1223
  const previous = pin.sample;
1176
1224
  const dirty = previous.voltage !== voltage || previous.level !== level || previous.status !== status;
1177
- if (dirty) changedSlots.push(slot);
1225
+ if (dirty) changedSlots[changedCount++] = slot;
1178
1226
  if (dirty || statistics.solves === 0) pending.set(pin, Object.freeze({
1179
1227
  voltage: voltage === null ? null : cleanZero(voltage),
1180
1228
  level,
@@ -1182,7 +1230,15 @@ function createElectricalNetwork(inputPins, inputNets) {
1182
1230
  }));
1183
1231
  }
1184
1232
  }
1185
- if (changedSlots.length > 1) changedSlots.sort(ascendingSlot);
1233
+ for (let index = 1; index < changedCount; index++) {
1234
+ const slot = changedSlots[index];
1235
+ let position = index;
1236
+ while (position > 0 && changedSlots[position - 1] > slot) {
1237
+ changedSlots[position] = changedSlots[position - 1];
1238
+ position--;
1239
+ }
1240
+ changedSlots[position] = slot;
1241
+ }
1186
1242
  for (const [pin, sample] of pending) pin.sample = sample;
1187
1243
  for (const [node, voltage] of pendingVoltages) publishedVoltages[node] = voltage;
1188
1244
  for (let position = 0; position < updated; position++) {
@@ -1217,63 +1273,101 @@ function createElectricalNetwork(inputPins, inputNets) {
1217
1273
  statistics.cacheHits += cacheHits;
1218
1274
  statistics.topologyPrepares += topologyPrepares;
1219
1275
  flushAdmissions();
1220
- return changedSlots.length === 0 ? emptySlots : changedSlots;
1221
1276
  }
1222
1277
  }
1223
1278
  //#endregion
1224
1279
  //#region src/queue.ts
1280
+ /**
1281
+ * Binary min-heap over parallel arrays. Every push/pop used to allocate a `{ time, order,
1282
+ * value }` record; a timed board pushes one continuation per suspension, so the flat form
1283
+ * keeps the scheduler loop allocation-free.
1284
+ */
1225
1285
  var EventQueue = class {
1226
- heap = [];
1286
+ times = [];
1287
+ orders = [];
1288
+ values = [];
1289
+ size = 0;
1227
1290
  sequence = 0;
1228
1291
  get time() {
1229
- return this.heap[0]?.time ?? Infinity;
1292
+ return this.size === 0 ? Infinity : this.times[0];
1230
1293
  }
1231
1294
  push(time, value) {
1232
- const task = {
1233
- time,
1234
- order: this.sequence++,
1235
- value
1236
- };
1237
- let at = this.heap.length;
1238
- this.heap.push(task);
1239
- while (at > 0) {
1240
- const parent = at - 1 >>> 1;
1241
- if (!this.before(task, this.heap[parent])) break;
1242
- this.heap[at] = this.heap[parent];
1243
- at = parent;
1244
- }
1245
- this.heap[at] = task;
1295
+ const at = this.size++;
1296
+ this.times[at] = time;
1297
+ this.orders[at] = this.sequence++;
1298
+ this.values[at] = value;
1299
+ this.siftUp(at);
1246
1300
  }
1247
1301
  pop() {
1248
- const first = this.heap[0];
1249
- const last = this.heap.pop();
1250
- if (this.heap.length) {
1251
- let at = 0;
1252
- while (at * 2 + 1 < this.heap.length) {
1253
- let child = at * 2 + 1;
1254
- if (child + 1 < this.heap.length && this.before(this.heap[child + 1], this.heap[child])) child++;
1255
- if (!this.before(this.heap[child], last)) break;
1256
- this.heap[at] = this.heap[child];
1257
- at = child;
1258
- }
1259
- this.heap[at] = last;
1302
+ const value = this.values[0];
1303
+ const last = --this.size;
1304
+ if (last >= 0) {
1305
+ this.times[0] = this.times[last];
1306
+ this.orders[0] = this.orders[last];
1307
+ this.values[0] = this.values[last];
1308
+ this.times[last] = 0;
1309
+ this.orders[last] = 0;
1310
+ this.values[last] = void 0;
1311
+ this.siftDown();
1260
1312
  }
1261
- return first.value;
1313
+ return value;
1262
1314
  }
1263
1315
  clear() {
1264
- this.heap.length = 0;
1316
+ this.size = 0;
1317
+ }
1318
+ before(first, second) {
1319
+ const times = this.times;
1320
+ const a = times[first];
1321
+ const b = times[second];
1322
+ return a < b || a === b && this.orders[first] < this.orders[second];
1323
+ }
1324
+ swap(first, second) {
1325
+ const times = this.times;
1326
+ const orders = this.orders;
1327
+ const values = this.values;
1328
+ const time = times[first];
1329
+ const order = orders[first];
1330
+ const value = values[first];
1331
+ times[first] = times[second];
1332
+ orders[first] = orders[second];
1333
+ values[first] = values[second];
1334
+ times[second] = time;
1335
+ orders[second] = order;
1336
+ values[second] = value;
1337
+ }
1338
+ siftUp(at) {
1339
+ while (at > 0) {
1340
+ const parent = at - 1 >>> 1;
1341
+ if (!this.before(at, parent)) break;
1342
+ this.swap(at, parent);
1343
+ at = parent;
1344
+ }
1265
1345
  }
1266
- before(a, b) {
1267
- return a.time < b.time || a.time === b.time && a.order < b.order;
1346
+ siftDown() {
1347
+ const size = this.size;
1348
+ let at = 0;
1349
+ for (;;) {
1350
+ const left = at * 2 + 1;
1351
+ if (left >= size) break;
1352
+ const right = left + 1;
1353
+ const child = right < size && this.before(right, left) ? right : left;
1354
+ if (!this.before(child, at)) break;
1355
+ this.swap(at, child);
1356
+ at = child;
1357
+ }
1268
1358
  }
1269
1359
  };
1270
1360
  var ActivationQueue = class {
1271
1361
  entries = [];
1272
1362
  words = [];
1363
+ /**
1364
+ * Active word indices in `[0, activeCount)`. The array keeps its high-water length:
1365
+ * truncating it would right-trim the backing store on every boundary.
1366
+ */
1273
1367
  activeWords = [];
1274
- batch = [];
1368
+ activeCount = 0;
1275
1369
  get size() {
1276
- return this.activeWords.length;
1370
+ return this.activeCount;
1277
1371
  }
1278
1372
  register(entry) {
1279
1373
  return this.entries.push(entry) - 1;
@@ -1281,53 +1375,75 @@ var ActivationQueue = class {
1281
1375
  add(slot) {
1282
1376
  const word = slot >>> 5;
1283
1377
  const previous = this.words[word] ?? 0;
1284
- if (previous === 0) this.activeWords.push(word);
1378
+ if (previous === 0) this.activeWords[this.activeCount++] = word;
1285
1379
  this.words[word] = previous | 1 << (slot & 31);
1286
1380
  }
1287
- take() {
1288
- const batch = this.batch;
1289
- batch.length = 0;
1290
- if (this.activeWords.length > 1) this.activeWords.sort((a, b) => a - b);
1291
- for (const word of this.activeWords) {
1381
+ /**
1382
+ * Visits every active entry in board order without materialising a batch. Entries added
1383
+ * by the visitor land past the visited range and survive.
1384
+ */
1385
+ drain(visit) {
1386
+ const active = this.activeWords;
1387
+ const visited = this.activeCount;
1388
+ if (visited === 0) return;
1389
+ if (visited > 1) for (let index = 1; index < visited; index++) {
1390
+ const word = active[index];
1391
+ let position = index;
1392
+ while (position > 0 && active[position - 1] > word) {
1393
+ active[position] = active[position - 1];
1394
+ position--;
1395
+ }
1396
+ active[position] = word;
1397
+ }
1398
+ for (let index = 0; index < visited; index++) {
1399
+ const word = active[index];
1292
1400
  let bits = this.words[word];
1293
1401
  this.words[word] = 0;
1402
+ const base = word * 32;
1294
1403
  while (bits !== 0) {
1295
- const bit = 31 - Math.clz32(bits & -bits);
1296
- batch.push(this.entries[word * 32 + bit]);
1404
+ visit(this.entries[base + 31 - Math.clz32(bits & -bits)]);
1297
1405
  bits &= bits - 1;
1298
1406
  }
1299
1407
  }
1300
- this.activeWords.length = 0;
1301
- return batch;
1408
+ if (this.activeCount === visited) this.activeCount = 0;
1409
+ else {
1410
+ for (let index = visited; index < this.activeCount; index++) active[index - visited] = active[index];
1411
+ this.activeCount -= visited;
1412
+ }
1302
1413
  }
1303
1414
  clear() {
1304
1415
  this.entries.length = 0;
1305
1416
  this.words.length = 0;
1306
1417
  this.activeWords.length = 0;
1307
- this.batch.length = 0;
1418
+ this.activeCount = 0;
1308
1419
  }
1309
1420
  };
1310
1421
  var Fifo = class {
1311
1422
  values = [];
1312
1423
  head = 0;
1424
+ tail = 0;
1313
1425
  get length() {
1314
- return this.values.length - this.head;
1426
+ return this.tail - this.head;
1315
1427
  }
1316
1428
  push(value) {
1317
- this.values.push(value);
1429
+ this.values[this.tail++] = value;
1318
1430
  }
1319
1431
  shift() {
1320
1432
  const value = this.values[this.head];
1321
1433
  this.values[this.head++] = void 0;
1322
- if (this.head === this.values.length) this.clear();
1434
+ if (this.head === this.tail) {
1435
+ this.head = 0;
1436
+ this.tail = 0;
1437
+ }
1323
1438
  return value;
1324
1439
  }
1325
1440
  clear() {
1326
1441
  this.values.length = 0;
1327
1442
  this.head = 0;
1443
+ this.tail = 0;
1328
1444
  }
1329
1445
  drain() {
1330
- const result = this.values.slice(this.head);
1446
+ const result = this.values.slice(this.head, this.tail);
1331
1447
  this.clear();
1332
1448
  return result;
1333
1449
  }
@@ -2151,6 +2267,9 @@ var Instance = class {
2151
2267
  processes = [];
2152
2268
  reactions = [];
2153
2269
  derived = /* @__PURE__ */ new Map();
2270
+ /** One-entry memo for repeated `read('derived', name)` calls inside a body. */
2271
+ derivedName;
2272
+ derivedEntry;
2154
2273
  derivedBuffers = /* @__PURE__ */ new Map();
2155
2274
  stateResources = /* @__PURE__ */ new Map();
2156
2275
  memoryResources = /* @__PURE__ */ new Map();
@@ -2168,6 +2287,11 @@ var Instance = class {
2168
2287
  memoryPlans = /* @__PURE__ */ new Map();
2169
2288
  /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */
2170
2289
  codeVersions = /* @__PURE__ */ new Map();
2290
+ /**
2291
+ * Every memory name any attached JIT binds as a code region. A write outside this set
2292
+ * cannot affect a JIT, so the store path skips the region scans entirely.
2293
+ */
2294
+ codeMemories = /* @__PURE__ */ new Set();
2171
2295
  observationFrames = /* @__PURE__ */ new WeakMap();
2172
2296
  evaluating = /* @__PURE__ */ new Set();
2173
2297
  random;
@@ -2184,7 +2308,8 @@ var Instance = class {
2184
2308
  if ("name" in declaration) this.declarations.set(declaration.name, declaration);
2185
2309
  if (declaration.kind === "state" || declaration.kind === "memory" || declaration.kind === "pin") (declaration.kind === "state" ? this.stateResources : declaration.kind === "memory" ? this.memoryResources : this.sampleResources).set(declaration.name, {
2186
2310
  version: 0,
2187
- subscribers: /* @__PURE__ */ new Set()
2311
+ subscribers: /* @__PURE__ */ new Set(),
2312
+ waiters: void 0
2188
2313
  });
2189
2314
  }
2190
2315
  dataObject(props);
@@ -2210,7 +2335,7 @@ var Instance = class {
2210
2335
  const plan = this.memoryPlan(memory);
2211
2336
  const size = kind.startsWith("load8") ? 1 : kind.startsWith("load16") ? 2 : 4;
2212
2337
  const at = range(plan.bytes, offset, size);
2213
- const dependencies = this.dependencyStack.at(-1);
2338
+ const dependencies = this.dependencies();
2214
2339
  if (dependencies) dependencies.set(plan.slot, plan.slot.version);
2215
2340
  if (size === 1) return plan.bytes[at];
2216
2341
  return size === 2 ? plan.view.getUint16(at, kind.endsWith("le")) : plan.view.getUint32(at, kind.endsWith("le"));
@@ -2248,8 +2373,13 @@ var Instance = class {
2248
2373
  track(resources, name) {
2249
2374
  this.trackSlot(resources.get(name));
2250
2375
  }
2376
+ /** Innermost dependency sink, or `undefined` outside an evaluation. */
2377
+ dependencies() {
2378
+ const stack = this.dependencyStack;
2379
+ return stack.length === 0 ? void 0 : stack[stack.length - 1];
2380
+ }
2251
2381
  trackSlot(slot) {
2252
- const dependencies = this.dependencyStack.at(-1);
2382
+ const dependencies = this.dependencies();
2253
2383
  if (dependencies) dependencies.set(slot, slot.version);
2254
2384
  }
2255
2385
  /** Read-only evidence that a process frame bound per-instance resource handles. */
@@ -2269,6 +2399,13 @@ var Instance = class {
2269
2399
  for (const [slot, version] of dependencies) if (slot.version !== version) return false;
2270
2400
  return true;
2271
2401
  }
2402
+ /** Publishes a derived cache entry; the memo must follow every table write. */
2403
+ setDerived(name, entry) {
2404
+ if (this.derivedName === name && this.derivedEntry === entry) return;
2405
+ this.derived.set(name, entry);
2406
+ this.derivedName = name;
2407
+ this.derivedEntry = entry;
2408
+ }
2272
2409
  evaluate(compute, target) {
2273
2410
  const dependencies = target ?? /* @__PURE__ */ new Map();
2274
2411
  this.dependencyStack.push(dependencies);
@@ -2279,7 +2416,7 @@ var Instance = class {
2279
2416
  };
2280
2417
  } finally {
2281
2418
  this.dependencyStack.pop();
2282
- const parent = this.dependencyStack.at(-1);
2419
+ const parent = this.dependencies();
2283
2420
  if (parent) for (const [key, version] of dependencies) parent.set(key, version);
2284
2421
  }
2285
2422
  }
@@ -2290,7 +2427,7 @@ var Instance = class {
2290
2427
  return snapshot(this.source(path));
2291
2428
  } finally {
2292
2429
  this.dependencyStack.pop();
2293
- const parent = this.dependencyStack.at(-1);
2430
+ const parent = this.dependencies();
2294
2431
  if (parent) for (const [key, version] of dependencies) parent.set(key, version);
2295
2432
  }
2296
2433
  }
@@ -2351,8 +2488,9 @@ var Instance = class {
2351
2488
  return this.states.get(name);
2352
2489
  }
2353
2490
  if (kind === "derived") {
2354
- let cached = this.derived.get(name);
2355
- if (!cached || !this.dependenciesCurrent(cached.dependencies)) {
2491
+ let cached = name === this.derivedName ? this.derivedEntry : this.derived.get(name);
2492
+ const epoch = this.board.resourceEpoch;
2493
+ if (cached === void 0 || cached.epoch !== epoch && !this.dependenciesCurrent(cached.dependencies)) {
2356
2494
  const declaration = this.declarations.get(name);
2357
2495
  if (declaration?.kind !== "derived") throw new TypeError(`Unknown derived ${name}`);
2358
2496
  let buffer = this.derivedBuffers.get(name);
@@ -2360,10 +2498,15 @@ var Instance = class {
2360
2498
  buffer = /* @__PURE__ */ new Map();
2361
2499
  this.derivedBuffers.set(name, buffer);
2362
2500
  } else buffer.clear();
2363
- cached = this.evaluate(() => computation(declaration.value, this.host), buffer);
2364
- this.derived.set(name, cached);
2365
- }
2366
- const parent = this.dependencyStack.at(-1);
2501
+ const evaluated = this.evaluate(() => computation(declaration.value, this.host), buffer);
2502
+ cached = {
2503
+ value: evaluated.value,
2504
+ dependencies: evaluated.dependencies,
2505
+ epoch: this.board.resourceEpoch
2506
+ };
2507
+ this.setDerived(name, cached);
2508
+ } else if (cached.epoch !== epoch) cached.epoch = epoch;
2509
+ const parent = this.dependencies();
2367
2510
  if (parent) for (const [key, version] of cached.dependencies) parent.set(key, version);
2368
2511
  return cached.value;
2369
2512
  }
@@ -2457,7 +2600,7 @@ var Instance = class {
2457
2600
  if (this.sampleEntries.size >= 512) this.sampleEntries.clear();
2458
2601
  this.sampleEntries.set(name, entry);
2459
2602
  }
2460
- const dependencies = this.dependencyStack.at(-1);
2603
+ const dependencies = this.dependencies();
2461
2604
  if (dependencies) dependencies.set(entry.slot, entry.slot.version);
2462
2605
  return entry.pin.sample;
2463
2606
  }
@@ -2500,8 +2643,10 @@ var Instance = class {
2500
2643
  const base = word << 5;
2501
2644
  while (bits !== 0) {
2502
2645
  const slot = stateSlots[base + 31 - Math.clz32(bits & -bits)];
2503
- if (slot.subscribers.size === 0) slot.version++;
2504
- else board.invalidate(slot);
2646
+ if (slot.subscribers.size === 0) {
2647
+ slot.version++;
2648
+ board.noteResourceVersion(slot);
2649
+ } else board.invalidate(slot);
2505
2650
  bits &= bits - 1;
2506
2651
  }
2507
2652
  }
@@ -2598,6 +2743,7 @@ var Instance = class {
2598
2743
  }
2599
2744
  memoryChangedSlot(name, slot, offset, size) {
2600
2745
  this.board.invalidate(slot);
2746
+ if (!this.codeMemories.has(name)) return;
2601
2747
  if (this.hasCodeRegion(name, offset, size)) this.codeVersions.set(name, this.codeVersion(name) + 1);
2602
2748
  for (const jit of this.jits) {
2603
2749
  let affected = false;
@@ -2643,16 +2789,19 @@ var Instance = class {
2643
2789
  return handles;
2644
2790
  }
2645
2791
  /**
2646
- * Each method repeats the generic host operation exactly: name resolution stays lazy so
2647
- * an invalid name still fails at the same operation, dependency slots are still
2792
+ * Each method repeats the generic host operation exactly: dependency slots are still
2648
2793
  * recorded, state writes still snapshot, and memory stores still run the code-memory
2649
- * invalidation that clears JIT caches.
2794
+ * invalidation that clears JIT caches. Every resource a declaration already provides is
2795
+ * resolved here, at bind time; a name that does not exist yet keeps resolving lazily so
2796
+ * it still fails at its first real use, not while binding.
2650
2797
  */
2651
2798
  resourceHandle(kind, name) {
2652
2799
  if (kind === "pin") {
2653
- let pin;
2654
- let slot = -1;
2655
- let sample;
2800
+ let pin = this.pins.get(name);
2801
+ let slot = pin === void 0 ? -1 : this.board.electricalSlot(pin);
2802
+ let sample = pin === void 0 ? void 0 : this.sampleResources.get(name);
2803
+ let lastResistance;
2804
+ let lastIntent;
2656
2805
  const resolve = () => {
2657
2806
  if (pin === void 0) {
2658
2807
  pin = this.pin(name);
@@ -2664,7 +2813,7 @@ var Instance = class {
2664
2813
  return Object.freeze({
2665
2814
  sample: () => {
2666
2815
  const current = resolve();
2667
- const dependencies = this.dependencyStack.at(-1);
2816
+ const dependencies = this.dependencies();
2668
2817
  if (dependencies) dependencies.set(sample, sample.version);
2669
2818
  return current.sample;
2670
2819
  },
@@ -2675,22 +2824,28 @@ var Instance = class {
2675
2824
  this.board.markElectricalDirty(slot);
2676
2825
  },
2677
2826
  resistor: (resistance) => {
2827
+ if (lastIntent !== void 0 && resistance === lastResistance) return lastIntent;
2678
2828
  const r = electricalNumber(resistance);
2679
2829
  if (r < .001 || r > 1e9) throw new ElectricalParameterError("Resistance outside [0.001, 1e9]");
2680
- return this.resistorIntent(name, r);
2830
+ const intent = this.resistorIntent(name, r);
2831
+ lastResistance = resistance;
2832
+ lastIntent = intent;
2833
+ return intent;
2681
2834
  }
2682
2835
  });
2683
2836
  }
2684
2837
  if (kind === "state") {
2685
- let slot;
2838
+ let slot = this.states.has(name) ? this.stateResources.get(name) : void 0;
2839
+ let banked = slot === void 0 ? -1 : this.directBank?.states.get(name) ?? -2;
2686
2840
  const resolve = () => slot ??= this.stateSlot(name);
2687
2841
  const states = this.states;
2688
2842
  return Object.freeze({
2689
2843
  read: () => {
2690
2844
  const current = resolve();
2691
- const dependencies = this.dependencyStack.at(-1);
2845
+ const dependencies = this.dependencies();
2692
2846
  if (dependencies) dependencies.set(current, current.version);
2693
- return states.get(name);
2847
+ if (banked === -2) banked = this.directBank?.states.get(name) ?? -1;
2848
+ return banked < 0 ? states.get(name) : this.directBank.stateValues[banked];
2694
2849
  },
2695
2850
  write: (value) => {
2696
2851
  const current = resolve();
@@ -2698,12 +2853,12 @@ var Instance = class {
2698
2853
  }
2699
2854
  });
2700
2855
  }
2701
- let plan;
2856
+ let plan = this.memories.has(name) ? this.memoryPlan(name) : void 0;
2702
2857
  const resolve = () => plan ??= this.memoryPlan(name);
2703
2858
  const read = (size, little, offset) => {
2704
2859
  const current = resolve();
2705
2860
  const at = range(current.bytes, offset, size);
2706
- const dependencies = this.dependencyStack.at(-1);
2861
+ const dependencies = this.dependencies();
2707
2862
  if (dependencies) dependencies.set(current.slot, current.slot.version);
2708
2863
  return size === 1 ? current.bytes[at] : size === 2 ? current.view.getUint16(at, little) : current.view.getUint32(at, little);
2709
2864
  };
@@ -3137,6 +3292,8 @@ var Instance = class {
3137
3292
  pollingPeriod: 0,
3138
3293
  pollingOrigin: 0,
3139
3294
  pollingToken: 0,
3295
+ dependencyDirty: true,
3296
+ waiterSlots: void 0,
3140
3297
  active: true,
3141
3298
  stopped: false,
3142
3299
  queued: false,
@@ -3144,13 +3301,14 @@ var Instance = class {
3144
3301
  };
3145
3302
  this.jits.push(jit);
3146
3303
  this.board.jits.push(jit);
3304
+ for (const region of jit.codeRegions) this.codeMemories.add(region.memory);
3147
3305
  const disposable = { dispose: () => {
3148
3306
  if (!jit.active) return;
3149
3307
  jit.active = false;
3150
3308
  jit.execution = void 0;
3151
3309
  delete jit.predicate;
3152
3310
  jit.pollingToken++;
3153
- this.board.waitingJits.delete(jit);
3311
+ this.board.unparkWaiter(jit);
3154
3312
  jit.cache.clear();
3155
3313
  jit.cacheMemories.clear();
3156
3314
  jit.directPrograms.clear();
@@ -3790,7 +3948,7 @@ function waitForPolling(board, jit, dependencies, duration, advance) {
3790
3948
  jit.dependencies = dependencies;
3791
3949
  jit.pollingWait = true;
3792
3950
  jit.pollingPeriod = 0;
3793
- board.waitingJits.add(jit);
3951
+ board.parkWaiter(jit);
3794
3952
  const token = ++jit.pollingToken;
3795
3953
  board.boundary();
3796
3954
  if (duration === 0 || advance === void 0) return;
@@ -3798,9 +3956,8 @@ function waitForPolling(board, jit, dependencies, duration, advance) {
3798
3956
  board.events.push(due, () => {
3799
3957
  if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit)) return;
3800
3958
  const pending = jit.dependencies;
3801
- jit.pollingWait = false;
3802
3959
  delete jit.dependencies;
3803
- board.waitingJits.delete(jit);
3960
+ board.unparkWaiter(jit);
3804
3961
  jit.pollingToken++;
3805
3962
  board.current = jit.instance;
3806
3963
  if (!jit.instance.dependenciesCurrent(pending)) {
@@ -3827,7 +3984,7 @@ function jitSignal(board, jit, signal) {
3827
3984
  jit.predicate = signal.predicate;
3828
3985
  jit.pollingWait = false;
3829
3986
  jit.dependencies = checked.dependencies;
3830
- board.waitingJits.add(jit);
3987
+ board.parkWaiter(jit);
3831
3988
  board.boundary();
3832
3989
  return true;
3833
3990
  }
@@ -3855,7 +4012,7 @@ function jitSignal(board, jit, signal) {
3855
4012
  jit.pollingWait = true;
3856
4013
  jit.pollingPeriod = duration;
3857
4014
  jit.pollingOrigin = board.time;
3858
- board.waitingJits.add(jit);
4015
+ board.parkWaiter(jit);
3859
4016
  } else board.queueJit(jit);
3860
4017
  });
3861
4018
  return true;
@@ -4031,7 +4188,11 @@ var BoardRuntime = class {
4031
4188
  current;
4032
4189
  /** -1: clean; -2: initial solve or multiple dirty slots; otherwise the only dirty slot. */
4033
4190
  pendingElectricalSlot = -2;
4034
- dirtyElectricalSlots = /* @__PURE__ */ new Set();
4191
+ /** Flat dirty batch for the multi-slot publication path, stamped to drop repetitions. */
4192
+ dirtyElectricalSlots = /* @__PURE__ */ new Int32Array(0);
4193
+ dirtyElectricalStamps = /* @__PURE__ */ new Int32Array(0);
4194
+ dirtyElectricalLength = 0;
4195
+ dirtyElectricalEpoch = 1;
4035
4196
  observations = new ActivationQueue();
4036
4197
  reactionBatch = [];
4037
4198
  changeObservations = [];
@@ -4055,7 +4216,27 @@ var BoardRuntime = class {
4055
4216
  models = new Fifo();
4056
4217
  events = new EventQueue();
4057
4218
  readyJits = new Fifo();
4219
+ /**
4220
+ * Bumped on every resource-version mutation board wide. The value is bare arithmetic: a
4221
+ * difference proves *some* resource moved, never which one, so it only ever guards
4222
+ * "nothing changed at all" conclusions.
4223
+ *
4224
+ * Mutations cluster inside `publish()` while derived reads spread across the gaps
4225
+ * between publications, so a checkpoint compared against this counter hits far more
4226
+ * often than the raw mutation-to-read ratio suggests: `camera-mcu` sees 8514 bumps and
4227
+ * 5638 derived reads per frame, yet 99.93% of those reads find the epoch unchanged.
4228
+ */
4229
+ versionEpoch = 0;
4058
4230
  waitingJits = /* @__PURE__ */ new Set();
4231
+ /**
4232
+ * Advances whenever a parked JIT is flagged or parks. The global `versionEpoch` cannot
4233
+ * gate the scan: every electrical publish bumps it even when no JIT waits on the slot.
4234
+ */
4235
+ waiterEpoch = 0;
4236
+ /** `waiterEpoch` at the last parked-JIT scan; equal means no parked JIT can have woken. */
4237
+ waitingScanEpoch = 0;
4238
+ /** Parked JITs whose `pollingWait` is set: their polling boundary needs every round. */
4239
+ pollingWaiterCount = 0;
4059
4240
  jits = [];
4060
4241
  instances = [];
4061
4242
  network;
@@ -4164,6 +4345,8 @@ var BoardRuntime = class {
4164
4345
  this.sampleSlotsBySlot.push(slot);
4165
4346
  }
4166
4347
  this.network = createElectricalNetwork(pins, nets);
4348
+ this.dirtyElectricalSlots = new Int32Array(pins.length);
4349
+ this.dirtyElectricalStamps = new Int32Array(pins.length);
4167
4350
  this.phase = "initialize";
4168
4351
  for (const instance of this.instances) {
4169
4352
  this.current = instance;
@@ -4229,13 +4412,19 @@ var BoardRuntime = class {
4229
4412
  processReport() {
4230
4413
  const resumable = [];
4231
4414
  const generic = [];
4415
+ const programs = [];
4232
4416
  for (const instance of this.instances) for (const process of instance.processes) {
4233
4417
  const key = `${instance.id}/${process.declaration.kind === "on" ? process.declaration.name : "start"}`;
4234
4418
  (process.resumable ? resumable : generic).push(key);
4419
+ programs.push(Object.freeze({
4420
+ key,
4421
+ blocks: process.resumable?.blocks ?? 0
4422
+ }));
4235
4423
  }
4236
4424
  return Object.freeze({
4237
4425
  resumable: Object.freeze(resumable),
4238
4426
  generic: Object.freeze(generic),
4427
+ programs: Object.freeze(programs),
4239
4428
  bindings: Object.freeze(this.instances.map((instance) => instance.bindingReport()))
4240
4429
  });
4241
4430
  }
@@ -4397,9 +4586,71 @@ var BoardRuntime = class {
4397
4586
  }
4398
4587
  invalidate(slot) {
4399
4588
  slot.version++;
4589
+ this.versionEpoch++;
4590
+ this.flagWaiters(slot);
4400
4591
  if (slot.subscribers.size === 0) return;
4401
4592
  for (const observation of slot.subscribers) this.observations.add(observation.order);
4402
4593
  }
4594
+ /** Records a resource version bumped outside :func:`invalidate` (direct JIT writes). */
4595
+ noteResourceVersion(slot) {
4596
+ this.versionEpoch++;
4597
+ this.flagWaiters(slot);
4598
+ }
4599
+ /** Flags every parked JIT that recorded `slot`, so the next round rescans it exactly once. */
4600
+ flagWaiters(slot) {
4601
+ const waiters = slot.waiters;
4602
+ if (waiters === void 0 || waiters.size === 0) return;
4603
+ for (const jit of waiters) jit.dependencyDirty = true;
4604
+ this.waiterEpoch++;
4605
+ }
4606
+ /**
4607
+ * Registers a parked JIT on the slots its predicate recorded. A later version bump then
4608
+ * flags that JIT directly, so a scheduler round rescans dependencies only when the
4609
+ * evidence it would read has actually moved.
4610
+ */
4611
+ watchWaiter(jit) {
4612
+ const dependencies = jit.dependencies;
4613
+ if (jit.waiterSlots === dependencies) return;
4614
+ const previous = jit.waiterSlots;
4615
+ if (previous !== void 0) for (const slot of previous.keys()) slot.waiters?.delete(jit);
4616
+ if (dependencies !== void 0) for (const slot of dependencies.keys()) (slot.waiters ??= /* @__PURE__ */ new Set()).add(jit);
4617
+ jit.waiterSlots = dependencies;
4618
+ jit.dependencyDirty = true;
4619
+ }
4620
+ /**
4621
+ * Parks a JIT on the versions it just recorded. Registering here instead of in the scan
4622
+ * makes `waiterEpoch` a complete wake source: the scan can then be skipped whenever no
4623
+ * parked JIT was flagged or registered since the last scan, and no poll is due.
4624
+ */
4625
+ parkWaiter(jit) {
4626
+ if (!this.waitingJits.has(jit)) {
4627
+ this.waitingJits.add(jit);
4628
+ if (jit.pollingWait) this.pollingWaiterCount++;
4629
+ }
4630
+ this.watchWaiter(jit);
4631
+ jit.dependencyDirty = true;
4632
+ this.waiterEpoch++;
4633
+ }
4634
+ /** Wakes or drops a parked JIT and removes the registrations that would flag it later. */
4635
+ unparkWaiter(jit) {
4636
+ if (this.waitingJits.delete(jit) && jit.pollingWait) {
4637
+ jit.pollingWait = false;
4638
+ this.pollingWaiterCount--;
4639
+ }
4640
+ const slots = jit.waiterSlots;
4641
+ if (slots !== void 0) {
4642
+ for (const slot of slots.keys()) slot.waiters?.delete(jit);
4643
+ jit.waiterSlots = void 0;
4644
+ }
4645
+ }
4646
+ /**
4647
+ * Checkpoint source for cached dependency evidence. An unchanged value since a previous
4648
+ * checkpoint proves no resource version moved in between, which is enough to reuse that
4649
+ * evidence without scanning it.
4650
+ */
4651
+ get resourceEpoch() {
4652
+ return this.versionEpoch;
4653
+ }
4403
4654
  /** Pin slot of an electrical endpoint; bound once because the board order is fixed. */
4404
4655
  electricalSlot(pin) {
4405
4656
  return this.electricalSlots.get(pin);
@@ -4407,28 +4658,46 @@ var BoardRuntime = class {
4407
4658
  markElectricalDirty(slot) {
4408
4659
  const pending = this.pendingElectricalSlot;
4409
4660
  if (pending === slot) return;
4661
+ const stamps = this.dirtyElectricalStamps;
4662
+ if (slot >= stamps.length) throw new RangeError("Electrical slot is outside the board");
4663
+ const epoch = this.dirtyElectricalEpoch;
4664
+ if (stamps[slot] === epoch) return;
4665
+ stamps[slot] = epoch;
4666
+ if (pending >= 0) {
4667
+ const list = this.dirtyElectricalSlots;
4668
+ list[0] = pending;
4669
+ list[1] = slot;
4670
+ stamps[pending] = epoch;
4671
+ this.dirtyElectricalLength = 2;
4672
+ this.pendingElectricalSlot = -2;
4673
+ return;
4674
+ }
4410
4675
  if (pending === -1) {
4411
4676
  this.pendingElectricalSlot = slot;
4412
4677
  return;
4413
4678
  }
4414
- if (pending >= 0) {
4415
- this.dirtyElectricalSlots.add(pending);
4416
- this.pendingElectricalSlot = -2;
4417
- }
4418
- this.dirtyElectricalSlots.add(slot);
4679
+ this.dirtyElectricalSlots[this.dirtyElectricalLength++] = slot;
4419
4680
  }
4420
4681
  /** Dirty slot count for diagnostics, not used by the publication path. */
4421
4682
  get dirtyElectricalCount() {
4422
- return this.pendingElectricalSlot >= 0 ? 1 : this.dirtyElectricalSlots.size;
4683
+ return this.pendingElectricalSlot >= 0 ? 1 : this.dirtyElectricalLength;
4423
4684
  }
4424
4685
  publish() {
4425
4686
  const pending = this.pendingElectricalSlot;
4426
4687
  if (pending === -1) return;
4427
- const changed = pending >= 0 ? this.network.solveSlot(pending) : this.network.solveSlots(this.dirtyElectricalSlots);
4428
- if (pending === -2) this.dirtyElectricalSlots.clear();
4688
+ if (pending >= 0) this.network.solveSlotInto(pending, this.publishSlot);
4689
+ else this.network.solveSlotBatchInto(this.dirtyElectricalSlots, this.dirtyElectricalLength, this.publishSlot);
4690
+ if (pending === -2) this.dirtyElectricalLength = 0;
4691
+ if (++this.dirtyElectricalEpoch === 2147483647) {
4692
+ this.dirtyElectricalStamps.fill(0);
4693
+ this.dirtyElectricalEpoch = 1;
4694
+ }
4429
4695
  this.pendingElectricalSlot = -1;
4430
- for (let index = 0; index < changed.length; index++) this.invalidate(this.sampleSlotsBySlot[changed[index]]);
4431
4696
  }
4697
+ /** Publication sink: enter the observation queue for one published board slot. */
4698
+ publishSlot = (slot) => {
4699
+ this.invalidate(this.sampleSlotsBySlot[slot]);
4700
+ };
4432
4701
  bindObservation(observation, path) {
4433
4702
  const instance = observation.instance;
4434
4703
  observation.previous = instance.observe(observation, path);
@@ -4481,7 +4750,8 @@ var BoardRuntime = class {
4481
4750
  dependencies: /* @__PURE__ */ new Map(),
4482
4751
  entry: {
4483
4752
  dependencies: /* @__PURE__ */ new Map(),
4484
- value: void 0
4753
+ value: void 0,
4754
+ epoch: -1
4485
4755
  },
4486
4756
  order: 0,
4487
4757
  previous: void 0,
@@ -4521,11 +4791,17 @@ var BoardRuntime = class {
4521
4791
  commitChain(chain, value) {
4522
4792
  const path = chain.plan.path;
4523
4793
  if (path.length !== 1) return;
4524
- for (const slot of chain.plan.slots) chain.dependencies.set(slot, slot.version);
4794
+ const slots = chain.plan.slots;
4795
+ const dependencies = chain.dependencies;
4796
+ for (let index = 0; index < slots.length; index++) {
4797
+ const slot = slots[index];
4798
+ dependencies.set(slot, slot.version);
4799
+ }
4525
4800
  const entry = chain.entry;
4526
4801
  if (entry.value !== value) entry.value = value;
4527
- entry.dependencies = chain.dependencies;
4528
- if (chain.instance.derived.get(path[0]) !== entry) chain.instance.derived.set(path[0], entry);
4802
+ entry.dependencies = dependencies;
4803
+ entry.epoch = this.versionEpoch;
4804
+ chain.instance.setDerived(path[0], entry);
4529
4805
  }
4530
4806
  collectChain(chain) {
4531
4807
  const value = chain.plan.evaluate();
@@ -4586,25 +4862,12 @@ var BoardRuntime = class {
4586
4862
  if (this.pendingElectricalSlot !== -1) this.publish();
4587
4863
  if (!this.observations.size) return;
4588
4864
  const reactions = this.reactionBatch;
4589
- reactions.length = 0;
4865
+ if (reactions.length) reactions.length = 0;
4590
4866
  const changes = this.changeObservations;
4591
- changes.length = 0;
4592
- this.changePrevious.length = 0;
4593
- this.changeCurrent.length = 0;
4594
- const batch = this.observations.take();
4595
- for (let index = 0; index < batch.length; index++) {
4596
- const observation = batch[index];
4597
- if ("plan" in observation) {
4598
- this.collectChain(observation);
4599
- continue;
4600
- }
4601
- const current = observation.readSource();
4602
- if (same(observation.previous, current)) continue;
4603
- const previous = observation.previous;
4604
- observation.previous = current;
4605
- if (changes.length) this.recordChange(observation, previous, current);
4606
- else this.applyChange(observation, previous, current);
4607
- }
4867
+ if (changes.length) changes.length = 0;
4868
+ if (this.changePrevious.length) this.changePrevious.length = 0;
4869
+ if (this.changeCurrent.length) this.changeCurrent.length = 0;
4870
+ this.observations.drain(this.consumeObservation);
4608
4871
  const count = changes.length;
4609
4872
  if (count) {
4610
4873
  for (let index = 0; index < count; index++) this.applyChange(changes[index], this.changePrevious[index], this.changeCurrent[index]);
@@ -4616,6 +4879,19 @@ var BoardRuntime = class {
4616
4879
  else return;
4617
4880
  }
4618
4881
  }
4882
+ /** One due receiver: chains collapse their members, plain sources apply inline. */
4883
+ consumeObservation = (observation) => {
4884
+ if ("plan" in observation) {
4885
+ this.collectChain(observation);
4886
+ return;
4887
+ }
4888
+ const current = observation.readSource();
4889
+ if (same(observation.previous, current)) return;
4890
+ const previous = observation.previous;
4891
+ observation.previous = current;
4892
+ if (this.changeObservations.length) this.recordChange(observation, previous, current);
4893
+ else this.applyChange(observation, previous, current);
4894
+ };
4619
4895
  /** Shared capture barrier and ordered body runner for generic and static boundaries. */
4620
4896
  runBoundaryReactions(reactions) {
4621
4897
  try {
@@ -4720,13 +4996,15 @@ var BoardRuntime = class {
4720
4996
  * the body reports ticks/receive through the frame and returns whether it suspended.
4721
4997
  */
4722
4998
  driveResumable(process, program, value) {
4723
- this.current = process.instance;
4999
+ const instance = process.instance;
5000
+ this.current = instance;
4724
5001
  process.state = "running";
4725
5002
  const state = process.frame ??= frame(program);
5003
+ const host = instance.host;
4726
5004
  let input = value;
4727
5005
  for (;;) {
4728
5006
  state.value = input;
4729
- if (!program.run(process.instance.host, void 0, void 0, state)) {
5007
+ if (!program.run(host, void 0, void 0, state)) {
4730
5008
  this.boundary();
4731
5009
  process.state = "idle";
4732
5010
  if (process.pending) {
@@ -4736,7 +5014,7 @@ var BoardRuntime = class {
4736
5014
  return;
4737
5015
  }
4738
5016
  if (state.kind === RESUMABLE_RECEIVE) {
4739
- const channel = process.instance.channels.get(state.channel);
5017
+ const channel = instance.channels.get(state.channel);
4740
5018
  if (channel.incoming.length) {
4741
5019
  input = channel.incoming.shift().value;
4742
5020
  continue;
@@ -4806,40 +5084,48 @@ var BoardRuntime = class {
4806
5084
  continue;
4807
5085
  }
4808
5086
  let pollingBoundary = Infinity;
4809
- if (this.waitingJits.size) for (let index = 0; index < this.jits.length; index++) {
4810
- const jit = this.jits[index];
4811
- if (!jit.active || jit.stopped || !this.waitingJits.has(jit)) continue;
4812
- if (jit.instance.dependenciesCurrent(jit.dependencies)) {
4813
- if (jit.pollingWait && jit.pollingPeriod > 0) {
4814
- const lastStart = MAX_TIME - (MAX_TIME - jit.pollingOrigin) % jit.pollingPeriod;
4815
- if (lastStart < 72e14 && lastStart < end) {
4816
- if (lastStart === this.time) {
4817
- jit.pollingWait = false;
4818
- jit.pollingToken++;
4819
- delete jit.dependencies;
4820
- this.waitingJits.delete(jit);
4821
- this.queueJit(jit);
4822
- } else pollingBoundary = Math.min(pollingBoundary, lastStart);
5087
+ if (this.waitingJits.size && (this.waiterEpoch !== this.waitingScanEpoch || this.pollingWaiterCount !== 0)) {
5088
+ this.waitingScanEpoch = this.waiterEpoch;
5089
+ for (let index = 0; index < this.jits.length; index++) {
5090
+ const jit = this.jits[index];
5091
+ if (!jit.active || jit.stopped || !this.waitingJits.has(jit)) continue;
5092
+ this.watchWaiter(jit);
5093
+ if (!jit.dependencyDirty && !jit.pollingWait) continue;
5094
+ if (jit.instance.dependenciesCurrent(jit.dependencies)) {
5095
+ jit.dependencyDirty = false;
5096
+ if (jit.pollingWait && jit.pollingPeriod > 0) {
5097
+ const lastStart = MAX_TIME - (MAX_TIME - jit.pollingOrigin) % jit.pollingPeriod;
5098
+ if (lastStart < 72e14 && lastStart < end) {
5099
+ if (lastStart === this.time) {
5100
+ jit.pollingToken++;
5101
+ delete jit.dependencies;
5102
+ this.unparkWaiter(jit);
5103
+ this.queueJit(jit);
5104
+ } else pollingBoundary = Math.min(pollingBoundary, lastStart);
5105
+ }
4823
5106
  }
5107
+ continue;
4824
5108
  }
4825
- continue;
4826
- }
4827
- if (jit.pollingWait) {
4828
- jit.pollingWait = false;
4829
- jit.pollingToken++;
4830
- delete jit.dependencies;
4831
- this.waitingJits.delete(jit);
4832
- const remainder = jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;
4833
- if (remainder) this.events.push(time(this.time + (jit.pollingPeriod - remainder)), () => this.queueJit(jit));
4834
- else this.queueJit(jit);
4835
- } else if (jit.predicate) {
4836
- const checked = jit.instance.evaluate(() => syncJitCall(jit, jit.predicate));
4837
- jit.dependencies = checked.dependencies;
4838
- if (checked.value === true) {
4839
- delete jit.predicate;
5109
+ jit.dependencyDirty = false;
5110
+ if (jit.pollingWait) {
5111
+ jit.pollingToken++;
4840
5112
  delete jit.dependencies;
4841
- this.waitingJits.delete(jit);
4842
- this.queueJit(jit);
5113
+ this.unparkWaiter(jit);
5114
+ const remainder = jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;
5115
+ if (remainder) this.events.push(time(this.time + (jit.pollingPeriod - remainder)), () => this.queueJit(jit));
5116
+ else this.queueJit(jit);
5117
+ } else if (jit.predicate) {
5118
+ const checked = jit.instance.evaluate(() => syncJitCall(jit, jit.predicate));
5119
+ jit.dependencies = checked.dependencies;
5120
+ if (checked.value === true) {
5121
+ delete jit.predicate;
5122
+ delete jit.dependencies;
5123
+ this.unparkWaiter(jit);
5124
+ this.queueJit(jit);
5125
+ } else {
5126
+ this.watchWaiter(jit);
5127
+ this.waiterEpoch++;
5128
+ }
4843
5129
  }
4844
5130
  }
4845
5131
  }
@@ -4852,8 +5138,10 @@ var BoardRuntime = class {
4852
5138
  this.time = pollingBoundary;
4853
5139
  continue;
4854
5140
  }
4855
- if (this.events.time <= end) {
4856
- this.time = this.events.time;
5141
+ const next = this.events.time;
5142
+ if (next <= end) {
5143
+ this.time = next;
5144
+ while (this.events.time === this.time) this.events.pop()();
4857
5145
  continue;
4858
5146
  }
4859
5147
  this.time = end;