CIRCT 24.0.0git
Loading...
Searching...
No Matches
ESIRuntimeTypedPortsTest.cpp
Go to the documentation of this file.
1//===- ESIRuntimeTypedPortsTest.cpp - Typed ESI port tests ----------------===//
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/TypedPorts.h"
10#include "gtest/gtest.h"
11
12#include <algorithm>
13#include <array>
14#include <chrono>
15#include <cstring>
16#include <deque>
17#include <vector>
18
19using namespace esi;
20
21namespace {
22
23TEST(TypedPortsTest, UnwrapTypeAlias) {
24 BitsType bits("i8", 8);
25 TypeAliasType alias("alias", "Alias", &bits);
26 TypeAliasType nested("nested", "Nested", &alias);
27 ChannelType channel("channel", &nested);
28 TypeAliasType channelAlias("channelAlias", "ChannelAlias", &channel);
29
30 EXPECT_EQ(unwrapTypeAlias(nullptr), nullptr);
31 EXPECT_EQ(unwrapTypeAlias(&bits), &bits);
32 EXPECT_EQ(unwrapTypeAlias(&nested), &bits);
33 EXPECT_EQ(unwrapTypeAlias(&channelAlias), &channel);
34}
35
36TEST(TypedPortsTest, GetUnwrappedAs) {
37 BitsType bits("i8", 8);
38 StructType payload("payload", {{"data", &bits}});
39 TypeAliasType alias("alias", "Alias", &payload);
40 TypeAliasType nestedAlias("nestedAlias", "NestedAlias", &alias);
41 ChannelType channel("channel", &nestedAlias);
42 TypeAliasType channelAlias("channelAlias", "ChannelAlias", &channel);
43 ChannelType outerChannel("outerChannel", &channelAlias);
44 ArrayType array("array", &payload, 2);
45
46 EXPECT_EQ(getUnwrappedAs<StructType>(nullptr), nullptr);
47 EXPECT_EQ(getUnwrappedAs<StructType>(&payload), &payload);
48 EXPECT_EQ(getUnwrappedAs<StructType>(&nestedAlias), &payload);
49 EXPECT_EQ(getUnwrappedAs<StructType>(&channel), &payload);
50 EXPECT_EQ(getUnwrappedAs<StructType>(&channelAlias), &payload);
51 EXPECT_EQ(getUnwrappedAs<StructType>(&outerChannel), &payload);
52 EXPECT_EQ(getUnwrappedAs<BitVectorType>(&outerChannel), nullptr);
53 EXPECT_EQ(getUnwrappedAs<StructType>(&array), nullptr);
54 EXPECT_EQ(getUnwrappedAs<ArrayType>(&array), &array);
55}
56
57//===----------------------------------------------------------------------===//
58// verifyTypeCompatibility tests
59//===----------------------------------------------------------------------===//
60
61TEST(TypedPortsTest, VoidTypeCompatibility) {
62 VoidType voidType("void");
63 EXPECT_NO_THROW(verifyTypeCompatibility<void>(&voidType));
64
65 // Non-void types should fail.
66 UIntType uint1("ui1", 1);
68
69 SIntType sint32("si32", 32);
70 EXPECT_THROW(verifyTypeCompatibility<void>(&sint32),
72}
73
74TEST(TypedPortsTest, BoolTypeCompatibility) {
75 BitsType bits1("i1", 1);
76 EXPECT_NO_THROW(verifyTypeCompatibility<bool>(&bits1));
77
78 // Width > 1 should fail.
79 BitsType bits8("i8", 8);
81
82 // Wrong type entirely should fail.
83 SIntType sint1("si1", 1);
85}
86
87TEST(TypedPortsTest, SignedIntTypeCompatibility) {
88 // int32_t can hold si17 (width 17, in range (16,32]).
89 SIntType sint17("si17", 17);
90 EXPECT_NO_THROW(verifyTypeCompatibility<int32_t>(&sint17));
91
92 // si32 has width 32, which fits exactly in int32_t. Should pass.
93 SIntType sint32("si32", 32);
94 EXPECT_NO_THROW(verifyTypeCompatibility<int32_t>(&sint32));
95
96 // si33 has width 33, which exceeds int32_t. Should fail.
97 SIntType sint33("si33", 33);
98 EXPECT_THROW(verifyTypeCompatibility<int32_t>(&sint33),
100
101 // si16 fits in int32_t but a smaller type (int16_t) would suffice. Reject.
102 SIntType sint16("si16", 16);
103 EXPECT_THROW(verifyTypeCompatibility<int32_t>(&sint16),
105
106 // si8 is even smaller — also reject for int32_t.
107 SIntType sint8("si8", 8);
108 EXPECT_THROW(verifyTypeCompatibility<int32_t>(&sint8),
110
111 // But si8 should be fine for int8_t (closest match).
112 EXPECT_NO_THROW(verifyTypeCompatibility<int8_t>(&sint8));
113
114 // UIntType should fail for signed C++ type.
115 UIntType uint31("ui31", 31);
116 EXPECT_THROW(verifyTypeCompatibility<int32_t>(&uint31),
118
119 // int64_t can hold si33 (width 33, in range (32,64]).
120 SIntType sint33b("si33", 33);
121 EXPECT_NO_THROW(verifyTypeCompatibility<int64_t>(&sint33b));
122
123 // si64 fits exactly in int64_t. Should pass.
124 SIntType sint64("si64", 64);
125 EXPECT_NO_THROW(verifyTypeCompatibility<int64_t>(&sint64));
126
127 // si65 exceeds int64_t. Should fail.
128 SIntType sint65("si65", 65);
129 EXPECT_THROW(verifyTypeCompatibility<int64_t>(&sint65),
131
132 // si32 fits in int64_t but int32_t would suffice. Reject.
133 EXPECT_THROW(verifyTypeCompatibility<int64_t>(&sint32),
135}
136
137TEST(TypedPortsTest, UnsignedIntTypeCompatibility) {
138 // uint32_t can hold ui17 (width 17, in range (16,32]).
139 UIntType uint17("ui17", 17);
140 EXPECT_NO_THROW(verifyTypeCompatibility<uint32_t>(&uint17));
141
142 // ui32 has width 32, which fits exactly in uint32_t. Should pass.
143 UIntType uint32_t_("ui32", 32);
144 EXPECT_NO_THROW(verifyTypeCompatibility<uint32_t>(&uint32_t_));
145
146 // ui33 exceeds uint32_t. Should fail.
147 UIntType uint33("ui33", 33);
148 EXPECT_THROW(verifyTypeCompatibility<uint32_t>(&uint33),
150
151 // ui16 fits but uint16_t would suffice. Reject for uint32_t.
152 UIntType uint16_("ui16", 16);
153 EXPECT_THROW(verifyTypeCompatibility<uint32_t>(&uint16_),
155
156 // But ui16 should be fine for uint16_t.
157 EXPECT_NO_THROW(verifyTypeCompatibility<uint16_t>(&uint16_));
158
159 // BitsType (signless iM) should also be accepted for unsigned.
160 BitsType bits17("i17", 17);
161 EXPECT_NO_THROW(verifyTypeCompatibility<uint32_t>(&bits17));
162
163 // BitsType with width 32 fits in uint32_t. Should pass.
164 BitsType bits32("i32", 32);
165 EXPECT_NO_THROW(verifyTypeCompatibility<uint32_t>(&bits32));
166
167 // BitsType with width 33 exceeds uint32_t. Should fail.
168 BitsType bits33("i33", 33);
169 EXPECT_THROW(verifyTypeCompatibility<uint32_t>(&bits33),
171
172 // BitsType width 8 should be rejected for uint32_t (uint8_t suffices).
173 BitsType bits8("i8", 8);
174 EXPECT_THROW(verifyTypeCompatibility<uint32_t>(&bits8),
176 EXPECT_NO_THROW(verifyTypeCompatibility<uint8_t>(&bits8));
177
178 // uint64_t with ui33 (in range (32,64]).
179 UIntType uint33b("ui33", 33);
180 EXPECT_NO_THROW(verifyTypeCompatibility<uint64_t>(&uint33b));
181
182 // uint64_t with ui64 fits exactly. Should pass.
183 UIntType uint64_t_("ui64", 64);
184 EXPECT_NO_THROW(verifyTypeCompatibility<uint64_t>(&uint64_t_));
185
186 // uint64_t with ui65 exceeds. Should fail.
187 UIntType uint65("ui65", 65);
188 EXPECT_THROW(verifyTypeCompatibility<uint64_t>(&uint65),
190
191 // uint64_t with ui32 — uint32_t would suffice. Reject.
192 EXPECT_THROW(verifyTypeCompatibility<uint64_t>(&uint32_t_),
194
195 // SIntType should fail for unsigned C++ type.
196 SIntType sint31("si31", 31);
197 EXPECT_THROW(verifyTypeCompatibility<uint32_t>(&sint31),
199}
200
201// Test struct with _ESI_ID.
202struct TestStruct {
203 static constexpr std::string_view _ESI_ID = "MyModule.TestStruct";
204 uint32_t field1;
205 uint16_t field2;
206};
207
208struct DeserializerWithESIID {
209 static constexpr std::string_view _ESI_ID = "MyModule.DeserializedStruct";
210
211 class TypeDeserializer
212 : public QueuedDecodeTypeDeserializer<DeserializerWithESIID> {
213 public:
214 using Base = QueuedDecodeTypeDeserializer<DeserializerWithESIID>;
215 using OutputCallback = Base::OutputCallback;
216 using DecodedOutputs = Base::DecodedOutputs;
217
218 explicit TypeDeserializer(OutputCallback output)
219 : Base(std::move(output)) {}
220
221 private:
222 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) override {
223 msg.reset();
224 return {};
225 }
226 };
227};
228
229TEST(TypedPortsTest, ESIIDTypeCompatibility) {
230 // Matching ID should pass.
231 StructType matchType("MyModule.TestStruct", {});
232 EXPECT_NO_THROW(verifyTypeCompatibility<TestStruct>(&matchType));
233
234 // Mismatched ID should fail.
235 StructType mismatchType("OtherModule.OtherStruct", {});
236 EXPECT_THROW(verifyTypeCompatibility<TestStruct>(&mismatchType),
238
239 // Even a non-struct type with matching ID should pass (ID comparison only).
240 UIntType uintWithMatchingID("MyModule.TestStruct", 32);
241 EXPECT_NO_THROW(verifyTypeCompatibility<TestStruct>(&uintWithMatchingID));
242}
243
244TEST(TypedPortsTest, NullPortTypeThrows) {
245 EXPECT_THROW(
246 verifyTypeCompatibility<int32_t>(static_cast<const Type *>(nullptr)),
248 EXPECT_THROW(
249 verifyTypeCompatibility<void>(static_cast<const Type *>(nullptr)),
251}
252
253// A type that is not integral and has no _ESI_ID — should hit fallback.
254struct UnknownCppType {
255 double x;
256};
257
258TEST(TypedPortsTest, FallbackThrows) {
259 UIntType uint32("ui32", 32);
260 EXPECT_THROW(verifyTypeCompatibility<UnknownCppType>(&uint32),
262}
263
264//===----------------------------------------------------------------------===//
265// TypedWritePort round-trip tests (verify MessageData encoding)
266//===----------------------------------------------------------------------===//
267
268// A minimal concrete WriteChannelPort for testing. Captures the last written
269// MessageData instead of sending it anywhere.
270class MockWritePort : public WriteChannelPort {
271public:
272 MockWritePort(const Type *type) : WriteChannelPort(type) {}
273
274 void connect(const ConnectOptions &opts = {}) override {
275 connectImpl(opts);
276 connected = true;
277 }
278 void disconnect() override { connected = false; }
279 bool isConnected() const override { return connected; }
280
281 MessageData lastWritten;
282 /// When false, tryWriteImpl() rejects writes (simulates a full buffer).
283 bool acceptTryWrites = true;
284
285protected:
286 void writeImpl(const MessageData &data) override { lastWritten = data; }
287 bool tryWriteImpl(const MessageData &data) override {
288 if (!acceptTryWrites)
289 return false;
290 lastWritten = data;
291 return true;
292 }
293
294private:
295 bool connected = false;
296};
297
298// A write port whose `tryWriteImpl()` accepts `credits` more frames. Unlike
299// `MockWritePort`, it uses the base `connect()`, so window translation works.
300class CreditedWritePort : public WriteChannelPort {
301public:
302 using WriteChannelPort::WriteChannelPort;
303
304 size_t credits = 0;
305 std::vector<MessageData> written;
306
307protected:
308 void writeImpl(const MessageData &data) override { written.push_back(data); }
309 bool tryWriteImpl(const MessageData &data) override {
310 if (credits == 0)
311 return false;
312 --credits;
313 written.push_back(data);
314 return true;
315 }
316};
317
318TEST(TypedPortsTest, TranslatedTryWriteKeepsNothingWhenRefused) {
319 UIntType u8("ui8", 8);
320 StructType into("into", {{"a", &u8}, {"b", &u8}});
321 // Two frames per message.
322 WindowType window("win", "win", &into, &into,
323 {{"f0", {{"a"}}}, {"f1", {{"b"}}}});
324 CreditedWritePort port(&window);
325 port.connect();
326 MessageData data(std::vector<uint8_t>{1, 2});
327
328 // The first frame is refused: nothing is sent or kept for a later flush.
329 EXPECT_FALSE(port.tryWrite(data));
330 EXPECT_TRUE(port.flush());
331 EXPECT_TRUE(port.written.empty());
332
333 // Only the first frame fits: the rest waits for `flush()`.
334 port.credits = 1;
335 EXPECT_TRUE(port.tryWrite(data));
336 EXPECT_EQ(port.written.size(), 1u);
337 EXPECT_FALSE(port.flush());
338 port.credits = 1;
339 EXPECT_TRUE(port.flush());
340 EXPECT_EQ(port.written.size(), 2u);
341}
342
343TEST(TypedPortsTest, TypedWritePortConnectThrowsOnMismatch) {
344 UIntType uint32("ui32", 32);
345 MockWritePort mock(&uint32);
346 TypedWritePort<int32_t> typed(mock); // int32_t expects SIntType
347 EXPECT_THROW(typed.connect(), AcceleratorMismatchError);
348}
349
350TEST(TypedPortsTest, TypedWritePortConnectSucceeds) {
351 SIntType sint31("si31", 31);
352 MockWritePort mock(&sint31);
353 TypedWritePort<int32_t> typed(mock);
354 EXPECT_NO_THROW(typed.connect());
355 EXPECT_TRUE(typed.isConnected());
356}
357
358TEST(TypedPortsTest, TypedWritePortRoundTrip) {
359 SIntType sint15("si15", 15);
360 MockWritePort mock(&sint15);
361 TypedWritePort<int16_t> typed(mock);
362 typed.connect();
363
364 int16_t val = 12345;
365 typed.write(val);
366
367 // Wire size for si15 is 2 bytes ((15+7)/8).
368 ASSERT_EQ(mock.lastWritten.getSize(), 2u);
369}
370
371TEST(TypedPortsTest, SignExtensionNonByteAligned) {
372 // Test fromMessageData sign extension for non-byte-aligned widths.
373 // si4 value -1 is wire 0x0F (4 bits: 1111). Sign bit is bit 3.
374 {
375 SIntType si4("si4", 4);
376 WireInfo wi = getWireInfo(&si4);
377 EXPECT_EQ(wi.bytes, 1u);
378 EXPECT_EQ(wi.bitWidth, 4u);
379 uint8_t wire = 0x0F; // -1 in si4
380 MessageData msg(&wire, 1);
381 int32_t val = fromMessageData<int32_t>(msg, wi);
382 EXPECT_EQ(val, -1);
383 }
384 // si4 value 7 is wire 0x07 (4 bits: 0111). Positive, no sign extension.
385 {
386 SIntType si4("si4", 4);
387 WireInfo wi = getWireInfo(&si4);
388 uint8_t wire = 0x07;
389 MessageData msg(&wire, 1);
390 int32_t val = fromMessageData<int32_t>(msg, wi);
391 EXPECT_EQ(val, 7);
392 }
393 // si22 value -1 is wire {0xFF, 0xFF, 0x3F} (22 bits all 1s).
394 // Sign bit is bit 21 = bit 5 of byte 2, mask 0x20.
395 {
396 SIntType si22("si22", 22);
397 WireInfo wi = getWireInfo(&si22);
398 EXPECT_EQ(wi.bytes, 3u);
399 uint8_t wire[3] = {0xFF, 0xFF, 0x3F};
400 MessageData msg(wire, 3);
401 int32_t val = fromMessageData<int32_t>(msg, wi);
402 EXPECT_EQ(val, -1);
403 }
404 // si22 positive value: 0x1FFFFF (all data bits 1, sign bit 0)
405 {
406 SIntType si22("si22", 22);
407 WireInfo wi = getWireInfo(&si22);
408 uint8_t wire[3] = {0xFF, 0xFF, 0x1F}; // bit 21 = 0
409 MessageData msg(wire, 3);
410 int32_t val = fromMessageData<int32_t>(msg, wi);
411 EXPECT_EQ(val, 0x1FFFFF); // 2097151
412 }
413}
414
415TEST(TypedPortsTest, TypedWritePortVoid) {
416 VoidType voidType("void");
417 MockWritePort mock(&voidType);
418 TypedWritePort<void> typed(mock);
419 EXPECT_NO_THROW(typed.connect());
420
421 typed.write();
422 ASSERT_EQ(mock.lastWritten.getSize(), 1u);
423 EXPECT_EQ(mock.lastWritten.getData()[0], 0);
424}
425
426//===----------------------------------------------------------------------===//
427// MockReadPort for TypedFunction testing
428//===----------------------------------------------------------------------===//
429
430// A minimal concrete ReadChannelPort that returns a preset response.
431class MockReadPort : public ReadChannelPort {
432public:
433 MockReadPort(const Type *type) : ReadChannelPort(type) {}
434
435 void connect(std::function<bool(MessageData)>,
436 const ConnectOptions & = {}) override {
437 mode = Mode::Callback;
438 }
439 void connect(const ConnectOptions & = {}) override { mode = Mode::Polling; }
440
441 void read(MessageData &outData) override { outData = nextResponse; }
442 std::future<MessageData> readAsync() override {
443 std::promise<MessageData> p;
444 p.set_value(nextResponse);
445 return p.get_future();
446 }
447
448 MessageData nextResponse;
449};
450
451TEST(TypedPortsTest, TypedReadPortCustomDeserializerVerifiesESIID) {
452 StructType matchType("MyModule.DeserializedStruct", {});
453 MockReadPort matching(&matchType);
455 EXPECT_NO_THROW(ok.connect());
456
457 StructType mismatchType("OtherModule.OtherStruct", {});
458 MockReadPort mismatch(&mismatchType);
460 EXPECT_THROW(bad.connect(), AcceleratorMismatchError);
461}
462
463class CallbackDrivenMockReadPort : public ReadChannelPort {
464public:
465 CallbackDrivenMockReadPort(const Type *type) : ReadChannelPort(type) {}
466
467 bool deliver(std::unique_ptr<SegmentedMessageData> msg) {
468 ++deliveryCount;
469 pending = std::move(msg);
470 return retryPending();
471 }
472
473 bool retryPending() {
474 if (!pending)
475 throw std::runtime_error(
476 "CallbackDrivenMockReadPort::retryPending with no message");
477 if (!invokeCallback(pending))
478 return false;
479 pending.reset();
480 return true;
481 }
482
483 bool hasPending() const { return static_cast<bool>(pending); }
484 size_t numActiveCallbacks() const { return activeCallbacks; }
485
486 size_t deliveryCount = 0;
487
488private:
489 std::unique_ptr<SegmentedMessageData> pending;
490};
491
492class ThrowOnCopyReadCallback {
493public:
494 explicit ThrowOnCopyReadCallback(std::shared_ptr<bool> shouldThrow)
495 : shouldThrow(std::move(shouldThrow)) {}
496
497 ThrowOnCopyReadCallback(const ThrowOnCopyReadCallback &other)
498 : shouldThrow(other.shouldThrow) {
499 if (*shouldThrow)
500 throw std::runtime_error("ThrowOnCopyReadCallback copy failure");
501 }
502
503 ThrowOnCopyReadCallback(ThrowOnCopyReadCallback &&) = default;
504 ThrowOnCopyReadCallback &operator=(const ThrowOnCopyReadCallback &) = default;
505 ThrowOnCopyReadCallback &operator=(ThrowOnCopyReadCallback &&) = default;
506
507 bool operator()(std::unique_ptr<SegmentedMessageData> &) const {
508 return true;
509 }
510
511private:
512 std::shared_ptr<bool> shouldThrow;
513};
514
515static MessageData packUint32Words(std::initializer_list<uint32_t> values) {
516 std::vector<uint8_t> bytes(values.size() * sizeof(uint32_t));
517 size_t offset = 0;
518 for (uint32_t value : values) {
519 std::memcpy(bytes.data() + offset, &value, sizeof(value));
520 offset += sizeof(value);
521 }
522 return MessageData(std::move(bytes));
523}
524
525struct BufferedSequence {
526 std::vector<uint32_t> values;
527
528 class TypeDeserializer
529 : public QueuedDecodeTypeDeserializer<BufferedSequence> {
530 public:
531 using Base = QueuedDecodeTypeDeserializer<BufferedSequence>;
532 using OutputCallback = Base::OutputCallback;
533 using DecodedOutputs = Base::DecodedOutputs;
534
535 explicit TypeDeserializer(OutputCallback output)
536 : Base(std::move(output)) {}
537
538 private:
539 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) override {
540 MessageData scratch;
541 const MessageData &flat = msg->asMessageData(scratch);
542 if (flat.getSize() % sizeof(uint32_t) != 0)
543 throw std::runtime_error(
544 "BufferedSequence::TypeDeserializer: truncated word payload");
545
546 DecodedOutputs decoded;
547 for (size_t offset = 0; offset < flat.getSize();
548 offset += sizeof(uint32_t)) {
549 uint32_t value = 0;
550 std::memcpy(&value, flat.getBytes() + offset, sizeof(value));
551 auto sequence = std::make_unique<BufferedSequence>();
552 sequence->values.push_back(value);
553 decoded.push_back(std::move(sequence));
554 }
555 msg.reset();
556 return decoded;
557 }
558 };
559};
560
561TEST(TypedPortsTest, TypedReadPortPODBackpressuresAfterOneBufferedOutput) {
562 UIntType uint32("ui32", 32);
563 CallbackDrivenMockReadPort mock(&uint32);
564
565 TypedReadPort<uint32_t> typed(mock);
566 typed.connect();
567 typed.setMaxDataQueueMsgs(1);
568
569 EXPECT_TRUE(
570 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
571 // The second raw message is consumed into the POD deserializer's single-slot
572 // typed buffer even though the polling queue is full. Backpressure shows up
573 // on the next raw message boundary.
574 EXPECT_TRUE(
575 mock.deliver(std::make_unique<MessageData>(packUint32Words({22}))));
576 EXPECT_FALSE(mock.hasPending());
577 EXPECT_FALSE(
578 mock.deliver(std::make_unique<MessageData>(packUint32Words({33}))));
579 EXPECT_TRUE(mock.hasPending());
580
581 std::unique_ptr<uint32_t> first = typed.read();
582 ASSERT_TRUE(first);
583 EXPECT_EQ(*first, 11u);
584 EXPECT_TRUE(mock.retryPending());
585 EXPECT_FALSE(mock.hasPending());
586 std::unique_ptr<uint32_t> second = typed.read();
587 ASSERT_TRUE(second);
588 EXPECT_EQ(*second, 22u);
589 std::unique_ptr<uint32_t> third = typed.read();
590 ASSERT_TRUE(third);
591 EXPECT_EQ(*third, 33u);
592}
593
594TEST(TypedPortsTest, TypedReadPortPODRetriesSameOwnedObjectOnLaterPush) {
595 UIntType uint32("ui32", 32);
596 CallbackDrivenMockReadPort mock(&uint32);
597
598 TypedReadPort<uint32_t> typed(mock);
599 const uint32_t *firstObject = nullptr;
600 size_t callbackAttempts = 0;
601
602 typed.connect([&](std::unique_ptr<uint32_t> &value) {
603 ++callbackAttempts;
604 EXPECT_TRUE(value);
605 if (callbackAttempts == 1) {
606 EXPECT_EQ(*value, 11u);
607 firstObject = value.get();
608 return false;
609 }
610 if (callbackAttempts == 2) {
611 EXPECT_EQ(*value, 11u);
612 EXPECT_EQ(value.get(), firstObject);
613 return true;
614 }
615 EXPECT_EQ(*value, 22u);
616 return true;
617 });
618
619 EXPECT_TRUE(
620 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
621 EXPECT_FALSE(mock.hasPending());
622 // A later raw push first retries the buffered typed value, then handles the
623 // new message once that buffered value is accepted.
624 EXPECT_TRUE(
625 mock.deliver(std::make_unique<MessageData>(packUint32Words({22}))));
626 EXPECT_FALSE(mock.hasPending());
627 EXPECT_EQ(callbackAttempts, 3u);
628}
629
630TEST(TypedPortsTest, ZeroWidthMessagePlaceholderAndEmpty) {
631 VoidType voidType("void");
632 CallbackDrivenMockReadPort mock(&voidType);
633
634 size_t attempts = 0;
635 mock.connect([&](std::unique_ptr<SegmentedMessageData> &msg) {
636 ++attempts;
637 EXPECT_EQ(msg->totalSize(), 0u);
638 return attempts > 1;
639 });
640
641 EXPECT_FALSE(
642 mock.deliver(std::make_unique<MessageData>(std::vector<uint8_t>{0})));
643 EXPECT_TRUE(mock.hasPending());
644 // The retained message has already had its placeholder stripped; the retry
645 // must accept it rather than reject it as malformed.
646 EXPECT_TRUE(mock.retryPending());
647 EXPECT_FALSE(mock.hasPending());
648 EXPECT_EQ(attempts, 2u);
649
650 // Transports may also send void messages without the placeholder.
651 EXPECT_TRUE(mock.deliver(std::make_unique<MessageData>()));
652 EXPECT_EQ(attempts, 3u);
653
654 EXPECT_THROW(
655 mock.deliver(std::make_unique<MessageData>(std::vector<uint8_t>{0, 0})),
656 std::runtime_error);
657 EXPECT_EQ(mock.numActiveCallbacks(), 0u);
658 mock.disconnect();
659}
660
661TEST(TypedPortsTest, TypedReadPortCustomDeserializerPokesBlockedOutput) {
662 UIntType uint32("ui32", 32);
663 CallbackDrivenMockReadPort mock(&uint32);
664
666 typed.connect();
667 typed.setMaxDataQueueMsgs(1);
668
669 EXPECT_TRUE(
670 mock.deliver(std::make_unique<MessageData>(packUint32Words({10, 20}))));
671 EXPECT_EQ(mock.deliveryCount, 1u);
672
673 std::unique_ptr<BufferedSequence> first = typed.read();
674 ASSERT_TRUE(first);
675 ASSERT_EQ(first->values.size(), 1u);
676 EXPECT_EQ(first->values[0], 10u);
677
678 std::unique_ptr<BufferedSequence> second = typed.read();
679 ASSERT_TRUE(second);
680 ASSERT_EQ(second->values.size(), 1u);
681 EXPECT_EQ(second->values[0], 20u);
682 EXPECT_EQ(mock.deliveryCount, 1u);
683}
684
685TEST(TypedPortsTest,
686 TypedReadPortCustomDeserializerConsumesMultipleFramesPerRawMessage) {
687 UIntType uint32("ui32", 32);
688 CallbackDrivenMockReadPort mock(&uint32);
689
691 typed.connect();
692
693 std::future<std::unique_ptr<BufferedSequence>> first = typed.readAsync();
694 std::future<std::unique_ptr<BufferedSequence>> second = typed.readAsync();
695 std::future<std::unique_ptr<BufferedSequence>> third = typed.readAsync();
696
697 EXPECT_TRUE(
698 mock.deliver(std::make_unique<MessageData>(packUint32Words({1, 2, 3}))));
699
700 std::unique_ptr<BufferedSequence> firstValue = first.get();
701 ASSERT_TRUE(firstValue);
702 EXPECT_EQ(firstValue->values[0], 1u);
703
704 std::unique_ptr<BufferedSequence> secondValue = second.get();
705 ASSERT_TRUE(secondValue);
706 EXPECT_EQ(secondValue->values[0], 2u);
707
708 std::unique_ptr<BufferedSequence> thirdValue = third.get();
709 ASSERT_TRUE(thirdValue);
710 EXPECT_EQ(thirdValue->values[0], 3u);
711}
712
713TEST(TypedPortsTest,
714 TypedReadPortCustomDeserializerQueuesMultiplePendingOutputs) {
715 UIntType uint32("ui32", 32);
716 CallbackDrivenMockReadPort mock(&uint32);
717
719 typed.connect();
720 typed.setMaxDataQueueMsgs(1);
721
722 EXPECT_TRUE(
723 mock.deliver(std::make_unique<MessageData>(packUint32Words({7, 8, 9}))));
724 EXPECT_EQ(mock.deliveryCount, 1u);
725
726 std::unique_ptr<BufferedSequence> first = typed.read();
727 ASSERT_TRUE(first);
728 EXPECT_EQ(first->values[0], 7u);
729
730 std::unique_ptr<BufferedSequence> second = typed.read();
731 ASSERT_TRUE(second);
732 EXPECT_EQ(second->values[0], 8u);
733
734 std::unique_ptr<BufferedSequence> third = typed.read();
735 ASSERT_TRUE(third);
736 EXPECT_EQ(third->values[0], 9u);
737 EXPECT_EQ(mock.deliveryCount, 1u);
738}
739
740struct FragmentedCoord {
741 uint32_t y;
742 uint32_t x;
743};
744static_assert(sizeof(FragmentedCoord) == 8, "Size mismatch");
745
746static std::array<uint8_t, sizeof(FragmentedCoord)> packCoordBytes(uint32_t y,
747 uint32_t x) {
748 FragmentedCoord coord{y, x};
749 std::array<uint8_t, sizeof(FragmentedCoord)> bytes{};
750 std::memcpy(bytes.data(), &coord, sizeof(coord));
751 return bytes;
752}
753
754struct FragmentedCoordBatch {
755 std::vector<FragmentedCoord> coords;
756
757 class TypeDeserializer
758 : public QueuedDecodeTypeDeserializer<FragmentedCoordBatch> {
759 public:
760 using Base = QueuedDecodeTypeDeserializer<FragmentedCoordBatch>;
761 using OutputCallback = Base::OutputCallback;
762 using DecodedOutputs = Base::DecodedOutputs;
763
764 explicit TypeDeserializer(OutputCallback output)
765 : Base(std::move(output)) {}
766
767 private:
768 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) override {
769 MessageData scratch;
770 const MessageData &flat = msg->asMessageData(scratch);
771
772 DecodedOutputs decoded;
773 const uint8_t *bytes = flat.getBytes();
774 size_t offset = 0;
775 while (offset < flat.getSize()) {
776 size_t needed = sizeof(FragmentedCoord) - partialFrameBytes.size();
777 size_t chunkSize = std::min(needed, flat.getSize() - offset);
778 partialFrameBytes.insert(partialFrameBytes.end(), bytes + offset,
779 bytes + offset + chunkSize);
780 offset += chunkSize;
781
782 if (partialFrameBytes.size() != sizeof(FragmentedCoord))
783 break;
784
785 FragmentedCoord coord;
786 std::memcpy(&coord, partialFrameBytes.data(), sizeof(coord));
787 partialFrameBytes.clear();
788
789 auto batch = std::make_unique<FragmentedCoordBatch>();
790 batch->coords.push_back(coord);
791 decoded.push_back(std::move(batch));
792 }
793
794 msg.reset();
795 return decoded;
796 }
797
798 std::vector<uint8_t> partialFrameBytes;
799 };
800};
801
802TEST(TypedPortsTest,
803 TypedReadPortCustomDeserializerConsumesSplitFramesAcrossRawMessages) {
804 UIntType uint32("ui32", 32);
805 CallbackDrivenMockReadPort mock(&uint32);
806
808 typed.connect();
809
810 std::future<std::unique_ptr<FragmentedCoordBatch>> first = typed.readAsync();
811 std::future<std::unique_ptr<FragmentedCoordBatch>> second = typed.readAsync();
812
813 std::array<uint8_t, sizeof(FragmentedCoord)> coordA = packCoordBytes(10, 20);
814 std::array<uint8_t, sizeof(FragmentedCoord)> coordB = packCoordBytes(30, 40);
815
816 std::vector<uint8_t> firstChunk(coordA.begin(), coordA.begin() + 6);
817 EXPECT_TRUE(mock.deliver(
818 std::make_unique<MessageData>(MessageData(std::move(firstChunk)))));
819
820 std::vector<uint8_t> secondChunk;
821 secondChunk.insert(secondChunk.end(), coordA.begin() + 6, coordA.end());
822 secondChunk.insert(secondChunk.end(), coordB.begin(), coordB.end());
823 EXPECT_TRUE(mock.deliver(
824 std::make_unique<MessageData>(MessageData(std::move(secondChunk)))));
825
826 std::unique_ptr<FragmentedCoordBatch> firstBatch = first.get();
827 ASSERT_TRUE(firstBatch);
828 ASSERT_EQ(firstBatch->coords.size(), 1u);
829 EXPECT_EQ(firstBatch->coords[0].y, 10u);
830 EXPECT_EQ(firstBatch->coords[0].x, 20u);
831
832 std::unique_ptr<FragmentedCoordBatch> secondBatch = second.get();
833 ASSERT_TRUE(secondBatch);
834 ASSERT_EQ(secondBatch->coords.size(), 1u);
835 EXPECT_EQ(secondBatch->coords[0].y, 30u);
836 EXPECT_EQ(secondBatch->coords[0].x, 40u);
837}
838//===----------------------------------------------------------------------===//
839// TypedFunction tests
840//===----------------------------------------------------------------------===//
841
842TEST(TypedPortsTest, TypedFunctionNullThrowsAtConnect) {
843 // Null is accepted at construction but throws at connect().
845 EXPECT_THROW(typed.connect(), AcceleratorMismatchError);
846}
847
848TEST(TypedPortsTest, TypedFunctionCallBeforeConnectThrows) {
849 // call() before connect() must throw, not dereference a null optional.
851 EXPECT_THROW(typed.call(0u).get(), std::runtime_error);
852}
853
854TEST(TypedPortsTest, TypedFunctionDoubleConnectThrows) {
855 // A second connect() on an already-connected wrapper must throw rather
856 // than silently rebuild internal state.
857 SIntType argInner("si24", 24);
858 ChannelType argChanType("channel<si24>", &argInner);
859 UIntType resultInner("ui15", 15);
860 ChannelType resultChanType("channel<ui15>", &resultInner);
861
862 BundleType::ChannelVector channels = {
863 {"arg", BundleType::Direction::To, &argChanType},
864 {"result", BundleType::Direction::From, &resultChanType},
865 };
866 BundleType bundleType("func_bundle", channels);
867
868 MockWritePort mockWrite(&argInner);
869 CallbackDrivenMockReadPort mockRead(&resultInner);
870
871 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
872 mockWrite, mockRead);
873
875 typed.connect();
876 EXPECT_THROW(typed.connect(), std::runtime_error);
877 delete func;
878}
879
880TEST(TypedPortsTest, TypedFunctionConnectVerifiesTypes) {
881 // Create channel types matching si24 arg and ui16 result.
882 SIntType argInner("si24", 24);
883 ChannelType argChanType("channel<si24>", &argInner);
884 UIntType resultInner("ui15", 15);
885 ChannelType resultChanType("channel<ui15>", &resultInner);
886
887 BundleType::ChannelVector channels = {
888 {"arg", BundleType::Direction::To, &argChanType},
889 {"result", BundleType::Direction::From, &resultChanType},
890 };
891 BundleType bundleType("func_bundle", channels);
892
893 MockWritePort mockWrite(&argInner);
894 MockReadPort mockRead(&resultInner);
895
896 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
897 mockWrite, mockRead);
898
899 // int32_t arg (signed) against si24 — should pass.
900 // uint16_t result (unsigned) against ui15 — should pass.
902 EXPECT_NO_THROW(typed.connect());
903 delete func;
904}
905
906TEST(TypedPortsTest, TypedFunctionConnectRejectsArgMismatch) {
907 UIntType argInner("ui24", 24);
908 ChannelType argChanType("channel<ui24>", &argInner);
909 UIntType resultInner("ui15", 15);
910 ChannelType resultChanType("channel<ui15>", &resultInner);
911
912 BundleType::ChannelVector channels = {
913 {"arg", BundleType::Direction::To, &argChanType},
914 {"result", BundleType::Direction::From, &resultChanType},
915 };
916 BundleType bundleType("func_bundle", channels);
917
918 MockWritePort mockWrite(&argInner);
919 MockReadPort mockRead(&resultInner);
920
921 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
922 mockWrite, mockRead);
923
924 // int32_t (signed) against UIntType — should fail at connect.
926 EXPECT_THROW(typed.connect(), AcceleratorMismatchError);
927 delete func;
928}
929
930TEST(TypedPortsTest, TypedFunctionCallRoundTrip) {
931 SIntType argInner("si24", 24);
932 ChannelType argChanType("channel<si24>", &argInner);
933 UIntType resultInner("ui15", 15);
934 ChannelType resultChanType("channel<ui15>", &resultInner);
935
936 BundleType::ChannelVector channels = {
937 {"arg", BundleType::Direction::To, &argChanType},
938 {"result", BundleType::Direction::From, &resultChanType},
939 };
940 BundleType bundleType("func_bundle", channels);
941
942 MockWritePort mockWrite(&argInner);
943 CallbackDrivenMockReadPort mockRead(&resultInner);
944
945 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
946 mockWrite, mockRead);
947
949 typed.connect();
950
951 int32_t arg = 100;
952 std::future<uint16_t> f = typed.call(arg);
953 // Deliver the response frame to satisfy the future. ui15 wire width is 2
954 // bytes so a 2-byte payload is required.
955 uint16_t expected = 42;
956 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(MessageData(
957 reinterpret_cast<const uint8_t *>(&expected), sizeof(expected)))));
958 uint16_t result = f.get();
959 EXPECT_EQ(result, 42);
960
961 // Verify the written arg matches — si24 wire size is 3 bytes.
962 ASSERT_EQ(mockWrite.lastWritten.getSize(), 3u);
963 delete func;
964}
965
966//===----------------------------------------------------------------------===//
967// SegmentedMessageData tests via TypedWritePort
968//===----------------------------------------------------------------------===//
969
970/// A minimal SegmentedMessageData for testing.
971struct TestSegmented : public SegmentedMessageData {
972#pragma pack(push, 1)
973 struct Header {
974 uint32_t a;
975 uint16_t b;
976 };
977#pragma pack(pop)
978
979 Header header;
980 std::vector<uint32_t> items;
981
982 size_t numSegments() const override { return 2; }
983 Segment segment(size_t idx) const override {
984 if (idx == 0)
985 return {reinterpret_cast<const uint8_t *>(&header), sizeof(Header)};
986 return {reinterpret_cast<const uint8_t *>(items.data()),
987 items.size() * sizeof(uint32_t)};
988 }
989};
990
991TEST(TypedPortsTest, ReadChannelPortSegmentedCallbackRetriesSameMessageObject) {
992 UIntType uint32("ui32", 32);
993 CallbackDrivenMockReadPort mock(&uint32);
994
995 uint32_t expected = 0x12345678;
996 const uint8_t *firstBytes = nullptr;
997 size_t callbackCalls = 0;
998
999 mock.connect([&](std::unique_ptr<SegmentedMessageData> &msg) -> bool {
1000 ++callbackCalls;
1001 EXPECT_EQ(msg->numSegments(), 1u);
1002
1003 auto *flat = dynamic_cast<MessageData *>(msg.get());
1004 EXPECT_NE(flat, nullptr);
1005 if (!flat)
1006 return false;
1007 EXPECT_EQ(*flat->as<uint32_t>(), expected);
1008
1009 if (callbackCalls == 1)
1010 firstBytes = flat->getBytes();
1011 else
1012 EXPECT_EQ(flat->getBytes(), firstBytes);
1013
1014 return callbackCalls == 2;
1015 });
1016
1017 EXPECT_FALSE(
1018 mock.deliver(std::make_unique<MessageData>(MessageData::from(expected))));
1019 EXPECT_TRUE(mock.hasPending());
1020 EXPECT_TRUE(mock.retryPending());
1021 EXPECT_FALSE(mock.hasPending());
1022 EXPECT_EQ(callbackCalls, 2u);
1023}
1024
1025TEST(TypedPortsTest, ReadChannelPortFlatCallbackFlattensSegmentedMessageRetry) {
1026 UIntType uint32("ui32", 32);
1027 CallbackDrivenMockReadPort mock(&uint32);
1028
1029 TestSegmented input;
1030 input.header.a = 0x12345678;
1031 input.header.b = 0xABCD;
1032 input.items = {1, 2, 3};
1033 MessageData expected = input.toMessageData();
1034
1035 size_t callbackCalls = 0;
1036 mock.connect([&](MessageData data) {
1037 ++callbackCalls;
1038 EXPECT_EQ(data.getData(), expected.getData());
1039 return callbackCalls == 2;
1040 });
1041
1042 EXPECT_FALSE(mock.deliver(std::make_unique<TestSegmented>(input)));
1043 EXPECT_TRUE(mock.hasPending());
1044 EXPECT_TRUE(mock.retryPending());
1045 EXPECT_FALSE(mock.hasPending());
1046 EXPECT_EQ(callbackCalls, 2u);
1047}
1048
1049TEST(TypedPortsTest, ReadChannelPortPollingRetriesFlattenedSegmentedMessage) {
1050 UIntType uint32("ui32", 32);
1051 CallbackDrivenMockReadPort mock(&uint32);
1052 mock.connect();
1053 mock.setMaxDataQueueMsgs(1);
1054
1055 TestSegmented firstInput;
1056 firstInput.header.a = 0xAAAA5555;
1057 firstInput.header.b = 0x1357;
1058 firstInput.items = {10};
1059 MessageData firstExpected = firstInput.toMessageData();
1060
1061 TestSegmented secondInput;
1062 secondInput.header.a = 0xDEADBEEF;
1063 secondInput.header.b = 0x2468;
1064 secondInput.items = {20, 30};
1065 MessageData secondExpected = secondInput.toMessageData();
1066
1067 EXPECT_TRUE(mock.deliver(std::make_unique<TestSegmented>(firstInput)));
1068 EXPECT_FALSE(mock.deliver(std::make_unique<TestSegmented>(secondInput)));
1069 EXPECT_TRUE(mock.hasPending());
1070
1071 MessageData firstOut;
1072 mock.read(firstOut);
1073 EXPECT_EQ(firstOut.getData(), firstExpected.getData());
1074
1075 EXPECT_TRUE(mock.retryPending());
1076 EXPECT_FALSE(mock.hasPending());
1077
1078 MessageData secondOut;
1079 mock.read(secondOut);
1080 EXPECT_EQ(secondOut.getData(), secondExpected.getData());
1081}
1082
1083TEST(TypedPortsTest, ReadChannelPortPollingReadAsyncThrowsWhenDisconnected) {
1084 UIntType uint32("ui32", 32);
1085 CallbackDrivenMockReadPort mock(&uint32);
1086
1087 EXPECT_THROW(mock.readAsync(), std::runtime_error);
1088
1089 mock.connect();
1090 std::future<MessageData> pending = mock.readAsync();
1091 mock.disconnect();
1092
1093 EXPECT_EQ(pending.wait_for(std::chrono::milliseconds(0)),
1094 std::future_status::ready);
1095 EXPECT_THROW(pending.get(), std::future_error);
1096 EXPECT_THROW(mock.readAsync(), std::runtime_error);
1097
1098 mock.connect();
1099 EXPECT_TRUE(
1100 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1101 MessageData out;
1102 mock.read(out);
1103 EXPECT_EQ(*out.as<uint32_t>(), 11u);
1104}
1105
1106TEST(TypedPortsTest, ReadChannelPortPollingConnectRejectsReconnect) {
1107 UIntType uint32("ui32", 32);
1108 CallbackDrivenMockReadPort mock(&uint32);
1109
1110 mock.connect();
1111 EXPECT_THROW(mock.connect(), std::runtime_error);
1112}
1113
1114TEST(TypedPortsTest, ReadChannelPortDisconnectRevokesCallback) {
1115 UIntType uint32("ui32", 32);
1116 CallbackDrivenMockReadPort mock(&uint32);
1117
1118 mock.connect();
1119 mock.disconnect();
1120
1121 EXPECT_FALSE(
1122 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1123 EXPECT_TRUE(mock.hasPending());
1124
1125 mock.connect();
1126 EXPECT_TRUE(mock.retryPending());
1127 EXPECT_FALSE(mock.hasPending());
1128
1129 MessageData out;
1130 mock.read(out);
1131 EXPECT_EQ(*out.as<uint32_t>(), 11u);
1132}
1133
1134TEST(TypedPortsTest, TypedReadPortDestructorDisconnectsRawPort) {
1135 UIntType uint32("ui32", 32);
1136 CallbackDrivenMockReadPort mock(&uint32);
1137
1138 {
1139 TypedReadPort<uint32_t> typed(mock);
1140 typed.connect();
1141 EXPECT_TRUE(mock.isConnected());
1142 }
1143
1144 EXPECT_FALSE(mock.isConnected());
1145 EXPECT_FALSE(
1146 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))));
1147 EXPECT_TRUE(mock.hasPending());
1148
1149 TypedReadPort<uint32_t> reconnected(mock);
1150 reconnected.connect();
1151 EXPECT_TRUE(mock.retryPending());
1152 EXPECT_FALSE(mock.hasPending());
1153
1154 std::unique_ptr<uint32_t> out = reconnected.read();
1155 ASSERT_TRUE(out);
1156 EXPECT_EQ(*out, 11u);
1157}
1158
1159TEST(TypedPortsTest,
1160 ReadChannelPortInvokeCallbackMaintainsCountOnCallbackCopyFailure) {
1161 UIntType uint32("ui32", 32);
1162 CallbackDrivenMockReadPort mock(&uint32);
1163 auto shouldThrow = std::make_shared<bool>(false);
1164
1165 mock.connect(ThrowOnCopyReadCallback(shouldThrow));
1166 *shouldThrow = true;
1167
1168 EXPECT_THROW(
1169 mock.deliver(std::make_unique<MessageData>(packUint32Words({11}))),
1170 std::runtime_error);
1171 EXPECT_EQ(mock.numActiveCallbacks(), 0u);
1172}
1173
1174TEST(TypedPortsTest, TypedWritePortSegmentedMessageData) {
1175 // Use any type — SegmentedMessageData skips type checks.
1176 UIntType uint32("ui32", 32);
1177 MockWritePort mock(&uint32);
1178
1180 typed.connect();
1181
1182 TestSegmented msg;
1183 msg.header.a = 0x12345678;
1184 msg.header.b = 0xABCD;
1185 msg.items = {1, 2, 3};
1186
1187 // write(const T&) should flatten via toMessageData().
1188 typed.write(msg);
1189
1190 // Expected: 6 bytes header + 12 bytes data = 18 bytes.
1191 EXPECT_EQ(mock.lastWritten.getSize(), 18u);
1192
1193 // Verify header bytes.
1194 const uint8_t *bytes = mock.lastWritten.getBytes();
1195 uint32_t gotA;
1196 uint16_t gotB;
1197 std::memcpy(&gotA, bytes, 4);
1198 std::memcpy(&gotB, bytes + 4, 2);
1199 EXPECT_EQ(gotA, 0x12345678u);
1200 EXPECT_EQ(gotB, 0xABCDu);
1201
1202 // Verify item bytes.
1203 uint32_t gotItems[3];
1204 std::memcpy(gotItems, bytes + 6, 12);
1205 EXPECT_EQ(gotItems[0], 1u);
1206 EXPECT_EQ(gotItems[1], 2u);
1207 EXPECT_EQ(gotItems[2], 3u);
1208}
1209
1210TEST(TypedPortsTest, WriteChannelPortTryWriteSegmented) {
1211 UIntType uint32("ui32", 32);
1212 MockWritePort mock(&uint32);
1213 mock.connect();
1214
1215 auto input = std::make_unique<TestSegmented>();
1216 input->header.a = 0x12345678;
1217 input->header.b = 0xABCD;
1218 input->items = {1, 2, 3};
1219 MessageData expected = input->toMessageData();
1220 SegmentedMessageData *raw = input.get();
1221 std::unique_ptr<SegmentedMessageData> msg = std::move(input);
1222
1223 // Rejected: the message must be left with the caller for a retry.
1224 mock.acceptTryWrites = false;
1225 EXPECT_FALSE(mock.tryWrite(msg));
1226 ASSERT_NE(msg, nullptr);
1227 EXPECT_EQ(msg.get(), raw);
1228 EXPECT_EQ(mock.lastWritten.getSize(), 0u);
1229
1230 // Accepted: ownership is taken and the flattened bytes are written.
1231 mock.acceptTryWrites = true;
1232 EXPECT_TRUE(mock.tryWrite(msg));
1233 EXPECT_EQ(msg, nullptr);
1234 EXPECT_EQ(mock.lastWritten.getData(), expected.getData());
1235
1236 std::unique_ptr<SegmentedMessageData> null;
1237 EXPECT_THROW(mock.tryWrite(null), std::runtime_error);
1238}
1239
1240TEST(TypedPortsTest, TypedWritePortTryWriteSegmentedUniquePtr) {
1241 UIntType uint32("ui32", 32);
1242 MockWritePort mock(&uint32);
1243
1245 typed.connect();
1246
1247 auto msg = std::make_unique<TestSegmented>();
1248 msg->header.a = 42;
1249 msg->header.b = 7;
1250 msg->items = {100, 200};
1251 MessageData expected = msg->toMessageData();
1252 TestSegmented *raw = msg.get();
1253
1254 mock.acceptTryWrites = false;
1255 EXPECT_FALSE(typed.tryWrite(msg));
1256 ASSERT_NE(msg, nullptr);
1257 EXPECT_EQ(msg.get(), raw);
1258 EXPECT_EQ(msg->items.size(), 2u);
1259
1260 mock.acceptTryWrites = true;
1261 EXPECT_TRUE(typed.tryWrite(msg));
1262 EXPECT_EQ(msg, nullptr);
1263 EXPECT_EQ(mock.lastWritten.getData(), expected.getData());
1264
1265 std::unique_ptr<TestSegmented> null;
1266 EXPECT_THROW(typed.tryWrite(null), std::runtime_error);
1267}
1268
1269TEST(TypedPortsTest, TypedWritePortTryWriteNonSegmentedUniquePtr) {
1270 UIntType uint32("ui32", 32);
1271 MockWritePort mock(&uint32);
1272
1273 TypedWritePort<uint32_t> typed(mock);
1274 typed.connect();
1275
1276 auto value = std::make_unique<uint32_t>(0xDEADBEEF);
1277
1278 mock.acceptTryWrites = false;
1279 EXPECT_FALSE(typed.tryWrite(value));
1280 ASSERT_NE(value, nullptr);
1281 EXPECT_EQ(*value, 0xDEADBEEFu);
1282
1283 mock.acceptTryWrites = true;
1284 EXPECT_TRUE(typed.tryWrite(value));
1285 EXPECT_EQ(value, nullptr);
1286 ASSERT_EQ(mock.lastWritten.getSize(), 4u);
1287 EXPECT_EQ(*mock.lastWritten.as<uint32_t>(), 0xDEADBEEFu);
1288}
1289
1290TEST(TypedPortsTest, TypedWritePortSegmentedNoTypeCheck) {
1291 // SegmentedMessageData type against a mismatched port type — works because
1292 // SkipTypeCheck=true bypasses verifyTypeCompatibility entirely.
1293 SIntType sint8("si8", 8);
1294 MockWritePort mock(&sint8);
1295
1297 EXPECT_NO_THROW(typed.connect());
1298
1299 TestSegmented msg;
1300 msg.header.a = 42;
1301 msg.header.b = 7;
1302 msg.items = {100};
1303
1304 typed.write(msg);
1305 // 6 bytes header + 4 bytes data = 10 bytes.
1306 EXPECT_EQ(mock.lastWritten.getSize(), 10u);
1307}
1308
1309TEST(TypedPortsTest, TypedFunctionSegmentedArg) {
1310 // Arg type is SegmentedMessageData — type check is skipped for it.
1311 // Use an arbitrary inner type for the arg channel since it won't be checked.
1312 UIntType argInner("ui32", 32);
1313 ChannelType argChanType("channel<ui32>", &argInner);
1314 UIntType resultInner("ui16", 16);
1315 ChannelType resultChanType("channel<ui16>", &resultInner);
1316
1317 BundleType::ChannelVector channels = {
1318 {"arg", BundleType::Direction::To, &argChanType},
1319 {"result", BundleType::Direction::From, &resultChanType},
1320 };
1321 BundleType bundleType("func_bundle", channels);
1322
1323 MockWritePort mockWrite(&argInner);
1324 CallbackDrivenMockReadPort mockRead(&resultInner);
1325
1326 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
1327 mockWrite, mockRead);
1328
1330 typed.connect();
1331
1332 TestSegmented arg;
1333 arg.header.a = 0xDEAD;
1334 arg.header.b = 0xBE;
1335 arg.items = {10, 20};
1336
1337 std::future<uint16_t> f = typed.call(arg);
1338 // Deliver the response frame to satisfy the call's future.
1339 uint16_t expected = 99;
1340 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(MessageData(
1341 reinterpret_cast<const uint8_t *>(&expected), sizeof(expected)))));
1342 uint16_t result = f.get();
1343 EXPECT_EQ(result, 99u);
1344
1345 // Verify the flattened arg: 6 bytes header + 8 bytes items = 14 bytes.
1346 EXPECT_EQ(mockWrite.lastWritten.getSize(), 14u);
1347
1348 const uint8_t *bytes = mockWrite.lastWritten.getBytes();
1349 uint32_t gotA;
1350 std::memcpy(&gotA, bytes, 4);
1351 EXPECT_EQ(gotA, 0xDEADu);
1352
1353 uint32_t gotItem0, gotItem1;
1354 std::memcpy(&gotItem0, bytes + 6, 4);
1355 std::memcpy(&gotItem1, bytes + 10, 4);
1356 EXPECT_EQ(gotItem0, 10u);
1357 EXPECT_EQ(gotItem1, 20u);
1358
1359 delete func;
1360}
1361
1362// A plain struct without _ESI_ID — not integral, not void, not bool.
1363struct UnrecognizedCppType {
1364 double x;
1365 double y;
1366};
1367
1368TEST(TypedPortsTest, VerifyTypeCompatibilityThrowsForUnsupportedType) {
1369 UIntType uint32("ui32", 32);
1372
1373 SIntType sint16("si16", 16);
1376}
1377
1378//===----------------------------------------------------------------------===//
1379// TypedFunction custom-deserializer tests
1380//===----------------------------------------------------------------------===//
1381
1382// Simple TypeDeserializer that decodes a single uint32 from one frame and
1383// emits exactly one OneWord value per push. Used to exercise the typical
1384// 1-frame-in / 1-typed-value-out custom path.
1385//
1386// Implements the standard backpressure/retry contract: a decoded `OneWord`
1387// is buffered until the output callback accepts it; only then is the raw
1388// message consumed. If `output()` returns false, the same raw message will
1389// be retried later, and a follow-up `poke()` retries delivery of the
1390// already-decoded value without re-decoding.
1391struct OneWord {
1392 uint32_t value;
1393
1394 class TypeDeserializer {
1395 public:
1396 using OutputCallback = detail::TypedReadOwnedCallback<OneWord>;
1397
1398 explicit TypeDeserializer(OutputCallback output)
1399 : output(std::move(output)) {}
1400
1401 bool push(std::unique_ptr<SegmentedMessageData> &msg) {
1402 // First, try to flush any previously-decoded value blocked on output.
1403 if (pending) {
1404 if (!output(pending))
1405 return false;
1406 pending.reset();
1407 }
1408
1409 MessageData scratch;
1410 const MessageData &flat = msg->asMessageData(scratch);
1411 if (flat.getSize() != sizeof(uint32_t))
1412 throw std::runtime_error("OneWord: bad size");
1413 pending = std::make_unique<OneWord>();
1414 std::memcpy(&pending->value, flat.getBytes(), sizeof(uint32_t));
1415 // Raw message is consumed regardless of whether the typed output is
1416 // immediately accepted.
1417 msg.reset();
1418 if (output(pending))
1419 pending.reset();
1420 return true;
1421 }
1422
1423 bool poke() {
1424 if (pending && output(pending)) {
1425 pending.reset();
1426 return true;
1427 }
1428 return false;
1429 }
1430
1431 private:
1432 OutputCallback output;
1433 std::unique_ptr<OneWord> pending;
1434 };
1435};
1436
1437TEST(TypedPortsTest, TypedFunctionCustomDeserializerSingleFrame) {
1438 UIntType argInner("ui32", 32);
1439 ChannelType argChanType("channel<ui32>", &argInner);
1440 UIntType resultInner("ui32", 32);
1441 ChannelType resultChanType("channel<ui32>", &resultInner);
1442
1443 BundleType::ChannelVector channels = {
1444 {"arg", BundleType::Direction::To, &argChanType},
1445 {"result", BundleType::Direction::From, &resultChanType},
1446 };
1447 BundleType bundleType("func_bundle", channels);
1448
1449 MockWritePort mockWrite(&argInner);
1450 CallbackDrivenMockReadPort mockRead(&resultInner);
1451
1452 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
1453 mockWrite, mockRead);
1454
1456 typed.connect();
1457
1458 std::future<OneWord> f = typed.call(0u);
1459 // Deliver one frame containing a single uint32; the deserializer produces
1460 // one OneWord which fulfills the call's pending future.
1461 uint32_t expected = 0xCAFE;
1462 EXPECT_TRUE(mockRead.deliver(std::make_unique<MessageData>(MessageData(
1463 reinterpret_cast<const uint8_t *>(&expected), sizeof(expected)))));
1464
1465 OneWord result = f.get();
1466 EXPECT_EQ(result.value, expected);
1467
1468 delete func;
1469}
1470
1471TEST(TypedPortsTest, TypedFunctionCustomDeserializerReadsMultipleFrames) {
1472 // FragmentedCoordBatch's TypeDeserializer emits one batch per 8-byte
1473 // FragmentedCoord. By feeding partial frames across multiple raw messages,
1474 // we exercise the deserializer's persistent partial-buffer state across
1475 // raw callback invocations.
1476 UIntType argInner("ui32", 32);
1477 ChannelType argChanType("channel<ui32>", &argInner);
1478 UIntType resultInner("ui32", 32);
1479 ChannelType resultChanType("channel<ui32>", &resultInner);
1480
1481 BundleType::ChannelVector channels = {
1482 {"arg", BundleType::Direction::To, &argChanType},
1483 {"result", BundleType::Direction::From, &resultChanType},
1484 };
1485 BundleType bundleType("func_bundle", channels);
1486
1487 MockWritePort mockWrite(&argInner);
1488 CallbackDrivenMockReadPort mockRead(&resultInner);
1489
1490 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
1491 mockWrite, mockRead);
1492
1494 typed.connect();
1495
1496 std::future<FragmentedCoordBatch> f = typed.call(0u);
1497
1498 // Split a single 8-byte FragmentedCoord across two raw frames.
1499 std::array<uint8_t, sizeof(FragmentedCoord)> coordBytes =
1500 packCoordBytes(/*y=*/55, /*x=*/77);
1501 std::vector<uint8_t> firstChunk(coordBytes.begin(), coordBytes.begin() + 6);
1502 std::vector<uint8_t> secondChunk(coordBytes.begin() + 6, coordBytes.end());
1503 EXPECT_TRUE(
1504 mockRead.deliver(std::make_unique<MessageData>(std::move(firstChunk))));
1505 EXPECT_TRUE(
1506 mockRead.deliver(std::make_unique<MessageData>(std::move(secondChunk))));
1507
1508 FragmentedCoordBatch batch = f.get();
1509 ASSERT_EQ(batch.coords.size(), 1u);
1510 EXPECT_EQ(batch.coords[0].y, 55u);
1511 EXPECT_EQ(batch.coords[0].x, 77u);
1512
1513 delete func;
1514}
1515
1516TEST(TypedPortsTest, TypedFunctionCustomDeserializerSkipsResultTypeCheck) {
1517 // OneWord has no _ESI_ID, so the result-side type check should be skipped
1518 // and we should be able to connect against an arbitrarily-typed result
1519 // channel without a thrown AcceleratorMismatchError.
1520 UIntType argInner("ui32", 32);
1521 ChannelType argChanType("channel<ui32>", &argInner);
1522 // Use a wildly mismatched result type to prove the check is skipped.
1523 StructType resultInner("Anything", {});
1524 ChannelType resultChanType("channel<Anything>", &resultInner);
1525
1526 BundleType::ChannelVector channels = {
1527 {"arg", BundleType::Direction::To, &argChanType},
1528 {"result", BundleType::Direction::From, &resultChanType},
1529 };
1530 BundleType bundleType("func_bundle", channels);
1531
1532 MockWritePort mockWrite(&argInner);
1533 CallbackDrivenMockReadPort mockRead(&resultInner);
1534
1535 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
1536 mockWrite, mockRead);
1537
1539 EXPECT_NO_THROW(typed.connect());
1540
1541 delete func;
1542}
1543
1544TEST(TypedPortsTest, TypedFunctionPipelinedCallsGetOutOfOrder) {
1545 // Two pipelined calls, each with a multi-frame response decoded by the
1546 // shared deserializer. Even when the second future's get() is called
1547 // before the first, each future must yield its own call's result -- not
1548 // the other call's frames. This exercises the FIFO contract of the
1549 // TypedReadPort polling buffer that backs `call()`.
1550 UIntType argInner("ui32", 32);
1551 ChannelType argChanType("channel<ui32>", &argInner);
1552 UIntType resultInner("ui32", 32);
1553 ChannelType resultChanType("channel<ui32>", &resultInner);
1554
1555 BundleType::ChannelVector channels = {
1556 {"arg", BundleType::Direction::To, &argChanType},
1557 {"result", BundleType::Direction::From, &resultChanType},
1558 };
1559 BundleType bundleType("func_bundle", channels);
1560
1561 MockWritePort mockWrite(&argInner);
1562 CallbackDrivenMockReadPort mockRead(&resultInner);
1563
1564 auto *func = services::FuncService::Function::get(AppID("test"), &bundleType,
1565 mockWrite, mockRead);
1566
1568 typed.connect();
1569
1570 // Issue two calls before any frames arrive; futures reserve slots in the
1571 // polling buffer in call FIFO order.
1572 std::future<FragmentedCoordBatch> f1 = typed.call(0u);
1573 std::future<FragmentedCoordBatch> f2 = typed.call(0u);
1574
1575 auto deliverCoord = [&](uint32_t y, uint32_t x) {
1576 auto bytes = packCoordBytes(y, x);
1577 std::vector<uint8_t> first(bytes.begin(), bytes.begin() + 6);
1578 std::vector<uint8_t> second(bytes.begin() + 6, bytes.end());
1579 EXPECT_TRUE(
1580 mockRead.deliver(std::make_unique<MessageData>(std::move(first))));
1581 EXPECT_TRUE(
1582 mockRead.deliver(std::make_unique<MessageData>(std::move(second))));
1583 };
1584 deliverCoord(/*y=*/11, /*x=*/22); // call 1's response
1585 deliverCoord(/*y=*/33, /*x=*/44); // call 2's response
1586
1587 // Intentionally retrieve the second call's result first.
1588 FragmentedCoordBatch r2 = f2.get();
1589 ASSERT_EQ(r2.coords.size(), 1u);
1590 EXPECT_EQ(r2.coords[0].y, 33u);
1591 EXPECT_EQ(r2.coords[0].x, 44u);
1592
1593 FragmentedCoordBatch r1 = f1.get();
1594 ASSERT_EQ(r1.coords.size(), 1u);
1595 EXPECT_EQ(r1.coords[0].y, 11u);
1596 EXPECT_EQ(r1.coords[0].x, 22u);
1597
1598 delete func;
1599}
1600
1601} // namespace
Arrays have a compile time specified (static) size and an element type.
Definition Types.h:301
Bits are just an array of bits.
Definition Types.h:224
Bundles represent a collection of channels.
Definition Types.h:104
std::vector< std::tuple< std::string, Direction, const Type * > > ChannelVector
Definition Types.h:108
Channels are the basic communication primitives.
Definition Types.h:125
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
const std::vector< uint8_t > & getData() const
Get the data as a vector of bytes.
Definition Common.h:219
const uint8_t * getBytes() const
Definition Common.h:216
const T * as() const
Cast to a type.
Definition Common.h:240
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:230
static MessageData from(T &t)
Cast from a type to its raw bytes.
Definition Common.h:250
detail::TypedReadOwnedCallback< DeserializerWithESIID > OutputCallback
Definition TypedPorts.h:232
std::vector< std::unique_ptr< DeserializerWithESIID > > DecodedOutputs
Definition TypedPorts.h:233
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
Signed integer.
Definition Types.h:242
Abstract multi-segment message.
Definition Common.h:151
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Definition Common.cpp:62
Structs are an ordered collection of fields, each with a name and a type.
Definition Types.h:264
Type aliases provide a named type which forwards to an inner type.
Definition Types.h:166
Root class of the ESI type system.
Definition Types.h:36
Strongly typed wrapper around a raw read channel.
Definition TypedPorts.h:798
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
Windows represent a fixed-size sliding window over a stream of data.
Definition Types.h:334
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
static Function * get(AppID id, BundleType *type, WriteChannelPort &arg, ReadChannelPort &result)
Definition Services.cpp:308
connect(destination, source)
Definition support.py:39
Definition esi.py:1
void verifyTypeCompatibility(const Type *portType)
Definition TypedPorts.h:447
WireInfo getWireInfo(const Type *portType)
Definition TypedPorts.h:70
const T * getUnwrappedAs(const Type *type)
Unwrap aliases and channels, then cast the payload to T.
Definition Types.h:203
T fromMessageData(const MessageData &msg, WireInfo wi)
Unpack a MessageData into a C++ integral value with the given wire info.
Definition TypedPorts.h:103
const Type * unwrapTypeAlias(const Type *type)
Unwrap TypeAliasType (possibly recursively) to get the underlying type.
Definition Types.h:193
read(addr)
Definition xrt_cosim.py:23
Compute the wire byte count for a port type.
Definition TypedPorts.h:65
size_t bitWidth
Definition TypedPorts.h:67