• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

llnl-asr / dftracer-utils / 38033748054

10 Oct 2026 07:14AM UTC coverage: 62.608% (+5.2%) from 57.391%
38033748054

push

github

rayandrew
ci: shard the test job

The coverage jobs ran 64 minutes of C++ tests in one process. Each shard
runs every n-th test with ctest -I, the Python tests and the type check
run in shard 1 only, and each shard uploads its own coverage report to
Coveralls, which merges the parallel uploads.

117733 of 235605 branches covered (49.97%)

Branch coverage included in aggregate %.

102379 of 115969 relevant lines covered (88.28%)

3014114.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.15
/src/dftracer/utils/python/plugin_host.cpp
1
#define PY_SSIZE_T_CLEAN
2
#include <dftracer/utils/core/common/error.h>
3
#include <dftracer/utils/core/common/filesystem.h>
4
#include <dftracer/utils/core/runtime.h>
5
#include <dftracer/utils/core/tasks/coro_scope.h>
6
#include <dftracer/utils/index/build/resolve_and_build.h>
7
#include <dftracer/utils/plugins/config.h>
8
#include <dftracer/utils/plugins/plugins.h>
9
#include <dftracer/utils/plugins/result_registry.h>
10
#include <dftracer/utils/python/plugin_host.h>
11
#include <dftracer/utils/python/py_dict_helpers.h>
12
#include <dftracer/utils/python/py_errors.h>
13
#include <dftracer/utils/python/py_method.h>
14
#include <dftracer/utils/python/py_runtime_mixin.h>
15
#include <dftracer/utils/python/py_seq_helpers.h>
16
#include <dftracer/utils/python/py_str_helpers.h>
17
#include <dftracer/utils/python/py_type_helpers.h>
18
#include <dftracer/utils/python/runtime.h>
19
#include <dftracer/utils/trace/internal/utils.h>
20
#include <dftracer/utils/trace/views/view.h>
21
#include <dftracer/utils/utilities/filesystem/pattern_directory_scanner_utility.h>
22
// Unconditional: the native-frame result path (OwnedDataFrame) needs the
23
// DataFrame wrapper regardless of the Arrow build option.
24
#include <dftracer/utils/dataframe/dataframe.h>
25
#include <dftracer/utils/dataframe/internal/lazyframe_handle.h>
26
#include <dftracer/utils/dataframe/lazyframe.h>
27
#include <dftracer/utils/python/dataframe.h>
28
#include <dftracer/utils/python/lazyframe.h>
29

30
#ifdef DFTRACER_UTILS_ENABLE_ARROW
31
#include <dftracer/utils/python/arrow_helpers.h>
32
#include <nanoarrow/nanoarrow.h>
33
#endif
34

35
#include <algorithm>
36
#include <cerrno>
37
#include <cstddef>
38
#include <cstdint>
39
#include <cstring>
40
#include <new>
41
#include <optional>
42
#include <string>
43
#include <unordered_map>
44
#include <utility>
45
#include <variant>
46
#include <vector>
47

48
namespace {
49

50
using dftracer::utils::CoroScope;
51
using dftracer::utils::Runtime;
52
using dftracer::utils::coro::CoroTask;
53
using dftracer::utils::plugins::ConfigTree;
54
using dftracer::utils::plugins::NamedResult;
55
using dftracer::utils::plugins::NamedResultRegistry;
56
using dftracer::utils::plugins::OwnedArrow;
57
using dftracer::utils::plugins::OwnedDataFrame;
58
using dftracer::utils::plugins::OwnedLazyFrame;
59
using dftracer::utils::plugins::PluginRun;
60
using dftracer::utils::plugins::Plugins;
61
using dftracer::utils::python::parse_seq;
62
using dftracer::utils::python::parse_string_seq;
63
namespace internal = dftracer::utils::trace::internal;
64
namespace views = dftracer::utils::trace::views;
65
namespace filesystem = dftracer::utils::utilities::filesystem;
66

67
}  // namespace
68

69
namespace dftracer::utils::python {
70

71
// A host object's mutable side: the built set (immutable once constructed) and
72
// the named results of the most recent run or session.
73
struct PluginHostState {
74
    std::optional<Plugins> set;
75
    NamedResultRegistry results;
76
    // wire id -> attribute name, so a caller indexes results[...] with the
77
    // plugin's declared name rather than its package-qualified wire identity.
78
    std::unordered_map<std::string, std::string> result_names;
79
};
80

81
}  // namespace dftracer::utils::python
82

83
namespace {
84

85
using dftracer::utils::python::PluginHostState;
86

87
PluginHostState* state_of(PluginHostObject* self) {
376 ✔
88
    return static_cast<PluginHostState*>(self->host_ptr);
376 ✔
89
}
90

91
// The set built at construction. NULL with a Python error set if construction
92
// did not leave a built set (should not happen: __init__ raises on failure).
93
const Plugins* built_set(PluginHostObject* self) {
90 ✔
94
    PluginHostState* st = state_of(self);
90 ✔
95
    if (!st->set) {
90 !
96
        PyErr_SetString(PyExc_RuntimeError, "Plugins set was not built");
×
97
        return nullptr;
×
98
    }
99
    return &*st->set;
90 ✔
100
}
101

102
// Expand any directory in `inputs` to its trace files, index (unless
103
// disabled), then drive every loaded plugin as a fold over one fused scan.
104
CoroTask<void> run_host_scan(CoroScope& scope, std::vector<std::string> inputs,
83 !
105
                             std::string index_dir, const Plugins* plugins,
106
                             bool auto_index, PluginRun* out) {
107
    std::vector<std::string> files;
108
    for (const auto& p : inputs) {
109
        std::error_code ec;
110
        if (fs::is_directory(p, ec)) {
111
            filesystem::PatternDirectoryScannerUtilityInput in(
112
                p, filesystem::trace_file_patterns(), /*recursive=*/true,
113
                /*populate_size=*/false);
114
            filesystem::PatternDirectoryScannerUtility scanner;
115
            auto entries = co_await scanner(scope, in);
116
            for (auto& e : entries) files.push_back(e.path.string());
117
        } else {
118
            files.push_back(p);
119
        }
120
    }
121
    std::sort(files.begin(), files.end());
122
    if (files.empty())
123
        throw dftracer::utils::DFTUtilsException(
124
            dftracer::utils::ErrorCode::NOT_FOUND, "no trace files found");
125

126
    if (auto_index) {
127
        auto norm = co_await dftracer::utils::index::build::
128
            normalize_members_for_ingest(files, 0);
129
        files = std::move(norm.files);
130
        co_await dftracer::utils::index::build::ensure_indexes_fresh(
131
            &scope, "", files, index_dir);
132
    }
133

134
    std::vector<views::ViewFile> view_files;
135
    view_files.reserve(files.size());
136
    for (const auto& f : files) {
137
        views::ViewFile vf;
138
        vf.file_path = f;
139
        vf.index_path = internal::determine_index_path(f, index_dir);
140
        view_files.push_back(std::move(vf));
141
    }
142
    views::View view = views::View::from_files(std::move(view_files));
143
    auto run = co_await plugins->run(view);
144
    if (!run)
145
        throw dftracer::utils::DFTUtilsException(run.error().code,
146
                                                 run.error().message);
147
    *out = std::move(*run);
148
}
166 !
149

150
bool collect_inputs(PyObject* traces, std::vector<std::string>& out) {
83 ✔
151
    if (PyUnicode_Check(traces)) {
83 ✔
152
        const char* s = PyUnicode_AsUTF8(traces);
80 !
153
        if (!s) return false;
80 !
154
        out.emplace_back(s);
80 !
155
        return true;
80 ✔
156
    }
157
    return parse_string_seq(traces, "traces must be a str or list[str]", out);
3 ✔
158
}
159

160
// Convert one emitted result to Python: an opaque blob to bytes, a single
161
// user-schema Arrow array to a pyarrow-compatible table, and a streamed
162
// multi-batch map result to a pull-based pyarrow.RecordBatchReader. Returns a
163
// new reference, or nullptr with a Python error set.
164
PyObject* result_to_py(NamedResult& result) {
114 ✔
165
    if (auto* blob = std::get_if<std::vector<std::byte>>(&result))
114 ✔
166
        return PyBytes_FromStringAndSize(
1 !
167
            reinterpret_cast<const char*>(blob->data()),
1 ✔
168
            static_cast<Py_ssize_t>(blob->size()));
2 ✔
169
    if (auto* frame = std::get_if<OwnedDataFrame>(&result)) {
113 !
170
        // Adopt the handle's columns into a native DataFrame (shared buffers,
171
        // zero-copy) and hand it back as a _DataFrame; the OwnedDataFrame frees
172
        // the emptied handle.
173
        namespace df_ns = dftracer::utils::dataframe;
174
        dftu_dataframe* h = frame->handle;
113 ✔
175
        df_ns::DataFrame df;
113 ✔
176
        std::int32_t n = dftu_dataframe_num_columns(h);
113 !
177
        df.names.reserve(static_cast<std::size_t>(n));
113 !
178
        df.columns.reserve(static_cast<std::size_t>(n));
113 !
179
        for (std::int32_t i = 0; i < n; ++i) {
357 ✔
180
            const char* nm = dftu_dataframe_column_name(h, i);
244 !
181
            df.names.emplace_back(nm ? nm : "");
244 !
182
            df.columns.emplace_back(
244 !
183
                df_ns::Series{dftu_dataframe_column(h, nm)});
488 !
184
        }
185
        return dftracer::utils::python::wrap_dataframe(std::move(df));
113 !
186
    }
113 ✔
187
    if (auto* lazy = std::get_if<OwnedLazyFrame>(&result)) {
×
188
        // Move the plan out into the native Python LazyFrame wrapper; the
189
        // OwnedLazyFrame frees the emptied handle. The plan must be
190
        // self-contained (see the emit_lazyframe contract).
191
        namespace df_ns = dftracer::utils::dataframe;
192
        df_ns::LazyFrame lf =
193
            std::move(df_ns::lazyframe_handle_unwrap(lazy->handle));
×
194
        return dftracer::utils::python::wrap_lazyframe(std::move(lf));
×
195
    }
×
196
#ifdef DFTRACER_UTILS_ENABLE_ARROW
197
    namespace arr = dftracer::utils::utilities::common::arrow;
198
    auto* owned = std::get_if<OwnedArrow>(&result);
×
199
    nanoarrow::UniqueSchema schema;
×
200
    nanoarrow::UniqueArray array;
×
201
    ArrowSchemaMove(&owned->schema, schema.get());
×
202
    ArrowArrayMove(&owned->array, array.get());
×
203
    return dftracer::utils::python::arrow_result_to_table(
×
204
        arr::ArrowExportResult(std::move(schema), std::move(array)));
×
205
#else
206
    PyErr_SetString(PyExc_RuntimeError,
207
                    "plugin emitted an Arrow result but the extension was "
208
                    "built without Arrow support");
209
    return nullptr;
210
#endif
211
}
×
212

213
PyObject* results_to_dict(PluginHostState* st) {
89 ✔
214
    PyObject* d = PyDict_New();
89 ✔
215
    if (!d) return nullptr;
89 !
216
    for (auto& [wire_name, result] : st->results.results()) {
203 ✔
217
        PyObject* val = result_to_py(result);
114 !
218
        if (!val) {
114 !
219
            Py_DECREF(d);
220
            return nullptr;
×
221
        }
222
        auto it = st->result_names.find(wire_name);
114 !
223
        const std::string& key =
224
            it != st->result_names.end() ? it->second : wire_name;
114 ✔
225
        if (PyDict_SetItemString(d, key.c_str(), val) < 0) {
114 !
226
            Py_DECREF(val);
227
            Py_DECREF(d);
228
            return nullptr;
×
229
        }
230
        Py_DECREF(val);
231
    }
232
    return d;
89 ✔
233
}
234

235
PyObject* ph_new(PyTypeObject* type, PyObject*, PyObject*) {
95 ✔
236
    PluginHostObject* self = (PluginHostObject*)type->tp_alloc(type, 0);
95 ✔
237
    if (!self) return nullptr;
95 !
238
    self->runtime_obj = nullptr;
95 ✔
239
    self->host_ptr = new PluginHostState();
95 ✔
240
    return (PyObject*)self;
95 ✔
241
}
242

243
void ph_dealloc(PluginHostObject* self) {
95 ✔
244
    delete state_of(self);
95 !
245
    Py_XDECREF(self->runtime_obj);
95 ✔
246
    Py_TYPE(self)->tp_free((PyObject*)self);
95 ✔
247
}
95 ✔
248

249
bool parse_result_names(PyObject* obj,
95 ✔
250
                        std::unordered_map<std::string, std::string>& out) {
251
    if (!obj || obj == Py_None) return true;
95 !
252
    if (!PyDict_Check(obj)) {
70 !
253
        PyErr_SetString(PyExc_TypeError, "result_names must be a dict or None");
×
254
        return false;
×
255
    }
256
    PyObject *key = nullptr, *value = nullptr;
70 ✔
257
    Py_ssize_t pos = 0;
70 ✔
258
    while (PyDict_Next(obj, &pos, &key, &value)) {
161 !
259
        const char* k = as_utf8(key);
91 !
260
        const char* v = as_utf8(value);
91 !
261
        if (!k || !v) {
91 !
262
            PyErr_SetString(PyExc_TypeError,
×
263
                            "result_names keys and values must be str");
264
            return false;
×
265
        }
266
        out.emplace(k, v);
91 !
267
    }
268
    return true;
70 ✔
269
}
270

271
// __init__(specs, result_names=None, runtime=None): specs is a sequence of
272
// (path, config_json_or_None) pairs; config_json is a JSON object string (the
273
// Python wrapper serializes a dict). Builds the set now - dlopen, the ABI
274
// gate, and capability resolution all run here, so a load/symbol/ABI/
275
// capability failure raises ImportError from the constructor.
276
int ph_init(PluginHostObject* self, PyObject* args, PyObject* kwds) {
95 ✔
277
    static const char* kwlist[] = {"specs", "result_names", "runtime", nullptr};
278
    PyObject* specs = nullptr;
95 ✔
279
    PyObject* result_names_obj = nullptr;
95 ✔
280
    PyObject* runtime_arg = nullptr;
95 ✔
281
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO",
95 !
282
                                     const_cast<char**>(kwlist), &specs,
283
                                     &result_names_obj, &runtime_arg))
284
        return -1;
×
285
    if (bind_runtime_arg(self, runtime_arg) != 0) return -1;
95 !
286

287
    PluginHostState* st = state_of(self);
95 ✔
288
    if (!parse_result_names(result_names_obj, st->result_names)) return -1;
95 !
289

290
    Plugins::Builder builder;
95 !
291
    PyObject* iter = PyObject_GetIter(specs);
95 !
292
    if (!iter) return -1;
95 !
293
    PyObject* item;
294
    while ((item = PyIter_Next(iter)) != nullptr) {
194 !
295
        const char* path = nullptr;
99 ✔
296
        const char* config_json = nullptr;
99 ✔
297
        bool ok = PyArg_ParseTuple(item, "s|z", &path, &config_json) != 0;
99 !
298
        if (ok) {
99 !
299
            try {
300
                if (config_json)
99 ✔
301
                    builder.add(path,
6 !
302
                                ConfigTree::from_json_string(config_json));
12 !
303
                else
304
                    builder.add(path);
93 !
305
            } catch (const std::exception& e) {
×
306
                PyErr_SetString(dftracer::utils::python::g_dft_value_error
×
307
                                    ? dftracer::utils::python::g_dft_value_error
308
                                    : PyExc_ValueError,
309
                                e.what());
×
310
                ok = false;
×
311
            }
×
312
        }
313
        Py_DECREF(item);
314
        if (!ok) {
99 !
315
            Py_DECREF(iter);
316
            return -1;
×
317
        }
318
    }
319
    Py_DECREF(iter);
320
    if (PyErr_Occurred()) return -1;
95 !
321

322
    auto built = builder.build();
95 !
323
    if (!built) {
95 ✔
324
        PyErr_SetString(PyExc_ImportError, built.error().message.c_str());
4 !
325
        return -1;
4 ✔
326
    }
327
    st->set.emplace(std::move(*built));
91 !
328
    return 0;
91 ✔
329
}
95 ✔
330

331
// run(traces, index_dir=None, auto_index=True) -> (results, stats). Drives the
332
// fused scan with the GIL released.
333
PyObject* ph_run(PluginHostObject* self, PyObject* args, PyObject* kwds) {
83 ✔
334
    static const char* kwlist[] = {"traces", "index_dir", "auto_index",
335
                                   nullptr};
336
    PyObject* traces = nullptr;
83 ✔
337
    const char* index_dir = nullptr;
83 ✔
338
    int auto_index = 1;
83 ✔
339
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|zp",
83 !
340
                                     const_cast<char**>(kwlist), &traces,
341
                                     &index_dir, &auto_index))
342
        return nullptr;
×
343

344
    std::vector<std::string> inputs;
83 ✔
345
    if (!collect_inputs(traces, inputs)) return nullptr;
83 !
346

347
    Runtime* rt = resolve_runtime(self);
83 !
348
    const Plugins* plugins = built_set(self);
83 !
349
    if (!plugins) return nullptr;
83 !
350
    std::string index_dir_s = index_dir ? index_dir : "";
83 !
351
    PluginRun run;
83 ✔
352
    if (!run_blocking([&] {
83 !
353
            rt->submit(
334 !
354
                  dftracer::utils::run_coro_scope(
335 !
355
                      rt->executor(), run_host_scan, std::move(inputs),
166 ✔
356
                      std::move(index_dir_s), plugins, auto_index != 0, &run),
83 ✔
357
                  "plugin-host-run")
358
                .get();
83 ✔
359
        }))
82 ✔
360
        return nullptr;
1 ✔
361

362
    PyObject* stats_dict = PyDict_New();
82 !
363
    if (!stats_dict) return nullptr;
82 !
364
    dict_set_i64(stats_dict, "events_scanned",
82 ✔
365
                 (long long)run.stats.events_scanned);
82 !
366
    dict_set_i64(stats_dict, "events_matched",
82 ✔
367
                 (long long)run.stats.events_matched);
82 !
368

369
    PluginHostState* st = state_of(self);
82 ✔
370
    st->results = std::move(run.results);
82 ✔
371
    PyObject* results_dict = results_to_dict(st);
82 !
372
    if (!results_dict) {
82 !
373
        Py_DECREF(stats_dict);
374
        return nullptr;
×
375
    }
376
    PyObject* out = PyTuple_Pack(2, results_dict, stats_dict);
82 !
377
    Py_DECREF(results_dict);
378
    Py_DECREF(stats_dict);
379
    return out;
82 ✔
380
}
83 ✔
381

382
PyMethodDef ph_methods[] = {
383
    {"run", DFTU_PYCFUNCTION(ph_run), METH_VARARGS | METH_KEYWORDS,
384
     "run(traces, index_dir=None, auto_index=True) -> (dict, dict): fold every "
385
     "plugin over one fused scan. Returns ({name: bytes | pyarrow table}, "
386
     "{events_scanned, events_matched})."},
387
    {nullptr, nullptr, 0, nullptr}};
388

389
}  // namespace
390

391
PyTypeObject PluginHostType = {
392
    PyVarObject_HEAD_INIT(nullptr, 0) "dftracer_utils_ext.Plugins",
393
    sizeof(PluginHostObject),
394
    0,
395
    (destructor)ph_dealloc,
396
    0,
397
    0,
398
    0,
399
    0,
400
    0,
401
    0,
402
    0,
403
    0,
404
    0,
405
    0,
406
    0,
407
    0,
408
    0,
409
    0,
410
    Py_TPFLAGS_DEFAULT,
411
    "Load and run compiled DFTracer plugins over trace files.",
412
    0,
413
    0,
414
    0,
415
    0,
416
    0,
417
    0,
418
    ph_methods,
419
    0,
420
    0,
421
    0,
422
    0,
423
    0,
424
    0,
425
    0,
426
    (initproc)ph_init,
427
    0,
428
    ph_new,
429
};
430

431
int dftracer::utils::python::init_plugin_host(PyObject* m) {
7 ✔
432
    return register_type(m, &PluginHostType, "Plugins");
7 ✔
433
}
434

435
PyObject* dftracer::utils::python::plugin_host_results_dict(PyObject* host) {
7 ✔
436
    if (!PyObject_TypeCheck(host, &PluginHostType)) {
7 !
437
        PyErr_SetString(PyExc_TypeError, "expected a Plugins instance");
×
438
        return nullptr;
×
439
    }
440
    return results_to_dict(state_of((PluginHostObject*)host));
7 ✔
441
}
442

443
const dftracer::utils::plugins::Plugins*
444
dftracer::utils::python::plugin_host_plugins(PyObject* host) {
7 ✔
445
    if (!PyObject_TypeCheck(host, &PluginHostType)) {
7 !
446
        PyErr_SetString(PyExc_TypeError, "expected a Plugins instance");
×
447
        return nullptr;
×
448
    }
449
    return built_set((PluginHostObject*)host);
7 ✔
450
}
451

452
dftracer::utils::plugins::NamedResultRegistry*
453
dftracer::utils::python::plugin_host_results(PyObject* host) {
7 ✔
454
    if (!PyObject_TypeCheck(host, &PluginHostType)) {
7 !
455
        PyErr_SetString(PyExc_TypeError, "expected a Plugins instance");
×
456
        return nullptr;
×
457
    }
458
    return &state_of((PluginHostObject*)host)->results;
7 ✔
459
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc