Live stills: a failed START or analysis thread no longer hangs the broker

With rugnux on, a serial FPGA collection sends its start message only after the pre-pass. If that send
failed (no writer listening), or the azimuthal mapping or IndexAndRefine could not be built, the latch the
analysis threads wait on was never released: no END, and the next /start hung in the receiver's
destructor.

Now the setup after the pre-pass runs in a try. On failure the latch is still released, the analysis
threads drop the held frames (nothing can be written without START), the receiver is cancelled at once
(as on an error in a frame thread), and StillsGPUAnalysis::Finish rethrows the error. FinalizeMeasurement
then skips END, as the old path never had one either, still stops and joins the acquisition devices, and
the error becomes the collection's result: /wait_till_done and /status report it, the state is Idle and
the next /start runs. The non-stills path reports the same error from /start itself, as the start message
is sent in the receiver constructor there; the stills path can only report it once the pre-pass is done.

An analysis thread no longer dies on a non-JFJoch exception: a thread whose MXAnalysisWithoutFPGA cannot
be built passes its frames on unanalysed, a frame whose analysis throws std::exception is written
unanalysed, and a failing sink does not stop the thread, so the queue is always drained and END goes out.
Such errors finish the live status as Failed with the first message. GPUSink also catches std::exception,
and ~StillsGPUAnalysis cannot throw.

Tests: StillsGPUAnalysis_StartFailureReleasesThreads, StillsGPUAnalysis_FailingFrameDoesNotStopAnalysis,
JFJochIntegrationTest_ZMQ_GPUStills_writer_down (HLS-simulated JF4M, no writer, then a writer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdJKPUFLoeAchjzv3x4
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-11-03 13:47:33 +01:00
1 parent 6c5fbc8dae
commit 41696976f4
6 files changed
+255 -29

No files matched your search

+27 -4
View File
@@ -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);
}
}
+77 -23
View File
@@ -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<AzimuthalIntegrationMapping>(setup.experiment, setup.mask);
indexer = std::make_unique<IndexAndRefine>(setup.experiment, indexing_thread_pool, false, true);
ready(setup);
try {
setup.mapping = std::make_unique<AzimuthalIntegrationMapping>(setup.experiment, setup.mask);
indexer = std::make_unique<IndexAndRefine>(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<const JFJochException *>(&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<MXAnalysisWithoutFPGA> analysis;
try {
analysis = std::make_unique<MXAnalysisWithoutFPGA>(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<float>(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()));
}
}
}
+15 -2
View File
@@ -4,6 +4,7 @@
#pragma once
#include <condition_variable>
#include <exception>
#include <functional>
#include <future>
#include <latch>
@@ -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<void(const Setup &)>;
using Sink = std::function<void(DataMessage &, const AzimuthalIntegrationProfile &)>;
using Settings = std::function<SpotFindingSettings()>;
using Failed = std::function<void(const JFJochException &)>;
// `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<HeldImage> &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<int64_t, std::shared_ptr<HeldImage>> 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<std::shared_ptr<HeldImage>> queue;
std::future<void> prepass_future;
+1
View File
@@ -127,6 +127,7 @@ ADD_EXECUTABLE(jfjoch_test
ModuleRefinementTest.cpp
LiveCollectionTest.cpp
RugnuxLiveStatusTest.cpp
StillsGPUAnalysisTest.cpp
RugnuxStructureTest.cpp
SweepLayoutTest.cpp
BrukerReaderTest.cpp
+55
View File
@@ -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<int16_t> image_conv (file_space.GetDimensions()[1] * file_space.GetDimensions()[2]);
std::vector<hsize_t> start = {4,0,0};
std::vector<hsize_t> file_size = {1, file_space.GetDimensions()[1], file_space.GetDimensions()[2]};
dataset.ReadVector(image_conv, start, file_size);
std::vector<int16_t> image_raw_geom(experiment.GetModulesNum() * RAW_MODULE_SIZE);
ConvertedToRawGeometry(experiment, image_raw_geom.data(), image_conv.data());
AcquisitionDeviceGroup aq_devices;
std::unique_ptr<HLSSimulatedDevice> test = std::make_unique<HLSSimulatedDevice>(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());
+80
View File
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <catch2/catch_all.hpp>
#include <atomic>
#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<HeldImage> Frame(int64_t number) {
auto held = std::make_shared<HeldImage>();
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<int> 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<int> 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());
}