diff --git a/receiver/JFJochReceiverFPGA.cpp b/receiver/JFJochReceiverFPGA.cpp index 5bb5d2847..3da176215 100644 --- a/receiver/JFJochReceiverFPGA.cpp +++ b/receiver/JFJochReceiverFPGA.cpp @@ -145,7 +145,11 @@ JFJochReceiverFPGA::JFJochReceiverFPGA(const DiffractionExperiment &in_experimen s.adaptive_threshold = true; s.min_pix_per_spot = std::nullopt; return s; - }, rugnux_status); + }, + // The start message did not go out (or the analysis could not be set up): nothing can + // be written, so the collection stops, as it does on an error in a frame thread. + [this](const JFJochException &e) { Cancel(e); }, + rugnux_status); } else { SendStartMessage(); SendCalibration(); @@ -645,13 +649,22 @@ void JFJochReceiverFPGA::FinalizeMeasurement() { logger.Debug("All processing threads done"); } - if (gpu) - gpu->Finish(); + // Where the start message never went out (or the analysis could not be set up), there is no end + // message either: the devices are stopped all the same, and the error is the collection's result. + std::exception_ptr gpu_error; + if (gpu) { + try { + gpu->Finish(); + } catch (const std::exception &) { + gpu_error = std::current_exception(); + } + } current_status.SetProgress(1.0); current_status.SetStatus(GetStatus()); - SendEndMessage(); + if (!gpu_error) + SendEndMessage(); if (experiment.GetImageNum() > 0) { for (int d = 0; d < ndatastreams; d++) @@ -670,6 +683,11 @@ void JFJochReceiverFPGA::FinalizeMeasurement() { throw JFJochException(JFJochExceptionCategory::ZeroMQ, "Send commands not finalized in " + std::to_string(SendFinalizeTimeout.count()) + " seconds"); } + if (gpu_error) { + current_status.SetProgress({}); + current_status.SetStatus(GetStatus()); + std::rethrow_exception(gpu_error); + } logger.Info("Receiving data done"); if (push_images_to_writer) @@ -809,6 +827,11 @@ void JFJochReceiverFPGA::GPUSink(DataMessage &message, const AzimuthalIntegratio } catch (const JFJochException &e) { logger.ErrorException(e); Cancel(e); + } catch (const std::exception &e) { + const JFJochException error(JFJochExceptionCategory::WrongDAQState, + fmt::format("Image {} not written - {}", message.number, e.what())); + logger.ErrorException(error); + Cancel(error); } } diff --git a/receiver/StillsGPUAnalysis.cpp b/receiver/StillsGPUAnalysis.cpp index 8ef27a838..7e84c5e5d 100644 --- a/receiver/StillsGPUAnalysis.cpp +++ b/receiver/StillsGPUAnalysis.cpp @@ -11,10 +11,10 @@ StillsGPUAnalysis::StillsGPUAnalysis(const DiffractionExperiment &in_experiment, const PixelMask &in_mask, const StartMessage &in_start, IndexerThreadPool *in_indexing_thread_pool, int64_t nthreads, Logger &in_logger, Ready in_ready, Sink in_sink, - Settings in_settings, RugnuxLiveStatus *in_status) + Settings in_settings, Failed in_failed, RugnuxLiveStatus *in_status) : experiment(in_experiment), mask(in_mask), start(in_start), indexing_thread_pool(in_indexing_thread_pool), logger(in_logger), ready(std::move(in_ready)), sink(std::move(in_sink)), settings(std::move(in_settings)), - status(in_status) { + setup_failed(std::move(in_failed)), status(in_status) { live.images_needed = std::min(PREPASS_IMAGES, experiment.GetImageNum()); live.file_beam_x_pxl = experiment.GetBeamX_pxl(); live.file_beam_y_pxl = experiment.GetBeamY_pxl(); @@ -34,8 +34,19 @@ StillsGPUAnalysis::StillsGPUAnalysis(const DiffractionExperiment &in_experiment, } StillsGPUAnalysis::~StillsGPUAnalysis() { - if (!finished) - Finish(); + try { + if (!finished) + Finish(); + } catch (const std::exception &e) { + logger.Error("GPU analysis: {}", e.what()); + } +} + +void StillsGPUAnalysis::AnalysisError(const std::string &text) { + logger.Error("GPU analysis: {}", text); + std::unique_lock ul(error_mutex); + if (analysis_error.empty()) + analysis_error = text; } void StillsGPUAnalysis::Publish() { @@ -90,8 +101,18 @@ void StillsGPUAnalysis::Finish() { if (status) { status->LastImage(); Publish(); - status->Finish(RugnuxLiveState::Done); + if (setup_error) + status->Finish(RugnuxLiveState::Failed, "GPU analysis setup failed"); + else { + std::unique_lock ul(error_mutex); + if (analysis_error.empty()) + status->Finish(RugnuxLiveState::Done); + else + status->Finish(RugnuxLiveState::Failed, analysis_error); + } } + if (setup_error) + std::rethrow_exception(setup_error); } void StillsGPUAnalysis::PrePassThread() { @@ -145,10 +166,23 @@ void StillsGPUAnalysis::PrePassThread() { } } sample.clear(); - setup.mapping = std::make_unique(setup.experiment, setup.mask); - indexer = std::make_unique(setup.experiment, indexing_thread_pool, false, true); - - ready(setup); + try { + setup.mapping = std::make_unique(setup.experiment, setup.mask); + indexer = std::make_unique(setup.experiment, indexing_thread_pool, false, true); + ready(setup); + } catch (const std::exception &e) { + // Nothing can be written without the start message: the frames are dropped (AnalysisThread), and + // the collection is stopped. + const auto *j = dynamic_cast(&e); + const JFJochException error = j ? *j : JFJochException(JFJochExceptionCategory::WrongDAQState, + std::string("GPU analysis setup failed: ") + e.what()); + logger.ErrorException(error); + setup_error = j ? std::current_exception() : std::make_exception_ptr(error); + if (setup_failed) + setup_failed(error); + prepass_done.count_down(); + return; + } { std::unique_lock ul(live_mutex); live.prepass = failed ? RugnuxLivePrePass::Failed : RugnuxLivePrePass::Done; @@ -165,38 +199,58 @@ void StillsGPUAnalysis::PrePassThread() { void StillsGPUAnalysis::AnalysisThread() { try { pin_gpu(); - } catch (const JFJochException &e) { + } catch (const std::exception &e) { logger.Warning("Error pinning GPU {}", e.what()); } prepass_done.wait(); - MXAnalysisWithoutFPGA analysis(setup.experiment, *setup.mapping, setup.mask, *indexer, - /*enable_fused_adaptive_gpu=*/true); + if (setup_error) { + while (queue.GetBlocking()) {} + return; + } + + // A thread whose analysis cannot be built still passes its frames on, unanalysed. + std::unique_ptr analysis; + try { + analysis = std::make_unique(setup.experiment, *setup.mapping, setup.mask, *indexer, + /*enable_fused_adaptive_gpu=*/true); + } catch (const std::exception &e) { + AnalysisError(std::string("analysis thread could not start, its frames are written unanalysed - ") + + e.what()); + } while (auto held = queue.GetBlocking()) { DataMessage &message = held->message; AzimuthalIntegrationProfile profile(*setup.mapping); const auto start_time = std::chrono::steady_clock::now(); try { - analysis.Analyze(message, profile, settings()); + if (analysis) + analysis->Analyze(message, profile, settings()); } catch (const JFJochException &e) { // The frame is still written, without its analysis. logger.ErrorException(e); + } catch (const std::exception &e) { + AnalysisError(fmt::format("image {} written unanalysed - {}", message.number, e.what())); } message.processing_time_s = std::chrono::duration(std::chrono::steady_clock::now() - start_time).count(); - sink(message, profile); - if (status) { - int64_t analysed; - { - std::unique_lock ul(live_mutex); - analysed = ++live.images_analysed; - if (message.indexing_result.value_or(false)) - ++live.images_indexed; + try { + sink(message, profile); + if (status) { + int64_t analysed; + { + std::unique_lock ul(live_mutex); + analysed = ++live.images_analysed; + if (message.indexing_result.value_or(false)) + ++live.images_indexed; + } + status->Progress(analysed, experiment.GetImageNum()); + Publish(); } - status->Progress(analysed, experiment.GetImageNum()); - Publish(); + } catch (const std::exception &e) { + // The thread goes on with the next frame, so that the queue is drained. + AnalysisError(fmt::format("image {} lost - {}", message.number, e.what())); } } } diff --git a/receiver/StillsGPUAnalysis.h b/receiver/StillsGPUAnalysis.h index ba21cc9c2..9223b503f 100644 --- a/receiver/StillsGPUAnalysis.h +++ b/receiver/StillsGPUAnalysis.h @@ -4,6 +4,7 @@ #pragma once #include +#include #include #include #include @@ -15,6 +16,7 @@ #include "StillsPrePass.h" #include "RugnuxLiveStatus.h" #include "../common/DiffractionExperiment.h" +#include "../common/JFJochException.h" #include "../common/AzimuthalIntegrationMapping.h" #include "../common/AzimuthalIntegrationProfile.h" #include "../common/Logger.h" @@ -27,6 +29,9 @@ // geometry and mask the frames are then analysed at, before any of them is analysed; `sink` gets each // frame once analysed, from one of the analysis threads. Where `status` is given, the run is reported there // (pre-pass, its decisions, the analysis). +// Where the setup after the pre-pass fails (`ready` included), `failed` is called at once, the frames are +// dropped unanalysed and Finish throws the error. An analysis thread that fails passes its frames on +// unanalysed, and the run is reported as failed. class StillsGPUAnalysis { public: constexpr static int64_t PREPASS_IMAGES = 100; @@ -39,16 +44,18 @@ public: using Ready = std::function; using Sink = std::function; using Settings = std::function; + using Failed = std::function; // `start`: the collection's start message, as it would be sent without the pre-pass. StillsGPUAnalysis(const DiffractionExperiment &experiment, const PixelMask &mask, const StartMessage &start, IndexerThreadPool *indexing_thread_pool, int64_t nthreads, Logger &logger, - Ready ready, Sink sink, Settings settings, RugnuxLiveStatus *status = nullptr); + Ready ready, Sink sink, Settings settings, Failed failed = {}, + RugnuxLiveStatus *status = nullptr); ~StillsGPUAnalysis(); void Hold(const std::shared_ptr &image); // No frame comes after this: the pre-pass runs on what came, if it has not, and every frame is - // analysed before it returns. + // analysed before it returns. Throws where the setup after the pre-pass failed. void Finish(); // After Finish. @@ -66,6 +73,7 @@ private: Ready ready; Sink sink; Settings settings; + Failed setup_failed; RugnuxLiveStatus *status; std::mutex live_mutex; @@ -82,6 +90,11 @@ private: int64_t images_held = 0; std::map> prepass_images; std::latch prepass_done{1}; + std::exception_ptr setup_error; // set before prepass_done + + std::mutex error_mutex; + std::string analysis_error; // the first, where an analysis thread failed + void AnalysisError(const std::string &text); ThreadSafeFIFO> queue; std::future prepass_future; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index fbc70d3bc..5592b2f66 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -127,6 +127,7 @@ ADD_EXECUTABLE(jfjoch_test ModuleRefinementTest.cpp LiveCollectionTest.cpp RugnuxLiveStatusTest.cpp + StillsGPUAnalysisTest.cpp RugnuxStructureTest.cpp SweepLayoutTest.cpp BrukerReaderTest.cpp diff --git a/tests/JFJochReceiverProcessingTest.cpp b/tests/JFJochReceiverProcessingTest.cpp index ed36b2fce..8cd8d6bea 100644 --- a/tests/JFJochReceiverProcessingTest.cpp +++ b/tests/JFJochReceiverProcessingTest.cpp @@ -188,6 +188,61 @@ TEST_CASE("JFJochIntegrationTest_ZMQ_crystal_spot_and_index_GPUStills", "[JFJoch REQUIRE_NOTHROW(writer_future.get()); } +TEST_CASE("JFJochIntegrationTest_ZMQ_GPUStills_writer_down", "[JFJochReceiver]") { + // The start message goes out after the pre-pass: with no writer listening, the collection ends with + // the error, and the next one runs. + Logger logger(Catch::getResultCapture().getCurrentTestName()); + + RegisterHDF5Filter(); + + DiffractionExperiment experiment(DetJF4M()); + experiment.ImagesPerTrigger(5).NumTriggers(1).UseInternalPacketGenerator(true).ImagesPerFile(2) + .FilePrefix("crystal_test_gpu_stills_writer_down").JungfrauConvPhotonCnt(false) + .SetFileWriterFormat(FileWriterFormat::NXmxVDS).OverwriteExistingFiles(true) + .DetectorDistance_mm(75).BeamY_pxl(1136).BeamX_pxl(1090).IncidentEnergy_keV(12.4) + .SetUnitCell(UnitCell{.a = 36.9, .b = 78.95, .c = 78.95, .alpha =90, .beta = 90, .gamma = 90}); + + PixelMask pixel_mask(experiment); + + HDF5ReadOnlyFile data("../../tests/test_data/compression_benchmark.h5"); + HDF5DataSet dataset(data, "/entry/data/data"); + HDF5DataSpace file_space(dataset); + std::vector image_conv (file_space.GetDimensions()[1] * file_space.GetDimensions()[2]); + std::vector start = {4,0,0}; + std::vector file_size = {1, file_space.GetDimensions()[1], file_space.GetDimensions()[2]}; + dataset.ReadVector(image_conv, start, file_size); + std::vector image_raw_geom(experiment.GetModulesNum() * RAW_MODULE_SIZE); + ConvertedToRawGeometry(experiment, image_raw_geom.data(), image_conv.data()); + + AcquisitionDeviceGroup aq_devices; + std::unique_ptr test = std::make_unique(0, 64); + for (int m = 0; m < experiment.GetModulesNum(); m++) + test->SetInternalGeneratorFrame((uint16_t *) image_raw_geom.data() + m * RAW_MODULE_SIZE, m); + aq_devices.Add(std::move(test)); + + ZMQStream2Pusher pusher({"ipc://*"}); + pusher.WriterNotificationSocket("ipc://*"); + + JFJochReceiverService service(aq_devices, logger, pusher); + service.NumThreads(4); + service.Indexing(experiment.GetIndexingSettings()); + service.RugnuxLive(true, nullptr, 4, 60); + + service.Start(experiment, pixel_mask, nullptr); + REQUIRE_THROWS_AS(service.Stop(), JFJochException); + REQUIRE(!service.GetProgress().has_value()); + + ZMQImagePuller puller(pusher.GetAddress()[0]); + StreamWriter writer(logger, puller); + auto writer_future = std::async(std::launch::async, &StreamWriter::Run, &writer); + + service.Start(experiment, pixel_mask, nullptr); + auto receiver_out = service.Stop(); + CHECK(receiver_out.status.images_sent == experiment.GetImageNum()); + CHECK(!receiver_out.status.cancelled); + REQUIRE_NOTHROW(writer_future.get()); +} + TEST_CASE("JFJochIntegrationTest_ZMQ_crystal_spot_and_index_refinement", "[JFJochReceiver]") { Logger logger(Catch::getResultCapture().getCurrentTestName()); diff --git a/tests/StillsGPUAnalysisTest.cpp b/tests/StillsGPUAnalysisTest.cpp new file mode 100644 index 000000000..a78d88dac --- /dev/null +++ b/tests/StillsGPUAnalysisTest.cpp @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include + +#include + +#include "../receiver/StillsGPUAnalysis.h" + +namespace { + DiffractionExperiment StillsExperiment() { + DiffractionExperiment x(DetJF(1)); + x.ImagesPerTrigger(200).NumTriggers(1).DetectorDistance_mm(100).BeamX_pxl(500).BeamY_pxl(250) + .IncidentEnergy_keV(12.4); + return x; + } + + // A frame after the pre-pass's sample (numbers from PREPASS_IMAGES on are never in it). + std::shared_ptr Frame(int64_t number) { + auto held = std::make_shared(); + held->message.number = StillsGPUAnalysis::PREPASS_IMAGES + number; + held->message.image_collection_efficiency = 1.0f; + return held; + } + + StartMessage Start(const DiffractionExperiment &x) { + StartMessage start; + x.FillMessage(start); + return start; + } +} + +TEST_CASE("StillsGPUAnalysis_StartFailureReleasesThreads", "[StillsGPUAnalysis]") { + Logger logger(Catch::getResultCapture().getCurrentTestName()); + const DiffractionExperiment x = StillsExperiment(); + const PixelMask mask(x); + RugnuxLiveStatus status; + + std::atomic failed = 0, sunk = 0; + { + StillsGPUAnalysis gpu(x, mask, Start(x), nullptr, 4, logger, + [](const StillsGPUAnalysis::Setup &) { + throw JFJochException(JFJochExceptionCategory::ZeroMQ, "Timeout on pushing start message"); + }, + [&](DataMessage &, const AzimuthalIntegrationProfile &) { ++sunk; }, + [] { return DiffractionExperiment::DefaultDataProcessingSettings(); }, + [&](const JFJochException &) { ++failed; }, &status); + for (int i = 0; i < 3; i++) + gpu.Hold(Frame(i)); + REQUIRE_THROWS_AS(gpu.Finish(), JFJochException); + } + CHECK(failed == 1); + CHECK(sunk == 0); + CHECK(status.Get().state == RugnuxLiveState::Failed); +} + +TEST_CASE("StillsGPUAnalysis_FailingFrameDoesNotStopAnalysis", "[StillsGPUAnalysis]") { + Logger logger(Catch::getResultCapture().getCurrentTestName()); + const DiffractionExperiment x = StillsExperiment(); + const PixelMask mask(x); + RugnuxLiveStatus status; + + std::atomic sunk = 0; + StillsGPUAnalysis gpu(x, mask, Start(x), nullptr, 1, logger, + [](const StillsGPUAnalysis::Setup &) {}, + [&](DataMessage &m, const AzimuthalIntegrationProfile &) { + ++sunk; + if (m.number == StillsGPUAnalysis::PREPASS_IMAGES) + throw std::runtime_error("not a JFJochException"); + }, + [] { return DiffractionExperiment::DefaultDataProcessingSettings(); }, + {}, &status); + // The frames carry no image, so their analysis fails too - they are passed on all the same. + for (int i = 0; i < 3; i++) + gpu.Hold(Frame(i)); + REQUIRE_NOTHROW(gpu.Finish()); + CHECK(sunk == 3); + CHECK(status.Get().state == RugnuxLiveState::Failed); + CHECK(!status.Get().message.empty()); +}