Project
Loading...
Searching...
No Matches
AnalysisCCDBHelpers.cxx
Go to the documentation of this file.
1// Copyright 2019-2025 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
12#include "AnalysisCCDBHelpers.h"
13#include "CCDBFetcherHelper.h"
21#include "Framework/Output.h"
22#include "Framework/Signpost.h"
26#include <fairmq/Version.h>
27#include <arrow/array/builder_binary.h>
28#include <arrow/type.h>
29#include <arrow/type_fwd.h>
30#include <arrow/util/key_value_metadata.h>
31#include <arrow/table.h>
32#include <arrow/array.h>
33#include <arrow/builder.h>
34#include <fmt/base.h>
35#include <ctime>
36#include <memory>
37#include "CCDBPathTable.h"
38
39#include <string>
40#include <unordered_map>
41#include <vector>
42
44
45namespace o2::framework
46{
47// Fill valid routes. Notice that for analysis the timestamps are associated to
48// a ATIM table and there might be multiple CCDB objects of the same kind for
49// dataframe.
50// For this reason rather than matching the Lifetime::Condition, we match the
51// origin.
52namespace
53{
54void fillValidRoutes(CCDBFetcherHelper& helper, std::vector<o2::framework::OutputRoute> const& outputRoutes, std::unordered_map<std::string, int>& bindings)
55{
56 for (auto& route : outputRoutes) {
57 if (std::ranges::none_of(route.matcher.metadata, [](auto const& m) { return m.name.starts_with("ccdb:"); })) {
58 continue;
59 }
60 auto specStr = DataSpecUtils::describe(route.matcher);
61 if (bindings.find(specStr) != bindings.end()) {
62 continue;
63 }
64 bindings[specStr] = helper.routes.size();
65 helper.routes.push_back(route);
66 LOGP(info, "The following route needs condition objects {} ", DataSpecUtils::describe(route.matcher));
67 for (auto& metadata : route.matcher.metadata) {
68 if (metadata.type == VariantType::String) {
69 LOGP(info, "- {}: {}", metadata.name, metadata.defaultValue.asString());
70 }
71 }
72 }
73}
74} // namespace
75
77{
78 return adaptStateful([](ConfigParamRegistry const& options, DeviceSpec const& spec, InitContext& ic) {
79 auto& dec = ic.services().get<DanglingEdgesContext>();
80 // The effective default for each ccdb: option was already resolved at topology
81 // time by ArrowSupport (consulting task Configurables) and registered on this
82 // device's options. Here we just read the final value — honouring any further
83 // runtime override supplied via CLI or JSON config.
84 std::unordered_map<std::string, std::string> ccdbUrls;
85 std::unordered_map<std::string, std::string> runDependent;
86 for (auto& input : dec.analysisCCDBInputs) {
87 for (auto& m : input.metadata) {
88 if (m.name.starts_with("ccdb-run-dependent:")) {
89 runDependent.emplace(m.name, m.defaultValue.asString());
90 continue;
91 }
92 if (!m.name.starts_with("ccdb:") || ccdbUrls.count(m.name)) {
93 continue;
94 }
95 std::string url = m.defaultValue.asString();
96 if (ConfigParamsHelper::hasOption(spec.options, m.name)) {
97 url = options.get<std::string>(m.name.c_str());
98 }
99 LOGP(info, "CCDB path resolved for {}: {}", m.name, url);
100 ccdbUrls.emplace(m.name, std::move(url));
101 }
102 }
103 std::vector<std::shared_ptr<arrow::Schema>> schemas;
104 for (auto& input : dec.analysisCCDBInputs) {
105 auto schemaMetadata = std::make_shared<arrow::KeyValueMetadata>();
106 std::vector<std::shared_ptr<arrow::Field>> fields;
107 schemaMetadata->Append("outputRoute", DataSpecUtils::describe(input));
108 schemaMetadata->Append("outputBinding", input.binding);
109 for (auto& m : input.metadata) {
110 if (m.name.starts_with("input:")) {
111 auto name = m.name.substr(6);
112 schemaMetadata->Append("sourceTable", name);
113 schemaMetadata->Append("sourceMatcher", DataSpecUtils::describe(std::get<ConcreteDataMatcher>(DataSpecUtils::fromMetadataString(m.defaultValue.get<std::string>()).matcher)));
114 continue;
115 }
116 if (m.name == "timestamp-column" || m.name == "uniformity-column") {
117 schemaMetadata->Append(m.name, m.defaultValue.asString());
118 continue;
119 }
120 if (!m.name.starts_with("ccdb:")) {
121 continue;
122 }
123 auto fieldMetadata = std::make_shared<arrow::KeyValueMetadata>();
124 auto it = ccdbUrls.find(m.name);
125 fieldMetadata->Append("url", it != ccdbUrls.end() ? it->second : m.defaultValue.asString());
126 auto runDep = runDependent.find("ccdb-run-dependent:" + m.name.substr(strlen("ccdb:")));
127 fieldMetadata->Append("runDependent", runDep != runDependent.end() ? runDep->second : "0");
128 auto columnName = m.name.substr(strlen("ccdb:"));
129 fields.emplace_back(std::make_shared<arrow::Field>(columnName, soa::asArrowDataType<int64_t[3]>(), false, fieldMetadata));
130 }
131 schemas.emplace_back(std::make_shared<arrow::Schema>(fields, schemaMetadata));
132 }
133
134 // Parse the declared path mappings once; they are fixed for the run of the workflow.
135 std::vector<std::vector<PathTable>> pathTables;
136 for (auto const& schema : schemas) {
137 auto& tables = pathTables.emplace_back();
138 for (auto const& field : schema->fields()) {
139 tables.push_back(PathTable::parse(*field->metadata()->Get("url")));
140 }
141 }
142
143 std::vector<std::pair<uint32_t, std::shared_ptr<arrow::FixedSizeListBuilder>>> allbuilders;
144 allbuilders.resize([&schemas]() { size_t size = 0; for (auto& schema : schemas) { size += schema->num_fields(); }; return size; }());
145 auto* pool = arrow::default_memory_pool();
146
147 int idx = 0;
148 int sidx = 0;
149 for (auto const& schema : schemas) {
150 for (auto const& _ : schema->fields()) {
151 auto value_builder = std::make_shared<arrow::Int64Builder>();
152 allbuilders[idx] = std::make_pair(sidx, std::make_shared<arrow::FixedSizeListBuilder>(pool, std::move(value_builder), 3));
153 ++idx;
154 }
155 ++sidx;
156 }
157
158 std::shared_ptr<CCDBFetcherHelper> helper = std::make_shared<CCDBFetcherHelper>();
159 CCDBFetcherHelper::initialiseHelper(*helper, options);
160 std::unordered_map<std::string, int> bindings;
161 fillValidRoutes(*helper, spec.outputs, bindings);
162
163 return adaptStateless([schemas, bindings, helper, allbuilders, pathTables](InputRecord& inputs, DataTakingContext& dtc, DataAllocator& allocator, TimingInfo& timingInfo, DataProcessingStats& stats) {
164 O2_SIGNPOST_ID_GENERATE(sid, ccdb);
165 O2_SIGNPOST_START(ccdb, sid, "fetchFromAnalysisCCDB", "Fetching CCDB objects for analysis%" PRIu64, (uint64_t)timingInfo.timeslice);
166 std::ranges::for_each(allbuilders, [](auto& builder) { builder.second->Reset(); });
167 for (auto i = 0U; i < schemas.size(); ++i) {
168 auto& schema = schemas[i];
169 std::vector<CCDBFetcherHelper::FetchOp> ops;
170 auto inputBinding = *schema->metadata()->Get("sourceTable");
171 auto outRouteDesc = *schema->metadata()->Get("outputRoute");
172 std::string outBinding = *schema->metadata()->Get("outputBinding");
173 auto timestampColumnName = schema->metadata()->Contains("timestamp-column") ? *schema->metadata()->Get("timestamp-column") : std::string{"fTimestamp"};
174 auto uniformityColumnName = schema->metadata()->Contains("uniformity-column") ? *schema->metadata()->Get("uniformity-column") : timestampColumnName;
175 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
176 "Fetching CCDB objects for %{public}s's columns with timestamps from %{public}s and putting them in route %{public}s",
177 outBinding.c_str(), inputBinding.c_str(), outRouteDesc.c_str());
178 // The timestamp and uniformity columns may live in different source tables (the
179 // run number is on aod::BCs, the timestamp on aod::Timestamps). Locate each by
180 // name across every declared source, and read them positionally.
181 std::shared_ptr<arrow::ChunkedArray> timestampColumn;
182 std::shared_ptr<arrow::ChunkedArray> uniformityColumn;
183 auto const& schemaKeys = schema->metadata()->keys();
184 auto const& schemaValues = schema->metadata()->values();
185 for (size_t mi = 0; mi < schemaKeys.size(); ++mi) {
186 if (schemaKeys[mi] != "sourceMatcher") {
187 continue;
188 }
189 auto sourceTable = inputs.get<TableConsumer>(DataSpecUtils::fromString(schemaValues[mi]))->asArrowTable();
190 if (auto column = sourceTable->GetColumnByName(timestampColumnName); column && !timestampColumn) {
191 timestampColumn = column;
192 }
193 if (auto column = sourceTable->GetColumnByName(uniformityColumnName); column && !uniformityColumn) {
194 uniformityColumn = column;
195 }
196 }
197 if (!timestampColumn) {
198 LOGP(fatal, "No source table of {} provides the timestamp column \"{}\"", outBinding, timestampColumnName);
199 }
200 if (!uniformityColumn) {
201 LOGP(fatal, "No source table of {} provides the uniformity column \"{}\"", outBinding, uniformityColumnName);
202 }
203 // Positional reading is only sound if the two sources are row-aligned; ASoA has
204 // no type-level way to state that, so it is checked here.
205 if (uniformityColumn->length() != timestampColumn->length()) {
206 LOGP(fatal, "Uniformity column \"{}\" has {} rows but timestamp column \"{}\" has {}; the two sources of {} are not row-aligned",
207 uniformityColumnName, uniformityColumn->length(), timestampColumnName, timestampColumn->length(), outBinding);
208 }
209 auto reserveSize = timestampColumn->length();
210 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
211 "There are %zu bindings available", bindings.size());
212 for (auto const& binding : bindings) {
213 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
214 "* %{public}s: %d",
215 binding.first.c_str(), binding.second);
216 }
217 int outputRouteIndex = bindings.at(outRouteDesc);
218 auto& spec = helper->routes[outputRouteIndex].matcher;
219 auto concrete = DataSpecUtils::asConcreteDataMatcher(spec);
220 Output output{concrete.origin, concrete.description, concrete.subSpec};
221 auto builders = allbuilders | std::views::filter([&i](auto const& builder) { return builder.first == i; });
222 unsigned int numBuilders = std::ranges::count_if(allbuilders, [&i](auto const& builder) { return builder.first == i; });
223 arrow::Status status;
224 std::ranges::for_each(builders, [&status, &reserveSize](auto& builder) {
225 if (reserveSize > builder.second->capacity()) {
226 status &= builder.second->Reserve(reserveSize - builder.second->capacity());
227 }
228 });
229 if (!status.ok()) {
230 throw framework::runtime_error_f("Failed to reserve arrays: ", status.ToString().c_str());
231 }
232
233 std::vector<DataAllocator::CacheId> lastIds(numBuilders, DataAllocator::CacheId{.value = -1, .handle = -1, .segment = -1});
234
235 // Rows sharing a uniformity value resolve to the same objects, so the query is
236 // issued once per distinct value and the resulting handles are repeated for the
237 // rest of the run. When uniformity is the timestamp itself (the default) this
238 // degenerates to the previous behaviour, one query per row.
239 std::vector<int64_t> uniformity;
240 bool const shortCircuit = uniformityColumn.get() != timestampColumn.get();
241 if (shortCircuit) {
242 uniformity.reserve(reserveSize);
243 for (auto uci = 0; uci < uniformityColumn->num_chunks(); ++uci) {
244 auto uchunk = uniformityColumn->chunk(uci);
245 auto const length = uchunk->data()->length;
246 switch (uchunk->type_id()) {
247 case arrow::Type::INT32:
248 for (int64_t ui = 0; ui < length; ++ui) {
249 uniformity.push_back(uchunk->data()->GetValuesSafe<int32_t>(1)[ui]);
250 }
251 break;
252 case arrow::Type::INT64:
253 case arrow::Type::UINT64:
254 for (int64_t ui = 0; ui < length; ++ui) {
255 uniformity.push_back(uchunk->data()->GetValuesSafe<int64_t>(1)[ui]);
256 }
257 break;
258 default:
259 LOGP(fatal, "Uniformity column \"{}\" of {} has unsupported arrow type {}",
260 uniformityColumnName, outBinding, uchunk->type()->ToString());
261 }
262 }
263 }
264 int64_t row = -1;
265 int64_t previousUniformity = 0;
266 bool haveResponses = false;
267 std::vector<CCDBFetcherHelper::Response> responses;
268
269 for (auto ci = 0; ci < timestampColumn->num_chunks(); ++ci) {
270 std::shared_ptr<arrow::Array> chunk = timestampColumn->chunk(ci);
271 auto const* timestamps = chunk->data()->GetValuesSafe<size_t>(1);
272
273 for (int64_t ri = 0; ri < chunk->data()->length; ri++) {
274 ++row;
275 bool const sameAsPrevious = shortCircuit && haveResponses && uniformity[row] == previousUniformity;
276 if (shortCircuit) {
277 previousUniformity = uniformity[row];
278 }
279 ops.clear();
280 int64_t timestamp = timestamps[ri];
281 // Key the path lookup on the uniformity value; when uniformity is the
282 // timestamp itself the mapping expresses validity intervals instead.
283 int64_t const uniformityKey = shortCircuit ? uniformity[row] : timestamp;
284 int fi = 0;
285 for (auto& field : schema->fields()) {
286 auto const& url = pathTables[i][fi++].resolve(uniformityKey, field->name());
287 // Time to actually populate the blob
288 // A run-dependent object is queried with the run number rather than by
289 // timestamp alone. The run comes from the uniformity value, so the column's
290 // table has to be uniform in the run number for this to mean anything.
291 int const fieldRunDependent = field->metadata()->Contains("runDependent")
292 ? std::stoi(*field->metadata()->Get("runDependent"))
293 : 0;
294 if (fieldRunDependent != 0 && uniformityColumnName != "fRunNumber") {
295 LOGP(fatal, R"(Column "{}" of {} is declared run-dependent, but its table is uniform in "{}" rather than fRunNumber, so no run number is available to query with. Declare the table with DECLARE_SOA_UNIFORM_TABLE(..., aod::BCs, o2::aod::bc::RunNumber, ...).)",
296 field->name(), outBinding, uniformityColumnName);
297 }
298 ops.push_back({
299 .spec = spec,
300 .url = url,
301 .timestamp = timestamp,
302 .runNumber = fieldRunDependent != 0 ? static_cast<int>(uniformityKey) : 1,
303 .runDependent = fieldRunDependent,
304 .queryRate = 0,
305 });
306 }
307 if (!sameAsPrevious) {
308 responses = CCDBFetcherHelper::populateCacheWith(helper, ops, timingInfo, dtc, allocator);
309 haveResponses = true;
310 }
311 O2_SIGNPOST_START(ccdb, sid, "handlingResponses",
312 "Got %zu responses from server.",
313 responses.size());
314 if (numBuilders != responses.size()) {
315 LOGP(fatal, "Not enough responses (expected {}, found {})", numBuilders, responses.size());
316 }
317 arrow::Status result;
318
319 int bi = 0;
320 for (auto& builder : builders) {
321 auto& response = responses[bi];
322 auto& lastId = lastIds[bi];
323 if (response.id.value != lastId.value) {
324 lastId.value = response.id.value;
326 }
327 result &= builder.second->Append();
328 auto* value_builder = dynamic_cast<arrow::Int64Builder*>(builder.second->value_builder());
329 result &= value_builder->Append(response.id.handle);
330 result &= value_builder->Append(response.id.segment);
331 result &= value_builder->Append(response.size);
332 ++bi;
333 }
334 if (!result.ok()) {
335 LOGP(fatal, "Error adding results from CCDB");
336 }
337 O2_SIGNPOST_END(ccdb, sid, "handlingResponses", "Done processing responses");
338 }
339 }
340 arrow::ArrayVector arrays;
341 std::ranges::for_each(builders, [&arrays](auto& builder) { arrays.push_back(*builder.second->Finish()); });
342 auto outTable = arrow::Table::Make(schema, arrays);
343 allocator.adopt(output, outTable);
344 }
345
346 stats.updateStats({(int)ProcessingStatsId::CCDB_CACHE_FETCHED_BYTES, DataProcessingStats::Op::Set, (int64_t)helper->totalFetchedBytes});
347 stats.updateStats({(int)ProcessingStatsId::CCDB_CACHE_REQUESTED_BYTES, DataProcessingStats::Op::Set, (int64_t)helper->totalRequestedBytes});
348 O2_SIGNPOST_END(ccdb, sid, "fetchFromAnalysisCCDB", "Fetching CCDB objects");
349 });
350 });
351}
352
353} // namespace o2::framework
std::string binding
std::string url
std::shared_ptr< arrow::Schema > schema
std::vector< std::shared_ptr< arrow::Field > > fields
int32_t i
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_EVENT_EMIT_INFO(log, id, name, format,...)
Definition Signpost.h:532
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:609
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:507
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:603
void adopt(const Output &spec, std::string *)
void adoptFromCache(Output const &spec, CacheId id, header::SerializationMethod method=header::gSerializationMethodNone)
Adopt an already cached message, using an already provided CacheId.
ServiceRegistryRef services()
Definition InitContext.h:34
The input API of the Data Processing Layer This class holds the inputs which are valid for processing...
decltype(auto) get(R binding, int part=0) const
const GLfloat * m
Definition glcorearb.h:4066
GLuint64EXT * result
Definition glcorearb.h:5662
GLsizeiptr size
Definition glcorearb.h:659
GLuint const GLchar * name
Definition glcorearb.h:781
GLuint GLsizei GLsizei * length
Definition glcorearb.h:790
const GLuint * arrays
Definition glcorearb.h:1314
constexpr framework::ConcreteDataMatcher matcher()
Definition ASoA.h:388
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
AlgorithmSpec::ProcessCallback adaptStateless(LAMBDA l)
RuntimeErrorRef runtime_error_f(const char *,...)
AlgorithmSpec::InitCallback adaptStateful(LAMBDA l)
constexpr o2::header::SerializationMethod gSerializationMethodCCDB
Definition DataHeader.h:329
std::shared_ptr< arrow::DataType > asArrowDataType(int list_size=1)
Definition ArrowTypes.h:174
static AlgorithmSpec fetchFromCCDB(ConfigContext const &)
static auto populateCacheWith(std::shared_ptr< CCDBFetcherHelper > const &helper, std::vector< FetchOp > const &ops, TimingInfo &timingInfo, DataTakingContext &dtc, DataAllocator &allocator) -> std::vector< Response >
static void initialiseHelper(CCDBFetcherHelper &helper, ConfigParamRegistry const &options)
static bool hasOption(const std::vector< ConfigParamSpec > &specs, const std::string &optName)
Check if option is defined.
Helper struct to hold statistics about the data processing happening.
static InputSpec fromMetadataString(std::string s)
Create an InputSpec from metadata string.
static std::string describe(InputSpec const &spec)
static ConcreteDataMatcher asConcreteDataMatcher(InputSpec const &input)
static ConcreteDataMatcher fromString(std::string s)
Create a concrete data matcher from serialized string.
std::vector< ConfigParamSpec > options
Definition DeviceSpec.h:57
std::vector< OutputRoute > outputs
Definition DeviceSpec.h:63
std::variant< ConcreteDataMatcher, data_matcher::DataDescriptorMatcher > matcher
The actual matcher for the input spec.
Definition InputSpec.h:70
header::DataOrigin origin
Definition Output.h:28
static PathTable parse(std::string const &spec)
std::vector< int > row