From 3e2cff174fa2c4bb33bb1579a2a44322df52be3f Mon Sep 17 00:00:00 2001
From: Felix Weiglhofer <weiglhofer@fias.uni-frankfurt.de>
Date: Tue, 30 May 2023 13:56:31 +0000
Subject: [PATCH] algo: Fix issue with freeing buffers in constant memory.

---
 algo/detectors/sts/StsHitfinderChain.cxx | 8 ++++++++
 algo/detectors/sts/StsHitfinderChain.h   | 5 +++++
 algo/global/Reco.cxx                     | 2 ++
 3 files changed, 15 insertions(+)

diff --git a/algo/detectors/sts/StsHitfinderChain.cxx b/algo/detectors/sts/StsHitfinderChain.cxx
index f38562ed95..e2eddc103d 100644
--- a/algo/detectors/sts/StsHitfinderChain.cxx
+++ b/algo/detectors/sts/StsHitfinderChain.cxx
@@ -15,6 +15,14 @@ void sts::HitfinderChain::SetParameters(const sts::HitfinderPars& parameters)
   AllocateStatic();
 }
 
+void sts::HitfinderChain::Finalize()
+{
+  // Explicitly free buffers in constant memory.
+  // This avoids an issue in xpu with teardown order of static variables when using CPU.
+  fHitfinder = {};
+  xpu::set<TheHitfinder>(fHitfinder);
+}
+
 void sts::HitfinderChain::operator()(gsl::span<const CbmStsDigi> digis)
 {
   EnsureParameters();
diff --git a/algo/detectors/sts/StsHitfinderChain.h b/algo/detectors/sts/StsHitfinderChain.h
index 7676a05f17..46e59f733e 100644
--- a/algo/detectors/sts/StsHitfinderChain.h
+++ b/algo/detectors/sts/StsHitfinderChain.h
@@ -43,6 +43,11 @@ namespace cbm::algo::sts
     void SetParameters(const sts::HitfinderPars& parameters);
     const sts::HitfinderPars& GetParameters() const { return *fPars; }
 
+    /**
+     * Teardown chain.
+     */
+    void Finalize();
+
     void operator()(gsl::span<const CbmStsDigi>);
 
   private:
diff --git a/algo/global/Reco.cxx b/algo/global/Reco.cxx
index b8c5b8bc24..0d3c0ffc50 100644
--- a/algo/global/Reco.cxx
+++ b/algo/global/Reco.cxx
@@ -106,6 +106,8 @@ void Reco::Run(const fles::Timeslice& ts)
 
 void Reco::Finalize()
 {
+  fStsHitFinder.Finalize();
+
   // Pop timer that was started in Init()
   xpu::timings t = xpu::pop_timer();
   if (Opts().CollectKernelTimes()) {
-- 
GitLab