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..bde504be37fd4 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) { + dataAllocator.forwardPayload(output, *inputPayload, inputHeader->payloadSerializationMethod); + } else { + LOG(error) << "DS: got an empty payload, skipping"; + } } 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..1d0d1d14fe90a --- /dev/null +++ b/Utilities/DataSampling/test/dataSamplingSharedPayload.cxx @@ -0,0 +1,515 @@ +// 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 Checks that STFSender releasing its messages cannot free data still read by a local QC task. +/// +/// 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: +/// +/// 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, STFSender destroys messages immediately +/// o2-datasampling-datasampling-shared-payload -b --run --shm-segment-size 1000000000 +/// +/// # 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 \ +/// --timeframes 3000 --parts 8 --block-size 65536 --blocks 24 +/// +/// # 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 + +#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{"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 +#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; + } +}; + +/// 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 = "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 + 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) { + // 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); + 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); + }); + })}; +} + +/// 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, 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 lastHolderReads = 0; + }; + auto stats = std::make_shared(); + callbacks.set([stats, expectedParts, requireLastHolderReads, expectZeroCopy](EndOfStreamContext&) { + LOG(info) << "Checked " << stats->parts << " parts, " << stats->errors << " errors, " + << 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 || (expectedParts > 0 && stats->parts != expectedParts)) { + LOG(fatal) << "Received " << stats->parts << " parts, expected " << (expectedParts > 0 ? std::to_string(expectedParts) : "some"); + } + 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](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 (DataRefUtils::getHeader(ref) == nullptr) { + LOG(error) << "Missing DataSamplingHeader"; + stats->errors++; + } + const auto size = DataRefUtils::getPayloadSize(ref); + stats->parts++; + + 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 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 << (lastHolder ? ", last holder" : "") << "): " << failure; + stats->errors++; + break; + } + if (lastHolder) { + stats->lastHolderReads++; + } + if (pass == 0) { + std::this_thread::sleep_for(holdTime); + } + } + } + } + }); + })}; +} + +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) +{ + 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 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(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 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"); + 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("qcAll", "1.0")}); + policies.push_back({"", makePolicy("qcHalf", "0.5")}); + DataSampling::GenerateInfrastructure(specs, policies); + + return specs; +}