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

llnl-asr / dftracer-utils / 41234231155

31 Oct 2026 07:26PM UTC coverage: 63.705% (+0.02%) from 63.686%
41234231155

push

github

rayandrew
feat(trace): read gzip traces that are still being written

A trace that is still being written ends in an unfinished gzip member,
and on a parallel filesystem it can also have a hole where a member has
not landed yet. Tools that watch a running application need to read
such a file, and dftracer-utils had no reader for it.

Add trace::views::LiveView. It walks each file member by member with
zlib, checks each CRC, and stops at the first unfinished tail or hole.
The verified bytes are appended to a snapshot file, and refresh()
returns a normal View over the snapshots, so every view operation works
on them. A later refresh() reads only what follows the verified bytes,
picks up new files in a directory, and drops the rows of a file that
was replaced. The work is in C++ so that C++ and Python read the same
way; LiveTraceViewer in Python is a thin adaptor over a new
_LiveTraceViewer binding.

Add C++ tests for tails, holes, corrupt members, replaced files and
directory rescans, and Python tests for the same cases plus
TraceViewer parity and record_schema across a refresh.

128667 of 249563 branches covered (51.56%)

Branch coverage included in aggregate %.

323 of 339 new or added lines in 3 files covered. (95.28%)

17 existing lines in 14 files now uncovered.

107420 of 121033 relevant lines covered (88.75%)

3373301.21 hits per line

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

63.73
/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/live_view.h>
29
#include <dftracer/utils/trace/views/view.h>
30
#include <dftracer/utils/trace/views/view_source.h>
31

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

44
namespace {
45

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

57
View& tv_of(PyObject* self) {
4,906 ✔
58
    return *reinterpret_cast<TraceViewerObject*>(self)->tv;
4,906 ✔
59
}
60

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

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

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

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

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

135
class FileSink : public views::ExportSink {
136
   public:
137
    explicit FileSink(FILE* f) : f_(f) {}
60 ✔
138
    ~FileSink() override {
62 ✔
139
        if (f_) std::fclose(f_);
40 !
140
    }
62 ✔
141
    void write(std::string_view data) override {
10,268 ✔
142
        std::fwrite(data.data(), 1, data.size(), f_);
10,268 ✔
143
    }
10,268 ✔
144
    void flush() override { std::fflush(f_); }
38 ✔
145

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

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

189
// name | cat | pid | tid | fhash | hhash | io_cat | acc_pat | rank |
190
// file_path | file_name | host_name | arg:<key> | any other field, each
191
// optionally wrapped in a transform call.
192
GroupKey parse_group_key(const std::string& s) {
500 ✔
193
    std::string t = s;
500 !
194
    GroupKey::Transform tf = GroupKey::Transform::None;
500 ✔
195
    std::vector<std::string> targs;
500 ✔
196
    std::string inner;
500 ✔
197
    if (split_transform(t, tf, targs, inner)) t = inner;
500 !
198
    GroupKey out;
500 ✔
199
    if (t == "name")
500 ✔
200
        out = GroupKey::name();
102 !
201
    else if (t == "cat")
398 ✔
202
        out = GroupKey::cat();
214 !
203
    else if (t == "pid")
184 ✔
204
        out = GroupKey::pid();
40 !
205
    else if (t == "tid")
144 ✔
206
        out = GroupKey::tid();
18 !
207
    else if (t == "fhash")
126 ✔
208
        out = GroupKey::fhash();
14 !
209
    else if (t == "hhash")
112 ✔
210
        out = GroupKey::hhash();
12 !
211
    else if (t == "io_cat")
100 ✔
212
        out = GroupKey::io_cat();
18 !
213
    else if (t == "acc_pat")
82 !
214
        out = GroupKey::acc_pat();
×
215
    else if (t == "file_path")
82 ✔
216
        out = GroupKey::file_path();
26 !
217
    else if (t == "file_name")
56 ✔
218
        out = GroupKey::file_name();
4 !
219
    else if (t == "host_name")
52 ✔
220
        out = GroupKey::host_name();
12 !
221
    else if (t == "rank")
40 ✔
222
        out = GroupKey::rank();
4 !
223
    else if (t.rfind("arg:", 0) == 0)
36 !
224
        out = GroupKey::of_arg(t.substr(4));
×
225
    else
226
        out = GroupKey::field(t);
36 !
227
    out.transform = tf;
500 ✔
228
    out.transform_args = std::move(targs);
500 ✔
229
    return out;
750 ✔
230
}
500 !
231

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

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

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

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

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

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

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

397
PyObject* tv_lazy(PyObject* self, PyObject*) {
2,698 ✔
398
    return guarded(
4,047 !
399
        [&] { return py::wrap_lazyframe(LazyFrame(tv_of(self).lazy())); });
6,745 !
400
}
401

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1177
// -- _LiveTraceViewer -------------------------------------------------------
1178

1179
views::LiveView& live_of(PyObject* self) {
80 ✔
1180
    return *reinterpret_cast<LiveTraceViewerObject*>(self)->live;
80 ✔
1181
}
1182

1183
PyObject* ltv_new(PyTypeObject* type, PyObject*, PyObject*) {
42 ✔
1184
    auto* self =
21 ✔
1185
        reinterpret_cast<LiveTraceViewerObject*>(type->tp_alloc(type, 0));
42 ✔
1186
    if (self) self->live = nullptr;
42 ✔
1187
    return reinterpret_cast<PyObject*>(self);
42 ✔
1188
}
1189

1190
void ltv_dealloc(LiveTraceViewerObject* self) {
42 ✔
1191
    delete self->live;
42 ✔
1192
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
42 ✔
1193
}
42 ✔
1194

1195
int ltv_init(LiveTraceViewerObject* self, PyObject* args, PyObject* kwds) {
42 ✔
1196
    static const char* kwlist[] = {"files", "index_path", "snapshot_dir",
1197
                                   nullptr};
1198
    PyObject* files = nullptr;
42 ✔
1199
    PyObject* index_obj = nullptr;
42 ✔
1200
    PyObject* snapshot_obj = nullptr;
42 ✔
1201
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO",
42 !
1202
                                     const_cast<char**>(kwlist), &files,
1203
                                     &index_obj, &snapshot_obj))
NEW
1204
        return -1;
×
1205
    std::vector<std::string> paths;
42 ✔
1206
    if (!py::parse_string_seq(files, "files must be a sequence of paths",
42 !
1207
                              paths))
NEW
1208
        return -1;
×
1209
    std::string index_dir;
42 ✔
1210
    std::string snapshot_dir;
42 ✔
1211
    for (auto [obj, out] : {std::pair{index_obj, &index_dir},
189 ✔
1212
                            std::pair{snapshot_obj, &snapshot_dir}}) {
105 ✔
1213
        if (!obj || obj == Py_None) continue;
84 !
1214
        const char* s = as_utf8(obj);
6 !
1215
        if (!s) return -1;
6 !
1216
        *out = s;
6 !
1217
    }
1218
    views::LiveView* live = nullptr;
42 ✔
1219
    if (!run_blocking([&] {
63 !
1220
            live =
63 !
1221
                new views::LiveView(std::move(paths), index_dir, snapshot_dir);
63 !
1222
        }))
42 ✔
NEW
1223
        return -1;
×
1224
    delete self->live;
42 !
1225
    self->live = live;
42 ✔
1226
    return 0;
42 ✔
1227
}
42 ✔
1228

1229
PyObject* ltv_refresh(PyObject* self, PyObject*) {
58 ✔
1230
    View tv;
58 !
1231
    if (!run_blocking([&] { tv = live_of(self).refresh(); })) return nullptr;
116 !
1232
    return guarded([&] { return make_viewer(std::move(tv)); });
112 !
1233
}
58 ✔
1234

1235
PyObject* ltv_verified_bytes(PyObject* self, PyObject*) {
6 ✔
1236
    return PyLong_FromUnsignedLongLong(live_of(self).verified_bytes());
6 ✔
1237
}
1238

1239
PyObject* ltv_skipped_tail_bytes(PyObject* self, PyObject*) {
6 ✔
1240
    return PyLong_FromUnsignedLongLong(live_of(self).skipped_tail_bytes());
6 ✔
1241
}
1242

1243
PyObject* ltv_holes(PyObject* self, PyObject*) {
10 ✔
1244
    const std::vector<views::LiveHole> holes = live_of(self).holes();
10 !
1245
    PyObject* out = PyList_New(static_cast<Py_ssize_t>(holes.size()));
10 !
1246
    if (!out) return nullptr;
10 ✔
1247
    for (std::size_t i = 0; i < holes.size(); ++i) {
14 ✔
1248
        PyObject* t =
2 ✔
1249
            Py_BuildValue("(sKK)", holes[i].path.c_str(),
6 !
1250
                          static_cast<unsigned long long>(holes[i].offset),
4 ✔
1251
                          static_cast<unsigned long long>(holes[i].length));
4 ✔
1252
        if (!t) {
4 !
1253
            Py_DECREF(out);
×
NEW
1254
            return nullptr;
×
1255
        }
1256
        PyList_SET_ITEM(out, static_cast<Py_ssize_t>(i), t);
4 !
1257
    }
2 ✔
1258
    return out;
10 ✔
1259
}
10 ✔
1260

1261
PyMethodDef ltv_methods[] = {
1262
    {"refresh", ltv_refresh, METH_NOARGS,
1263
     "Walk the files again; a _TraceViewer of what is whole now."},
1264
    {"verified_bytes", ltv_verified_bytes, METH_NOARGS,
1265
     "Bytes of whole members being read."},
1266
    {"skipped_tail_bytes", ltv_skipped_tail_bytes, METH_NOARGS,
1267
     "Bytes from each file's stop point to its end."},
1268
    {"holes", ltv_holes, METH_NOARGS,
1269
     "(path, offset, length) of the hole that cut each file short."},
1270
    {nullptr, nullptr, 0, nullptr}};
1271

1272
}  // namespace
1273

1274
PyTypeObject LiveTraceViewerType = [] {
7 ✔
1275
    PyTypeObject t{PyVarObject_HEAD_INIT(nullptr, 0)};
7 ✔
1276
    t.tp_name = "dftracer_utils_ext._LiveTraceViewer";
7 ✔
1277
    t.tp_basicsize = sizeof(LiveTraceViewerObject);
7 ✔
1278
    t.tp_dealloc = reinterpret_cast<destructor>(ltv_dealloc);
7 ✔
1279
    t.tp_flags = Py_TPFLAGS_DEFAULT;
7 ✔
1280
    t.tp_doc = "Trace files that may still be growing.";
7 ✔
1281
    t.tp_methods = ltv_methods;
7 ✔
1282
    t.tp_init = reinterpret_cast<initproc>(ltv_init);
7 ✔
1283
    t.tp_new = ltv_new;
7 ✔
1284
    return t;
7 ✔
1285
}();
1286

1287
PyTypeObject TraceViewerType = [] {
7 ✔
1288
    PyTypeObject t{PyVarObject_HEAD_INIT(nullptr, 0)};
7 ✔
1289
    t.tp_name = "dftracer_utils_ext._TraceViewer";
7 ✔
1290
    t.tp_basicsize = sizeof(TraceViewerObject);
7 ✔
1291
    t.tp_dealloc = reinterpret_cast<destructor>(tv_dealloc);
7 ✔
1292
    t.tp_flags = Py_TPFLAGS_DEFAULT;
7 ✔
1293
    t.tp_doc = "A trace scan and the plan over it.";
7 ✔
1294
    t.tp_methods = tv_methods;
7 ✔
1295
    t.tp_init = reinterpret_cast<initproc>(tv_init);
7 ✔
1296
    t.tp_new = tv_new;
7 ✔
1297
    return t;
7 ✔
1298
}();
1299

1300
int dftracer::utils::python::init_trace_viewer(PyObject* m) {
14 ✔
1301
    if (register_type(m, &TraceViewerType, "_TraceViewer") < 0) return -1;
14 ✔
1302
    if (register_type(m, &LiveTraceViewerType, "_LiveTraceViewer") < 0)
14 ✔
NEW
1303
        return -1;
×
1304
    return PyModule_AddFunctions(m, module_methods);
14 ✔
1305
}
7 ✔
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