delphi-edm4hep
DELPHI SDST/FDST -> EDM4hep converter
Loading...
Searching...
No Matches
PhdstHarness.cpp
Go to the documentation of this file.
1// PhdstHarness.cpp — implementation S5.
2//
3// Drives the PHDST Fortran event loop in-process and dispatches per-event
4// work to user-supplied hooks. PHDST is globally stateful (one instance
5// per process), so the state here is `static` and the user*_ callbacks
6// are Fortran-linkage entry points that the binary's overrides forward to.
7//
8// The binary's user00_..user99_ overrides must live in the *binary* TU
9// (not in this library), because libphdstxx.a / libskelanaxx.a ship
10// default stubs and a static-archive double definition would error.
11
13
15
17
18#include "phdst/functions.hpp" // ph::PHSET, phdst_, ph::IIIRUN etc.
19#include "phdst/phciii.hpp"
20#include "phdst/uxcom.hpp"
21#include "phdst/uxlink.hpp"
22#include "skelana/functions.hpp" // sk::psini_, sk::psbeg_
23#include "skelana/pscflg.hpp"
24
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <exception>
29#include <fstream>
30#include <iostream>
31#include <map>
32#include <memory>
33#include <set>
34#include <string>
35#include <system_error>
36#include <utility>
37#include <vector>
38
39#include <unistd.h>
40
41namespace ph = phdst;
42namespace sk = skelana;
43
45
46namespace {
47
48Config g_cfg;
49std::unique_ptr<podio::ROOTWriter> g_writer;
50
51// Pass-2 only: intermediate edm4hep reader(s) + (run, evt) -> (reader,
52// entry) index. Built once at job start in on_user00. Multiple readers
53// because a run's official short-DST events can span several .al tape
54// files (see Config::input_edm4hep_extra); the index unions them.
55std::vector<std::unique_ptr<podio::ROOTReader>> g_sdst_readers;
56std::map<std::pair<int, int>, std::pair<unsigned, unsigned>> g_sdst_index;
57
58// (run, evt) of every event we have already disposed of this job —
59// written OR deliberately skipped. The data fadana delivers each event
60// as ~3 separate PHDST DST records (Records/DST ~ 3); without this we
61// emit 3 identical frames per event. (run,evt) is unique per physical
62// event, so this dedup is exact.
63std::set<std::pair<int, int>> g_processed;
64
65// Pointer to the currently in-flight per-event Frame so any writer
66// (or hook) needing read access during user02 can grab it.
67const podio::Frame* g_current_sdst_frame = nullptr;
68long g_n_seen = 0;
69long g_n_written = 0;
70long g_n_no_dst = 0;
71long g_n_redelivered = 0;
72bool g_callback_failed = false;
73std::string g_callback_failure;
74
75// Configure SKELANA IFL* flags. These activate the standard DELPHI
76// analysis processors and are copied verbatim from
77// delphi-nanoaod/config/delphi-nanoaod.yaml (the same values the current
78// SDST converter uses; bit-by-bit-compatible output).
79void setSkelanaFlags() {
80 sk::IFLTRA = 1;
81 sk::IFLODR = 1;
82 sk::IFLVEC = 22;
83 sk::IFLSTR = 11;
84 sk::IFLCUT = 3;
85 sk::IFLRVR = 111;
86 sk::IFLSIM = 1;
87 sk::IFLBSP = 2;
88 // AABTAG runs on every event: PSFBTG fills the per-track b-tag commons, and
89 // the stored BTAG bank is read separately, so both tags are emitted.
90 // IFLPVT = 0 keeps SKELANA's primary vertex intact; AABTAG's own vertex is
91 // emitted as a separate collection.
92 sk::IFLBTG = 2;
93 sk::IFLPVT = 0;
94 sk::IFLVDR = 1;
95 sk::IFLFCT = 1;
96 sk::IFLRNQ = 0;
97 sk::IFLBHP = 1;
98 sk::IFLUTE = 1;
99 sk::IFLVDH = 1;
100 sk::IFLMUO = 1;
101 sk::IFLECL = 22;
102 sk::IFLELE = 1;
103 sk::IFLEMC = 1;
104 sk::IFLPHO = 1;
105 sk::IFLPHC = 1;
106 sk::IFLSTC = 1;
107 sk::IFLHAC = 1;
108 sk::IFLHAD = 1;
109 sk::IFLRV0 = 1;
110}
111
112void recordCallbackFailure(const char* phase, const char* message) noexcept {
113 const bool first_failure = !g_callback_failed;
114 g_callback_failed = true;
115 g_current_sdst_frame = nullptr;
116
117 // Keep the first failure as the authoritative process diagnostic. A later
118 // writer-finalization failure is useful to log, but must not hide the event
119 // failure that made the output partial in the first place.
120 if (first_failure) {
121 try {
122 g_callback_failure = phase ? phase : "callback";
123 if (message && *message) {
124 g_callback_failure += ": ";
125 g_callback_failure += message;
126 }
127 } catch (...) {
128 // The failure flag remains authoritative if retaining text allocates.
129 }
130 }
131
132 // C stdio does not throw C++ exceptions. In particular, do not let an
133 // iostream exception turn this noexcept containment path into terminate().
134 std::fprintf(stderr,
135 "delphi_edm4hep::harness: caught C++ %s failure%s%s\n",
136 phase ? phase : "callback", message && *message ? ": " : "",
137 message && *message ? message : "");
138}
139
140template <typename Callback>
141void guardCallback(const char* phase, Callback&& callback) noexcept {
142 try {
143 std::forward<Callback>(callback)();
144 } catch (const std::exception& error) {
145 recordCallbackFailure(phase, error.what());
146 } catch (...) {
147 recordCallbackFailure(phase, nullptr);
148 }
149}
150
151void finishWriterNoexcept(const char* phase) noexcept {
152 if (!g_writer) return;
153 guardCallback(phase, [] { g_writer->finish(); });
154 g_writer.reset();
155}
156
157} // namespace
158
159void on_user00() noexcept {
160 guardCallback("user00 initialization", [] {
161 // Suppress FPE during SKELANA's borderline-track work — without this,
162 // transient FPEs in PSHSCT/PSHBANKS would change IREJ outcomes.
163 ph::PHSET("FPE", 0);
164 sk::PSINI();
165 setSkelanaFlags();
166
167 if (g_cfg.output.empty()) {
168 std::cerr << "harness::on_user00: output path not set\n";
169 std::exit(2);
170 }
171 g_writer = std::make_unique<podio::ROOTWriter>(g_cfg.output.string());
172 std::cout << "delphi_edm4hep::harness: opened " << g_cfg.output << "\n";
173
174 // Assemble the list of intermediate(s): the primary input_edm4hep
175 // plus any extras to union with it.
176 std::vector<std::filesystem::path> inters;
177 if (!g_cfg.input_edm4hep.empty()) inters.push_back(g_cfg.input_edm4hep);
178 for (const auto& p : g_cfg.input_edm4hep_extra) inters.push_back(p);
179
180 if (!inters.empty()) {
181 g_sdst_readers.reserve(inters.size());
182 for (unsigned r = 0; r < inters.size(); ++r) {
183 auto reader = std::make_unique<podio::ROOTReader>();
184 reader->openFile(inters[r].string());
185
186 // Build (run, evt) -> (reader, entry-idx) index by scanning all
187 // frames. Reads Frame parameters only (collection deserialization
188 // is lazy in podio, so this is cheap). First occurrence wins on
189 // the (rare) duplicate key (begin-of-run records share evt across
190 // tapes); emplace keeps the earliest reader.
191 const unsigned N = reader->getEntries("events");
192 unsigned added = 0;
193 for (unsigned i = 0; i < N; ++i) {
194 auto fd = reader->readEntry("events", i);
195 if (!fd) break;
196 const podio::Frame f(std::move(fd));
197 const auto run = f.getParameter<int>(
198 bank::make(bank::Pass::Sdst, "EVT", "runNumber"));
199 const auto evt = f.getParameter<int>(
200 bank::make(bank::Pass::Sdst, "EVT", "eventNumber"));
201 if (run && evt) {
202 if (g_sdst_index.emplace(std::make_pair(*run, *evt),
203 std::make_pair(r, i)).second) {
204 ++added;
205 }
206 }
207 }
208 std::cout << "delphi_edm4hep::harness: intermediate " << inters[r]
209 << " indexed (" << added << " new keys / " << N
210 << " entries)\n";
211 g_sdst_readers.push_back(std::move(reader));
212 }
213 std::cout << "delphi_edm4hep::harness: " << g_sdst_readers.size()
214 << " intermediate(s), " << g_sdst_index.size()
215 << " unique (run, evt) keys total\n";
216 }
217
218 if (g_cfg.on_init) g_cfg.on_init();
219 });
220}
221
222void on_user01(int* need) noexcept {
223 if (!need) return;
224 if (g_callback_failed) {
225 *need = -3; // stop after a caught C++ callback failure
226 return;
227 }
228 if (g_cfg.max_events > 0 && g_n_written >= g_cfg.max_events) {
229 *need = -3; // stop the loop
230 return;
231 }
232 *need = 1;
233}
234
235static void on_user02_impl() {
236 ++g_n_seen;
237 if (g_cfg.max_events > 0 && g_n_written >= g_cfg.max_events) return;
238
239 sk::PSBEG();
240
241 // Records with no DST bank are not events. File headers and end-of-run
242 // trailers reach this callback too, and can appear mid-file. They carry
243 // no event of their own: the SKELANA commons still hold the preceding
244 // event's values, so emitting one produces a frame whose event-level
245 // quantities belong to a different event.
246 if (ph::LDTOP <= 0) { ++g_n_no_dst; return; }
247
248 // Dedup. The data fullDST (.fadana) delivers each physical event as
249 // ~3 separate PHDST DST records (Records/DST ~ 3.0); the .sdst/.al
250 // streams deliver one. Without this guard we write 3 identical frames
251 // per event. Recording both written AND skipped (run,evt) here means
252 // any later re-delivery of the same event is a no-op, regardless of
253 // record count. Placed after the no-DST test so a header record cannot
254 // consume the key of a later real event, and before the first-event skip
255 // so a re-delivered begin-of-run record can never slip through.
256 const std::pair<int, int> key{ph::IIIRUN, ph::IIIEVT};
257 if (!g_processed.insert(key).second) { ++g_n_redelivered; return; }
258
259 // DELSIM's event 1 is a setup record that has a DST bank but no PV chain;
260 // drop it so the output event count equals the number of physics events.
261 if (g_n_seen == 1 && ph::LQ(ph::LDTOP - 1) == 0) return;
262
263 podio::Frame frame;
264
265 // Pass-2: look up the intermediate frame for this (run, evt) and
266 // load it AS our output frame. Subsequent put() calls in the event
267 // hook add fDST_* collections alongside the sDST_* already in the
268 // frame. No copy-through writer needed — podio's writeFrame at the
269 // end of user02 emits everything.
270 //
271 // If no matching intermediate exists, we SKIP this event rather
272 // than writing an empty frame. Reasons:
273 // (a) pass-2's output is meant to be a strict superset of pass-1
274 // (sDST_* present); an event with no sDST_* would have a
275 // different schema and break podio's per-category consistency
276 // check.
277 // (b) pass-1's first-event-empty skip drops the (run, evt) of any
278 // DELSIM-empty sDST event 1. The corresponding fadana event 1
279 // isn't necessarily empty (the fullDST reconstruction may
280 // have produced PA banks where the condensed sDST didn't),
281 // so we'd hit a mismatch. Skipping keeps the two streams in
282 // lock-step on (run, evt).
283 if (!g_sdst_readers.empty()) {
284 auto it = g_sdst_index.find(key);
285 if (it == g_sdst_index.end()) {
286 if (g_n_seen <= 5) {
287 std::cerr << "delphi_edm4hep::harness: skip — no sDST frame for"
288 << " (run=" << ph::IIIRUN
289 << ", evt=" << ph::IIIEVT << ")\n";
290 }
291 return;
292 }
293 auto fd = g_sdst_readers[it->second.first]
294 ->readEntry("events", it->second.second);
295 if (fd) frame = podio::Frame(std::move(fd));
296 }
297 g_current_sdst_frame = &frame;
298
299 // Record what this event's DST record carries, for the metadata frame.
301
302 if (g_cfg.on_event) {
303 g_cfg.on_event(frame, ph::IIIRUN, ph::IIIEVT);
304 }
305
306 g_writer->writeFrame(frame, "events");
307 g_current_sdst_frame = nullptr;
308 ++g_n_written;
309
310 if (g_n_written <= 5 || g_n_written % 500 == 0) {
311 std::cout << "delphi_edm4hep::harness: event " << g_n_written
312 << " run=" << ph::IIIRUN
313 << " evt=" << ph::IIIEVT << "\n";
314 }
315}
316
317void on_user02() noexcept {
318 if (g_callback_failed) return;
319 guardCallback("user02 event callback", [] { on_user02_impl(); });
320}
321
322void on_user99() noexcept {
323 if (g_cfg.on_finalize) {
324 guardCallback("user99 finalize hook", [] { g_cfg.on_finalize(); });
325 }
326 // Provenance is identical for every event, so it goes into a single
327 // metadata frame rather than being repeated per event. Written before the
328 // writer is finalized.
329 guardCallback("user99 metadata frame", [] {
330 if (!g_writer) return;
331 const auto record = provenanceRecord();
332 if (record.collections.empty()) return;
333 podio::Frame meta;
334 meta.putParameter("provenance_collection", record.collections);
335 meta.putParameter("provenance_source", record.sources);
336
337 // What the input file actually carried, so an empty collection can be
338 // told apart from a module the file never had. Covers the events
339 // converted, not the whole file.
340 meta.putParameter("dst_pa_modules_present", census::paModules());
341 meta.putParameter("dst_pilot_blocklets_present", census::pilotBlocklets());
342
343 // The SKELANA track selection this file was produced with. IFLCUT names
344 // the cut table (1 old SKELANA, 2 May-98 tuning, 3 April-99 tuning; the
345 // tables are in the README). IFLSTR = 11 means rejected tracks are flagged
346 // in VECP_LVLOCK, not removed.
347 meta.putParameter("skelana_IFLCUT", sk::IFLCUT);
348 meta.putParameter("skelana_IFLSTR", sk::IFLSTR);
349 g_writer->writeFrame(meta, "metadata");
350 });
351
352 finishWriterNoexcept("user99 writer finalization");
353 guardCallback("user99 provenance summary", [] { reportProvenance(); });
354
355 // PHDST hands this callback every record, not every event. Report what was
356 // dropped, so a change in the output count can be accounted for from the
357 // job's own log rather than by comparing against PHDST's record footer.
358 try {
359 if (g_n_no_dst || g_n_redelivered) {
360 std::cout << "delphi_edm4hep::harness: skipped " << g_n_no_dst
361 << " records with no DST bank, " << g_n_redelivered
362 << " re-delivered events\n";
363 }
364 } catch (...) {
365 }
366
367 // The canonical success footer is consumed by campaign audits. Never emit
368 // it for a failed/partial job, even though run() will also return nonzero.
369 try {
370 if (g_callback_failed) {
371 std::cerr << "delphi_edm4hep::harness: aborted after " << g_n_written
372 << " written events; partial output is not publishable\n";
373 } else {
374 std::cout << "delphi_edm4hep::harness: wrote " << g_n_written
375 << " events to " << g_cfg.output << "\n";
376 }
377 } catch (...) {
378 // Diagnostics are best effort; the failure state and exit code are not.
379 }
380}
381
382const podio::Frame* currentSdstFrame() { return g_current_sdst_frame; }
383
384int run(const Config& cfg) {
385 g_cfg = cfg;
386 g_n_seen = 0;
387 g_n_written = 0;
388 g_n_no_dst = 0;
389 g_n_redelivered = 0;
390 g_callback_failed = false;
391 g_callback_failure.clear();
392 g_current_sdst_frame = nullptr;
393 g_writer.reset();
394 g_sdst_readers.clear();
395 g_sdst_index.clear(); // derived from the readers — reset together, so a
396 // second run() in one process can't use stale
397 // (run,evt) entry numbers against the new readers
398 g_processed.clear();
399
400 // PHDST reads its input from a fixed-format text file named PDLINPUT in cwd.
401 // Refuse to replace one we did not create; the cleanup below removes ours.
402 std::error_code path_error;
403 const auto pdl_status = std::filesystem::symlink_status("PDLINPUT", path_error);
404 if (path_error == std::errc::no_such_file_or_directory) {
405 path_error.clear();
406 } else if (path_error) {
407 std::cerr << "harness::run: cannot inspect PDLINPUT: "
408 << path_error.message() << "\n";
409 return 1;
410 } else if (pdl_status.type() != std::filesystem::file_type::not_found) {
411 std::cerr << "harness::run: PDLINPUT already exists in "
412 << std::filesystem::current_path() << "; remove it and retry\n";
413 return 1;
414 }
415
416 struct InputFileCleanup {
417 std::filesystem::path link;
418 bool remove_pdl_input = false;
419 ~InputFileCleanup() {
420 std::error_code ignored;
421 if (remove_pdl_input) std::filesystem::remove("PDLINPUT", ignored);
422 if (!link.empty()) std::filesystem::remove(link, ignored);
423 }
424 } cleanup;
425
426 std::ofstream pdl;
427 switch (cfg.input_mode) {
428 case InputMode::File: {
429 if (!std::filesystem::exists(cfg.input)) {
430 std::cerr << "harness::run: input not found: " << cfg.input << "\n";
431 return 1;
432 }
433 const auto abs_input = std::filesystem::absolute(cfg.input, path_error);
434 if (path_error) {
435 std::cerr << "harness::run: cannot resolve input path " << cfg.input
436 << ": " << path_error.message() << "\n";
437 return 1;
438 }
439 // The legacy parser truncates paths over 120 characters, which turns a
440 // valid input into a zero-event job. Point PDLINPUT at a short
441 // process-unique symlink instead of the real path.
442 const std::filesystem::path link(
443 ".phdst_input_" + std::to_string(static_cast<long long>(::getpid())));
444 if (std::filesystem::exists(link, path_error) || path_error) {
445 std::cerr << "harness::run: short input link already exists or cannot "
446 "be inspected: " << link;
447 if (path_error) std::cerr << ": " << path_error.message();
448 std::cerr << "\n";
449 return 1;
450 }
451 std::filesystem::create_symlink(abs_input, link, path_error);
452 if (path_error) {
453 std::cerr << "harness::run: cannot create short input link " << link
454 << " -> " << abs_input << ": " << path_error.message()
455 << "\n";
456 return 1;
457 }
458 cleanup.link = link;
459
460 pdl.open("PDLINPUT");
461 if (!pdl) {
462 std::cerr << "harness::run: cannot create PDLINPUT in "
463 << std::filesystem::current_path() << "\n";
464 return 1;
465 }
466 cleanup.remove_pdl_input = true;
467 pdl << "FILE = " << link.string() << "\n";
468 break;
469 }
470 case InputMode::Nickname: {
471 pdl.open("PDLINPUT");
472 if (!pdl) {
473 std::cerr << "harness::run: cannot create PDLINPUT in "
474 << std::filesystem::current_path() << "\n";
475 return 1;
476 }
477 cleanup.remove_pdl_input = true;
478 pdl << "FAT = " << cfg.input_nickname << "\n";
479 break;
480 }
481 case InputMode::Pdl: {
482 if (!std::filesystem::exists(cfg.input)) {
483 std::cerr << "harness::run: pdl file not found: " << cfg.input << "\n";
484 return 1;
485 }
486 std::filesystem::copy_file(cfg.input, "PDLINPUT",
487 std::filesystem::copy_options::none,
488 path_error);
489 if (path_error) {
490 std::cerr << "harness::run: cannot copy " << cfg.input
491 << " to PDLINPUT: " << path_error.message() << "\n";
492 return 1;
493 }
494 cleanup.remove_pdl_input = true;
495 break;
496 }
497 }
498 if (cfg.input_mode != InputMode::Pdl) {
499 pdl.close();
500 if (!pdl) {
501 std::cerr << "harness::run: cannot write PDLINPUT\n";
502 return 1;
503 }
504 }
505
506 // Drive the PHDST event loop. Empty option string -> default mode.
507 // PHDST will invoke user00_ / user01_ / user02_ / user99_ as
508 // the binary's overrides; those forward into our on_userNN above.
509 int n = 0, m = 0;
510 const char opt[] = " ";
511 ph::phdst_(const_cast<char*>(opt), &n, &m, std::strlen(opt));
512
513 // PHDST can report an input/open error yet return normally after producing a
514 // nonempty metadata-only ROOT file. Make a zero-event conversion fail at the
515 // process boundary so batch drivers cannot publish it as a valid product.
516 finishWriterNoexcept("post-PHDST writer finalization");
517 if (g_callback_failed) {
518 std::cerr << "harness::run: event callback failed";
519 if (!g_callback_failure.empty()) {
520 std::cerr << ": " << g_callback_failure;
521 }
522 std::cerr << "\n";
523 return 3;
524 }
525 if (g_n_written <= 0) {
526 std::cerr << "harness::run: no events were written; conversion failed\n";
527 return 2;
528 }
529 return 0;
530}
531
532} // namespace delphi_edm4hep::harness
std::string make(Pass pass, std::string_view bank, std::string_view readable_name)
std::vector< std::string > pilotBlocklets()
Definition DstCensus.cpp:93
std::vector< std::string > paModules()
Definition DstCensus.cpp:89
void on_user99() noexcept
void on_user02() noexcept
int run(const Config &cfg)
const podio::Frame * currentSdstFrame()
void on_user01(int *need) noexcept
void on_user00() noexcept
ProvenanceRecord provenanceRecord()
Definition PaWalk.h:21
std::filesystem::path input