fix(shmem): release region blocks of reused messages to their own region

- Remove the `fRegionPtr` member of `shmem::Message`. It cached the
  region of the last `GetData()`, `GetRefCount()` or `Copy()` call.
  `Rebuild()` and `Socket::Receive()` did not reset it.
- When a message received a block of region A, was read, rebuilt, and
  then received a block of region B, its release went to region A.
  Region A got a wrong callback and region B never got its block back.
- Look up the region with `Manager::GetRegionFromCache()` where it is
  needed. The lookup is a thread-local fast path.
- `sizeof(shmem::Message)` goes from 80 to 72 bytes on LP64.

Refs: #477

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude
2026-11-03 12:57:27 +00:00
committed by Dennis Klein
parent f4e265a562
commit f1312aefe3
2 changed files with 84 additions and 29 deletions

View File

@@ -183,9 +183,9 @@ class Message final : public fair::mq::Message
fLocalPtr = nullptr; fLocalPtr = nullptr;
} }
} else { } else {
fRegionPtr = fManager.GetRegionFromCache(fRegionId); UnmanagedRegion* region = fManager.GetRegionFromCache(fRegionId);
if (fRegionPtr) { if (region) {
fLocalPtr = reinterpret_cast<char*>(fRegionPtr->GetData()) + fHandle; fLocalPtr = reinterpret_cast<char*>(region->GetData()) + fHandle;
} else { } else {
// LOG(warn) << "could not get pointer from a region message"; // LOG(warn) << "could not get pointer from a region message";
fLocalPtr = nullptr; fLocalPtr = nullptr;
@@ -258,12 +258,12 @@ class Message final : public fair::mq::Message
if (fShared < 0) { // UR msg is not yet shared if (fShared < 0) { // UR msg is not yet shared
return 1; return 1;
} }
fRegionPtr = fManager.GetRegionFromCache(fRegionId); UnmanagedRegion* region = fManager.GetRegionFromCache(fRegionId);
if (!fRegionPtr) { if (!region) {
throw TransportError(tools::ToString("Cannot get unmanaged region with id ", fRegionId)); throw TransportError(tools::ToString("Cannot get unmanaged region with id ", fRegionId));
} }
if (fRegionPtr->fRcSegmentSize > 0) { if (region->fRcSegmentSize > 0) {
return fRegionPtr->GetRefCountAddressFromHandle(fShared)->Get(); return region->GetRefCountAddressFromHandle(fShared)->Get();
} else { } else {
fManager.GetSegment(fSegmentId); fManager.GetSegment(fSegmentId);
return ShmHeader::RefCount(fManager.GetAddressFromHandle(fShared, fSegmentId)); return ShmHeader::RefCount(fManager.GetAddressFromHandle(fShared, fSegmentId));
@@ -289,20 +289,20 @@ class Message final : public fair::mq::Message
fManager.GetSegment(otherMsg.fSegmentId); fManager.GetSegment(otherMsg.fSegmentId);
ShmHeader::IncrementRefCount(fManager.GetAddressFromHandle(otherMsg.fHandle, otherMsg.fSegmentId)); ShmHeader::IncrementRefCount(fManager.GetAddressFromHandle(otherMsg.fHandle, otherMsg.fSegmentId));
} else { // msg in unmanaged region } else { // msg in unmanaged region
fRegionPtr = fManager.GetRegionFromCache(otherMsg.fRegionId); UnmanagedRegion* region = fManager.GetRegionFromCache(otherMsg.fRegionId);
if (!fRegionPtr) { if (!region) {
throw TransportError(tools::ToString("Cannot get unmanaged region with id ", otherMsg.fRegionId)); throw TransportError(tools::ToString("Cannot get unmanaged region with id ", otherMsg.fRegionId));
} }
if (fRegionPtr->fRcSegmentSize > 0) { if (region->fRcSegmentSize > 0) {
if (otherMsg.fShared < 0) { if (otherMsg.fShared < 0) {
// UR msg not yet shared, create the reference counting object with count 2 // UR msg not yet shared, create the reference counting object with count 2
try { try {
otherMsg.fShared = fRegionPtr->HandleFromAddress(&(fRegionPtr->MakeRefCount(2))); otherMsg.fShared = region->HandleFromAddress(&(region->MakeRefCount(2)));
} catch (boost::interprocess::bad_alloc& ba) { } catch (boost::interprocess::bad_alloc& ba) {
throw RefCountBadAlloc(tools::ToString("Insufficient space in the reference count segment ", otherMsg.fRegionId, ", original exception: bad_alloc: ", ba.what())); throw RefCountBadAlloc(tools::ToString("Insufficient space in the reference count segment ", otherMsg.fRegionId, ", original exception: bad_alloc: ", ba.what()));
} }
} else { } else {
fRegionPtr->GetRefCountAddressFromHandle(otherMsg.fShared)->Increment(); region->GetRefCountAddressFromHandle(otherMsg.fShared)->Increment();
} }
} else { // if RefCount segment size is 0, store the ref count in the managed segment } else { // if RefCount segment size is 0, store the ref count in the managed segment
if (otherMsg.fShared < 0) { // if UR msg is not yet shared if (otherMsg.fShared < 0) { // if UR msg is not yet shared
@@ -332,9 +332,10 @@ class Message final : public fair::mq::Message
~Message() override { CloseMessage(); } ~Message() override { CloseMessage(); }
private: private:
// Members are sorted by size to avoid padding. Keep the message small: it is
// allocated for every transfer. sizeof(Message) is checked in test/message.
Manager& fManager; Manager& fManager;
mutable UnmanagedRegion* fRegionPtr = nullptr; mutable char* fLocalPtr = nullptr; // local cache of the data ptr, for received messages obtained from the handle
mutable char* fLocalPtr = nullptr;
size_t fSize = 0; // size of the shm buffer size_t fSize = 0; // size of the shm buffer
size_t fHint = 0; // user-defined value, given by the user on message creation and returned to the user on "buffer no longer needed"-callbacks size_t fHint = 0; // user-defined value, given by the user on message creation and returned to the user on "buffer no longer needed"-callbacks
boost::interprocess::managed_shared_memory::handle_t fHandle = -1; // handle to shm buffer, convertible to shm buffer ptr boost::interprocess::managed_shared_memory::handle_t fHandle = -1; // handle to shm buffer, convertible to shm buffer ptr
@@ -378,16 +379,16 @@ class Message final : public fair::mq::Message
fManager.Deallocate(fHandle, fSegmentId); fManager.Deallocate(fHandle, fSegmentId);
} }
} else { // unmanaged region } else { // unmanaged region
UnmanagedRegion* region = fManager.GetRegionFromCache(fRegionId);
if (fShared >= 0) { if (fShared >= 0) {
fRegionPtr = fManager.GetRegionFromCache(fRegionId); if (!region) {
if (!fRegionPtr) {
throw TransportError(tools::ToString("Cannot get unmanaged region with id ", fRegionId)); throw TransportError(tools::ToString("Cannot get unmanaged region with id ", fRegionId));
} }
if (fRegionPtr->fRcSegmentSize > 0) { if (region->fRcSegmentSize > 0) {
uint16_t refCount = fRegionPtr->GetRefCountAddressFromHandle(fShared)->Decrement(); uint16_t refCount = region->GetRefCountAddressFromHandle(fShared)->Decrement();
if (refCount == 1) { if (refCount == 1) {
fRegionPtr->RemoveRefCount(*(fRegionPtr->GetRefCountAddressFromHandle(fShared))); region->RemoveRefCount(*(region->GetRefCountAddressFromHandle(fShared)));
ReleaseUnmanagedRegionBlock(); ReleaseUnmanagedRegionBlock(region);
} }
} else { // if RefCount segment size is 0, get the ref count from the managed segment } else { // if RefCount segment size is 0, get the ref count from the managed segment
// make sure segment is initialized in this transport // make sure segment is initialized in this transport
@@ -396,11 +397,11 @@ class Message final : public fair::mq::Message
uint16_t refCount = ShmHeader::DecrementRefCount(fManager.GetAddressFromHandle(fShared, fSegmentId)); uint16_t refCount = ShmHeader::DecrementRefCount(fManager.GetAddressFromHandle(fShared, fSegmentId));
if (refCount == 1) { if (refCount == 1) {
fManager.Deallocate(fShared, fSegmentId); fManager.Deallocate(fShared, fSegmentId);
ReleaseUnmanagedRegionBlock(); ReleaseUnmanagedRegionBlock(region);
} }
} }
} else { } else {
ReleaseUnmanagedRegionBlock(); ReleaseUnmanagedRegionBlock(region);
} }
} }
} }
@@ -409,14 +410,10 @@ class Message final : public fair::mq::Message
fSize = 0; fSize = 0;
} }
void ReleaseUnmanagedRegionBlock() void ReleaseUnmanagedRegionBlock(UnmanagedRegion* region)
{ {
if (!fRegionPtr) { if (region) {
fRegionPtr = fManager.GetRegionFromCache(fRegionId); region->ReleaseBlock({fHandle, fSize, fHint});
}
if (fRegionPtr) {
fRegionPtr->ReleaseBlock({fHandle, fSize, fHint});
} else { } else {
LOG(warn) << "region ack queue for id " << fRegionId << " no longer exist. Not sending ack"; LOG(warn) << "region ack queue for id " << fRegionId << " no longer exist. Not sending ack";
} }

View File

@@ -19,11 +19,14 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <array> #include <array>
#include <atomic>
#include <cassert> #include <cassert>
#include <chrono>
#include <cstdint> #include <cstdint>
#include <memory> #include <memory>
#include <string_view> #include <string_view>
#include <string> #include <string>
#include <thread>
#include <utility> #include <utility>
namespace namespace
@@ -546,6 +549,56 @@ auto SideChannelUnmanaged() -> void
blocker.Wait(); blocker.Wait();
} }
auto ReuseReceivedRegionMessage() -> void
{
ProgOptions config;
config.SetProperty<string>("session", tools::Uuid());
config.SetProperty<size_t>("shm-segment-size", 100000000);
config.SetProperty<bool>("shm-monitor", true);
auto factory(TransportFactory::CreateTransportFactory("shmem", tools::Uuid(), &config));
const size_t regionSize = 1000000;
std::atomic<int> releasedA{0};
std::atomic<int> releasedB{0};
auto regionA = factory->CreateUnmanagedRegion(regionSize, [&](void*, size_t, void*) { ++releasedA; });
auto regionB = factory->CreateUnmanagedRegion(regionSize, [&](void*, size_t, void*) { ++releasedB; });
auto waitFor = [](std::atomic<int> const& counter, int value) {
for (int i = 0; i < 500 && counter < value; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return counter == value;
};
Channel push{"Push", "push", factory};
Channel pull{"Pull", "pull", factory};
auto const address(tools::ToString("ipc://test_reuse_received_region_msg_", config.GetProperty<string>("session")));
push.Bind(address);
pull.Connect(address);
// Receive a block of region A and read it. This resolves region A in the message.
auto inMsg(pull.NewMessage());
{
auto outMsg(push.NewMessage(regionA, regionA->GetData(), 2, nullptr));
ASSERT_EQ(push.Send(outMsg), 2);
}
ASSERT_EQ(pull.Receive(inMsg), 2);
ASSERT_NE(inMsg->GetData(), nullptr);
inMsg->Rebuild();
ASSERT_TRUE(waitFor(releasedA, 1));
// Receive a block of region B into the same message, and release it without a read.
{
auto outMsg(push.NewMessage(regionB, regionB->GetData(), 2, nullptr));
ASSERT_EQ(push.Send(outMsg), 2);
}
ASSERT_EQ(pull.Receive(inMsg), 2);
inMsg->Rebuild();
// The block must go back to region B, not to region A.
EXPECT_TRUE(waitFor(releasedB, 1));
EXPECT_EQ(releasedA, 1);
}
auto SideChannelErrors() -> void auto SideChannelErrors() -> void
{ {
ProgOptions config; ProgOptions config;
@@ -585,6 +638,11 @@ TEST(SideChannel, shmem_unmanaged) // NOLINT
SideChannelUnmanaged(); SideChannelUnmanaged();
} }
TEST(ReuseReceivedRegionMessage, shmem) // NOLINT
{
ReuseReceivedRegionMessage();
}
TEST(SideChannel, errors) // NOLINT TEST(SideChannel, errors) // NOLINT
{ {
SideChannelErrors(); SideChannelErrors();