mini_racer_rs 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,21 @@
1
1
  use std::borrow::Cow;
2
+ use std::cell::Cell;
2
3
  use std::collections::hash_map::RandomState;
3
4
  use std::hash::BuildHasher;
4
5
  use std::panic::{AssertUnwindSafe, catch_unwind};
5
- use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
6
+ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
6
7
  use std::sync::{Arc, Mutex};
7
- use std::time::Duration;
8
+ use std::time::{Duration, Instant};
8
9
 
9
10
  use mini_racer_sourcemap::{Frame, Match, Placement, SourceMap};
10
11
  use mini_racer_sync::{
11
- DispatchId, DispatchKind, Halt, Interrupt, Phase, Side, TerminationCause, ToV8, lock,
12
+ DispatchId, DispatchKind, Halt, Interrupt, Phase, Side, TermCell, TerminationCause, ToV8, lock,
12
13
  };
13
14
  use mini_racer_wire::Writer;
14
15
  use v8::ValueDeserializerHelper;
15
16
 
16
17
  use crate::control::{
17
- CallRequest, CallbackReply, ControlBlock, Depth, IsolateTerminator, JsText, Request,
18
+ CallRequest, CallbackReply, ControlBlock, Depth, HeapWatch, IsolateTerminator, JsText, Request,
18
19
  };
19
20
  use crate::fast_calls::{self, Hoisted, Shape};
20
21
  use crate::process::code_cache::{Building, Key, Plan};
@@ -74,6 +75,58 @@ struct Runtime {
74
75
  frames: Mutex<Vec<v8::Global<v8::Array>>>,
75
76
  // Scripts that hold a bundle with a source map, latest last.
76
77
  matched: Mutex<Vec<Matched>>,
78
+ // When the runner's current stretch of JavaScript began, in nanoseconds
79
+ // after `clock`, or `STOPPED`; only the runner touches it.
80
+ clock: Instant,
81
+ since: AtomicU64,
82
+ }
83
+
84
+ const STOPPED: u64 = u64::MAX;
85
+
86
+ // Times the runner's JavaScript: started for a request that runs scripts,
87
+ // and paused while a callback waits for Ruby, an await sleeps until a task is
88
+ // due or a script waits out a fork. Each restores what it found, so a request
89
+ // nested in a callback is timed inside the pause.
90
+ struct Timing<'a> {
91
+ runtime: &'a Runtime,
92
+ was_running: bool,
93
+ }
94
+
95
+ impl Drop for Timing<'_> {
96
+ fn drop(&mut self) {
97
+ self.runtime.switch(self.was_running);
98
+ }
99
+ }
100
+
101
+ // The collections V8 runs on a runner's isolate. Kept apart from the
102
+ // runtime, which needs the isolate's contexts, so a collection while they
103
+ // are made counts too.
104
+ struct Collections {
105
+ block: Arc<ControlBlock>,
106
+ began: Cell<Option<Instant>>,
107
+ }
108
+
109
+ impl Collections {
110
+ fn new(block: &Arc<ControlBlock>) -> Self {
111
+ Self {
112
+ block: Arc::clone(block),
113
+ began: Cell::new(None),
114
+ }
115
+ }
116
+ }
117
+
118
+ pub fn collection_began(isolate: &v8::Isolate) {
119
+ if let Some(collections) = isolate.get_slot::<Collections>() {
120
+ collections.began.set(Some(Instant::now()));
121
+ }
122
+ }
123
+
124
+ pub fn collection_ended(isolate: &v8::Isolate) {
125
+ if let Some(collections) = isolate.get_slot::<Collections>()
126
+ && let Some(began) = collections.began.take()
127
+ {
128
+ collections.block.counters.collected(began.elapsed());
129
+ }
77
130
  }
78
131
 
79
132
  #[derive(Clone)]
@@ -168,6 +221,30 @@ impl Runtime {
168
221
  hoisting: Mutex::default(),
169
222
  frames: Mutex::default(),
170
223
  matched: Mutex::default(),
224
+ clock: Instant::now(),
225
+ since: AtomicU64::new(STOPPED),
226
+ }
227
+ }
228
+
229
+ // Charges the stretch running so far, if one is, and starts or stops the
230
+ // next; returns whether one was running. A load and a store, as only the
231
+ // runner writes either.
232
+ fn switch(&self, run: bool) -> bool {
233
+ let now = u64::try_from(self.clock.elapsed().as_nanos()).unwrap_or(STOPPED - 1);
234
+ let since = self.since.load(Ordering::Relaxed);
235
+ self.since
236
+ .store(if run { now } else { STOPPED }, Ordering::Relaxed);
237
+ if since == STOPPED {
238
+ return false;
239
+ }
240
+ self.block.counters.ran_js(now.saturating_sub(since));
241
+ true
242
+ }
243
+
244
+ fn timing(&self, run: bool) -> Timing<'_> {
245
+ Timing {
246
+ runtime: self,
247
+ was_running: self.switch(run),
171
248
  }
172
249
  }
173
250
  }
@@ -197,7 +274,12 @@ pub fn run(block: &Arc<ControlBlock>, generation: &'static Generation, start: St
197
274
  Start::Adopted => {
198
275
  let isolate = lock(&block.custody).take();
199
276
  isolate.map_or_else(
200
- || refuse(block, "no isolate to take over"),
277
+ || {
278
+ refuse(
279
+ block,
280
+ EngineError::Internal("no isolate to take over".to_owned()),
281
+ )
282
+ },
201
283
  |isolate| adopt(block, generation, isolate),
202
284
  )
203
285
  }
@@ -234,19 +316,128 @@ pub fn check_heap(isolate: &mut v8::Isolate) {
234
316
  }
235
317
  }
236
318
 
319
+ const EXHAUSTED: Option<Halt> = Some(Halt::Terminated(TerminationCause::HeapExhausted));
320
+
321
+ // A hit lends V8 room up to three times the old generation's limit, all at
322
+ // once: V8 asks at most a few times per allocation, around its last-resort
323
+ // collection, then retries the allocation once and aborts, so room lent a
324
+ // share at a time ran out under one allocation, such as the backing store a
325
+ // growing `Map` doubles into. Past that V8 aborts the process as it would
326
+ // without a limit.
327
+ const CEILING: usize = 3;
328
+
329
+ // V8 is about to abort the process at the heap limit: the running script is
330
+ // ended as out of memory, and V8 is lent room to unwind it. With no dispatch
331
+ // armed, which the termination cell checks, or the runner collecting on its
332
+ // own, no script is running, and `recover` settles the heap once the runner
333
+ // is done.
334
+ pub fn near_heap_limit(block: &ControlBlock, current: usize, initial: usize) -> usize {
335
+ let watch = &block.heap;
336
+ watch.old_generation.store(initial, Ordering::Relaxed);
337
+ watch.hit.store(true, Ordering::Relaxed);
338
+ if !watch.collecting.load(Ordering::Relaxed) {
339
+ block.term.request(Interrupt::HeapExhausted);
340
+ }
341
+ initial.saturating_mul(CEILING).max(current)
342
+ }
343
+
344
+ // After a hit, a full collection, then the old generation's limit back to the
345
+ // one the heap limit set if the live heap fits under it. V8 puts a limit back
346
+ // no lower than the live size and a quarter, so a heap that does not fit, or
347
+ // a limit V8 did not put back, poisons the context instead of leaving it
348
+ // above the heap limit. A script terminated with the heap that full gets the
349
+ // collection too: V8 otherwise calls the callback in the next script, which
350
+ // would end it though its own heap is small.
351
+ fn recover(isolate: &mut v8::Isolate, block: &ControlBlock) {
352
+ if block.config.heap_limit.is_none() {
353
+ return;
354
+ }
355
+ let watch = &block.heap;
356
+ let ended = watch.ended.swap(false, Ordering::Relaxed);
357
+ if block.term.is_disposing() || watch.poisoned.load(Ordering::Relaxed) {
358
+ watch.hit.store(false, Ordering::Relaxed);
359
+ return;
360
+ }
361
+ let crowded = ended && !fits(isolate, watch);
362
+ if !crowded && !watch.hit.load(Ordering::Relaxed) {
363
+ return;
364
+ }
365
+ collect(isolate, block);
366
+ if !watch.hit.swap(false, Ordering::Relaxed) {
367
+ return;
368
+ }
369
+ let fits = fits(isolate, watch);
370
+ if fits {
371
+ let limit = watch.old_generation.load(Ordering::Relaxed);
372
+ sys::unwatch_heap_limit(isolate, limit);
373
+ sys::watch_heap_limit(isolate, block);
374
+ }
375
+ let reserved = isolate.get_heap_statistics().heap_size_limit();
376
+ if !fits || reserved > watch.reserved.load(Ordering::Relaxed) {
377
+ watch.poisoned.store(true, Ordering::Relaxed);
378
+ }
379
+ }
380
+
381
+ // The generations of a heap of `limit` bytes, with the old one's size.
382
+ // `heap_limits` splits the limit, but V8 15.2's `Heap::ConfigureHeap` rounds
383
+ // a third of the young generation, a semi-space, up to a power of two, which
384
+ // can reserve a tenth more than the limit; rounded down here instead, the
385
+ // heap V8 reserves is the limit, less its rounding of the old generation
386
+ // down to a page. `heap_limits` also sets a code range of the limit's size,
387
+ // which V8 aborts on unless it is a multiple of the allocation page, so the
388
+ // code range is left at V8's own size, as for a context without a limit.
389
+ fn sized(params: v8::CreateParams, limit: usize) -> (v8::CreateParams, usize) {
390
+ let params = params.heap_limits(0, limit);
391
+ let semi_space = (params.max_young_generation_size_in_bytes() / 3)
392
+ .checked_ilog2()
393
+ .map_or(0, |log| 1_usize << log);
394
+ let young_generation = semi_space.saturating_mul(3);
395
+ let old_generation = limit.saturating_sub(young_generation);
396
+ let params = params
397
+ .set_max_young_generation_size_in_bytes(young_generation)
398
+ .set_max_old_generation_size_in_bytes(old_generation)
399
+ .set_code_range_size_in_bytes(0);
400
+ (params, old_generation)
401
+ }
402
+
403
+ // Whether V8 would put the old generation's limit back where it started: no
404
+ // lower than the live heap and a quarter.
405
+ fn fits(isolate: &mut v8::Isolate, watch: &HeapWatch) -> bool {
406
+ let used = isolate.get_heap_statistics().used_heap_size();
407
+ used.saturating_add(used / 4) <= watch.old_generation.load(Ordering::Relaxed)
408
+ }
409
+
410
+ // A full collection the runner asks for itself, with no script to end if the
411
+ // heap is at its limit.
412
+ fn collect(isolate: &mut v8::Isolate, block: &ControlBlock) {
413
+ block.heap.collecting.store(true, Ordering::Relaxed);
414
+ isolate.low_memory_notification();
415
+ block.heap.collecting.store(false, Ordering::Relaxed);
416
+ }
417
+
418
+ // A context whose heap stayed over its limit runs no more JavaScript.
419
+ fn unpoisoned(runtime: &Runtime) -> Result<(), EngineError> {
420
+ let block = &runtime.block;
421
+ match block.config.heap_limit {
422
+ Some(limit) if block.heap.poisoned.load(Ordering::Relaxed) => {
423
+ Err(EngineError::from(JsError::heap_limit_exceeded(limit)))
424
+ }
425
+ _ => Ok(()),
426
+ }
427
+ }
428
+
237
429
  pub fn park_for_fork(isolate: &v8::Isolate) {
238
430
  if let Some(runtime) = isolate.get_slot::<Arc<Runtime>>() {
431
+ let _paused = runtime.timing(false);
239
432
  runtime.generation.pause(&runtime.block);
240
433
  }
241
434
  }
242
435
 
243
- fn refuse(block: &ControlBlock, message: &str) -> bool {
436
+ fn refuse(block: &ControlBlock, error: EngineError) -> bool {
244
437
  // Holding no isolate, it never keeps a fork waiting.
245
438
  block.phase.set(Phase::Deposited);
246
439
  if receive(block).is_some() {
247
- let _ = block
248
- .channel
249
- .respond(Err(EngineError::Internal(message.to_owned())));
440
+ let _ = block.channel.respond(Err(error));
250
441
  }
251
442
  false
252
443
  }
@@ -263,19 +454,49 @@ fn serve(block: &Arc<ControlBlock>, generation: &'static Generation) -> bool {
263
454
  Some(blob) => params.snapshot_blob(sys::startup_data(blob)),
264
455
  None => params,
265
456
  };
457
+ let params = match block.config.heap_limit {
458
+ Some(limit) => {
459
+ let (params, old_generation) = sized(params, limit);
460
+ block
461
+ .heap
462
+ .old_generation
463
+ .store(old_generation, Ordering::Relaxed);
464
+ params
465
+ }
466
+ None => params,
467
+ };
266
468
  let mut isolate = v8::Isolate::new(params);
469
+ isolate.set_slot(Collections::new(block));
470
+ sys::count_collections(&mut isolate);
267
471
  if block.config.max_memory.is_some() {
268
472
  sys::watch_heap(&mut isolate);
269
473
  }
474
+ let reserved = block
475
+ .config
476
+ .heap_limit
477
+ .map(|_| isolate.get_heap_statistics().heap_size_limit());
478
+ if let Some(reserved) = reserved {
479
+ block.heap.reserved.store(reserved, Ordering::Relaxed);
480
+ sys::watch_heap_limit(&mut isolate, block);
481
+ }
270
482
  let key = sys::isolate_key(&isolate);
271
483
  generation.tasks().register(key, &block.tasks);
484
+ // V8 reads its own flags, so this catches any that sized the heap past
485
+ // the limit, whatever `platform::read_sizing` made of them.
486
+ if reserved > block.config.heap_limit {
487
+ retire(block, generation, key, isolate);
488
+ return refuse(block, EngineError::HeapLimitOverridden);
489
+ }
272
490
  let contexts = {
273
491
  v8::scope!(let scope, &mut isolate);
274
492
  serialize::contexts(scope, from_snapshot)
275
493
  };
276
494
  let Some(contexts) = contexts else {
277
495
  retire(block, generation, key, isolate);
278
- return refuse(block, "context setup failed");
496
+ return refuse(
497
+ block,
498
+ EngineError::Internal("context setup failed".to_owned()),
499
+ );
279
500
  };
280
501
  let runtime = Arc::new(Runtime::new(
281
502
  block,
@@ -292,7 +513,10 @@ fn serve(block: &Arc<ControlBlock>, generation: &'static Generation) -> bool {
292
513
  Ok(shared) => shared,
293
514
  Err(refused) => {
294
515
  retire(block, generation, key, refused);
295
- return refuse(block, "isolate could not be shared");
516
+ return refuse(
517
+ block,
518
+ EngineError::Internal("isolate could not be shared".to_owned()),
519
+ );
296
520
  }
297
521
  };
298
522
  let _ = block.isolate.set(shared.thread_safe_handle());
@@ -312,7 +536,10 @@ fn adopt(
312
536
  // Disposed here, before the runner counts as idle to a fork.
313
537
  drop(block.tasks.close());
314
538
  drop(shared);
315
- return refuse(block, "inherited isolate has no context");
539
+ return refuse(
540
+ block,
541
+ EngineError::Internal("inherited isolate has no context".to_owned()),
542
+ );
316
543
  };
317
544
  let runtime = {
318
545
  let mut locker = shared.lock();
@@ -328,7 +555,16 @@ fn adopt(
328
555
  if let Ok(matched) = inherited.matched.try_lock() {
329
556
  lock(&runtime.matched).clone_from(&matched);
330
557
  }
558
+ // V8's callback still names the parent's block, whose termination
559
+ // cell no runner here serves.
560
+ if block.config.heap_limit.is_some() {
561
+ block.heap.inherit(&inherited.block.heap);
562
+ sys::unwatch_heap_limit(&mut locker, 0);
563
+ sys::watch_heap_limit(&mut locker, block);
564
+ }
331
565
  locker.set_slot(Arc::clone(&runtime));
566
+ // The parent's callbacks stay registered and now count here.
567
+ locker.set_slot(Collections::new(block));
332
568
  runtime
333
569
  };
334
570
  block
@@ -393,7 +629,8 @@ fn serve_held(block: &ControlBlock, shared: &v8::SharedIsolate, runtime: &Arc<Ru
393
629
  // A collection for a context about to be torn down is wasted.
394
630
  Received::Idle => {
395
631
  if !block.term.is_disposing() {
396
- isolate.low_memory_notification();
632
+ collect(&mut isolate, block);
633
+ recover(&mut isolate, block);
397
634
  sys::release_free_memory();
398
635
  }
399
636
  collected = true;
@@ -465,7 +702,7 @@ fn serve_one(
465
702
  block
466
703
  .term
467
704
  .end(dispatch)
468
- .map_or(built, |halt| Err(halted(halt)))
705
+ .map_or(built, |halt| Err(halted(block, halt)))
469
706
  }
470
707
  Depth::Nested => Err(EngineError::Internal(
471
708
  "snapshot inside a callback".to_owned(),
@@ -488,6 +725,7 @@ fn serve_one(
488
725
  };
489
726
  // Before the response, so a fork that follows finds this runner idle.
490
727
  cache_uncached(isolate, runtime);
728
+ recover(isolate, block);
491
729
  let served = respond(block, response);
492
730
  // After the response, so the caller does not wait for it.
493
731
  if matches!(served, Served::Next) && runtime.freed.swap(false, Ordering::Relaxed) {
@@ -568,6 +806,7 @@ fn handle(
568
806
  runtime: &Runtime,
569
807
  request: Request,
570
808
  ) -> Result<Vec<u8>, EngineError> {
809
+ let _timing = request.runs_script().then(|| runtime.timing(true));
571
810
  match request {
572
811
  Request::Init { depth } => match depth {
573
812
  Depth::Outermost(dispatch) => ended(runtime, dispatch),
@@ -588,25 +827,35 @@ fn handle(
588
827
  source,
589
828
  depth,
590
829
  awaited,
591
- } => script(scope, runtime, depth, DispatchKind::Script, |tc| {
592
- evaluate(tc, runtime, (&filename, &source), (depth, awaited))
593
- }),
830
+ timeout,
831
+ } => {
832
+ let timed = Timed::Script(runtime.block.config.timeout_within(timeout));
833
+ script(scope, runtime, depth, timed, |tc| {
834
+ unpoisoned(runtime)?;
835
+ evaluate(tc, runtime, (&filename, &source), (depth, awaited))
836
+ })
837
+ }
594
838
  Request::Call {
595
839
  request,
596
840
  depth,
597
841
  awaited,
598
- } => script(scope, runtime, depth, DispatchKind::Script, |tc| {
599
- invoke(tc, runtime, &request, (depth, awaited))
600
- }),
842
+ timeout,
843
+ } => {
844
+ let timed = Timed::Script(runtime.block.config.timeout_within(timeout));
845
+ script(scope, runtime, depth, timed, |tc| {
846
+ unpoisoned(runtime)?;
847
+ invoke(tc, runtime, &request, (depth, awaited))
848
+ })
849
+ }
601
850
  Request::Attach { request, depth } => {
602
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
851
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
603
852
  attach(tc, &request)
604
853
  })
605
854
  }
606
855
  // A collection for a context about to be torn down is wasted.
607
856
  Request::LowMemoryNotification { depth } => {
608
857
  if !runtime.block.term.is_disposing() {
609
- scope.low_memory_notification();
858
+ collect(scope, &runtime.block);
610
859
  runtime.freed.store(true, Ordering::Relaxed);
611
860
  }
612
861
  match depth {
@@ -617,26 +866,38 @@ fn handle(
617
866
  // mini_racer leaves a termination this meets for the dispatch around
618
867
  // it, or for the next script.
619
868
  Request::MicrotaskCheckpoint { depth } => {
620
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
869
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
870
+ unpoisoned(runtime)?;
621
871
  tc.perform_microtask_checkpoint();
872
+ // Maintenance reports no cause, and an exhausted heap leaves
873
+ // none for the next script, so the checkpoint raises it.
874
+ if tc.has_terminated()
875
+ && runtime.block.term.check(DispatchKind::Script) == EXHAUSTED
876
+ {
877
+ return Err(halted(
878
+ &runtime.block,
879
+ Halt::Terminated(TerminationCause::HeapExhausted),
880
+ ));
881
+ }
622
882
  Ok(Vec::new())
623
883
  })
624
884
  }
625
- Request::HeapStats { depth } => {
626
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
627
- Ok(heap_stats(tc))
628
- })
629
- }
885
+ Request::HeapStats { depth } => script(scope, runtime, depth, Timed::Maintenance, |tc| {
886
+ Ok(heap_stats(tc))
887
+ }),
630
888
  Request::HeapSnapshot { depth } => {
631
- script(scope, runtime, depth, DispatchKind::Maintenance, |tc| {
632
- Ok(heap_snapshot(tc))
633
- })
634
- }
635
- Request::PumpMessageLoop { depth } => {
636
- script(scope, runtime, depth, DispatchKind::Pump, |tc| {
637
- Ok(vec![u8::from(pump(tc, runtime))])
889
+ script(scope, runtime, depth, Timed::Maintenance, |tc| {
890
+ let heap = &runtime.block.heap;
891
+ heap.collecting.store(true, Ordering::Relaxed);
892
+ let json = heap_snapshot(tc);
893
+ heap.collecting.store(false, Ordering::Relaxed);
894
+ Ok(json)
638
895
  })
639
896
  }
897
+ Request::PumpMessageLoop { depth } => script(scope, runtime, depth, Timed::Pump, |tc| {
898
+ unpoisoned(runtime)?;
899
+ Ok(vec![u8::from(pump(tc, runtime))])
900
+ }),
640
901
  // The extension refuses a dispose from inside a callback before it
641
902
  // gets here.
642
903
  Request::Dispose => Err(EngineError::DisposeBusy),
@@ -655,9 +916,12 @@ fn ended(runtime: &Runtime, dispatch: DispatchId) -> Result<Vec<u8>, EngineError
655
916
  }
656
917
  }
657
918
 
658
- fn halted(halt: Halt) -> EngineError {
919
+ fn halted(block: &ControlBlock, halt: Halt) -> EngineError {
659
920
  match halt {
660
- Halt::Terminated(cause) => EngineError::from(JsError::terminated(cause)),
921
+ Halt::Terminated(cause) => EngineError::from(match (cause, block.config.heap_limit) {
922
+ (TerminationCause::HeapExhausted, Some(limit)) => JsError::heap_limit_reached(limit),
923
+ _ => JsError::terminated(cause),
924
+ }),
661
925
  // mini_racer cancels the wait of a dispatch a dispose catches in
662
926
  // flight, which raises its disposed error.
663
927
  Halt::Disposed => EngineError::Disposed,
@@ -675,19 +939,23 @@ fn script(
675
939
  scope: &mut v8::PinScope<'_, '_>,
676
940
  runtime: &Runtime,
677
941
  depth: Depth,
678
- kind: DispatchKind,
942
+ timed: Timed,
679
943
  run: impl FnOnce(&mut Tc<'_, '_, '_, '_>) -> Result<Vec<u8>, EngineError>,
680
944
  ) -> Result<Vec<u8>, EngineError> {
681
945
  let term = &runtime.block.term;
946
+ let kind = timed.kind();
682
947
  v8::tc_scope!(let tc, scope);
683
948
  tc.set_verbose(runtime.block.config.verbose_exceptions);
684
- let result = if let Err(error) = arm_timeout(runtime, depth, kind) {
949
+ let result = if let Err(error) = arm_timeout(runtime, depth, timed) {
685
950
  Err(error)
686
951
  } else if term.refuses(kind) {
687
952
  Err(EngineError::Internal("halted without a cause".to_owned()))
688
953
  } else {
689
954
  run(tc)
690
955
  };
956
+ if tc.has_terminated() && runtime.block.config.heap_limit.is_some() {
957
+ runtime.block.heap.ended.store(true, Ordering::Relaxed);
958
+ }
691
959
  let since = term.mark();
692
960
  // mini_racer's maintenance never cancels a termination it meets, so the
693
961
  // interrupt is used up while the cause waits for the next script. Inside
@@ -714,13 +982,22 @@ fn script(
714
982
  // the timeout bounds them again here.
715
983
  Depth::Outermost(dispatch) if kind == DispatchKind::Script && tc.has_terminated() => {
716
984
  let verdict = term.settle(dispatch);
717
- let drains = verdict.is_some_and(|halt| halt != Halt::Disposed)
718
- && rearm_timeout(runtime, dispatch).is_ok();
985
+ let exhausted = verdict == EXHAUSTED;
986
+ if exhausted {
987
+ discard_microtasks(tc, term);
988
+ }
989
+ let drains = !exhausted
990
+ && verdict.is_some_and(|halt| halt != Halt::Disposed)
991
+ && rearm_timeout(runtime, dispatch, timed).is_ok();
719
992
  if drains {
720
993
  tc.reset();
721
994
  tc.perform_microtask_checkpoint();
722
995
  }
723
- if drains && (tc.has_terminated() || tc.is_execution_terminating()) {
996
+ // The microtasks it left reached the heap limit, which outranks
997
+ // every other cause: this script reports it, and nothing carries.
998
+ if drains && term.check(DispatchKind::Script) == EXHAUSTED {
999
+ term.end(dispatch)
1000
+ } else if drains && (tc.has_terminated() || tc.is_execution_terminating()) {
724
1001
  term.spend(term.mark(), false);
725
1002
  match term.finish(dispatch) {
726
1003
  Some(Halt::Disposed) => Some(Halt::Disposed),
@@ -755,26 +1032,56 @@ fn script(
755
1032
  message: String::new(),
756
1033
  }));
757
1034
  }
758
- halt.map_or(result, |halt| Err(halted(halt)))
1035
+ halt.map_or(result, |halt| Err(halted(&runtime.block, halt)))
1036
+ }
1037
+
1038
+ // The microtasks a script left as it reached the heap limit would allocate
1039
+ // again. V8 empties the queue when a termination reaches it there, so they
1040
+ // are dropped rather than run, now or with the next script.
1041
+ fn discard_microtasks(tc: &mut Tc<'_, '_, '_, '_>, term: &TermCell<IsolateTerminator>) {
1042
+ tc.reset();
1043
+ term.interrupt();
1044
+ tc.perform_microtask_checkpoint();
1045
+ term.release();
1046
+ tc.reset();
1047
+ }
1048
+
1049
+ // A dispatch's kind, and for a script the timeout it runs under.
1050
+ #[derive(Clone, Copy)]
1051
+ enum Timed {
1052
+ Script(Option<Duration>),
1053
+ Maintenance,
1054
+ Pump,
1055
+ }
1056
+
1057
+ impl Timed {
1058
+ const fn kind(self) -> DispatchKind {
1059
+ match self {
1060
+ Self::Script(_) => DispatchKind::Script,
1061
+ Self::Maintenance => DispatchKind::Maintenance,
1062
+ Self::Pump => DispatchKind::Pump,
1063
+ }
1064
+ }
759
1065
  }
760
1066
 
761
1067
  // mini_racer starts a script's watchdog on its V8 thread as it takes the
762
1068
  // request, so time spent waiting for the runner, such as behind a collection
763
1069
  // after `ensure_gc_after_idle`, never counts against the timeout. Setup and
764
1070
  // maintenance are never timed.
765
- fn arm_timeout(runtime: &Runtime, depth: Depth, kind: DispatchKind) -> Result<(), EngineError> {
766
- match (depth, kind, runtime.block.config.timeout) {
767
- (Depth::Outermost(dispatch), DispatchKind::Script, Some(timeout)) => {
1071
+ fn arm_timeout(runtime: &Runtime, depth: Depth, timed: Timed) -> Result<(), EngineError> {
1072
+ match (depth, timed) {
1073
+ (Depth::Outermost(dispatch), Timed::Script(Some(timeout))) => {
768
1074
  watchdog::schedule(timeout, &runtime.block, dispatch)
769
1075
  }
770
1076
  _ => Ok(()),
771
1077
  }
772
1078
  }
773
1079
 
774
- fn rearm_timeout(runtime: &Runtime, dispatch: DispatchId) -> Result<(), EngineError> {
775
- runtime.block.config.timeout.map_or(Ok(()), |timeout| {
776
- watchdog::rearm_if_fired(timeout, &runtime.block, dispatch)
777
- })
1080
+ fn rearm_timeout(runtime: &Runtime, dispatch: DispatchId, timed: Timed) -> Result<(), EngineError> {
1081
+ match timed {
1082
+ Timed::Script(Some(timeout)) => watchdog::rearm_if_fired(timeout, &runtime.block, dispatch),
1083
+ _ => Ok(()),
1084
+ }
778
1085
  }
779
1086
 
780
1087
  fn escaped(tc: &Tc<'_, '_, '_, '_>, runtime: &Runtime) -> bool {
@@ -1229,7 +1536,7 @@ fn verdict(runtime: &Runtime, depth: Depth) -> Result<(), EngineError> {
1229
1536
  Depth::Outermost(dispatch) => term.settle(dispatch),
1230
1537
  Depth::Nested => term.check(DispatchKind::Script),
1231
1538
  };
1232
- halt.map_or(Ok(()), |halt| Err(halted(halt)))
1539
+ halt.map_or(Ok(()), |halt| Err(halted(&runtime.block, halt)))
1233
1540
  }
1234
1541
 
1235
1542
  // V8 runs no microtask checkpoint inside another, so an await nested in a
@@ -1252,7 +1559,7 @@ fn refuse_nested_await(
1252
1559
  if matches!(halt, Some(Halt::Terminated(_))) {
1253
1560
  runtime.block.term.renew();
1254
1561
  }
1255
- let halt = halt.map(halted);
1562
+ let halt = halt.map(|halt| halted(&runtime.block, halt));
1256
1563
  Err(match (halt, refused) {
1257
1564
  (Some(EngineError::Js(halt)), EngineError::Js(refused)) => EngineError::from(JsError {
1258
1565
  kind: halt.kind,
@@ -1301,6 +1608,7 @@ fn await_promise<'s>(
1301
1608
  // Waiting, the runner holds its isolate but runs nothing in it, so a fork need
1302
1609
  // not wait for it.
1303
1610
  fn wait_for_task(runtime: &Runtime) {
1611
+ let _paused = runtime.timing(false);
1304
1612
  runtime.block.phase.set(Phase::Parked);
1305
1613
  runtime.block.tasks.wait();
1306
1614
  runtime.generation.resume(&runtime.block);
@@ -1570,6 +1878,7 @@ fn callback<'s>(
1570
1878
  let Some(bytes) = serialize::write(scope, request.into()) else {
1571
1879
  return;
1572
1880
  };
1881
+ let waiting = runtime.timing(false);
1573
1882
  if runtime.block.channel.callback(bytes).is_err() {
1574
1883
  terminate(scope, runtime);
1575
1884
  return;
@@ -1599,6 +1908,7 @@ fn callback<'s>(
1599
1908
  return;
1600
1909
  }
1601
1910
  };
1911
+ drop(waiting);
1602
1912
  // A nested dispatch that was halted leaves its termination to unwind
1603
1913
  // this script too, as mini_racer restores it.
1604
1914
  let terminating = scope.is_execution_terminating();