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