Repository navigation
Expand file tree
/
Copy pathCompilePoolTest.cpp
More file actions
452 lines (424 loc) · 14.1 KB
/
Copy pathCompilePoolTest.cpp
File metadata and controls
452 lines (424 loc) · 14.1 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
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <memory>
#include <mutex>
#include <random>
#include <thread>
#include <vector>
#include "FakePlatform.h"
#include "loader/CompilePool.h"
#include "ns/RuntimeLiveness.h"
// RuntimeLiveness::Post needs a Loop, which needs V8; it is Enter, a post to
// the loop and Leave, and the V8-free part is what these tests cover.
using namespace nativescript::common;
using loader::CompilePool;
using loader::FileJobSignal;
namespace {
int failures = 0;
void Check(bool ok, const char* what) {
if (!ok) {
failures++;
std::fprintf(stderr, "FAIL %s\n", what);
}
}
constexpr size_t kStack = 2 * 1024 * 1024;
// Never destroyed, like CompilePool::Shared(): its threads wait on it forever.
CompilePool& NewPool(unsigned threads) { return *new CompilePool(threads); }
// Opened once; every Wait returns after that.
class Latch {
public:
// Notifies under the lock, so a waiter that then destroys the latch cannot
// do it while this call still uses it.
void Open() {
std::lock_guard<std::mutex> lock(mutex_);
open_ = true;
cv_.notify_all();
}
bool Wait(std::chrono::milliseconds timeout = std::chrono::seconds(10)) {
std::unique_lock<std::mutex> lock(mutex_);
return cv_.wait_for(lock, timeout, [this] { return open_; });
}
private:
std::mutex mutex_;
std::condition_variable cv_;
bool open_ = false;
};
void TestLivenessSections() {
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
Check(liveness->IsAlive(), "a new token is alive");
Check(liveness->Enter(), "enter while alive");
liveness->Leave();
int serviced = 0;
Check(!liveness->CloseAndDrain([&] { serviced++; }),
"nothing to wait for without a section");
Check(serviced == 0, "no service without a section");
Check(!liveness->IsAlive(), "closed");
Check(!liveness->Enter(), "no section after closing");
Check(!liveness->CloseAndDrain(nullptr), "closing again is harmless");
}
void TestLivenessWaitsForSections() {
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
Latch entered;
Latch release;
std::atomic<bool> left{false};
Check(liveness->Enter(), "enter");
std::thread worker([&] {
entered.Open();
release.Wait();
left = true;
liveness->Leave();
});
entered.Wait();
int serviced = 0;
const bool waited = liveness->CloseAndDrain([&] {
// The service runs before the first wait and between waits; the
// section ends only once it has run a few times.
if (++serviced == 3) {
release.Open();
}
});
worker.join();
Check(waited, "drain reports the section it waited for");
Check(left.load(), "drain returned only after the section left");
Check(serviced >= 3, "service ran between waits");
}
void TestPoolRunsEveryJobOnce() {
CompilePool& pool = NewPool(2);
constexpr int kJobs = 50;
std::atomic<int> runs{0};
std::atomic<int> discards{0};
std::mutex mutex;
std::condition_variable cv;
int done = 0;
const int runJobsBefore = fake_platform::runJobCalls.load();
int owner = 0;
for (int i = 0; i < kJobs; i++) {
Check(pool.Post(&owner, kStack,
[&](bool run) {
(run ? runs : discards)++;
std::lock_guard<std::mutex> lock(mutex);
done++;
cv.notify_all();
}),
"post");
}
std::unique_lock<std::mutex> lock(mutex);
Check(cv.wait_for(lock, std::chrono::seconds(10),
[&] { return done == kJobs; }),
"every job finished");
lock.unlock();
Check(runs.load() == kJobs, "every job ran");
Check(discards.load() == 0, "none discarded");
Check(fake_platform::runJobCalls.load() - runJobsBefore == kJobs,
"each job through platform::RunJob");
}
void TestPoolDiscardsOneOwner() {
CompilePool& pool = NewPool(1);
int ownerA = 0;
int ownerB = 0;
Latch blockerRunning;
Latch releaseBlocker;
Check(pool.Post(&ownerB, kStack,
[&](bool) {
blockerRunning.Open();
releaseBlocker.Wait();
}),
"post blocker");
blockerRunning.Wait();
std::atomic<int> aRuns{0};
std::atomic<int> aDiscards{0};
std::thread::id discardThread;
Latch bRan;
std::atomic<bool> bRun{false};
for (int i = 0; i < 3; i++) {
pool.Post(&ownerA, kStack, [&](bool run) {
if (run) {
aRuns++;
} else {
aDiscards++;
discardThread = std::this_thread::get_id();
}
});
}
pool.Post(&ownerB, kStack, [&](bool run) {
bRun = run;
bRan.Open();
});
pool.Discard(&ownerA);
Check(aDiscards.load() == 3, "every queued job of the owner discarded");
Check(discardThread == std::this_thread::get_id(),
"discarded on the calling thread");
releaseBlocker.Open();
Check(bRan.Wait(), "the other owner's job still runs");
Check(bRun.load(), "with run == true");
Check(aRuns.load() == 0, "a discarded job never runs");
}
// Quiesce's pattern: the drain's service discards the runtime's queued jobs,
// so a teardown never waits behind another isolate's compile.
void TestDrainDoesNotWaitForOtherOwners() {
CompilePool& pool = NewPool(1);
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
int other = 0;
Latch blockerRunning;
Latch releaseBlocker;
Latch blockerDone;
pool.Post(&other, kStack, [&](bool) {
blockerRunning.Open();
releaseBlocker.Wait();
blockerDone.Open();
});
blockerRunning.Wait();
std::atomic<int> ran{0};
std::atomic<int> discarded{0};
Check(liveness->Enter(), "section for the job");
Check(pool.Post(liveness.get(), kStack,
[&ran, &discarded, liveness](bool run) mutable {
if (run && liveness->IsAlive()) {
ran++;
} else if (!run) {
discarded++;
}
const std::shared_ptr<RuntimeLiveness> token =
std::move(liveness);
token->Leave();
}),
"post");
const auto start = std::chrono::steady_clock::now();
RuntimeLiveness* raw = liveness.get();
const bool waited =
liveness->CloseAndDrain([&pool, raw] { pool.Discard(raw); });
const auto elapsed = std::chrono::steady_clock::now() - start;
releaseBlocker.Open();
blockerDone.Wait();
Check(waited, "the queued job held a section");
Check(discarded.load() == 1 && ran.load() == 0, "discarded, not run");
Check(elapsed < std::chrono::seconds(2),
"the drain did not wait for the other owner's job");
}
// A job that runs after the token closed does no work and still leaves.
void TestJobAfterCloseSkipsWork() {
CompilePool& pool = NewPool(1);
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
Latch release;
Latch started;
std::atomic<int> work{0};
Check(liveness->Enter(), "section");
pool.Post(liveness.get(), kStack, [&, liveness](bool run) mutable {
started.Open();
release.Wait();
if (run && liveness->IsAlive()) {
work++;
}
const std::shared_ptr<RuntimeLiveness> token = std::move(liveness);
token->Leave();
});
started.Wait();
// The service runs only once the token is closed, so the job sees it
// closed whatever the scheduling.
Check(liveness->CloseAndDrain([&] { release.Open(); }),
"waited for the running job");
Check(work.load() == 0, "no work once closed");
}
// Enter before the close, Post after the drain's first Discard: the next
// service round discards the job, and the drain waits for it.
void TestPostAfterFirstDiscard() {
CompilePool& pool = NewPool(1);
int other = 0;
Latch blockerRunning;
Latch releaseBlocker;
Latch blockerDone;
pool.Post(&other, kStack, [&](bool) {
blockerRunning.Open();
releaseBlocker.Wait();
blockerDone.Open();
});
blockerRunning.Wait();
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
Check(liveness->Enter(), "section taken before the close");
RuntimeLiveness* raw = liveness.get();
Latch firstDiscardDone;
std::atomic<int> discards{0};
std::atomic<int> runs{0};
std::atomic<bool> drainReturned{false};
std::atomic<bool> leftBeforeDrainReturned{false};
std::thread drain([&] {
liveness->CloseAndDrain([&pool, raw, &firstDiscardDone] {
pool.Discard(raw);
firstDiscardDone.Open();
});
drainReturned = true;
});
firstDiscardDone.Wait();
Check(pool.Post(raw, kStack,
[&, token = liveness](bool run) mutable {
(run ? runs : discards)++;
leftBeforeDrainReturned = !drainReturned.load();
const std::shared_ptr<RuntimeLiveness> moved =
std::move(token);
moved->Leave();
}),
"late post");
drain.join();
releaseBlocker.Open();
blockerDone.Wait();
Check(discards.load() == 1 && runs.load() == 0,
"the late job was discarded by a later round");
Check(leftBeforeDrainReturned.load(),
"the drain waited for the late job's section");
}
// A job the pool has taken off its queue but not yet run is out of
// Discard's reach: it runs with run == true, sees the token closed, and the
// drain waits for it.
void TestDiscardBetweenPopAndRun() {
CompilePool& pool = NewPool(1);
auto liveness =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
RuntimeLiveness* raw = liveness.get();
Latch popped;
Latch releasePopped;
fake_platform::SetRunJobHook([&] {
popped.Open();
releasePopped.Wait();
});
std::atomic<int> runs{0};
std::atomic<int> discards{0};
std::atomic<int> work{0};
Check(liveness->Enter(), "section");
Check(pool.Post(raw, kStack,
[&, token = liveness](bool run) mutable {
(run ? runs : discards)++;
if (run && token->IsAlive()) {
work++;
}
const std::shared_ptr<RuntimeLiveness> moved =
std::move(token);
moved->Leave();
}),
"post");
popped.Wait();
fake_platform::SetRunJobHook(nullptr);
int rounds = 0;
const bool waited = liveness->CloseAndDrain([&] {
pool.Discard(raw);
if (rounds++ == 0) {
releasePopped.Open();
}
});
Check(waited, "the drain waited for the popped job");
Check(runs.load() == 1 && discards.load() == 0,
"the popped job ran rather than being discarded");
Check(work.load() == 0, "and did no work on the closed token");
}
// Once CloseAndDrain returns, no thread is inside a section and none can
// enter: a transport thread hands sections to pool jobs and two more threads
// take short ones, while the isolate's thread closes the token at a random
// point.
void TestConcurrentCloseAndDrain() {
// Sized for a few seconds under TSan. An Enter that checks the token
// before taking its mutex shows hundreds of violations at this count.
#if defined(__has_feature)
#if __has_feature(thread_sanitizer) || __has_feature(address_sanitizer)
constexpr int kIterations = 5000;
#else
constexpr int kIterations = 20000;
#endif
#else
constexpr int kIterations = 20000;
#endif
CompilePool& pool = NewPool(3);
std::atomic<long> violations{0};
std::mt19937 rng(7);
for (int iteration = 0; iteration < kIterations; iteration++) {
auto token =
std::make_shared<RuntimeLiveness>(nullptr, std::weak_ptr<Loop>());
auto dead = std::make_shared<std::atomic<bool>>(false);
std::atomic<bool> stop{false};
std::vector<std::thread> threads;
for (int t = 0; t < 3; t++) {
threads.emplace_back([&, t] {
while (!stop.load(std::memory_order_relaxed)) {
if (!token->Enter()) {
continue;
}
if (t != 0) {
if (dead->load()) {
violations++;
}
token->Leave();
continue;
}
const bool posted = pool.Post(
token.get(), kStack,
[token = token, dead, &violations](bool) mutable {
if (dead->load()) {
violations++;
}
const std::shared_ptr<RuntimeLiveness> moved = std::move(token);
moved->Leave();
});
if (!posted) {
token->Leave();
}
}
});
}
for (volatile unsigned spin = rng() % 3000; spin > 0; spin = spin - 1) {
}
RuntimeLiveness* raw = token.get();
token->CloseAndDrain([&pool, raw] { pool.Discard(raw); });
dead->store(true);
stop = true;
for (std::thread& thread : threads) {
thread.join();
}
}
Check(violations.load() == 0,
"no section outlived the drain or started after it");
}
void TestFileJobSignal() {
FileJobSignal signal;
const uint64_t seen = signal.Generation();
const auto start = std::chrono::steady_clock::now();
signal.WaitForChange(seen, std::chrono::milliseconds(20));
Check(
std::chrono::steady_clock::now() - start >= std::chrono::milliseconds(15),
"times out without a change");
std::thread notifier([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
signal.Notify();
});
signal.WaitForChange(seen, std::chrono::seconds(10));
notifier.join();
Check(signal.Generation() == seen + 1, "a notify bumps the generation");
const auto again = std::chrono::steady_clock::now();
signal.WaitForChange(seen, std::chrono::seconds(10));
Check(
std::chrono::steady_clock::now() - again < std::chrono::milliseconds(500),
"a stale generation returns at once");
}
} // namespace
int main() {
TestLivenessSections();
TestLivenessWaitsForSections();
TestPoolRunsEveryJobOnce();
TestPoolDiscardsOneOwner();
TestDrainDoesNotWaitForOtherOwners();
TestJobAfterCloseSkipsWork();
TestPostAfterFirstDiscard();
TestDiscardBetweenPopAndRun();
TestConcurrentCloseAndDrain();
TestFileJobSignal();
if (failures > 0) {
std::fprintf(stderr, "%d failure(s)\n", failures);
return 1;
}
std::printf("all compile pool tests passed\n");
return 0;
}