@vessel-dsp/runtime 0.3.1 → 0.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.
@@ -575,34 +575,47 @@ var require_v2_dsp = __commonJS({
575
575
  var _v2_engine_create = Module["_v2_engine_create"] = () => (_v2_engine_create = Module["_v2_engine_create"] = wasmExports["g"])();
576
576
  var _v2_engine_destroy = Module["_v2_engine_destroy"] = (a0) => (_v2_engine_destroy = Module["_v2_engine_destroy"] = wasmExports["h"])(a0);
577
577
  var _v2_engine_load_json = Module["_v2_engine_load_json"] = (a0, a1) => (_v2_engine_load_json = Module["_v2_engine_load_json"] = wasmExports["i"])(a0, a1);
578
- var _v2_engine_prepare = Module["_v2_engine_prepare"] = (a0, a1, a2, a3) => (_v2_engine_prepare = Module["_v2_engine_prepare"] = wasmExports["j"])(a0, a1, a2, a3);
579
- var _v2_engine_reset = Module["_v2_engine_reset"] = (a0) => (_v2_engine_reset = Module["_v2_engine_reset"] = wasmExports["k"])(a0);
580
- var _v2_engine_set_control = Module["_v2_engine_set_control"] = (a0, a1, a2) => (_v2_engine_set_control = Module["_v2_engine_set_control"] = wasmExports["l"])(a0, a1, a2);
581
- var _v2_engine_get_control = Module["_v2_engine_get_control"] = (a0, a1) => (_v2_engine_get_control = Module["_v2_engine_get_control"] = wasmExports["m"])(a0, a1);
582
- var _v2_engine_set_supply = Module["_v2_engine_set_supply"] = (a0, a1, a2, a3, a4) => (_v2_engine_set_supply = Module["_v2_engine_set_supply"] = wasmExports["n"])(a0, a1, a2, a3, a4);
583
- var _v2_engine_process_sample = Module["_v2_engine_process_sample"] = (a0, a1) => (_v2_engine_process_sample = Module["_v2_engine_process_sample"] = wasmExports["o"])(a0, a1);
584
- var _v2_engine_process_block = Module["_v2_engine_process_block"] = (a0, a1, a2, a3) => (_v2_engine_process_block = Module["_v2_engine_process_block"] = wasmExports["p"])(a0, a1, a2, a3);
585
- var _v2_engine_get_input_buffer = Module["_v2_engine_get_input_buffer"] = (a0, a1) => (_v2_engine_get_input_buffer = Module["_v2_engine_get_input_buffer"] = wasmExports["q"])(a0, a1);
586
- var _v2_engine_get_output_buffer = Module["_v2_engine_get_output_buffer"] = (a0, a1) => (_v2_engine_get_output_buffer = Module["_v2_engine_get_output_buffer"] = wasmExports["r"])(a0, a1);
587
- var _v2_engine_process_internal = Module["_v2_engine_process_internal"] = (a0, a1) => (_v2_engine_process_internal = Module["_v2_engine_process_internal"] = wasmExports["s"])(a0, a1);
588
- var _v2_engine_get_last_iteration_count = Module["_v2_engine_get_last_iteration_count"] = (a0) => (_v2_engine_get_last_iteration_count = Module["_v2_engine_get_last_iteration_count"] = wasmExports["t"])(a0);
589
- var _v2_engine_get_last_converged = Module["_v2_engine_get_last_converged"] = (a0) => (_v2_engine_get_last_converged = Module["_v2_engine_get_last_converged"] = wasmExports["u"])(a0);
590
- var _v2_engine_get_max_iterations = Module["_v2_engine_get_max_iterations"] = (a0) => (_v2_engine_get_max_iterations = Module["_v2_engine_get_max_iterations"] = wasmExports["v"])(a0);
591
- var _v2_engine_get_operating_point = Module["_v2_engine_get_operating_point"] = (a0, a1, a2) => (_v2_engine_get_operating_point = Module["_v2_engine_get_operating_point"] = wasmExports["w"])(a0, a1, a2);
592
- var _v2_engine_get_state = Module["_v2_engine_get_state"] = (a0, a1, a2) => (_v2_engine_get_state = Module["_v2_engine_get_state"] = wasmExports["x"])(a0, a1, a2);
593
- var _v2_engine_get_last_error = Module["_v2_engine_get_last_error"] = (a0) => (_v2_engine_get_last_error = Module["_v2_engine_get_last_error"] = wasmExports["y"])(a0);
594
- var _v2_engine_get_schedule_solves = Module["_v2_engine_get_schedule_solves"] = (a0) => (_v2_engine_get_schedule_solves = Module["_v2_engine_get_schedule_solves"] = wasmExports["z"])(a0);
595
- var _v2_engine_get_schedule_fallbacks = Module["_v2_engine_get_schedule_fallbacks"] = (a0) => (_v2_engine_get_schedule_fallbacks = Module["_v2_engine_get_schedule_fallbacks"] = wasmExports["A"])(a0);
596
- var _v2_engine_get_kernel_solves = Module["_v2_engine_get_kernel_solves"] = (a0) => (_v2_engine_get_kernel_solves = Module["_v2_engine_get_kernel_solves"] = wasmExports["B"])(a0);
597
- var _v2_engine_get_repivoted_schedule_blocks = Module["_v2_engine_get_repivoted_schedule_blocks"] = (a0) => (_v2_engine_get_repivoted_schedule_blocks = Module["_v2_engine_get_repivoted_schedule_blocks"] = wasmExports["C"])(a0);
598
- var _v2_engine_get_abandoned_schedule_blocks = Module["_v2_engine_get_abandoned_schedule_blocks"] = (a0) => (_v2_engine_get_abandoned_schedule_blocks = Module["_v2_engine_get_abandoned_schedule_blocks"] = wasmExports["D"])(a0);
599
- var _v2_engine_get_dropped_schedule_blocks = Module["_v2_engine_get_dropped_schedule_blocks"] = (a0) => (_v2_engine_get_dropped_schedule_blocks = Module["_v2_engine_get_dropped_schedule_blocks"] = wasmExports["E"])(a0);
600
- var _malloc = Module["_malloc"] = (a0) => (_malloc = Module["_malloc"] = wasmExports["F"])(a0);
601
- var _free = Module["_free"] = (a0) => (_free = Module["_free"] = wasmExports["G"])(a0);
602
- var ___trap = () => (___trap = wasmExports["H"])();
603
- var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["I"])(a0);
604
- var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["J"])(a0);
605
- var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["K"])();
578
+ var _v2_engine_prepare = Module["_v2_engine_prepare"] = (a0, a1, a2, a3, a4) => (_v2_engine_prepare = Module["_v2_engine_prepare"] = wasmExports["j"])(a0, a1, a2, a3, a4);
579
+ var _v2_engine_get_host_sample_rate = Module["_v2_engine_get_host_sample_rate"] = (a0) => (_v2_engine_get_host_sample_rate = Module["_v2_engine_get_host_sample_rate"] = wasmExports["k"])(a0);
580
+ var _v2_engine_get_oversample_latency = Module["_v2_engine_get_oversample_latency"] = (a0) => (_v2_engine_get_oversample_latency = Module["_v2_engine_get_oversample_latency"] = wasmExports["l"])(a0);
581
+ var _v2_resample_stage_count = Module["_v2_resample_stage_count"] = () => (_v2_resample_stage_count = Module["_v2_resample_stage_count"] = wasmExports["m"])();
582
+ var _v2_resample_prototype_length = Module["_v2_resample_prototype_length"] = (a0) => (_v2_resample_prototype_length = Module["_v2_resample_prototype_length"] = wasmExports["n"])(a0);
583
+ var _v2_resample_prototype_tap = Module["_v2_resample_prototype_tap"] = (a0, a1) => (_v2_resample_prototype_tap = Module["_v2_resample_prototype_tap"] = wasmExports["o"])(a0, a1);
584
+ var _v2_testonly_resample_create = Module["_v2_testonly_resample_create"] = (a0) => (_v2_testonly_resample_create = Module["_v2_testonly_resample_create"] = wasmExports["p"])(a0);
585
+ var _v2_testonly_resample_reset = Module["_v2_testonly_resample_reset"] = (a0) => (_v2_testonly_resample_reset = Module["_v2_testonly_resample_reset"] = wasmExports["q"])(a0);
586
+ var _v2_testonly_resample_process = Module["_v2_testonly_resample_process"] = (a0, a1) => (_v2_testonly_resample_process = Module["_v2_testonly_resample_process"] = wasmExports["r"])(a0, a1);
587
+ var _v2_testonly_resample_destroy = Module["_v2_testonly_resample_destroy"] = (a0) => (_v2_testonly_resample_destroy = Module["_v2_testonly_resample_destroy"] = wasmExports["s"])(a0);
588
+ var _v2_engine_reset = Module["_v2_engine_reset"] = (a0) => (_v2_engine_reset = Module["_v2_engine_reset"] = wasmExports["t"])(a0);
589
+ var _v2_engine_set_control = Module["_v2_engine_set_control"] = (a0, a1, a2) => (_v2_engine_set_control = Module["_v2_engine_set_control"] = wasmExports["u"])(a0, a1, a2);
590
+ var _v2_engine_get_control = Module["_v2_engine_get_control"] = (a0, a1) => (_v2_engine_get_control = Module["_v2_engine_get_control"] = wasmExports["v"])(a0, a1);
591
+ var _v2_engine_set_supply = Module["_v2_engine_set_supply"] = (a0, a1, a2, a3, a4) => (_v2_engine_set_supply = Module["_v2_engine_set_supply"] = wasmExports["w"])(a0, a1, a2, a3, a4);
592
+ var _v2_engine_process_sample = Module["_v2_engine_process_sample"] = (a0, a1) => (_v2_engine_process_sample = Module["_v2_engine_process_sample"] = wasmExports["x"])(a0, a1);
593
+ var _v2_engine_process_block = Module["_v2_engine_process_block"] = (a0, a1, a2, a3) => (_v2_engine_process_block = Module["_v2_engine_process_block"] = wasmExports["y"])(a0, a1, a2, a3);
594
+ var _v2_engine_get_input_buffer = Module["_v2_engine_get_input_buffer"] = (a0, a1) => (_v2_engine_get_input_buffer = Module["_v2_engine_get_input_buffer"] = wasmExports["z"])(a0, a1);
595
+ var _v2_engine_get_output_buffer = Module["_v2_engine_get_output_buffer"] = (a0, a1) => (_v2_engine_get_output_buffer = Module["_v2_engine_get_output_buffer"] = wasmExports["A"])(a0, a1);
596
+ var _v2_engine_process_internal = Module["_v2_engine_process_internal"] = (a0, a1) => (_v2_engine_process_internal = Module["_v2_engine_process_internal"] = wasmExports["B"])(a0, a1);
597
+ var _v2_engine_get_last_iteration_count = Module["_v2_engine_get_last_iteration_count"] = (a0) => (_v2_engine_get_last_iteration_count = Module["_v2_engine_get_last_iteration_count"] = wasmExports["C"])(a0);
598
+ var _v2_engine_get_last_converged = Module["_v2_engine_get_last_converged"] = (a0) => (_v2_engine_get_last_converged = Module["_v2_engine_get_last_converged"] = wasmExports["D"])(a0);
599
+ var _v2_engine_get_max_iterations = Module["_v2_engine_get_max_iterations"] = (a0) => (_v2_engine_get_max_iterations = Module["_v2_engine_get_max_iterations"] = wasmExports["E"])(a0);
600
+ var _v2_engine_get_operating_point = Module["_v2_engine_get_operating_point"] = (a0, a1, a2) => (_v2_engine_get_operating_point = Module["_v2_engine_get_operating_point"] = wasmExports["F"])(a0, a1, a2);
601
+ var _v2_engine_get_state = Module["_v2_engine_get_state"] = (a0, a1, a2) => (_v2_engine_get_state = Module["_v2_engine_get_state"] = wasmExports["G"])(a0, a1, a2);
602
+ var _v2_engine_get_last_error = Module["_v2_engine_get_last_error"] = (a0) => (_v2_engine_get_last_error = Module["_v2_engine_get_last_error"] = wasmExports["H"])(a0);
603
+ var _v2_engine_get_schedule_solves = Module["_v2_engine_get_schedule_solves"] = (a0) => (_v2_engine_get_schedule_solves = Module["_v2_engine_get_schedule_solves"] = wasmExports["I"])(a0);
604
+ var _v2_engine_get_schedule_fallbacks = Module["_v2_engine_get_schedule_fallbacks"] = (a0) => (_v2_engine_get_schedule_fallbacks = Module["_v2_engine_get_schedule_fallbacks"] = wasmExports["J"])(a0);
605
+ var _v2_engine_get_predictor_seeds = Module["_v2_engine_get_predictor_seeds"] = (a0) => (_v2_engine_get_predictor_seeds = Module["_v2_engine_get_predictor_seeds"] = wasmExports["K"])(a0);
606
+ var _v2_engine_get_one_iteration_solves = Module["_v2_engine_get_one_iteration_solves"] = (a0) => (_v2_engine_get_one_iteration_solves = Module["_v2_engine_get_one_iteration_solves"] = wasmExports["L"])(a0);
607
+ var _v2_engine_get_total_iterations = Module["_v2_engine_get_total_iterations"] = (a0) => (_v2_engine_get_total_iterations = Module["_v2_engine_get_total_iterations"] = wasmExports["M"])(a0);
608
+ var _v2_engine_get_predictor_order = Module["_v2_engine_get_predictor_order"] = (a0, a1) => (_v2_engine_get_predictor_order = Module["_v2_engine_get_predictor_order"] = wasmExports["N"])(a0, a1);
609
+ var _v2_engine_get_kernel_solves = Module["_v2_engine_get_kernel_solves"] = (a0) => (_v2_engine_get_kernel_solves = Module["_v2_engine_get_kernel_solves"] = wasmExports["O"])(a0);
610
+ var _v2_engine_get_repivoted_schedule_blocks = Module["_v2_engine_get_repivoted_schedule_blocks"] = (a0) => (_v2_engine_get_repivoted_schedule_blocks = Module["_v2_engine_get_repivoted_schedule_blocks"] = wasmExports["P"])(a0);
611
+ var _v2_engine_get_abandoned_schedule_blocks = Module["_v2_engine_get_abandoned_schedule_blocks"] = (a0) => (_v2_engine_get_abandoned_schedule_blocks = Module["_v2_engine_get_abandoned_schedule_blocks"] = wasmExports["Q"])(a0);
612
+ var _v2_engine_get_dropped_schedule_blocks = Module["_v2_engine_get_dropped_schedule_blocks"] = (a0) => (_v2_engine_get_dropped_schedule_blocks = Module["_v2_engine_get_dropped_schedule_blocks"] = wasmExports["R"])(a0);
613
+ var _malloc = Module["_malloc"] = (a0) => (_malloc = Module["_malloc"] = wasmExports["S"])(a0);
614
+ var _free = Module["_free"] = (a0) => (_free = Module["_free"] = wasmExports["T"])(a0);
615
+ var ___trap = () => (___trap = wasmExports["U"])();
616
+ var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["V"])(a0);
617
+ var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["W"])(a0);
618
+ var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["X"])();
606
619
  Module["ccall"] = ccall;
607
620
  Module["cwrap"] = cwrap;
608
621
  Module["setValue"] = setValue;
@@ -862,7 +875,7 @@ function slotLabel(slot, index) {
862
875
  return slot.kind === "processor" ? `slot ${index} (${slot.processor.id})` : `slot ${index}`;
863
876
  }
864
877
 
865
- // src/numeric-pivot.ts
878
+ // ../compiler/src/sparse-schedule.ts
866
879
  var NUMERIC_REPIVOT_TAU = 1e-3;
867
880
  function computeNumericRepivot(schedule, size, matrix, tau = NUMERIC_REPIVOT_TAU) {
868
881
  const rows = Array.from({ length: size }, () => /* @__PURE__ */ new Set());
@@ -1027,6 +1040,132 @@ function computeNumericRepivot(schedule, size, matrix, tau = NUMERIC_REPIVOT_TAU
1027
1040
  };
1028
1041
  }
1029
1042
 
1043
+ // src/resample.ts
1044
+ var RESAMPLE_STAGE_SPECS = [
1045
+ [41, 6],
1046
+ [29, 7],
1047
+ [21, 6]
1048
+ ];
1049
+ function resampleStageSpec(index) {
1050
+ return RESAMPLE_STAGE_SPECS[Math.min(index, RESAMPLE_STAGE_SPECS.length - 1)];
1051
+ }
1052
+ var RESAMPLE_KAISER_BETA = 8.3;
1053
+ function besselI0(x) {
1054
+ let sum = 1;
1055
+ let term = 1;
1056
+ const half = x * x / 4;
1057
+ for (let k = 1; k <= 32; k += 1) {
1058
+ term *= half / (k * k);
1059
+ sum += term;
1060
+ if (term < 1e-17 * sum) break;
1061
+ }
1062
+ return sum;
1063
+ }
1064
+ function designHalfBand2x(taps = 57, beta = RESAMPLE_KAISER_BETA) {
1065
+ if (!Number.isInteger(taps) || taps < 9 || taps % 4 !== 1) {
1066
+ throw new Error(
1067
+ `half-band prototype needs an odd tap count of 1 mod 4 (got ${String(taps)})`
1068
+ );
1069
+ }
1070
+ const center = (taps - 1) / 2;
1071
+ const denom = besselI0(beta);
1072
+ const out = new Float64Array(taps);
1073
+ for (let i = 0; i < taps; i += 1) {
1074
+ const d = i - center;
1075
+ const r = d / center;
1076
+ const window2 = besselI0(beta * Math.sqrt(Math.max(0, 1 - r * r))) / denom;
1077
+ if (d === 0) {
1078
+ out[i] = 0.5;
1079
+ } else if (d % 2 === 0) {
1080
+ out[i] = 0;
1081
+ } else {
1082
+ out[i] = window2 * Math.sin(Math.PI * d / 2) / (Math.PI * d);
1083
+ }
1084
+ }
1085
+ let oddSum = 0;
1086
+ for (let i = 1; i < taps; i += 2) oddSum += out[i];
1087
+ const scale = 0.5 / oddSum;
1088
+ for (let i = 1; i < taps; i += 2) out[i] = out[i] * scale;
1089
+ out[center] = 0.5;
1090
+ return out;
1091
+ }
1092
+ var HalfBandStage2x = class {
1093
+ odd;
1094
+ /** Input samples of history behind the even (passthrough) output. */
1095
+ upDelay;
1096
+ /** Group delay in high-rate samples, each direction. */
1097
+ delayHighRate;
1098
+ histUp;
1099
+ histDown;
1100
+ constructor(prototype) {
1101
+ const taps = prototype.length;
1102
+ if (taps % 4 !== 1 || taps < 9) {
1103
+ throw new Error(
1104
+ `half-band stage needs a 1-mod-4 prototype (got ${taps})`
1105
+ );
1106
+ }
1107
+ const center = (taps - 1) / 2;
1108
+ if (prototype[center] !== 0.5) {
1109
+ throw new Error("half-band prototype center tap must be exactly 0.5");
1110
+ }
1111
+ const oddCount = (taps - 1) / 2;
1112
+ const odd = new Float64Array(oddCount);
1113
+ for (let j = 0; j < oddCount; j += 1)
1114
+ odd[j] = prototype[2 * j + 1];
1115
+ this.odd = odd;
1116
+ this.upDelay = center / 2;
1117
+ this.delayHighRate = center;
1118
+ this.histUp = new Float64Array(oddCount);
1119
+ this.histDown = new Float64Array(taps);
1120
+ }
1121
+ /** Zero both histories. */
1122
+ reset() {
1123
+ this.histUp.fill(0);
1124
+ this.histDown.fill(0);
1125
+ }
1126
+ /**
1127
+ * Interpolate one input sample into two: `out[at]` is the delayed input
1128
+ * itself (bit-exact, coefficient 1), `out[at+1]` the filtered midpoint.
1129
+ */
1130
+ interpolate(x, out, at) {
1131
+ this.histUp.copyWithin(1, 0, this.histUp.length - 1);
1132
+ this.histUp[0] = x;
1133
+ out[at] = this.histUp[this.upDelay];
1134
+ let mid = 0;
1135
+ const odd = this.odd;
1136
+ for (let j = 0; j < odd.length; j += 1) {
1137
+ mid += odd[j] * this.histUp[j];
1138
+ }
1139
+ out[at + 1] = 2 * mid;
1140
+ }
1141
+ /**
1142
+ * Decimate a consecutive pair (`first` older, `second` newer) to one
1143
+ * sample at gain 1.
1144
+ */
1145
+ decimate(first, second) {
1146
+ this.histDown.copyWithin(2, 0, this.histDown.length - 2);
1147
+ this.histDown[0] = second;
1148
+ this.histDown[1] = first;
1149
+ let acc = 0.5 * this.histDown[this.delayHighRate];
1150
+ const odd = this.odd;
1151
+ for (let j = 0; j < odd.length; j += 1) {
1152
+ acc += odd[j] * this.histDown[2 * j + 1];
1153
+ }
1154
+ return acc;
1155
+ }
1156
+ };
1157
+ function cascadeLatencyHostSamples(stages) {
1158
+ if (!Number.isInteger(stages) || stages < 1) {
1159
+ throw new Error(`resampler cascade needs a positive integer stage count (got ${String(stages)})`);
1160
+ }
1161
+ let total = 0;
1162
+ for (let s = 0; s < stages; s += 1) {
1163
+ const center = (resampleStageSpec(s)[0] - 1) / 2;
1164
+ total += (2 * center - 1) / 2 ** (s + 1);
1165
+ }
1166
+ return total;
1167
+ }
1168
+
1030
1169
  // src/taper.ts
1031
1170
  function taperFraction(taper, position) {
1032
1171
  const x = Math.min(1, Math.max(0, position));
@@ -1520,6 +1659,20 @@ var ReferenceRuntime = class {
1520
1659
  * correct at the sub-sample rate. `hostSampleRate()` is the rate a caller passed in.
1521
1660
  */
1522
1661
  oversample = 1;
1662
+ /**
1663
+ * Band-limited resampling around the solver, one 2x half-band stage per
1664
+ * entry, cascaded for 4x and 8x. Empty unless `oversample` is a power of
1665
+ * two greater than 1; any other factor keeps the legacy hold-and-last
1666
+ * path below. Built fresh (zero state) in `prepare()`, so the filter
1667
+ * state never leaks across renders and block splits stay bit-identical.
1668
+ */
1669
+ resampleUp = [];
1670
+ resampleDown = [];
1671
+ /** Scratch for the sub-sample streams, sized to `oversample` in `prepare()`. */
1672
+ resampleBufA = new Float64Array(0);
1673
+ resampleBufB = new Float64Array(0);
1674
+ /** Total resampler group delay in host samples (0 on the legacy path). */
1675
+ resampleLatencyHost = 0;
1523
1676
  positions = /* @__PURE__ */ new Map();
1524
1677
  lastShiftedSample = /* @__PURE__ */ new Map();
1525
1678
  /**
@@ -1760,6 +1913,37 @@ var ReferenceRuntime = class {
1760
1913
  * samples 4800 of 4800 -> 22.
1761
1914
  */
1762
1915
  unproductiveUntilSample = /* @__PURE__ */ new Map();
1916
+ /**
1917
+ * Per block, the last three converged sub-sample solutions and the extrapolation order
1918
+ * that would have predicted the newest of them best, for the Newton start predictor.
1919
+ *
1920
+ * **The start of a Newton solve is a guess, and the previous solution is only the
1921
+ * cheapest guess, not the best one.** At 4x oversampling the circuit moves a quarter as
1922
+ * far per solve, and a quadratic extrapolation of the last three solutions lands inside
1923
+ * the convergence tolerance on most sub-samples, so the first Newton step is already the
1924
+ * answer and the check that follows it is the whole solve: one iteration where the
1925
+ * previous-solution start needs two (one step, one check). Measured 2026-10-09 on the six
1926
+ * profile packets at os4 (`docs/spikes/2026-10-09-newton-iteration-budget.md`): iterations
1927
+ * per host sample fall 38-47 % on the pedals with every converged solution within 0.02
1928
+ * tolerance units of the full-Newton solution from the same state.
1929
+ *
1930
+ * **The order is chosen by the block's own history, not by a constant.** After every
1931
+ * converged solve the three candidate starts the history could have produced (order 0 =
1932
+ * the previous solution, 1 = linear, 2 = quadratic) are scored against the solution just
1933
+ * reached, in tolerance units, and the best one is used for the next solve -- but only
1934
+ * when that solve took at most two iterations (the floor: one step and one check). A
1935
+ * solve that needed more was hunting across a knee, and there a closer start is not a
1936
+ * cheaper one (`recordNewtonSolution` has the measurement). On a hard edge the
1937
+ * extrapolations overshoot the clipping knee and score worse than the previous solution,
1938
+ * so the next solve starts exactly where it always did; on a signal it cannot predict it
1939
+ * costs nothing. A non-converged solve breaks the chain (no history to extrapolate from).
1940
+ *
1941
+ * Only the start moves. The convergence test, the limiter histories, the relaxation rule
1942
+ * and the fold reseed (which reads the caller's `start`, the previous solution) are
1943
+ * untouched, so what converges is still the circuit's equations at the shipped
1944
+ * tolerances -- a different first iterate, the same fixed point.
1945
+ */
1946
+ newtonStartHistory = /* @__PURE__ */ new Map();
1763
1947
  blockNewtonCensus = /* @__PURE__ */ new Map();
1764
1948
  totalIterations = 0;
1765
1949
  nonFiniteSamples = 0;
@@ -2001,6 +2185,28 @@ var ReferenceRuntime = class {
2001
2185
  }
2002
2186
  this.oversample = oversample;
2003
2187
  this.sampleRate = sampleRate2 * oversample;
2188
+ const resampleStages = Math.log2(oversample);
2189
+ if (Number.isInteger(resampleStages) && resampleStages >= 1) {
2190
+ const prototypes = Array.from({ length: resampleStages }, (_, stage) => {
2191
+ const [taps, beta] = resampleStageSpec(stage);
2192
+ return designHalfBand2x(taps, beta);
2193
+ });
2194
+ this.resampleUp = prototypes.map(
2195
+ (prototype) => new HalfBandStage2x(prototype)
2196
+ );
2197
+ this.resampleDown = prototypes.map(
2198
+ (prototype) => new HalfBandStage2x(prototype)
2199
+ );
2200
+ this.resampleBufA = new Float64Array(oversample);
2201
+ this.resampleBufB = new Float64Array(oversample);
2202
+ this.resampleLatencyHost = cascadeLatencyHostSamples(resampleStages);
2203
+ } else {
2204
+ this.resampleUp = [];
2205
+ this.resampleDown = [];
2206
+ this.resampleBufA = new Float64Array(0);
2207
+ this.resampleBufB = new Float64Array(0);
2208
+ this.resampleLatencyHost = 0;
2209
+ }
2004
2210
  this.maxNewtonIterations = maxNewtonIterations;
2005
2211
  this.inputSourceOhms = Math.max(0, options.inputSourceOhms ?? 0);
2006
2212
  this.timeSeconds = 0;
@@ -2016,6 +2222,7 @@ var ReferenceRuntime = class {
2016
2222
  this.solvedButFlaggedSamples = 0;
2017
2223
  this.blockNewtonCensus.clear();
2018
2224
  this.unproductiveUntilSample.clear();
2225
+ this.newtonStartHistory.clear();
2019
2226
  this.totalIterations = 0;
2020
2227
  this.nonFiniteSamples = 0;
2021
2228
  this.peakIterations = 0;
@@ -2749,7 +2956,8 @@ var ReferenceRuntime = class {
2749
2956
  values: new Float64Array(schedule.slots),
2750
2957
  rhs: new Float64Array(size),
2751
2958
  factors: new Float64Array(schedule.factorCount),
2752
- consecutiveFallbacks: 0
2959
+ consecutiveFallbacks: 0,
2960
+ repivotAttempted: false
2753
2961
  });
2754
2962
  }
2755
2963
  /**
@@ -2863,6 +3071,16 @@ var ReferenceRuntime = class {
2863
3071
  * smallest dropped disagreement is `boss-aw-2` at `9.8e+3`. Dense is not
2864
3072
  * assumed right -- `tw-1` diverges on 61 samples densely while converging
2865
3073
  * sparsely -- the gate only fires where the replay demonstrably collapses.
3074
+ *
3075
+ * A validating shipped order is still replaced when the value-aware candidate
3076
+ * reaches the audio-agreement bar (1e-9) an order of magnitude more cleanly
3077
+ * without meaningful fill cost -- the refinement in `SCHEDULE_REFINEMENT_BAR`.
3078
+ * Bar-clean ties keep shipped even when the audios differ: the
3079
+ * operating-point replay cannot adjudicate audio-time divergence (`boss-os-2`
3080
+ * replays 3.4e-10 shipped vs 2.5e-13 candidate while the audios differ 1000x),
3081
+ * so the rule only moves past the bar it can measure, never on a tie.
3082
+ * Measured adopters: `boss-sd-1` (1.8e-9 to 4.2e-13, audio 6.9e-8 to
3083
+ * 6.5e-12).
2866
3084
  */
2867
3085
  settlePivotOrders() {
2868
3086
  if (this.pivotOrdersSettled) {
@@ -2963,10 +3181,8 @@ var ReferenceRuntime = class {
2963
3181
  planRow.worstPivotRatio = worstRatio;
2964
3182
  planRow.pivotDisagreement = Number.isFinite(disagreement) ? disagreement : null;
2965
3183
  }
2966
- if (disagreement <= SCHEDULE_VALIDATION_TOL) {
2967
- continue;
2968
- }
2969
3184
  const candidate = computeNumericRepivot(schedule, size, matrix);
3185
+ let candidateDisagreement = Infinity;
2970
3186
  if (candidate !== null) {
2971
3187
  const candidateValues = new Float64Array(candidate.slots);
2972
3188
  const candidateRhs = new Float64Array(size);
@@ -2988,28 +3204,39 @@ var ReferenceRuntime = class {
2988
3204
  candidateDiffSquares += difference * difference;
2989
3205
  candidateDenseSquares += denseOut[index] ** 2;
2990
3206
  }
2991
- const candidateDisagreement = candidateReplayed ? Math.sqrt(candidateDiffSquares) / Math.max(Math.sqrt(candidateDenseSquares), 1e-9) : Infinity;
2992
- if (candidateDisagreement <= SCHEDULE_VALIDATION_TOL) {
2993
- this.sparseSchedules.set(blockId, {
2994
- schedule: candidate,
2995
- values: new Float64Array(candidate.slots),
2996
- rhs: new Float64Array(size),
2997
- factors: new Float64Array(candidate.factorCount),
2998
- consecutiveFallbacks: 0
2999
- });
3000
- this.repivotedSchedules.add(blockId);
3001
- this.droppedSchedules.delete(blockId);
3002
- if (planRow !== void 0) {
3003
- planRow.path = "sparse";
3004
- planRow.reason = `numeric re-pivot ${candidateDisagreement.toExponential(1)} vs dense`;
3005
- planRow.pivotDisagreement = candidateDisagreement;
3006
- planRow.repivoted = true;
3007
- planRow.patternEntries = candidate.slots;
3008
- planRow.sparseOps = candidate.sparseOps;
3009
- planRow.unprovenPivots = candidate.unprovenPivots;
3010
- }
3207
+ candidateDisagreement = candidateReplayed ? Math.sqrt(candidateDiffSquares) / Math.max(Math.sqrt(candidateDenseSquares), 1e-9) : Infinity;
3208
+ }
3209
+ if (disagreement <= SCHEDULE_VALIDATION_TOL) {
3210
+ if (candidate !== null && shouldRefinePivotOrder({
3211
+ shippedDisagreement: disagreement,
3212
+ candidateDisagreement,
3213
+ shippedOps: schedule.sparseOps,
3214
+ shippedSlots: schedule.slots,
3215
+ candidateOps: candidate.sparseOps,
3216
+ candidateSlots: candidate.slots
3217
+ })) {
3218
+ this.adoptRepivotedSchedule(
3219
+ blockId,
3220
+ candidate,
3221
+ size,
3222
+ planRow,
3223
+ `numeric re-pivot ${candidateDisagreement.toExponential(1)} vs dense (shipped ${Number.isFinite(disagreement) ? disagreement.toExponential(1) : "replay refused"}); +${((candidate.sparseOps / Math.max(schedule.sparseOps, 1) - 1) * 100).toFixed(1)}% ops`,
3224
+ candidateDisagreement
3225
+ );
3011
3226
  continue;
3012
3227
  }
3228
+ continue;
3229
+ }
3230
+ if (candidate !== null && candidateDisagreement <= SCHEDULE_VALIDATION_TOL) {
3231
+ this.adoptRepivotedSchedule(
3232
+ blockId,
3233
+ candidate,
3234
+ size,
3235
+ planRow,
3236
+ `numeric re-pivot ${candidateDisagreement.toExponential(1)} vs dense`,
3237
+ candidateDisagreement
3238
+ );
3239
+ continue;
3013
3240
  }
3014
3241
  this.sparseSchedules.delete(blockId);
3015
3242
  this.droppedSchedules.add(blockId);
@@ -3023,6 +3250,115 @@ var ReferenceRuntime = class {
3023
3250
  }
3024
3251
  }
3025
3252
  }
3253
+ /**
3254
+ * Adopt a value-aware replacement order for a block, from settle or from
3255
+ * the mid-run re-pivot, with one shared bookkeeping shape.
3256
+ *
3257
+ * The replacement's slots are a superset of the shipped filled pattern
3258
+ * whose extra cells no stamp writes (see `computeNumericRepivot`), so the
3259
+ * pattern-sized matrix refresh keeps reading correct zeros and neither
3260
+ * `clearPairs` nor the selective-copy machinery needs a rebuild -- the
3261
+ * same reason a dropped block, which does change the refresh, sets
3262
+ * `clearPairs` to null where this does not.
3263
+ */
3264
+ adoptRepivotedSchedule(blockId, candidate, size, planRow, reason, pivotDisagreement) {
3265
+ this.sparseSchedules.set(blockId, {
3266
+ schedule: candidate,
3267
+ values: new Float64Array(candidate.slots),
3268
+ rhs: new Float64Array(size),
3269
+ factors: new Float64Array(candidate.factorCount),
3270
+ consecutiveFallbacks: 0,
3271
+ repivotAttempted: false
3272
+ });
3273
+ this.repivotedSchedules.add(blockId);
3274
+ this.droppedSchedules.delete(blockId);
3275
+ if (planRow !== void 0) {
3276
+ planRow.path = "sparse";
3277
+ planRow.reason = reason;
3278
+ planRow.pivotDisagreement = pivotDisagreement;
3279
+ planRow.repivoted = true;
3280
+ planRow.patternEntries = candidate.slots;
3281
+ planRow.sparseOps = candidate.sparseOps;
3282
+ planRow.unprovenPivots = candidate.unprovenPivots;
3283
+ }
3284
+ }
3285
+ /**
3286
+ * The mid-run half of the pivot-guard contract: at the consecutive-trip
3287
+ * limit, re-pivot once from the current matrix instead of abandoning.
3288
+ *
3289
+ * Takes the stamped matrix and rhs snapshotted before the dense fallback
3290
+ * destroyed them, plus the fallback's answer, and returns whether a
3291
+ * value-aware order was adopted. Adoption needs the rescue standard --
3292
+ * replay within `SCHEDULE_VALIDATION_TOL` of the dense answer on this
3293
+ * matrix -- the same bar a collapse rescue clears at settle, because this
3294
+ * is a rescue: the shipped order demonstrably does not suit this
3295
+ * operating region. A refusal (null candidate, tripped replay, or a
3296
+ * disagreeing replay) returns false and the caller abandons exactly as
3297
+ * before, with the reason naming the refusal. Either outcome lands in
3298
+ * the plan row, so a mid-run adoption is as visible as a settle one.
3299
+ *
3300
+ * Structured for direct unit testing (pure inputs, boolean verdict): the
3301
+ * corpus never trips the guard, so no corpus run exercises this path.
3302
+ */
3303
+ adoptMidRunRepivot(blockId, entry, matrix, rhs, denseAnswer) {
3304
+ const planRow = this.solverPlanRows.find(
3305
+ (candidate2) => candidate2.blockId === blockId
3306
+ );
3307
+ const block = this.blocksById.get(blockId);
3308
+ const size = block !== void 0 && block.kind === "mna" ? block.nodeCount + block.auxCount : 0;
3309
+ const refuse = (reason) => {
3310
+ if (planRow !== void 0) {
3311
+ planRow.reason += ` mid-run re-pivot ${reason}; abandoned`;
3312
+ }
3313
+ return false;
3314
+ };
3315
+ if (block === void 0 || block.kind !== "mna" || size <= 0) {
3316
+ return refuse("refused (unknown block)");
3317
+ }
3318
+ const candidate = computeNumericRepivot(entry.schedule, size, matrix);
3319
+ if (candidate === null) {
3320
+ return refuse("refused (no candidate meets the threshold)");
3321
+ }
3322
+ const values = new Float64Array(candidate.slots);
3323
+ const scratchRhs = new Float64Array(size);
3324
+ const factors = new Float64Array(candidate.factorCount);
3325
+ const out = new Array(size).fill(0);
3326
+ const replayed = runSparseSchedule(
3327
+ candidate,
3328
+ matrix,
3329
+ rhs,
3330
+ values,
3331
+ scratchRhs,
3332
+ factors,
3333
+ out
3334
+ );
3335
+ let diffSquares = 0;
3336
+ let denseSquares = 0;
3337
+ for (let index = 0; index < size; index += 1) {
3338
+ const difference = out[index] - denseAnswer[index];
3339
+ diffSquares += difference * difference;
3340
+ denseSquares += denseAnswer[index] ** 2;
3341
+ }
3342
+ const disagreement = replayed ? Math.sqrt(diffSquares) / Math.max(Math.sqrt(denseSquares), 1e-9) : Infinity;
3343
+ if (!(disagreement <= SCHEDULE_VALIDATION_TOL)) {
3344
+ return refuse(
3345
+ `refused (replay ${Number.isFinite(disagreement) ? disagreement.toExponential(1) : "tripped"} vs dense)`
3346
+ );
3347
+ }
3348
+ this.adoptRepivotedSchedule(
3349
+ blockId,
3350
+ candidate,
3351
+ size,
3352
+ planRow,
3353
+ `mid-run numeric re-pivot ${disagreement.toExponential(1)} vs dense after ${SCHEDULE_CONSECUTIVE_FALLBACK_LIMIT} guard trips`,
3354
+ disagreement
3355
+ );
3356
+ const adopted = this.sparseSchedules.get(blockId);
3357
+ if (adopted !== void 0) {
3358
+ adopted.repivotAttempted = true;
3359
+ }
3360
+ return true;
3361
+ }
3026
3362
  /**
3027
3363
  * Which blocks took the static schedule and which kept the dense solve, and how often the
3028
3364
  * pivot guard sent a solve back to the dense path.
@@ -3051,52 +3387,131 @@ var ReferenceRuntime = class {
3051
3387
  }
3052
3388
  const output = new Float64Array(input.length);
3053
3389
  this.samples += input.length;
3054
- for (let index = 0; index < input.length; index += 1) {
3055
- const sample = input[index] ?? 0;
3056
- let hostResult = 0;
3057
- let hostNonConverged = false;
3058
- let hostNonFinite = false;
3059
- for (let sub = 0; sub < this.oversample; sub += 1) {
3060
- this.timeSeconds = this.elapsedSamples / this.sampleRate;
3061
- let result = 0;
3062
- this.sampleNonConverged = false;
3063
- this.sampleNonFinite = false;
3064
- for (const id of this.program.order) {
3065
- const block = this.blocksById.get(id);
3066
- if (block === void 0) {
3067
- continue;
3068
- }
3069
- const blockOutput = this.processBlock(block, sample);
3070
- if (block.kind === "mna" && block.outputNode !== null) {
3071
- result = blockOutput;
3072
- }
3073
- }
3074
- if (this.sampleNonConverged) {
3075
- hostNonConverged = true;
3076
- }
3077
- if (this.sampleNonFinite) {
3078
- hostNonFinite = true;
3079
- }
3080
- for (const branch of this.supplyBranchSlots) {
3081
- const amps = this.nodeVoltages.get(branch.blockId)?.[branch.slot] ?? 0;
3082
- const magnitude = Math.abs(amps);
3083
- if (magnitude > this.renderedSupplyPeakAmps) {
3084
- this.renderedSupplyPeakAmps = magnitude;
3085
- }
3086
- }
3087
- this.elapsedSamples += 1;
3088
- hostResult = result;
3390
+ if (this.resampleUp.length === 0) {
3391
+ for (let index = 0; index < input.length; index += 1) {
3392
+ output[index] = this.processHeldSample(input[index] ?? 0);
3089
3393
  }
3090
- if (hostNonConverged) {
3091
- this.nonConvergedSamples += 1;
3092
- }
3093
- if (hostNonFinite) {
3094
- this.nonFiniteSamples += 1;
3394
+ } else {
3395
+ for (let index = 0; index < input.length; index += 1) {
3396
+ output[index] = this.processResampledSample(input[index] ?? 0);
3095
3397
  }
3096
- output[index] = hostResult;
3097
3398
  }
3098
3399
  return output;
3099
3400
  }
3401
+ /**
3402
+ * One host sample through the legacy path: the input held flat across the
3403
+ * sub-samples, the last sub-sample kept. Bit-identical to the behaviour
3404
+ * before the band-limited resampler existed, which is what makes factor 1
3405
+ * (and non-power-of-two factors) cost nothing and change nothing.
3406
+ */
3407
+ processHeldSample(sample) {
3408
+ let hostResult = 0;
3409
+ let hostNonConverged = false;
3410
+ let hostNonFinite = false;
3411
+ for (let sub = 0; sub < this.oversample; sub += 1) {
3412
+ hostResult = this.solveSubSample(sample);
3413
+ if (this.sampleNonConverged) {
3414
+ hostNonConverged = true;
3415
+ }
3416
+ if (this.sampleNonFinite) {
3417
+ hostNonFinite = true;
3418
+ }
3419
+ }
3420
+ if (hostNonConverged) {
3421
+ this.nonConvergedSamples += 1;
3422
+ }
3423
+ if (hostNonFinite) {
3424
+ this.nonFiniteSamples += 1;
3425
+ }
3426
+ return hostResult;
3427
+ }
3428
+ /**
3429
+ * One host sample through the band-limited path: half-band interpolate up
3430
+ * by 2 per stage, solve each sub-sample, FIR-decimate back to one host
3431
+ * sample. The resampler state lives on the stages across `process()`
3432
+ * calls, so any block split renders bit-identically to one long call;
3433
+ * the group delay this adds is reported by `oversampleLatency()`.
3434
+ */
3435
+ processResampledSample(sample) {
3436
+ const stages = this.resampleUp.length;
3437
+ let cur = this.resampleBufA;
3438
+ let next = this.resampleBufB;
3439
+ this.resampleUp[0].interpolate(sample, cur, 0);
3440
+ let width = 2;
3441
+ for (let stage = 1; stage < stages; stage += 1) {
3442
+ for (let i = 0; i < width; i += 1) {
3443
+ this.resampleUp[stage].interpolate(
3444
+ cur[i],
3445
+ next,
3446
+ 2 * i
3447
+ );
3448
+ }
3449
+ const swap = cur;
3450
+ cur = next;
3451
+ next = swap;
3452
+ width *= 2;
3453
+ }
3454
+ let hostNonConverged = false;
3455
+ let hostNonFinite = false;
3456
+ for (let sub = 0; sub < width; sub += 1) {
3457
+ next[sub] = this.solveSubSample(cur[sub]);
3458
+ if (this.sampleNonConverged) {
3459
+ hostNonConverged = true;
3460
+ }
3461
+ if (this.sampleNonFinite) {
3462
+ hostNonFinite = true;
3463
+ }
3464
+ }
3465
+ const hi = next;
3466
+ for (let stage = stages - 1; stage >= 0; stage -= 1) {
3467
+ const half = width / 2;
3468
+ for (let i = 0; i < half; i += 1) {
3469
+ hi[i] = this.resampleDown[stage].decimate(
3470
+ hi[2 * i],
3471
+ hi[2 * i + 1]
3472
+ );
3473
+ }
3474
+ width = half;
3475
+ }
3476
+ if (hostNonConverged) {
3477
+ this.nonConvergedSamples += 1;
3478
+ }
3479
+ if (hostNonFinite) {
3480
+ this.nonFiniteSamples += 1;
3481
+ }
3482
+ return hi[0];
3483
+ }
3484
+ /**
3485
+ * One sub-sample solve at the solver rate: every block stepped once at
3486
+ * `t = elapsedSamples / sampleRate`, returning the output jack's value.
3487
+ * Shared by the held and the resampled paths, so factor 1 executes the
3488
+ * same operations in the same order as before the resampler existed.
3489
+ */
3490
+ solveSubSample(subInput) {
3491
+ this.timeSeconds = this.elapsedSamples / this.sampleRate;
3492
+ let result = 0;
3493
+ this.sampleNonConverged = false;
3494
+ this.sampleNonFinite = false;
3495
+ for (const id of this.program.order) {
3496
+ const block = this.blocksById.get(id);
3497
+ if (block === void 0) {
3498
+ continue;
3499
+ }
3500
+ const blockOutput = this.processBlock(block, subInput);
3501
+ if (block.kind === "mna" && block.outputNode !== null) {
3502
+ result = blockOutput;
3503
+ }
3504
+ }
3505
+ for (const branch of this.supplyBranchSlots) {
3506
+ const amps = this.nodeVoltages.get(branch.blockId)?.[branch.slot] ?? 0;
3507
+ const magnitude = Math.abs(amps);
3508
+ if (magnitude > this.renderedSupplyPeakAmps) {
3509
+ this.renderedSupplyPeakAmps = magnitude;
3510
+ }
3511
+ }
3512
+ this.elapsedSamples += 1;
3513
+ return result;
3514
+ }
3100
3515
  /**
3101
3516
  * The rate the caller passed to `prepare`, as opposed to the solver's sub-sample rate.
3102
3517
  *
@@ -3106,6 +3521,17 @@ var ReferenceRuntime = class {
3106
3521
  hostSampleRate() {
3107
3522
  return this.sampleRate === null ? null : this.sampleRate / this.oversample;
3108
3523
  }
3524
+ /**
3525
+ * The resampler's total group delay in **host** samples, or `null` before
3526
+ * `prepare()`. Zero when the resampler is bypassed (factor 1, or a factor
3527
+ * that is not a power of two and keeps the legacy path): the held path
3528
+ * adds no latency by construction. At 2x/4x/8x this is 19.5/26.25/28.625
3529
+ * host samples for the stage-specific half-band cascade -- a real, reported
3530
+ * latency the caller must absorb or declare, not a hidden one.
3531
+ */
3532
+ oversampleLatency() {
3533
+ return this.sampleRate === null ? null : this.resampleLatencyHost;
3534
+ }
3109
3535
  processBlock(block, input) {
3110
3536
  if (block.kind === "composed") {
3111
3537
  this.processComposedBlock(block);
@@ -3571,8 +3997,10 @@ var ReferenceRuntime = class {
3571
3997
  const { matrix, rhs, solutionA, solutionB } = scratch;
3572
3998
  const sparse = dc ? void 0 : this.sparseSchedules.get(block.id);
3573
3999
  const blockIndex = this.blockIndexById.get(block.id) ?? 0;
4000
+ const predictorPass = !dc && sourceScale === 1 && gmin === GMIN_SIEMENS && !block.linear;
4001
+ const seed = (predictorPass ? this.predictedNewtonStart(block.id, size) : null) ?? start;
3574
4002
  for (let index = 0; index < size; index += 1) {
3575
- solutionA[index] = start[index] ?? 0;
4003
+ solutionA[index] = seed[index] ?? 0;
3576
4004
  }
3577
4005
  let current = solutionA;
3578
4006
  let next = solutionB;
@@ -3690,11 +4118,26 @@ var ReferenceRuntime = class {
3690
4118
  this.scheduleFallbacks += 1;
3691
4119
  sparse.consecutiveFallbacks += 1;
3692
4120
  if (sparse.consecutiveFallbacks >= SCHEDULE_CONSECUTIVE_FALLBACK_LIMIT) {
3693
- this.sparseSchedules.delete(block.id);
3694
- this.abandonedSchedules.add(block.id);
4121
+ if (!sparse.repivotAttempted) {
4122
+ sparse.repivotAttempted = true;
4123
+ const matrixCopy = matrix.map((row) => [...row]);
4124
+ const rhsCopy = [...rhs];
4125
+ scratch.denseDirty = true;
4126
+ solve(matrix, rhs, next);
4127
+ if (!this.adoptMidRunRepivot(block.id, sparse, matrixCopy, rhsCopy, next)) {
4128
+ this.sparseSchedules.delete(block.id);
4129
+ this.abandonedSchedules.add(block.id);
4130
+ }
4131
+ } else {
4132
+ this.sparseSchedules.delete(block.id);
4133
+ this.abandonedSchedules.add(block.id);
4134
+ scratch.denseDirty = true;
4135
+ solve(matrix, rhs, next);
4136
+ }
4137
+ } else {
4138
+ scratch.denseDirty = true;
4139
+ solve(matrix, rhs, next);
3695
4140
  }
3696
- scratch.denseDirty = true;
3697
- solve(matrix, rhs, next);
3698
4141
  }
3699
4142
  }
3700
4143
  if (relaxing) {
@@ -3789,6 +4232,9 @@ var ReferenceRuntime = class {
3789
4232
  if (used > census.peakIterations) census.peakIterations = used;
3790
4233
  }
3791
4234
  }
4235
+ if (predictorPass) {
4236
+ this.recordNewtonSolution(block.id, current, converged, used);
4237
+ }
3792
4238
  return { solution: current, converged, used, worstNode, worstDelta };
3793
4239
  }
3794
4240
  /**
@@ -4005,8 +4451,10 @@ var ReferenceRuntime = class {
4005
4451
  full[portRows[p]] = y[p];
4006
4452
  }
4007
4453
  };
4454
+ const predictorPass = !dc && sourceScale === 1 && gmin === GMIN_SIEMENS && !block.linear;
4455
+ const seed = (predictorPass ? this.predictedNewtonStart(block.id, size) : null) ?? start;
4008
4456
  for (let p = 0; p < portCount; p += 1) {
4009
- scratch.yCurrent[p] = start[portRows[p]] ?? 0;
4457
+ scratch.yCurrent[p] = seed[portRows[p]] ?? 0;
4010
4458
  }
4011
4459
  reconstructFull(scratch.yCurrent, scratch.fullCurrent);
4012
4460
  const iterations = this.maxNewtonIterations;
@@ -4138,6 +4586,9 @@ var ReferenceRuntime = class {
4138
4586
  if (used > census.peakIterations) census.peakIterations = used;
4139
4587
  }
4140
4588
  }
4589
+ if (predictorPass) {
4590
+ this.recordNewtonSolution(block.id, current, converged, used);
4591
+ }
4141
4592
  return { solution: current, converged, used, worstNode, worstDelta };
4142
4593
  }
4143
4594
  /**
@@ -4379,6 +4830,86 @@ var ReferenceRuntime = class {
4379
4830
  this.opampHistory.clear();
4380
4831
  this.triodeHistory.clear();
4381
4832
  }
4833
+ /**
4834
+ * The Newton start `newtonStartHistory` selects for this block, or `null` to start from
4835
+ * the caller's previous solution (order 0, or a chain too short for the chosen order).
4836
+ * The returned array is the block's reused scratch: read it before the next solve.
4837
+ */
4838
+ predictedNewtonStart(blockId, size) {
4839
+ const history = this.newtonStartHistory.get(blockId);
4840
+ if (history === void 0 || history.order === 0) {
4841
+ return null;
4842
+ }
4843
+ if (history.candidate.length !== size) {
4844
+ history.candidate = new Array(size).fill(0);
4845
+ }
4846
+ return extrapolateNewtonStart(history, history.order, size, history.candidate) ? history.candidate : null;
4847
+ }
4848
+ /**
4849
+ * Record a finished standard-pass solve: on convergence, score the three candidate
4850
+ * starts the history could have produced against the solution just reached (one fused
4851
+ * pass, no allocation) and keep the best order for the next solve, then rotate the
4852
+ * solution into the history ring; on failure, break the chain.
4853
+ */
4854
+ recordNewtonSolution(blockId, solution, converged, used) {
4855
+ let history = this.newtonStartHistory.get(blockId);
4856
+ if (history === void 0) {
4857
+ history = { x1: null, x2: null, x3: null, chain: 0, order: 0, candidate: [] };
4858
+ this.newtonStartHistory.set(blockId, history);
4859
+ }
4860
+ if (!converged) {
4861
+ history.chain = 0;
4862
+ history.order = 0;
4863
+ return;
4864
+ }
4865
+ const size = solution.length;
4866
+ const { x1, x2, x3 } = history;
4867
+ const has1 = history.chain >= 1 && x1 !== null && x1.length === size;
4868
+ const has2 = has1 && history.chain >= 2 && x2 !== null && x2.length === size;
4869
+ const has3 = has2 && history.chain >= 3 && x3 !== null && x3.length === size;
4870
+ let error0 = has1 ? 0 : Number.POSITIVE_INFINITY;
4871
+ let error1 = has2 ? 0 : Number.POSITIVE_INFINITY;
4872
+ let error2 = has3 ? 0 : Number.POSITIVE_INFINITY;
4873
+ if (has1) {
4874
+ for (let index = 0; index < size; index += 1) {
4875
+ const s = solution[index];
4876
+ const magnitude = Math.abs(s);
4877
+ const v1 = x1[index];
4878
+ const ratio0 = Math.abs(v1 - s) / (NEWTON_RELATIVE_TOLERANCE * Math.max(Math.abs(v1), magnitude) + NEWTON_VOLTAGE_TOLERANCE);
4879
+ if (ratio0 > error0) error0 = ratio0;
4880
+ if (!has2) continue;
4881
+ const v2 = x2[index];
4882
+ const guess1 = 2 * v1 - v2;
4883
+ const ratio1 = Math.abs(guess1 - s) / (NEWTON_RELATIVE_TOLERANCE * Math.max(Math.abs(guess1), magnitude) + NEWTON_VOLTAGE_TOLERANCE);
4884
+ if (ratio1 > error1) error1 = ratio1;
4885
+ if (!has3) continue;
4886
+ const guess2 = 3 * v1 - 3 * v2 + x3[index];
4887
+ const ratio2 = Math.abs(guess2 - s) / (NEWTON_RELATIVE_TOLERANCE * Math.max(Math.abs(guess2), magnitude) + NEWTON_VOLTAGE_TOLERANCE);
4888
+ if (ratio2 > error2) error2 = ratio2;
4889
+ }
4890
+ }
4891
+ let best = 0;
4892
+ let bestError = error0;
4893
+ if (error1 < bestError) {
4894
+ best = 1;
4895
+ bestError = error1;
4896
+ }
4897
+ if (error2 < bestError) {
4898
+ best = 2;
4899
+ }
4900
+ if (used > 2) {
4901
+ best = 0;
4902
+ }
4903
+ history.order = best;
4904
+ const oldest = history.x3;
4905
+ history.x3 = history.x2;
4906
+ history.x2 = history.x1;
4907
+ history.x1 = oldest !== null && oldest.length === size ? oldest : new Array(size).fill(0);
4908
+ for (let index = 0; index < size; index += 1) {
4909
+ history.x1[index] = solution[index];
4910
+ }
4911
+ history.chain += 1;
4912
+ }
4382
4913
  snapshotLimiterHistories() {
4383
4914
  return {
4384
4915
  diode: new Map(this.diodeHistory),
@@ -5570,8 +6101,17 @@ function solve(matrix, rhs, out) {
5570
6101
  var SCHEDULE_OP_WIDTH = 4;
5571
6102
  var SCHEDULE_PIVOT_FLOOR = 1e-18;
5572
6103
  var SCHEDULE_VALIDATION_TOL = 1e-3;
6104
+ var SCHEDULE_REFINEMENT_BAR = 1e-9;
6105
+ var SCHEDULE_REFINEMENT_RATIO = 10;
6106
+ var SCHEDULE_REFINEMENT_MAX_COST_GROWTH = 1.1;
5573
6107
  var SCHEDULE_MINIMUM_SAVING = 4;
5574
6108
  var SCHEDULE_CONSECUTIVE_FALLBACK_LIMIT = 64;
6109
+ function shouldRefinePivotOrder(input) {
6110
+ if (!Number.isFinite(input.shippedDisagreement) || !Number.isFinite(input.candidateDisagreement)) {
6111
+ return false;
6112
+ }
6113
+ return input.shippedDisagreement > SCHEDULE_REFINEMENT_BAR && input.candidateDisagreement <= SCHEDULE_REFINEMENT_BAR && input.candidateDisagreement < input.shippedDisagreement / SCHEDULE_REFINEMENT_RATIO && input.candidateOps <= SCHEDULE_REFINEMENT_MAX_COST_GROWTH * input.shippedOps && input.candidateSlots <= SCHEDULE_REFINEMENT_MAX_COST_GROWTH * input.shippedSlots;
6114
+ }
5575
6115
  function runSparseSchedule(schedule, matrix, rhs, values, scratchRhs, factors, out) {
5576
6116
  const { ops, gatherRow, gatherColumn, slots, size } = schedule;
5577
6117
  for (let index = 0; index < slots; index += 1) {
@@ -5692,6 +6232,26 @@ function relativeResidual(matrix, rhs, x, pairs, size) {
5692
6232
  }
5693
6233
  return Number.isFinite(worst) ? worst : Number.POSITIVE_INFINITY;
5694
6234
  }
6235
+ function extrapolateNewtonStart(history, order, size, out) {
6236
+ const { x1, x2, x3, chain } = history;
6237
+ if (order === 0) {
6238
+ if (chain < 1 || x1 === null) return false;
6239
+ for (let index = 0; index < size; index += 1) out[index] = x1[index];
6240
+ return true;
6241
+ }
6242
+ if (order === 1) {
6243
+ if (chain < 2 || x1 === null || x2 === null) return false;
6244
+ for (let index = 0; index < size; index += 1) {
6245
+ out[index] = 2 * x1[index] - x2[index];
6246
+ }
6247
+ return true;
6248
+ }
6249
+ if (chain < 3 || x1 === null || x2 === null || x3 === null) return false;
6250
+ for (let index = 0; index < size; index += 1) {
6251
+ out[index] = 3 * x1[index] - 3 * x2[index] + x3[index];
6252
+ }
6253
+ return true;
6254
+ }
5695
6255
  function withinTolerance(next, previous) {
5696
6256
  for (let index = 0; index < next.length; index += 1) {
5697
6257
  const a = next[index] ?? 0;
@@ -6127,7 +6687,33 @@ var V2WasmEngine = class _V2WasmEngine {
6127
6687
  const sr = options.sampleRate ?? 48e3;
6128
6688
  const maxIters = options.maxNewtonIterations ?? DEFAULT_NEWTON_MAX_ITERATIONS;
6129
6689
  const inputOhms = options.inputSourceOhms ?? 0;
6130
- this.mod._v2_engine_prepare(this.handle, sr, maxIters, inputOhms);
6690
+ const oversample = Math.max(1, Math.floor(options.oversample ?? 1));
6691
+ if (!Number.isFinite(oversample)) {
6692
+ throw new RuntimeError(
6693
+ `oversample must be a finite integer of at least 1, got ${String(options.oversample)}`
6694
+ );
6695
+ }
6696
+ this.mod._v2_engine_prepare(this.handle, sr, maxIters, inputOhms, oversample);
6697
+ }
6698
+ /**
6699
+ * The rate `prepare` was called with (the host rate), as opposed to the
6700
+ * solver's sub-sample rate -- the same name and semantics as
6701
+ * `ReferenceRuntime.hostSampleRate()`, including `null` before
6702
+ * `prepare()`.
6703
+ */
6704
+ hostSampleRate() {
6705
+ const value = this.mod._v2_engine_get_host_sample_rate(this.handle);
6706
+ return value < 0 ? null : value;
6707
+ }
6708
+ /**
6709
+ * The resampler's total group delay in **host** samples -- the same name
6710
+ * and semantics as `ReferenceRuntime.oversampleLatency()`, including
6711
+ * `null` before `prepare()` and 0 on the held path (factor 1 or a factor
6712
+ * that is not a power of two).
6713
+ */
6714
+ oversampleLatency() {
6715
+ const value = this.mod._v2_engine_get_oversample_latency(this.handle);
6716
+ return value < 0 ? null : value;
6131
6717
  }
6132
6718
  reset() {
6133
6719
  this.mod._v2_engine_reset(this.handle);
@@ -6318,6 +6904,25 @@ var V2WasmEngine = class _V2WasmEngine {
6318
6904
  * A healthy packet reads `fallbacks === 0` and `abandonedBlocks === 0`. Anything else is a
6319
6905
  * cost defect even though the audio is correct.
6320
6906
  */
6907
+ /**
6908
+ * Newton start predictor telemetry, the console-side mirror of the reference's
6909
+ * `newtonStartHistory` decisions: `seedsUsed` counts standard-pass solves that started
6910
+ * from an extrapolated solution (order > 0), `oneIterationSolves` those that converged in
6911
+ * exactly one iteration -- the saving itself, attributable on the shipping console.
6912
+ * Counted since `prepare()`/`reset()`. `predictorOrder(blockIdx)` reads the order the
6913
+ * block's next solve will seed from (0 = previous solution, 1 = linear, 2 = quadratic;
6914
+ * -1 for a bad index), so a decision can be compared against the reference per sample.
6915
+ */
6916
+ getPredictorTelemetry() {
6917
+ return {
6918
+ seedsUsed: this.mod._v2_engine_get_predictor_seeds(this.handle),
6919
+ oneIterationSolves: this.mod._v2_engine_get_one_iteration_solves(this.handle),
6920
+ totalIterations: this.mod._v2_engine_get_total_iterations(this.handle)
6921
+ };
6922
+ }
6923
+ getPredictorOrder(blockIdx) {
6924
+ return this.mod._v2_engine_get_predictor_order(this.handle, blockIdx);
6925
+ }
6321
6926
  getScheduleTelemetry() {
6322
6927
  return {
6323
6928
  solves: this.mod._v2_engine_get_schedule_solves(this.handle),