Nektar++
Loading...
Searching...
No Matches
TestSharedIdResolvers.cpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: TestSharedIdResolvers.cpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description: Unit tests for the shared-id rendezvous and plan logic,
32// driven over an in-memory transport.
33//
34///////////////////////////////////////////////////////////////////////////////
35
36// Validates the real ConnectivityResolver, SharedPayloadResolver and
37// SharedIdPlan logic (hash bucketing, sharer discovery, reply, and the
38// persistent fold) without MPI, by running P instances on P threads that share
39// an in-memory transport. The transport is barrier synchronised so each
40// collective Exchange lines up across threads, exactly as MPI would. Results
41// are checked against a brute-force oracle.
42//
43// Note: crystal-router *routing* is validated separately, in
44// TestCrystalRouter.cpp. Since any correct transport delivers the same
45// messages, a direct in-memory delivery here fully exercises the resolver logic
46// on top. The real MPI transports are covered by
47// SharedIdResolversMPITest.cpp.
48
50
51#include <boost/test/unit_test.hpp>
52
53#include <algorithm>
54#include <atomic>
55#include <condition_variable>
56#include <cstdint>
57#include <functional>
58#include <map>
59#include <memory>
60#include <mutex>
61#include <random>
62#include <sstream>
63#include <string>
64#include <thread>
65#include <utility>
66#include <vector>
67
68namespace Nektar::UnitTests
69{
70
71using namespace Nektar::LibUtilities;
72
73namespace
74{
75
76// A reusable barrier for `n` participating threads.
77class Barrier
78{
79public:
80 explicit Barrier(int n) : m_n(n), m_count(0), m_gen(0)
81 {
82 }
83
84 void Wait()
85 {
86 std::unique_lock<std::mutex> lk(m_mtx);
87 const int gen = m_gen;
88 if (++m_count == m_n)
89 {
90 m_count = 0;
91 ++m_gen;
92 m_cv.notify_all();
93 }
94 else
95 {
96 m_cv.wait(lk, [&] { return gen != m_gen; });
97 }
98 }
99
100private:
101 std::mutex m_mtx;
102 std::condition_variable m_cv;
104};
105
106// Shared switch backing all in-memory transports. Direct delivery: every
107// outbound message is placed in its destination's inbox. Collective per round.
108class InMemorySwitch
109{
110public:
111 explicit InMemorySwitch(int np)
112 : m_np(np), m_barrier(np), m_outbox(np), m_inbox(np), m_sorted(true)
113 {
114 }
115
116 void Exchange(int rank, std::vector<RoutedMessage> &outbound,
117 std::vector<RoutedMessage> &inbound)
118 {
119 m_outbox[rank] = std::move(outbound);
120 m_barrier.Wait();
121
122 if (rank == 0)
123 {
124 for (auto &box : m_inbox)
125 {
126 box.clear();
127 }
128 for (int r = 0; r < m_np; ++r)
129 {
130 for (auto &m : m_outbox[r])
131 {
133 d.src = r;
134 d.dest = m.dest;
135 d.bytes = std::move(m.bytes);
136 m_inbox[m.dest].push_back(std::move(d));
137 }
138 }
139 }
140 m_barrier.Wait();
141
142 inbound = std::move(m_inbox[rank]);
143
144 // ITransport requires inbound sorted by ascending src (stable within a
145 // source). The delivery loop above already produces that order; record
146 // a violation so this fake can't silently drift from the contract the
147 // resolvers rely on for reproducible reductions. (Checked on the test
148 // thread rather than asserted here: Boost.Test's assertion macros are
149 // not thread safe.)
150 if (!std::is_sorted(inbound.begin(), inbound.end(),
151 [](const RoutedMessage &a, const RoutedMessage &b) {
152 return a.src < b.src;
153 }))
154 {
155 m_sorted = false;
156 }
157
158 m_barrier.Wait(); // ensure all read before next round reuses buffers
159
160 // Contract: Exchange() consumes outbound.
161 outbound.clear();
162 }
163
164 int Np() const
165 {
166 return m_np;
167 }
168
169 /// False if any Exchange() delivered an inbox that was not sorted by src.
170 bool InboundWasSorted() const
171 {
172 return m_sorted;
173 }
174
175private:
176 int m_np;
177 Barrier m_barrier;
178 std::vector<std::vector<RoutedMessage>> m_outbox;
179 std::vector<std::vector<RoutedMessage>> m_inbox;
180 std::atomic<bool> m_sorted;
181};
182
183class InMemoryTransport : public ITransport
184{
185public:
186 InMemoryTransport(InMemorySwitch &sw, int rank) : m_sw(sw), m_rank(rank)
187 {
188 }
189
190 void Exchange(std::vector<RoutedMessage> &outbound,
191 std::vector<RoutedMessage> &inbound) override
192 {
193 m_sw.Exchange(m_rank, outbound, inbound);
194 }
195 int Rank() const override
196 {
197 return m_rank;
198 }
199 int Size() const override
200 {
201 return m_sw.Np();
202 }
203 CommSharedPtr Comm() const override
204 {
205 return CommSharedPtr();
206 }
207
208private:
209 InMemorySwitch &m_sw;
211};
212
213// The registrations we hand to each rank, plus the oracle derived from them.
214struct Workload
215{
216 // registrations[rank] = list of (id, order)
217 std::vector<std::vector<std::pair<int64_t, int>>> registrations;
218 // oracle: id -> (max order, sorted unique set of contributing ranks)
219 std::map<int64_t, int> maxOrder;
220 std::map<int64_t, std::vector<int>> sharers;
221};
222
223/**
224 * @brief Build a workload that mirrors the adjacency patterns a real mesh
225 * produces: ring edges, a multi-rank corner, a periodic pair, purely local
226 * entities and a duplicate registration.
227 */
228Workload MakeWorkload(int np, std::mt19937 &rng)
229{
230 Workload w;
231 w.registrations.resize(np);
232
233 auto addReg = [&](int rank, int64_t id, int order) {
234 w.registrations[rank].emplace_back(id, order);
235 auto it = w.maxOrder.find(id);
236 w.maxOrder[id] =
237 (it == w.maxOrder.end()) ? order : std::max(it->second, order);
238 w.sharers[id].push_back(rank);
239 };
240
241 std::uniform_int_distribution<int> orderDist(1, 15);
242
243 // 1. Ring edges: rank r and rank (r+1)%np share edge id 1000 + r.
244 // Both endpoints register with independent orders.
245 for (int r = 0; r < np; ++r)
246 {
247 const int64_t edge = 1000 + r;
248 addReg(r, edge, orderDist(rng));
249 addReg((r + 1) % np, edge, orderDist(rng));
250 }
251
252 // 2. A shared "corner" vertex touched by several ranks (multi-rank sharing,
253 // like a vertex-only connection in 3D). Up to min(np, 8) ranks.
254 const int64_t corner = 500000;
255 const int nCorner = std::min(np, 8);
256 for (int r = 0; r < nCorner; ++r)
257 {
258 addReg(r, corner, orderDist(rng));
259 }
260
261 // 3. A periodic pair: canonicalised to the same id, touched by rank 0 and
262 // rank np-1 (the "wrap" faces). Trivial when np == 1.
263 const int64_t periodic = 900000;
264 addReg(0, periodic, orderDist(rng));
265 if (np > 1)
266 {
267 addReg(np - 1, periodic, orderDist(rng));
268 }
269
270 // 4. Purely local entities (single sharer) to check the degenerate case.
271 for (int r = 0; r < np; ++r)
272 {
273 addReg(r, 2000000 + r, orderDist(rng));
274 }
275
276 // 5. A rank that registers the same id twice (duplicate contributions).
277 addReg(0, 3000000, orderDist(rng));
278 addReg(0, 3000000, orderDist(rng));
279
280 for (auto &kv : w.sharers)
281 {
282 // GetSharers() returns ascending, duplicate-free ranks: a rank that
283 // registers the same id twice (id 3000000 above, and edge 1000 when
284 // np == 1) appears once. The oracle must match.
285 std::sort(kv.second.begin(), kv.second.end());
286 kv.second.erase(std::unique(kv.second.begin(), kv.second.end()),
287 kv.second.end());
288 }
289 return w;
290}
291
292/// A single mismatch found while checking one rank's resolver output.
293struct Failure
294{
295 bool failed = false;
296 std::string message;
297};
298
299/// Oracle for the payload and plan tests, derived from the same Workload.
300struct PlanOracle
301{
302 std::map<int64_t, double> sum; // id -> sum of contributions
303 std::map<int64_t, std::map<int, int>> mult; // id -> rank -> #registrations
304 std::map<int64_t, bool> anyHigh; // id -> any contribution > 7
305};
306
307PlanOracle MakePlanOracle(const Workload &w)
308{
309 PlanOracle o;
310 for (size_t r = 0; r < w.registrations.size(); ++r)
311 {
312 for (auto &pr : w.registrations[r])
313 {
314 o.sum[pr.first] += pr.second;
315 o.mult[pr.first][static_cast<int>(r)]++;
316 o.anyHigh[pr.first] = o.anyHigh[pr.first] || (pr.second > 7);
317 }
318 }
319 return o;
320}
321
322/// A payload that identifies its origin exactly.
323struct Tag
324{
326 int rank;
327 int slot;
328};
329
330/// The distinct ids rank @p rank registered, ascending -- what a caller hands
331/// ConnectivityResolver, and the order it answers in.
332std::vector<int64_t> DistinctIds(const Workload &w, int rank)
333{
334 std::vector<int64_t> ids;
335 for (auto &pr : w.registrations[rank])
336 {
337 ids.push_back(pr.first);
338 }
339 std::sort(ids.begin(), ids.end());
340 ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
341 return ids;
342}
343
344/**
345 * @brief Check rank @p rank's one-shot resolvers against the oracle.
346 *
347 * Runs on a worker thread, so it records failures into a per-rank slot rather
348 * than calling Boost.Test macros (which are not thread safe); the caller
349 * reports them once the threads have joined. Every collective Resolve() is
350 * issued before any check runs, so a mismatch on one rank returns without
351 * stranding the others on the in-memory transport's barrier.
352 */
353void CheckOneShotRank(int rank, const Workload &w, const PlanOracle &o,
354 InMemorySwitch &sw, Failure &out)
355{
356 auto fail = [&](const std::string &msg) {
357 if (!out.failed)
358 {
359 out.failed = true;
360 out.message = "rank " + std::to_string(rank) + ": " + msg;
361 }
362 };
363
364 auto transport = std::make_shared<InMemoryTransport>(sw, rank);
365 const auto &regs = w.registrations[rank];
366 const std::vector<int64_t> ids = DistinctIds(w, rank);
367
368 // Discovery alone.
369 ConnectivityResolver cr(transport);
370 cr.Reserve(ids.size());
371 cr.RegisterKeys(ids);
372 cr.Resolve();
373
374 // Every sharer's raw payload, keyed by id.
375 SharedPayloadResolver<Tag> sp(transport);
376 sp.Reserve(regs.size());
377 for (size_t i = 0; i < regs.size(); ++i)
378 {
379 sp.Register(regs[i].first,
380 Tag{regs[i].first, rank, static_cast<int>(i)});
381 }
382 sp.Resolve();
383
384 // bool payloads are held as char internally (std::vector<bool> has no
385 // data()), so they get their own pass through the same machinery.
386 SharedPayloadResolver<bool> sb(transport);
387 sb.Reserve(regs.size());
388 for (auto &pr : regs)
389 {
390 sb.Register(pr.first, pr.second > 7);
391 }
392 sb.Resolve();
393
394 // ---- no more collectives past this point ----
395
396 if (cr.NumResolved() != ids.size())
397 {
398 fail("ConnectivityResolver resolved " +
399 std::to_string(cr.NumResolved()) + " ids, registered " +
400 std::to_string(ids.size()));
401 return;
402 }
403 for (size_t u = 0; u < cr.NumResolved(); ++u)
404 {
405 const int64_t id = cr.ResolvedId(u);
406 if (id != ids[u])
407 {
408 fail("ConnectivityResolver: ids not returned ascending");
409 return;
410 }
411 // Do NOT sort: ascending order and absence of duplicates are part of
412 // the SharersAt() contract, so compare as returned.
413 const ConnectivityResolver::SharerView sh = cr.SharersAt(u);
414 const std::vector<int> got(sh.begin(), sh.end());
415 if (!std::is_sorted(got.begin(), got.end()) ||
416 std::adjacent_find(got.begin(), got.end()) != got.end())
417 {
418 fail("id " + std::to_string(id) + " sharers not sorted/unique");
419 return;
420 }
421 if (got != w.sharers.at(id))
422 {
423 fail("id " + std::to_string(id) + " sharer mismatch");
424 return;
425 }
426 if (cr.SharersOf(id).begin() != sh.begin())
427 {
428 fail("SharersOf disagrees with SharersAt for id " +
429 std::to_string(id));
430 return;
431 }
432 }
433
434 for (int64_t id : ids)
435 {
436 if (!sp.Knows(id) || !sb.Knows(id))
437 {
438 fail("missing id " + std::to_string(id));
439 return;
440 }
441
442 // One entry per (sharer, registration), in unspecified order.
443 std::map<int, int> count;
444 bool anyHigh = false;
445 for (auto &entry : sp.GetSharedPayloads(id))
446 {
447 if (entry.second.id != id || entry.second.rank != entry.first)
448 {
449 fail("misrouted payload for id " + std::to_string(id));
450 return;
451 }
452 count[entry.first]++;
453 }
454 if (count != o.mult.at(id))
455 {
456 fail("wrong payload multiplicities for id " + std::to_string(id));
457 return;
458 }
459 for (auto &entry : sb.GetSharedPayloads(id))
460 {
461 anyHigh = anyHigh || entry.second;
462 }
463 if (anyHigh != o.anyHigh.at(id))
464 {
465 fail("SharedPayloadResolver<bool> wrong for id " +
466 std::to_string(id));
467 return;
468 }
469
470 std::vector<int> ranks = sp.GetSharers(id);
471 std::sort(ranks.begin(), ranks.end());
472 ranks.erase(std::unique(ranks.begin(), ranks.end()), ranks.end());
473 if (ranks != w.sharers.at(id))
474 {
475 fail("payload sharer mismatch for id " + std::to_string(id));
476 return;
477 }
478 }
479}
480
481/**
482 * @brief Run one round of one-shot resolves over @p np simulated ranks and
483 * check every rank's answer against the oracle.
484 */
485void TrialForNp(int np, std::mt19937 &rng)
486{
487 const Workload w = MakeWorkload(np, rng);
488 const PlanOracle o = MakePlanOracle(w);
489 InMemorySwitch sw(np);
490
491 std::vector<Failure> failures(np);
492
493 std::vector<std::thread> threads;
494 threads.reserve(np);
495 for (int r = 0; r < np; ++r)
496 {
497 threads.emplace_back(
498 [&, r] { CheckOneShotRank(r, w, o, sw, failures[r]); });
499 }
500 for (auto &t : threads)
501 {
502 t.join();
503 }
504
505 BOOST_REQUIRE_MESSAGE(sw.InboundWasSorted(),
506 "InMemorySwitch: inbound not sorted by src");
507
508 for (auto &f : failures)
509 {
510 BOOST_REQUIRE_MESSAGE(!f.failed, f.message);
511 }
512}
513
514} // namespace
515
516/**
517 * @brief The one-shot resolvers agree with a brute-force oracle on the sharer
518 * set and on every sharer's raw payload, across a spread of rank counts.
519 *
520 * The rank counts deliberately straddle powers of two, since the rendezvous
521 * bucketing and the transports beneath it are where odd splits bite.
522 */
523BOOST_AUTO_TEST_CASE(TestOneShotResolversAgainstOracle)
524{
525 std::mt19937 rng(424242);
526
527 const std::vector<int> npList = {1, 2, 3, 4, 5, 6, 7, 8, 9,
528 13, 16, 17, 31, 32, 33, 47, 64, 65};
529
530 for (int np : npList)
531 {
532 BOOST_TEST_CONTEXT("np = " << np)
533 {
534 for (int trial = 0; trial < 8; ++trial)
535 {
536 TrialForNp(np, rng);
537 }
538 }
539 }
540}
541
542// ---------------------------------------------------------------------------
543// Persistent layer: SharedIdPlan, and SharedPayloadResolver's Setup() mode.
544// Same threads-as-ranks harness, eTransport backend (the only one that runs
545// without a real Comm).
546// ---------------------------------------------------------------------------
547
548namespace
549{
550
551/// The slot array a rank hands its plan: its registrations in order, with an
552/// ignored slot after every third to exercise SharedIdPlan::kIgnore.
553/// @p regOfSlot maps each slot back to its registration, or -1.
554std::vector<int64_t> PlanSlots(const Workload &w, int rank,
555 std::vector<int> &regOfSlot)
556{
557 std::vector<int64_t> ids;
558 regOfSlot.clear();
559 const auto &regs = w.registrations[rank];
560 for (size_t i = 0; i < regs.size(); ++i)
561 {
562 ids.push_back(regs[i].first);
563 regOfSlot.push_back(static_cast<int>(i));
564 if (i % 3 == 2)
565 {
566 ids.push_back(SharedIdPlan::kIgnore);
567 regOfSlot.push_back(-1);
568 }
569 }
570 return ids;
571}
572
573/// What one rank's plan delivered, for cross-rank checks after joining.
574struct PlanRecord
575{
576 Failure failure;
577 /// Whether this rank's plan took the one-slot-per-id fast path.
578 bool fastPath = false;
579 /// Ids whose UniqueMask() bit is set on this rank.
580 std::vector<int64_t> maskedIds;
581 /// Per id, the (rank, slot) list ExchangePayloads() delivered.
582 std::map<int64_t, std::vector<std::pair<int, int>>> payloads;
583};
584
585void CheckPlanRank(int rank, const Workload &w, const PlanOracle &o,
586 InMemorySwitch &sw, PlanRecord &rec)
587{
588 auto fail = [&](const std::string &msg) {
589 if (!rec.failure.failed)
590 {
591 rec.failure.failed = true;
592 rec.failure.message = "rank " + std::to_string(rank) + ": " + msg;
593 }
594 };
595
596 auto transport = std::make_shared<InMemoryTransport>(sw, rank);
597 const auto &regs = w.registrations[rank];
598 std::vector<int> regOfSlot;
599 const std::vector<int64_t> ids = PlanSlots(w, rank, regOfSlot);
600
601 SharedIdPlan plan(transport, ids, ExchangeBackend::eTransport);
602 rec.fastPath = plan.UsesSingleSlotFastPath();
603
604 // Gather(+), twice: every live slot holds the global sum; ignored slots
605 // are untouched. The second pass proves the plan replays.
606 for (int round = 0; round < 2; ++round)
607 {
608 std::vector<double> vals(ids.size(), -1.0);
609 for (size_t s = 0; s < ids.size(); ++s)
610 {
611 if (regOfSlot[s] >= 0)
612 {
613 vals[s] = regs[regOfSlot[s]].second;
614 }
615 }
616 plan.Gather(vals.data(), std::plus<double>{});
617 for (size_t s = 0; s < ids.size(); ++s)
618 {
619 const double expect = regOfSlot[s] < 0 ? -1.0 : o.sum.at(ids[s]);
620 if (vals[s] != expect)
621 {
622 fail("Gather: slot " + std::to_string(s) + " got " +
623 std::to_string(vals[s]) + ", expected " +
624 std::to_string(expect));
625 return;
626 }
627 }
628 }
629
630 // Every slot past ActiveSlotBound() must be a single, unshared id: the
631 // guarantee that lets a caller gather a shorter array.
632 const std::vector<int> &s2u = plan.SlotToUnique();
633 for (size_t s = plan.ActiveSlotBound(); s < ids.size(); ++s)
634 {
635 const int u = s2u[s];
636 if (u >= 0 &&
637 (plan.IsShared(u) || std::count(s2u.begin(), s2u.end(), u) > 1))
638 {
639 fail("slot " + std::to_string(s) +
640 " lies past ActiveSlotBound() but is shared or repeated");
641 return;
642 }
643 }
644
645 // Reduce(max) into per-unique results, leaving its input alone.
646 std::vector<int> ord(ids.size(), 0);
647 for (size_t s = 0; s < ids.size(); ++s)
648 {
649 if (regOfSlot[s] >= 0)
650 {
651 ord[s] = regs[regOfSlot[s]].second;
652 }
653 }
654 const std::vector<int> ordBefore = ord;
655 std::vector<int> uniq(plan.NumUnique());
656 plan.Reduce(ord.data(), uniq.data(),
657 [](int a, int b) { return std::max(a, b); });
658 if (ord != ordBefore)
659 {
660 fail("Reduce modified its input");
661 return;
662 }
663 for (size_t u = 0; u < plan.NumUnique(); ++u)
664 {
665 const int64_t id = plan.UniqueIds()[u];
666 if (uniq[u] != w.maxOrder.at(id))
667 {
668 fail("Reduce: id " + std::to_string(id) + " wrong max");
669 return;
670 }
671 if (plan.GetSharers(u) != w.sharers.at(id))
672 {
673 fail("plan sharers wrong for id " + std::to_string(id));
674 return;
675 }
676 }
677
678 // UniqueMask: recorded here, counted across ranks after the join.
679 const std::vector<int> mask = plan.UniqueMask();
680 for (size_t s = 0; s < ids.size(); ++s)
681 {
682 if (mask[s])
683 {
684 if (regOfSlot[s] < 0)
685 {
686 fail("UniqueMask set on an ignored slot");
687 return;
688 }
689 rec.maskedIds.push_back(ids[s]);
690 }
691 }
692
693 // Payload exchange: every sharer's every slot, ascending rank.
694 plan.PreparePayloadExchange();
695 std::vector<Tag> tags(ids.size());
696 for (size_t s = 0; s < ids.size(); ++s)
697 {
698 tags[s] = Tag{ids[s], rank, static_cast<int>(s)};
699 }
700 std::vector<Tag> out;
701 plan.ExchangePayloads(tags.data(), out);
702 for (size_t u = 0; u < plan.NumUnique(); ++u)
703 {
704 const int64_t id = plan.UniqueIds()[u];
705 std::map<int, int> count;
706 int prev = -1;
707 for (size_t e = plan.PayloadBegin(u); e < plan.PayloadEnd(u); ++e)
708 {
709 if (out[e].id != id || out[e].rank != plan.PayloadRank(e) ||
710 plan.PayloadRank(e) < prev)
711 {
712 fail("ExchangePayloads: bad entry for id " +
713 std::to_string(id));
714 return;
715 }
716 prev = plan.PayloadRank(e);
717 count[out[e].rank]++;
718 rec.payloads[id].emplace_back(out[e].rank, out[e].slot);
719 }
720 if (count != o.mult.at(id))
721 {
722 fail("ExchangePayloads: wrong multiplicities for id " +
723 std::to_string(id));
724 return;
725 }
726 }
727}
728
729/// SharedPayloadResolver's Setup() mode, over several Resolve() rounds with
730/// payloads that change between rounds -- a stale plan or a missed update
731/// would show up as the previous round's answer.
732void CheckPersistentResolver(int rank, const Workload &w, const PlanOracle &o,
733 InMemorySwitch &sw, Failure &f)
734{
735 auto fail = [&](const std::string &msg) {
736 if (!f.failed)
737 {
738 f.failed = true;
739 f.message = "rank " + std::to_string(rank) + ": " + msg;
740 }
741 };
742
743 auto transport = std::make_shared<InMemoryTransport>(sw, rank);
744 const auto &regs = w.registrations[rank];
745
746 SharedPayloadResolver<Tag> sp(transport);
747 for (size_t i = 0; i < regs.size(); ++i)
748 {
749 sp.Register(regs[i].first, Tag{regs[i].first, rank, 0});
750 }
751 sp.Setup(ExchangeBackend::eTransport);
752 for (int round = 0; round < 2; ++round)
753 {
754 for (size_t i = 0; i < regs.size(); ++i)
755 {
756 sp.SetPayload(i, Tag{regs[i].first, rank, round});
757 }
758 sp.Resolve();
759 for (auto &pr : regs)
760 {
761 std::map<int, int> count;
762 for (auto &entry : sp.GetSharedPayloads(pr.first))
763 {
764 if (entry.second.id != pr.first ||
765 entry.second.rank != entry.first ||
766 entry.second.slot != round)
767 {
768 fail("persistent SharedPayloadResolver: stale or "
769 "misrouted payload for id " +
770 std::to_string(pr.first));
771 return;
772 }
773 count[entry.first]++;
774 }
775 if (count != o.mult.at(pr.first))
776 {
777 fail("persistent SharedPayloadResolver: wrong "
778 "multiplicities for id " +
779 std::to_string(pr.first));
780 return;
781 }
782 }
783 }
784}
785
786void PlanTrialForNp(int np, std::mt19937 &rng)
787{
788 const Workload w = MakeWorkload(np, rng);
789 const PlanOracle o = MakePlanOracle(w);
790 InMemorySwitch sw(np);
791 std::vector<PlanRecord> recs(np);
792 std::vector<Failure> persistent(np);
793
794 auto runRank = [&](int rank) {
795 CheckPlanRank(rank, w, o, sw, recs[rank]);
796 CheckPersistentResolver(rank, w, o, sw, persistent[rank]);
797 };
798
799 std::vector<std::thread> threads;
800 threads.reserve(np);
801 for (int r = 0; r < np; ++r)
802 {
803 threads.emplace_back(runRank, r);
804 }
805 for (auto &t : threads)
806 {
807 t.join();
808 }
809
810 // Both Fold() paths must be exercised: rank 0 registers an id twice, so
811 // it takes the general path, while every other rank is one slot per id
812 // and takes the fast path. Without this the two could silently diverge.
813 if (np >= 2)
814 {
815 int nFast = 0;
816 for (int r = 0; r < np; ++r)
817 {
818 nFast += recs[r].fastPath ? 1 : 0;
819 }
820 BOOST_REQUIRE_MESSAGE(nFast > 0 && nFast < np,
821 "expected both SharedIdPlan fold paths to be "
822 "exercised, got " +
823 std::to_string(nFast) + " fast of " +
824 std::to_string(np));
825 }
826
827 for (int r = 0; r < np; ++r)
828 {
829 BOOST_REQUIRE_MESSAGE(!recs[r].failure.failed, recs[r].failure.message);
830 BOOST_REQUIRE_MESSAGE(!persistent[r].failed, persistent[r].message);
831 }
832
833 // UniqueMask keeps exactly one slot per id, globally.
834 std::map<int64_t, int> kept;
835 for (auto &rec : recs)
836 {
837 for (int64_t id : rec.maskedIds)
838 {
839 kept[id]++;
840 }
841 }
842 for (auto &kv : o.sum)
843 {
844 BOOST_REQUIRE_MESSAGE(kept[kv.first] == 1, "UniqueMask kept id "
845 << kv.first << " "
846 << kept[kv.first]
847 << " times");
848 }
849
850 // ExchangePayloads gives every sharer of an id the same list.
851 for (auto &kv : w.sharers)
852 {
853 const auto &ref = recs[kv.second.front()].payloads.at(kv.first);
854 for (int r : kv.second)
855 {
856 BOOST_REQUIRE_MESSAGE(recs[r].payloads.at(kv.first) == ref,
857 "payload lists differ between sharers of id "
858 << kv.first);
859 }
860 }
861}
862
863} // namespace
864
865/**
866 * @brief SharedIdPlan reproduces gs_gather / gs_unique semantics and the
867 * payload exchange against the oracle, and SharedPayloadResolver's persistent
868 * mode stays correct across repeated Resolve() calls with changing payloads.
869 */
870BOOST_AUTO_TEST_CASE(TestSharedIdPlanAgainstOracle)
871{
872 std::mt19937 rng(171717);
873
874 const std::vector<int> npList = {1, 2, 3, 4, 5, 7, 8, 13, 16, 17, 33};
875
876 for (int np : npList)
877 {
878 BOOST_TEST_CONTEXT("np = " << np)
879 {
880 for (int trial = 0; trial < 4; ++trial)
881 {
882 PlanTrialForNp(np, rng);
883 }
884 }
885 }
886}
887
888} // namespace Nektar::UnitTests
Id-keyed exchange of every sharer's raw payload for a shared entity.
std::map< int64_t, std::vector< int > > sharers
std::map< int64_t, std::map< int, int > > mult
std::map< int64_t, std::vector< std::pair< int, int > > > payloads
Per id, the (rank, slot) list ExchangePayloads() delivered.
std::vector< std::vector< RoutedMessage > > m_outbox
std::mutex m_mtx
bool fastPath
Whether this rank's plan took the one-slot-per-id fast path.
std::vector< std::vector< RoutedMessage > > m_inbox
std::atomic< bool > m_sorted
std::string message
Barrier m_barrier
std::vector< int64_t > maskedIds
Ids whose UniqueMask() bit is set on this rank.
std::map< int64_t, int > maxOrder
InMemorySwitch & m_sw
std::map< int64_t, bool > anyHigh
std::vector< std::vector< std::pair< int64_t, int > > > registrations
int64_t id
Failure failure
std::condition_variable m_cv
std::map< int64_t, double > sum
Base communications class.
Definition Comm.h:95
Rendezvous discovery on its own, for the common case where you only need to find which ranks share ea...
Abstract interface for a personalised all-to-all exchange of opaque byte blobs.
A persistent gather-scatter plan over shared global ids: discovery is paid once, then a fixed neighbo...
static constexpr int64_t kIgnore
Slot id meaning "take no part", the role id 0 plays for gslib. Mesh entity ids use 0 legitimately,...
Discovery-then-direct-exchange resolver: for every registered (entity id, payload) pair,...
std::shared_ptr< Comm > CommSharedPtr
Pointer to a Communicator object.
Definition Comm.h:62
NEK_DEVICE_KERNEL void const TData *NEK_RESTRICT const TData *NEK_RESTRICT const size_t const unsigned int const unsigned int const unsigned int const unsigned int const size_t const TData *NEK_RESTRICT const TData *NEK_RESTRICT const TUseSharedWsp TData *NEK_RESTRICT const TData *NEK_RESTRICT TData *NEK_RESTRICT out
std::vector< double > w(NPUPPER)
std::vector< double > d(NPUPPER *NPUPPER)
std::int64_t int64_t
BOOST_AUTO_TEST_CASE(TestCanGetRawPtr)
A resolved id's sharer ranks, as a range over the resolver's own storage – ascending,...
An opaque byte payload plus routing metadata.