diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index a0a384ccd..8b0defde1 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -110,6 +110,14 @@ if (TARGET RestDetector) restRoot PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/libraries/detector/inc) target_link_libraries(restRoot RestDetector) target_compile_definitions(restRoot PRIVATE REST_LEGACY_SIGNAL_RECOVERY) + if ("${TEST}" + AND UNIX + AND NOT APPLE + AND TARGET RestLegacyRecoveryFixtureWriter + AND TARGET RestLegacyRecoveryFixtureReader) + find_package(Python3 REQUIRED COMPONENTS Interpreter) + add_subdirectory(bin/test/legacy-recovery) + endif () endif () # remove duplicates diff --git a/source/bin/LegacySignalRecovery.cxx b/source/bin/LegacySignalRecovery.cxx index 2cc4e4600..d0723017e 100644 --- a/source/bin/LegacySignalRecovery.cxx +++ b/source/bin/LegacySignalRecovery.cxx @@ -9,10 +9,12 @@ #include #include +#include #include #include #include #include +#include #include #include #include @@ -189,24 +191,25 @@ bool ValidateOutput(const fs::path& outputName, const fs::path& intermediateName * * ROOT separates the in-memory TTree, its stored header (addressed by a file key * such as EventTree;1), and the baskets containing branch data. Get() loads the - * tree object; its baskets can remain on disk. Fast cloning copies the baskets - * of every branch outside the disabled signal subtree into the candidate and - * builds a new in-memory tree describing them. It does not yet persist the - * completed replacement tree header. + * tree object; its baskets can remain on disk. The candidate is already a byte + * copy of the source, so the unaffected branches can retain their original + * baskets and file offsets. Only the signal branch is removed and rebuilt. + * CloneTree("fast") would unnecessarily bind addresses for the other branches, + * which can fail when a loaded dictionary has removed historical base members + * (for example TObject::fUniqueID in TRestTrack version 2). * * SetName() only renames the in-memory tree, not its existing file keys. The - * clone inherits that temporary name, protecting BOTH in-memory trees from - * Delete("EventTree;*"), which removes all stored EventTree cycles and would also - * delete matching in-memory objects. The old tree remains directory-owned until - * the candidate closes; the clone is renamed back to EventTree for publication. + * temporary name protects the in-memory tree from Delete("EventTree;*"), which + * removes all stored EventTree cycles and would also delete matching in-memory + * objects. The tree is renamed back to EventTree for publication. * * Filling only the new signal branch adds its entries alongside the already - * cloned entries in the other branches. ROOT allocates its baskets and records + * existing entries in the other branches. ROOT allocates its baskets and records * their locations; logical entry order does not require the original physical * layout or contiguous placement after the copied baskets. The final Write() * flushes buffered data and saves the completed header linking all branches and - * baskets. Copying baskets alone is not enough to publish a readable replacement - * tree; without its header those copied baskets can be left unreferenced. + * baskets. The removed signal baskets remain unreferenced in the private copy; + * no baskets belonging to an unaffected branch are rewritten or deleted. */ bool Rebuild(const fs::path& sourceName, const fs::path& intermediateName, const fs::path& candidateName) { TFile source(sourceName.c_str(), "READ"); @@ -257,23 +260,31 @@ bool Rebuild(const fs::path& sourceName, const fs::path& intermediateName, const candidate->GetUUID().AsString() != sourceUuid) return false; - // Clone every unaffected branch as raw baskets. Disabling the top-level - // signal branch makes ROOT omit its complete split subtree. - oldSignal->SetStatus(false); - oldTree->SetName("__RESTLegacySourceEventTree"); - // CloneTree attaches its clone to ROOT's current directory (not the OS cwd). - candidate->cd(); - std::cerr << "Recovery: fast-cloning unaffected EventTree branches...\n"; - auto* newTree = oldTree->CloneTree(-1, "fast"); - if (newTree == nullptr || newTree->GetEntries() != sourceEntries) return false; - candidate->Delete("EventTree;*"); + // The whole file was copied above: keep unaffected branches and their + // baskets in place instead of asking ROOT to bind their current layouts. + // TTree's byte counters include the old signal subtree. Its public counter + // updates take Int_t, so subtract large branches in bounded chunks. + const auto subtractBytes = [&](Long64_t bytes, void (TTree::*add)(Int_t)) { + while (bytes > 0) { + const Int_t chunk = + static_cast(std::min(bytes, std::numeric_limits::max())); + (oldTree->*add)(-chunk); + bytes -= chunk; + } + }; + subtractBytes(oldSignal->GetTotBytes("*"), &TTree::AddTotBytes); + subtractBytes(oldSignal->GetZipBytes("*"), &TTree::AddZipBytes); + oldTree->GetListOfBranches()->Remove(oldSignal); + // TBranch's destructor removes this subtree's leaves from the tree as well. + delete oldSignal; + oldTree->GetListOfBranches()->Compress(); + oldTree->GetListOfLeaves()->Compress(); std::cerr << "Recovery: rebuilding detector signal branch...\n"; - newTree->SetName(kEventTree); IntermediateEvent input; auto* event = new TRestDetectorSignalEvent; // Branch binds the event pointer; each newSignal->Fill() serializes its current object. - auto* newSignal = newTree->Branch(kSignalBranch, &event); + auto* newSignal = oldTree->Branch(kSignalBranch, &event); if (!input.Bind(*data) || newSignal == nullptr) return false; Long64_t signalCount = 0, pointCount = 0; for (Long64_t entry = 0; entry < sourceEntries; ++entry) { @@ -290,9 +301,13 @@ bool Rebuild(const fs::path& sourceName, const fs::path& intermediateName, const "source=" + sourceUuid + ";signalVersion=" + std::to_string(sourceVersion) + ";entries=" + std::to_string(sourceEntries) + ";signals=" + std::to_string(signalCount) + ";points=" + std::to_string(pointCount); - // Persist the finished tree header; already copied baskets are not copied again. + // Remove every old header cycle without deleting the directory-owned tree. + oldTree->SetName("__RESTLegacySourceEventTree"); + candidate->Delete("EventTree;*"); + oldTree->SetName(kEventTree); + // Persist the finished header, retaining the unaffected basket references. std::cerr << "Recovery: writing rebuilt EventTree...\n"; - if (newTree->Write(kEventTree, TObject::kOverwrite) <= 0 || + if (oldTree->Write(kEventTree, TObject::kOverwrite) <= 0 || !WriteText(*candidate, "REST_LegacySignalRecovery", provenance) || !candidate.Close()) return false; return ValidateOutput(candidateName, intermediateName, branches, keys); diff --git a/source/bin/test/legacy-recovery/CMakeLists.txt b/source/bin/test/legacy-recovery/CMakeLists.txt new file mode 100644 index 000000000..d0f686a58 --- /dev/null +++ b/source/bin/test/legacy-recovery/CMakeLists.txt @@ -0,0 +1,29 @@ +# The base legacy-signal fixtures are supplied by detectorlib's recovery tests. +# The changed unrelated class lives here so this regression needs no tracklib. +root_generate_dictionary(G__RecoveryOldTrack TrackFixture.h LINKDEF LinkDef.h) +add_executable( + RecoveryTrackFixtureIO TrackFixtureIO.cxx TrackFixture.cxx + ${CMAKE_CURRENT_BINARY_DIR}/G__RecoveryOldTrack.cxx) +target_include_directories(RecoveryTrackFixtureIO + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(RecoveryTrackFixtureIO PRIVATE ${ROOT_LIBRARIES}) + +root_generate_dictionary(G__RecoveryNewTrack TrackFixture.h LINKDEF LinkDef.h + OPTIONS -DRECOVERY_NEW_TRACK_SCHEMA) +add_library( + RecoveryNewTrack SHARED TrackFixture.cxx + ${CMAKE_CURRENT_BINARY_DIR}/G__RecoveryNewTrack.cxx) +target_compile_definitions(RecoveryNewTrack PRIVATE RECOVERY_NEW_TRACK_SCHEMA) +target_include_directories(RecoveryNewTrack PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(RecoveryNewTrack PRIVATE ${ROOT_LIBRARIES}) + +add_test( + NAME LegacySignalRecovery.PreservesBranchWithRemovedBase + COMMAND + ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/check_recovery.py + $ $ + $ + $ $ + ${CMAKE_SOURCE_DIR}/macros/legacy/recoverLegacySignalData.C) +set_tests_properties(LegacySignalRecovery.PreservesBranchWithRemovedBase + PROPERTIES TIMEOUT 180) diff --git a/source/bin/test/legacy-recovery/LinkDef.h b/source/bin/test/legacy-recovery/LinkDef.h new file mode 100644 index 000000000..40f54ce5a --- /dev/null +++ b/source/bin/test/legacy-recovery/LinkDef.h @@ -0,0 +1,5 @@ +#ifdef __ROOTCLING__ +#pragma link C++ class RecoveryTrack + ; +#pragma link C++ class std::vector < RecoveryTrack> + ; +#pragma link C++ class RecoveryTrackEvent + ; +#endif diff --git a/source/bin/test/legacy-recovery/TrackFixture.cxx b/source/bin/test/legacy-recovery/TrackFixture.cxx new file mode 100644 index 000000000..d8c24373e --- /dev/null +++ b/source/bin/test/legacy-recovery/TrackFixture.cxx @@ -0,0 +1,4 @@ +#include "TrackFixture.h" + +ClassImp(RecoveryTrack); +ClassImp(RecoveryTrackEvent); diff --git a/source/bin/test/legacy-recovery/TrackFixture.h b/source/bin/test/legacy-recovery/TrackFixture.h new file mode 100644 index 000000000..b2531f156 --- /dev/null +++ b/source/bin/test/legacy-recovery/TrackFixture.h @@ -0,0 +1,30 @@ +#ifndef REST_RECOVERY_TRACK_FIXTURE_H +#define REST_RECOVERY_TRACK_FIXTURE_H + +#include + +#include + +// Reproduce TRestTrack's removal of TObject without depending on tracklib. +#ifdef RECOVERY_NEW_TRACK_SCHEMA +class RecoveryTrack { +#else +class RecoveryTrack : public TObject { +#endif + public: + Int_t fID = 0; + Double_t fEnergy = 0; +#ifdef RECOVERY_NEW_TRACK_SCHEMA + ClassDef(RecoveryTrack, 3); +#else + ClassDef(RecoveryTrack, 2); +#endif +}; + +class RecoveryTrackEvent : public TObject { + public: + std::vector fTrack; + ClassDef(RecoveryTrackEvent, 1); +}; + +#endif diff --git a/source/bin/test/legacy-recovery/TrackFixtureIO.cxx b/source/bin/test/legacy-recovery/TrackFixtureIO.cxx new file mode 100644 index 000000000..f11d46245 --- /dev/null +++ b/source/bin/test/legacy-recovery/TrackFixtureIO.cxx @@ -0,0 +1,155 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "TrackFixture.h" + +namespace { +void Require(bool ok, const char* message) { + if (!ok) throw std::runtime_error(message); +} + +std::vector Bytes(TFile& file, Long64_t offset, Int_t size) { + Require(offset > 0 && size > 0, "invalid record range"); + std::vector bytes(size); + Require(!file.ReadBuffer(bytes.data(), offset, size), "cannot read record"); + return bytes; +} + +void CheckBranch(TFile& source, TBranch& oldBranch, TFile& fixed, TBranch& newBranch) { + Require(std::string(oldBranch.GetName()) == newBranch.GetName(), "branch name changed"); + Require(oldBranch.GetEntries() == newBranch.GetEntries(), "branch entries changed"); + Require(oldBranch.GetTotBytes() == newBranch.GetTotBytes(), "branch total bytes changed"); + Require(oldBranch.GetZipBytes() == newBranch.GetZipBytes(), "branch compressed bytes changed"); + Require(oldBranch.GetMaxBaskets() == newBranch.GetMaxBaskets(), "basket inventory changed"); + for (Int_t index = 0; index < oldBranch.GetMaxBaskets(); ++index) { + const auto seek = oldBranch.GetBasketSeek(index); + const auto size = oldBranch.GetBasketBytes()[index]; + Require(seek == newBranch.GetBasketSeek(index), "unaffected basket moved"); + Require(size == newBranch.GetBasketBytes()[index], "unaffected basket size changed"); + if (seek > 0 && size > 0) + Require(Bytes(source, seek, size) == Bytes(fixed, seek, size), "unaffected basket changed"); + } + const auto* children = oldBranch.GetListOfBranches(); + Require(children->GetEntries() == newBranch.GetListOfBranches()->GetEntries(), "subtree changed"); + for (Int_t index = 0; index < children->GetEntries(); ++index) + CheckBranch(source, *static_cast(children->At(index)), fixed, + *static_cast(newBranch.GetListOfBranches()->At(index))); +} + +void AppendTrack(const char* path) { + TFile file(path, "UPDATE"); + auto* tree = file.Get("EventTree"); + Require(tree != nullptr && tree->GetEntries() == 3, "unexpected base fixture"); + auto* event = new RecoveryTrackEvent; + auto* branch = tree->Branch("RecoveryTrackEventBranch", &event, 128, 99); + for (Int_t entry = 0; entry < 3; ++entry) { + event->fTrack.clear(); + for (Int_t index = 0; index <= entry; ++index) { + RecoveryTrack track; + track.SetUniqueID(1000 + 10 * entry + index); + track.fID = 10 * entry + index; + track.fEnergy = entry + 0.25 * index; + event->fTrack.push_back(track); + } + Require(branch->Fill() > 0 && branch->FlushBaskets() >= 0, "cannot write track fixture"); + } + // Multiple old header cycles must not leave a legacy signal branch reachable. + Require(tree->Write() > 0 && tree->Write() > 0, "cannot write header cycles"); + tree->ResetBranchAddress(branch); + delete event; +} + +void Verify(const char* sourcePath, const char* fixedPath) { + TFile source(sourcePath, "READ"); + TFile fixed(fixedPath, "READ"); + auto* oldTree = source.Get("EventTree"); + auto* newTree = fixed.Get("EventTree"); + Require(oldTree != nullptr && newTree != nullptr, "missing EventTree"); + Require(newTree->GetEntries() == 3, "incorrect recovered entry count"); + TIter branches(oldTree->GetListOfBranches()); + while (auto* branch = static_cast(branches())) { + if (std::string(branch->GetName()) == "TRestDetectorSignalEventBranch") continue; + auto* recovered = newTree->GetBranch(branch->GetName()); + Require(recovered != nullptr, "unaffected branch lost"); + CheckBranch(source, *branch, fixed, *recovered); + } + TIter keys(source.GetListOfKeys()); + while (auto* key = static_cast(keys())) { + if (std::string(key->GetName()) == "EventTree") continue; + auto* recovered = fixed.GetKey(key->GetName(), key->GetCycle()); + Require(recovered && recovered->GetSeekKey() == key->GetSeekKey() && + recovered->GetNbytes() == key->GetNbytes(), + "unaffected key moved"); + Require(Bytes(source, key->GetSeekKey(), key->GetNbytes()) == + Bytes(fixed, recovered->GetSeekKey(), recovered->GetNbytes()), + "unaffected key changed"); + } + Int_t treeCycles = 0; + TIter newKeys(fixed.GetListOfKeys()); + while (auto* key = static_cast(newKeys())) + if (std::string(key->GetName()) == "EventTree") ++treeCycles; + Require(treeCycles == 1, "obsolete EventTree cycles remain"); + + std::set owners; + const auto collect = [&](auto&& self, TObjArray* array) -> void { + TIter next(array); + while (auto* branch = static_cast(next())) { + owners.insert(branch); + self(self, branch->GetListOfBranches()); + } + }; + collect(collect, newTree->GetListOfBranches()); + TIter leaves(newTree->GetListOfLeaves()); + while (auto* leaf = static_cast(leaves())) + Require(owners.count(leaf->GetBranch()) != 0, "dangling leaf after signal replacement"); + + Long64_t total = 0, zipped = 0; + TIter newBranches(newTree->GetListOfBranches()); + while (auto* branch = static_cast(newBranches())) { + total += branch->GetTotBytes("*"); + zipped += branch->GetZipBytes("*"); + } + Require(total == newTree->GetTotBytes() && zipped == newTree->GetZipBytes(), + "incorrect tree byte counters"); + + auto* event = new RecoveryTrackEvent; + auto* branch = newTree->GetBranch("RecoveryTrackEventBranch"); + Require(newTree->SetBranchAddress(branch->GetName(), &event) >= TTree::kMatch, "cannot bind old tracks"); + for (Int_t entry = 0; entry < 3; ++entry) { + Require(branch->GetEntry(entry) > 0, "cannot read old tracks"); + Require(event->fTrack.size() == static_cast(entry + 1), "track count changed"); + for (Int_t index = 0; index <= entry; ++index) { + const auto& track = event->fTrack[index]; + Require(track.GetUniqueID() == static_cast(1000 + 10 * entry + index) && + track.fID == 10 * entry + index && track.fEnergy == entry + 0.25 * index, + "historical track values changed"); + } + } + newTree->ResetBranchAddress(branch); + delete event; +} +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 3 && std::string(argv[1]) == "append") + AppendTrack(argv[2]); + else if (argc == 4 && std::string(argv[1]) == "verify") + Verify(argv[2], argv[3]); + else + return 2; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/source/bin/test/legacy-recovery/check_recovery.py b/source/bin/test/legacy-recovery/check_recovery.py new file mode 100644 index 000000000..f67100374 --- /dev/null +++ b/source/bin/test/legacy-recovery/check_recovery.py @@ -0,0 +1,35 @@ +"""Recover signals while a loaded unrelated dictionary has removed TObject.""" + +import hashlib +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +restroot, writer, reader, fixture, dictionary, macro = sys.argv[1:] +with tempfile.TemporaryDirectory(prefix="rest-recovery-track-") as directory: + directory = Path(directory) + source, recovered = directory / "legacy.root", directory / "recovered.root" + subprocess.run([writer, source, "--keep-signal-streamer-info"], check=True) + subprocess.run([fixture, "append", source], check=True) + original = hashlib.sha256(source.read_bytes()).digest() + environment = os.environ.copy() + # Load schema 3 in the recovery process; the writer/verifier use schema 2. + # This ROOT-only dictionary is also safe in the plain-ROOT signal extractor. + environment["LD_PRELOAD"] = ":".join( + filter(None, (dictionary, environment.get("LD_PRELOAD"))) + ) + environment["REST_LEGACY_RECOVERY_MACRO"] = macro + try: + subprocess.run( + [restroot, "--recover-legacy-signals", source, "--output", recovered], + env=environment, + check=True, + ) + finally: + assert ( + hashlib.sha256(source.read_bytes()).digest() == original + ), "original was modified" + subprocess.run([fixture, "verify", source, recovered], check=True) + subprocess.run([reader, recovered], check=True)