Repository navigation
Expand file tree
/
Copy pathLoaderHostTest.cpp
More file actions
903 lines (864 loc) · 35.8 KB
/
Copy pathLoaderHostTest.cpp
File metadata and controls
903 lines (864 loc) · 35.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
// The graph walk, file jobs, streamed compiles and loader::Quiesce against
// real V8: synchronous and asynchronous loads of file and HTTP graphs,
// parking, invalidation, termination, and teardown of runtimes mid-walk on
// several threads sharing the compile pool.
//
// Usage: LoaderHostTest [scenario,...|all] [stress threads] [stress rounds]
// [V8 flags] [code cache dir]
// "all" leaves out s11.
#include <spawn.h>
#include <sys/wait.h>
#include <v8.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <random>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#include "FakePlatform.h"
#include "V8Host.h"
#include "ns/RuntimeLiveness.h"
#include "ns/V8Helpers.h"
#include "ns/http/ModuleFetch.h"
#include "ns/loader/CodeCacheQueue.h"
#include "ns/loader/GraphLoad.h"
#include "ns/loader/LoaderState.h"
#include "ns/loader/ModuleImport.h"
#include "ns/loader/ModuleRegistry.h"
extern char** environ;
using namespace nativescript::common;
using v8host::Clock;
using v8host::DestroyRuntime;
using v8host::HostLoop;
using v8host::HostRuntime;
using v8host::NewRuntime;
namespace {
std::atomic<int> g_resolverMisses{0};
char* g_self = nullptr;
// The core's resolver, counting each module the walk did not leave
// registered (or finished on the pool) for it.
v8::MaybeLocal<v8::Module> CountingResolve(v8::Local<v8::Context> context,
v8::Local<v8::String> specifier,
v8::Local<v8::FixedArray> attributes,
v8::Local<v8::Module> referrer) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
const loader::ModuleResolution resolution = loader::ResolveModuleSpecifier(
isolate, ToString(isolate, specifier),
loader::FindKeyForModule(isolate, referrer));
if (resolution.kind == loader::ModuleResolution::Kind::kHttp) {
const std::string key = http::CanonicalizeNormalizedHttpUrlKey(
resolution.url, loader::CanonicalizationConfigFor(isolate));
if (!loader::IsModuleRegistered(isolate, key)) {
g_resolverMisses++;
}
} else if (resolution.kind == loader::ModuleResolution::Kind::kFile &&
!loader::IsModuleRegistered(isolate, resolution.key) &&
loader::FinalizeFinishedFileModule(isolate, context,
resolution.key)
.IsEmpty()) {
g_resolverMisses++;
}
return loader::ResolveModuleCallback(context, specifier, attributes,
referrer);
}
// ── Module graphs ───────────────────────────────────────────────────────────
struct GraphSpec {
std::string prefix; // "/app/g1/"
int modules = 0;
std::vector<std::string> paths;
};
std::string Padding(size_t bytes, bool ascii) {
std::string out;
out.reserve(bytes + 64);
const char* line =
ascii ? "// padding padding padding padding padding padding\n"
: "// p\xC3\xA4"
"dding p\xC3\xA4"
"dding p\xC3\xA4"
"dding "
"p\xC3\xA4"
"dding\n";
while (out.size() < bytes) {
out += line;
// Real functions too, so a compile has something to do.
out += "function f" + std::to_string(out.size()) +
"(a,b){ let s = 0; for (let i = 0; i < a; i++) { s += i * b; } "
"return s; }\n";
}
return out;
}
// A DAG: module i imports up to three later modules. `http` gives the edge
// specifiers as absolute URLs. Returns each module's source.
std::vector<std::string> BuildSources(int n, uint32_t seed,
const std::string& base,
double largeShare) {
std::mt19937 rng(seed);
std::vector<std::string> sources;
for (int i = 0; i < n; i++) {
std::string src;
std::string sum = std::to_string(i);
for (int k = 0; k < 3; k++) {
if (i + 1 >= n) {
break;
}
const int j = i + 1 + static_cast<int>(rng() % std::min(8, n - i - 1));
src += "import { v as v" + std::to_string(k) + " } from \"" + base + "m" +
std::to_string(j) + ".mjs\";\n";
sum += " + v" + std::to_string(k);
}
src += "export const v = " + sum + ";\n";
const double roll = (rng() % 1000) / 1000.0;
if (roll < largeShare) {
const size_t size = (rng() % 4 == 0) ? 300 * 1024 + rng() % 65536
: 33 * 1024 + rng() % 65536;
src += Padding(size, rng() % 3 != 0);
} else {
src += Padding(rng() % 2048, true);
}
sources.push_back(std::move(src));
}
return sources;
}
GraphSpec InstallFileGraph(const std::string& prefix, int n, uint32_t seed,
double largeShare) {
GraphSpec spec;
spec.prefix = prefix;
spec.modules = n;
std::vector<std::string> sources = BuildSources(n, seed, "./", largeShare);
for (int i = 0; i < n; i++) {
const std::string path = prefix + "m" + std::to_string(i) + ".mjs";
fake_platform::SetFile(path, std::move(sources[i]),
"t" + std::to_string(seed));
spec.paths.push_back(path);
}
return spec;
}
bool InstantiateAndEvaluate(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& key) {
v8::TryCatch tc(isolate);
v8::Local<v8::Module> root = loader::FindRegisteredModule(isolate, key);
if (root.IsEmpty()) {
std::fprintf(stderr, "root %s not registered\n", key.c_str());
return false;
}
if (!root->InstantiateModule(context, CountingResolve).FromMaybe(false)) {
if (tc.HasCaught()) {
std::fprintf(stderr, "instantiate: %s\n",
ToString(isolate, tc.Exception()).c_str());
}
return false;
}
v8::Local<v8::Value> result;
if (!root->Evaluate(context).ToLocal(&result)) {
return false;
}
isolate->PerformMicrotaskCheckpoint();
if (root->GetStatus() != v8::Module::kEvaluated) {
if (root->GetStatus() == v8::Module::kErrored) {
std::fprintf(stderr, "evaluate: %s\n",
ToString(isolate, root->GetException()).c_str());
}
return false;
}
return true;
}
// ── Scenarios ───────────────────────────────────────────────────────────────
// S1: a synchronous pumped load of a file graph, then evaluation; then a
// second isolate that finds fresh code caches.
void ScenarioSyncFileGraph() {
const GraphSpec graph = InstallFileGraph("/app/s1/", 60, 11, 0.4);
for (int pass = 0; pass < 3; pass++) {
const int missesBefore = g_resolverMisses.load();
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
const auto t0 = Clock::now();
const bool ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(graph.paths[0]), 20);
std::printf(
"S1 pumped load took %.1f ms\n",
std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
V8HOST_CHECK(ok, "S1 pumped load completed");
V8HOST_CHECK(loader::RegisteredModuleCount(rt->isolate) > 0,
"S1 registered modules");
V8HOST_CHECK(InstantiateAndEvaluate(rt->isolate, context, graph.paths[0]),
"S1 evaluated");
V8HOST_CHECK(g_resolverMisses.load() == missesBefore,
"S1 the walk registered every edge");
std::printf("S1 pass %d: registered=%zu misses=%d\n", pass,
loader::RegisteredModuleCount(rt->isolate),
g_resolverMisses.load() - missesBefore);
// Flush code caches through the token, as a backgrounding app would.
std::shared_ptr<RuntimeLiveness> token = loader::LivenessFor(rt->isolate);
V8HOST_CHECK(token != nullptr, "S1 token");
if (token) {
loader::NotifyAppBackgrounded(token);
}
for (int i = 0; i < 20; i++) {
rt->loop->Turn();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
DestroyRuntime(std::move(rt));
// Let the cache writer thread finish before the next pass looks.
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
}
struct HttpGraph {
std::string origin;
std::vector<std::string> sources;
};
std::mutex g_httpMutex;
std::vector<HttpGraph> g_httpGraphs;
std::atomic<int> g_httpDelayMs{0};
void InstallHttpResponder() {
fake_platform::Transport().Reset();
fake_platform::Transport().schedulesItself = true;
fake_platform::Transport().SetResponder(
[](const http::AttemptRequest& request) {
const int delay = g_httpDelayMs.load();
if (delay > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
}
std::lock_guard<std::mutex> lock(g_httpMutex);
for (const HttpGraph& graph : g_httpGraphs) {
if (request.url.compare(0, graph.origin.size(), graph.origin) == 0) {
const std::string name = request.url.substr(graph.origin.size());
// "m<i>.mjs"
const int index = std::atoi(name.c_str() + 1);
if (index >= 0 && index < static_cast<int>(graph.sources.size())) {
return fake_platform::Ok(request.url, graph.sources[index]);
}
}
}
http::AttemptOutcome missing;
missing.arrived = true;
missing.status = 404;
missing.finalUrl = request.url;
return missing;
});
}
std::string InstallHttpGraph(const std::string& origin, int n, uint32_t seed,
double largeShare) {
HttpGraph graph;
graph.origin = origin;
graph.sources = BuildSources(n, seed, origin, largeShare);
std::lock_guard<std::mutex> lock(g_httpMutex);
g_httpGraphs.push_back(std::move(graph));
return origin + "m0.mjs";
}
// S3: a pumped load of an HTTP graph with large bodies (streamed compiles).
void ScenarioSyncHttpGraph() {
const std::string rootUrl =
InstallHttpGraph("http://localhost:9000/s3/", 40, 31, 0.5);
const auto before = loader::GetStreamedCompileStats();
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
const int missesBefore = g_resolverMisses.load();
const auto t0 = Clock::now();
const bool ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(rootUrl), 20);
std::printf(
"S3 pumped load took %.1f ms\n",
std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
V8HOST_CHECK(ok, "S3 pumped load completed");
const std::string key = http::CanonicalizeNormalizedHttpUrlKey(
rootUrl, loader::CanonicalizationConfigFor(rt->isolate));
V8HOST_CHECK(InstantiateAndEvaluate(rt->isolate, context, key),
"S3 evaluated");
V8HOST_CHECK(g_resolverMisses.load() == missesBefore,
"S3 the walk registered every edge");
const auto after = loader::GetStreamedCompileStats();
std::printf(
"S3: registered=%zu streamed finalized=%llu fellBack=%llu "
"discarded=%llu\n",
loader::RegisteredModuleCount(rt->isolate),
(unsigned long long)(after.finalized - before.finalized),
(unsigned long long)(after.fellBack - before.fellBack),
(unsigned long long)(after.discarded - before.discarded));
V8HOST_CHECK(after.finalized > before.finalized,
"S3 streamed compiles ran");
}
DestroyRuntime(std::move(rt));
}
// S2: teardown stress. Several "worker" threads each repeatedly start a walk
// over a mixed file + HTTP graph, pump for a random short time and tear the
// runtime down mid-walk. All share the compile pool.
void ScenarioTeardownStress(int threads, int rounds) {
const GraphSpec files = InstallFileGraph("/app/s2/", 80, 51, 0.6);
const std::string httpRoot =
InstallHttpGraph("http://localhost:9000/s2/", 30, 52, 0.6);
std::atomic<int> completed{0};
std::atomic<int> torn{0};
std::atomic<int64_t> maxTeardownUs{0};
std::atomic<int64_t> totalTeardownUs{0};
std::vector<std::thread> workers;
for (int t = 0; t < threads; t++) {
workers.emplace_back([&, t] {
std::mt19937 rng(1000 + t);
for (int round = 0; round < rounds; round++) {
std::unique_ptr<HostRuntime> rt = NewRuntime();
auto done = std::make_shared<std::atomic<int>>(0);
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
loader::StartModuleGraphLoad(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[rng() % 10]),
std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(httpRoot),
std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
const int mode = rng() % 5;
if (mode == 0) {
// tear down at once
} else if (mode == 4) {
// A synchronous load that gives up while its jobs are in flight.
loader::RunModuleGraphLoadPumped(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[10 + rng() % 10]),
0.0005 * (1 + rng() % 20));
} else if (mode == 1) {
const auto until =
Clock::now() + std::chrono::microseconds(rng() % 3000);
while (Clock::now() < until) {
rt->loop->Turn();
}
} else {
const auto until =
Clock::now() + std::chrono::microseconds(rng() % 40000);
while (Clock::now() < until && done->load() < 2) {
rt->loop->Turn();
rt->loop->WaitForWork(1);
}
}
if (done->load() == 2) {
completed++;
}
}
const auto t0 = Clock::now();
DestroyRuntime(std::move(rt));
const int64_t us =
std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() -
t0)
.count();
int64_t seen = maxTeardownUs.load();
while (us > seen && !maxTeardownUs.compare_exchange_weak(seen, us)) {
}
totalTeardownUs += us;
torn++;
}
});
}
for (std::thread& w : workers) {
w.join();
}
const auto stats = loader::GetStreamedCompileStats();
std::printf(
"S2: runtimes=%d walks-completed-both=%d teardownWaits=%llu "
"running=%lld pendingGraphWork=%d\n",
torn.load(), completed.load(), (unsigned long long)stats.teardownWaits,
(long long)stats.running, loader::HasPendingGraphWork() ? 1 : 0);
std::printf(
"S2: teardown (Quiesce + close + dispose) mean %.2f ms, max %.2f ms\n",
totalTeardownUs.load() / 1000.0 / std::max(1, torn.load()),
maxTeardownUs.load() / 1000.0);
}
// S4: termination while a pumped load waits on a slow fetch.
void ScenarioTerminateDuringPump() {
const std::string rootUrl =
InstallHttpGraph("http://localhost:9000/s4/", 6, 71, 0.5);
g_httpDelayMs = 300;
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
HostLoop* loop = rt->loop.get();
v8::Isolate* isolate = rt->isolate;
std::thread killer([loop, isolate] {
std::this_thread::sleep_for(std::chrono::milliseconds(40));
loop->RequestTermination();
isolate->TerminateExecution();
});
const auto start = Clock::now();
const bool ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(rootUrl), 20);
const double ms =
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
killer.join();
V8HOST_CHECK(!ok, "S4 a terminated pumped load reports false");
V8HOST_CHECK(ms < 250,
"S4 the wait ended at termination, not at the fetch");
std::printf("S4: returned %d after %.0f ms\n", ok ? 1 : 0, ms);
}
DestroyRuntime(std::move(rt));
g_httpDelayMs = 0;
V8HOST_CHECK(!loader::HasPendingGraphWork(),
"S4 a quiesced runtime's walks no longer count as pending");
// Let the slow fetch threads land on the closed token.
std::this_thread::sleep_for(std::chrono::milliseconds(700));
}
// S5: a walk started before a synchronous load parks inside it and resumes
// after it.
void ScenarioParkedWalk() {
const std::string slowRoot =
InstallHttpGraph("http://localhost:9000/s5a/", 5, 81, 0.5);
const GraphSpec files = InstallFileGraph("/app/s5/", 40, 82, 0.5);
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
auto asyncDone = std::make_shared<int>(0);
auto syncReturned = std::make_shared<bool>(false);
auto completedInsideSync = std::make_shared<bool>(false);
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(slowRoot),
std::nullopt,
[=](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) {
(*asyncDone)++;
if (!*syncReturned) {
*completedInsideSync = true;
}
});
{
loader::SyncModuleLoadScope outer(rt->isolate);
// Hold the synchronous section open long enough for the fetches to
// land in it.
const auto until = Clock::now() + std::chrono::milliseconds(150);
bool ok = false;
while (Clock::now() < until) {
ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[0]), 20);
// Pump the way a nested synchronous wait would.
rt->loop->PumpUntil(
DeadlineAfterSeconds(0.01), [] { return false; },
PumpMode::kNestableOnly, nullptr);
}
V8HOST_CHECK(ok, "S5 sync load completed");
}
*syncReturned = true;
V8HOST_CHECK(!*completedInsideSync,
"S5 the earlier walk did not complete inside the sync scope");
const auto until = Clock::now() + std::chrono::seconds(10);
while (*asyncDone == 0 && Clock::now() < until) {
rt->loop->Turn();
rt->loop->WaitForWork(2);
}
V8HOST_CHECK(*asyncDone == 1,
"S5 the parked walk resumed and completed once");
std::printf("S5: asyncDone=%d insideSync=%d\n", *asyncDone,
*completedInsideSync ? 1 : 0);
}
DestroyRuntime(std::move(rt));
}
// S6: modules invalidated while their file jobs are in flight.
void ScenarioSupersede() {
const GraphSpec files = InstallFileGraph("/app/s6/", 50, 91, 0.8);
for (int round = 0; round < 20; round++) {
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
auto done = std::make_shared<int>(0);
loader::StartModuleGraphLoad(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[0]), std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
for (int i = 0; i < 50; i += 1 + round % 3) {
loader::RemoveModuleFromRegistry(rt->isolate, files.paths[i]);
}
const auto until = Clock::now() + std::chrono::seconds(10);
while (*done == 0 && Clock::now() < until) {
rt->loop->Turn();
rt->loop->WaitForWork(1);
if (round % 2 == 0) {
loader::RemoveModuleFromRegistry(rt->isolate,
files.paths[(round * 7) % 50]);
}
}
V8HOST_CHECK(*done == 1,
"S6 a walk with superseded jobs still completes");
}
DestroyRuntime(std::move(rt));
}
std::printf("S6: done\n");
}
// S7: the resolver's finalize racing the pool: FinalizeFinishedFileModule is
// called for every key while the jobs run.
void ScenarioResolverRace() {
const GraphSpec files = InstallFileGraph("/app/s7/", 60, 101, 0.8);
int finalizedByResolver = 0;
for (int round = 0; round < 15; round++) {
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
auto done = std::make_shared<int>(0);
loader::StartModuleGraphLoad(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[0]), std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
// Without loop turns the walk cannot see past the modules whose jobs
// it has already started.
const auto until = Clock::now() + std::chrono::milliseconds(300);
while (*done == 0 && Clock::now() < until) {
for (const std::string& path : files.paths) {
v8::HandleScope inner(rt->isolate);
if (!loader::IsModuleRegistered(rt->isolate, path) &&
!loader::FinalizeFinishedFileModule(rt->isolate, context, path)
.IsEmpty()) {
finalizedByResolver++;
}
}
if (round % 3 == 0) {
rt->loop->Turn();
}
}
// The resolver took every result; the completions still have to land
// for the walk to go on.
const auto until2 = Clock::now() + std::chrono::seconds(10);
while (*done == 0 && Clock::now() < until2) {
rt->loop->Turn();
rt->loop->WaitForWork(1);
}
V8HOST_CHECK(*done == 1, "S7 walk completed");
V8HOST_CHECK(InstantiateAndEvaluate(rt->isolate, context, files.paths[0]),
"S7 evaluated");
}
DestroyRuntime(std::move(rt));
}
std::printf("S7: finalized by the resolver=%d\n", finalizedByResolver);
}
// S8: the runtime replaces its loop after the loader first used it. The
// next walk must abort the process (run in a child) rather than post its
// completions to a loop nobody runs.
void ScenarioReplacedLoopChild() {
const GraphSpec files = InstallFileGraph("/app/s8/", 4, 81, 0.5);
std::unique_ptr<HostRuntime> rt = NewRuntime();
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::FilePath(files.paths[0]),
std::nullopt,
[](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) {});
rt->loop->SetContext(nullptr);
rt->loop = std::make_shared<HostLoop>(rt->isolate);
rt->loop->SetContext(&rt->context);
loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::FilePath(files.paths[1]),
5);
std::printf("S8 child: the walk ran on a replaced loop\n");
std::exit(0);
}
// Runs this binary on `scenario` and checks that it aborts.
void ExpectChildAborts(const char* scenario, const char* what) {
std::string name = scenario;
char* args[] = {g_self, name.data(), nullptr};
pid_t pid = 0;
if (posix_spawn(&pid, g_self, nullptr, nullptr, args, environ) != 0) {
V8HOST_CHECK(false, what);
return;
}
int status = 0;
waitpid(pid, &status, 0);
V8HOST_CHECK(WIFSIGNALED(status) && WTERMSIG(status) == SIGABRT, what);
std::printf("%s: child %s %d\n", scenario,
WIFSIGNALED(status) ? "signal" : "exit",
WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));
}
void ScenarioReplacedLoop() {
ExpectChildAborts("s8-child", "S8 a walk after the loop was replaced aborts");
}
// S14: a runtime that closes its state bag without loader::Quiesce (a debug
// build aborts).
void ScenarioCloseWithoutQuiesceChild() {
std::unique_ptr<HostRuntime> rt = NewRuntime();
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
rt->bag.Close();
std::printf("S14 child: the bag closed without Quiesce\n");
std::exit(0);
}
void ScenarioCloseWithoutQuiesce() {
#ifndef NDEBUG
ExpectChildAborts("s14-child",
"S14 closing the state bag before Quiesce aborts");
#endif
}
// S13: synchronous loads off the loop's home thread (multithreaded
// JavaScript) never pump: one with a fetch outstanding gives up at once, one
// that completes inline reports success.
void ScenarioOffHomeThread() {
const std::string httpRoot =
InstallHttpGraph("http://localhost:9000/s13/", 4, 151, 0.5);
const GraphSpec files = InstallFileGraph("/app/s13/", 12, 152, 0.5);
g_httpDelayMs = 300;
std::unique_ptr<HostRuntime> rt = NewRuntime();
bool httpOk = true;
bool fileOk = false;
double httpMs = 0;
std::thread other([&] {
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
const auto start = Clock::now();
httpOk = loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(httpRoot), 20);
httpMs =
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
fileOk = loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::FilePath(files.paths[0]),
20);
});
other.join();
V8HOST_CHECK(!httpOk && httpMs < 200,
"S13 off the home thread a pending fetch is not waited for");
V8HOST_CHECK(fileOk, "S13 off the home thread an inline walk completes");
std::printf("S13: http %d after %.0f ms, file %d\n", httpOk ? 1 : 0, httpMs,
fileOk ? 1 : 0);
DestroyRuntime(std::move(rt));
g_httpDelayMs = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
// S9: file jobs land while the runtime has no main context: the walks waiting
// on them still complete, and the resolver finalizes what they left.
void ScenarioNoMainContext() {
const GraphSpec files = InstallFileGraph("/app/s9/", 30, 91, 0.8);
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
v8host::mainContextEmpty = true;
auto done = std::make_shared<int>(0);
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::FilePath(files.paths[0]),
std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
const auto until = Clock::now() + std::chrono::seconds(10);
while (*done == 0 && Clock::now() < until) {
rt->loop->Turn();
rt->loop->WaitForWork(1);
}
v8host::mainContextEmpty = false;
V8HOST_CHECK(*done == 1, "S9 the walk completed without a main context");
// A later walk over the same modules finds the results left with their
// jobs.
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::FilePath(files.paths[0]),
std::nullopt,
[done](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*done)++; });
const auto until2 = Clock::now() + std::chrono::seconds(10);
while (*done == 1 && Clock::now() < until2) {
rt->loop->Turn();
rt->loop->WaitForWork(1);
}
V8HOST_CHECK(*done == 2, "S9 a later walk completed");
V8HOST_CHECK(InstantiateAndEvaluate(rt->isolate, context, files.paths[0]),
"S9 evaluated");
}
DestroyRuntime(std::move(rt));
std::printf("S9: done\n");
}
// S11: background compiles under a small heap, with an isolate thread that
// does not pump: a compile that needs a GC parks until the drain serves it.
void ScenarioGcDuringDrain(int rounds) {
const GraphSpec files = InstallFileGraph("/app/s11/", 160, 131, 1.0);
for (int round = 0; round < rounds; round++) {
std::unique_ptr<HostRuntime> rt = NewRuntime();
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
// Fill the heap first: the later half of the graph, loaded and kept.
const bool ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[80 + round % 3]), 20);
V8HOST_CHECK(ok, "S11 pumped load completed under GC pressure");
// One walk per module not loaded yet: without a pump a walk only ever
// dispatches its root's job.
for (int i = 0; i < 80; i++) {
loader::StartModuleGraphLoad(
rt->isolate, context,
loader::ModuleGraphRoot::FilePath(files.paths[i]), std::nullopt,
[](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) {});
}
// Busy elsewhere: no loop turn before teardown.
std::this_thread::sleep_for(std::chrono::milliseconds(150));
std::printf("S11 before the drain: pool compiles still running=%lld\n",
(long long)loader::GetStreamedCompileStats().running);
}
std::printf("S11 drain begin\n");
std::fflush(stdout);
const auto start = Clock::now();
DestroyRuntime(std::move(rt));
std::fflush(stdout);
const double ms =
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
std::printf("S11 round %d: teardown %.0f ms\n", round, ms);
}
}
// S12: termination while an earlier walk is parked inside a synchronous load.
void ScenarioTerminateWhileParked() {
const std::string earlier =
InstallHttpGraph("http://localhost:9000/s12a/", 6, 141, 0.5);
const std::string slow =
InstallHttpGraph("http://localhost:9000/s12b/", 6, 142, 0.5);
for (int round = 0; round < 6; round++) {
std::unique_ptr<HostRuntime> rt = NewRuntime();
auto asyncDone = std::make_shared<int>(0);
{
v8::Locker locker(rt->isolate);
v8::Isolate::Scope isolateScope(rt->isolate);
v8::HandleScope handleScope(rt->isolate);
v8::Local<v8::Context> context = rt->context.Get(rt->isolate);
v8::Context::Scope contextScope(context);
g_httpDelayMs = 0;
loader::StartModuleGraphLoad(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(earlier),
std::nullopt,
[asyncDone](bool, const std::string&, v8::Local<v8::Value>,
v8::Local<v8::Context>) { (*asyncDone)++; });
// The synchronous load's own fetches are slow, so the earlier walk's
// land (and park) inside it; then the isolate is terminated.
g_httpDelayMs = 200;
HostLoop* loop = rt->loop.get();
v8::Isolate* isolate = rt->isolate;
std::thread killer([loop, isolate, round] {
std::this_thread::sleep_for(std::chrono::milliseconds(30 + 10 * round));
loop->RequestTermination();
isolate->TerminateExecution();
});
const auto start = Clock::now();
const bool ok = loader::RunModuleGraphLoadPumped(
rt->isolate, context, loader::ModuleGraphRoot::HttpUrl(slow), 20);
const double ms =
std::chrono::duration<double, std::milli>(Clock::now() - start)
.count();
killer.join();
g_httpDelayMs = 0;
V8HOST_CHECK(!ok, "S12 terminated load reports false");
V8HOST_CHECK(ms < 150, "S12 the wait ended at termination");
V8HOST_CHECK(*asyncDone == 0,
"S12 the parked walk did not complete inside");
}
DestroyRuntime(std::move(rt));
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::printf("S12: done, pendingGraphWork=%d\n",
loader::HasPendingGraphWork() ? 1 : 0);
}
bool Selected(const std::string& which, std::string_view scenario, bool inAll) {
if (which == "all") {
return inAll;
}
std::string_view rest = which;
for (;;) {
const size_t comma = rest.find(',');
if (rest.substr(0, comma) == scenario) {
return true;
}
if (comma == std::string_view::npos) {
return false;
}
rest.remove_prefix(comma + 1);
}
}
} // namespace
int main(int argc, char** argv) {
g_self = argv[0];
const std::string which = argc > 1 ? argv[1] : "all";
const int stressThreads = argc > 2 ? std::atoi(argv[2]) : 3;
const int stressRounds = argc > 3 ? std::atoi(argv[3]) : 40;
const std::string flags = argc > 4 ? argv[4] : "--jitless";
const std::string cacheDir = argc > 5 ? argv[5] : "";
v8host::InitializeV8(flags);
LoaderConfig& config = fake_platform::MutableLoaderConfig();
config.appRoot = "/app";
config.codeCacheEnabled = !cacheDir.empty();
config.codeCacheDir = cacheDir;
config.v8Flags = flags;
http::HttpLoaderConfig httpConfig;
httpConfig.isDebug = true;
fake_platform::SetConfig(httpConfig);
InstallHttpResponder();
if (Selected(which, "s1", true)) ScenarioSyncFileGraph();
if (Selected(which, "s3", true)) ScenarioSyncHttpGraph();
if (Selected(which, "s5", true)) ScenarioParkedWalk();
if (Selected(which, "s6", true)) ScenarioSupersede();
if (Selected(which, "s7", true)) ScenarioResolverRace();
if (Selected(which, "s8", true)) ScenarioReplacedLoop();
if (Selected(which, "s8-child", false)) ScenarioReplacedLoopChild();
if (Selected(which, "s9", true)) ScenarioNoMainContext();
if (Selected(which, "s13", true)) ScenarioOffHomeThread();
if (Selected(which, "s14", true)) ScenarioCloseWithoutQuiesce();
if (Selected(which, "s14-child", false)) ScenarioCloseWithoutQuiesceChild();
if (Selected(which, "s11", false)) ScenarioGcDuringDrain(stressRounds);
if (Selected(which, "s12", true)) ScenarioTerminateWhileParked();
if (Selected(which, "s4", true)) ScenarioTerminateDuringPump();
if (Selected(which, "s2", true)) {
ScenarioTeardownStress(stressThreads, stressRounds);
}
// Detached fetch threads of torn-down runtimes still hold walks.
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::printf("loopDestroyedOffThread=%d tasksDroppedOffThread=%d\n",
v8host::loopDestroyedOffThread.load(),
v8host::tasksDroppedOffThread.load());
V8HOST_CHECK(!loader::HasPendingGraphWork(),
"every runtime is gone, and no walk counts as pending");
return v8host::Finish();
}