@hew-lang/sandbox-vm 0.10.0-rc1 → 0.11.0-rc3

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.
@@ -11,7 +11,7 @@ import { executeCodec } from "./codecs.js";
11
11
  import { actorIdentical } from "./actor-identity.js";
12
12
  import { ActorWaits } from "./actor-waits.js";
13
13
  import { TraceBuilder, runtimeFailure } from "../trace.js";
14
- import { UNIT, cloneValue, releaseVector, byteVectorValue, vectorStorage, stringValue, toJsonValue, } from "../values.js";
14
+ import { UNIT, cloneValue, releaseVector, byteVectorValue, vectorStorage, vectorItems, vectorLength, vectorElement, stringValue, toJsonValue, } from "../values.js";
15
15
  import { runtimeTag, staticOperations } from "./package.js";
16
16
  import { StructuralRenderer } from "./structural.js";
17
17
  import { timestampBinary } from "./timestamp.js";
@@ -21,11 +21,17 @@ import { Semaphores } from "./semaphores.js";
21
21
  import { FrameScheduler } from "./scheduler.js";
22
22
  import { DeterministicIds } from "../../scheduler/ids.js";
23
23
  import { Mt19937 } from "./mt19937.js";
24
+ import { FAILURE_TEXT_LIMIT, FAILURE_TRUNCATED_SUFFIX, } from "./failure-limits.generated.js";
24
25
  import { ShimFault, CODEC_REGISTRATION, decodeUtf8Checked, resolveExtern, resolveRuntime, resolveSuspension, } from "./shims.js";
25
26
  import { AdmittedPackage } from "./validate.js";
26
27
  import { HeapExceeded, ManagedBudget, ManagedLayouts, } from "./managed-budget.js";
27
28
  const DEFAULT_STEP_BUDGET = 1_000_000;
28
29
  const DEFAULT_ACTOR_STOP_NS = 5_000_000_000;
30
+ /// Deepest activation a task may reach below its root before a call fails
31
+ /// with `StackOverflow`. HEW-SPEC-2026 §2.2 guarantees 10,000 frames. Twice
32
+ /// that matches what a native stack admits for small frames and leaves an
33
+ /// unbounded recursion failing well inside the default step budget.
34
+ const MAX_FRAME_DEPTH = 20_000;
29
35
  /// Ends the run. The status is already recorded on the trace.
30
36
  class Halt extends Error {
31
37
  status;
@@ -306,6 +312,7 @@ class ExecutorV1 {
306
312
  if (op.op !== "coverage.hit")
307
313
  this.commitStep();
308
314
  try {
315
+ act.instruction = op;
309
316
  this.execute(act, op);
310
317
  }
311
318
  catch (error) {
@@ -320,6 +327,7 @@ class ExecutorV1 {
320
327
  return;
321
328
  this.commitStep();
322
329
  try {
330
+ act.instruction = act.block.term;
323
331
  this.terminate(act, act.block.term);
324
332
  }
325
333
  catch (error) {
@@ -404,6 +412,7 @@ class ExecutorV1 {
404
412
  fault: null,
405
413
  parked: [],
406
414
  caller,
415
+ depth: caller ? caller.depth + 1 : 0,
407
416
  result,
408
417
  normal: normal ?? undefined,
409
418
  unwind,
@@ -523,8 +532,8 @@ class ExecutorV1 {
523
532
  (row.kind === "vector" ||
524
533
  row.kind === "array" ||
525
534
  row.kind === "slice")
526
- ? value.items.map((item) => this.managed.copy(item, row.element))
527
- : value.items;
535
+ ? vectorItems(value).map((item) => this.managed.copy(item, row.element))
536
+ : vectorItems(value);
528
537
  if (appended?.length) {
529
538
  if (row.kind !== "vector" &&
530
539
  row.kind !== "array" &&
@@ -538,6 +547,8 @@ class ExecutorV1 {
538
547
  budget.checkMutation(value, {
539
548
  ...value,
540
549
  items,
550
+ offset: 0,
551
+ length: undefined,
541
552
  storage: { ...storage, capacity, items, owners: 1 },
542
553
  }, detached);
543
554
  }
@@ -717,8 +728,7 @@ class ExecutorV1 {
717
728
  previous?.budget?.changed();
718
729
  actor.budget?.changed();
719
730
  }
720
- failActorBudget(actor) {
721
- const fault = { kind: "trap", trap: "heap_exceeded" };
731
+ failActorBudget(actor, fault = { kind: "trap", trap: "heap_exceeded" }) {
722
732
  if (!actor.active)
723
733
  this.crashActor(actor, fault);
724
734
  else {
@@ -1695,7 +1705,13 @@ class ExecutorV1 {
1695
1705
  case "checked.binary": {
1696
1706
  const failure = checkedFailure(term.binary_op, this.read(act, term.lhs), this.read(act, term.rhs), term.ty);
1697
1707
  if (failure) {
1698
- const edge = term.failures.find((candidate) => candidate.trap === failure);
1708
+ // Earlier v1 packages fold the signed minimum by -1 into their
1709
+ // overflow edge, so they keep the IntegerOverflow trap their
1710
+ // compiler emitted.
1711
+ const edge = term.failures.find((candidate) => candidate.trap === failure) ??
1712
+ (failure === "signed_min_div_neg_one"
1713
+ ? term.failures.find((candidate) => candidate.trap === "integer_overflow")
1714
+ : undefined);
1699
1715
  if (!edge) {
1700
1716
  throw new Error(`checked.binary names no ${failure} edge`);
1701
1717
  }
@@ -1930,6 +1946,7 @@ class ExecutorV1 {
1930
1946
  message: renderMessage(message),
1931
1947
  ...(assertion ? { assertion } : {}),
1932
1948
  };
1949
+ this.captureFault(act, act.fault);
1933
1950
  if (act.context.actor)
1934
1951
  act.context.actor.crashing ??= act.fault;
1935
1952
  this.takeEdge(act, term.cleanup);
@@ -1937,6 +1954,7 @@ class ExecutorV1 {
1937
1954
  }
1938
1955
  case "checked_raise":
1939
1956
  act.fault = { kind: "trap", trap: term.trap };
1957
+ this.captureFault(act, act.fault);
1940
1958
  if (act.context.actor)
1941
1959
  act.context.actor.crashing ??= act.fault;
1942
1960
  this.takeEdge(act, term.cleanup);
@@ -1988,6 +2006,26 @@ class ExecutorV1 {
1988
2006
  tag: deadline ? term.deadline_variant : term.fault_variant,
1989
2007
  payload: [stringValue(faultRecoveryMessage(fault))],
1990
2008
  };
2009
+ // Scope recovery must preserve the original fault even when the
2010
+ // current actor cannot retain its diagnostic text. Preflight the same
2011
+ // managed graph that completion will retain, then use the canonical
2012
+ // empty string on refusal without publishing an uncharged owner.
2013
+ const result = term.result?.value;
2014
+ const type = result == null ? undefined : act.managedTypes.get(result);
2015
+ const budget = result != null && act.owned.has(result)
2016
+ ? act.context.actor?.budget
2017
+ : undefined;
2018
+ if (budget && type != null) {
2019
+ try {
2020
+ this.managed.stampGraph({ value, type });
2021
+ budget.check([{ value, type }]);
2022
+ }
2023
+ catch (error) {
2024
+ if (!(error instanceof HeapExceeded))
2025
+ throw error;
2026
+ value.payload[0] = stringValue("");
2027
+ }
2028
+ }
1991
2029
  act.fault = null;
1992
2030
  if (act.context.actor)
1993
2031
  act.context.actor.crashing = null;
@@ -2359,13 +2397,13 @@ class ExecutorV1 {
2359
2397
  if (operation === "Len") {
2360
2398
  this.completeShim(act, term, {
2361
2399
  kind: "i64",
2362
- value: BigInt(view.items.length),
2400
+ value: BigInt(vectorLength(view)),
2363
2401
  });
2364
2402
  return;
2365
2403
  }
2366
2404
  if (index?.kind !== "i64")
2367
2405
  throw new Error("pool operation has no index");
2368
- const value = view.items[Number(index.value)];
2406
+ const value = vectorElement(view, Number(index.value));
2369
2407
  if (operation === "Get") {
2370
2408
  this.completeShim(act, term, this.variant(term.result_shape, value ? "OptionSome" : "OptionNone", value ? [value] : []));
2371
2409
  return;
@@ -2402,7 +2440,7 @@ class ExecutorV1 {
2402
2440
  }, (fault) => {
2403
2441
  this.raiseFault(act, fault, term.unwind);
2404
2442
  this.scheduler.enqueue(act.context.id, () => this.runFrame(act));
2405
- });
2443
+ }, act.context.actor?.rcOwner ?? null, false, undefined, act);
2406
2444
  act.context.cancel = (fault) => callback.cancel?.(fault);
2407
2445
  };
2408
2446
  continueRendering();
@@ -2610,6 +2648,7 @@ class ExecutorV1 {
2610
2648
  /// Raise a fault at a call site: enter the named unwind edge, or end the
2611
2649
  /// program when the call names none.
2612
2650
  raiseFault(act, fault, unwind) {
2651
+ this.captureFault(act, fault);
2613
2652
  if (!unwind) {
2614
2653
  this.running = false;
2615
2654
  act.context.failed(fault);
@@ -2619,6 +2658,8 @@ class ExecutorV1 {
2619
2658
  this.takeEdge(act, unwind);
2620
2659
  }
2621
2660
  resumeUnwind(act, handback) {
2661
+ if (act.fault)
2662
+ this.captureFault(act, act.fault);
2622
2663
  if (this.finishConsumedCallable(act, null, () => this.resumeUnwind(act, handback)))
2623
2664
  return;
2624
2665
  if (this.finishConstruction(act, () => this.resumeUnwind(act, handback)))
@@ -2940,9 +2981,9 @@ class ExecutorV1 {
2940
2981
  const wake = this.park(act, term);
2941
2982
  let target;
2942
2983
  let checkWait;
2943
- const cancelRequest = this.ask(protocol, inputs, (value, error, closeFault) => {
2984
+ const cancelRequest = this.ask(protocol, inputs, (value, error, closeFault, _envelope, actorFault) => {
2944
2985
  act.fault ??= closeFault ?? null;
2945
- return wake(this.completion(term.result_shape, term.error_shape, value, error));
2986
+ return wake(this.completion(term.result_shape, term.error_shape, value, error, actorFault, act.accountActor?.budget));
2946
2987
  }, term.request_shapes, (actor) => {
2947
2988
  target = actor;
2948
2989
  checkWait?.();
@@ -3015,6 +3056,17 @@ class ExecutorV1 {
3015
3056
  return;
3016
3057
  }
3017
3058
  case "Safepoint": {
3059
+ // A function's entry safepoint is its stack check (HEW-SPEC-2026
3060
+ // §2.2): past the frame limit the call fails with `StackOverflow`
3061
+ // and its parameters follow the cancellation cleanup.
3062
+ if (term.cancel &&
3063
+ act.depth > MAX_FRAME_DEPTH &&
3064
+ act.block.id === act.fn.entry) {
3065
+ act.fault = { kind: "trap", trap: "stack_overflow" };
3066
+ this.captureFault(act, act.fault);
3067
+ this.takeEdge(act, term.cancel);
3068
+ return;
3069
+ }
3018
3070
  if (act.context.pollSuppression) {
3019
3071
  this.takeEdge(act, term.resumes[0]);
3020
3072
  return;
@@ -3816,7 +3868,11 @@ class ExecutorV1 {
3816
3868
  reply: { value: envelope, type: provider.reply },
3817
3869
  };
3818
3870
  }
3819
- invokeFrame(actor, callable, args, returned, failed, rcOwner = actor?.rcOwner ?? null, inline = false, retainedBy) {
3871
+ invokeFrame(actor, callable, args, returned, failed, rcOwner = actor?.rcOwner ?? null, inline = false, retainedBy,
3872
+ // The activation this frame runs on behalf of. Its depth carries on, so a
3873
+ // recursion through runtime callbacks reaches the frame limit as a direct
3874
+ // one does.
3875
+ invoker = retainedBy) {
3820
3876
  const context = {
3821
3877
  id: actor?.id ?? "actor:root",
3822
3878
  actor,
@@ -3834,6 +3890,10 @@ class ExecutorV1 {
3834
3890
  },
3835
3891
  };
3836
3892
  const frame = this.activate(this.functionAt(callable), args, null, null, undefined, null, context);
3893
+ if (invoker) {
3894
+ frame.depth = invoker.depth + 1;
3895
+ frame.traceCaller = invoker;
3896
+ }
3837
3897
  retainedBy?.managedChildren.add(frame);
3838
3898
  let cancelled = null;
3839
3899
  context.cancel = (fault = { kind: "panic", message: "task cancelled", cancelled: true }) => {
@@ -3869,7 +3929,161 @@ class ExecutorV1 {
3869
3929
  }
3870
3930
  return value;
3871
3931
  }
3872
- completion(result, errorShape, value, error) {
3932
+ /// Bytecode has real function identities but no file/line table. Capture
3933
+ /// up to the native snapshot's 48 physical activations at the origin, before
3934
+ /// unwind replaces them. The VM always captures available frames; it has no
3935
+ /// environment-variable trace policy. Repeated frames retain their count.
3936
+ captureFault(act, fault) {
3937
+ const origin = fault.primary ?? fault;
3938
+ if (origin.frames !== undefined)
3939
+ return;
3940
+ origin.frames = [];
3941
+ let previous;
3942
+ let previousInstruction;
3943
+ let previousBlock;
3944
+ let previousIndex;
3945
+ for (let frame = act, count = 0; frame && count < 48; frame = frame.caller ?? frame.traceCaller ?? null, count++) {
3946
+ if (!failureTextPrefix(frame.fn.name).complete) {
3947
+ previous = undefined;
3948
+ previousInstruction = undefined;
3949
+ continue;
3950
+ }
3951
+ if (previous === frame.fn.id &&
3952
+ frame.instruction !== undefined &&
3953
+ previousInstruction === frame.instruction &&
3954
+ previousBlock === frame.block.id &&
3955
+ previousIndex === frame.opIndex)
3956
+ origin.frames.at(-1).repeat++;
3957
+ else
3958
+ origin.frames.push({ function: frame.fn.name, repeat: 1 });
3959
+ previous = frame.fn.id;
3960
+ previousInstruction = frame.instruction;
3961
+ previousBlock = frame.block.id;
3962
+ previousIndex = frame.opIndex;
3963
+ }
3964
+ }
3965
+ trappedError(errorShape, fault, budget) {
3966
+ const row = (this.pkg.managed_types ?? []).find((row) => row.kind === "variant" && row.shape === errorShape);
3967
+ if (!row || row.kind !== "variant")
3968
+ throw new Error("actor error lacks its managed variant descriptor");
3969
+ const tag = runtimeTag(this.pkg.variants[errorShape], "ActorErrorTrapped");
3970
+ const type = row.cases[tag]?.[0];
3971
+ if (type == null)
3972
+ throw new Error("trapped actor completion lacks its crash payload descriptor");
3973
+ return this.variant(errorShape, "ActorErrorTrapped", [
3974
+ this.crashInfo(type, fault, budget),
3975
+ ]);
3976
+ }
3977
+ crashInfo(type, fault, budget) {
3978
+ const origin = fault.primary ?? fault;
3979
+ const info = this.managed.row(type);
3980
+ if (info.kind !== "aggregate" || info.fields.length !== 5)
3981
+ throw new Error("crash payload lacks its five-field managed descriptor");
3982
+ const variant = (type) => {
3983
+ const row = this.managed.row(type);
3984
+ if (row.kind !== "variant")
3985
+ throw new Error("crash payload child is not a variant");
3986
+ return row;
3987
+ };
3988
+ const option = (type, value) => this.variant(variant(type).shape, value === undefined ? "OptionNone" : "OptionSome", value === undefined ? [] : [value]);
3989
+ const someType = (type) => {
3990
+ const row = variant(type);
3991
+ const child = row.cases[runtimeTag(this.pkg.variants[row.shape], "OptionSome")]?.[0];
3992
+ if (child == null)
3993
+ throw new Error("crash payload option lacks its child descriptor");
3994
+ return child;
3995
+ };
3996
+ const aggregateShape = (type) => {
3997
+ const row = this.managed.row(type);
3998
+ if (row.kind !== "aggregate")
3999
+ throw new Error("crash payload record lacks its descriptor");
4000
+ const shape = row.shape;
4001
+ if (shape == null)
4002
+ throw new Error("crash payload record lacks its aggregate identity");
4003
+ return shape;
4004
+ };
4005
+ const record = (type, fields) => {
4006
+ const shape = aggregateShape(type);
4007
+ return {
4008
+ kind: "record",
4009
+ typeId: this.aggregateName(shape),
4010
+ shape,
4011
+ fields,
4012
+ };
4013
+ };
4014
+ const [kindType, trapType, , siteType, traceType] = info.fields;
4015
+ const [code, reason] = faultInfo(origin);
4016
+ const kind = this.variant(variant(kindType).shape, code === 200
4017
+ ? "CrashKindHeapExceeded"
4018
+ : code === 214
4019
+ ? "CrashKindTimerOverdue"
4020
+ : code === 213
4021
+ ? "CrashKindHandlerFailed"
4022
+ : code === 215
4023
+ ? "CrashKindStackOverflow"
4024
+ : "CrashKindFault");
4025
+ const trap = variant(someType(trapType));
4026
+ const trapTag = this.pkg.variants[trap.shape].cases.findIndex((item) => item.name === reason);
4027
+ const trapValue = trapTag < 0
4028
+ ? undefined
4029
+ : {
4030
+ kind: "enum",
4031
+ typeId: this.variantName(trap.shape),
4032
+ shape: trap.shape,
4033
+ tag: trapTag,
4034
+ payload: [],
4035
+ };
4036
+ const vector = this.managed.row(someType(traceType));
4037
+ if (vector.kind !== "vector")
4038
+ throw new Error("crash trace lacks its vector descriptor");
4039
+ const frame = this.managed.row(vector.element);
4040
+ if (frame.kind !== "aggregate" || frame.fields.length !== 3)
4041
+ throw new Error("crash frame lacks its managed descriptor");
4042
+ const frames = {
4043
+ kind: "vector",
4044
+ elementType: this.aggregateName(aggregateShape(vector.element)),
4045
+ items: (origin.frames ?? []).map((item) => record(vector.element, [
4046
+ stringValue(item.function),
4047
+ option(frame.fields[1]),
4048
+ { kind: "i64", value: BigInt(item.repeat) },
4049
+ ])),
4050
+ };
4051
+ const value = record(type, [
4052
+ kind,
4053
+ option(trapType, trapValue),
4054
+ stringValue(boundedFailureMessage(faultApplicationMessage(origin) ?? reason)),
4055
+ option(siteType),
4056
+ option(traceType, origin.frames === undefined ? undefined : frames),
4057
+ ]);
4058
+ if (value.kind !== "record")
4059
+ throw new Error("crash payload is not a record");
4060
+ // Diagnostics must not replace the original failure with an allocation
4061
+ // failure. Drop trace storage first, then the message (site is unavailable).
4062
+ for (const omit of [null, 4, 2]) {
4063
+ if (omit === 4)
4064
+ value.fields[4] = option(traceType);
4065
+ if (omit === 2)
4066
+ value.fields[2] = stringValue("");
4067
+ try {
4068
+ this.managed.stampGraph({ value, type });
4069
+ budget?.check([{ value, type }]);
4070
+ return value;
4071
+ }
4072
+ catch (error) {
4073
+ if (!(error instanceof HeapExceeded))
4074
+ throw error;
4075
+ }
4076
+ }
4077
+ return value;
4078
+ }
4079
+ completion(result, errorShape, value, error, fault, budget) {
4080
+ if (error === "Trapped") {
4081
+ if (!fault)
4082
+ throw new Error("trapped actor completion lost its originating fault");
4083
+ return this.variant(result, "ResultErr", [
4084
+ this.trappedError(errorShape, fault, budget),
4085
+ ]);
4086
+ }
3873
4087
  return error
3874
4088
  ? this.variant(result, "ResultErr", [
3875
4089
  this.variant(errorShape, actorErrorRole(error), (error === "Failed" || error === "Rejected") && value
@@ -4211,7 +4425,8 @@ class ExecutorV1 {
4211
4425
  const task = this.newTask(act.context.actor?.budget, term.result && term.result !== "never"
4212
4426
  ? (term.result.managed_type ?? undefined)
4213
4427
  : undefined);
4214
- const cancelRequest = this.ask(operation.protocol, args, (value, error, closeFault, envelope) => {
4428
+ const cancelRequest = this.ask(operation.protocol, args, (value, error, closeFault, envelope, actorFault) => {
4429
+ task.actorFault = actorFault;
4215
4430
  const reply = this.managedCompletion(task, value, error, envelope);
4216
4431
  if (reply && !closeFault && act.context.actor?.budget) {
4217
4432
  try {
@@ -4220,12 +4435,12 @@ class ExecutorV1 {
4220
4435
  catch (failure) {
4221
4436
  if (!(failure instanceof HeapExceeded))
4222
4437
  throw failure;
4438
+ const fault = { kind: "trap", trap: "heap_exceeded" };
4439
+ this.captureFault(act, fault);
4223
4440
  task.actorError = "Trapped";
4224
- this.settleTask(task, UNIT, {
4225
- kind: "trap",
4226
- trap: "heap_exceeded",
4227
- });
4228
- this.failActorBudget(act.context.actor);
4441
+ task.actorFault = fault;
4442
+ this.settleTask(task, UNIT, fault);
4443
+ this.failActorBudget(act.context.actor, fault);
4229
4444
  return false;
4230
4445
  }
4231
4446
  }
@@ -4258,7 +4473,7 @@ class ExecutorV1 {
4258
4473
  task.value = UNIT;
4259
4474
  task.taken = true;
4260
4475
  const result = task.managedResult ??
4261
- this.completion(term.result_shape, term.error_shape, value, task.actorError);
4476
+ this.completion(term.result_shape, term.error_shape, value, task.actorError, task.actorFault, act.accountActor?.budget);
4262
4477
  task.managedResult = undefined;
4263
4478
  task.managedReply = undefined;
4264
4479
  this.completeShim(act, term, result);
@@ -4322,7 +4537,7 @@ class ExecutorV1 {
4322
4537
  this.closeValueAsync(payload, "actor heap limit exceeded", (fault) => {
4323
4538
  act.fault ??= fault;
4324
4539
  finish(this.variant(term.result_shape, "ResultErr", [
4325
- this.variant(term.error_shape, "ActorErrorTrapped"),
4540
+ this.trappedError(term.error_shape, actor.crashing ?? { kind: "trap", trap: "heap_exceeded" }, act.accountActor?.budget),
4326
4541
  ]));
4327
4542
  }, act.context.actor, act.rcOwner);
4328
4543
  return;
@@ -4374,27 +4589,32 @@ class ExecutorV1 {
4374
4589
  if (isPool && count?.kind !== "i64")
4375
4590
  throw new Error("pool construction has no count");
4376
4591
  const configured = isPool ? args.slice(0, -1) : args;
4377
- const initial = layout.backoff
4378
- ? configured[configured.length - 2]
4379
- : undefined;
4380
- const maximum = layout.backoff
4381
- ? configured[configured.length - 1]
4382
- : undefined;
4383
- const backoff = initial?.kind === "i64" && maximum?.kind === "i64"
4384
- ? { initial: initial.value, maximum: maximum.value }
4385
- : null;
4386
- const validBackoff = !layout.backoff ||
4387
- (backoff !== null &&
4388
- backoff.initial > 0n &&
4389
- backoff.maximum >= backoff.initial);
4390
- const config = layout.backoff ? configured.slice(0, -2) : configured;
4592
+ // Config, then each backoff child's `(initial, maximum)` pair in
4593
+ // declaration order.
4594
+ const pairs = layout.children.filter((child) => child.backoff).length;
4595
+ const config = configured.slice(0, configured.length - 2 * pairs);
4596
+ let pair = config.length;
4597
+ const declared = layout.children.map((child) => {
4598
+ if (!child.backoff)
4599
+ return null;
4600
+ const initial = configured[pair];
4601
+ const maximum = configured[pair + 1];
4602
+ pair += 2;
4603
+ return initial?.kind === "i64" && maximum?.kind === "i64"
4604
+ ? { initial: initial.value, maximum: maximum.value }
4605
+ : undefined;
4606
+ });
4607
+ const validBackoff = declared.every((backoff) => backoff === null ||
4608
+ (backoff !== undefined &&
4609
+ ((backoff.initial === 0n && backoff.maximum === 0n) ||
4610
+ (backoff.initial > 0n && backoff.maximum >= backoff.initial))));
4391
4611
  if (!validBackoff ||
4392
4612
  (count?.kind === "i64" &&
4393
4613
  (count.value <= 0n || count.value > 2147483647n))) {
4394
4614
  const fault = {
4395
4615
  kind: "panic",
4396
4616
  message: !validBackoff
4397
- ? "supervisor backoff requires positive initial and maximum >= initial"
4617
+ ? "supervisor backoff requires positive initial and maximum >= initial, or both zero"
4398
4618
  : "supervisor pool count must be between 1 and 2147483647",
4399
4619
  };
4400
4620
  this.running = false;
@@ -4423,7 +4643,7 @@ class ExecutorV1 {
4423
4643
  teardownChild: null,
4424
4644
  teardownCancelTimer: null,
4425
4645
  restartTimes: [],
4426
- backoff,
4646
+ backoffs: declared.flatMap((backoff) => Array.from({ length: members }, () => backoff ?? null)),
4427
4647
  restartDelays: new Map(),
4428
4648
  restartTimers: new Map(),
4429
4649
  closed: [],
@@ -4637,12 +4857,12 @@ class ExecutorV1 {
4637
4857
  ? { kind: "Actor", identity: owner.identity }
4638
4858
  : { kind: "Task" };
4639
4859
  let receiver = null;
4640
- const finish = (value, error, drained, envelope) => {
4860
+ const finish = (value, error, drained, envelope, actorFault) => {
4641
4861
  const alreadySettled = settled;
4642
4862
  settled = true;
4643
4863
  cancelTimer?.();
4644
4864
  if (alreadySettled ||
4645
- complete(value, error, undefined, envelope) === false) {
4865
+ complete(value, error, undefined, envelope, actorFault) === false) {
4646
4866
  // The finishing receiver still owns a reply that its caller no
4647
4867
  // longer accepts. Its next turn must wait for this release.
4648
4868
  this.closeValueAsync(value ?? UNIT, null, (fault) => {
@@ -4678,7 +4898,7 @@ class ExecutorV1 {
4678
4898
  waiter(fault);
4679
4899
  }, owner, rcOwner);
4680
4900
  };
4681
- const reject = (reason) => {
4901
+ const reject = (reason, actorFault) => {
4682
4902
  if (settled || closing)
4683
4903
  return;
4684
4904
  closeRequest((fault) => {
@@ -4686,7 +4906,7 @@ class ExecutorV1 {
4686
4906
  return;
4687
4907
  settled = true;
4688
4908
  cancelTimer?.();
4689
- complete(null, reason, fault);
4909
+ complete(null, reason, fault, undefined, actorFault);
4690
4910
  });
4691
4911
  };
4692
4912
  const attempt = () => {
@@ -4757,7 +4977,7 @@ class ExecutorV1 {
4757
4977
  if (!(error instanceof HeapExceeded))
4758
4978
  throw error;
4759
4979
  this.failActorBudget(actor);
4760
- reject("Trapped");
4980
+ reject("Trapped", actor.crashing ?? { kind: "trap", trap: "heap_exceeded" });
4761
4981
  return;
4762
4982
  }
4763
4983
  admitted = true;
@@ -5086,7 +5306,7 @@ class ExecutorV1 {
5086
5306
  this.closeValueAsync(value, this.faultText(fault), (closeFault) => {
5087
5307
  released();
5088
5308
  this.crashActor(actor, combineFaults(fault, closeFault), message.handler);
5089
- message.complete(null, "Trapped");
5309
+ message.complete(null, "Trapped", undefined, undefined, fault);
5090
5310
  }, actor, actor.rcOwner);
5091
5311
  return;
5092
5312
  }
@@ -5108,11 +5328,13 @@ class ExecutorV1 {
5108
5328
  if (message.reply)
5109
5329
  message.complete(value.payload[0] ?? UNIT, "Failed", drained, value);
5110
5330
  else {
5111
- this.crashActor(actor, {
5331
+ const fault = {
5112
5332
  kind: "panic",
5113
5333
  handlerFailed: true,
5114
5334
  message: "unhandled declared handler failure",
5115
- }, message.handler);
5335
+ };
5336
+ this.captureFault(frame, fault);
5337
+ this.crashActor(actor, fault, message.handler);
5116
5338
  return;
5117
5339
  }
5118
5340
  }
@@ -5141,7 +5363,7 @@ class ExecutorV1 {
5141
5363
  }
5142
5364
  else {
5143
5365
  this.crashActor(actor, fault, message.handler);
5144
- message.complete(null, "Trapped");
5366
+ message.complete(null, "Trapped", undefined, undefined, fault);
5145
5367
  }
5146
5368
  },
5147
5369
  });
@@ -5221,29 +5443,11 @@ class ExecutorV1 {
5221
5443
  };
5222
5444
  const runHook = () => {
5223
5445
  if (actor.layout.crash != null) {
5224
- const [code, reason] = faultInfo(fault);
5225
- const message = faultApplicationMessage(fault) ?? reason;
5226
- const info = {
5227
- kind: "record",
5228
- typeId: this.aggregateName(actor.layout.crash_info),
5229
- shape: actor.layout.crash_info,
5230
- fields: [
5231
- {
5232
- kind: "enum",
5233
- typeId: this.variantName(actor.layout.crash_kind),
5234
- shape: actor.layout.crash_kind,
5235
- tag: runtimeTag(this.pkg.variants[actor.layout.crash_kind], code === 200
5236
- ? "CrashKindHeapExceeded"
5237
- : code === 214
5238
- ? "CrashKindTimerOverdue"
5239
- : code === 213
5240
- ? "CrashKindHandlerFailed"
5241
- : "CrashKindFault"),
5242
- payload: [],
5243
- },
5244
- stringValue(String(message)),
5245
- ],
5246
- };
5446
+ const type = this.functionAt(actor.layout.crash).params[1]
5447
+ ?.managed_type;
5448
+ if (type == null)
5449
+ throw new Error("crash hook lacks its crash payload descriptor");
5450
+ const info = this.crashInfo(type, fault, actor.budget);
5247
5451
  let cancelTimer;
5248
5452
  const complete = (action) => {
5249
5453
  cancelTimer?.();
@@ -5420,24 +5624,38 @@ class ExecutorV1 {
5420
5624
  return;
5421
5625
  }
5422
5626
  if (owner.restartBusy) {
5423
- owner.pendingRestarts.push({ child, debts });
5627
+ owner.pendingRestarts.push({
5628
+ child,
5629
+ debts,
5630
+ incarnation: owner.children[child] ?? null,
5631
+ });
5424
5632
  return;
5425
5633
  }
5426
5634
  const now = this.trace.virtualTimeMs;
5427
- if (owner.backoff && debts.length > 0 && !delayElapsed) {
5635
+ const backoff = owner.backoffs[child];
5636
+ if (backoff && backoff.initial > 0n && debts.length > 0 && !delayElapsed) {
5428
5637
  const previous = owner.restartDelays.get(child);
5429
5638
  const healthy = previous?.publishedAt != null &&
5430
5639
  now - previous.publishedAt >= owner.layout.window_secs * 1000;
5431
- const doubled = previous ? previous.delay * 2n : owner.backoff.initial;
5640
+ const doubled = previous ? previous.delay * 2n : backoff.initial;
5432
5641
  const delay = !previous || healthy
5433
- ? owner.backoff.initial
5434
- : doubled < owner.backoff.maximum
5642
+ ? backoff.initial
5643
+ : doubled < backoff.maximum
5435
5644
  ? doubled
5436
- : owner.backoff.maximum;
5645
+ : backoff.maximum;
5437
5646
  owner.restartDelays.set(child, { delay, publishedAt: null });
5438
5647
  owner.recovering.add(child);
5439
5648
  owner.restartTimers.set(child, this.scheduler.after(delay, () => {
5440
5649
  owner.restartTimers.delete(child);
5650
+ // A group restart that already replaced this role recovered its
5651
+ // fault; restarting again would tear down a healthy group and
5652
+ // charge the budget twice.
5653
+ if (owner.restartDelays.get(child)?.publishedAt != null) {
5654
+ for (const debt of debts)
5655
+ this.faultDebts.delete(debt);
5656
+ this.wakeRoles();
5657
+ return;
5658
+ }
5441
5659
  this.restartChild(owner, child, debts, true);
5442
5660
  }));
5443
5661
  return;
@@ -5484,11 +5702,16 @@ class ExecutorV1 {
5484
5702
  if (index === undefined) {
5485
5703
  for (const debt of debts)
5486
5704
  this.faultDebts.delete(debt);
5487
- for (const pending of owner.pendingRestarts.filter((pending) => affected.includes(pending.child))) {
5705
+ // This group replaced a queued crash's incarnation, which recovers it.
5706
+ // A replacement that crashed after its own publication still needs
5707
+ // its restart.
5708
+ const replaced = (pending) => affected.includes(pending.child) &&
5709
+ owner.children[pending.child] !== pending.incarnation;
5710
+ for (const pending of owner.pendingRestarts.filter(replaced)) {
5488
5711
  for (const debt of pending.debts)
5489
5712
  this.faultDebts.delete(debt);
5490
5713
  }
5491
- owner.pendingRestarts = owner.pendingRestarts.filter((pending) => !affected.includes(pending.child));
5714
+ owner.pendingRestarts = owner.pendingRestarts.filter((pending) => !replaced(pending));
5492
5715
  owner.restartBusy = false;
5493
5716
  this.wakeRoles();
5494
5717
  const pending = owner.pendingRestarts.shift();
@@ -5500,6 +5723,12 @@ class ExecutorV1 {
5500
5723
  const delay = owner.restartDelays.get(index);
5501
5724
  if (delay)
5502
5725
  delay.publishedAt = this.trace.virtualTimeMs;
5726
+ // The crashed role's replacement is the recovery that settles its
5727
+ // fault, as natively; a later sibling's cancelled start does not
5728
+ // reopen it.
5729
+ if (index === child)
5730
+ for (const debt of debts)
5731
+ this.faultDebts.delete(debt);
5503
5732
  start();
5504
5733
  }, () => {
5505
5734
  owner.restartBusy = false;
@@ -5768,6 +5997,7 @@ class ExecutorV1 {
5768
5997
  });
5769
5998
  }
5770
5999
  haltWithFault(fault) {
6000
+ this.captureFault(this.current, fault);
5771
6001
  const isPanic = fault.kind === "panic";
5772
6002
  const status = isPanic ? "panic" : "trap";
5773
6003
  const trapKind = isPanic ? "panic" : fault.trap;
@@ -5784,6 +6014,25 @@ class ExecutorV1 {
5784
6014
  throw new Halt(status);
5785
6015
  }
5786
6016
  }
6017
+ /// Retain only bounded scratch space even when raw fault text or a compiler
6018
+ /// function name is much larger than the public diagnostic limit.
6019
+ function failureTextPrefix(text) {
6020
+ const bytes = new Uint8Array(FAILURE_TEXT_LIMIT);
6021
+ const { read, written } = new TextEncoder().encodeInto(text, bytes);
6022
+ return { bytes: bytes.subarray(0, written), complete: read === text.length };
6023
+ }
6024
+ /// Match the owned native snapshot without changing raw fault reporting.
6025
+ /// The suffix counts inside the UTF-8 limit and never splits a character.
6026
+ function boundedFailureMessage(message) {
6027
+ const { bytes, complete } = failureTextPrefix(message);
6028
+ if (complete)
6029
+ return message;
6030
+ let end = Math.min(bytes.length, FAILURE_TEXT_LIMIT -
6031
+ new TextEncoder().encode(FAILURE_TRUNCATED_SUFFIX).length);
6032
+ while ((bytes[end] & 0xc0) === 0x80)
6033
+ end--;
6034
+ return (new TextDecoder().decode(bytes.subarray(0, end)) + FAILURE_TRUNCATED_SUFFIX);
6035
+ }
5787
6036
  function combineFaults(primary, secondary) {
5788
6037
  if (!primary)
5789
6038
  return secondary;
@@ -5828,15 +6077,19 @@ function faultInfo(fault) {
5828
6077
  return [-2, "Deadline"];
5829
6078
  return [212, "UserPanic"];
5830
6079
  }
5831
- return {
5832
- integer_overflow: [201, "IntegerOverflow"],
5833
- divide_by_zero: [202, "DivideByZero"],
5834
- shift_out_of_range: [204, "ShiftOutOfRange"],
5835
- vector_bounds: [205, "IndexOutOfBounds"],
5836
- actor_refused: [-4, "Refused"],
5837
- heap_exceeded: [200, "HeapExceeded"],
5838
- }[fault.trap];
6080
+ return TRAP_FAULTS[fault.trap];
5839
6081
  }
6082
+ /// The native exit reason each package trap reports, as code and name.
6083
+ const TRAP_FAULTS = {
6084
+ integer_overflow: [201, "IntegerOverflow"],
6085
+ divide_by_zero: [202, "DivideByZero"],
6086
+ signed_min_div_neg_one: [203, "SignedMinDivNegOne"],
6087
+ shift_out_of_range: [204, "ShiftOutOfRange"],
6088
+ vector_bounds: [205, "IndexOutOfBounds"],
6089
+ actor_refused: [-4, "Refused"],
6090
+ heap_exceeded: [200, "HeapExceeded"],
6091
+ stack_overflow: [215, "StackOverflow"],
6092
+ };
5840
6093
  function faultApplicationMessage(fault) {
5841
6094
  return fault.kind === "panic" &&
5842
6095
  (fault.cancelled || fault.deadline || fault.timerOverdue)
@@ -6034,7 +6287,7 @@ function toComparable(value) {
6034
6287
  case "enum":
6035
6288
  return [value.tag, value.payload.map(toComparable)];
6036
6289
  case "vector":
6037
- return value.items.map(toComparable);
6290
+ return vectorItems(value).map(toComparable);
6038
6291
  case "rc":
6039
6292
  return "Rc";
6040
6293
  case "weak":
@@ -6074,6 +6327,8 @@ function trapMessage(trap) {
6074
6327
  return "integer overflow";
6075
6328
  case "divide_by_zero":
6076
6329
  return "divide by zero";
6330
+ case "signed_min_div_neg_one":
6331
+ return "signed minimum divided by -1";
6077
6332
  case "shift_out_of_range":
6078
6333
  return "shift amount out of range";
6079
6334
  case "vector_bounds":
@@ -6082,6 +6337,8 @@ function trapMessage(trap) {
6082
6337
  return "delivery refused by interceptor";
6083
6338
  case "heap_exceeded":
6084
6339
  return "actor heap limit exceeded";
6340
+ case "stack_overflow":
6341
+ return "stack overflow";
6085
6342
  }
6086
6343
  }
6087
6344
  /// The operand type the package records. `isize` and `usize` are 64-bit in the
@@ -6131,8 +6388,16 @@ function checkedFailure(op, lhs, rhs, ty) {
6131
6388
  return null;
6132
6389
  }
6133
6390
  const scalar = intTy(ty);
6134
- if ((op === "Divide" || op === "Modulo") && rhs.value === 0n) {
6135
- return "divide_by_zero";
6391
+ if (op === "Divide" || op === "Modulo") {
6392
+ if (rhs.value === 0n)
6393
+ return "divide_by_zero";
6394
+ // Both the quotient and the remainder of the signed minimum by -1 trap,
6395
+ // although the remainder alone would be representable.
6396
+ if (scalar.signed &&
6397
+ rhs.value === -1n &&
6398
+ lhs.value === -(1n << (scalar.bits - 1n))) {
6399
+ return "signed_min_div_neg_one";
6400
+ }
6136
6401
  }
6137
6402
  if ((op === "Shl" || op === "Shr") &&
6138
6403
  (rhs.value < 0n || rhs.value >= scalar.bits)) {
@@ -6316,8 +6581,8 @@ function equals(lhs, rhs) {
6316
6581
  lhs.payload.every((field, at) => equals(field, rhs.payload[at])));
6317
6582
  }
6318
6583
  if (lhs.kind === "vector" && rhs.kind === "vector") {
6319
- return (lhs.items.length === rhs.items.length &&
6320
- lhs.items.every((item, at) => equals(item, rhs.items[at])));
6584
+ return (vectorLength(lhs) === vectorLength(rhs) &&
6585
+ vectorItems(lhs).every((item, at) => equals(item, vectorElement(rhs, at))));
6321
6586
  }
6322
6587
  return canonical(lhs) === canonical(rhs);
6323
6588
  }