@swf2es/codegen 0.1.41 → 0.1.43

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/src/index.ts CHANGED
@@ -201,7 +201,12 @@ export interface LoggedModule {
201
201
  log: string | null;
202
202
  }
203
203
 
204
- /** How long compactStep may go on: as an IdleDeadline, the milliseconds left. */
204
+ /**
205
+ * How long compactStep may go on: as an IdleDeadline, the milliseconds left. One that goes below
206
+ * 0 as the time passes its end, rather than stop at 0 as an IdleDeadline does, lets compactStep
207
+ * go past it where it would (see compactStep), as it can tell how far; one that stops at 0 ends
208
+ * each slice at it, after one part at least.
209
+ */
205
210
  export interface CompactDeadline {
206
211
  timeRemaining(): number;
207
212
  }
@@ -217,18 +222,24 @@ export type MoveAbort =
217
222
  | "refused"
218
223
  /** A call meanwhile could not be journaled, so the spare could not catch up. */
219
224
  | "unjournaled"
220
- /** The domain was reset, recovered from a panic, or rebuilt in place meanwhile. */
225
+ /**
226
+ * The domain was reset, recovered from a panic, or rebuilt in place
227
+ * meanwhile; or a revival took the place of a move that only compacted
228
+ * (see reviveDomain).
229
+ */
221
230
  | "superseded";
222
231
 
223
232
  /**
224
- * compactStep's moves: started, completed, and given up by why; and of the
225
- * last one completed, the calls replayed into its spare after its rebuild,
226
- * and the bytes of its snapshot, which recovery keeps as its checkpoint.
233
+ * compactStep's moves: started, completed, and given up by why; the
234
+ * domains revived by those completed (see reviveDomain); and of the last
235
+ * one completed, the calls replayed into its spare after its rebuild, and
236
+ * the bytes of its snapshot, which recovery keeps as its checkpoint.
227
237
  */
228
238
  export interface MoveCounts {
229
239
  started: number;
230
240
  completed: number;
231
241
  aborted: Record<MoveAbort, number>;
242
+ revived: number;
232
243
  lastCaughtUp: number;
233
244
  lastSavedBytes: number;
234
245
  }
@@ -293,9 +304,12 @@ export interface Codegen {
293
304
  /**
294
305
  * compact a part at a time, for a host that goes on compiling meanwhile:
295
306
  * a move into the spare instance is snapshotted, loaded and rebuilt there
296
- * while `deadline.timeRemaining()` is above 0 (one part at least), the
297
- * calls made meanwhile replayed into it, and it takes this instance's
298
- * place once it has caught up. "moving" while some is left, to be called
307
+ * while `deadline.timeRemaining()` is above 0, the calls made meanwhile
308
+ * replayed into it, and it takes this instance's place once it has
309
+ * caught up. A slice makes one part at least, of some 5 ms at most; a
310
+ * deadline that goes below 0 past its end lets it go on starting parts
311
+ * until 9 ms from its start while the spare rebuilds, and until 25 ms,
312
+ * later 50, while it catches up with a host that keeps outrunning it. "moving" while some is left, to be called
299
313
  * again; "done" once a rebuild finished in this call; "none" if none was
300
314
  * due, or the move was given up, the domain left as it was. Only a small
301
315
  * domain is rebuilt in place, in one call; a larger one moves.
@@ -336,9 +350,22 @@ export interface Codegen {
336
350
  * ancestors, the first of them a child of a live domain: given all their
337
351
  * ABCs again by their indices, as they were added, their ABCs link as
338
352
  * they did, by one rebuild at most, and what they found holds. Throws if
339
- * they cannot be.
353
+ * they cannot be. True once live.
354
+ *
355
+ * A rebuild of a large domain takes seconds, so `stepped`, a revival that
356
+ * needs one is made by a move into the spare instance instead, a part at
357
+ * a time as compactStep moves a domain to compact it, the domain staying
358
+ * evicted here until the spare takes this instance's place: then false,
359
+ * and compactStep carries the move on ("moving" until it is done), while
360
+ * the host goes on compiling elsewhere; isLive tells when it is live, and
361
+ * calling this again meanwhile returns false. The host asks again with
362
+ * the chain's ABCs as they are then: a chain an eviction lengthened needs
363
+ * the new ancestor's, and those of a domain revived meanwhile are not
364
+ * taken. A revival that needs no rebuild, or only a small one, is done at
365
+ * once, and so is one whose move was given up as failed, in place as
366
+ * without `stepped`; without it, a revival under way finishes its move.
340
367
  */
341
- reviveDomain(appDomain: number, abcs: Map<number, Uint8Array>): void;
368
+ reviveDomain(appDomain: number, abcs: Map<number, Uint8Array>, stepped?: boolean): boolean;
342
369
  /** Record a definition an application domain has found; it holds for the ABCs added after. */
343
370
  found(definition: FoundDefinition): void;
344
371
  /**
@@ -579,6 +606,12 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
579
606
  interface Checkpoint {
580
607
  state: Uint8Array;
581
608
  abcs: Map<number, Uint8Array>;
609
+ /**
610
+ * Evicted domains the load revives before it rebuilds, a move's
611
+ * revivals (see Revival), and their ABCs' bytes: the rebuild then
612
+ * links them in their places, as a revival's rebuild here would.
613
+ */
614
+ revive?: { domains: number[]; abcs: Map<number, Uint8Array> };
582
615
  }
583
616
  let checkpoint: Checkpoint | null = null;
584
617
  const saveCheckpoint = (): Checkpoint => {
@@ -598,11 +631,18 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
598
631
  if (!loaded) {
599
632
  return false;
600
633
  }
601
- for (const [index, abc] of saved.abcs) {
602
- if (into.domainLoadAbc(index, abc) !== 0) {
634
+ for (const domain of saved.revive?.domains ?? []) {
635
+ if (into.domainLoadRevive(domain) !== 0) {
603
636
  return false;
604
637
  }
605
638
  }
639
+ for (const abcs of [saved.abcs, saved.revive?.abcs ?? []]) {
640
+ for (const [index, abc] of abcs) {
641
+ if (into.domainLoadAbc(index, abc) !== 0) {
642
+ return false;
643
+ }
644
+ }
645
+ }
606
646
  return into.domainLoadRebuild();
607
647
  };
608
648
  // The rebuild domainCompact, domainRevive or domainLoadRebuild started in
@@ -667,6 +707,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
667
707
  started: 0,
668
708
  completed: 0,
669
709
  aborted: { spare: 0, refused: 0, unjournaled: 0, superseded: 0 },
710
+ revived: 0,
670
711
  lastCaughtUp: 0,
671
712
  lastSavedBytes: 0,
672
713
  };
@@ -677,8 +718,25 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
677
718
  // same domain would likely fail the same way.
678
719
  let lettings = 0;
679
720
  let retryAt = 0;
721
+ // The revivals reviveDomain left to a move, in the order asked for, until
722
+ // a move made them, or the domain is no longer evicted here; one whose
723
+ // move was given up as failed is done in place when asked for again.
724
+ interface Revival {
725
+ appDomain: number;
726
+ abcs: Map<number, Uint8Array>;
727
+ failed: boolean;
728
+ }
729
+ const revivals: Revival[] = [];
730
+ // Whether the last spare could not be instantiated, so that a revival waiting for one is done in place.
731
+ let spareFailed = false;
680
732
  const abortMove = (why: MoveAbort) => {
681
733
  if (move !== null) {
734
+ if (why === "spare" || why === "refused") {
735
+ for (const r of move.revivals) {
736
+ r.failed = true;
737
+ }
738
+ }
739
+
682
740
  move = null;
683
741
  moves.aborted[why]++;
684
742
  if (why !== "superseded") {
@@ -697,9 +755,11 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
697
755
  (made) => {
698
756
  spare = made;
699
757
  making = false;
758
+ spareFailed = false;
700
759
  },
701
760
  () => {
702
761
  making = false;
762
+ spareFailed = true;
703
763
  },
704
764
  );
705
765
  }
@@ -768,9 +828,12 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
768
828
  }
769
829
  // A move compactStep makes a part at a time: the spare it rebuilds in,
770
830
  // the snapshot it rebuilds, the calls journaled since, how many of those
771
- // the spare has replayed and where in one it is; the bytes of the ABCs
772
- // revivals since restored in it, copied once; the saved ABCs not yet
773
- // given to it; its phase; and the slices it has spent catching up.
831
+ // the spare has replayed, where in one it is and whether a verification
832
+ // there is under way, a part at a time; the bytes of the ABCs
833
+ // revivals since restored in it, copied once; the ABCs to give it, saved
834
+ // and revived, and how many it has been given; the revivals it makes,
835
+ // which its snapshot carries; its phase; and the slices it has spent
836
+ // catching up.
774
837
  interface Move {
775
838
  into: Bound;
776
839
  saved: Checkpoint;
@@ -778,8 +841,14 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
778
841
  replayed: number;
779
842
  /** Where in the log entry being replayed, a compile's, the spare is. */
780
843
  word: number;
844
+ /** Whether the spare is verifying the ABC of the entry at `word` a part at a time (replayEntryStep). */
845
+ verifying: boolean;
781
846
  restored: Map<number, Uint8Array>;
782
- abcs: IterableIterator<[number, Uint8Array]> | null;
847
+ abcs: [number, Uint8Array][];
848
+ given: number;
849
+ revivals: Revival[];
850
+ /** The domains evicted at the snapshot, which a revival folded in must find its chain among (see scheduleRevivals). */
851
+ evicted: Set<number>;
783
852
  phase: "load" | "abcs" | "rebuild" | "catch up";
784
853
  catchUp: number;
785
854
  }
@@ -790,8 +859,10 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
790
859
  let bytes = 0;
791
860
  if (checkpoint) {
792
861
  bytes += checkpoint.state.byteLength;
793
- for (const abc of checkpoint.abcs.values()) {
794
- bytes += abc.byteLength;
862
+ for (const abcs of [checkpoint.abcs, checkpoint.revive?.abcs ?? new Map()]) {
863
+ for (const abc of abcs.values()) {
864
+ bytes += abc.byteLength;
865
+ }
795
866
  }
796
867
  }
797
868
 
@@ -816,8 +887,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
816
887
  };
817
888
  const restores = new Map<number, Entry>();
818
889
  const abcDomains: number[] = [];
819
- // Each ABC's length, by its index, which a replay of its verification takes time in proportion to.
820
- const abcLengths: number[] = [];
821
890
  let replayable = true;
822
891
  const journaled = (entry: Entry, owner = 0) => {
823
892
  const id = owner | 0;
@@ -960,6 +1029,13 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
960
1029
  into.domainEvict(entry.appDomain);
961
1030
  break;
962
1031
  case "restore":
1032
+ // One of a domain a move's load revived (Checkpoint.revive), which
1033
+ // this instance, still evicting it, gave back for a revival of
1034
+ // another under it: `into` holds it, live.
1035
+ if (into.domainState(abcDomains[entry.index] ?? -1) === 0) {
1036
+ break;
1037
+ }
1038
+
963
1039
  if (into.domainRestore(entry.index, entry.bytes) !== 0) {
964
1040
  throw new Error("a journaled ABC did not restore");
965
1041
  }
@@ -1039,10 +1115,10 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1039
1115
  // snapshot of this instance, as a move by compact is, and never reading
1040
1116
  // this instance again, while the host goes on with it, each call it
1041
1117
  // makes journaled and replayed into the spare once the spare has rebuilt.
1042
- const startMove = (into: Bound): boolean => {
1118
+ const startMove = (into: Bound, carried: Revival[] = []): boolean => {
1043
1119
  let saved: Checkpoint;
1044
1120
  try {
1045
- saved = saveCheckpoint();
1121
+ saved = withRevivals(saveCheckpoint(), carried);
1046
1122
  } catch (error) {
1047
1123
  if (error instanceof CodegenOutOfMemory) {
1048
1124
  spare = into;
@@ -1052,7 +1128,9 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1052
1128
  throw error;
1053
1129
  }
1054
1130
 
1055
- // Parts that block the host for little: a part's time is its garbage's, but for one large method's verification.
1131
+ // Parts that block the host for little, the rebuild's and catch-up's verifications alike, a
1132
+ // long method's verification across parts too: a part's time is about its budget's, but for
1133
+ // linking one large ABC, which a part does whole.
1056
1134
  into.domainRebuildBudget(MOVE_PartBudget);
1057
1135
  move = {
1058
1136
  into,
@@ -1060,25 +1138,114 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1060
1138
  entries: [],
1061
1139
  replayed: 0,
1062
1140
  word: 0,
1141
+ verifying: false,
1063
1142
  restored: new Map(),
1064
- abcs: null,
1143
+ abcs: [],
1144
+ given: 0,
1145
+ revivals: carried,
1146
+ evicted: new Set([...journalDomains.keys()].filter((d) => wasm.domainState(d) === 1)),
1065
1147
  phase: "load",
1066
1148
  catchUp: 0,
1067
1149
  };
1068
1150
  moves.started++;
1069
1151
  return true;
1070
1152
  };
1153
+ // `saved` with `carried` revived by its load, their ABCs' bytes joined,
1154
+ // each once. A revival's ABCs were gathered when it was asked for: those
1155
+ // of domains revived since, live in the snapshot, which holds them, are
1156
+ // left out, else the load would take one twice and refuse the move. The
1157
+ // chain's states here are the snapshot's, for a snapshot taken now and for
1158
+ // one a revival is folded into (see scheduleRevivals).
1159
+ const withRevivals = (saved: Checkpoint, carried: Revival[]): Checkpoint => {
1160
+ if (!carried.length) {
1161
+ return saved;
1162
+ }
1163
+
1164
+ const domains = [...(saved.revive?.domains ?? [])];
1165
+ const abcs = new Map(saved.revive?.abcs ?? []);
1166
+ for (const r of carried) {
1167
+ // One an earlier revival's chain takes in is revived by that one's load.
1168
+ if (!domains.some((d) => inChain(r.appDomain, d))) {
1169
+ domains.push(r.appDomain);
1170
+ }
1171
+
1172
+ for (const [index, bytes] of r.abcs) {
1173
+ if (!abcs.has(index) && !saved.abcs.has(index) && evictedAbc(index)) {
1174
+ abcs.set(index, bytes);
1175
+ }
1176
+ }
1177
+ }
1178
+
1179
+ return { state: saved.state, abcs: saved.abcs, revive: { domains, abcs } };
1180
+ };
1181
+ const evictedAbc = (index: number) =>
1182
+ Number.isInteger(index) &&
1183
+ index >= 0 &&
1184
+ index < abcDomains.length &&
1185
+ wasm.domainState(abcDomains[index]) === 1;
1186
+ // Domain `appDomain` and its evicted ancestors, the last a child of a live one.
1187
+ const evictedChain = (appDomain: number) => {
1188
+ const chain = new Set<number>();
1189
+ for (let d = appDomain; d > 0 && wasm.domainState(d) === 1; d = wasm.domainParent(d)) {
1190
+ chain.add(d);
1191
+ }
1192
+
1193
+ return chain;
1194
+ };
1195
+ // The domains the load of `m` revived, live in its spare, caught up, that
1196
+ // this instance evicts and no revival still wants: those between a
1197
+ // revival's domain and its chain's top, the domain dropped since. Evicted
1198
+ // in the spare too before it takes this instance's place, else the move
1199
+ // would leave them live where a compiler that never moved has them
1200
+ // evicted; in order, a parent before its children, which it evicts.
1201
+ const unwantedRevived = (m: Move): number[] => {
1202
+ if (!m.revivals.length) {
1203
+ return [];
1204
+ }
1205
+
1206
+ const wanted = new Set<number>();
1207
+ for (const r of m.revivals) {
1208
+ for (const d of evictedChain(r.appDomain)) {
1209
+ wanted.add(d);
1210
+ }
1211
+ }
1212
+
1213
+ const unwanted: number[] = [];
1214
+ for (const d of [...journalDomains.keys()].sort((x, y) => x - y)) {
1215
+ if (
1216
+ d > 0 &&
1217
+ !wanted.has(d) &&
1218
+ wasm.domainState(d) === 1 &&
1219
+ m.into.domainState(d) === 0 &&
1220
+ !unwanted.some((u) => inChain(u, d))
1221
+ ) {
1222
+ unwanted.push(d);
1223
+ }
1224
+ }
1225
+
1226
+ return unwanted;
1227
+ };
1071
1228
  // The spare, rebuilt and caught up, takes this instance's place, as a
1072
1229
  // recovery's does, and the snapshot it rebuilt is the checkpoint, the
1073
1230
  // calls since it the journal.
1074
1231
  const swapMove = (m: Move) => {
1075
1232
  move = null;
1076
1233
  moves.completed++;
1234
+ moves.revived += m.revivals.length;
1235
+ for (const r of m.revivals) {
1236
+ const at = revivals.indexOf(r);
1237
+ if (at >= 0) {
1238
+ revivals.splice(at, 1);
1239
+ }
1240
+ }
1241
+
1077
1242
  const kept = m.entries.filter((entry) => journal.has(entry));
1078
1243
  moves.lastCaughtUp = kept.length;
1079
1244
  moves.lastSavedBytes = m.saved.state.length;
1080
- for (const abc of m.saved.abcs.values()) {
1081
- moves.lastSavedBytes += abc.length;
1245
+ for (const abcs of [m.saved.abcs, m.saved.revive?.abcs ?? new Map()]) {
1246
+ for (const abc of abcs.values()) {
1247
+ moves.lastSavedBytes += abc.length;
1248
+ }
1082
1249
  }
1083
1250
 
1084
1251
  journal.clear();
@@ -1121,13 +1288,23 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1121
1288
  return "none";
1122
1289
  }
1123
1290
 
1124
- m.abcs = m.saved.abcs.entries();
1291
+ // domainLoad's MOVE_Limit counts the snapshot alone: the chains
1292
+ // revived after it add their ABCs at their weight, three times
1293
+ // their bytes, small beside the limit's gigabyte.
1294
+ for (const domain of m.saved.revive?.domains ?? []) {
1295
+ if (into.domainLoadRevive(domain) !== 0) {
1296
+ abortMove("refused");
1297
+ return "none";
1298
+ }
1299
+ }
1300
+
1301
+ m.abcs = [...m.saved.abcs, ...(m.saved.revive?.abcs ?? [])];
1125
1302
  m.phase = "abcs";
1126
1303
  return "moving";
1127
1304
  case "abcs": {
1128
- const next = m.abcs?.next();
1129
- if (next && !next.done) {
1130
- if (into.domainLoadAbc(next.value[0], next.value[1]) !== 0) {
1305
+ if (m.given < m.abcs.length) {
1306
+ const [index, bytes] = m.abcs[m.given++];
1307
+ if (into.domainLoadAbc(index, bytes) !== 0) {
1131
1308
  abortMove("refused");
1132
1309
  return "none";
1133
1310
  }
@@ -1135,7 +1312,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1135
1312
  return "moving";
1136
1313
  }
1137
1314
 
1138
- m.abcs = null;
1315
+ m.abcs = [];
1139
1316
  if (!into.domainLoadRebuild()) {
1140
1317
  abortMove("refused");
1141
1318
  return "none";
@@ -1162,6 +1339,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1162
1339
  // forgetDropped), but one half replayed is finished.
1163
1340
  while (
1164
1341
  m.word === 0 &&
1342
+ !m.verifying &&
1165
1343
  m.replayed < m.entries.length &&
1166
1344
  !journal.has(m.entries[m.replayed])
1167
1345
  ) {
@@ -1169,20 +1347,41 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1169
1347
  }
1170
1348
 
1171
1349
  if (m.replayed === m.entries.length) {
1350
+ const unwanted = unwantedRevived(m);
1351
+ for (const domain of unwanted) {
1352
+ into.domainEvict(domain);
1353
+ }
1354
+
1172
1355
  swapMove(m);
1356
+ // Owned by the root, as evictDomain's: a revival journaled later
1357
+ // needs it though the domain is dropped after.
1358
+ for (const domain of unwanted) {
1359
+ journaled({ kind: "evict", appDomain: domain });
1360
+ }
1361
+
1173
1362
  return "done";
1174
1363
  }
1175
1364
 
1176
- // A compile's log a log entry a part, a run of them taking long.
1365
+ // A compile's log a log entry a part, a run of them taking long,
1366
+ // and a verification, as long as the compile's, a part of about a
1367
+ // rebuild's part at a time, the entries after it waiting.
1177
1368
  const entry = m.entries[m.replayed];
1178
1369
  if (entry.kind === "log") {
1179
1370
  const w = entry.words;
1180
1371
  const i = m.word;
1181
- if (!into.replayEntry(w[i], w[i + 1], w[i + 2], w[i + 3])) {
1372
+ const step = m.verifying
1373
+ ? into.replayEntryStep()
1374
+ : into.replayEntryStepped(w[i], w[i + 1], w[i + 2], w[i + 3]);
1375
+ if (step < 0) {
1182
1376
  abortMove("refused");
1183
1377
  return "none";
1184
1378
  }
1185
1379
 
1380
+ m.verifying = step === 0;
1381
+ if (m.verifying) {
1382
+ return "moving";
1383
+ }
1384
+
1186
1385
  m.word = i + 4 < w.length ? i + 4 : 0;
1187
1386
  if (m.word === 0) {
1188
1387
  m.replayed++;
@@ -1208,20 +1407,12 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1208
1407
  return "none";
1209
1408
  }
1210
1409
  };
1211
- // Whether the move's next part replays a call that takes long in one:
1212
- // a compile's verification of a large ABC, as long as the compile
1213
- // verified it for, or the add of a large ABC, which parses and links it.
1410
+ // The length of the ABC whose add the move's next part replays if that
1411
+ // takes long in one call, parsing and linking it, else 0. A compile's
1412
+ // verification is replayed a part at a time.
1214
1413
  const longNext = (m: Move) => {
1215
1414
  const entry = m.phase === "catch up" ? m.entries[m.replayed] : undefined;
1216
- if (entry?.kind === "add") {
1217
- return entry.abc.length > LARGE_Add;
1218
- }
1219
-
1220
- return (
1221
- entry?.kind === "log" &&
1222
- entry.words[m.word] === LOG_Verify &&
1223
- (abcLengths[entry.words[m.word + 1]] ?? 0) > LARGE_Verify
1224
- );
1415
+ return entry?.kind === "add" && entry.abc.length > LARGE_Add ? entry.abc.length : 0;
1225
1416
  };
1226
1417
  // What compactStep starts, as compact decides, but that a large domain
1227
1418
  // moves rather than rebuild in place, which would take one call.
@@ -1262,6 +1453,183 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1262
1453
  spare = null;
1263
1454
  return startMove(into) ? "moving" : "none";
1264
1455
  };
1456
+ // The revivals left to a move whose domains are still evicted here, those
1457
+ // revived otherwise or dropped since let go of, as are those whose chain
1458
+ // has grown by an ancestor evicted since, which the host, asking again,
1459
+ // gives the bytes of; and the revivals waiting for a move, failed ones apart.
1460
+ const waitingRevivals = (): Revival[] => {
1461
+ for (let i = revivals.length - 1; i >= 0; i--) {
1462
+ const r = revivals[i];
1463
+ if (wasm.domainState(r.appDomain) !== 1 || !givenAll(r)) {
1464
+ revivals.splice(i, 1);
1465
+ }
1466
+ }
1467
+
1468
+ return revivals.filter((r) => !r.failed && !move?.revivals.includes(r));
1469
+ };
1470
+ const givenAll = (r: Revival) => {
1471
+ const chain = evictedChain(r.appDomain);
1472
+ for (let index = 0; index < abcDomains.length; index++) {
1473
+ if (chain.has(abcDomains[index]) && !r.abcs.has(index)) {
1474
+ return false;
1475
+ }
1476
+ }
1477
+
1478
+ return true;
1479
+ };
1480
+ // Whether the chain of `r` is not what it was at the snapshot of `m`, an
1481
+ // ancestor evicted or revived since, by a revival of its own or of
1482
+ // another under it: its load would then revive a chain other than the one
1483
+ // here, with ABCs of it not given, or the spare replay a revival or an
1484
+ // eviction its load had made moot.
1485
+ const chainChanged = (m: Move, r: Revival) => {
1486
+ if (
1487
+ m.entries.some(
1488
+ (e) => (e.kind === "evict" || e.kind === "revive") && inChain(e.appDomain, r.appDomain),
1489
+ )
1490
+ ) {
1491
+ return true;
1492
+ }
1493
+
1494
+ const now = evictedChain(r.appDomain);
1495
+ let d = r.appDomain;
1496
+ for (; d > 0 && m.evicted.has(d); d = wasm.domainParent(d)) {
1497
+ if (!now.delete(d)) {
1498
+ return true;
1499
+ }
1500
+ }
1501
+
1502
+ return now.size > 0;
1503
+ };
1504
+ // Revivals waiting, given to the move under way while its spare has not
1505
+ // begun to rebuild, as its load revives them, unless their chain changed
1506
+ // since its snapshot; else, if it only compacts, the move is given up for
1507
+ // one that revives as it compacts, as going on would cost its rest and
1508
+ // then a rebuild; those a move that revives cannot take wait for the next.
1509
+ const scheduleRevivals = (waiting: Revival[]) => {
1510
+ const m = move;
1511
+ if (m === null || !waiting.length) {
1512
+ return;
1513
+ }
1514
+
1515
+ const fresh =
1516
+ m.phase === "load" || m.phase === "abcs" ? waiting.filter((r) => !chainChanged(m, r)) : [];
1517
+ if (fresh.length < waiting.length && !m.revivals.length) {
1518
+ abortMove("superseded");
1519
+ return;
1520
+ }
1521
+
1522
+ if (!fresh.length) {
1523
+ return;
1524
+ }
1525
+
1526
+ const loaded = m.phase === "abcs";
1527
+ const before = m.saved.revive;
1528
+ const saved = withRevivals(m.saved, fresh);
1529
+ try {
1530
+ for (const domain of saved.revive?.domains ?? []) {
1531
+ if (loaded && !before?.domains.includes(domain) && m.into.domainLoadRevive(domain) !== 0) {
1532
+ for (const r of fresh) {
1533
+ r.failed = true;
1534
+ }
1535
+
1536
+ abortMove("refused");
1537
+ return;
1538
+ }
1539
+ }
1540
+ } catch (error) {
1541
+ for (const r of fresh) {
1542
+ r.failed = true;
1543
+ }
1544
+
1545
+ abortMove(
1546
+ error instanceof CodegenPanic || error instanceof CodegenOutOfMemory ? "spare" : "refused",
1547
+ );
1548
+ return;
1549
+ }
1550
+
1551
+ m.revivals.push(...fresh);
1552
+ m.saved = saved;
1553
+ if (loaded) {
1554
+ for (const entry of saved.revive?.abcs ?? []) {
1555
+ if (!before?.abcs.has(entry[0])) {
1556
+ m.abcs.push(entry);
1557
+ }
1558
+ }
1559
+ }
1560
+ };
1561
+ // A move that revives the domains waiting, and compacts as it does, once
1562
+ // there is a spare to make it in; where none can be made, or the journal
1563
+ // cannot catch one up, they are done in place when asked for again.
1564
+ const beginRevival = (waiting: Revival[]): CompactProgress => {
1565
+ const fail = (): CompactProgress => {
1566
+ for (const r of waiting) {
1567
+ r.failed = true;
1568
+ }
1569
+
1570
+ return "none";
1571
+ };
1572
+ if (!replayable) {
1573
+ return fail();
1574
+ }
1575
+
1576
+ const into = spare;
1577
+ if (into === null) {
1578
+ if (spareFailed && !making) {
1579
+ spareFailed = false;
1580
+ return fail();
1581
+ }
1582
+
1583
+ prepare();
1584
+ return "moving";
1585
+ }
1586
+
1587
+ spare = null;
1588
+ return startMove(into, waiting) ? "moving" : fail();
1589
+ };
1590
+ // The ABCs of evicted domain `appDomain` and its evicted ancestors, the
1591
+ // first a child of a live one, among `abcs`, copied: each must be there,
1592
+ // else the revival throws, as reviveDomain does when it cannot revive.
1593
+ const revivalAbcs = (appDomain: number, abcs: Map<number, Uint8Array>) => {
1594
+ const chain = evictedChain(appDomain);
1595
+ const top = [...chain].pop() ?? appDomain;
1596
+ let missing = false;
1597
+ const owned = new Map<number, Uint8Array>();
1598
+ for (let index = 0; index < abcDomains.length; index++) {
1599
+ if (chain.has(abcDomains[index])) {
1600
+ const bytes = abcs.get(index);
1601
+ if (bytes === undefined) {
1602
+ missing = true;
1603
+ } else {
1604
+ owned.set(index, new Uint8Array(bytes));
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ if (missing || wasm.domainState(wasm.domainParent(top)) !== 0) {
1610
+ throw new Error(
1611
+ `application domain ${appDomain}: not evicted, its parent not live, or an ABC of it not given`,
1612
+ );
1613
+ }
1614
+
1615
+ return owned;
1616
+ };
1617
+ // Whether the domain, with the chain a revival links again, its ABCs
1618
+ // `abcs`, is large enough that the revival's rebuild goes to a move
1619
+ // rather than block: a small domain reviving a large chain rebuilds as
1620
+ // long as one that was large all along.
1621
+ const revivalSteps = (abcs: Map<number, Uint8Array>) => {
1622
+ if (!replayable || moveRefused) {
1623
+ return false;
1624
+ }
1625
+
1626
+ let weight = Number(wasm.domainUsage().split(" ")[0]);
1627
+ for (const bytes of abcs.values()) {
1628
+ weight += REVIVED_Weight * bytes.length;
1629
+ }
1630
+
1631
+ return weight >= IN_PLACE_Live;
1632
+ };
1265
1633
  // Whether the domain was lost to a panic recovery could not undo (see fresh).
1266
1634
  let lost = false;
1267
1635
  const api: Codegen = {
@@ -1276,6 +1644,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1276
1644
  reset(version = API_VERSION) {
1277
1645
  checkApiVersion(version);
1278
1646
  abortMove("superseded");
1647
+ revivals.length = 0;
1279
1648
  moveRefused = false;
1280
1649
  retryAt = 0;
1281
1650
  wasm.domainReset(version);
@@ -1288,7 +1657,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1288
1657
  journal.clear();
1289
1658
  restores.clear();
1290
1659
  abcDomains.length = 0;
1291
- abcLengths.length = 0;
1292
1660
  replayable = true;
1293
1661
  checkpoint = null;
1294
1662
  },
@@ -1305,7 +1673,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1305
1673
  if (error === 0 || wasm.lastAddLinked()) {
1306
1674
  if (error === 0) {
1307
1675
  abcDomains.push(appDomain);
1308
- abcLengths.push(bytes.length);
1309
1676
  }
1310
1677
  journaled(
1311
1678
  {
@@ -1408,9 +1775,11 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1408
1775
  return wasm.domainCompact(true) && rebuild(wasm, null, true);
1409
1776
  },
1410
1777
  compactStep(deadline) {
1778
+ const waiting = waitingRevivals();
1779
+ scheduleRevivals(waiting);
1411
1780
  let m = move;
1412
1781
  if (m === null) {
1413
- const begun = beginCompaction();
1782
+ const begun = waiting.length ? beginRevival(waiting) : beginCompaction();
1414
1783
  if (begun !== "moving" || move === null) {
1415
1784
  return begun;
1416
1785
  }
@@ -1419,34 +1788,62 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1419
1788
  }
1420
1789
 
1421
1790
  // Catch-up chases what the host goes on doing. Past CATCH_UP_Slices
1422
- // slices it goes on CATCH_UP_Overrun past the deadline, a long part
1423
- // still starting a slice of its own; past twice as many, it finishes
1424
- // in this slice, which has only what came in since the last to
1425
- // replay (a revival's rebuild still a part at a time).
1791
+ // slices, a slice whose deadline is sooner goes on starting parts
1792
+ // until CATCH_UP_Overrun from its start, and past twice as many
1793
+ // until CATCH_UP_OverrunLate, so a busy page's short slices catch up
1794
+ // as an idle page's do, a long part still starting a slice of its
1795
+ // own. Never longer: replaying a compile costs no more than the
1796
+ // compile did, so catch-up falls behind only while the host spends
1797
+ // more of its time compiling than that, and catches up once its
1798
+ // loads pause, rather than block for all it is behind by.
1426
1799
  let slices = 0;
1427
1800
  if (m.phase === "catch up") {
1428
1801
  slices = ++m.catchUp;
1429
1802
  }
1430
1803
 
1804
+ const start = deadline.timeRemaining();
1805
+ let read = start;
1806
+ let unchanged = 0;
1431
1807
  for (;;) {
1432
1808
  const progress = moveUnit(m);
1433
1809
  if (progress !== "moving") {
1434
1810
  return progress;
1435
1811
  }
1436
1812
 
1437
- const catchingUp = m.phase === "catch up";
1438
- if (catchingUp && slices > CATCH_UP_Slices * 2) {
1439
- continue;
1813
+ // SLICE_Parts bounds a deadline that has stopped telling time, one
1814
+ // that reads the same however many parts it is asked after.
1815
+ // Counting every part instead would cut slices of parts of a few
1816
+ // microseconds, as catch-up replays a compile's log, at a few
1817
+ // milliseconds.
1818
+ const left = deadline.timeRemaining();
1819
+ unchanged = left === read ? unchanged + 1 : 0;
1820
+ read = left;
1821
+ if (unchanged >= SLICE_Parts) {
1822
+ return "moving";
1440
1823
  }
1441
1824
 
1442
- // A part that takes long in one call starts a slice of its own,
1443
- // so that it adds to no other part's time.
1444
- if (longNext(m)) {
1825
+ // A part that takes long in one call starts a slice of its own, so
1826
+ // that it adds to no other part's time, unless this one has the
1827
+ // time left for it: ending a slice tens of milliseconds early at
1828
+ // each large add left catch-up behind the host's loads.
1829
+ const adding = longNext(m);
1830
+ if (adding > 0 && !(left > adding / ADD_Rate)) {
1445
1831
  return "moving";
1446
1832
  }
1447
1833
 
1448
- const overrun = catchingUp && slices > CATCH_UP_Slices ? CATCH_UP_Overrun : 0;
1449
- if (deadline.timeRemaining() <= -overrun) {
1834
+ // A rebuild's parts start until REBUILD_Floor into a slice given
1835
+ // any time, so that a busy page's short slices still move it along.
1836
+ // That and catch-up's overrun go past the deadline only where it
1837
+ // tells the time past it, below 0: an IdleDeadline stops at 0. Not
1838
+ // by its falling, as a coarse clock reads the same across short
1839
+ // parts.
1840
+ const telling = left < 0;
1841
+ const overrun =
1842
+ m.phase === "catch up" &&
1843
+ slices > CATCH_UP_Slices &&
1844
+ left > start - (slices > 2 * CATCH_UP_Slices ? CATCH_UP_OverrunLate : CATCH_UP_Overrun);
1845
+ const floor = m.phase === "rebuild" && start > 0 && left > start - REBUILD_Floor;
1846
+ if (left <= 0 && !(telling && (overrun || floor))) {
1450
1847
  return "moving";
1451
1848
  }
1452
1849
  }
@@ -1454,7 +1851,40 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1454
1851
  isLive(appDomain) {
1455
1852
  return wasm.domainState(appDomain) === 0;
1456
1853
  },
1457
- reviveDomain(appDomain, abcs) {
1854
+ reviveDomain(appDomain, abcs, stepped = false) {
1855
+ // A revival left to a move already, of this domain or a descendant,
1856
+ // which revives it too.
1857
+ const queued = revivals.find((r) => inChain(appDomain, r.appDomain));
1858
+ if (stepped && queued !== undefined && !queued.failed && replayable) {
1859
+ return false;
1860
+ }
1861
+
1862
+ // One the move under way makes, finished here, as compact finishes it;
1863
+ // a revival given up is done in place below.
1864
+ const m = move;
1865
+ if (queued !== undefined && m?.revivals.includes(queued)) {
1866
+ let progress = moveUnit(m);
1867
+ while (progress === "moving") {
1868
+ progress = moveUnit(m);
1869
+ }
1870
+
1871
+ if (wasm.domainState(appDomain) === 0) {
1872
+ return true;
1873
+ }
1874
+ }
1875
+
1876
+ if (queued !== undefined && revivals.includes(queued)) {
1877
+ revivals.splice(revivals.indexOf(queued), 1);
1878
+ }
1879
+
1880
+ if (stepped && queued === undefined && wasm.domainReviveNeeds(appDomain) === 1) {
1881
+ const owned = revivalAbcs(appDomain, abcs);
1882
+ if (revivalSteps(owned)) {
1883
+ revivals.push({ appDomain, abcs: owned, failed: false });
1884
+ return false;
1885
+ }
1886
+ }
1887
+
1458
1888
  // A move's spare lets go of the ABCs of the domains evicted before its
1459
1889
  // snapshot, and before any rebuild a replayed revival makes in it,
1460
1890
  // which this instance may still hold: restores journaled before the
@@ -1473,6 +1903,17 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1473
1903
  let revived = wasm.domainRevive(appDomain, true);
1474
1904
  if (revived < 0) {
1475
1905
  for (const [index, bytes] of abcs) {
1906
+ // One of a domain live here, which a move revived after the host
1907
+ // gathered the chain's bytes, is held already.
1908
+ if (
1909
+ Number.isInteger(index) &&
1910
+ index >= 0 &&
1911
+ index < abcDomains.length &&
1912
+ wasm.domainState(abcDomains[index]) === 0
1913
+ ) {
1914
+ continue;
1915
+ }
1916
+
1476
1917
  const owned = new Uint8Array(bytes);
1477
1918
  const error = wasm.domainRestore(index, owned);
1478
1919
  if (error !== 0) {
@@ -1519,6 +1960,8 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1519
1960
  `application domain ${appDomain}: not evicted, its parent not live, or an ABC of it not given`,
1520
1961
  );
1521
1962
  }
1963
+
1964
+ return true;
1522
1965
  },
1523
1966
  found({ domain, nsKind, uri, name, abc, asType }) {
1524
1967
  wasm.domainFound(domain, nsKind, uri, name, abc, asType);
@@ -1774,21 +2217,47 @@ const WANT_Spare = 3;
1774
2217
  * rebuilds in place, in one call, rather than move a part at a time.
1775
2218
  */
1776
2219
  const IN_PLACE_Live = 4 << 20;
1777
- /** A compile's log entry that verified an ABC: LogKind.verify (avm2/link/domain.zig). */
1778
- const LOG_Verify = 4;
2220
+ // The weight of an ABC's byte a revival links again, before its compiles:
2221
+ // the compiler's own ABC_Weight (zig/src/avm2/link/domain.zig).
2222
+ const REVIVED_Weight = 3;
1779
2223
  /**
1780
- * The length of an ABC whose verification, replayed, starts a slice of its
1781
- * own: some 20 ms of it on real content, 750 ms for 2.3 MB.
2224
+ * The garbage a part of a move's rebuild, and of a verification its catch-up replays, makes at
2225
+ * most (domainRebuildBudget): some 5 ms of verifying. Halving it from 256 KiB cost no time in all.
1782
2226
  */
1783
- const LARGE_Verify = 64 << 10;
1784
- /** The garbage a part of a move's rebuild makes at most (domainRebuildBudget). */
1785
- const MOVE_PartBudget = 256 << 10;
2227
+ const MOVE_PartBudget = 128 << 10;
1786
2228
  /** The slices compactStep catches a move up in before it goes on past their deadlines (see compactStep). */
1787
2229
  const CATCH_UP_Slices = 32;
1788
- /** How far past its deadline a slice catches up after CATCH_UP_Slices, in milliseconds. */
1789
- const CATCH_UP_Overrun = 50;
1790
- /** The length of an ABC whose add, replayed, starts a slice of its own: some 4 ms of parsing and linking. */
2230
+ /**
2231
+ * How long after its start a slice starts catch-up's parts until, past CATCH_UP_Slices, in
2232
+ * milliseconds: a few parts, each some 5 ms at most since long methods are verified across parts.
2233
+ */
2234
+ const CATCH_UP_Overrun = 25;
2235
+ /**
2236
+ * As CATCH_UP_Overrun, past twice CATCH_UP_Slices: catch-up outrun that long still catches up
2237
+ * while the host spends up to about half its time compiling, where CATCH_UP_Overrun's would only
2238
+ * up to a quarter.
2239
+ */
2240
+ const CATCH_UP_OverrunLate = 50;
2241
+ /**
2242
+ * How long after its start a slice starts a move's rebuild parts until, past its deadline, in
2243
+ * milliseconds: the slice so takes this and one part more, of some 5 ms at most. With parts
2244
+ * that short, a busy page's slices of a few milliseconds would each take one, the move then
2245
+ * going on for many more loads, the dead ABCs it is to let go of meanwhile kept.
2246
+ */
2247
+ const REBUILD_Floor = 9;
2248
+ /**
2249
+ * The parts a slice makes at most while its deadline reads the same: more than a coarse clock's
2250
+ * tick holds of the shortest parts, a few microseconds each, so that only a deadline that stops
2251
+ * telling time meets it.
2252
+ */
2253
+ const SLICE_Parts = 1000;
2254
+ /** The length of an ABC whose add, replayed, starts a slice of its own unless the slice has time left for it: some 4 ms of parsing and linking. */
1791
2255
  const LARGE_Add = 256 << 10;
2256
+ /**
2257
+ * The bytes of a large add's ABC a slice reckons a millisecond of its time to replay: half
2258
+ * LARGE_Add's rate, so that one made within a slice still ends before its deadline.
2259
+ */
2260
+ const ADD_Rate = LARGE_Add / 4 / 2;
1792
2261
  /** The drops and evictions after a move given up as failed before compactStep starts another. */
1793
2262
  const RETRY_Lettings = 16;
1794
2263
  /** How many SWFs whose blocks or units are compiled codegen holds a copy of at most. */