CIRCT 24.0.0git
Loading...
Searching...
No Matches
ESIRuntimeWriteAsyncTest.cpp
Go to the documentation of this file.
1//===- ESIRuntimeWriteAsyncTest.cpp - WriteChannelPort callback mode -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "esi/Accelerator.h"
10#include "esi/Ports.h"
11#include "esi/TypedPorts.h"
12#include "gtest/gtest.h"
13
14#include <algorithm>
15#include <any>
16#include <atomic>
17#include <chrono>
18#include <deque>
19#include <functional>
20#include <future>
21#include <map>
22#include <mutex>
23#include <stdexcept>
24#include <thread>
25#include <vector>
26
27using namespace esi;
28
29namespace {
30
31/// A WriteChannelPort which records accepted messages. tryWriteImpl() can be
32/// made to backpressure or throw.
33class RecordingWritePort : public WriteChannelPort {
34public:
35 using WriteChannelPort::WriteChannelPort;
36
37 std::vector<std::vector<uint8_t>> written() {
38 std::lock_guard<std::mutex> lock(mutex);
39 return writtenMsgs;
40 }
41
42 /// Reject (backpressure) this many tryWriteImpl() calls before accepting.
43 std::atomic<int> rejectCount = 0;
44 /// Reject all tryWriteImpl() calls.
45 std::atomic<bool> rejectAll = false;
46 /// Accept this many tryWriteImpl() calls, then throw on the next one.
47 std::atomic<int> throwAfter = -1;
48 /// If non-negative, accept this many more tryWriteImpl() calls, then reject.
49 std::atomic<int> acceptBudget = -1;
50 /// Reject every other tryWriteImpl() call.
51 std::atomic<bool> alternate = false;
52 /// Number of pollWriteImpl() calls.
53 std::atomic<int> pollImplCount = 0;
54
55protected:
56 void writeImpl(const MessageData &data) override {
57 while (!tryWriteImpl(data))
58 std::this_thread::yield();
59 }
60 bool tryWriteImpl(const MessageData &data) override {
61 if (rejectAll || acceptBudget == 0 || (alternate && calls++ % 2))
62 return false;
63 if (acceptBudget > 0)
64 --acceptBudget;
65 if (rejectCount > 0) {
66 --rejectCount;
67 return false;
68 }
69 if (throwAfter >= 0 && throwAfter-- == 0)
70 throw std::out_of_range("injected failure");
71 std::lock_guard<std::mutex> lock(mutex);
72 writtenMsgs.push_back(data.getData());
73 return true;
74 }
75 bool pollWriteImpl() override {
76 ++pollImplCount;
77 return false;
78 }
79
80private:
81 std::atomic<unsigned> calls = 0;
82 std::mutex mutex;
83 std::vector<std::vector<uint8_t>> writtenMsgs;
84};
85
86/// A data source for callback mode: a queue of messages which the port fetches
87/// from, plus a record of the errors reported for them.
88struct Source {
89 std::mutex mutex;
90 std::deque<std::unique_ptr<SegmentedMessageData>> queue;
91 std::vector<std::exception_ptr> errors;
92 size_t fetches = 0;
93 /// Optional extra behavior, invoked at the start of each fetch with its
94 /// index, and with each error's index.
95 std::function<void(size_t)> onFetch, onError;
96
97 void push(std::vector<uint8_t> bytes) {
98 std::lock_guard<std::mutex> lock(mutex);
99 queue.push_back(std::make_unique<MessageData>(std::move(bytes)));
100 }
101 void push(std::unique_ptr<SegmentedMessageData> msg) {
102 std::lock_guard<std::mutex> lock(mutex);
103 queue.push_back(std::move(msg));
104 }
105
107 return [this]() -> std::unique_ptr<SegmentedMessageData> {
108 size_t idx;
109 {
110 std::lock_guard<std::mutex> lock(mutex);
111 idx = fetches++;
112 }
113 if (onFetch)
114 onFetch(idx);
115 std::lock_guard<std::mutex> lock(mutex);
116 if (queue.empty())
117 return nullptr;
118 std::unique_ptr<SegmentedMessageData> msg = std::move(queue.front());
119 queue.pop_front();
120 return msg;
121 };
122 }
124 return [this](std::exception_ptr e) {
125 size_t idx;
126 {
127 std::lock_guard<std::mutex> lock(mutex);
128 idx = errors.size();
129 errors.push_back(e);
130 }
131 if (onError)
132 onError(idx);
133 };
134 }
135
136 size_t numFetches() {
137 std::lock_guard<std::mutex> lock(mutex);
138 return fetches;
139 }
140 size_t numErrors() {
141 std::lock_guard<std::mutex> lock(mutex);
142 return errors.size();
143 }
144 std::exception_ptr operator[](size_t idx) {
145 std::lock_guard<std::mutex> lock(mutex);
146 return errors.at(idx);
147 }
148 size_t queued() {
149 std::lock_guard<std::mutex> lock(mutex);
150 return queue.size();
151 }
152};
153
154/// A two-segment message.
155struct TwoSegmentMessage : public SegmentedMessageData {
156 std::vector<uint8_t> header = {1, 2};
157 std::vector<uint8_t> body = {3, 4, 5};
158 size_t numSegments() const override { return 2; }
159 Segment segment(size_t idx) const override {
160 const std::vector<uint8_t> &seg = idx == 0 ? header : body;
161 return {seg.data(), seg.size()};
162 }
163};
164
165std::unique_ptr<SegmentedMessageData> makeMsg(std::vector<uint8_t> bytes) {
166 return std::make_unique<MessageData>(std::move(bytes));
167}
168
169using Frames = std::vector<std::vector<uint8_t>>;
170
171/// Rethrow `error` and return its message, checking that it is of type `E`.
172template <typename E>
173std::string errorMessage(std::exception_ptr error) {
174 EXPECT_TRUE(error);
175 if (!error)
176 return "";
177 try {
178 std::rethrow_exception(error);
179 } catch (const E &e) {
180 return e.what();
181 } catch (...) {
182 ADD_FAILURE() << "unexpected exception type";
183 }
184 return "";
185}
186
187/// A two-frame window over a struct of two ui16s.
188struct TwoFrameWindow {
189 UIntType ui16{"ui16", 16};
190 StructType into{"into", {{"a", &ui16}, {"b", &ui16}}, /*reverse=*/false};
191 BitsType lowered{"lowered", 16};
192 WindowType window{
193 "window", "window", &into, &lowered, {{"f0", {{"a"}}}, {"f1", {{"b"}}}}};
194};
195
196/// A three-frame window over a struct of three ui16s.
197struct ThreeFrameWindow {
198 UIntType ui16{"ui16", 16};
199 StructType into{"into",
200 {{"a", &ui16}, {"b", &ui16}, {"c", &ui16}},
201 /*reverse=*/false};
202 BitsType lowered{"lowered", 16};
203 WindowType window{"window",
204 "window",
205 &into,
206 &lowered,
207 {{"f0", {{"a"}}}, {"f1", {{"b"}}}, {"f2", {{"c"}}}}};
208};
209
210/// Feed the frames a write port produced into a translating read port of the
211/// same type, as the receiving end of the channel would, and return the
212/// messages it assembles.
213std::vector<std::vector<uint8_t>>
214receive(const Type *type, const std::vector<std::vector<uint8_t>> &frames) {
215 struct LoopbackReadPort : public ReadChannelPort {
217 void deliver(const std::vector<uint8_t> &frame) {
218 std::unique_ptr<SegmentedMessageData> msg =
219 std::make_unique<MessageData>(frame);
220 EXPECT_TRUE(invokeCallback(msg));
221 }
222 };
223 std::vector<std::vector<uint8_t>> received;
224 LoopbackReadPort reader(type);
225 reader.connect(ReadChannelPort::ReadCallback(
226 [&](std::unique_ptr<SegmentedMessageData> &msg) {
227 received.push_back(msg->toMessageData().getData());
228 return true;
229 }),
230 ChannelPort::ConnectOptions(std::nullopt, true));
231 for (const auto &frame : frames)
232 reader.deliver(frame);
233 reader.disconnect();
234 return received;
235}
236
237TEST(WriteCallbackModeTest, NotifyWritesImmediately) {
238 UIntType ui24("ui24", 24);
239 Source source;
240 RecordingWritePort port(&ui24);
241 port.connect(source.fetch(), source.error());
242
243 // The data is written on the calling thread before the notification returns,
244 // then the source is drained until it returns nullptr.
245 source.push({1, 2, 3});
246 source.push({4, 5, 6});
247 port.notifyAsyncDataAvailable();
248 EXPECT_EQ(port.written(), (Frames{{1, 2, 3}, {4, 5, 6}}));
249 EXPECT_EQ(source.numFetches(), 3u);
250
251 // After returning nullptr, the source isn't called again until notified.
252 source.push({7, 8, 9});
253 port.poll();
254 EXPECT_EQ(source.numFetches(), 3u);
255 EXPECT_EQ(port.pollImplCount, 1);
256 port.notifyAsyncDataAvailable();
257 EXPECT_EQ(port.written().size(), 3u);
258 EXPECT_EQ(source.numErrors(), 0u);
259}
260
261TEST(WriteCallbackModeTest, FirstPollFetches) {
262 UIntType ui8("ui8", 8);
263 Source source;
264 source.push({1});
265 RecordingWritePort port(&ui8);
266 port.connect(source.fetch(), source.error());
267 // Connecting doesn't call the source; the first poll() does.
268 EXPECT_EQ(source.numFetches(), 0u);
269 port.poll();
270 EXPECT_EQ(port.written(), (Frames{{1}}));
271}
272
273TEST(WriteCallbackModeTest, BackpressureHoldsOneMessage) {
274 UIntType ui8("ui8", 8);
275 Source source;
276 RecordingWritePort port(&ui8);
277 port.connect(source.fetch(), source.error());
278 for (uint8_t i = 0; i < 10; ++i)
279 source.push({i});
280
281 // Under backpressure, only one message is taken from the source.
282 port.rejectAll = true;
283 port.notifyAsyncDataAvailable();
284 port.notifyAsyncDataAvailable();
285 port.poll();
286 port.poll();
287 EXPECT_EQ(source.numFetches(), 1u);
288 EXPECT_EQ(source.queued(), 9u);
289 EXPECT_TRUE(port.written().empty());
290
291 // Once the backend accepts it, the rest are fetched and written in order.
292 port.rejectAll = false;
293 port.poll();
294 Frames expected;
295 for (uint8_t i = 0; i < 10; ++i)
296 expected.push_back({i});
297 EXPECT_EQ(port.written(), expected);
298 EXPECT_EQ(source.numErrors(), 0u);
299}
300
301TEST(WriteCallbackModeTest, NotificationDuringFetchIsNotLost) {
302 UIntType ui8("ui8", 8);
303 Source source;
304 RecordingWritePort port(&ui8);
305 // While the port is fetching (and about to be told there's no data), data
306 // arrives and the port is notified.
307 source.onFetch = [&](size_t idx) {
308 if (idx == 0) {
309 port.notifyAsyncDataAvailable();
310 EXPECT_EQ(source.numFetches(), 1u) << "notify must not recurse";
311 }
312 };
313 port.connect(source.fetch(), source.error());
314 port.notifyAsyncDataAvailable();
315 EXPECT_EQ(source.numFetches(), 2u);
316
317 source.onFetch = [&](size_t idx) {
318 if (idx == 2) {
319 source.push({1});
320 port.notifyAsyncDataAvailable();
321 }
322 };
323 port.notifyAsyncDataAvailable();
324 EXPECT_EQ(port.written(), (Frames{{1}}));
325}
326
327TEST(WriteCallbackModeTest, LongBurstIsWrittenInBoundedChunks) {
328 UIntType ui8("ui8", 8);
329 Source source;
330 RecordingWritePort port(&ui8);
331 constexpr size_t perCall = WriteChannelPort::kMaxAsyncWritesPerCall;
332 constexpr size_t numMsgs = 10 * perCall + 5;
333 for (size_t i = 0; i < numMsgs; ++i)
334 source.push({static_cast<uint8_t>(i)});
335 port.connect(source.fetch(), source.error());
336
337 // Each call returns after a bounded number of messages, even though the
338 // source always has more; poll() writes the rest.
339 port.notifyAsyncDataAvailable();
340 EXPECT_EQ(port.written().size(), perCall);
341 port.poll();
342 EXPECT_EQ(port.written().size(), 2 * perCall);
343 for (size_t i = 2; i < 11; ++i)
344 port.poll();
345 EXPECT_EQ(port.written().size(), numMsgs);
346 EXPECT_EQ(source.numErrors(), 0u);
347}
348
349TEST(WriteCallbackModeTest, WriteErrorReportedAndMessageDropped) {
350 UIntType ui8("ui8", 8);
351 Source source;
352 RecordingWritePort port(&ui8);
353 port.connect(source.fetch(), source.error());
354 source.push({1});
355 source.push({2});
356 port.throwAfter = 0;
357 port.notifyAsyncDataAvailable();
358
359 // {1} fails and is dropped; writing continues with {2}.
360 ASSERT_EQ(source.numErrors(), 1u);
361 EXPECT_EQ(errorMessage<std::out_of_range>(source[0]), "injected failure");
362 EXPECT_EQ(port.written(), (Frames{{2}}));
363}
364
365TEST(WriteCallbackModeTest, FetchErrorReported) {
366 UIntType ui8("ui8", 8);
367 Source source;
368 RecordingWritePort port(&ui8);
369 source.onFetch = [](size_t idx) {
370 if (idx == 0)
371 throw std::logic_error("fetch failure");
372 };
373 port.connect(source.fetch(), source.error());
374 source.push({1});
375 port.notifyAsyncDataAvailable();
376 ASSERT_EQ(source.numErrors(), 1u);
377 EXPECT_EQ(errorMessage<std::logic_error>(source[0]), "fetch failure");
378 // Like returning nullptr, the port doesn't fetch again until notified.
379 EXPECT_TRUE(port.written().empty());
380 port.poll();
381 EXPECT_EQ(source.numFetches(), 1u);
382 port.notifyAsyncDataAvailable();
383 EXPECT_EQ(port.written(), (Frames{{1}}));
384}
385
386TEST(WriteCallbackModeTest, ThrowingErrorCallbackPropagates) {
387 UIntType ui8("ui8", 8);
388 Source source;
389 RecordingWritePort port(&ui8);
390 source.onError = [](size_t) { throw std::runtime_error("callback failure"); };
391 port.connect(source.fetch(), source.error());
392 source.push({1});
393 source.push({2});
394 port.throwAfter = 0;
395 EXPECT_THROW(port.notifyAsyncDataAvailable(), std::runtime_error);
396 EXPECT_EQ(source.numErrors(), 1u);
397 EXPECT_TRUE(port.written().empty());
398
399 // The failed message was dropped, and the port keeps working.
400 port.poll();
401 EXPECT_EQ(port.written(), (Frames{{2}}));
402}
403
404TEST(WriteCallbackModeTest, SegmentedMessageIsFlattened) {
405 BitsType bits40("i40", 40);
406 Source source;
407 RecordingWritePort port(&bits40);
408 port.connect(source.fetch(), source.error());
409 source.push(std::make_unique<TwoSegmentMessage>());
410 port.notifyAsyncDataAvailable();
411 EXPECT_EQ(port.written(), (Frames{{1, 2, 3, 4, 5}}));
412}
413
414TEST(WriteCallbackModeTest, UsesBackendSegmentedTryWrite) {
415 // A backend with scatter-gather support, which takes segmented messages
416 // as-is.
417 struct ScatterGatherPort : public RecordingWritePort {
418 using RecordingWritePort::RecordingWritePort;
419 bool
420 tryWriteSegmentedImpl(std::unique_ptr<SegmentedMessageData> &msg) override {
421 if (rejectAll)
422 return false;
423 received.push_back(std::move(msg));
424 return true;
425 }
426 void
427 writeSegmentedImpl(std::unique_ptr<SegmentedMessageData> msg) override {
428 received.push_back(std::move(msg));
429 }
430 std::vector<std::unique_ptr<SegmentedMessageData>> received;
431 };
432
433 BitsType bits40("i40", 40);
434 Source source;
435 ScatterGatherPort port(&bits40);
436 port.connect(source.fetch(), source.error());
437 auto msg = std::make_unique<TwoSegmentMessage>();
438 SegmentedMessageData *original = msg.get();
439 source.push(std::move(msg));
440 port.rejectAll = true;
441 port.notifyAsyncDataAvailable();
442 EXPECT_TRUE(port.received.empty());
443 port.rejectAll = false;
444 port.poll();
445 // The original message was handed over without being flattened.
446 ASSERT_EQ(port.received.size(), 1u);
447 EXPECT_EQ(port.received[0].get(), original);
448 EXPECT_TRUE(port.written().empty());
449
450 // The backend's segmented write hooks can't be used to bypass callback mode.
451 std::unique_ptr<SegmentedMessageData> direct = makeMsg({1, 2, 3, 4, 5});
452 EXPECT_THROW(port.tryWrite(direct), std::runtime_error);
453 EXPECT_TRUE(direct);
454 EXPECT_THROW(port.write(makeMsg({1, 2, 3, 4, 5})), std::runtime_error);
455 EXPECT_EQ(port.received.size(), 1u);
456
457 // In sync mode, they are used.
458 port.disconnect();
459 port.connect();
460 EXPECT_TRUE(port.tryWrite(direct));
461 EXPECT_FALSE(direct);
462 port.write(makeMsg({6, 7, 8, 9, 10}));
463 EXPECT_EQ(port.received.size(), 3u);
464 EXPECT_TRUE(port.written().empty());
465}
466
467TEST(WriteCallbackModeTest, VoidTypeIsPadded) {
468 VoidType voidType("void");
469 Source source;
470 RecordingWritePort port(&voidType);
471 port.connect(source.fetch(), source.error());
472 source.push(std::make_unique<MessageData>());
473 port.notifyAsyncDataAvailable();
474 EXPECT_EQ(port.written(), (Frames{{0}}));
475}
476
477TEST(WriteCallbackModeTest, InvalidCalls) {
478 UIntType ui8("ui8", 8);
479 Source source;
480 RecordingWritePort port(&ui8);
481 // Notifying a port which isn't in callback mode throws.
482 EXPECT_THROW(port.notifyAsyncDataAvailable(), std::runtime_error);
483 EXPECT_THROW(port.connect(nullptr, source.error()), std::invalid_argument);
484 EXPECT_THROW(port.connect(source.fetch(), nullptr), std::invalid_argument);
485 EXPECT_FALSE(port.isConnected());
486 port.connect();
487 EXPECT_THROW(port.notifyAsyncDataAvailable(), std::runtime_error);
488 port.disconnect();
489 port.connect(source.fetch(), source.error());
490 port.disconnect();
491 EXPECT_THROW(port.notifyAsyncDataAvailable(), std::runtime_error);
492 EXPECT_EQ(source.numFetches(), 0u);
493}
494TEST(WriteCallbackModeTest, ModesAreExclusive) {
495 UIntType ui8("ui8", 8);
496 Source source;
497 RecordingWritePort port(&ui8);
498 MessageData data(std::vector<uint8_t>{1});
499
500 // Sync mode rejects connecting with callbacks.
501 port.connect();
502 EXPECT_THROW(port.connect(source.fetch(), source.error()),
503 std::runtime_error);
504 port.write(data);
505 EXPECT_TRUE(port.tryWrite(data));
506 EXPECT_TRUE(port.flush());
507 port.disconnect();
508
509 // Callback mode rejects the sync APIs and reconnecting.
510 port.connect(source.fetch(), source.error());
511 EXPECT_THROW(port.write(data), std::runtime_error);
512 EXPECT_THROW(port.write(makeMsg({1})), std::runtime_error);
513 EXPECT_THROW(port.tryWrite(data), std::runtime_error);
514 std::unique_ptr<SegmentedMessageData> segmented = makeMsg({1});
515 EXPECT_THROW(port.tryWrite(segmented), std::runtime_error);
516 EXPECT_TRUE(segmented);
517 EXPECT_THROW(port.flush(), std::runtime_error);
518 EXPECT_THROW(port.connect(), std::runtime_error);
519 EXPECT_THROW(port.connect(source.fetch(), source.error()),
520 std::runtime_error);
521 port.disconnect();
522
523 // After disconnecting, sync mode works again.
524 port.connect();
525 port.write(data);
526 EXPECT_EQ(port.written().size(), 3u);
527}
528
529/// Count how many of the sync write APIs throw when called on `port`.
530int countRejectedSyncWrites(WriteChannelPort &port) {
531 MessageData data(std::vector<uint8_t>{9, 9});
532 int rejected = 0;
533 auto expectThrow = [&](auto &&fn) {
534 try {
535 fn();
536 } catch (const std::runtime_error &) {
537 ++rejected;
538 }
539 };
540 expectThrow([&] { port.write(data); });
541 expectThrow([&] { port.write(makeMsg({9, 9})); });
542 expectThrow([&] { port.tryWrite(data); });
543 expectThrow([&] {
544 std::unique_ptr<SegmentedMessageData> msg = makeMsg({9, 9});
545 port.tryWrite(msg);
546 });
547 expectThrow([&] { port.flush(); });
548 return rejected;
549}
550
551TEST(WriteCallbackModeTest, SyncWritesThrowInCallbacks) {
552 UIntType ui16("ui16", 16);
553 Source source;
554 RecordingWritePort port(&ui16);
555 int rejected = 0;
556 source.onFetch = [&](size_t) { rejected += countRejectedSyncWrites(port); };
557 source.onError = [&](size_t) { rejected += countRejectedSyncWrites(port); };
558 port.connect(source.fetch(), source.error());
559 source.push({1, 2});
560 source.push({3, 4});
561 port.throwAfter = 0;
563 // Three fetches and one error.
564 EXPECT_EQ(rejected, 4 * 5);
565 EXPECT_EQ(port.written(), (Frames{{3, 4}}));
566}
567
568//===----------------------------------------------------------------------===//
569// Windowed messages, whose frames may be sent across several calls.
570//===----------------------------------------------------------------------===//
571
572TEST(WriteCallbackModeTest, WindowedFramesSentBeforeNextMessage) {
573 TwoFrameWindow types;
574 Source source;
575 RecordingWritePort port(&types.window);
576 std::vector<size_t> framesWrittenAtFetch;
577 source.onFetch = [&](size_t) {
578 framesWrittenAtFetch.push_back(port.written().size());
579 };
580 port.connect(source.fetch(), source.error(),
581 ChannelPort::ConnectOptions(std::nullopt, true));
582 source.push({1, 2, 3, 4});
583 source.push({5, 6, 7, 8});
584
585 // The first frame is accepted, the second isn't. The next message is
586 // fetched and held, but not written until the first one's frames are.
587 port.acceptBudget = 1;
589 EXPECT_EQ(port.written().size(), 1u);
590 EXPECT_EQ(source.numFetches(), 2u);
591 port.poll();
592
593 port.acceptBudget = -1;
594 port.poll();
595 EXPECT_EQ(framesWrittenAtFetch, (std::vector<size_t>{0, 1, 4}));
596 EXPECT_EQ(receive(&types.window, port.written()),
597 (Frames{{1, 2, 3, 4}, {5, 6, 7, 8}}));
598}
599
600TEST(WriteCallbackModeTest, FetchErrorKeepsPreviousMessagesFrames) {
601 TwoFrameWindow types;
602 Source source;
603 RecordingWritePort port(&types.window);
604 source.onFetch = [](size_t idx) {
605 if (idx == 1)
606 throw std::runtime_error("fetch failure");
607 };
608 port.connect(source.fetch(), source.error(),
609 ChannelPort::ConnectOptions(std::nullopt, true));
610 source.push({1, 2, 3, 4});
611 source.push({5, 6, 7, 8});
612
613 // The first message's second frame is backpressured when the next fetch
614 // fails. Only the failed fetch is reported: the first message isn't lost.
615 port.acceptBudget = 1;
617 EXPECT_EQ(source.numErrors(), 1u);
618 port.acceptBudget = -1;
620 EXPECT_EQ(receive(&types.window, port.written()),
621 (Frames{{1, 2, 3, 4}, {5, 6, 7, 8}}));
622}
623
624TEST(WriteCallbackModeTest, PollSendsRemainingFrames) {
625 ThreeFrameWindow types;
626 Source source;
627 RecordingWritePort port(&types.window);
628 port.connect(source.fetch(), source.error(),
629 ChannelPort::ConnectOptions(std::nullopt, true));
630 source.push({1, 2, 3, 4, 5, 6});
631 port.acceptBudget = 1;
633 EXPECT_EQ(port.written().size(), 1u);
634
635 // Each poll sends what frames it can.
636 port.acceptBudget = 1;
637 port.poll();
638 EXPECT_EQ(port.written().size(), 2u);
639 port.poll();
640
641 port.acceptBudget = -1;
642 port.poll();
643 EXPECT_EQ(receive(&types.window, port.written()),
644 (Frames{{1, 2, 3, 4, 5, 6}}));
645}
646
647TEST(WriteCallbackModeTest, WindowedFrameFailureReported) {
648 TwoFrameWindow types;
649 Source source;
650 RecordingWritePort port(&types.window);
651 port.connect(source.fetch(), source.error(),
652 ChannelPort::ConnectOptions(std::nullopt, true));
653 source.push({1, 2, 3, 4});
654 source.push({5, 6, 7, 8});
655 // The first frame is sent, then the second fails.
656 port.throwAfter = 1;
658 ASSERT_EQ(source.numErrors(), 1u);
659 EXPECT_EQ(errorMessage<std::out_of_range>(source[0]), "injected failure");
660 // Its remaining frame is dropped, and writing continues.
661 EXPECT_EQ(port.written(), (Frames{{1, 2}, {5, 6}, {7, 8}}));
662}
663
664//===----------------------------------------------------------------------===//
665// Disconnection and destruction.
666//===----------------------------------------------------------------------===//
667
668TEST(WriteCallbackModeTest, DisconnectDropsHeldMessage) {
669 UIntType ui8("ui8", 8);
670 Source source;
671 RecordingWritePort port(&ui8);
672 port.connect(source.fetch(), source.error());
673 source.push({1});
674 source.push({2});
675 port.rejectAll = true;
677
678 // The held message is dropped silently.
679 port.disconnect();
680 EXPECT_EQ(source.numErrors(), 0u);
681 // Only the held message was fetched; the other stays with the source.
682 EXPECT_EQ(source.queued(), 1u);
683 port.rejectAll = false;
684 EXPECT_FALSE(port.poll());
685 EXPECT_TRUE(port.written().empty());
686
687 // The port can be reconnected and used again.
688 Source source2;
689 port.connect(source2.fetch(), source2.error());
690 source2.push({3});
692 EXPECT_EQ(port.written(), (Frames{{3}}));
693}
694TEST(WriteCallbackModeTest, DisconnectDropsWindowedRemainder) {
695 TwoFrameWindow types;
696 Source source;
697 RecordingWritePort port(&types.window);
698 ChannelPort::ConnectOptions opts(std::nullopt, true);
699 port.connect(source.fetch(), source.error(), opts);
700 source.push({1, 2, 3, 4});
701 port.acceptBudget = 1;
703 port.disconnect();
704 EXPECT_EQ(source.numErrors(), 0u);
705
706 // The dropped frame isn't sent after reconnecting, in either mode.
707 port.acceptBudget = -1;
708 port.connect(opts);
709 EXPECT_TRUE(port.flush());
710 EXPECT_TRUE(port.tryWrite(MessageData(std::vector<uint8_t>{5, 6, 7, 8})));
711 EXPECT_EQ(port.written(), (Frames{{1, 2}, {5, 6}, {7, 8}}));
712}
713TEST(WriteCallbackModeTest, DisconnectFromFetchDropsFetchedMessage) {
714 UIntType ui8("ui8", 8);
715 Source source;
716 RecordingWritePort port(&ui8);
717 source.onFetch = [&](size_t) { port.disconnect(); };
718 port.connect(source.fetch(), source.error());
719 source.push({1});
721 // The message returned after disconnecting is dropped.
722 EXPECT_FALSE(port.isConnected());
723 EXPECT_TRUE(port.written().empty());
724 EXPECT_EQ(source.numErrors(), 0u);
725 EXPECT_EQ(port.pollImplCount, 0);
726}
727TEST(WriteCallbackModeTest, FetchErrorAfterReconnectFromFetchIsDropped) {
728 UIntType ui8("ui8", 8);
729 Source source, source2;
730 RecordingWritePort port(&ui8);
731 source.onFetch = [&](size_t) {
732 port.disconnect();
733 port.connect(source2.fetch(), source2.error());
734 throw std::runtime_error("fetch failure");
735 };
736 port.connect(source.fetch(), source.error());
738 // The old connection's error isn't reported, and the new one works.
739 EXPECT_EQ(source.numErrors(), 0u);
740 source2.push({1});
742 EXPECT_EQ(port.written(), (Frames{{1}}));
743 EXPECT_EQ(source2.numErrors(), 0u);
744}
745
746TEST(WriteCallbackModeTest, SyncFramesBlockCallbackConnect) {
747 TwoFrameWindow types;
748 Source source;
749 RecordingWritePort port(&types.window);
750 ChannelPort::ConnectOptions translate(std::nullopt, true);
751 port.connect(translate);
752 // A sync write whose second frame is backpressured.
753 port.acceptBudget = 1;
754 std::unique_ptr<SegmentedMessageData> msg =
755 std::make_unique<MessageData>(std::vector<uint8_t>{1, 2, 3, 4});
756 EXPECT_TRUE(port.tryWrite(msg));
757 port.disconnect();
758
759 // Connecting in callback mode would drop it, so is refused.
760 EXPECT_THROW(port.connect(source.fetch(), source.error(), translate),
761 std::runtime_error);
762 EXPECT_FALSE(port.isConnected());
763 port.connect(translate);
764 port.acceptBudget = -1;
765 EXPECT_TRUE(port.flush());
766 port.disconnect();
767 port.connect(source.fetch(), source.error(), translate);
768 EXPECT_EQ(receive(&types.window, port.written()), (Frames{{1, 2, 3, 4}}));
769}
770
771TEST(WriteCallbackModeTest, OverridingBackendDisconnectDropsFrames) {
772 // A backend which overrides callback mode, but writes with the inherited
773 // segmented write hook.
774 struct OverridingPort : public RecordingWritePort {
775 using RecordingWritePort::connect;
776 using RecordingWritePort::RecordingWritePort;
777 void connect(DataFetchCallback fetch, WriteErrorCallback,
778 const ConnectOptions &options = {}) override {
779 connectCallbackMode(options);
780 this->fetch = std::move(fetch);
781 }
782 void notifyAsyncDataAvailable() override {
783 std::unique_ptr<SegmentedMessageData> msg = fetch();
784 tryWriteSegmentedImpl(msg);
785 }
786 DataFetchCallback fetch;
787 };
788
789 TwoFrameWindow types;
790 Source source;
791 OverridingPort port(&types.window);
792 ChannelPort::ConnectOptions translate(std::nullopt, true);
793 port.connect(source.fetch(), source.error(), translate);
794 source.push({1, 2, 3, 4});
795 port.acceptBudget = 1;
797 EXPECT_EQ(port.written().size(), 1u);
798
799 // The callback mode message's remaining frame isn't sent after reconnecting
800 // in sync mode.
801 port.disconnect();
802 port.connect(translate);
803 port.acceptBudget = -1;
804 EXPECT_TRUE(port.flush());
805 EXPECT_EQ(port.written().size(), 1u);
806}
807
808TEST(WriteCallbackModeTest, ReconnectFromCallback) {
809 UIntType ui8("ui8", 8);
810 Source oldSource, newSource;
811 RecordingWritePort port(&ui8);
812 // Reconnect with new callbacks from within a callback.
813 oldSource.onFetch = [&](size_t) {
814 port.disconnect();
815 port.connect(newSource.fetch(), newSource.error());
816 newSource.push({2});
818 };
819 port.connect(oldSource.fetch(), oldSource.error());
820 oldSource.push({1});
822
823 // The old connection's fetched message is dropped; the new one works.
824 EXPECT_TRUE(port.isConnected());
825 EXPECT_EQ(port.written(), (Frames{{2}}));
826 newSource.push({3});
828 EXPECT_EQ(port.written(), (Frames{{2}, {3}}));
829 EXPECT_EQ(oldSource.numFetches(), 1u);
830 EXPECT_EQ(oldSource.numErrors() + newSource.numErrors(), 0u);
831}
832TEST(WriteCallbackModeTest, ReconnectOnOtherThreadWhileInCallback) {
833 UIntType ui8("ui8", 8);
834 Source oldSource, newSource;
835 RecordingWritePort port(&ui8);
836 // A callback disconnects the port, then another thread reconnects it and
837 // writes while the callback is still running.
838 oldSource.onFetch = [&](size_t idx) {
839 if (idx != 0)
840 return;
841 port.disconnect();
842 std::thread([&] {
843 port.connect(newSource.fetch(), newSource.error());
844 newSource.push({2});
846 }).join();
847 };
848 port.connect(oldSource.fetch(), oldSource.error());
849 oldSource.push({1});
851 // The message fetched by the old connection isn't written.
852 EXPECT_EQ(port.written(), (Frames{{2}}));
853 newSource.push({3});
855 EXPECT_EQ(port.written(), (Frames{{2}, {3}}));
856 EXPECT_EQ(oldSource.numFetches(), 1u);
857}
858TEST(WriteCallbackModeTest, DisconnectWaitsForWriterOnOtherThread) {
859 UIntType ui8("ui8", 8);
860 Source source;
861 RecordingWritePort port(&ui8);
862 std::atomic<bool> inFetch = false, releaseFetch = false;
863 source.onFetch = [&](size_t idx) {
864 if (idx != 0)
865 return;
866 inFetch = true;
867 while (!releaseFetch)
868 std::this_thread::yield();
869 };
870 port.connect(source.fetch(), source.error());
871 source.push({1});
872 std::thread writer([&] { port.notifyAsyncDataAvailable(); });
873 while (!inFetch)
874 std::this_thread::yield();
875
876 // While the other thread is in a callback, disconnect() blocks.
877 std::atomic<bool> disconnected = false;
878 std::thread disconnecter([&] {
879 port.disconnect();
880 disconnected = true;
881 });
882 std::this_thread::sleep_for(std::chrono::milliseconds(50));
883 EXPECT_FALSE(disconnected);
884 releaseFetch = true;
885 writer.join();
886 disconnecter.join();
887 EXPECT_TRUE(disconnected);
888 // The message fetched meanwhile was dropped.
889 EXPECT_TRUE(port.written().empty());
890}
891
892TEST(WriteCallbackModeTest, DestructorDropsHeldMessage) {
893 UIntType ui8("ui8", 8);
894 Source source;
895 {
896 RecordingWritePort port(&ui8);
897 port.connect(source.fetch(), source.error());
898 source.push({1});
899 port.rejectAll = true;
901 }
902 EXPECT_EQ(source.numFetches(), 1u);
903 EXPECT_EQ(source.numErrors(), 0u);
904}
905TEST(WriteCallbackModeTest, BackendCanOverride) {
906 // A backend which replaces the default implementation: it fetches a message
907 // each time its device has room.
908 struct OverridingPort : public RecordingWritePort {
909 using RecordingWritePort::RecordingWritePort;
910 void connect(DataFetchCallback fetch, WriteErrorCallback onError,
911 const ConnectOptions &options = {}) override {
912 connectCallbackMode(options);
913 this->fetch = std::move(fetch);
914 }
915 void notifyAsyncDataAvailable() override { ++notifications; }
916 void disconnect() override {
917 fetch = nullptr;
918 RecordingWritePort::disconnect();
919 }
920 void deviceHasRoom() {
921 if (std::unique_ptr<SegmentedMessageData> msg = fetch())
922 sent.push_back(msg->toMessageData().getData());
923 }
924 DataFetchCallback fetch;
925 int notifications = 0;
926 Frames sent;
927 };
928
929 UIntType ui8("ui8", 8);
930 Source source;
931 OverridingPort port(&ui8);
932 port.connect(source.fetch(), source.error());
933 EXPECT_TRUE(port.isConnected());
934 // The sync APIs are rejected in callback mode, as with the default.
935 EXPECT_EQ(countRejectedSyncWrites(port), 5);
936
937 source.push({1});
938 source.push({2});
940 EXPECT_EQ(port.notifications, 1);
941 // The default implementation isn't used: polling doesn't fetch.
942 port.poll();
943 EXPECT_EQ(source.numFetches(), 0u);
944 port.deviceHasRoom();
945 EXPECT_EQ(port.sent, (Frames{{1}}));
946 EXPECT_EQ(source.numFetches(), 1u);
947 EXPECT_TRUE(port.written().empty());
948 port.disconnect();
949 EXPECT_FALSE(port.isConnected());
950}
951
952//===----------------------------------------------------------------------===//
953// Concurrency.
954//===----------------------------------------------------------------------===//
955
956TEST(WriteCallbackModeTest, ProducerThreadsWithServiceThread) {
957 TwoFrameWindow types;
958 Source source;
959 RecordingWritePort port(&types.window);
960 port.connect(source.fetch(), source.error(),
961 ChannelPort::ConnectOptions(std::nullopt, true));
962 // Backpressure every other frame, so messages are written both by the
963 // producers' notifications and by the service thread's polls.
964 port.alternate = true;
965
966 AcceleratorServiceThread serviceThread;
967 serviceThread.addTask([&port]() { port.poll(); });
968 constexpr size_t numProducers = 4, numMsgs = 1000;
969 std::vector<std::thread> producers;
970 for (size_t p = 0; p < numProducers; ++p)
971 producers.emplace_back([&, p] {
972 for (size_t i = 0; i < numMsgs; ++i) {
973 source.push({static_cast<uint8_t>(p), static_cast<uint8_t>(i),
974 static_cast<uint8_t>(i >> 8), 0});
975 port.notifyAsyncDataAvailable();
976 }
977 });
978 for (auto &producer : producers)
979 producer.join();
980
981 auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
982 while (port.written().size() < 2 * numProducers * numMsgs &&
983 std::chrono::steady_clock::now() < deadline)
984 std::this_thread::sleep_for(std::chrono::milliseconds(1));
985 serviceThread.stop();
986 EXPECT_EQ(source.numErrors(), 0u);
987
988 // Every message arrives intact, and each producer's in order.
989 Frames received = receive(&types.window, port.written());
990 ASSERT_EQ(received.size(), numProducers * numMsgs);
991 std::vector<size_t> next(numProducers, 0);
992 for (const auto &msg : received) {
993 size_t p = msg[0], i = msg[1] | (msg[2] << 8);
994 EXPECT_EQ(i, next[p]++);
995 }
996}
997
998TEST(WriteCallbackModeTest, ServiceThreadLogsErrorCallbackExceptions) {
999 struct RecordingLogger : public Logger {
1000 RecordingLogger() : Logger(false, false) {}
1001 void log(Level level, const std::string &, const std::string &msg,
1002 const std::map<std::string, std::any> *) override {
1003 std::lock_guard<std::mutex> lock(mutex);
1004 if (level == Level::Error)
1005 errors.push_back(msg);
1006 }
1007 size_t numErrors() {
1008 std::lock_guard<std::mutex> lock(mutex);
1009 return errors.size();
1010 }
1011 std::mutex mutex;
1012 std::vector<std::string> errors;
1013 };
1014
1015 UIntType ui8("ui8", 8);
1016 Source source;
1017 source.onError = [](size_t) { throw std::runtime_error("callback failure"); };
1018 RecordingWritePort port(&ui8);
1019 port.connect(source.fetch(), source.error());
1020 source.push({1});
1021 source.push({2});
1022 port.throwAfter = 0;
1023
1024 // The exception is logged, and the service thread carries on: it writes the
1025 // next message, and runs its other tasks.
1026 auto ownedLogger = std::make_unique<RecordingLogger>();
1027 RecordingLogger &logger = *ownedLogger;
1028 Context ctxt(std::move(ownedLogger));
1029 std::atomic<int> otherTaskRuns = 0;
1030 {
1031 AcceleratorServiceThread serviceThread(&ctxt);
1032 serviceThread.addTask([&port]() { port.poll(); });
1033 serviceThread.addTask([&]() { ++otherTaskRuns; });
1034 auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
1035 while ((port.written().empty() || otherTaskRuns < 2) &&
1036 std::chrono::steady_clock::now() < deadline)
1037 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1038 }
1039 EXPECT_EQ(port.written(), (Frames{{2}}));
1040 EXPECT_GE(otherTaskRuns, 2);
1041 ASSERT_EQ(logger.numErrors(), 1u);
1042 EXPECT_NE(logger.errors[0].find("callback failure"), std::string::npos);
1043}
1044
1045//===----------------------------------------------------------------------===//
1046// TypedWritePort callback mode.
1047//===----------------------------------------------------------------------===//
1048
1049TEST(WriteCallbackModeTest, TypedWritePortValue) {
1050 UIntType ui24("ui24", 24);
1051 RecordingWritePort port(&ui24);
1052 TypedWritePort<uint32_t> typed(port);
1053 std::deque<uint32_t> values = {0x030201u, 0x060504u};
1054 typed.connect(
1055 [&]() -> std::unique_ptr<uint32_t> {
1056 if (values.empty())
1057 return nullptr;
1058 auto value = std::make_unique<uint32_t>(values.front());
1059 values.pop_front();
1060 return value;
1061 },
1062 [](std::exception_ptr) { ADD_FAILURE(); });
1063 typed.notifyAsyncDataAvailable();
1064 // Serialized to the 3-byte wire width.
1065 EXPECT_EQ(port.written(), (Frames{{1, 2, 3}, {4, 5, 6}}));
1066}
1067
1068TEST(WriteCallbackModeTest, TypedWritePortTypeCheck) {
1069 UIntType ui32("ui32", 32);
1070 Source source;
1071 RecordingWritePort port(&ui32);
1072 TypedWritePort<int32_t> typed(port); // int32_t expects SIntType
1073 EXPECT_THROW(
1074 typed.connect([] { return std::unique_ptr<int32_t>(); }, source.error()),
1076 EXPECT_FALSE(port.isConnected());
1077}
1078
1079TEST(WriteCallbackModeTest, TypedWritePortSegmented) {
1080 BitsType bits40("i40", 40);
1081 RecordingWritePort port(&bits40);
1082 TypedWritePort<TwoSegmentMessage, /*SkipTypeCheck=*/true> typed(port);
1083 bool sent = false;
1084 typed.connect(
1085 [&]() -> std::unique_ptr<TwoSegmentMessage> {
1086 if (sent)
1087 return nullptr;
1088 sent = true;
1089 return std::make_unique<TwoSegmentMessage>();
1090 },
1091 [](std::exception_ptr) { ADD_FAILURE(); });
1092 typed.notifyAsyncDataAvailable();
1093 EXPECT_EQ(port.written(), (Frames{{1, 2, 3, 4, 5}}));
1094}
1095
1096TEST(WriteCallbackModeTest, TypedWritePortTryWriteKeepsMessageOnThrow) {
1097 BitsType bits40("i40", 40);
1098 RecordingWritePort port(&bits40);
1099 TypedWritePort<TwoSegmentMessage, /*SkipTypeCheck=*/true> typed(port);
1100 typed.connect([]() -> std::unique_ptr<TwoSegmentMessage> { return nullptr; },
1101 [](std::exception_ptr) {});
1102 // tryWrite() throws in callback mode; the caller keeps the message.
1103 auto msg = std::make_unique<TwoSegmentMessage>();
1104 TwoSegmentMessage *original = msg.get();
1105 EXPECT_THROW(typed.tryWrite(msg), std::runtime_error);
1106 EXPECT_EQ(msg.get(), original);
1107}
1108
1109TEST(WriteCallbackModeTest, TypedWritePortVoid) {
1110 VoidType voidType("void");
1111 RecordingWritePort port(&voidType);
1112 TypedWritePort<void> typed(port);
1113 int remaining = 2;
1114 typed.connect([&] { return remaining-- > 0; },
1115 [](std::exception_ptr) { ADD_FAILURE(); });
1116 typed.notifyAsyncDataAvailable();
1117 EXPECT_EQ(port.written(), (Frames{{0}, {0}}));
1118}
1119
1120} // namespace
static void log(char *epId, bool toClient, const MessageData &msg)
Emit the contents of 'msg' to the log file in hex.
Background thread which services various requests.
virtual void stop()
Instruct the service thread to stop running.
virtual void addTask(std::function< void(void)> task)
Add a task to be invoked on every service iteration.
Bits are just an array of bits.
Definition Types.h:224
bool poll()
Poll for incoming data.
Definition Ports.h:208
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:34
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
std::function< bool(std::unique_ptr< SegmentedMessageData > &)> ReadCallback
Primary callback API for raw reads.
Definition Ports.h:603
bool invokeCallback(std::unique_ptr< SegmentedMessageData > &msg)
Invoke the currently registered callback.
Definition Ports.cpp:88
ReadChannelPort(const Type *type)
Definition Ports.h:610
Abstract multi-segment message.
Definition Common.h:151
Root class of the ESI type system.
Definition Types.h:36
Unsigned integer.
Definition Types.h:253
The "void" type is a special type which can be used to represent no type.
Definition Types.h:141
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
virtual bool isConnected() const override
Definition Ports.h:342
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
virtual void notifyAsyncDataAvailable()
Notify the port that the DataFetchCallback has data again.
Definition Ports.cpp:938
void write(const MessageData &data)
A very basic blocking write API.
Definition Ports.h:356
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.cpp:867
bool flush()
Flush any buffered data.
Definition Ports.h:401
bool tryWrite(const MessageData &data)
A basic non-blocking write API.
Definition Ports.h:379
std::function< void(std::exception_ptr)> WriteErrorCallback
Callback mode error handler.
Definition Ports.h:333
static constexpr size_t kMaxAsyncWritesPerCall
The most messages the default callback mode implementation writes per call to notifyAsyncDataAvailabl...
Definition Ports.h:445
std::function< std::unique_ptr< SegmentedMessageData >()> DataFetchCallback
Callback mode data source.
Definition Ports.h:327
connect(destination, source)
Definition support.py:39
void error(Twine message)
Definition LSPUtils.cpp:16
Definition esi.py:1