@swf2es/codegen 0.1.41 → 0.1.42

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
@@ -217,18 +217,24 @@ export type MoveAbort =
217
217
  | "refused"
218
218
  /** A call meanwhile could not be journaled, so the spare could not catch up. */
219
219
  | "unjournaled"
220
- /** The domain was reset, recovered from a panic, or rebuilt in place meanwhile. */
220
+ /**
221
+ * The domain was reset, recovered from a panic, or rebuilt in place
222
+ * meanwhile; or a revival took the place of a move that only compacted
223
+ * (see reviveDomain).
224
+ */
221
225
  | "superseded";
222
226
 
223
227
  /**
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.
228
+ * compactStep's moves: started, completed, and given up by why; the
229
+ * domains revived by those completed (see reviveDomain); and of the last
230
+ * one completed, the calls replayed into its spare after its rebuild, and
231
+ * the bytes of its snapshot, which recovery keeps as its checkpoint.
227
232
  */
228
233
  export interface MoveCounts {
229
234
  started: number;
230
235
  completed: number;
231
236
  aborted: Record<MoveAbort, number>;
237
+ revived: number;
232
238
  lastCaughtUp: number;
233
239
  lastSavedBytes: number;
234
240
  }
@@ -336,9 +342,22 @@ export interface Codegen {
336
342
  * ancestors, the first of them a child of a live domain: given all their
337
343
  * ABCs again by their indices, as they were added, their ABCs link as
338
344
  * they did, by one rebuild at most, and what they found holds. Throws if
339
- * they cannot be.
345
+ * they cannot be. True once live.
346
+ *
347
+ * A rebuild of a large domain takes seconds, so `stepped`, a revival that
348
+ * needs one is made by a move into the spare instance instead, a part at
349
+ * a time as compactStep moves a domain to compact it, the domain staying
350
+ * evicted here until the spare takes this instance's place: then false,
351
+ * and compactStep carries the move on ("moving" until it is done), while
352
+ * the host goes on compiling elsewhere; isLive tells when it is live, and
353
+ * calling this again meanwhile returns false. The host asks again with
354
+ * the chain's ABCs as they are then: a chain an eviction lengthened needs
355
+ * the new ancestor's, and those of a domain revived meanwhile are not
356
+ * taken. A revival that needs no rebuild, or only a small one, is done at
357
+ * once, and so is one whose move was given up as failed, in place as
358
+ * without `stepped`; without it, a revival under way finishes its move.
340
359
  */
341
- reviveDomain(appDomain: number, abcs: Map<number, Uint8Array>): void;
360
+ reviveDomain(appDomain: number, abcs: Map<number, Uint8Array>, stepped?: boolean): boolean;
342
361
  /** Record a definition an application domain has found; it holds for the ABCs added after. */
343
362
  found(definition: FoundDefinition): void;
344
363
  /**
@@ -579,6 +598,12 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
579
598
  interface Checkpoint {
580
599
  state: Uint8Array;
581
600
  abcs: Map<number, Uint8Array>;
601
+ /**
602
+ * Evicted domains the load revives before it rebuilds, a move's
603
+ * revivals (see Revival), and their ABCs' bytes: the rebuild then
604
+ * links them in their places, as a revival's rebuild here would.
605
+ */
606
+ revive?: { domains: number[]; abcs: Map<number, Uint8Array> };
582
607
  }
583
608
  let checkpoint: Checkpoint | null = null;
584
609
  const saveCheckpoint = (): Checkpoint => {
@@ -598,11 +623,18 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
598
623
  if (!loaded) {
599
624
  return false;
600
625
  }
601
- for (const [index, abc] of saved.abcs) {
602
- if (into.domainLoadAbc(index, abc) !== 0) {
626
+ for (const domain of saved.revive?.domains ?? []) {
627
+ if (into.domainLoadRevive(domain) !== 0) {
603
628
  return false;
604
629
  }
605
630
  }
631
+ for (const abcs of [saved.abcs, saved.revive?.abcs ?? []]) {
632
+ for (const [index, abc] of abcs) {
633
+ if (into.domainLoadAbc(index, abc) !== 0) {
634
+ return false;
635
+ }
636
+ }
637
+ }
606
638
  return into.domainLoadRebuild();
607
639
  };
608
640
  // The rebuild domainCompact, domainRevive or domainLoadRebuild started in
@@ -667,6 +699,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
667
699
  started: 0,
668
700
  completed: 0,
669
701
  aborted: { spare: 0, refused: 0, unjournaled: 0, superseded: 0 },
702
+ revived: 0,
670
703
  lastCaughtUp: 0,
671
704
  lastSavedBytes: 0,
672
705
  };
@@ -677,8 +710,25 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
677
710
  // same domain would likely fail the same way.
678
711
  let lettings = 0;
679
712
  let retryAt = 0;
713
+ // The revivals reviveDomain left to a move, in the order asked for, until
714
+ // a move made them, or the domain is no longer evicted here; one whose
715
+ // move was given up as failed is done in place when asked for again.
716
+ interface Revival {
717
+ appDomain: number;
718
+ abcs: Map<number, Uint8Array>;
719
+ failed: boolean;
720
+ }
721
+ const revivals: Revival[] = [];
722
+ // Whether the last spare could not be instantiated, so that a revival waiting for one is done in place.
723
+ let spareFailed = false;
680
724
  const abortMove = (why: MoveAbort) => {
681
725
  if (move !== null) {
726
+ if (why === "spare" || why === "refused") {
727
+ for (const r of move.revivals) {
728
+ r.failed = true;
729
+ }
730
+ }
731
+
682
732
  move = null;
683
733
  moves.aborted[why]++;
684
734
  if (why !== "superseded") {
@@ -697,9 +747,11 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
697
747
  (made) => {
698
748
  spare = made;
699
749
  making = false;
750
+ spareFailed = false;
700
751
  },
701
752
  () => {
702
753
  making = false;
754
+ spareFailed = true;
703
755
  },
704
756
  );
705
757
  }
@@ -769,8 +821,10 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
769
821
  // A move compactStep makes a part at a time: the spare it rebuilds in,
770
822
  // the snapshot it rebuilds, the calls journaled since, how many of those
771
823
  // 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.
824
+ // revivals since restored in it, copied once; the ABCs to give it, saved
825
+ // and revived, and how many it has been given; the revivals it makes,
826
+ // which its snapshot carries; its phase; and the slices it has spent
827
+ // catching up.
774
828
  interface Move {
775
829
  into: Bound;
776
830
  saved: Checkpoint;
@@ -779,7 +833,11 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
779
833
  /** Where in the log entry being replayed, a compile's, the spare is. */
780
834
  word: number;
781
835
  restored: Map<number, Uint8Array>;
782
- abcs: IterableIterator<[number, Uint8Array]> | null;
836
+ abcs: [number, Uint8Array][];
837
+ given: number;
838
+ revivals: Revival[];
839
+ /** The domains evicted at the snapshot, which a revival folded in must find its chain among (see scheduleRevivals). */
840
+ evicted: Set<number>;
783
841
  phase: "load" | "abcs" | "rebuild" | "catch up";
784
842
  catchUp: number;
785
843
  }
@@ -790,8 +848,10 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
790
848
  let bytes = 0;
791
849
  if (checkpoint) {
792
850
  bytes += checkpoint.state.byteLength;
793
- for (const abc of checkpoint.abcs.values()) {
794
- bytes += abc.byteLength;
851
+ for (const abcs of [checkpoint.abcs, checkpoint.revive?.abcs ?? new Map()]) {
852
+ for (const abc of abcs.values()) {
853
+ bytes += abc.byteLength;
854
+ }
795
855
  }
796
856
  }
797
857
 
@@ -960,6 +1020,13 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
960
1020
  into.domainEvict(entry.appDomain);
961
1021
  break;
962
1022
  case "restore":
1023
+ // One of a domain a move's load revived (Checkpoint.revive), which
1024
+ // this instance, still evicting it, gave back for a revival of
1025
+ // another under it: `into` holds it, live.
1026
+ if (into.domainState(abcDomains[entry.index] ?? -1) === 0) {
1027
+ break;
1028
+ }
1029
+
963
1030
  if (into.domainRestore(entry.index, entry.bytes) !== 0) {
964
1031
  throw new Error("a journaled ABC did not restore");
965
1032
  }
@@ -1039,10 +1106,10 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1039
1106
  // snapshot of this instance, as a move by compact is, and never reading
1040
1107
  // this instance again, while the host goes on with it, each call it
1041
1108
  // makes journaled and replayed into the spare once the spare has rebuilt.
1042
- const startMove = (into: Bound): boolean => {
1109
+ const startMove = (into: Bound, carried: Revival[] = []): boolean => {
1043
1110
  let saved: Checkpoint;
1044
1111
  try {
1045
- saved = saveCheckpoint();
1112
+ saved = withRevivals(saveCheckpoint(), carried);
1046
1113
  } catch (error) {
1047
1114
  if (error instanceof CodegenOutOfMemory) {
1048
1115
  spare = into;
@@ -1061,24 +1128,112 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1061
1128
  replayed: 0,
1062
1129
  word: 0,
1063
1130
  restored: new Map(),
1064
- abcs: null,
1131
+ abcs: [],
1132
+ given: 0,
1133
+ revivals: carried,
1134
+ evicted: new Set([...journalDomains.keys()].filter((d) => wasm.domainState(d) === 1)),
1065
1135
  phase: "load",
1066
1136
  catchUp: 0,
1067
1137
  };
1068
1138
  moves.started++;
1069
1139
  return true;
1070
1140
  };
1141
+ // `saved` with `carried` revived by its load, their ABCs' bytes joined,
1142
+ // each once. A revival's ABCs were gathered when it was asked for: those
1143
+ // of domains revived since, live in the snapshot, which holds them, are
1144
+ // left out, else the load would take one twice and refuse the move. The
1145
+ // chain's states here are the snapshot's, for a snapshot taken now and for
1146
+ // one a revival is folded into (see scheduleRevivals).
1147
+ const withRevivals = (saved: Checkpoint, carried: Revival[]): Checkpoint => {
1148
+ if (!carried.length) {
1149
+ return saved;
1150
+ }
1151
+
1152
+ const domains = [...(saved.revive?.domains ?? [])];
1153
+ const abcs = new Map(saved.revive?.abcs ?? []);
1154
+ for (const r of carried) {
1155
+ // One an earlier revival's chain takes in is revived by that one's load.
1156
+ if (!domains.some((d) => inChain(r.appDomain, d))) {
1157
+ domains.push(r.appDomain);
1158
+ }
1159
+
1160
+ for (const [index, bytes] of r.abcs) {
1161
+ if (!abcs.has(index) && !saved.abcs.has(index) && evictedAbc(index)) {
1162
+ abcs.set(index, bytes);
1163
+ }
1164
+ }
1165
+ }
1166
+
1167
+ return { state: saved.state, abcs: saved.abcs, revive: { domains, abcs } };
1168
+ };
1169
+ const evictedAbc = (index: number) =>
1170
+ Number.isInteger(index) &&
1171
+ index >= 0 &&
1172
+ index < abcDomains.length &&
1173
+ wasm.domainState(abcDomains[index]) === 1;
1174
+ // Domain `appDomain` and its evicted ancestors, the last a child of a live one.
1175
+ const evictedChain = (appDomain: number) => {
1176
+ const chain = new Set<number>();
1177
+ for (let d = appDomain; d > 0 && wasm.domainState(d) === 1; d = wasm.domainParent(d)) {
1178
+ chain.add(d);
1179
+ }
1180
+
1181
+ return chain;
1182
+ };
1183
+ // The domains the load of `m` revived, live in its spare, caught up, that
1184
+ // this instance evicts and no revival still wants: those between a
1185
+ // revival's domain and its chain's top, the domain dropped since. Evicted
1186
+ // in the spare too before it takes this instance's place, else the move
1187
+ // would leave them live where a compiler that never moved has them
1188
+ // evicted; in order, a parent before its children, which it evicts.
1189
+ const unwantedRevived = (m: Move): number[] => {
1190
+ if (!m.revivals.length) {
1191
+ return [];
1192
+ }
1193
+
1194
+ const wanted = new Set<number>();
1195
+ for (const r of m.revivals) {
1196
+ for (const d of evictedChain(r.appDomain)) {
1197
+ wanted.add(d);
1198
+ }
1199
+ }
1200
+
1201
+ const unwanted: number[] = [];
1202
+ for (const d of [...journalDomains.keys()].sort((x, y) => x - y)) {
1203
+ if (
1204
+ d > 0 &&
1205
+ !wanted.has(d) &&
1206
+ wasm.domainState(d) === 1 &&
1207
+ m.into.domainState(d) === 0 &&
1208
+ !unwanted.some((u) => inChain(u, d))
1209
+ ) {
1210
+ unwanted.push(d);
1211
+ }
1212
+ }
1213
+
1214
+ return unwanted;
1215
+ };
1071
1216
  // The spare, rebuilt and caught up, takes this instance's place, as a
1072
1217
  // recovery's does, and the snapshot it rebuilt is the checkpoint, the
1073
1218
  // calls since it the journal.
1074
1219
  const swapMove = (m: Move) => {
1075
1220
  move = null;
1076
1221
  moves.completed++;
1222
+ moves.revived += m.revivals.length;
1223
+ for (const r of m.revivals) {
1224
+ const at = revivals.indexOf(r);
1225
+ if (at >= 0) {
1226
+ revivals.splice(at, 1);
1227
+ }
1228
+ }
1229
+
1077
1230
  const kept = m.entries.filter((entry) => journal.has(entry));
1078
1231
  moves.lastCaughtUp = kept.length;
1079
1232
  moves.lastSavedBytes = m.saved.state.length;
1080
- for (const abc of m.saved.abcs.values()) {
1081
- moves.lastSavedBytes += abc.length;
1233
+ for (const abcs of [m.saved.abcs, m.saved.revive?.abcs ?? new Map()]) {
1234
+ for (const abc of abcs.values()) {
1235
+ moves.lastSavedBytes += abc.length;
1236
+ }
1082
1237
  }
1083
1238
 
1084
1239
  journal.clear();
@@ -1121,13 +1276,23 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1121
1276
  return "none";
1122
1277
  }
1123
1278
 
1124
- m.abcs = m.saved.abcs.entries();
1279
+ // domainLoad's MOVE_Limit counts the snapshot alone: the chains
1280
+ // revived after it add their ABCs at their weight, three times
1281
+ // their bytes, small beside the limit's gigabyte.
1282
+ for (const domain of m.saved.revive?.domains ?? []) {
1283
+ if (into.domainLoadRevive(domain) !== 0) {
1284
+ abortMove("refused");
1285
+ return "none";
1286
+ }
1287
+ }
1288
+
1289
+ m.abcs = [...m.saved.abcs, ...(m.saved.revive?.abcs ?? [])];
1125
1290
  m.phase = "abcs";
1126
1291
  return "moving";
1127
1292
  case "abcs": {
1128
- const next = m.abcs?.next();
1129
- if (next && !next.done) {
1130
- if (into.domainLoadAbc(next.value[0], next.value[1]) !== 0) {
1293
+ if (m.given < m.abcs.length) {
1294
+ const [index, bytes] = m.abcs[m.given++];
1295
+ if (into.domainLoadAbc(index, bytes) !== 0) {
1131
1296
  abortMove("refused");
1132
1297
  return "none";
1133
1298
  }
@@ -1135,7 +1300,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1135
1300
  return "moving";
1136
1301
  }
1137
1302
 
1138
- m.abcs = null;
1303
+ m.abcs = [];
1139
1304
  if (!into.domainLoadRebuild()) {
1140
1305
  abortMove("refused");
1141
1306
  return "none";
@@ -1169,7 +1334,18 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1169
1334
  }
1170
1335
 
1171
1336
  if (m.replayed === m.entries.length) {
1337
+ const unwanted = unwantedRevived(m);
1338
+ for (const domain of unwanted) {
1339
+ into.domainEvict(domain);
1340
+ }
1341
+
1172
1342
  swapMove(m);
1343
+ // Owned by the root, as evictDomain's: a revival journaled later
1344
+ // needs it though the domain is dropped after.
1345
+ for (const domain of unwanted) {
1346
+ journaled({ kind: "evict", appDomain: domain });
1347
+ }
1348
+
1173
1349
  return "done";
1174
1350
  }
1175
1351
 
@@ -1262,6 +1438,183 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1262
1438
  spare = null;
1263
1439
  return startMove(into) ? "moving" : "none";
1264
1440
  };
1441
+ // The revivals left to a move whose domains are still evicted here, those
1442
+ // revived otherwise or dropped since let go of, as are those whose chain
1443
+ // has grown by an ancestor evicted since, which the host, asking again,
1444
+ // gives the bytes of; and the revivals waiting for a move, failed ones apart.
1445
+ const waitingRevivals = (): Revival[] => {
1446
+ for (let i = revivals.length - 1; i >= 0; i--) {
1447
+ const r = revivals[i];
1448
+ if (wasm.domainState(r.appDomain) !== 1 || !givenAll(r)) {
1449
+ revivals.splice(i, 1);
1450
+ }
1451
+ }
1452
+
1453
+ return revivals.filter((r) => !r.failed && !move?.revivals.includes(r));
1454
+ };
1455
+ const givenAll = (r: Revival) => {
1456
+ const chain = evictedChain(r.appDomain);
1457
+ for (let index = 0; index < abcDomains.length; index++) {
1458
+ if (chain.has(abcDomains[index]) && !r.abcs.has(index)) {
1459
+ return false;
1460
+ }
1461
+ }
1462
+
1463
+ return true;
1464
+ };
1465
+ // Whether the chain of `r` is not what it was at the snapshot of `m`, an
1466
+ // ancestor evicted or revived since, by a revival of its own or of
1467
+ // another under it: its load would then revive a chain other than the one
1468
+ // here, with ABCs of it not given, or the spare replay a revival or an
1469
+ // eviction its load had made moot.
1470
+ const chainChanged = (m: Move, r: Revival) => {
1471
+ if (
1472
+ m.entries.some(
1473
+ (e) => (e.kind === "evict" || e.kind === "revive") && inChain(e.appDomain, r.appDomain),
1474
+ )
1475
+ ) {
1476
+ return true;
1477
+ }
1478
+
1479
+ const now = evictedChain(r.appDomain);
1480
+ let d = r.appDomain;
1481
+ for (; d > 0 && m.evicted.has(d); d = wasm.domainParent(d)) {
1482
+ if (!now.delete(d)) {
1483
+ return true;
1484
+ }
1485
+ }
1486
+
1487
+ return now.size > 0;
1488
+ };
1489
+ // Revivals waiting, given to the move under way while its spare has not
1490
+ // begun to rebuild, as its load revives them, unless their chain changed
1491
+ // since its snapshot; else, if it only compacts, the move is given up for
1492
+ // one that revives as it compacts, as going on would cost its rest and
1493
+ // then a rebuild; those a move that revives cannot take wait for the next.
1494
+ const scheduleRevivals = (waiting: Revival[]) => {
1495
+ const m = move;
1496
+ if (m === null || !waiting.length) {
1497
+ return;
1498
+ }
1499
+
1500
+ const fresh =
1501
+ m.phase === "load" || m.phase === "abcs" ? waiting.filter((r) => !chainChanged(m, r)) : [];
1502
+ if (fresh.length < waiting.length && !m.revivals.length) {
1503
+ abortMove("superseded");
1504
+ return;
1505
+ }
1506
+
1507
+ if (!fresh.length) {
1508
+ return;
1509
+ }
1510
+
1511
+ const loaded = m.phase === "abcs";
1512
+ const before = m.saved.revive;
1513
+ const saved = withRevivals(m.saved, fresh);
1514
+ try {
1515
+ for (const domain of saved.revive?.domains ?? []) {
1516
+ if (loaded && !before?.domains.includes(domain) && m.into.domainLoadRevive(domain) !== 0) {
1517
+ for (const r of fresh) {
1518
+ r.failed = true;
1519
+ }
1520
+
1521
+ abortMove("refused");
1522
+ return;
1523
+ }
1524
+ }
1525
+ } catch (error) {
1526
+ for (const r of fresh) {
1527
+ r.failed = true;
1528
+ }
1529
+
1530
+ abortMove(
1531
+ error instanceof CodegenPanic || error instanceof CodegenOutOfMemory ? "spare" : "refused",
1532
+ );
1533
+ return;
1534
+ }
1535
+
1536
+ m.revivals.push(...fresh);
1537
+ m.saved = saved;
1538
+ if (loaded) {
1539
+ for (const entry of saved.revive?.abcs ?? []) {
1540
+ if (!before?.abcs.has(entry[0])) {
1541
+ m.abcs.push(entry);
1542
+ }
1543
+ }
1544
+ }
1545
+ };
1546
+ // A move that revives the domains waiting, and compacts as it does, once
1547
+ // there is a spare to make it in; where none can be made, or the journal
1548
+ // cannot catch one up, they are done in place when asked for again.
1549
+ const beginRevival = (waiting: Revival[]): CompactProgress => {
1550
+ const fail = (): CompactProgress => {
1551
+ for (const r of waiting) {
1552
+ r.failed = true;
1553
+ }
1554
+
1555
+ return "none";
1556
+ };
1557
+ if (!replayable) {
1558
+ return fail();
1559
+ }
1560
+
1561
+ const into = spare;
1562
+ if (into === null) {
1563
+ if (spareFailed && !making) {
1564
+ spareFailed = false;
1565
+ return fail();
1566
+ }
1567
+
1568
+ prepare();
1569
+ return "moving";
1570
+ }
1571
+
1572
+ spare = null;
1573
+ return startMove(into, waiting) ? "moving" : fail();
1574
+ };
1575
+ // The ABCs of evicted domain `appDomain` and its evicted ancestors, the
1576
+ // first a child of a live one, among `abcs`, copied: each must be there,
1577
+ // else the revival throws, as reviveDomain does when it cannot revive.
1578
+ const revivalAbcs = (appDomain: number, abcs: Map<number, Uint8Array>) => {
1579
+ const chain = evictedChain(appDomain);
1580
+ const top = [...chain].pop() ?? appDomain;
1581
+ let missing = false;
1582
+ const owned = new Map<number, Uint8Array>();
1583
+ for (let index = 0; index < abcDomains.length; index++) {
1584
+ if (chain.has(abcDomains[index])) {
1585
+ const bytes = abcs.get(index);
1586
+ if (bytes === undefined) {
1587
+ missing = true;
1588
+ } else {
1589
+ owned.set(index, new Uint8Array(bytes));
1590
+ }
1591
+ }
1592
+ }
1593
+
1594
+ if (missing || wasm.domainState(wasm.domainParent(top)) !== 0) {
1595
+ throw new Error(
1596
+ `application domain ${appDomain}: not evicted, its parent not live, or an ABC of it not given`,
1597
+ );
1598
+ }
1599
+
1600
+ return owned;
1601
+ };
1602
+ // Whether the domain, with the chain a revival links again, its ABCs
1603
+ // `abcs`, is large enough that the revival's rebuild goes to a move
1604
+ // rather than block: a small domain reviving a large chain rebuilds as
1605
+ // long as one that was large all along.
1606
+ const revivalSteps = (abcs: Map<number, Uint8Array>) => {
1607
+ if (!replayable || moveRefused) {
1608
+ return false;
1609
+ }
1610
+
1611
+ let weight = Number(wasm.domainUsage().split(" ")[0]);
1612
+ for (const bytes of abcs.values()) {
1613
+ weight += REVIVED_Weight * bytes.length;
1614
+ }
1615
+
1616
+ return weight >= IN_PLACE_Live;
1617
+ };
1265
1618
  // Whether the domain was lost to a panic recovery could not undo (see fresh).
1266
1619
  let lost = false;
1267
1620
  const api: Codegen = {
@@ -1276,6 +1629,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1276
1629
  reset(version = API_VERSION) {
1277
1630
  checkApiVersion(version);
1278
1631
  abortMove("superseded");
1632
+ revivals.length = 0;
1279
1633
  moveRefused = false;
1280
1634
  retryAt = 0;
1281
1635
  wasm.domainReset(version);
@@ -1408,9 +1762,11 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1408
1762
  return wasm.domainCompact(true) && rebuild(wasm, null, true);
1409
1763
  },
1410
1764
  compactStep(deadline) {
1765
+ const waiting = waitingRevivals();
1766
+ scheduleRevivals(waiting);
1411
1767
  let m = move;
1412
1768
  if (m === null) {
1413
- const begun = beginCompaction();
1769
+ const begun = waiting.length ? beginRevival(waiting) : beginCompaction();
1414
1770
  if (begun !== "moving" || move === null) {
1415
1771
  return begun;
1416
1772
  }
@@ -1454,7 +1810,40 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1454
1810
  isLive(appDomain) {
1455
1811
  return wasm.domainState(appDomain) === 0;
1456
1812
  },
1457
- reviveDomain(appDomain, abcs) {
1813
+ reviveDomain(appDomain, abcs, stepped = false) {
1814
+ // A revival left to a move already, of this domain or a descendant,
1815
+ // which revives it too.
1816
+ const queued = revivals.find((r) => inChain(appDomain, r.appDomain));
1817
+ if (stepped && queued !== undefined && !queued.failed && replayable) {
1818
+ return false;
1819
+ }
1820
+
1821
+ // One the move under way makes, finished here, as compact finishes it;
1822
+ // a revival given up is done in place below.
1823
+ const m = move;
1824
+ if (queued !== undefined && m?.revivals.includes(queued)) {
1825
+ let progress = moveUnit(m);
1826
+ while (progress === "moving") {
1827
+ progress = moveUnit(m);
1828
+ }
1829
+
1830
+ if (wasm.domainState(appDomain) === 0) {
1831
+ return true;
1832
+ }
1833
+ }
1834
+
1835
+ if (queued !== undefined && revivals.includes(queued)) {
1836
+ revivals.splice(revivals.indexOf(queued), 1);
1837
+ }
1838
+
1839
+ if (stepped && queued === undefined && wasm.domainReviveNeeds(appDomain) === 1) {
1840
+ const owned = revivalAbcs(appDomain, abcs);
1841
+ if (revivalSteps(owned)) {
1842
+ revivals.push({ appDomain, abcs: owned, failed: false });
1843
+ return false;
1844
+ }
1845
+ }
1846
+
1458
1847
  // A move's spare lets go of the ABCs of the domains evicted before its
1459
1848
  // snapshot, and before any rebuild a replayed revival makes in it,
1460
1849
  // which this instance may still hold: restores journaled before the
@@ -1473,6 +1862,17 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1473
1862
  let revived = wasm.domainRevive(appDomain, true);
1474
1863
  if (revived < 0) {
1475
1864
  for (const [index, bytes] of abcs) {
1865
+ // One of a domain live here, which a move revived after the host
1866
+ // gathered the chain's bytes, is held already.
1867
+ if (
1868
+ Number.isInteger(index) &&
1869
+ index >= 0 &&
1870
+ index < abcDomains.length &&
1871
+ wasm.domainState(abcDomains[index]) === 0
1872
+ ) {
1873
+ continue;
1874
+ }
1875
+
1476
1876
  const owned = new Uint8Array(bytes);
1477
1877
  const error = wasm.domainRestore(index, owned);
1478
1878
  if (error !== 0) {
@@ -1519,6 +1919,8 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
1519
1919
  `application domain ${appDomain}: not evicted, its parent not live, or an ABC of it not given`,
1520
1920
  );
1521
1921
  }
1922
+
1923
+ return true;
1522
1924
  },
1523
1925
  found({ domain, nsKind, uri, name, abc, asType }) {
1524
1926
  wasm.domainFound(domain, nsKind, uri, name, abc, asType);
@@ -1774,6 +2176,9 @@ const WANT_Spare = 3;
1774
2176
  * rebuilds in place, in one call, rather than move a part at a time.
1775
2177
  */
1776
2178
  const IN_PLACE_Live = 4 << 20;
2179
+ // The weight of an ABC's byte a revival links again, before its compiles:
2180
+ // the compiler's own ABC_Weight (zig/src/avm2/link/domain.zig).
2181
+ const REVIVED_Weight = 3;
1777
2182
  /** A compile's log entry that verified an ABC: LogKind.verify (avm2/link/domain.zig). */
1778
2183
  const LOG_Verify = 4;
1779
2184
  /**
package/src/zig.ts CHANGED
@@ -98,6 +98,7 @@ export interface CodegenExports {
98
98
  domainLoad(words: Uint8Array): boolean;
99
99
  domainLoadAbc(index: number, bytes: Uint8Array): number;
100
100
  domainLoadRebuild(): boolean;
101
+ domainLoadRevive(appDomain: number): number;
101
102
  domainLogMark(): number;
102
103
  domainLogSince(mark: number, index?: number): string;
103
104
  domainModule(hashes?: string, index?: number, keep?: boolean, linkedOnly?: boolean): string;
@@ -113,6 +114,7 @@ export interface CodegenExports {
113
114
  domainRestore(index: number, bytes: Uint8Array): number;
114
115
  domainRevision(): string;
115
116
  domainRevive(appDomain: number, stepped?: boolean): number;
117
+ domainReviveNeeds(appDomain: number): number;
116
118
  domainSaveBytes(): number;
117
119
  domainSavedAbcBytes(index: number): number;
118
120
  domainSourceMap(): string;
@@ -175,6 +177,7 @@ export const SIGNATURES: {
175
177
  domainLoad: ["u8s", "bool"],
176
178
  domainLoadAbc: ["i32 u8s", "i32"],
177
179
  domainLoadRebuild: ["", "bool"],
180
+ domainLoadRevive: ["i32", "i32"],
178
181
  domainLogMark: ["", "i32"],
179
182
  domainLogSince: ["i32 i32=-1", "str"],
180
183
  domainModule: ["str= i32=-1 bool=true bool=false", "str"],
@@ -190,6 +193,7 @@ export const SIGNATURES: {
190
193
  domainRestore: ["i32 u8s", "i32"],
191
194
  domainRevision: ["", "str"],
192
195
  domainRevive: ["i32 bool=false", "i32"],
196
+ domainReviveNeeds: ["i32", "i32"],
193
197
  domainSaveBytes: ["", "address"],
194
198
  domainSavedAbcBytes: ["i32", "address"],
195
199
  domainSourceMap: ["", "str"],