Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions source/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
65 changes: 40 additions & 25 deletions source/bin/LegacySignalRecovery.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
#include <TSystem.h>
#include <TTree.h>

#include <algorithm>
#include <cerrno>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <limits>
#include <set>
#include <string>
#include <system_error>
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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<Int_t>(std::min<Long64_t>(bytes, std::numeric_limits<Int_t>::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) {
Expand All @@ -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);
Expand Down
29 changes: 29 additions & 0 deletions source/bin/test/legacy-recovery/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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
$<TARGET_FILE:restRoot> $<TARGET_FILE:RestLegacyRecoveryFixtureWriter>
$<TARGET_FILE:RestLegacyRecoveryFixtureReader>
$<TARGET_FILE:RecoveryTrackFixtureIO> $<TARGET_FILE:RecoveryNewTrack>
${CMAKE_SOURCE_DIR}/macros/legacy/recoverLegacySignalData.C)
set_tests_properties(LegacySignalRecovery.PreservesBranchWithRemovedBase
PROPERTIES TIMEOUT 180)
5 changes: 5 additions & 0 deletions source/bin/test/legacy-recovery/LinkDef.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#ifdef __ROOTCLING__
#pragma link C++ class RecoveryTrack + ;
#pragma link C++ class std::vector < RecoveryTrack> + ;
#pragma link C++ class RecoveryTrackEvent + ;
#endif
4 changes: 4 additions & 0 deletions source/bin/test/legacy-recovery/TrackFixture.cxx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#include "TrackFixture.h"

ClassImp(RecoveryTrack);
ClassImp(RecoveryTrackEvent);
30 changes: 30 additions & 0 deletions source/bin/test/legacy-recovery/TrackFixture.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#ifndef REST_RECOVERY_TRACK_FIXTURE_H
#define REST_RECOVERY_TRACK_FIXTURE_H

#include <TObject.h>

#include <vector>

// 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<RecoveryTrack> fTrack;
ClassDef(RecoveryTrackEvent, 1);
};

#endif
155 changes: 155 additions & 0 deletions source/bin/test/legacy-recovery/TrackFixtureIO.cxx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#include <TBranch.h>
#include <TFile.h>
#include <TKey.h>
#include <TLeaf.h>
#include <TTree.h>

#include <iostream>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

#include "TrackFixture.h"

namespace {
void Require(bool ok, const char* message) {
if (!ok) throw std::runtime_error(message);
}

std::vector<char> Bytes(TFile& file, Long64_t offset, Int_t size) {
Require(offset > 0 && size > 0, "invalid record range");
std::vector<char> 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<TBranch*>(children->At(index)), fixed,
*static_cast<TBranch*>(newBranch.GetListOfBranches()->At(index)));
}

void AppendTrack(const char* path) {
TFile file(path, "UPDATE");
auto* tree = file.Get<TTree>("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<TTree>("EventTree");
auto* newTree = fixed.Get<TTree>("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<TBranch*>(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<TKey*>(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<TKey*>(newKeys()))
if (std::string(key->GetName()) == "EventTree") ++treeCycles;
Require(treeCycles == 1, "obsolete EventTree cycles remain");

std::set<TBranch*> owners;
const auto collect = [&](auto&& self, TObjArray* array) -> void {
TIter next(array);
while (auto* branch = static_cast<TBranch*>(next())) {
owners.insert(branch);
self(self, branch->GetListOfBranches());
}
};
collect(collect, newTree->GetListOfBranches());
TIter leaves(newTree->GetListOfLeaves());
while (auto* leaf = static_cast<TLeaf*>(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<TBranch*>(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<std::size_t>(entry + 1), "track count changed");
for (Int_t index = 0; index <= entry; ++index) {
const auto& track = event->fTrack[index];
Require(track.GetUniqueID() == static_cast<UInt_t>(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;
}
}
35 changes: 35 additions & 0 deletions source/bin/test/legacy-recovery/check_recovery.py
Original file line number Diff line number Diff line change
@@ -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)
Loading