From b86dbc94100dfa57aaa202d6646453d41222b0b0 Mon Sep 17 00:00:00 2001 From: Barthelemy Date: Thu, 26 Nov 2026 11:04:39 +0100 Subject: [PATCH 1/4] [QC-1352] Use shallow copy in Dispatcher The Dispatcher no longer deep-copies sampled payloads but uses `forwardPayload`. STFSender cannot run on Mac, thus I asked Claude to build a test (dataSamplingSharedPayload) that makes sure we can forward data and that the data is readable by several agents. --- Utilities/DataSampling/CMakeLists.txt | 5 + .../include/DataSampling/Dispatcher.h | 2 +- Utilities/DataSampling/src/Dispatcher.cxx | 19 +- .../test/dataSamplingSharedPayload.cxx | 344 ++++++++++++++++++ 4 files changed, 363 insertions(+), 7 deletions(-) create mode 100644 Utilities/DataSampling/test/dataSamplingSharedPayload.cxx diff --git a/Utilities/DataSampling/CMakeLists.txt b/Utilities/DataSampling/CMakeLists.txt index 584dbce9a4235..722409b81a87d 100644 --- a/Utilities/DataSampling/CMakeLists.txt +++ b/Utilities/DataSampling/CMakeLists.txt @@ -86,3 +86,8 @@ o2_add_executable(datasampling-benchmark SOURCES test/dataSamplingBenchmark.cxx COMPONENT_NAME DataSampling PUBLIC_LINK_LIBRARIES O2::Framework O2::DataSampling) + +o2_add_executable(datasampling-shared-payload + SOURCES test/dataSamplingSharedPayload.cxx + COMPONENT_NAME DataSampling + PUBLIC_LINK_LIBRARIES O2::Framework O2::DataSampling) diff --git a/Utilities/DataSampling/include/DataSampling/Dispatcher.h b/Utilities/DataSampling/include/DataSampling/Dispatcher.h index c38ece1436bc0..061b0a88593d9 100644 --- a/Utilities/DataSampling/include/DataSampling/Dispatcher.h +++ b/Utilities/DataSampling/include/DataSampling/Dispatcher.h @@ -66,7 +66,7 @@ class Dispatcher : public framework::Task private: DataSamplingHeader prepareDataSamplingHeader(const DataSamplingPolicy& policy, header::DataHeader const& original); void reportStats(monitoring::Monitoring& monitoring) const; - void send(framework::DataAllocator& dataAllocator, const framework::DataRef& inputData, const framework::Output& output) const; + void send(framework::DataAllocator& dataAllocator, const framework::DataRef& inputData, fair::mq::Message* inputPayload, const framework::Output& output) const; std::string mName; DataSamplingHeader::DeviceIDType mDeviceID = "invalid"; diff --git a/Utilities/DataSampling/src/Dispatcher.cxx b/Utilities/DataSampling/src/Dispatcher.cxx index 5fcb965da76ed..3d39a0aed348a 100644 --- a/Utilities/DataSampling/src/Dispatcher.cxx +++ b/Utilities/DataSampling/src/Dispatcher.cxx @@ -19,14 +19,13 @@ #include "DataSampling/DataSamplingHeader.h" #include "Framework/DataProcessingHeader.h" #include "Framework/DataSpecUtils.h" -#include "Framework/Logger.h" #include "Framework/ConfigParamRegistry.h" #include "Framework/Monitoring.h" #include "Framework/DataRefUtils.h" -#include "Framework/FairMQDeviceProxy.h" #include "Framework/DataProcessingHelpers.h" #include "Framework/DataRelayer.h" +#include #include #include #include @@ -137,7 +136,9 @@ void Dispatcher::run(ProcessingContext& ctx) if (auto route = policy->match(inputMatcher); route != nullptr && policy->decide(firstPart)) { auto routeAsConcreteDataType = DataSpecUtils::asConcreteDataTypeMatcher(*route); auto dsheader = prepareDataSamplingHeader(*policy, *firstInputHeader); - for (const auto& part : inputIt.parts()) { + auto parts = inputIt.parts(); + for (auto partIt = parts.begin(); partIt != parts.end(); ++partIt) { + const DataRef& part = *partIt; if (part.header != nullptr) { // We copy every header which is not DataHeader or DataProcessingHeader, // so that custom data-dependent headers are passed forward, @@ -152,7 +153,7 @@ void Dispatcher::run(ProcessingContext& ctx) routeAsConcreteDataType.description, partInputHeader->subSpecification, std::move(headerStack)}; - send(ctx.outputs(), part, output); + send(ctx.outputs(), part, parts.getPayloadAtIndices(partIt.indices()), output); } } } @@ -193,10 +194,16 @@ DataSamplingHeader Dispatcher::prepareDataSamplingHeader(const DataSamplingPolic original}; } -void Dispatcher::send(DataAllocator& dataAllocator, const DataRef& inputData, const Output& output) const +void Dispatcher::send(DataAllocator& dataAllocator, const DataRef& inputData, fair::mq::Message* inputPayload, const Output& output) const { const auto* inputHeader = DataRefUtils::getHeader(inputData); - dataAllocator.snapshot(output, inputData.payload, DataRefUtils::getPayloadSize(inputData), inputHeader->payloadSerializationMethod); + const auto payloadSize = DataRefUtils::getPayloadSize(inputData); + // Shallow copy when we have the original message and it is exactly the payload described by the header. + if (inputPayload != nullptr && inputPayload->GetData() == inputData.payload && inputPayload->GetSize() == payloadSize) { + dataAllocator.forwardPayload(output, *inputPayload, inputHeader->payloadSerializationMethod); + } else { + dataAllocator.snapshot(output, inputData.payload, payloadSize, inputHeader->payloadSerializationMethod); + } } void Dispatcher::registerPolicy(std::unique_ptr&& policy) diff --git a/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx b/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx new file mode 100644 index 0000000000000..734258b6edcab --- /dev/null +++ b/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx @@ -0,0 +1,344 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file dataSamplingSharedPayload.cxx +/// \brief Stress test of the Dispatcher forwarding payloads by shallow copy. +/// +/// The producer mimics STFSender: payloads live in an unmanaged shared memory region and are +/// handed over to DPL without a copy. As soon as FairMQ reports a buffer as released, the producer +/// poisons it and puts it back into its free list, to be reused for the next timeframes. +/// The same messages are read concurrently by a regular consumer and, via the Dispatcher, +/// by two "QC-like" consumers (two policies sampling the same data, i.e. two shallow copies per part). +/// All consumers verify the payload twice, with a pause in between, while holding the message. +/// Any premature release of a shared buffer would make the verification fail. +/// The sampled consumers also check that they receive the region buffers themselves (no deep copy). +/// +/// How to run it: +/// +/// # build (from the O2 build directory, with the O2 environment loaded) +/// ninja stage/bin/o2-datasampling-datasampling-shared-payload +/// +/// # default run: 500 timeframes x 4 parts x 1 MB, 32 buffers in the region +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 +/// +/// # make the direct consumer read the buffers at the same time as the Dispatcher and the sampled consumers +/// # (by default DPL forwards the data to the Dispatcher only after the direct consumer has processed it) +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 --early-forward-policy always +/// +/// # heavier run: small region, so that buffers are released, poisoned and reused all the time +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 --early-forward-policy always \ +/// --timeframes 3000 --parts 8 --block-size 65536 --blocks 24 +/// +/// The workflow exits with 0 on success. Each consumer prints a summary at the end of stream, e.g. +/// Checked 2000 parts, 0 errors, 2000 in the producer's region, 0 copied, 850 seen while still shared with another reader +/// It exits with a non-zero code if a payload fails the verification ("payload has been poisoned", "corrupted word"), +/// if a consumer receives no data, or if sampled payloads were deep copies ("... sampled payloads were deep copies"). +/// The latter check can be disabled with --allow-deep-copy, e.g. to run the test against a Dispatcher which copies. +/// Only the shared memory transport (the DPL default) is supported. +/// +/// Generated with Claude + +#include "DataSampling/DataSampling.h" +#include "Framework/ConfigParamSpec.h" +#include "Framework/CompletionPolicy.h" +#include "Framework/ChannelConfigurationPolicy.h" + +#include + +using namespace o2::framework; +using namespace o2::utilities; + +void customize(std::vector& policies) +{ + DataSampling::CustomizeInfrastructure(policies); +} + +void customize(std::vector& policies) +{ + DataSampling::CustomizeInfrastructure(policies); +} + +void customize(std::vector& workflowOptions) +{ + workflowOptions.push_back(ConfigParamSpec{"timeframes", VariantType::Int, 500, {"number of timeframes to produce"}}); + workflowOptions.push_back(ConfigParamSpec{"parts", VariantType::Int, 4, {"number of parts (subspecs) per timeframe"}}); + workflowOptions.push_back(ConfigParamSpec{"block-size", VariantType::Int, 1 << 20, {"size of each payload in bytes"}}); + workflowOptions.push_back(ConfigParamSpec{"blocks", VariantType::Int, 32, {"number of payload buffers in the unmanaged region"}}); + workflowOptions.push_back(ConfigParamSpec{"allow-deep-copy", VariantType::Bool, false, {"do not fail if sampled payloads are copies instead of the original region buffers"}}); +} + +#include "Framework/runDataProcessing.h" +#include "Framework/ControlService.h" +#include "Framework/CallbackService.h" +#include "Framework/DataRefUtils.h" +#include "Framework/FairMQDeviceProxy.h" +#include "Framework/Logger.h" +#include "Framework/RoutingIndices.h" +#include "DataSampling/DataSamplingHeader.h" +#include "Headers/DataHeader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using DataHeader = o2::header::DataHeader; + +namespace +{ +constexpr uint64_t poisonWord = 0xDEDEDEDEDEDEDEDEull; +constexpr unsigned char poisonByte = 0xDE; +constexpr uint64_t mixer = 0x9E3779B97F4A7C15ull; + +uint64_t makeSeed(uint64_t tf, uint64_t part) { return (tf << 16) | part; } + +void fillPayload(char* data, size_t size, uint64_t seed) +{ + auto* words = reinterpret_cast(data); + const size_t nWords = size / sizeof(uint64_t); + words[0] = seed; + for (size_t i = 1; i < nWords; ++i) { + words[i] = seed * mixer + i; + } +} + +// returns an empty string if the payload is consistent, otherwise the reason of the failure +std::string checkPayload(const char* data, size_t size, size_t expectedSize, uint32_t subSpec) +{ + if (size != expectedSize) { + return fmt::format("unexpected size {} (expected {})", size, expectedSize); + } + const auto* words = reinterpret_cast(data); + const size_t nWords = size / sizeof(uint64_t); + const uint64_t seed = words[0]; + if (seed == poisonWord) { + return "payload has been poisoned, i.e. released while still in use"; + } + if ((seed & 0xFFFF) != subSpec) { + return fmt::format("payload belongs to part {}, but header says subspec {}", seed & 0xFFFF, subSpec); + } + for (size_t i = 1; i < nWords; ++i) { + if (words[i] != seed * mixer + i) { + return fmt::format("corrupted word {} (value {:#x}{})", i, words[i], words[i] == poisonWord ? ", poisoned" : ""); + } + } + return {}; +} + +/// Free list of buffers of an unmanaged region, filled back by the FairMQ release callback. +struct RegionPool { + std::mutex mutex; + std::condition_variable cv; + std::vector freeBlocks; + std::atomic released{0}; + size_t blockSize = 0; + // declared last, so that it is destroyed first, while the rest of the pool is still alive for its callbacks + std::unique_ptr region; + + char* acquire() + { + std::unique_lock lock(mutex); + if (!cv.wait_for(lock, std::chrono::seconds(20), [this] { return !freeBlocks.empty(); })) { + return nullptr; + } + auto* block = freeBlocks.back(); + freeBlocks.pop_back(); + return block; + } +}; + +DataProcessorSpec getProducer(int nTimeframes, int nParts, size_t blockSize, size_t nBlocks) +{ + Outputs outputs; + for (int p = 0; p < nParts; ++p) { + outputs.emplace_back(OutputSpec{"TST", "RAWDATA", static_cast(p)}); + } + return DataProcessorSpec{ + .name = "stf-like-producer", + .inputs = {}, + .outputs = outputs, + .algorithm = adaptStateful([nTimeframes, nParts, blockSize, nBlocks](CallbackService& callbacks) { + auto pool = std::make_shared(); + pool->blockSize = blockSize; + auto tf = std::make_shared(0); + // the region has to be destroyed before the transport which created it, like STFSender does + callbacks.set([pool]() { + LOG(info) << "Destroying the unmanaged region, " << pool->released << " buffers were released"; + pool->region.reset(); + }); + return adaptStateless([pool, tf, nTimeframes, nParts, blockSize, nBlocks](ProcessingContext& ctx) { + auto* transport = ctx.services().get().getOutputTransport(RouteIndex{0}); + if (!pool->region) { + if (transport->GetType() != fair::mq::Transport::SHM) { + LOG(fatal) << "This test requires the shared memory transport"; + } + fair::mq::RegionConfig cfg; + cfg.size = blockSize * nBlocks; + auto* rawPool = pool.get(); + pool->region = transport->CreateUnmanagedRegion( + cfg.size, + [rawPool](const std::vector& blocks) { + // like STFSender: once released, a buffer gets new content. Poisoning it makes any reader which + // still (wrongly) uses it fail. + std::lock_guard lock(rawPool->mutex); + for (const auto& block : blocks) { + std::memset(block.ptr, poisonByte, rawPool->blockSize); + rawPool->freeBlocks.push_back(static_cast(block.ptr)); + } + rawPool->released += blocks.size(); + rawPool->cv.notify_all(); + }, + cfg); + auto* base = static_cast(pool->region->GetData()); + for (size_t b = 0; b < nBlocks; ++b) { + pool->freeBlocks.push_back(base + b * blockSize); + } + LOG(info) << "Created unmanaged region of " << cfg.size << " bytes with " << nBlocks << " buffers"; + } + + if (*tf >= static_cast(nTimeframes)) { + LOG(info) << "Produced " << *tf << " timeframes, " << pool->released << " buffers released so far"; + ctx.services().get().endOfStream(); + ctx.services().get().readyToQuit(QuitRequest::Me); + return; + } + for (int p = 0; p < nParts; ++p) { + char* block = pool->acquire(); + if (block == nullptr) { + LOG(fatal) << "No region buffer was released for 20 seconds, they are leaking"; + } + fillPayload(block, blockSize, makeSeed(*tf, p)); + auto regionMessage = transport->CreateMessage(pool->region, block, blockSize); + ctx.outputs().forwardPayload(Output{"TST", "RAWDATA", static_cast(p)}, *regionMessage); + // regionMessage is destroyed here, the forwarded shallow copy keeps the buffer alive + } + ++(*tf); + }); + })}; +} + +DataProcessorSpec getChecker(std::string name, InputSpec input, size_t blockSize, std::chrono::microseconds holdTime, bool sampled, bool expectZeroCopy) +{ + return DataProcessorSpec{ + .name = std::move(name), + .inputs = {std::move(input)}, + .outputs = {}, + .algorithm = adaptStateful([blockSize, holdTime, sampled, expectZeroCopy](CallbackService& callbacks) { + struct Stats { + uint64_t parts = 0; + uint64_t errors = 0; + uint64_t inRegion = 0; + uint64_t notInRegion = 0; + uint64_t sharedRefs = 0; + }; + auto stats = std::make_shared(); + callbacks.set([stats, sampled, expectZeroCopy](EndOfStreamContext&) { + LOG(info) << "Checked " << stats->parts << " parts, " << stats->errors << " errors, " + << stats->inRegion << " in the producer's region, " << stats->notInRegion << " copied, " + << stats->sharedRefs << " seen while still shared with another reader"; + if (stats->errors > 0) { + LOG(fatal) << "Payload verification failed " << stats->errors << " times"; + } + if (stats->parts == 0) { + LOG(fatal) << "No data received"; + } + if (sampled && expectZeroCopy && stats->notInRegion > 0) { + LOG(fatal) << stats->notInRegion << " sampled payloads were deep copies"; + } + }); + return adaptStateless([stats, blockSize, holdTime, sampled](ProcessingContext& ctx) { + for (auto inputIt = ctx.inputs().begin(); inputIt != ctx.inputs().end(); ++inputIt) { + auto parts = inputIt.parts(); + for (auto partIt = parts.begin(); partIt != parts.end(); ++partIt) { + const DataRef& ref = *partIt; + if (ref.header == nullptr) { + continue; + } + const auto* dh = DataRefUtils::getHeader(ref); + if (sampled && DataRefUtils::getHeader(ref) == nullptr) { + LOG(error) << "Missing DataSamplingHeader"; + stats->errors++; + } + const auto size = DataRefUtils::getPayloadSize(ref); + stats->parts++; + + if (auto* shmMessage = dynamic_cast(parts.getPayloadAtIndices(partIt.indices()))) { + shmMessage->GetMeta().fManaged ? stats->notInRegion++ : stats->inRegion++; + if (shmMessage->GetRefCount() > 1) { + stats->sharedRefs++; + } + } else { + stats->notInRegion++; + } + + // read twice, holding the message in between, so that the other readers work on it at the same time + for (int pass = 0; pass < 2; ++pass) { + if (auto failure = checkPayload(ref.payload, size, blockSize, dh->subSpecification); !failure.empty()) { + LOG(error) << "Verification of " << dh->dataOrigin.as() << "/" << dh->dataDescription.as() + << "/" << dh->subSpecification << " failed (pass " << pass << "): " << failure; + stats->errors++; + break; + } + if (pass == 0) { + std::this_thread::sleep_for(holdTime); + } + } + } + } + }); + })}; +} +} // namespace + +WorkflowSpec defineDataProcessing(ConfigContext const& config) +{ + const int nTimeframes = config.options().get("timeframes"); + const int nParts = config.options().get("parts"); + const size_t blockSize = config.options().get("block-size"); + const size_t nBlocks = config.options().get("blocks"); + const bool expectZeroCopy = !config.options().get("allow-deep-copy"); + + WorkflowSpec specs; + specs.push_back(getProducer(nTimeframes, nParts, blockSize, nBlocks)); + specs.push_back(getChecker("direct-consumer", InputSpec{"raw", ConcreteDataTypeMatcher{"TST", "RAWDATA"}}, blockSize, std::chrono::microseconds(500), false, expectZeroCopy)); + specs.push_back(getChecker("sampled-consumer-all", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "sharedAll0"}, Lifetime::Sporadic}, blockSize, std::chrono::milliseconds(2), true, expectZeroCopy)); + specs.push_back(getChecker("sampled-consumer-half", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "sharedHalf0"}, Lifetime::Sporadic}, blockSize, std::chrono::milliseconds(5), true, expectZeroCopy)); + + // two policies on the same data: the Dispatcher forwards the same input message twice + auto makePolicy = [](const std::string& id, const std::string& fraction) { + boost::property_tree::ptree condition; + condition.put("condition", "random"); + condition.put("fraction", fraction); + condition.put("seed", "1234"); + boost::property_tree::ptree conditions; + conditions.push_back({"", condition}); + boost::property_tree::ptree policy; + policy.put("id", id); + policy.put("active", "true"); + policy.put("query", "raw:TST/RAWDATA"); + policy.add_child("samplingConditions", conditions); + policy.put("blocking", "true"); + return policy; + }; + boost::property_tree::ptree policies; + policies.push_back({"", makePolicy("sharedAll", "1.0")}); + policies.push_back({"", makePolicy("sharedHalf", "0.5")}); + DataSampling::GenerateInfrastructure(specs, policies); + + return specs; +} From 9549087b21163726cb2dac6157aa457aba0efd93 Mon Sep 17 00:00:00 2001 From: Barthelemy Date: Mon, 30 Nov 2026 13:41:11 +0100 Subject: [PATCH 2/4] simplify the condition in send --- Utilities/DataSampling/src/Dispatcher.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Utilities/DataSampling/src/Dispatcher.cxx b/Utilities/DataSampling/src/Dispatcher.cxx index 3d39a0aed348a..754f641f01c4d 100644 --- a/Utilities/DataSampling/src/Dispatcher.cxx +++ b/Utilities/DataSampling/src/Dispatcher.cxx @@ -199,7 +199,7 @@ void Dispatcher::send(DataAllocator& dataAllocator, const DataRef& inputData, fa const auto* inputHeader = DataRefUtils::getHeader(inputData); const auto payloadSize = DataRefUtils::getPayloadSize(inputData); // Shallow copy when we have the original message and it is exactly the payload described by the header. - if (inputPayload != nullptr && inputPayload->GetData() == inputData.payload && inputPayload->GetSize() == payloadSize) { + if (inputPayload) { dataAllocator.forwardPayload(output, *inputPayload, inputHeader->payloadSerializationMethod); } else { dataAllocator.snapshot(output, inputData.payload, payloadSize, inputHeader->payloadSerializationMethod); From de9d4f7db06b13eeff2a66ad85c7518a7b307e45 Mon Sep 17 00:00:00 2001 From: Barthelemy Date: Mon, 30 Nov 2026 14:59:23 +0100 Subject: [PATCH 3/4] in case we got an empty payload, log and skip. --- Utilities/DataSampling/src/Dispatcher.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Utilities/DataSampling/src/Dispatcher.cxx b/Utilities/DataSampling/src/Dispatcher.cxx index 754f641f01c4d..bde504be37fd4 100644 --- a/Utilities/DataSampling/src/Dispatcher.cxx +++ b/Utilities/DataSampling/src/Dispatcher.cxx @@ -202,7 +202,7 @@ void Dispatcher::send(DataAllocator& dataAllocator, const DataRef& inputData, fa if (inputPayload) { dataAllocator.forwardPayload(output, *inputPayload, inputHeader->payloadSerializationMethod); } else { - dataAllocator.snapshot(output, inputData.payload, payloadSize, inputHeader->payloadSerializationMethod); + LOG(error) << "DS: got an empty payload, skipping"; } } From f187f2791ee0b887b7de05b3992b90c83e7d7e60 Mon Sep 17 00:00:00 2001 From: Barthelemy Date: Mon, 30 Nov 2026 15:32:25 +0100 Subject: [PATCH 4/4] update the test --- .../test/dataSamplingSharedPayload.cxx | 275 ++++++++++++++---- 1 file changed, 223 insertions(+), 52 deletions(-) diff --git a/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx b/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx index 734258b6edcab..1d0d1d14fe90a 100644 --- a/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx +++ b/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx @@ -10,39 +10,80 @@ // or submit itself to any jurisdiction. /// \file dataSamplingSharedPayload.cxx -/// \brief Stress test of the Dispatcher forwarding payloads by shallow copy. +/// \brief Checks that STFSender releasing its messages cannot free data still read by a local QC task. /// -/// The producer mimics STFSender: payloads live in an unmanaged shared memory region and are -/// handed over to DPL without a copy. As soon as FairMQ reports a buffer as released, the producer -/// poisons it and puts it back into its free list, to be reused for the next timeframes. -/// The same messages are read concurrently by a regular consumer and, via the Dispatcher, -/// by two "QC-like" consumers (two policies sampling the same data, i.e. two shallow copies per part). -/// All consumers verify the payload twice, with a pause in between, while holding the message. -/// Any premature release of a shared buffer would make the verification fail. -/// The sampled consumers also check that they receive the region buffers themselves (no deep copy). +/// Context +/// ------- +/// The Dispatcher does not copy sampled payloads: it forwards a shallow copy of the input message +/// (DataAllocator::forwardPayload), so a QC task reads the very same shared memory buffer as the rest of the FLP chain: /// -/// How to run it: +/// readout --> StfBuilder --> [ DPL workflow ] --> output proxy --> STFSender --> EPN +/// | +/// +--> Dispatcher --> QC task /// +/// STFSender is downstream of the DPL workflow. It keeps the messages it receives until the EPN has +/// fetched the data, then destroys them. The question is whether this can free a buffer while the QC task +/// still reads its shallow copy. It should not: destroying a message only decrements a reference count kept +/// in shared memory, and the owner of the buffer (readout/StfBuilder) reuses it only when FairMQ calls the +/// region callback, i.e. once the last copy, in any process, is gone. This workflow tests exactly that. +/// +/// Topology of the test +/// -------------------- +/// +/// stfbuilder-like-source --> flp-output-proxy ==(FairMQ channel)==> stf-sender-like +/// | +/// +--> Dispatcher --> qc-task (samples 100%, slow reader) +/// \--> qc-task-half (samples 50%, a second shallow copy of the same messages) +/// +/// - stfbuilder-like-source plays readout + StfBuilder: it owns an unmanaged shared memory region and injects +/// its buffers into DPL without a copy. A buffer is reused only when FairMQ reports it as released (as in +/// StfBuilder's region reclaim callback), and it is then immediately poisoned (overwritten with 0xDE). +/// Any reader still looking at a released buffer therefore sees corrupted data. +/// - flp-output-proxy is the standard DPL output proxy (as o2-dpl-output-proxy on the FLP). It forwards the +/// original messages, without copy, to an external FairMQ channel. +/// - stf-sender-like plays STFSender: it receives the messages from that channel, outside of the DPL data +/// flow, checks them and destroys them, by default right away. With --stf-sender-hold-ms it keeps them for +/// a while and destroys them from a separate thread, like STFSender does once the EPN has fetched the data. +/// - qc-task and qc-task-half are the local QC tasks. They read each payload twice, with a pause in between, +/// while holding the message. Right before the second read, they check whether they are the last holder of +/// the buffer (shared memory reference count == 1), i.e. whether STFSender and everybody else already +/// destroyed their copy. The second read must still find intact data. +/// +/// Checks (the workflow exits with a non-zero code if any fails) +/// ------ +/// - every payload read by any device is intact: not poisoned, not corrupted, right size; +/// - stf-sender-like and qc-task receive all the parts (nothing lost); +/// - stf-sender-like receives the source's region buffers, i.e. the output proxy did not copy them +/// (otherwise the test would be meaningless); +/// - the QC tasks receive the source's region buffers, i.e. the Dispatcher did not copy them +/// (disable with --allow-deep-copy, e.g. to run against a Dispatcher which still copies); +/// - the scenario of concern actually happened: stf-sender-like destroyed messages while a QC task still held +/// them, and qc-task read buffers after it became their last holder (the latter is not required with +/// --stf-sender-hold-ms > 0, since then which of STFSender and QC releases last depends on timing). +/// These checks need a run of some length: with very few timeframes, everything may arrive in STFSender +/// only once QC is done, and the test fails with "the scenario was not exercised". +/// At the end of stream each device prints a summary, e.g.: +/// [stf-sender-like] Received 2000 parts, 0 errors, 2000 in the source's region, 0 copied, 1976 destroyed while still held by another process +/// [qc-task] Checked 2000 parts, 0 errors, 2000 in the source's region, 0 copied, 1952 read intact as the last holder of the buffer +/// +/// How to run it +/// ------------- /// # build (from the O2 build directory, with the O2 environment loaded) /// ninja stage/bin/o2-datasampling-datasampling-shared-payload /// -/// # default run: 500 timeframes x 4 parts x 1 MB, 32 buffers in the region +/// # default run: 500 timeframes x 4 parts x 1 MB, 32 buffers in the region, STFSender destroys messages immediately /// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 /// -/// # make the direct consumer read the buffers at the same time as the Dispatcher and the sampled consumers -/// # (by default DPL forwards the data to the Dispatcher only after the direct consumer has processed it) -/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 --early-forward-policy always -/// /// # heavier run: small region, so that buffers are released, poisoned and reused all the time -/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 --early-forward-policy always \ +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 \ /// --timeframes 3000 --parts 8 --block-size 65536 --blocks 24 /// -/// The workflow exits with 0 on success. Each consumer prints a summary at the end of stream, e.g. -/// Checked 2000 parts, 0 errors, 2000 in the producer's region, 0 copied, 850 seen while still shared with another reader -/// It exits with a non-zero code if a payload fails the verification ("payload has been poisoned", "corrupted word"), -/// if a consumer receives no data, or if sampled payloads were deep copies ("... sampled payloads were deep copies"). -/// The latter check can be disabled with --allow-deep-copy, e.g. to run the test against a Dispatcher which copies. -/// Only the shared memory transport (the DPL default) is supported. +/// # STFSender keeps the messages for a while before destroying them (other release order) +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 --stf-sender-hold-ms 20 +/// +/// Only the shared memory transport (the DPL default) is supported. The STFSender stand-in uses an IPC socket +/// in the default DPL IPC folder (abstract socket on Linux, /tmp on macOS), so two instances of the test +/// cannot run at the same time on one machine. /// /// Generated with Claude @@ -72,19 +113,23 @@ void customize(std::vector& workflowOptions) workflowOptions.push_back(ConfigParamSpec{"parts", VariantType::Int, 4, {"number of parts (subspecs) per timeframe"}}); workflowOptions.push_back(ConfigParamSpec{"block-size", VariantType::Int, 1 << 20, {"size of each payload in bytes"}}); workflowOptions.push_back(ConfigParamSpec{"blocks", VariantType::Int, 32, {"number of payload buffers in the unmanaged region"}}); + workflowOptions.push_back(ConfigParamSpec{"stf-sender-hold-ms", VariantType::Int, 0, {"how long the STFSender stand-in keeps messages before destroying them"}}); workflowOptions.push_back(ConfigParamSpec{"allow-deep-copy", VariantType::Bool, false, {"do not fail if sampled payloads are copies instead of the original region buffers"}}); } #include "Framework/runDataProcessing.h" #include "Framework/ControlService.h" #include "Framework/CallbackService.h" +#include "Framework/ChannelSpecHelpers.h" #include "Framework/DataRefUtils.h" +#include "Framework/ExternalFairMQDeviceProxy.h" #include "Framework/FairMQDeviceProxy.h" #include "Framework/Logger.h" #include "Framework/RoutingIndices.h" #include "DataSampling/DataSamplingHeader.h" #include "Headers/DataHeader.h" +#include #include #include #include @@ -94,6 +139,7 @@ void customize(std::vector& workflowOptions) #include #include #include +#include #include #include @@ -162,21 +208,22 @@ struct RegionPool { } }; -DataProcessorSpec getProducer(int nTimeframes, int nParts, size_t blockSize, size_t nBlocks) +/// Plays readout + StfBuilder: owns an unmanaged region and injects its buffers into DPL without a copy. +DataProcessorSpec getSource(int nTimeframes, int nParts, size_t blockSize, size_t nBlocks) { Outputs outputs; for (int p = 0; p < nParts; ++p) { outputs.emplace_back(OutputSpec{"TST", "RAWDATA", static_cast(p)}); } return DataProcessorSpec{ - .name = "stf-like-producer", + .name = "stfbuilder-like-source", .inputs = {}, .outputs = outputs, .algorithm = adaptStateful([nTimeframes, nParts, blockSize, nBlocks](CallbackService& callbacks) { auto pool = std::make_shared(); pool->blockSize = blockSize; auto tf = std::make_shared(0); - // the region has to be destroyed before the transport which created it, like STFSender does + // the region has to be destroyed before the transport which created it callbacks.set([pool]() { LOG(info) << "Destroying the unmanaged region, " << pool->released << " buffers were released"; pool->region.reset(); @@ -193,8 +240,8 @@ DataProcessorSpec getProducer(int nTimeframes, int nParts, size_t blockSize, siz pool->region = transport->CreateUnmanagedRegion( cfg.size, [rawPool](const std::vector& blocks) { - // like STFSender: once released, a buffer gets new content. Poisoning it makes any reader which - // still (wrongly) uses it fail. + // Called by FairMQ once the last copy of a message, in any process, is destroyed. + // Like StfBuilder, we then reuse the buffer. Poisoning it makes any reader which still uses it fail. std::lock_guard lock(rawPool->mutex); for (const auto& block : blocks) { std::memset(block.ptr, poisonByte, rawPool->blockSize); @@ -232,36 +279,41 @@ DataProcessorSpec getProducer(int nTimeframes, int nParts, size_t blockSize, siz })}; } -DataProcessorSpec getChecker(std::string name, InputSpec input, size_t blockSize, std::chrono::microseconds holdTime, bool sampled, bool expectZeroCopy) +/// A local QC task, reading sampled data from the Dispatcher. +DataProcessorSpec getQcTask(std::string name, InputSpec input, size_t blockSize, std::chrono::microseconds holdTime, + uint64_t expectedParts, bool requireLastHolderReads, bool expectZeroCopy) { return DataProcessorSpec{ .name = std::move(name), .inputs = {std::move(input)}, .outputs = {}, - .algorithm = adaptStateful([blockSize, holdTime, sampled, expectZeroCopy](CallbackService& callbacks) { + .algorithm = adaptStateful([blockSize, holdTime, expectedParts, requireLastHolderReads, expectZeroCopy](CallbackService& callbacks) { struct Stats { uint64_t parts = 0; uint64_t errors = 0; uint64_t inRegion = 0; uint64_t notInRegion = 0; - uint64_t sharedRefs = 0; + uint64_t lastHolderReads = 0; }; auto stats = std::make_shared(); - callbacks.set([stats, sampled, expectZeroCopy](EndOfStreamContext&) { + callbacks.set([stats, expectedParts, requireLastHolderReads, expectZeroCopy](EndOfStreamContext&) { LOG(info) << "Checked " << stats->parts << " parts, " << stats->errors << " errors, " - << stats->inRegion << " in the producer's region, " << stats->notInRegion << " copied, " - << stats->sharedRefs << " seen while still shared with another reader"; + << stats->inRegion << " in the source's region, " << stats->notInRegion << " copied, " + << stats->lastHolderReads << " read intact as the last holder of the buffer"; if (stats->errors > 0) { LOG(fatal) << "Payload verification failed " << stats->errors << " times"; } - if (stats->parts == 0) { - LOG(fatal) << "No data received"; + if (stats->parts == 0 || (expectedParts > 0 && stats->parts != expectedParts)) { + LOG(fatal) << "Received " << stats->parts << " parts, expected " << (expectedParts > 0 ? std::to_string(expectedParts) : "some"); } - if (sampled && expectZeroCopy && stats->notInRegion > 0) { + if (expectZeroCopy && stats->notInRegion > 0) { LOG(fatal) << stats->notInRegion << " sampled payloads were deep copies"; } + if (requireLastHolderReads && stats->lastHolderReads == 0) { + LOG(fatal) << "Never read a buffer after all other holders released it, the scenario was not exercised"; + } }); - return adaptStateless([stats, blockSize, holdTime, sampled](ProcessingContext& ctx) { + return adaptStateless([stats, blockSize, holdTime](ProcessingContext& ctx) { for (auto inputIt = ctx.inputs().begin(); inputIt != ctx.inputs().end(); ++inputIt) { auto parts = inputIt.parts(); for (auto partIt = parts.begin(); partIt != parts.end(); ++partIt) { @@ -270,30 +322,33 @@ DataProcessorSpec getChecker(std::string name, InputSpec input, size_t blockSize continue; } const auto* dh = DataRefUtils::getHeader(ref); - if (sampled && DataRefUtils::getHeader(ref) == nullptr) { + if (DataRefUtils::getHeader(ref) == nullptr) { LOG(error) << "Missing DataSamplingHeader"; stats->errors++; } const auto size = DataRefUtils::getPayloadSize(ref); stats->parts++; - if (auto* shmMessage = dynamic_cast(parts.getPayloadAtIndices(partIt.indices()))) { - shmMessage->GetMeta().fManaged ? stats->notInRegion++ : stats->inRegion++; - if (shmMessage->GetRefCount() > 1) { - stats->sharedRefs++; - } + auto* shmMessage = dynamic_cast(parts.getPayloadAtIndices(partIt.indices())); + if (shmMessage != nullptr && !shmMessage->GetMeta().fManaged) { + stats->inRegion++; } else { stats->notInRegion++; } - // read twice, holding the message in between, so that the other readers work on it at the same time + // read twice, holding the message in between, so that the other holders release their copies meanwhile for (int pass = 0; pass < 2; ++pass) { + // before the second read: are we the only holder left, i.e. did STFSender already destroy its copy? + const bool lastHolder = pass == 1 && shmMessage != nullptr && shmMessage->GetRefCount() == 1; if (auto failure = checkPayload(ref.payload, size, blockSize, dh->subSpecification); !failure.empty()) { LOG(error) << "Verification of " << dh->dataOrigin.as() << "/" << dh->dataDescription.as() - << "/" << dh->subSpecification << " failed (pass " << pass << "): " << failure; + << "/" << dh->subSpecification << " failed (pass " << pass << (lastHolder ? ", last holder" : "") << "): " << failure; stats->errors++; break; } + if (lastHolder) { + stats->lastHolderReads++; + } if (pass == 0) { std::this_thread::sleep_for(holdTime); } @@ -303,6 +358,112 @@ DataProcessorSpec getChecker(std::string name, InputSpec input, size_t blockSize }); })}; } + +std::string stfSenderChannelAddress() +{ + auto folder = ChannelSpecHelpers::defaultIPCFolder(); + if (!folder.empty() && folder[0] != '@' && folder.back() != '/') { + folder += '/'; + } + return "ipc://" + folder + "o2-datasampling-shared-payload-stf-sender"; +} + +/// Plays STFSender: receives the messages from the DPL output proxy over a FairMQ channel, outside of the +/// DPL data flow, checks them and destroys them (immediately, or after holdTime). +DataProcessorSpec getStfSenderLike(size_t blockSize, std::chrono::milliseconds holdTime, uint64_t expectedParts) +{ + struct State { + using Clock = std::chrono::steady_clock; + std::mutex mutex; + std::deque> held; + std::jthread releaseThread; + uint64_t parts = 0; + uint64_t errors = 0; + uint64_t inRegion = 0; + uint64_t notInRegion = 0; + uint64_t destroyedWhileShared = 0; + + void release(bool all) + { + std::lock_guard lock(mutex); + const auto now = Clock::now(); + while (!held.empty() && (all || held.front().first <= now)) { + auto* shmMessage = dynamic_cast(held.front().second.get()); + if (shmMessage != nullptr && shmMessage->GetRefCount() > 1) { + destroyedWhileShared++; // somebody else (a QC task) still holds this buffer + } + held.pop_front(); // this is what STFSender does once the EPN has the data: destroy the message + } + } + + void hold(Clock::time_point until, fair::mq::MessagePtr message) + { + std::lock_guard lock(mutex); + held.emplace_back(until, std::move(message)); + } + }; + auto state = std::make_shared(); + + auto converter = [state, blockSize, holdTime, expectedParts](TimingInfo&, ServiceRegistryRef const&, fair::mq::Parts& parts, ChannelRetriever, size_t, bool&) -> bool { + if (holdTime.count() > 0 && !state->releaseThread.joinable()) { + // like STFSender's dealloc thread: messages are destroyed once "acknowledged", independently of new data arriving. + // Started here, so that it exists only in this device and not in every process which builds the workflow. + state->releaseThread = std::jthread([rawState = state.get()](std::stop_token stop) { + while (!stop.stop_requested()) { + rawState->release(false); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + }); + } + bool endOfStream = false; + for (int i = 0; i + 1 < parts.Size(); i += 2) { + const auto* dh = o2::header::get(parts.At(i)->GetData()); + if (dh == nullptr) { + continue; + } + if (dh->dataDescription == o2::header::gDataDescriptionEos) { + endOfStream = true; + continue; + } + state->parts++; + auto& payload = parts.At(i + 1); + if (auto failure = checkPayload(static_cast(payload->GetData()), payload->GetSize(), blockSize, dh->subSpecification); !failure.empty()) { + LOG(error) << "Verification of " << dh->dataOrigin.as() << "/" << dh->dataDescription.as() + << "/" << dh->subSpecification << " failed: " << failure; + state->errors++; + } + auto* shmMessage = dynamic_cast(payload.get()); + (shmMessage != nullptr && !shmMessage->GetMeta().fManaged) ? state->inRegion++ : state->notInRegion++; + state->hold(State::Clock::now() + holdTime, std::move(payload)); + } + state->release(endOfStream); + + if (endOfStream) { + state->releaseThread.request_stop(); + std::lock_guard lock(state->mutex); + LOG(info) << "Received " << state->parts << " parts, " << state->errors << " errors, " + << state->inRegion << " in the source's region, " << state->notInRegion << " copied, " + << state->destroyedWhileShared << " destroyed while still held by another process"; + if (state->errors > 0) { + LOG(fatal) << "Payload verification failed " << state->errors << " times"; + } + if (state->parts != expectedParts) { + LOG(fatal) << "Received " << state->parts << " parts, expected " << expectedParts; + } + if (state->notInRegion > 0) { + LOG(fatal) << state->notInRegion << " payloads did not come from the source's region, the output proxy copied them"; + } + if (state->destroyedWhileShared == 0) { + LOG(fatal) << "Never destroyed a message still held by a QC task, the scenario was not exercised"; + } + } + return false; // nothing is sent further + }; + + // no name: the proxy names the channel after itself, it reads only channels whose name starts with its own + const auto channelConfig = "type=pull,method=connect,address=" + stfSenderChannelAddress() + ",transport=shmem,rateLogging=0"; + return specifyExternalFairMQDeviceProxy("stf-sender-like", {OutputSpec{"TST", "STFSENT"}}, channelConfig.c_str(), converter); +} } // namespace WorkflowSpec defineDataProcessing(ConfigContext const& config) @@ -311,15 +472,25 @@ WorkflowSpec defineDataProcessing(ConfigContext const& config) const int nParts = config.options().get("parts"); const size_t blockSize = config.options().get("block-size"); const size_t nBlocks = config.options().get("blocks"); + const int stfSenderHoldMs = config.options().get("stf-sender-hold-ms"); const bool expectZeroCopy = !config.options().get("allow-deep-copy"); + const uint64_t totalParts = static_cast(nTimeframes) * nParts; WorkflowSpec specs; - specs.push_back(getProducer(nTimeframes, nParts, blockSize, nBlocks)); - specs.push_back(getChecker("direct-consumer", InputSpec{"raw", ConcreteDataTypeMatcher{"TST", "RAWDATA"}}, blockSize, std::chrono::microseconds(500), false, expectZeroCopy)); - specs.push_back(getChecker("sampled-consumer-all", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "sharedAll0"}, Lifetime::Sporadic}, blockSize, std::chrono::milliseconds(2), true, expectZeroCopy)); - specs.push_back(getChecker("sampled-consumer-half", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "sharedHalf0"}, Lifetime::Sporadic}, blockSize, std::chrono::milliseconds(5), true, expectZeroCopy)); + specs.push_back(getSource(nTimeframes, nParts, blockSize, nBlocks)); + + // the FLP output: DPL output proxy -> STFSender + const auto outputProxyChannelConfig = "name=stf-sender,type=push,method=bind,address=" + stfSenderChannelAddress() + ",transport=shmem,rateLogging=0"; + specs.push_back(specifyFairMQDeviceOutputProxy("flp-output-proxy", {InputSpec{"raw", ConcreteDataTypeMatcher{"TST", "RAWDATA"}}}, outputProxyChannelConfig.c_str())); + specs.push_back(getStfSenderLike(blockSize, std::chrono::milliseconds(stfSenderHoldMs), totalParts)); + + // local QC: qc-task is the slow reader which should outlive STFSender's copy + specs.push_back(getQcTask("qc-task", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "qcAll0"}, Lifetime::Sporadic}, blockSize, + std::chrono::milliseconds(5), totalParts, stfSenderHoldMs == 0, expectZeroCopy)); + specs.push_back(getQcTask("qc-task-half", InputSpec{"raw", ConcreteDataTypeMatcher{"DS", "qcHalf0"}, Lifetime::Sporadic}, blockSize, + std::chrono::milliseconds(2), 0, false, expectZeroCopy)); - // two policies on the same data: the Dispatcher forwards the same input message twice + // two policies on the same data: the Dispatcher forwards two shallow copies of the same input message auto makePolicy = [](const std::string& id, const std::string& fraction) { boost::property_tree::ptree condition; condition.put("condition", "random"); @@ -336,8 +507,8 @@ WorkflowSpec defineDataProcessing(ConfigContext const& config) return policy; }; boost::property_tree::ptree policies; - policies.push_back({"", makePolicy("sharedAll", "1.0")}); - policies.push_back({"", makePolicy("sharedHalf", "0.5")}); + policies.push_back({"", makePolicy("qcAll", "1.0")}); + policies.push_back({"", makePolicy("qcHalf", "0.5")}); DataSampling::GenerateInfrastructure(specs, policies); return specs;