• 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

65.68
/src/dftracer/utils/python/trace_viewer.cpp
1
#define PY_SSIZE_T_CLEAN
2
#include <dftracer/utils/core/common/config.h>
3
#include <dftracer/utils/core/common/filesystem.h>
4
#include <dftracer/utils/core/runtime.h>
5
#include <dftracer/utils/dataframe/dataframe.h>
6
#include <dftracer/utils/dataframe/internal/lazy_plan.h>
7
#include <dftracer/utils/duql/macros.h>
8
#include <dftracer/utils/duql/query.h>
9
#include <dftracer/utils/duql/syntax/parser.h>
10
#include <dftracer/utils/duql/syntax/tree.h>
11
#include <dftracer/utils/index/record_schema.h>
12
#include <dftracer/utils/plugins/plugins.h>
13
#include <dftracer/utils/python/dataframe.h>
14
#include <dftracer/utils/python/gzip_sink.h>
15
#include <dftracer/utils/python/lazyframe.h>
16
#include <dftracer/utils/python/plugin_host.h>
17
#include <dftracer/utils/python/py_dict_helpers.h>
18
#include <dftracer/utils/python/py_errors.h>
19
#include <dftracer/utils/python/py_list_helpers.h>
20
#include <dftracer/utils/python/py_method.h>
21
#include <dftracer/utils/python/py_runtime_mixin.h>
22
#include <dftracer/utils/python/py_seq_helpers.h>
23
#include <dftracer/utils/python/py_str_helpers.h>
24
#include <dftracer/utils/python/py_type_helpers.h>
25
#include <dftracer/utils/python/trace_viewer.h>
26
#include <dftracer/utils/trace/internal/utils.h>
27
#include <dftracer/utils/trace/time_metric.h>
28
#include <dftracer/utils/trace/views/view.h>
29
#include <dftracer/utils/trace/views/view_source.h>
30

31
#include <cctype>
32
#include <cstdint>
33
#include <cstdio>
34
#include <cstring>
35
#include <functional>
36
#include <memory>
37
#include <optional>
38
#include <string>
39
#include <string_view>
40
#include <utility>
41
#include <vector>
42

43
namespace {
44

45
namespace py = dftracer::utils::python;
46
namespace views = dftracer::utils::trace::views;
47
using dftracer::utils::dataframe::DataFrame;
48
using dftracer::utils::dataframe::LazyFrame;
49
using views::AggOp;
50
using views::AggSpec;
51
using views::ExportStats;
52
using views::GroupKey;
53
using views::Phase;
54
using views::View;
55

56
View& tv_of(PyObject* self) {
2,215 ✔
57
    return *reinterpret_cast<TraceViewerObject*>(self)->tv;
2,215 ✔
58
}
59

60
PyObject* make_viewer(View&& t) {
805 ✔
61
    auto* self = reinterpret_cast<TraceViewerObject*>(
62
        TraceViewerType.tp_alloc(&TraceViewerType, 0));
805 ✔
63
    if (!self) return nullptr;
805 !
64
    self->tv = new View(std::move(t));
805 ✔
65
    return reinterpret_cast<PyObject*>(self);
805 ✔
66
}
67

68
// Runs `fn` with the GIL held, turning a C++ exception into the typed Python
69
// error.
70
template <class Fn>
71
PyObject* guarded(Fn&& fn) {
2,293 ✔
72
    try {
73
        return fn();
2,293 ✔
74
    } catch (const std::exception& e) {
23 !
75
        py::set_typed_py_error(e);
23 !
76
        return nullptr;
23 ✔
77
    }
78
}
79

80
template <class Fn>
81
PyObject* build(PyObject* self, Fn&& fn) {
822 ✔
82
    return guarded([&] { return make_viewer(fn(tv_of(self))); });
1,644 !
83
}
84

85
PyObject* stats_dict(const ExportStats& s) {
8 ✔
86
    PyObject* d = PyDict_New();
8 ✔
87
    if (!d) return nullptr;
8 !
88
    if (dict_set_i64(d, "events_matched",
24 ✔
89
                     static_cast<long long>(s.events_matched)) < 0 ||
8 ✔
90
        dict_set_i64(d, "events_scanned",
8 !
91
                     static_cast<long long>(s.events_scanned)) < 0 ||
8 ✔
92
        dict_set_i64(d, "lines_invalid",
8 !
93
                     static_cast<long long>(s.lines_invalid)) < 0 ||
8 ✔
94
        dict_set_i64(d, "values_unconverted",
8 !
95
                     static_cast<long long>(s.values_unconverted)) < 0 ||
8 ✔
96
        dict_set_i64(d, "chunks_scanned",
8 !
97
                     static_cast<long long>(s.chunks_scanned)) < 0 ||
8 ✔
98
        dict_set_i64(d, "chunks_skipped",
8 !
99
                     static_cast<long long>(s.chunks_skipped)) < 0 ||
8 ✔
100
        dict_set_i64(d, "chunks_covered",
8 !
101
                     static_cast<long long>(s.chunks_covered)) < 0 ||
8 ✔
102
        dict_set_bool(d, "artifacts_committed", s.artifacts_committed) < 0 ||
8 !
103
        dict_set_bool(d, "truncated", s.truncated) < 0 ||
24 !
104
        dict_set_bool(d, "served_from_mv", s.served_from_mv) < 0) {
8 !
105
        Py_DECREF(d);
106
        return nullptr;
×
107
    }
108
    return d;
8 ✔
109
}
110

111
// A Python (done, total) callback as a ProgressFn. It fires on a runtime
112
// worker, so each call takes the GIL.
113
views::ProgressFn progress_from(PyObject* obj) {
42 ✔
114
    if (!obj || obj == Py_None) return {};
42 !
115
    Py_INCREF(obj);
116
    std::shared_ptr<PyObject> cb(obj, [](PyObject* p) {
1 ✔
117
        PyGILState_STATE g = PyGILState_Ensure();
1 ✔
118
        Py_DECREF(p);
119
        PyGILState_Release(g);
1 ✔
120
    });
1 !
121
    return [cb](std::size_t done, std::size_t total) {
1 ✔
122
        PyGILState_STATE g = PyGILState_Ensure();
1 ✔
123
        PyObject* r =
124
            PyObject_CallFunction(cb.get(), "nn", static_cast<Py_ssize_t>(done),
1 ✔
125
                                  static_cast<Py_ssize_t>(total));
126
        if (r)
1 !
127
            Py_DECREF(r);
128
        else
129
            PyErr_Clear();
×
130
        PyGILState_Release(g);
1 ✔
131
    };
1 !
132
}
1 ✔
133

134
class FileSink : public views::ExportSink {
135
   public:
136
    explicit FileSink(FILE* f) : f_(f) {}
20 ✔
137
    ~FileSink() override {
21 ✔
138
        if (f_) std::fclose(f_);
20 !
139
    }
21 ✔
140
    void write(std::string_view data) override {
5,134 ✔
141
        std::fwrite(data.data(), 1, data.size(), f_);
5,134 ✔
142
    }
5,134 ✔
143
    void flush() override { std::fflush(f_); }
19 ✔
144

145
   private:
146
    FILE* f_;
147
};
148

149
// "fn(key)" or "fn(key, 'a', 'b')" -> transform + inner key text; false when
150
// `t` is not a call, leaving `t` to parse as a plain key.
151
bool split_transform(const std::string& t, GroupKey::Transform& tf,
244 ✔
152
                     std::vector<std::string>& targs, std::string& inner) {
153
    const auto lp = t.find('(');
244 ✔
154
    if (lp == std::string::npos || t.back() != ')') return false;
244 !
155
    const std::string fn = t.substr(0, lp);
7 !
156
    if (fn == "dirname")
7 ✔
157
        tf = GroupKey::Transform::Dirname;
3 ✔
158
    else if (fn == "basename")
4 ✔
159
        tf = GroupKey::Transform::Basename;
1 ✔
160
    else if (fn == "lower")
3 ✔
161
        tf = GroupKey::Transform::Lower;
1 ✔
162
    else if (fn == "bucket")
2 !
163
        tf = GroupKey::Transform::Bucket;
2 ✔
164
    else
165
        return false;
×
166
    std::vector<std::string> parts;
7 ✔
167
    std::string cur;
7 ✔
168
    for (char ch : t.substr(lp + 1, t.size() - lp - 2)) {
100 !
169
        if (ch == ',') {
93 ✔
170
            parts.push_back(cur);
4 !
171
            cur.clear();
4 ✔
172
        } else {
173
            cur += ch;
89 !
174
        }
175
    }
7 ✔
176
    parts.push_back(cur);
7 !
177
    auto trim = [](const std::string& x) {
11 ✔
178
        const auto b = x.find_first_not_of(" \t'\"");
11 ✔
179
        const auto e = x.find_last_not_of(" \t'\"");
11 ✔
180
        return b == std::string::npos ? std::string() : x.substr(b, e - b + 1);
11 !
181
    };
182
    inner = trim(parts[0]);
7 !
183
    for (std::size_t i = 1; i < parts.size(); ++i)
11 ✔
184
        targs.push_back(trim(parts[i]));
4 !
185
    return !inner.empty();
7 ✔
186
}
7 ✔
187

188
// name | cat | pid | tid | fhash | hhash | io_cat | acc_pat | rank |
189
// file_path | file_name | host_name | arg:<key> | any other field, each
190
// optionally wrapped in a transform call.
191
GroupKey parse_group_key(const std::string& s) {
244 ✔
192
    std::string t = s;
244 !
193
    GroupKey::Transform tf = GroupKey::Transform::None;
244 ✔
194
    std::vector<std::string> targs;
244 ✔
195
    std::string inner;
244 ✔
196
    if (split_transform(t, tf, targs, inner)) t = inner;
244 !
197
    GroupKey out;
244 ✔
198
    if (t == "name")
244 ✔
199
        out = GroupKey::name();
51 ✔
200
    else if (t == "cat")
193 ✔
201
        out = GroupKey::cat();
107 ✔
202
    else if (t == "pid")
86 ✔
203
        out = GroupKey::pid();
20 ✔
204
    else if (t == "tid")
66 ✔
205
        out = GroupKey::tid();
9 ✔
206
    else if (t == "fhash")
57 ✔
207
        out = GroupKey::fhash();
7 ✔
208
    else if (t == "hhash")
50 ✔
209
        out = GroupKey::hhash();
6 ✔
210
    else if (t == "io_cat")
44 ✔
211
        out = GroupKey::io_cat();
9 ✔
212
    else if (t == "acc_pat")
35 !
213
        out = GroupKey::acc_pat();
×
214
    else if (t == "file_path")
35 ✔
215
        out = GroupKey::file_path();
13 ✔
216
    else if (t == "file_name")
22 ✔
217
        out = GroupKey::file_name();
2 ✔
218
    else if (t == "host_name")
20 ✔
219
        out = GroupKey::host_name();
6 ✔
220
    else if (t == "rank")
14 ✔
221
        out = GroupKey::rank();
2 ✔
222
    else if (t.rfind("arg:", 0) == 0)
12 !
223
        out = GroupKey::of_arg(t.substr(4));
×
224
    else
225
        out = GroupKey::field(t);
12 !
226
    out.transform = tf;
244 ✔
227
    out.transform_args = std::move(targs);
244 ✔
228
    return out;
488 ✔
229
}
244 ✔
230

231
// "count" | "op:field" | "argmax:field:by" | "pct:field:q" | "pNN:field".
232
// "count" is the group row count; "count:field" counts the rows where the
233
// field is present.
234
std::optional<AggSpec> parse_agg_spec(const std::string& t) {
474 ✔
235
    auto c1 = t.find(':');
474 ✔
236
    std::string op = t.substr(0, c1);
474 !
237
    std::string field, by;
474 ✔
238
    if (c1 != std::string::npos) {
474 ✔
239
        std::string rest = t.substr(c1 + 1);
283 !
240
        auto c2 = rest.find(':');
283 ✔
241
        field = rest.substr(0, c2);
283 !
242
        if (c2 != std::string::npos) by = rest.substr(c2 + 1);
283 !
243
    }
283 ✔
244
    const std::string occ = field.empty() ? "dur" : field;
474 !
245
    if (op == "count") return AggSpec(AggOp::Count, field, "", "");
474 !
246
    if (op == "sum") return AggSpec(AggOp::Sum, field);
302 !
247
    if (op == "sumsq") return AggSpec(AggOp::SumSq, field);
240 !
248
    if (op == "min") return AggSpec(AggOp::Min, field);
225 !
249
    if (op == "max") return AggSpec(AggOp::Max, field);
175 !
250
    if (op == "mean") return AggSpec(AggOp::Mean, field);
124 !
251
    if (op == "var") return AggSpec(AggOp::Var, field);
69 !
252
    if (op == "std") return AggSpec(AggOp::Std, field);
64 !
253
    if (op == "skew") return AggSpec(AggOp::Skew, field);
35 !
254
    if (op == "kurt") return AggSpec(AggOp::Kurt, field);
32 !
255
    if (op == "hist") return AggSpec(AggOp::Hist, field);
29 !
256
    if (op == "argmax") return AggSpec(AggOp::ArgMax, field, "", by);
27 !
257
    if (op == "set_union" || op == "uniq")
27 !
258
        return AggSpec(AggOp::SetUnion, field);
3 !
259
    if (op == "busy") return AggSpec(AggOp::Busy, occ);
24 !
260
    if (op == "concurrency") return AggSpec(AggOp::Concurrency, occ);
16 !
261
    if (op == "utilization") return AggSpec(AggOp::Utilization, occ);
10 !
262
    if (op == "active") return AggSpec(AggOp::Active, occ);
9 !
263
    if (op == "pct")
8 !
264
        return AggSpec(AggOp::Pct, field, "", "",
×
265
                       by.empty() ? 0.0 : std::stod(by));
×
266
    if (op.size() >= 2 && op[0] == 'p') {
8 !
267
        double denom = 1.0;
8 ✔
268
        for (std::size_t i = 1; i < op.size(); ++i) {
24 ✔
269
            if (op[i] < '0' || op[i] > '9') return std::nullopt;
16 !
270
            denom *= 10.0;
16 ✔
271
        }
272
        return AggSpec(AggOp::Pct, field, op + "_" + field, "",
16 !
273
                       std::stod(op.substr(1)) / denom);
24 !
274
    }
275
    return std::nullopt;
×
276
}
474 ✔
277

278
bool parse_specs(PyObject* args, std::vector<AggSpec>& out) {
202 ✔
279
    const Py_ssize_t n = PyTuple_Size(args);
202 ✔
280
    for (Py_ssize_t i = 0; i < n; ++i) {
676 ✔
281
        const char* s = as_utf8(PyTuple_GetItem(args, i));
474 !
282
        if (!s) return false;
474 !
283
        std::optional<AggSpec> spec = parse_agg_spec(s);
948 !
284
        if (!spec) {
474 !
285
            PyErr_Format(PyExc_ValueError, "unknown agg spec: %s", s);
×
286
            return false;
×
287
        }
288
        out.push_back(std::move(*spec));
474 !
289
    }
474 !
290
    return true;
202 ✔
291
}
292

293
bool parse_containment(PyObject* args, PyObject* kwds, bool with_group,
24 ✔
294
                       views::ContainmentArgs& out) {
295
    static const char* kw_group[] = {"partition", "ts",    "dur",
296
                                     "name",      "group", nullptr};
297
    static const char* kw_plain[] = {"partition", "ts", "dur", "name", nullptr};
298
    PyObject* part = nullptr;
24 ✔
299
    PyObject* group = nullptr;
24 ✔
300
    const char* ts = "ts";
24 ✔
301
    const char* dur = "dur";
24 ✔
302
    const char* name = "name";
24 ✔
303
    if (!PyArg_ParseTupleAndKeywords(
24 !
304
            args, kwds, with_group ? "|OsssO" : "|Osss",
305
            const_cast<char**>(with_group ? kw_group : kw_plain), &part, &ts,
306
            &dur, &name, &group))
307
        return false;
×
308
    if (part && part != Py_None) {
24 !
309
        out.partition.clear();
24 ✔
310
        if (!py::parse_string_seq(part, "partition must be a sequence",
24 !
311
                                  out.partition))
24 !
312
            return false;
×
313
    }
314
    if (group && group != Py_None &&
45 !
315
        !py::parse_string_seq(group, "group must be a sequence", out.group))
21 !
316
        return false;
×
317
    out.ts = ts;
24 !
318
    out.dur = dur;
24 !
319
    out.name = name;
24 !
320
    return true;
24 ✔
321
}
322

323
// Runs the task `make` builds on the runtime `runtime_arg` names, with the GIL
324
// released.
325
template <class Make, class T>
326
bool run_on(PyObject* runtime_arg, Make&& make, T& out) {
47 ✔
327
    std::shared_ptr<dftracer::utils::Runtime> rt =
47 !
328
        runtime_from_arg(runtime_arg);
329
    if (!rt) return false;
47 !
330
    return run_blocking([&] { out = rt->submit(make()).get(); });
94 !
331
}
47 ✔
332

333
PyObject* tv_new(PyTypeObject* type, PyObject*, PyObject*) {
429 ✔
334
    auto* self = reinterpret_cast<TraceViewerObject*>(type->tp_alloc(type, 0));
429 ✔
335
    if (self) self->tv = nullptr;
429 !
336
    return reinterpret_cast<PyObject*>(self);
429 ✔
337
}
338

339
void tv_dealloc(TraceViewerObject* self) {
1,234 ✔
340
    delete self->tv;
1,234 ✔
341
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
1,234 ✔
342
}
1,234 ✔
343

344
int tv_init(TraceViewerObject* self, PyObject* args, PyObject* kwds) {
429 ✔
345
    static const char* kwlist[] = {"files", "index_path", nullptr};
346
    PyObject* files = nullptr;
429 ✔
347
    PyObject* index_obj = nullptr;
429 ✔
348
    if (!PyArg_ParseTupleAndKeywords(
429 !
349
            args, kwds, "O|O", const_cast<char**>(kwlist), &files, &index_obj))
350
        return -1;
×
351
    std::string index_dir;
429 ✔
352
    if (index_obj && index_obj != Py_None) {
429 !
353
        const char* s = as_utf8(index_obj);
94 !
354
        if (!s) return -1;
94 !
355
        index_dir = s;
94 !
356
    }
357
    std::vector<std::string> paths;
429 ✔
358
    std::optional<std::string> dir;
429 ✔
359
    if (PyUnicode_Check(files)) {
429 ✔
360
        const char* path = PyUnicode_AsUTF8(files);
364 !
361
        if (!path) return -1;
364 !
362
        std::error_code ec;
364 ✔
363
        if (fs::is_directory(path, ec))
364 !
364
            dir = path;
12 !
365
        else
366
            paths.emplace_back(path);
352 !
367
    } else if (!py::parse_string_seq(files,
65 !
368
                                     "files must be a path or a "
369
                                     "sequence of paths",
370
                                     paths)) {
371
        return -1;
×
372
    }
373
    View tv;
429 !
374
    if (dir) {
429 ✔
375
        if (!run_blocking([&] {
12 !
376
                tv = py::get_default_runtime()
12 ✔
377
                         ->submit(View::from_directory(*dir, index_dir))
24 !
378
                         .get();
12 !
379
            }))
12 ✔
380
            return -1;
×
381
    } else {
382
        std::vector<views::ViewFile> vfiles;
417 ✔
383
        vfiles.reserve(paths.size());
417 !
384
        for (const std::string& p : paths)
869 ✔
385
            vfiles.push_back(views::ViewFile{
452 !
386
                p, dftracer::utils::trace::internal::determine_index_path(
387
                       p, index_dir)});
388
        if (!run_blocking([&] { tv = View::from_files(std::move(vfiles)); }))
834 !
389
            return -1;
1 ✔
390
    }
417 ✔
391
    delete self->tv;
428 !
392
    self->tv = new View(std::move(tv));
428 !
393
    return 0;
428 ✔
394
}
429 ✔
395

396
PyObject* tv_lazy(PyObject* self, PyObject*) {
1,221 ✔
397
    return guarded(
2,442 !
398
        [&] { return py::wrap_lazyframe(LazyFrame(tv_of(self).lazy())); });
3,663 !
399
}
400

401
PyObject* tv_with_lazy(PyObject* self, PyObject* arg) {
32 ✔
402
    const LazyFrame* lf = py::lazyframe_of(arg);
32 !
403
    if (!lf) return nullptr;
32 !
404
    return build(self, [&](const View& t) { return t.with_lazy(*lf); });
64 !
405
}
406

407
PyObject* tv_filter(PyObject* self, PyObject* arg) {
103 ✔
408
    PyObject* s = PyObject_Str(arg);
103 !
409
    if (!s) return nullptr;
103 !
410
    const char* dsl = PyUnicode_AsUTF8(s);
103 !
411
    if (!dsl) {
103 !
412
        Py_DECREF(s);
413
        return nullptr;
×
414
    }
415
    auto parsed = dftracer::utils::duql::Query::from_string(dsl);
103 !
416
    Py_DECREF(s);
417
    if (!parsed) {
103 ✔
418
        PyErr_Format(PyExc_ValueError, "invalid duql filter: %s",
1 !
419
                     parsed.error().message.c_str());
1 !
420
        return nullptr;
1 ✔
421
    }
422
    return build(self, [&](const View& t) {
204 !
423
        return t.filter(std::move(parsed.value()));
102 !
424
    });
102 ✔
425
}
103 ✔
426

427
// A duql parameter from a Python bool, int, float or str.
428
bool duql_param(PyObject* v, dftracer::utils::duql::LiteralValue& out) {
32 ✔
429
    if (PyBool_Check(v)) {
32 !
430
        out = v == Py_True;
×
431
    } else if (PyLong_Check(v)) {
32 ✔
432
        int overflow = 0;
13 ✔
433
        const long long i = PyLong_AsLongLongAndOverflow(v, &overflow);
13 !
434
        if (overflow > 0) {
13 !
435
            const unsigned long long u = PyLong_AsUnsignedLongLong(v);
×
436
            if (PyErr_Occurred()) return false;
×
437
            out = static_cast<std::uint64_t>(u);
×
438
        } else if (overflow < 0 || (i == -1 && PyErr_Occurred())) {
13 !
439
            PyErr_SetString(PyExc_OverflowError,
×
440
                            "a duql integer parameter must fit in 64 bits");
441
            return false;
×
442
        } else if (i < 0) {
13 !
443
            out = static_cast<std::int64_t>(i);
×
444
        } else {
445
            out = static_cast<std::uint64_t>(i);
13 ✔
446
        }
447
    } else if (PyFloat_Check(v)) {
19 !
448
        out = PyFloat_AsDouble(v);
×
449
    } else if (PyUnicode_Check(v)) {
19 ✔
450
        const char* s = PyUnicode_AsUTF8(v);
18 ✔
451
        if (!s) return false;
18 !
452
        out = std::string(s);
18 !
453
    } else {
454
        PyErr_Format(PyExc_TypeError,
1 ✔
455
                     "a duql parameter must be bool, int, float or str, not %s",
456
                     Py_TYPE(v)->tp_name);
1 ✔
457
        return false;
1 ✔
458
    }
459
    return true;
31 ✔
460
}
461

462
// (text, params dict) -> the text and bound parameters, or false with a
463
// Python error set.
464
bool duql_args(PyObject* args, const char*& text,
177 ✔
465
               dftracer::utils::duql::Params& params) {
466
    PyObject* dict = nullptr;
177 ✔
467
    if (!PyArg_ParseTuple(args, "s|O!", &text, &PyDict_Type, &dict))
177 !
468
        return false;
×
469
    if (!dict) return true;
177 !
470
    PyObject* key = nullptr;
177 ✔
471
    PyObject* value = nullptr;
177 ✔
472
    Py_ssize_t pos = 0;
177 ✔
473
    while (PyDict_Next(dict, &pos, &key, &value)) {
205 !
474
        const char* name = PyUnicode_AsUTF8(key);
29 !
475
        if (!name) return false;
30 !
476
        if (PyList_Check(value) || PyTuple_Check(value)) {
29 ✔
477
            PyObject* seq = PySequence_Fast(value, "a list parameter");
5 !
478
            if (!seq) return false;
5 !
479
            std::vector<dftracer::utils::duql::LiteralValue> items;
5 ✔
480
            const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
5 ✔
481
            items.reserve(static_cast<std::size_t>(n));
5 !
482
            bool ok = true;
5 ✔
483
            for (Py_ssize_t i = 0; ok && i < n; ++i) {
13 !
484
                dftracer::utils::duql::LiteralValue lit;
8 ✔
485
                ok = duql_param(PySequence_Fast_GET_ITEM(seq, i), lit);
8 !
486
                if (ok) items.push_back(std::move(lit));
8 !
487
            }
8 ✔
488
            Py_DECREF(seq);
489
            if (!ok) return false;
5 !
490
            params.insert_or_assign(name, std::move(items));
5 !
491
            continue;
5 ✔
492
        }
5 !
493
        dftracer::utils::duql::LiteralValue lit;
24 ✔
494
        if (!duql_param(value, lit)) return false;
24 !
495
        params.insert_or_assign(name, std::move(lit));
23 !
496
    }
24 ✔
497
    return true;
176 ✔
498
}
499

500
PyObject* tv_duql(PyObject* self, PyObject* args) {
170 ✔
501
    const char* text = nullptr;
170 ✔
502
    dftracer::utils::duql::Params params;
170 !
503
    if (!duql_args(args, text, params)) return nullptr;
170 !
504
    return build(self, [&](const View& t) { return t.duql(text, params); });
352 !
505
}
170 ✔
506

507
PyObject* tv_explain_duql(PyObject* self, PyObject* args) {
7 ✔
508
    const char* text = nullptr;
7 ✔
509
    dftracer::utils::duql::Params params;
7 !
510
    if (!duql_args(args, text, params)) return nullptr;
7 !
511
    return guarded([&] {
14 !
512
        const std::string plan = tv_of(self).explain_duql(text, params);
14 !
513
        return PyUnicode_FromStringAndSize(
7 !
514
            plan.data(), static_cast<Py_ssize_t>(plan.size()));
21 ✔
515
    });
14 ✔
516
}
7 ✔
517

518
PyObject* tv_select(PyObject* self, PyObject* arg) {
22 ✔
519
    std::vector<std::string> names;
22 ✔
520
    if (!py::parse_string_seq(arg, "select expects a sequence of names", names))
22 !
521
        return nullptr;
×
522
    return build(self,
44 !
523
                 [&](const View& t) { return t.select(std::move(names)); });
44 !
524
}
22 ✔
525

526
PyObject* tv_phase(PyObject* self, PyObject* arg) {
38 ✔
527
    const char* s = as_utf8(arg);
38 !
528
    if (!s) return nullptr;
38 !
529
    const std::string t(s);
38 !
530
    Phase ph;
531
    if (t == "events")
38 ✔
532
        ph = Phase::Events;
18 ✔
533
    else if (t == "counters")
20 ✔
534
        ph = Phase::Counters;
1 ✔
535
    else if (t == "aggregated")
19 ✔
536
        ph = Phase::Aggregated;
2 ✔
537
    else if (t == "metadata")
17 ✔
538
        ph = Phase::Metadata;
11 ✔
539
    else if (t == "any")
6 !
540
        ph = Phase::Any;
6 ✔
541
    else {
542
        PyErr_SetString(PyExc_ValueError,
×
543
                        "phase must be 'events', 'counters', 'aggregated', "
544
                        "'metadata', or 'any'");
545
        return nullptr;
×
546
    }
547
    return build(self, [&](const View& v) { return v.phase(ph); });
76 !
548
}
38 ✔
549

550
PyObject* tv_time_range(PyObject* self, PyObject* args) {
7 ✔
551
    double begin = 0, end = 0;
7 ✔
552
    if (!PyArg_ParseTuple(args, "dd", &begin, &end)) return nullptr;
7 !
553
    return build(self, [&](const View& t) { return t.time_range(begin, end); });
14 !
554
}
555

556
PyObject* tv_time_bucket(PyObject* self, PyObject* args, PyObject* kwds) {
19 ✔
557
    long long us = 0;
19 ✔
558
    PyObject* normalize_to = nullptr;
19 ✔
559
    static const char* kwlist[] = {"interval_us", "normalize_to", nullptr};
560
    if (!PyArg_ParseTupleAndKeywords(
19 !
561
            args, kwds, "L|O", const_cast<char**>(kwlist), &us, &normalize_to))
562
        return nullptr;
×
563
    if (us < 0) {
19 !
564
        PyErr_SetString(PyExc_ValueError, "interval_us must be >= 0");
×
565
        return nullptr;
×
566
    }
567
    const auto width = static_cast<std::uint64_t>(us);
19 ✔
568
    if (!normalize_to || normalize_to == Py_None)
19 !
569
        return build(self, [&](const View& t) { return t.time_bucket(width); });
32 !
570
    if (PyUnicode_Check(normalize_to)) {
3 ✔
571
        const char* s = PyUnicode_AsUTF8(normalize_to);
1 !
572
        if (!s) return nullptr;
1 !
573
        if (std::strcmp(s, "min") != 0) {
1 !
574
            PyErr_SetString(PyExc_ValueError,
×
575
                            "normalize_to must be an int origin or 'min'");
576
            return nullptr;
×
577
        }
578
        return build(self,
2 !
579
                     [&](const View& t) { return t.time_bucket_min(width); });
2 ✔
580
    }
581
    const long long origin = PyLong_AsLongLong(normalize_to);
2 !
582
    if (origin == -1 && PyErr_Occurred()) return nullptr;
2 !
583
    if (origin < 0) {
2 !
584
        PyErr_SetString(PyExc_ValueError, "normalize_to must be >= 0");
×
585
        return nullptr;
×
586
    }
587
    return build(self, [&](const View& t) {
4 !
588
        return t.time_bucket(width, static_cast<std::uint64_t>(origin));
2 ✔
589
    });
2 ✔
590
}
591

592
PyObject* tv_resolution(PyObject* self, PyObject* arg) {
2 ✔
593
    const long long us = PyLong_AsLongLong(arg);
2 !
594
    if (us == -1 && PyErr_Occurred()) return nullptr;
2 !
595
    if (us < 0) {
2 !
596
        PyErr_SetString(PyExc_ValueError, "resolution must be >= 0");
×
597
        return nullptr;
×
598
    }
599
    return build(self, [&](const View& t) {
4 !
600
        return t.resolution(static_cast<std::uint64_t>(us));
2 ✔
601
    });
2 ✔
602
}
603

604
PyObject* tv_time_scale(PyObject* self, PyObject* arg) {
×
605
    const double ratio = PyFloat_AsDouble(arg);
×
606
    if (ratio == -1.0 && PyErr_Occurred()) return nullptr;
×
607
    return build(self, [&](const View& t) { return t.time_scale(ratio); });
×
608
}
609

610
PyObject* tv_time_unit(PyObject* self, PyObject* arg) {
2 ✔
611
    namespace trace = dftracer::utils::trace;
612
    const char* s = as_utf8(arg);
2 !
613
    if (!s) return nullptr;
2 !
614
    const std::string t(s);
2 !
615
    trace::TimeMetric target;
616
    if (t == "ns")
2 !
617
        target = trace::TimeMetric::NS;
×
618
    else if (t == "us")
2 !
619
        target = trace::TimeMetric::US;
2 ✔
620
    else if (t == "ms")
×
621
        target = trace::TimeMetric::MS;
×
622
    else if (t == "sec" || t == "s")
×
623
        target = trace::TimeMetric::SEC;
×
624
    else {
625
        PyErr_SetString(PyExc_ValueError, "time_unit must be ns/us/ms/sec/s");
×
626
        return nullptr;
×
627
    }
628
    return build(self, [&](const View& v) {
4 !
629
        const double ratio =
630
            static_cast<double>(
2 ✔
631
                trace::time_metric_ns_per_unit(v.time_metric())) /
2 ✔
632
            static_cast<double>(trace::time_metric_ns_per_unit(target));
2 ✔
633
        return v.time_scale(ratio);
2 ✔
634
    });
2 ✔
635
}
2 ✔
636

637
PyObject* tv_group_by(PyObject* self, PyObject* args) {
199 ✔
638
    std::vector<GroupKey> keys;
199 ✔
639
    const Py_ssize_t n = PyTuple_Size(args);
199 !
640
    for (Py_ssize_t i = 0; i < n; ++i) {
443 ✔
641
        const char* s = as_utf8(PyTuple_GetItem(args, i));
244 !
642
        if (!s) return nullptr;
244 !
643
        keys.push_back(parse_group_key(s));
244 !
644
    }
645
    return build(self,
398 !
646
                 [&](const View& t) { return t.group_by(std::move(keys)); });
398 !
647
}
199 ✔
648

649
PyObject* tv_agg(PyObject* self, PyObject* args) {
196 ✔
650
    std::vector<AggSpec> specs;
196 ✔
651
    if (!parse_specs(args, specs)) return nullptr;
196 !
652
    return build(self, [&](const View& t) { return t.agg(std::move(specs)); });
392 !
653
}
196 ✔
654

655
PyObject* tv_agg_numeric_args(PyObject* self, PyObject* args) {
6 ✔
656
    std::vector<AggSpec> specs;
6 ✔
657
    if (!parse_specs(args, specs)) return nullptr;
6 !
658
    return build(self, [&](const View& t) {
12 !
659
        return specs.empty() ? t.agg_numeric_args()
6 ✔
660
                             : t.agg_numeric_args(std::move(specs));
6 !
661
    });
6 ✔
662
}
6 ✔
663

664
PyObject* tv_record_schema(PyObject* self, PyObject* arg) {
11 ✔
665
    const char* id = as_utf8(arg);
11 !
666
    if (!id) return nullptr;
11 !
667
    return build(self, [&](const View& t) { return t.record_schema(id); });
23 !
668
}
669

670
PyObject* tv_rollup_root(PyObject* self, PyObject* arg) {
7 ✔
671
    const char* dir = as_utf8(arg);
7 !
672
    if (!dir) return nullptr;
7 !
673
    return build(self, [&](const View& t) { return t.rollup_root(dir); });
14 !
674
}
675

676
PyObject* tv_views_root(PyObject* self, PyObject* arg) {
7 ✔
677
    const char* dir = as_utf8(arg);
7 !
678
    if (!dir) return nullptr;
7 !
679
    return build(self, [&](const View& t) { return t.views_root(dir); });
14 !
680
}
681

682
PyObject* tv_memory_budget(PyObject* self, PyObject* arg) {
3 ✔
683
    const long long b = PyLong_AsLongLong(arg);
3 !
684
    if (b == -1 && PyErr_Occurred()) return nullptr;
3 !
685
    if (b < 0) {
3 !
686
        PyErr_SetString(PyExc_ValueError, "memory_budget must be >= 0");
×
687
        return nullptr;
×
688
    }
689
    return build(self, [&](const View& t) {
6 !
690
        return t.memory_budget(static_cast<std::uint64_t>(b));
3 ✔
691
    });
3 ✔
692
}
693

694
PyObject* tv_columns(PyObject* self, PyObject*) {
15 ✔
695
    std::vector<std::string> cols;
15 ✔
696
    if (!run_blocking([&] { cols = tv_of(self).columns(); })) return nullptr;
30 !
697
    return str_list_from(cols);
15 !
698
}
15 ✔
699

700
PyObject* tv_column_info(PyObject* self, PyObject*) {
3 ✔
701
    std::vector<views::ColumnInfo> info;
3 ✔
702
    if (!run_blocking([&] { info = tv_of(self).column_info(); }))
6 !
703
        return nullptr;
×
704
    PyObject* d = PyDict_New();
3 !
705
    if (!d) return nullptr;
3 !
706
    for (const auto& c : info) {
40 ✔
707
        PyObject* v = PyUnicode_FromString(c.type.c_str());
37 !
708
        if (!v || PyDict_SetItemString(d, c.name.c_str(), v) < 0) {
37 !
709
            Py_XDECREF(v);
×
710
            Py_DECREF(d);
711
            return nullptr;
×
712
        }
713
        Py_DECREF(v);
714
    }
715
    return d;
3 ✔
716
}
3 ✔
717

718
PyObject* tv_schema_tree(PyObject* self, PyObject*) {
1 ✔
719
    std::string json;
1 ✔
720
    if (!run_blocking(
1 !
721
            [&] { json = views::schema_tree_json(tv_of(self).schema_tree()); }))
1 !
722
        return nullptr;
×
723
    return PyUnicode_FromStringAndSize(json.data(),
1 !
724
                                       static_cast<Py_ssize_t>(json.size()));
2 ✔
725
}
1 ✔
726

727
PyObject* tv_time_metric(PyObject* self, PyObject*) {
2 ✔
728
    std::string s(dftracer::utils::trace::time_metric_to_string(
4 !
729
        tv_of(self).time_metric()));
4 !
730
    for (char& c : s) c = static_cast<char>(std::tolower(c));
6 ✔
731
    return PyUnicode_FromString(s.c_str());
4 !
732
}
2 ✔
733

734
PyObject* tv_aggregates(PyObject* self, PyObject*) {
×
735
    return guarded([&] { return PyBool_FromLong(tv_of(self).aggregates()); });
×
736
}
737

738
// True while a filter still selects raw events: no trace aggregation and no
739
// op but filters on the plan. Reads no index.
740
PyObject* tv_filters_events(PyObject* self, PyObject*) {
17 ✔
741
    return PyBool_FromLong(tv_of(self).filters_events());
17 ✔
742
}
743

744
PyObject* tv_call_tree(PyObject* self, PyObject* args, PyObject* kwds) {
3 ✔
745
    views::ContainmentArgs a;
3 !
746
    if (!parse_containment(args, kwds, false, a)) return nullptr;
3 !
747
    return guarded([&] {
6 !
748
        return py::wrap_lazyframe(
3 !
749
            tv_of(self).call_tree(a.partition, a.ts, a.dur, a.name));
6 !
750
    });
3 ✔
751
}
3 ✔
752

753
PyObject* tv_flamegraph(PyObject* self, PyObject* args, PyObject* kwds) {
13 ✔
754
    views::ContainmentArgs a;
13 !
755
    if (!parse_containment(args, kwds, true, a)) return nullptr;
13 !
756
    return guarded([&] {
26 !
757
        return py::wrap_lazyframe(
11 !
758
            tv_of(self).flamegraph(a.partition, a.ts, a.dur, a.name, a.group));
32 !
759
    });
13 ✔
760
}
13 ✔
761

762
PyObject* tv_containment(PyObject* self, PyObject* args, PyObject* kwds) {
5 ✔
763
    views::ContainmentArgs a;
5 !
764
    if (!parse_containment(args, kwds, true, a)) return nullptr;
5 !
765
    return guarded([&]() -> PyObject* {
10 !
766
        auto r =
767
            tv_of(self).containment(a.partition, a.ts, a.dur, a.name, a.group);
10 !
768
        PyObject* ct = py::wrap_lazyframe(LazyFrame(r.plans()[0]));
5 !
769
        if (!ct) return nullptr;
5 !
770
        PyObject* fg = py::wrap_lazyframe(LazyFrame(r.plans()[1]));
5 !
771
        if (!fg) {
5 !
772
            Py_DECREF(ct);
773
            return nullptr;
×
774
        }
775
        return Py_BuildValue("(NN)", ct, fg);
5 !
776
    });
10 ✔
777
}
5 ✔
778

779
PyObject* tv_flamegraph_partial(PyObject* self, PyObject* args,
3 ✔
780
                                PyObject* kwds) {
781
    views::ContainmentArgs a;
3 !
782
    if (!parse_containment(args, kwds, true, a)) return nullptr;
3 !
783
    return guarded([&] {
6 !
784
        return py::wrap_lazyframe(LazyFrame(
6 !
785
            tv_of(self)
3 ✔
786
                .flamegraph_partial(a.partition, a.ts, a.dur, a.name, a.group)
6 !
787
                .plans()
3 ✔
788
                .front()));
9 ✔
789
    });
3 ✔
790
}
3 ✔
791

792
PyObject* tv_aggregate_partial(PyObject* self, PyObject*) {
8 ✔
793
    return guarded([&] {
16 !
794
        return py::wrap_lazyframe(
7 !
795
            LazyFrame(tv_of(self).aggregate_partial().plans().front()));
15 !
796
    });
16 ✔
797
}
798

799
PyObject* tv_sink_json(PyObject* self, PyObject* arg) {
19 ✔
800
    const char* path = as_utf8(arg);
19 !
801
    if (!path) return nullptr;
19 !
802
    FILE* f = std::fopen(path, "wb");
19 !
803
    if (!f) {
19 !
804
        PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
×
805
        return nullptr;
×
806
    }
807
    auto sink = std::make_shared<FileSink>(f);
19 !
808
    return guarded([&] {
19 !
809
        return py::wrap_lazyframe(LazyFrame(
38 !
810
            tv_of(self).sink_json(sink, views::LAZY).plans().front()));
57 !
811
    });
19 ✔
812
}
19 ✔
813

814
PyObject* tv_typed(PyObject* self, PyObject* args, PyObject* kwds) {
39 ✔
815
    int shard_begin = 0, shard_end = 0;
39 ✔
816
    PyObject* progress = nullptr;
39 ✔
817
    PyObject* runtime_arg = nullptr;
39 ✔
818
    static const char* kwlist[] = {"shard_begin", "shard_end", "progress",
819
                                   "runtime", nullptr};
820
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiOO",
39 !
821
                                     const_cast<char**>(kwlist), &shard_begin,
822
                                     &shard_end, &progress, &runtime_arg))
823
        return nullptr;
×
824
    views::TypedResult typed;
39 ✔
825
    views::ProgressFn fn = progress_from(progress);
39 !
826
    if (!run_on(
39 !
827
            runtime_arg,
828
            [&] {
39 ✔
829
                return tv_of(self).collect_typed(shard_begin, shard_end, fn);
39 !
830
            },
831
            typed))
832
        return nullptr;
×
833
    PyObject* d = PyDict_New();
39 !
834
    if (!d) return nullptr;
39 !
835
    const std::pair<const char*, DataFrame*> parts[] = {
836
        {"regular", &typed.regular},
78 ✔
837
        {"aggregated", &typed.aggregated},
78 ✔
838
        {"counters", &typed.counters}};
39 ✔
839
    for (const auto& [key, frame] : parts) {
156 ✔
840
        PyObject* v = py::wrap_dataframe(std::move(*frame));
117 !
841
        if (!v || PyDict_SetItemString(d, key, v) < 0) {
117 !
842
            Py_XDECREF(v);
×
843
            Py_DECREF(d);
844
            return nullptr;
×
845
        }
846
        Py_DECREF(v);
847
    }
848
    return d;
39 ✔
849
}
39 ✔
850

851
PyObject* tv_materialize(PyObject* self, PyObject* args, PyObject* kwds) {
3 ✔
852
    long long checkpoint_size = 0, part_size = 0;
3 ✔
853
    PyObject* progress = nullptr;
3 ✔
854
    PyObject* runtime_arg = nullptr;
3 ✔
855
    static const char* kwlist[] = {"checkpoint_size", "part_size", "progress",
856
                                   "runtime", nullptr};
857
    if (!PyArg_ParseTupleAndKeywords(
3 !
858
            args, kwds, "|LLOO", const_cast<char**>(kwlist), &checkpoint_size,
859
            &part_size, &progress, &runtime_arg))
860
        return nullptr;
×
861
    ExportStats stats;
3 ✔
862
    views::ProgressFn fn = progress_from(progress);
3 !
863
    if (!run_on(
3 !
864
            runtime_arg,
865
            [&] {
3 ✔
866
                return tv_of(self).materialize(
3 ✔
867
                    static_cast<std::uint64_t>(checkpoint_size),
3 ✔
868
                    static_cast<std::uint64_t>(part_size), fn);
3 !
869
            },
870
            stats))
871
        return nullptr;
×
872
    return stats_dict(stats);
3 !
873
}
3 ✔
874

875
// A trace of the aggregation (counter events) when the viewer aggregates, else
876
// of the selected events.
877
PyObject* tv_export_trace(PyObject* self, PyObject* args, PyObject* kwds) {
5 ✔
878
    static const char* kwlist[] = {"path",        "compress", "index",
879
                                   "member_size", "level",    "part_size",
880
                                   "runtime",     nullptr};
881
    const char* path = nullptr;
5 ✔
882
    int compress = 1;
5 ✔
883
    int index = 0;
5 ✔
884
    long long member_size = 0;
5 ✔
885
    int level = 6;
5 ✔
886
    long long part_size = 0;
5 ✔
887
    PyObject* runtime_arg = nullptr;
5 ✔
888
    if (!PyArg_ParseTupleAndKeywords(
5 !
889
            args, kwds, "s|ppLiLO", const_cast<char**>(kwlist), &path,
890
            &compress, &index, &member_size, &level, &part_size, &runtime_arg))
891
        return nullptr;
×
892
    const View& t = tv_of(self);
5 ✔
893
    ExportStats stats;
5 ✔
894
    bool aggregates = false;
5 ✔
895
    try {
896
        aggregates = t.aggregates();
5 !
897
    } catch (const std::exception& e) {
×
898
        py::set_typed_py_error(e);
×
899
        return nullptr;
×
900
    }
×
901
    if (aggregates) {
5 ✔
902
        std::unique_ptr<views::ExportSink> sink;
3 ✔
903
        if (compress) {
3 ✔
904
            try {
905
                sink = std::make_unique<dftracer::utils::python::GzipSink>(
4 !
906
                    path, level);
2 ✔
907
            } catch (const std::exception& e) {
×
908
                py::set_typed_py_error(e);
×
909
                return nullptr;
×
910
            }
×
911
        } else {
912
            FILE* f = std::fopen(path, "wb");
1 !
913
            if (!f) {
1 !
914
                PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
×
915
                return nullptr;
×
916
            }
917
            sink = std::make_unique<FileSink>(f);
1 !
918
        }
919
        const bool ok =
920
            run_on(runtime_arg, [&] { return t.sink_counters(*sink); }, stats);
6 !
921
        sink.reset();
3 ✔
922
        if (!ok) return nullptr;
3 !
923
        return stats_dict(stats);
3 !
924
    }
3 ✔
925
    views::TraceWriteOptions opts;
2 ✔
926
    opts.output_path = path;
2 !
927
    opts.member_size = static_cast<std::size_t>(member_size);
2 ✔
928
    opts.compress = compress != 0;
2 ✔
929
    opts.level = level;
2 ✔
930
    opts.build_index = index != 0;
2 ✔
931
    opts.part_size = static_cast<std::size_t>(part_size);
2 ✔
932
    if (!run_on(
2 !
933
            runtime_arg, [&] { return t.sink_trace(std::move(opts)); }, stats))
2 !
934
        return nullptr;
×
935
    return stats_dict(stats);
2 !
936
}
2 ✔
937

938
PyObject* tv_merge_partials(PyObject* self, PyObject* arg) {
4 ✔
939
    std::vector<std::string> owned;
4 ✔
940
    if (!py::parse_bytes_seq(arg, "merge_partials expects a sequence", owned))
4 !
941
        return nullptr;
×
942
    std::vector<std::string_view> parts(owned.begin(), owned.end());
4 !
943
    DataFrame out;
4 ✔
944
    if (!run_blocking([&] { out = tv_of(self).merge_partials(parts); }))
8 !
945
        return nullptr;
×
946
    return py::wrap_dataframe(std::move(out));
4 !
947
}
4 ✔
948

949
PyObject* tv_materialize_partials(PyObject* self, PyObject* args,
1 ✔
950
                                  PyObject* kwds) {
951
    PyObject* arg = nullptr;
1 ✔
952
    PyObject* runtime_arg = nullptr;
1 ✔
953
    static const char* kwlist[] = {"partials", "runtime", nullptr};
954
    if (!PyArg_ParseTupleAndKeywords(
1 !
955
            args, kwds, "O|O", const_cast<char**>(kwlist), &arg, &runtime_arg))
956
        return nullptr;
×
957
    std::vector<std::string> owned;
1 ✔
958
    if (!py::parse_bytes_seq(arg, "materialize_partials expects a sequence",
1 !
959
                             owned))
960
        return nullptr;
×
961
    std::vector<std::string_view> parts(owned.begin(), owned.end());
1 !
962
    std::shared_ptr<dftracer::utils::Runtime> rt =
963
        runtime_from_arg(runtime_arg);
1 !
964
    if (!rt) return nullptr;
1 !
965
    if (!run_blocking(
1 !
966
            [&] { rt->submit(tv_of(self).materialize_partials(parts)).get(); }))
2 !
967
        return nullptr;
1 ✔
968
    Py_RETURN_NONE;
×
969
}
1 ✔
970

971
PyObject* tv_reconstruct_if_cached(PyObject* self, PyObject*) {
4 ✔
972
    std::optional<DataFrame> out;
4 ✔
973
    if (!run_blocking([&] { out = tv_of(self).reconstruct_if_cached(); }))
8 !
974
        return nullptr;
1 ✔
975
    if (!out) Py_RETURN_NONE;
3 ✔
976
    return py::wrap_dataframe(std::move(*out));
1 !
977
}
4 ✔
978

979
PyObject* tv_mv_source(PyObject* self, PyObject*) {
3 ✔
980
    std::vector<std::string> out;
3 ✔
981
    if (!run_blocking([&] { out = tv_of(self).mv_source(); })) return nullptr;
6 !
982
    return str_list_from(out);
3 !
983
}
3 ✔
984

985
PyObject* tv_materialize_dir(PyObject* self, PyObject*) {
×
986
    std::string out;
×
987
    if (!run_blocking([&] { out = tv_of(self).materialize_dir(); }))
×
988
        return nullptr;
×
989
    return PyUnicode_FromStringAndSize(out.data(),
×
990
                                       static_cast<Py_ssize_t>(out.size()));
×
991
}
×
992

993
PyObject* tv_register_materialized(PyObject* self, PyObject* arg) {
×
994
    const char* dir = as_utf8(arg);
×
995
    if (!dir) return nullptr;
×
996
    const std::string d(dir);
×
997
    if (!run_blocking([&] { tv_of(self).register_materialized(d); }))
×
998
        return nullptr;
×
999
    Py_RETURN_NONE;
×
1000
}
×
1001

1002
PyObject* tv_compare(PyObject* self, PyObject* arg) {
5 ✔
1003
    if (!PyObject_TypeCheck(arg, &TraceViewerType)) {
5 !
1004
        PyErr_SetString(PyExc_TypeError, "compare() needs a _TraceViewer");
×
1005
        return nullptr;
×
1006
    }
1007
    return guarded(
10 !
1008
        [&] { return py::wrap_lazyframe(tv_of(self).compare(tv_of(arg))); });
10 !
1009
}
1010

1011
// A branch that folds `host`'s plugin set over the scan and leaves the named
1012
// results in the host, where plugin_results() reads them after the collect.
1013
PyObject* tv_plugins(PyObject* self, PyObject* host) {
7 ✔
1014
    if (!PyObject_TypeCheck(host, &PluginHostType)) {
7 !
1015
        PyErr_SetString(PyExc_TypeError, "plugins() needs a Plugins instance");
×
1016
        return nullptr;
×
1017
    }
1018
    const dftracer::utils::plugins::Plugins* set =
1019
        py::plugin_host_plugins(host);
7 !
1020
    if (!set) return nullptr;
7 !
1021
    dftracer::utils::plugins::NamedResultRegistry* results =
1022
        py::plugin_host_results(host);
7 !
1023
    if (!results) return nullptr;
7 !
1024
    Py_INCREF(host);
1025
    std::shared_ptr<PyObject> keep(host, [](PyObject* p) {
7 ✔
1026
        PyGILState_STATE g = PyGILState_Ensure();
7 ✔
1027
        Py_DECREF(p);
1028
        PyGILState_Release(g);
7 ✔
1029
    });
7 !
1030
    views::SessionBranch attach = [set, results, keep](views::ViewSession& s) {
14 ✔
1031
        views::Deferred<dftracer::utils::plugins::PluginRun> h = set->attach(s);
7 !
1032
        return std::function<void(const ExportStats&)>(
1033
            [h, results, keep](const ExportStats&) mutable {
21 ✔
1034
                *results = std::move(h.get().results);
7 ✔
1035
            });
14 !
1036
    };
14 !
1037
    return guarded([&] {
7 !
1038
        return py::wrap_lazyframe(tv_of(self).branch(std::move(attach)));
7 !
1039
    });
7 ✔
1040
}
7 ✔
1041

1042
PyObject* merge_flamegraph_partials_py(PyObject*, PyObject* arg) {
2 ✔
1043
    std::vector<std::string> owned;
2 ✔
1044
    if (!py::parse_bytes_seq(
2 !
1045
            arg, "merge_flamegraph_partials expects a sequence", owned))
1046
        return nullptr;
×
1047
    std::vector<std::string_view> parts(owned.begin(), owned.end());
2 !
1048
    return guarded([&] {
2 !
1049
        return py::wrap_dataframe(View::merge_flamegraph_partials(parts));
2 !
1050
    });
2 ✔
1051
}
2 ✔
1052

1053
PyObject* plugin_results_py(PyObject*, PyObject* host) {
7 ✔
1054
    if (!PyObject_TypeCheck(host, &PluginHostType)) {
7 !
1055
        PyErr_SetString(PyExc_TypeError,
×
1056
                        "plugin_results() needs a Plugins instance");
1057
        return nullptr;
×
1058
    }
1059
    return py::plugin_host_results_dict(host);
7 ✔
1060
}
1061

1062
PyMethodDef tv_methods[] = {
1063
    {"lazy", tv_lazy, METH_NOARGS, "The plan as a _LazyFrame."},
1064
    {"with_lazy", tv_with_lazy, METH_O,
1065
     "This scan with `plan` (a _LazyFrame over it) as its plan."},
1066
    {"filter", tv_filter, METH_O, "Keep events matching a duql predicate."},
1067
    {"duql", tv_duql, METH_VARARGS,
1068
     "duql(text, params) -> the duql pipeline over this view."},
1069
    {"explain_duql", tv_explain_duql, METH_VARARGS,
1070
     "explain_duql(text, params) -> the pipeline's plan, one step per line."},
1071
    {"select", tv_select, METH_O,
1072
     "Fields the scan reads (raw events), or a projection of the plan."},
1073
    {"phase", tv_phase, METH_O,
1074
     "Select 'events', 'counters', 'aggregated', 'metadata', or 'any'."},
1075
    {"time_range", tv_time_range, METH_VARARGS,
1076
     "Restrict to a [begin, end) timestamp window."},
1077
    {"time_bucket", DFTU_PYCFUNCTION(tv_time_bucket),
1078
     METH_VARARGS | METH_KEYWORDS,
1079
     "time_bucket(interval_us, normalize_to=None); normalize_to is an int "
1080
     "origin or 'min'."},
1081
    {"resolution", tv_resolution, METH_O,
1082
     "Grid in microseconds the occupancy aggregates snap to; 0 is exact."},
1083
    {"time_scale", tv_time_scale, METH_O, "Multiply ts/dur by this ratio."},
1084
    {"time_unit", tv_time_unit, METH_O,
1085
     "Normalize ts/dur to ns/us/ms/sec from the trace's own unit."},
1086
    {"group_by", tv_group_by, METH_VARARGS, "Trace group keys."},
1087
    {"agg", tv_agg, METH_VARARGS, "Trace aggregate specs."},
1088
    {"agg_numeric_args", tv_agg_numeric_args, METH_VARARGS,
1089
     "Aggregate every discovered numeric arg."},
1090
    {"record_schema", tv_record_schema, METH_O,
1091
     "Read the files as the registered record schema `id`."},
1092
    {"rollup_root", tv_rollup_root, METH_O, "Rollup root directory."},
1093
    {"views_root", tv_views_root, METH_O, "Materialized-view root directory."},
1094
    {"memory_budget", tv_memory_budget, METH_O, "Spill budget in bytes."},
1095
    {"columns", tv_columns, METH_NOARGS,
1096
     "Columns discoverable from the index (no scan)."},
1097
    {"schema_tree", tv_schema_tree, METH_NOARGS,
1098
     "The index's paths with types, counts and declared fields, as JSON."},
1099
    {"column_info", tv_column_info, METH_NOARGS,
1100
     "Index columns mapped to their type name (no scan)."},
1101
    {"time_metric", tv_time_metric, METH_NOARGS, "The trace's time unit."},
1102
    {"aggregates", tv_aggregates, METH_NOARGS,
1103
     "True when the plan absorbs into an aggregating scan."},
1104
    {"filters_events", tv_filters_events, METH_NOARGS,
1105
     "True while a filter still selects raw events (reads no index)."},
1106
    {"call_tree", DFTU_PYCFUNCTION(tv_call_tree), METH_VARARGS | METH_KEYWORDS,
1107
     "Plan of the events plus level/parent_id."},
1108
    {"flamegraph", DFTU_PYCFUNCTION(tv_flamegraph),
1109
     METH_VARARGS | METH_KEYWORDS, "Plan of the folded node frame."},
1110
    {"containment", DFTU_PYCFUNCTION(tv_containment),
1111
     METH_VARARGS | METH_KEYWORDS,
1112
     "(call_tree plan, flamegraph plan) sharing one buffered fold."},
1113
    {"flamegraph_partial", DFTU_PYCFUNCTION(tv_flamegraph_partial),
1114
     METH_VARARGS | METH_KEYWORDS, "Plan of a one-row 'partial' frame."},
1115
    {"aggregate_partial", tv_aggregate_partial, METH_NOARGS,
1116
     "Plan of a one-row 'partial' frame."},
1117
    {"sink_json", tv_sink_json, METH_O,
1118
     "Plan writing the selected events to `path`; yields one stats row."},
1119
    {"typed", DFTU_PYCFUNCTION(tv_typed), METH_VARARGS | METH_KEYWORDS,
1120
     "The aggregation index's record families (runs now)."},
1121
    {"materialize", DFTU_PYCFUNCTION(tv_materialize),
1122
     METH_VARARGS | METH_KEYWORDS, "Persist this query (runs now)."},
1123
    {"export_trace", DFTU_PYCFUNCTION(tv_export_trace),
1124
     METH_VARARGS | METH_KEYWORDS, "Write a trace file (runs now)."},
1125
    {"merge_partials", tv_merge_partials, METH_O,
1126
     "Merge aggregate partials with this aggregation."},
1127
    {"materialize_partials", DFTU_PYCFUNCTION(tv_materialize_partials),
1128
     METH_VARARGS | METH_KEYWORDS, "Write the rollup from partials."},
1129
    {"reconstruct_if_cached", tv_reconstruct_if_cached, METH_NOARGS,
1130
     "The rollup as a DataFrame, or None on a miss."},
1131
    {"mv_source", tv_mv_source, METH_NOARGS,
1132
     "Materialized-view files that would serve this query."},
1133
    {"materialize_dir", tv_materialize_dir, METH_NOARGS,
1134
     "Create and return the shared materialized-view directory."},
1135
    {"register_materialized", tv_register_materialized, METH_O,
1136
     "Write the materialized-view manifest at `dir`."},
1137
    {"compare", tv_compare, METH_O,
1138
     "Plan comparing this aggregation against another viewer's events."},
1139
    {"plugins", tv_plugins, METH_O,
1140
     "Plan folding a Plugins set over the scan."},
1141
    {nullptr, nullptr, 0, nullptr}};
1142

1143
PyObject* duql_load_path_py(PyObject*, PyObject* arg) {
2 ✔
1144
    const char* path = as_utf8(arg);
2 !
1145
    if (!path) return nullptr;
2 !
1146
    return guarded([&]() -> PyObject* {
4 !
1147
        dftracer::utils::duql::load_macros(path);
3 !
1148
        Py_RETURN_NONE;
1 ✔
1149
    });
2 ✔
1150
}
1151

1152
PyObject* duql_canonical_py(PyObject*, PyObject* arg) {
176 ✔
1153
    const char* text = as_utf8(arg);
176 !
1154
    if (!text) return nullptr;
176 !
1155
    return guarded([&]() -> PyObject* {
352 !
1156
        auto program = dftracer::utils::duql::syntax::parse(text);
176 !
1157
        if (!program) throw std::invalid_argument(program.error().format());
176 !
1158
        const std::string out =
1159
            dftracer::utils::duql::syntax::to_text(*program);
175 !
1160
        return PyUnicode_FromStringAndSize(out.data(),
175 !
1161
                                           static_cast<Py_ssize_t>(out.size()));
525 ✔
1162
    });
352 ✔
1163
}
1164

1165
PyMethodDef module_methods[] = {
1166
    {"merge_flamegraph_partials", merge_flamegraph_partials_py, METH_O,
1167
     "merge_flamegraph_partials(partials) -> node DataFrame (no scan)."},
1168
    {"plugin_results", plugin_results_py, METH_O,
1169
     "plugin_results(plugins) -> {name: result} of its last run."},
1170
    {"duql_load_path", duql_load_path_py, METH_O,
1171
     "duql_load_path(path): load the macros of a .duql file or directory."},
1172
    {"duql_canonical", duql_canonical_py, METH_O,
1173
     "duql_canonical(text) -> the canonical duql text of `text`."},
1174
    {nullptr, nullptr, 0, nullptr}};
1175

1176
}  // namespace
1177

1178
PyTypeObject TraceViewerType = [] {
7 ✔
1179
    PyTypeObject t{PyVarObject_HEAD_INIT(nullptr, 0)};
7 ✔
1180
    t.tp_name = "dftracer_utils_ext._TraceViewer";
7 ✔
1181
    t.tp_basicsize = sizeof(TraceViewerObject);
7 ✔
1182
    t.tp_dealloc = reinterpret_cast<destructor>(tv_dealloc);
7 ✔
1183
    t.tp_flags = Py_TPFLAGS_DEFAULT;
7 ✔
1184
    t.tp_doc = "A trace scan and the plan over it.";
7 ✔
1185
    t.tp_methods = tv_methods;
7 ✔
1186
    t.tp_init = reinterpret_cast<initproc>(tv_init);
7 ✔
1187
    t.tp_new = tv_new;
7 ✔
1188
    return t;
7 ✔
1189
}();
1190

1191
int dftracer::utils::python::init_trace_viewer(PyObject* m) {
7 ✔
1192
    if (register_type(m, &TraceViewerType, "_TraceViewer") < 0) return -1;
7 !
1193
    return PyModule_AddFunctions(m, module_methods);
7 ✔
1194
}
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