• 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

56.9
/src/dftracer/utils/python/lazyframe.cpp
1
// A native LazyFrame exposed to Python: a deferred query over an in-memory
2
// dataframe::DataFrame. Builder methods record ops and return a new LazyFrame;
3
// nothing runs until collect(), which materializes a native _DataFrame. A
4
// filter/with_column expr's col(i) refers to the i-th column of the frame at
5
// that point, so the Python wrapper resolves names to indices against schema().
6

7
#include <dftracer/utils/core/common/config.h>  // DFTRACER_UTILS_ENABLE_ARROW
8
#include <dftracer/utils/core/common/memory_budget.h>  // NO_SPILL_BUDGET
9
#include <dftracer/utils/core/runtime.h>
10
#include <dftracer/utils/core/tasks/coro_scope.h>
11
#include <dftracer/utils/dataframe/dataframe.h>
12
#include <dftracer/utils/dataframe/expr.h>
13
#include <dftracer/utils/dataframe/lazyframe.h>
14
#include <dftracer/utils/python/columnar_eval.h>
15
#include <dftracer/utils/python/dataframe.h>
16
#include <dftracer/utils/python/lazyframe.h>
17
#include <dftracer/utils/python/py_agg_helpers.h>
18
#include <dftracer/utils/python/py_frame_op_helpers.h>
19
#include <dftracer/utils/python/py_join_helpers.h>
20
#include <dftracer/utils/python/py_list_helpers.h>
21
#include <dftracer/utils/python/py_method.h>
22
#include <dftracer/utils/python/py_runtime_mixin.h>  // run_blocking
23
#include <dftracer/utils/python/py_scalar_helpers.h>
24
#include <dftracer/utils/python/py_seq_helpers.h>
25
#include <dftracer/utils/python/py_type_helpers.h>
26
#include <dftracer/utils/python/series.h>
27
#include <dftracer/utils/python/streaming_iterator.h>
28

29
#include <cstdint>
30
#include <new>
31
#include <stdexcept>
32
#include <string>
33
#include <utility>
34
#include <vector>
35

36
namespace dataframe = dftracer::utils::dataframe;
37

38
namespace {
39

40
using dataframe::GroupAgg;
41
using dataframe::LazyFrame;
42
using dftracer::utils::python::aggs_from_seq;
43
using dftracer::utils::python::group_agg_from_spec;
44
using dftracer::utils::python::parse_string_seq;
45
using dftracer::utils::python::strings_from_str_or_seq;
46

47
struct LazyFrameObject {
48
    PyObject_HEAD LazyFrame lf;
49
};
50

51
PyTypeObject LazyFrameType;
52

53
LazyFrameObject* as_lazyframe(PyObject* o) {
4,019 ✔
54
    if (!PyObject_TypeCheck(o, &LazyFrameType)) {
4,019 ✔
55
        PyErr_SetString(PyExc_TypeError, "expected a LazyFrame");
1 ✔
56
        return nullptr;
1 ✔
57
    }
58
    return reinterpret_cast<LazyFrameObject*>(o);
4,018 ✔
59
}
60

61
PyObject* make_lazyframe(LazyFrame&& lf) {
3,744 ✔
62
    auto* self = reinterpret_cast<LazyFrameObject*>(
63
        LazyFrameType.tp_alloc(&LazyFrameType, 0));
3,744 ✔
64
    if (!self) return nullptr;
3,744 !
65
    new (&self->lf) LazyFrame(std::move(lf));
3,744 ✔
66
    return reinterpret_cast<PyObject*>(self);
3,744 ✔
67
}
68

69
void LazyFrame_dealloc(LazyFrameObject* self) {
3,744 ✔
70
    self->lf.~LazyFrame();
3,744 ✔
71
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
3,744 ✔
72
}
3,744 ✔
73

74
// Wrap a builder call that returns a LazyFrame, turning C++ exceptions into
75
// Python errors.
76
template <class Fn>
77
PyObject* run_lazy_op(Fn&& fn) {
1,395 ✔
78
    try {
79
        return make_lazyframe(fn());
1,395 !
80
    } catch (const std::exception& e) {
6 !
81
        PyErr_SetString(PyExc_ValueError, e.what());
6 !
82
        return nullptr;
6 ✔
83
    }
84
}
85

86
// filter(ast) -> LazyFrame. `ast` is the columnar.py post-order Expr AST; the
87
// engine rebuilds a dataframe::Expr referencing columns by position.
88
PyObject* LazyFrame_filter(PyObject* self, PyObject* ast) {
325 ✔
89
    LazyFrameObject* b = as_lazyframe(self);
325 !
90
    if (!b) return nullptr;
325 !
91
    dataframe::Expr pred;
325 ✔
92
    if (!dftracer::utils::python::build_expr_from_ast(ast, &pred))
325 !
93
        return nullptr;
×
94
    return run_lazy_op([&] { return b->lf.filter(pred); });
650 !
95
}
325 ✔
96

97
PyObject* LazyFrame_with_column(PyObject* self, PyObject* args) {
387 ✔
98
    LazyFrameObject* b = as_lazyframe(self);
387 !
99
    if (!b) return nullptr;
387 !
100
    const char* name = nullptr;
387 ✔
101
    PyObject* ast = nullptr;
387 ✔
102
    if (!PyArg_ParseTuple(args, "sO", &name, &ast)) return nullptr;
387 !
103
    dataframe::Expr e;
387 ✔
104
    if (!dftracer::utils::python::build_expr_from_ast(ast, &e)) return nullptr;
387 !
105
    return run_lazy_op([&] { return b->lf.with_column(name, e); });
774 !
106
}
387 ✔
107

108
PyObject* LazyFrame_select(PyObject* self, PyObject* names) {
197 ✔
109
    LazyFrameObject* b = as_lazyframe(self);
197 !
110
    if (!b) return nullptr;
197 !
111
    std::vector<std::string> ns;
197 ✔
112
    if (!parse_str_list(names, "names", ns)) return nullptr;
197 !
113
    return run_lazy_op([&] { return b->lf.select(std::move(ns)); });
394 !
114
}
197 ✔
115

116
PyObject* LazyFrame_rename(PyObject* self, PyObject* names) {
2 ✔
117
    LazyFrameObject* b = as_lazyframe(self);
2 !
118
    if (!b) return nullptr;
2 !
119
    std::vector<std::string> ns;
2 ✔
120
    if (!parse_str_list(names, "names", ns)) return nullptr;
2 !
121
    return run_lazy_op([&] { return b->lf.rename(std::move(ns)); });
4 !
122
}
2 ✔
123

124
PyObject* LazyFrame_drop(PyObject* self, PyObject* names) {
5 ✔
125
    LazyFrameObject* b = as_lazyframe(self);
5 !
126
    if (!b) return nullptr;
5 !
127
    std::vector<std::string> ns;
5 ✔
128
    if (!parse_str_list(names, "names", ns)) return nullptr;
5 !
129
    return run_lazy_op([&] { return b->lf.drop(std::move(ns)); });
10 !
130
}
5 ✔
131

132
PyObject* LazyFrame_rename_columns(PyObject* self, PyObject* args) {
8 ✔
133
    LazyFrameObject* b = as_lazyframe(self);
8 !
134
    if (!b) return nullptr;
8 !
135
    PyObject* from = nullptr;
8 ✔
136
    PyObject* to = nullptr;
8 ✔
137
    if (!PyArg_ParseTuple(args, "OO", &from, &to)) return nullptr;
8 !
138
    std::vector<std::string> f, t;
8 ✔
139
    if (!parse_str_list(from, "from", f) || !parse_str_list(to, "to", t))
8 !
140
        return nullptr;
×
141
    return run_lazy_op(
16 !
142
        [&] { return b->lf.rename_columns(std::move(f), std::move(t)); });
16 !
143
}
8 ✔
144

145
PyObject* LazyFrame_slice(PyObject* self, PyObject* args) {
7 ✔
146
    LazyFrameObject* b = as_lazyframe(self);
7 !
147
    if (!b) return nullptr;
7 !
148
    long long offset = 0, len = 0;
7 ✔
149
    if (!PyArg_ParseTuple(args, "LL", &offset, &len)) return nullptr;
7 !
150
    return run_lazy_op([&] { return b->lf.slice(offset, len); });
14 !
151
}
152

153
PyObject* LazyFrame_head(PyObject* self, PyObject* n) {
5 ✔
154
    LazyFrameObject* b = as_lazyframe(self);
5 !
155
    if (!b) return nullptr;
5 !
156
    long long v = PyLong_AsLongLong(n);
5 !
157
    if (v == -1 && PyErr_Occurred()) return nullptr;
5 !
158
    return run_lazy_op([&] { return b->lf.head(v); });
10 !
159
}
160

161
PyObject* LazyFrame_take(PyObject* self, PyObject* seq) {
4 ✔
162
    LazyFrameObject* b = as_lazyframe(self);
4 !
163
    if (!b) return nullptr;
4 !
164
    std::vector<std::int64_t> idx;
4 ✔
165
    if (!dftracer::utils::python::parse_int_seq(
4 !
166
            seq, "take() expects a sequence of ints", idx))
167
        return nullptr;
×
168
    return run_lazy_op([&] { return b->lf.take(std::move(idx)); });
8 !
169
}
4 ✔
170

171
PyObject* LazyFrame_filter_mask(PyObject* self, PyObject* mask) {
4 ✔
172
    LazyFrameObject* b = as_lazyframe(self);
4 !
173
    if (!b) return nullptr;
4 !
174
    const dataframe::Series* m =
175
        dftracer::utils::python::unwrap_vec_column(mask);
4 !
176
    if (!m) {
4 !
177
        PyErr_SetString(PyExc_TypeError,
×
178
                        "filter_mask() expects a Series boolean mask");
179
        return nullptr;
×
180
    }
181
    return run_lazy_op([&] { return b->lf.filter_mask(m->share()); });
12 !
182
}
183

184
PyObject* LazyFrame_reverse(PyObject* self, PyObject*) {
2 ✔
185
    LazyFrameObject* b = as_lazyframe(self);
2 !
186
    if (!b) return nullptr;
2 !
187
    return run_lazy_op([&] { return b->lf.reverse(); });
4 !
188
}
189

190
PyObject* LazyFrame_sort_by_multi(PyObject* self, PyObject* args,
40 ✔
191
                                  PyObject* kwds) {
192
    LazyFrameObject* b = as_lazyframe(self);
40 !
193
    if (!b) return nullptr;
40 !
194
    PyObject* names_obj = nullptr;
40 ✔
195
    PyObject* descending_obj = nullptr;
40 ✔
196
    static const char* kw[] = {"names", "descending", nullptr};
197
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", const_cast<char**>(kw),
40 !
198
                                     &names_obj, &descending_obj))
199
        return nullptr;
×
200
    std::vector<std::string> names;
40 ✔
201
    if (!strings_from_str_or_seq(names_obj, names)) return nullptr;
40 !
202
    std::vector<bool> descending;
40 ✔
203
    if (!descending_obj) {
40 !
204
        descending.push_back(false);
×
205
    } else if (PyBool_Check(descending_obj) || PyLong_Check(descending_obj)) {
40 !
206
        descending.push_back(PyObject_IsTrue(descending_obj) != 0);
31 !
207
    } else {
208
        PyObject* dseq = PySequence_Fast(
9 !
209
            descending_obj, "descending must be a bool or a sequence of bool");
210
        if (!dseq) return nullptr;
9 !
211
        const Py_ssize_t n = PySequence_Fast_GET_SIZE(dseq);
9 !
212
        for (Py_ssize_t i = 0; i < n; ++i)
35 ✔
213
            descending.push_back(
26 ✔
214
                PyObject_IsTrue(PySequence_Fast_GET_ITEM(dseq, i)) != 0);
26 !
215
        Py_DECREF(dseq);
216
    }
217
    return run_lazy_op([&] {
80 !
218
        return b->lf.sort_by_multi(std::move(names), std::move(descending));
40 !
219
    });
40 ✔
220
}
40 ✔
221

222
PyObject* LazyFrame_tail(PyObject* self, PyObject* n) {
1 ✔
223
    LazyFrameObject* b = as_lazyframe(self);
1 !
224
    if (!b) return nullptr;
1 !
225
    long long v = PyLong_AsLongLong(n);
1 !
226
    if (v == -1 && PyErr_Occurred()) return nullptr;
1 !
227
    return run_lazy_op([&] { return b->lf.tail(v); });
2 !
228
}
229

230
PyObject* LazyFrame_drop_nulls(PyObject* self, PyObject*) {
×
231
    LazyFrameObject* b = as_lazyframe(self);
×
232
    if (!b) return nullptr;
×
233
    return run_lazy_op([&] { return b->lf.drop_nulls(); });
×
234
}
235

236
PyObject* LazyFrame_fill_null(PyObject* self, PyObject* value) {
×
237
    LazyFrameObject* b = as_lazyframe(self);
×
238
    if (!b) return nullptr;
×
239
    dftu_scalar s{};
×
240
    if (!py_to_scalar(value, &s)) return nullptr;
×
241
    return run_lazy_op([&] { return b->lf.fill_null(s); });
×
242
}
243

244
PyObject* LazyFrame_with_row_index(PyObject* self, PyObject* name) {
15 ✔
245
    LazyFrameObject* b = as_lazyframe(self);
15 !
246
    if (!b) return nullptr;
15 !
247
    const char* s = PyUnicode_AsUTF8(name);
15 !
248
    if (!s) return nullptr;
15 !
249
    return run_lazy_op([&] { return b->lf.with_row_index(s); });
30 !
250
}
251

252
PyObject* LazyFrame_null_count(PyObject* self, PyObject*) {
×
253
    LazyFrameObject* b = as_lazyframe(self);
×
254
    if (!b) return nullptr;
×
255
    return run_lazy_op([&] { return b->lf.null_count(); });
×
256
}
257

258
PyObject* LazyFrame_reduce(PyObject* self, PyObject* arg) {
1 ✔
259
    LazyFrameObject* b = as_lazyframe(self);
1 !
260
    if (!b) return nullptr;
1 !
261
    const char* agg = PyUnicode_AsUTF8(arg);
1 !
262
    if (!agg) return nullptr;
1 !
263
    return run_lazy_op(
2 !
264
        [&] { return b->lf.reduce(dataframe::agg_from_string(agg)); });
2 !
265
}
266

267
PyObject* LazyFrame_group_transform(PyObject* self, PyObject* args,
16 ✔
268
                                    PyObject* kwds) {
269
    LazyFrameObject* b = as_lazyframe(self);
16 !
270
    if (!b) return nullptr;
16 !
271
    dftracer::utils::python::GroupwiseArgs a;
16 ✔
272
    if (!dftracer::utils::python::parse_groupwise_args(
16 !
273
            args, kwds, strings_from_str_or_seq, a))
274
        return nullptr;
×
275
    return run_lazy_op([&] {
32 !
276
        return b->lf.group_by(a.keys).transform(
32 !
277
            static_cast<dataframe::GroupwiseOp>(a.kind), a.n,
16 ✔
278
            static_cast<dataframe::RankMethod>(a.method), a.ascending != 0);
32 !
279
    });
16 ✔
280
}
16 ✔
281

282
// reduce_specs(agg, keys) -> list[str]: the "op:column:out" specs that
283
// broadcast `agg` over every eligible non-key column of the plan's schema.
284
PyObject* LazyFrame_reduce_specs(PyObject* self, PyObject* args) {
24 ✔
285
    LazyFrameObject* b = as_lazyframe(self);
24 !
286
    if (!b) return nullptr;
24 !
287
    const char* agg = nullptr;
24 ✔
288
    PyObject* keys_obj = Py_None;
24 ✔
289
    if (!PyArg_ParseTuple(args, "s|O", &agg, &keys_obj)) return nullptr;
24 !
290
    std::vector<std::string> keys;
24 ✔
291
    if (keys_obj != Py_None && !strings_from_str_or_seq(keys_obj, keys))
24 !
292
        return nullptr;
×
293
    std::vector<std::string> specs;
24 ✔
294
    try {
295
        specs = dftracer::utils::python::reduce_spec_strings(
48 !
296
            b->lf.reduce_specs(dataframe::agg_from_string(agg), keys));
72 !
297
    } catch (const std::out_of_range& e) {
×
298
        PyErr_SetString(PyExc_KeyError, e.what());
×
299
        return nullptr;
×
300
    } catch (const std::exception& e) {
×
301
        PyErr_SetString(PyExc_ValueError, e.what());
×
302
        return nullptr;
×
303
    }
×
304
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(specs.size()));
24 !
305
    if (!list) return nullptr;
24 !
306
    for (std::size_t i = 0; i < specs.size(); ++i) {
71 ✔
307
        PyObject* s = PyUnicode_FromString(specs[i].c_str());
47 !
308
        if (!s) {
47 !
309
            Py_DECREF(list);
310
            return nullptr;
×
311
        }
312
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
47 ✔
313
    }
314
    return list;
24 ✔
315
}
24 ✔
316

317
PyObject* LazyFrame_explode(PyObject* self, PyObject* column) {
×
318
    LazyFrameObject* b = as_lazyframe(self);
×
319
    if (!b) return nullptr;
×
320
    const char* s = PyUnicode_AsUTF8(column);
×
321
    if (!s) return nullptr;
×
322
    return run_lazy_op([&] { return b->lf.explode(s); });
×
323
}
324

325
PyObject* LazyFrame_unnest(PyObject* self, PyObject* args, PyObject* kwds) {
3 ✔
326
    LazyFrameObject* b = as_lazyframe(self);
3 !
327
    if (!b) return nullptr;
3 !
328
    const char* column = nullptr;
3 ✔
329
    int keep_empty = 0;
3 ✔
330
    static const char* kw[] = {"column", "keep_empty", nullptr};
331
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p", const_cast<char**>(kw),
3 !
332
                                     &column, &keep_empty))
333
        return nullptr;
×
334
    return run_lazy_op([&] { return b->lf.unnest(column, keep_empty != 0); });
7 !
335
}
336

337
PyObject* LazyFrame_compare_agg(PyObject* self, PyObject* args) {
1 ✔
338
    LazyFrameObject* b = as_lazyframe(self);
1 !
339
    if (!b) return nullptr;
1 !
340
    PyObject* other = nullptr;
1 ✔
341
    Py_ssize_t n_key = 1;
1 ✔
342
    if (!PyArg_ParseTuple(args, "On", &other, &n_key)) return nullptr;
1 !
343
    LazyFrameObject* o = as_lazyframe(other);
1 !
344
    if (!o) return nullptr;
1 !
345
    return run_lazy_op([&] {
2 !
346
        return b->lf.compare_agg(o->lf, static_cast<std::int64_t>(n_key));
1 !
347
    });
1 ✔
348
}
349

350
// The Arrow-layer relational kernels as plan steps: window and gap_fill build
351
// the C operand bag their dftu.frame.* row takes and append it through
352
// frame_op, which copies every operand into the plan; asof and interval are
353
// LazyFrame methods.
354
PyObject* LazyFrame_window(PyObject* self, PyObject* args, PyObject* kwds) {
55 ✔
355
    LazyFrameObject* b = as_lazyframe(self);
55 !
356
    if (!b) return nullptr;
55 !
357
    static const char* kw[] = {"partition_by", "order_by", "specs", nullptr};
358
    PyObject* part = nullptr;
55 ✔
359
    PyObject* order = nullptr;
55 ✔
360
    PyObject* specs = nullptr;
55 ✔
361
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", const_cast<char**>(kw),
55 !
362
                                     &part, &order, &specs))
363
        return nullptr;
×
364
    std::vector<std::string> pcols;
55 ✔
365
    std::vector<std::string> ocols;
55 ✔
366
    if (!parse_string_seq(part, "window: partition_by must be names", pcols) ||
110 !
367
        !parse_string_seq(order, "window: order_by must be names", ocols))
55 !
368
        return nullptr;
×
369
    dftracer::utils::python::WindowSpecs parsed;
55 !
370
    if (!dftracer::utils::python::parse_window_specs(specs, parsed))
55 !
371
        return nullptr;
×
372
    std::vector<const char*> pc;
55 ✔
373
    std::vector<const char*> oc;
55 ✔
374
    for (const std::string& s : pcols) pc.push_back(s.c_str());
110 !
375
    for (const std::string& s : ocols) oc.push_back(s.c_str());
110 !
376
    dataframe::OpArgs a;
55 ✔
377
    a.strlist(1, pc.data(), static_cast<std::int32_t>(pc.size()))
55 ✔
378
        .strlist(2, oc.data(), static_cast<std::int32_t>(oc.size()))
55 ✔
379
        .winlist(3, parsed.specs);
55 ✔
380
    return run_lazy_op([&] {
55 !
381
        // A window keeps every input column and appends one per spec.
382
        std::vector<std::string> names = b->lf.schema();
55 !
383
        if (!names.empty())
55 !
384
            for (const dftu_window_spec& s : parsed.specs)
167 ✔
385
                names.emplace_back(s.out);
112 !
386
        return b->lf.frame_op("dftu.frame.window", a, {}, std::move(names));
110 !
387
    });
110 ✔
388
}
55 ✔
389

390
// column_op(column, op, column2=None, a=0, b=0, text=None): the registered
391
// column op `op` over `column` as a plan step (dftu.frame.column_op, a
392
// breaker), the column replaced in place.
393
PyObject* LazyFrame_column_op(PyObject* self, PyObject* args, PyObject* kwds) {
×
394
    LazyFrameObject* b = as_lazyframe(self);
×
395
    if (!b) return nullptr;
×
396
    static const char* kw[] = {"column", "op",   "column2", "a",
397
                               "b",      "text", nullptr};
398
    const char* column = nullptr;
×
399
    const char* op = nullptr;
×
400
    const char* column2 = nullptr;
×
401
    PyObject* a_obj = nullptr;
×
402
    PyObject* b_obj = nullptr;
×
403
    const char* text = nullptr;
×
404
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss|zOOz",
×
405
                                     const_cast<char**>(kw), &column, &op,
406
                                     &column2, &a_obj, &b_obj, &text))
407
        return nullptr;
×
408
    dftu_scalar sa{};
×
409
    dftu_scalar sb{};
×
410
    sa.kind = DFTU_SCALAR_TAG_I64;
×
411
    sb.kind = DFTU_SCALAR_TAG_I64;
×
412
    if (a_obj && a_obj != Py_None && !py_to_scalar(a_obj, &sa)) return nullptr;
×
413
    if (b_obj && b_obj != Py_None && !py_to_scalar(b_obj, &sb)) return nullptr;
×
414
    const std::string c2 = column2 ? column2 : "";
×
415
    const std::string tx = text ? text : "";
×
416
    dataframe::OpArgs a;
×
417
    a.str(1, column).str(2, op).str(3, c2).scalar(4, sa).scalar(5, sb).str(6,
×
418
                                                                           tx);
419
    return run_lazy_op([&] {
×
420
        return b->lf.frame_op("dftu.frame.column_op", a, {}, b->lf.schema());
×
421
    });
×
422
}
×
423

424
PyObject* LazyFrame_gap_fill(PyObject* self, PyObject* args, PyObject* kwds) {
4 ✔
425
    LazyFrameObject* b = as_lazyframe(self);
4 !
426
    if (!b) return nullptr;
4 !
427
    static const char* kw[] = {"partition_by", "time",  "bucket", "values",
428
                               "mode",         "start", "end",    nullptr};
429
    PyObject* part = nullptr;
4 ✔
430
    const char* time = nullptr;
4 ✔
431
    long long bucket = 0;
4 ✔
432
    PyObject* values = nullptr;
4 ✔
433
    const char* mode = nullptr;
4 ✔
434
    PyObject* start_obj = Py_None;
4 ✔
435
    PyObject* end_obj = Py_None;
4 ✔
436
    if (!PyArg_ParseTupleAndKeywords(
4 !
437
            args, kwds, "OsLOs|OO", const_cast<char**>(kw), &part, &time,
438
            &bucket, &values, &mode, &start_obj, &end_obj))
439
        return nullptr;
×
440
    dftu_gap_fill_mode m;
441
    if (!dftracer::utils::python::gap_fill_mode_from_str(mode, &m))
4 !
442
        return nullptr;
×
443
    std::vector<std::string> pcols;
4 ✔
444
    std::vector<std::string> vcols;
4 ✔
445
    if (!parse_string_seq(part, "gap_fill: partition_by must be names",
4 !
446
                          pcols) ||
8 !
447
        !parse_string_seq(values, "gap_fill: values must be names", vcols))
4 !
448
        return nullptr;
×
449
    std::vector<std::int64_t> range;
4 ✔
450
    if (start_obj != Py_None) {
4 ✔
451
        const long long s = PyLong_AsLongLong(start_obj);
1 !
452
        const long long e = PyLong_AsLongLong(end_obj);
1 !
453
        if (PyErr_Occurred()) return nullptr;
1 !
454
        range = {static_cast<std::int64_t>(s), static_cast<std::int64_t>(e)};
1 !
455
    }
456
    std::vector<const char*> pc;
4 ✔
457
    std::vector<const char*> vc;
4 ✔
458
    for (const std::string& s : pcols) pc.push_back(s.c_str());
8 !
459
    for (const std::string& s : vcols) vc.push_back(s.c_str());
8 !
460
    dataframe::OpArgs a;
4 ✔
461
    a.strlist(1, pc.data(), static_cast<std::int32_t>(pc.size()))
4 ✔
462
        .str(2, time)
4 ✔
463
        .i64(3, static_cast<std::int64_t>(bucket))
4 ✔
464
        .strlist(4, vc.data(), static_cast<std::int32_t>(vc.size()))
4 ✔
465
        .i32(5, static_cast<std::int32_t>(m))
4 ✔
466
        .i64list(6, range);
4 ✔
467
    return run_lazy_op([&] {
4 !
468
        return b->lf.frame_op("dftu.frame.gap_fill", a, {}, b->lf.schema());
4 !
469
    });
4 ✔
470
}
4 ✔
471

472
PyObject* LazyFrame_asof(PyObject* self, PyObject* args, PyObject* kwds) {
27 ✔
473
    LazyFrameObject* b = as_lazyframe(self);
27 !
474
    if (!b) return nullptr;
27 !
475
    static const char* kw[] = {"other",     "on",        "by",
476
                               "direction", "tolerance", nullptr};
477
    PyObject* other = nullptr;
27 ✔
478
    const char* on = nullptr;
27 ✔
479
    PyObject* by = nullptr;
27 ✔
480
    const char* direction = nullptr;
27 ✔
481
    PyObject* tol_obj = Py_None;
27 ✔
482
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OsOsO",
27 !
483
                                     const_cast<char**>(kw), &other, &on, &by,
484
                                     &direction, &tol_obj))
485
        return nullptr;
×
486
    LazyFrameObject* o = as_lazyframe(other);
27 !
487
    if (!o) return nullptr;
27 !
488
    dftu_asof_direction dir;
489
    if (!dftracer::utils::python::asof_direction_from_str(direction, &dir))
27 !
490
        return nullptr;
1 ✔
491
    std::vector<std::string> equi;
26 ✔
492
    if (!parse_string_seq(by, "asof: by must be names", equi)) return nullptr;
26 !
493
    std::optional<double> tol;
26 ✔
494
    if (tol_obj != Py_None) {
26 ✔
495
        const double t = PyFloat_AsDouble(tol_obj);
14 !
496
        if (PyErr_Occurred()) return nullptr;
15 !
497
        if (!(t >= 0)) {
14 ✔
498
            PyErr_SetString(PyExc_ValueError,
1 !
499
                            "asof: tolerance must not be negative");
500
            return nullptr;
1 ✔
501
        }
502
        tol = t;
13 ✔
503
    }
504
    return run_lazy_op([&] {
50 !
505
        return b->lf.asof(o->lf, on, std::move(equi),
75 ✔
506
                          static_cast<dataframe::AsofDirection>(dir), tol);
28 !
507
    });
25 ✔
508
}
26 ✔
509

510
PyObject* LazyFrame_interval(PyObject* self, PyObject* args, PyObject* kwds) {
7 ✔
511
    LazyFrameObject* b = as_lazyframe(self);
7 !
512
    if (!b) return nullptr;
7 !
513
    static const char* kw[] = {"other", "point", "lo",   "hi",
514
                               "by",    "outer", nullptr};
515
    PyObject* other = nullptr;
7 ✔
516
    const char* point = nullptr;
7 ✔
517
    const char* lo = nullptr;
7 ✔
518
    const char* hi = nullptr;
7 ✔
519
    PyObject* by = nullptr;
7 ✔
520
    int outer = 0;
7 ✔
521
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OsssOp",
7 !
522
                                     const_cast<char**>(kw), &other, &point,
523
                                     &lo, &hi, &by, &outer))
524
        return nullptr;
×
525
    LazyFrameObject* o = as_lazyframe(other);
7 !
526
    if (!o) return nullptr;
7 !
527
    std::vector<std::string> equi;
7 ✔
528
    if (!parse_string_seq(by, "interval: by must be names", equi))
7 !
529
        return nullptr;
×
530
    return run_lazy_op([&] {
14 !
531
        return b->lf.interval(o->lf, point, lo, hi, std::move(equi),
35 ✔
532
                              outer != 0);
14 !
533
    });
7 ✔
534
}
7 ✔
535

536
// unpivot(id_vars, value_vars); melt is the same call.
537
PyObject* LazyFrame_unpivot(PyObject* self, PyObject* args) {
×
538
    LazyFrameObject* b = as_lazyframe(self);
×
539
    if (!b) return nullptr;
×
540
    PyObject* id_obj = nullptr;
×
541
    PyObject* val_obj = nullptr;
×
542
    if (!PyArg_ParseTuple(args, "OO", &id_obj, &val_obj)) return nullptr;
×
543
    std::vector<std::string> id_vars, value_vars;
×
544
    if (!parse_str_list(id_obj, "id_vars", id_vars) ||
×
545
        !parse_str_list(val_obj, "value_vars", value_vars))
×
546
        return nullptr;
×
547
    return run_lazy_op([&] {
×
548
        return b->lf.unpivot(std::move(id_vars), std::move(value_vars));
×
549
    });
×
550
}
×
551

552
PyObject* LazyFrame_topk(PyObject* self, PyObject* args, PyObject* kwds) {
4 ✔
553
    LazyFrameObject* b = as_lazyframe(self);
4 !
554
    if (!b) return nullptr;
4 !
555
    const char* name = nullptr;
4 ✔
556
    long long k = 0;
4 ✔
557
    int largest = 1;
4 ✔
558
    static const char* kw[] = {"name", "k", "largest", nullptr};
559
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "sL|p", const_cast<char**>(kw),
4 !
560
                                     &name, &k, &largest))
561
        return nullptr;
×
562
    return run_lazy_op([&] { return b->lf.topk(name, k, largest != 0); });
8 !
563
}
564

565
// group_by(key, aggs): key is a column name or a sequence of names (composite
566
// key); aggs is a sequence of "op[:column]" string specs.
567
PyObject* LazyFrame_group_by(PyObject* self, PyObject* args) {
90 ✔
568
    LazyFrameObject* b = as_lazyframe(self);
90 !
569
    if (!b) return nullptr;
90 !
570
    PyObject* key_obj = nullptr;
90 ✔
571
    PyObject* aggs_obj = nullptr;
90 ✔
572
    if (!PyArg_ParseTuple(args, "OO", &key_obj, &aggs_obj)) return nullptr;
90 !
573
    std::vector<std::string> keys;
90 ✔
574
    if (!strings_from_str_or_seq(key_obj, keys)) return nullptr;
90 !
575
    std::vector<GroupAgg> aggs;
90 ✔
576
    if (!aggs_from_seq(aggs_obj, aggs)) return nullptr;
90 !
577
    return run_lazy_op(
180 !
578
        [&] { return b->lf.group_by(std::move(keys), std::move(aggs)); });
180 !
579
}
90 ✔
580

581
PyObject* LazyFrame_sort_by(PyObject* self, PyObject* args, PyObject* kwds) {
28 ✔
582
    LazyFrameObject* b = as_lazyframe(self);
28 !
583
    if (!b) return nullptr;
28 !
584
    const char* name = nullptr;
28 ✔
585
    int descending = 0;
28 ✔
586
    static const char* kw[] = {"name", "descending", nullptr};
587
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p", const_cast<char**>(kw),
28 !
588
                                     &name, &descending))
589
        return nullptr;
×
590
    return run_lazy_op([&] { return b->lf.sort_by(name, descending != 0); });
56 !
591
}
592

593
PyObject* LazyFrame_join(PyObject* self, PyObject* args, PyObject* kwds) {
82 ✔
594
    LazyFrameObject* b = as_lazyframe(self);
82 !
595
    if (!b) return nullptr;
82 !
596
    PyObject* other = nullptr;
82 ✔
597
    PyObject* on = nullptr;
82 ✔
598
    const char* how = "inner";
82 ✔
599
    PyObject* left_on = nullptr;
82 ✔
600
    PyObject* right_on = nullptr;
82 ✔
601
    const char* suffix = "_right";
82 ✔
602
    int nulls_equal = 0;
82 ✔
603
    static const char* kw[] = {"other",    "on",     "how",         "left_on",
604
                               "right_on", "suffix", "nulls_equal", nullptr};
605
    if (!PyArg_ParseTupleAndKeywords(
82 !
606
            args, kwds, "O|OsOOsp", const_cast<char**>(kw), &other, &on, &how,
607
            &left_on, &right_on, &suffix, &nulls_equal))
608
        return nullptr;
×
609
    LazyFrameObject* o = as_lazyframe(other);
82 !
610
    if (!o) return nullptr;
82 !
611
    dataframe::JoinHow jh;
612
    if (!dftracer::utils::python::join_how_from_str(how, jh)) return nullptr;
82 !
613
    std::vector<std::string> l;
81 ✔
614
    std::vector<std::string> r;
81 ✔
615
    if (!dftracer::utils::python::join_keys_from_objs(on, left_on, right_on, jh,
81 !
616
                                                      l, r))
617
        return nullptr;
×
618
    return run_lazy_op([&] {
162 !
619
        return b->lf.join(o->lf, std::move(l), std::move(r), jh, suffix,
81 ✔
620
                          nulls_equal != 0);
162 !
621
    });
81 ✔
622
}
81 ✔
623

624
PyObject* LazyFrame_concat(PyObject* self, PyObject* args) {
8 ✔
625
    LazyFrameObject* b = as_lazyframe(self);
8 !
626
    if (!b) return nullptr;
8 !
627
    const Py_ssize_t n = PyTuple_GET_SIZE(args);
8 ✔
628
    std::vector<LazyFrameObject*> others;
8 ✔
629
    others.reserve(static_cast<std::size_t>(n));
8 !
630
    for (Py_ssize_t i = 0; i < n; ++i) {
16 ✔
631
        LazyFrameObject* o = as_lazyframe(PyTuple_GET_ITEM(args, i));
9 !
632
        if (!o) return nullptr;
9 ✔
633
        others.push_back(o);
8 !
634
    }
635
    return run_lazy_op([&] {
14 !
636
        dataframe::LazyFrame out = b->lf;
7 ✔
637
        for (LazyFrameObject* o : others) out = out.concat(o->lf);
15 !
638
        return out;
6 ✔
639
    });
8 ✔
640
}
8 ✔
641

642
PyObject* LazyFrame_unique(PyObject* self, PyObject* args, PyObject* kwds) {
35 ✔
643
    LazyFrameObject* b = as_lazyframe(self);
35 !
644
    if (!b) return nullptr;
35 !
645
    PyObject* subset_obj = Py_None;
35 ✔
646
    static const char* kw[] = {"subset", nullptr};
647
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", const_cast<char**>(kw),
35 !
648
                                     &subset_obj))
649
        return nullptr;
×
650
    std::vector<std::string> subset;
35 ✔
651
    if (subset_obj != Py_None && !strings_from_str_or_seq(subset_obj, subset))
35 !
652
        return nullptr;
×
653
    return run_lazy_op([&] { return b->lf.unique(std::move(subset)); });
70 !
654
}
35 ✔
655

656
PyObject* LazyFrame_sample(PyObject* self, PyObject* args, PyObject* kwds) {
×
657
    LazyFrameObject* b = as_lazyframe(self);
×
658
    if (!b) return nullptr;
×
659
    long long n = 0;
×
660
    unsigned long long seed = 0;
×
661
    static const char* kw[] = {"n", "seed", nullptr};
662
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "L|K", const_cast<char**>(kw),
×
663
                                     &n, &seed))
664
        return nullptr;
×
665
    return run_lazy_op([&] { return b->lf.sample(n, seed); });
×
666
}
667

668
PyObject* LazyFrame_head_by(PyObject* self, PyObject* args, PyObject* kwds) {
8 ✔
669
    LazyFrameObject* b = as_lazyframe(self);
8 !
670
    if (!b) return nullptr;
8 !
671
    PyObject* keys_obj = nullptr;
8 ✔
672
    long long n = 0;
8 ✔
673
    static const char* kw[] = {"keys", "n", nullptr};
674
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OL", const_cast<char**>(kw),
8 !
675
                                     &keys_obj, &n))
676
        return nullptr;
×
677
    std::vector<std::string> keys;
8 ✔
678
    if (!strings_from_str_or_seq(keys_obj, keys)) return nullptr;
8 !
679
    return run_lazy_op([&] { return b->lf.head_by(std::move(keys), n); });
16 !
680
}
8 ✔
681

682
PyObject* LazyFrame_is_duplicated(PyObject* self, PyObject*) {
×
683
    LazyFrameObject* b = as_lazyframe(self);
×
684
    if (!b) return nullptr;
×
685
    return run_lazy_op([&] { return b->lf.is_duplicated(); });
×
686
}
687

688
PyObject* LazyFrame_is_unique(PyObject* self, PyObject*) {
×
689
    LazyFrameObject* b = as_lazyframe(self);
×
690
    if (!b) return nullptr;
×
691
    return run_lazy_op([&] { return b->lf.is_unique(); });
×
692
}
693

694
// group_by_dynamic(time_col, every, period=None, aggs=[], origin=0,
695
// origin_min=False). period defaults to every (tumbling window).
696
PyObject* LazyFrame_group_by_dynamic(PyObject* self, PyObject* args,
2 ✔
697
                                     PyObject* kwds) {
698
    LazyFrameObject* b = as_lazyframe(self);
2 !
699
    if (!b) return nullptr;
2 !
700
    const char* time_col = nullptr;
2 ✔
701
    long long every = 0;
2 ✔
702
    PyObject* period_obj = Py_None;
2 ✔
703
    PyObject* aggs_obj = nullptr;
2 ✔
704
    long long origin = 0;
2 ✔
705
    int origin_min = 0;
2 ✔
706
    static const char* kw[] = {"time_col", "every",      "period", "aggs",
707
                               "origin",   "origin_min", nullptr};
708
    if (!PyArg_ParseTupleAndKeywords(
2 !
709
            args, kwds, "sL|OOLp", const_cast<char**>(kw), &time_col, &every,
710
            &period_obj, &aggs_obj, &origin, &origin_min))
711
        return nullptr;
×
712
    long long period = every;
2 ✔
713
    if (period_obj && period_obj != Py_None) {
2 !
714
        period = PyLong_AsLongLong(period_obj);
×
715
        if (period == -1 && PyErr_Occurred()) return nullptr;
×
716
    }
717
    std::vector<GroupAgg> aggs;
2 ✔
718
    if (aggs_obj && aggs_obj != Py_None && !aggs_from_seq(aggs_obj, aggs))
2 !
719
        return nullptr;
×
720
    return run_lazy_op([&] {
4 !
721
        return b->lf.group_by_dynamic(time_col, every, period, std::move(aggs),
6 ✔
722
                                      origin, origin_min != 0);
2 !
723
    });
2 ✔
724
}
2 ✔
725

726
PyObject* LazyFrame_pivot(PyObject* self, PyObject* args, PyObject* kwds) {
×
727
    LazyFrameObject* b = as_lazyframe(self);
×
728
    if (!b) return nullptr;
×
729
    const char* index = nullptr;
×
730
    const char* on = nullptr;
×
731
    const char* values = nullptr;
×
732
    const char* agg = "first";
×
733
    static const char* kw[] = {"index", "on", "values", "agg", nullptr};
734
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "sss|s",
×
735
                                     const_cast<char**>(kw), &index, &on,
736
                                     &values, &agg))
737
        return nullptr;
×
738
    return run_lazy_op([&] { return b->lf.pivot(index, on, values, agg); });
×
739
}
740

741
PyObject* LazyFrame_to_dummies(PyObject* self, PyObject* column) {
1 ✔
742
    LazyFrameObject* b = as_lazyframe(self);
1 !
743
    if (!b) return nullptr;
1 !
744
    const char* s = PyUnicode_AsUTF8(column);
1 !
745
    if (!s) return nullptr;
1 !
746
    return run_lazy_op([&] { return b->lf.to_dummies(s); });
2 !
747
}
748

749
PyObject* LazyFrame_describe(PyObject* self, PyObject*) {
×
750
    LazyFrameObject* b = as_lazyframe(self);
×
751
    if (!b) return nullptr;
×
752
    return run_lazy_op([&] { return b->lf.describe(); });
×
753
}
754

755
PyObject* LazyFrame_memory_budget(PyObject* self, PyObject* bytes) {
25 ✔
756
    LazyFrameObject* b = as_lazyframe(self);
25 !
757
    if (!b) return nullptr;
25 !
758
    unsigned long long v = PyLong_AsUnsignedLongLong(bytes);
25 !
759
    if (v == static_cast<unsigned long long>(-1) && PyErr_Occurred())
25 !
760
        return nullptr;
×
761
    return run_lazy_op([&] { return b->lf.memory_budget(v); });
50 !
762
}
763

764
PyObject* LazyFrame_auto_spill(PyObject* self, PyObject*) {
×
765
    LazyFrameObject* b = as_lazyframe(self);
×
766
    if (!b) return nullptr;
×
767
    return run_lazy_op([&] { return b->lf.auto_spill(); });
×
768
}
769

770
PyObject* LazyFrame_schema(PyObject* self, PyObject*) {
870 ✔
771
    LazyFrameObject* b = as_lazyframe(self);
870 !
772
    if (!b) return nullptr;
870 !
773
    std::vector<std::string> names;
870 ✔
774
    try {
775
        names = b->lf.schema();
870 ✔
776
    } catch (const std::exception& e) {
2 !
777
        PyErr_SetString(PyExc_ValueError, e.what());
2 !
778
        return nullptr;
2 ✔
779
    }
2 ✔
780
    return str_list_from(names);
868 !
781
}
870 ✔
782

783
PyObject* LazyFrame_explain(PyObject* self, PyObject*) {
10 ✔
784
    LazyFrameObject* b = as_lazyframe(self);
10 !
785
    if (!b) return nullptr;
10 !
786
    std::string text;
10 ✔
787
    try {
788
        text = b->lf.explain();
10 !
789
    } catch (const std::exception& e) {
×
790
        PyErr_SetString(PyExc_ValueError, e.what());
×
791
        return nullptr;
×
792
    }
×
793
    return PyUnicode_FromStringAndSize(text.data(),
10 !
794
                                       static_cast<Py_ssize_t>(text.size()));
20 ✔
795
}
10 ✔
796

797
PyObject* LazyFrame_collect(PyObject* self, PyObject* args, PyObject* kwds) {
1,400 ✔
798
    LazyFrameObject* b = as_lazyframe(self);
1,400 !
799
    if (!b) return nullptr;
1,400 !
800
    long long morsel_rows = 0;
1,400 ✔
801
    PyObject* runtime_arg = nullptr;
1,400 ✔
802
    static const char* kw[] = {"morsel_rows", "runtime", nullptr};
803
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|LO", const_cast<char**>(kw),
1,400 !
804
                                     &morsel_rows, &runtime_arg))
805
        return nullptr;
×
806
    std::shared_ptr<dftracer::utils::Runtime> rt =
807
        runtime_from_arg(runtime_arg);
1,400 !
808
    if (!rt) return nullptr;
1,400 !
809
    dataframe::DataFrame out;
1,400 ✔
810
    if (!run_blocking(
1,400 !
811
            [&] { out = rt->submit(b->lf.collect(morsel_rows)).get(); }))
1,415 !
812
        return nullptr;
5 ✔
813
    return dftracer::utils::python::wrap_dataframe(std::move(out));
1,395 !
814
}
1,400 ✔
815

816
// Drains the plan's chunk generator into `state`, which the Python iterator
817
// pulls from with the GIL released.
818
dftracer::utils::coro::CoroTask<void> drain_stream(
43 !
819
    dftracer::utils::CoroScope&,
820
    std::shared_ptr<
821
        dftracer::utils::python::StreamingState<dataframe::DataFrame>>
822
        state,
823
    LazyFrame lf, std::int64_t morsel_rows) {
824
    try {
825
        auto gen = lf.stream(morsel_rows);
826
        while (auto df = co_await gen.next()) {
827
            if (state->cancelled()) break;
828
            const std::size_t bytes =
829
                static_cast<std::size_t>(df->num_rows()) *
830
                static_cast<std::size_t>(df->num_columns() + 1) * 16;
831
            if (!state->push(std::move(*df), bytes)) break;
832
        }
833
        state->complete();
834
    } catch (...) {
835
        state->fail(std::current_exception());
836
    }
837
}
86 !
838

839
PyObject* LazyFrame_stream(PyObject* self, PyObject* args, PyObject* kwds) {
43 ✔
840
    LazyFrameObject* b = as_lazyframe(self);
43 !
841
    if (!b) return nullptr;
43 !
842
    long long morsel_rows = 0;
43 ✔
843
    PyObject* runtime_arg = nullptr;
43 ✔
844
    static const char* kw[] = {"morsel_rows", "runtime", nullptr};
845
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|LO", const_cast<char**>(kw),
43 !
846
                                     &morsel_rows, &runtime_arg))
847
        return nullptr;
×
848
    std::shared_ptr<dftracer::utils::Runtime> rt =
849
        runtime_from_arg(runtime_arg);
43 !
850
    if (!rt) return nullptr;
43 !
851
    namespace py = dftracer::utils::python;
852
    auto state = std::make_shared<py::StreamingState<dataframe::DataFrame>>(
853
        dftracer::utils::compute_memory_budget(0));
43 !
854
    auto* it = reinterpret_cast<py::ArrowStreamingIteratorObject*>(
855
        py::ArrowStreamingIteratorType.tp_new(&py::ArrowStreamingIteratorType,
43 !
856
                                              nullptr, nullptr));
857
    if (!it) return nullptr;
43 !
858
    it->cpp_state->state = state;
43 ✔
859
    it->cpp_state->pull_df = [state]() { return state->pull(); };
53,737 !
860
    it->cpp_state->get_error = [state]() { return state->error(); };
86 !
861
    it->cpp_state->cancel = [state]() { state->cancel(); };
86 !
862
    LazyFrame lf = b->lf;
43 !
863
    Py_BEGIN_ALLOW_THREADS rt->submit(
129 !
864
        dftracer::utils::run_coro_scope(rt->executor(), drain_stream, state,
86 !
865
                                        std::move(lf),
43 ✔
866
                                        static_cast<std::int64_t>(morsel_rows)),
867
        "lazyframe_stream");
868
    Py_END_ALLOW_THREADS return reinterpret_cast<PyObject*>(it);
43 !
869
}
43 ✔
870

871
PyObject* LazyFrame_output_schema(PyObject* self, PyObject*) {
9 ✔
872
    LazyFrameObject* b = as_lazyframe(self);
9 !
873
    if (!b) return nullptr;
9 !
874
    dataframe::Schema schema;
9 ✔
875
    try {
876
        schema = b->lf.output_schema();
9 !
877
    } catch (const std::exception& e) {
×
878
        PyErr_SetString(PyExc_ValueError, e.what());
×
879
        return nullptr;
×
880
    }
×
881
    PyObject* out = PyList_New(static_cast<Py_ssize_t>(schema.fields.size()));
9 !
882
    if (!out) return nullptr;
9 !
883
    for (std::size_t i = 0; i < schema.fields.size(); ++i) {
52 ✔
884
        const dataframe::Field& f = schema.fields[i];
43 ✔
885
        PyObject* item =
886
            Py_BuildValue("(si)", f.name.c_str(), static_cast<int>(f.type.id));
43 !
887
        if (!item) {
43 !
888
            Py_DECREF(out);
889
            return nullptr;
×
890
        }
891
        PyList_SET_ITEM(out, static_cast<Py_ssize_t>(i), item);
43 ✔
892
    }
893
    return out;
9 ✔
894
}
9 ✔
895

896
PyMethodDef LazyFrame_methods[] = {
897
    {"filter", LazyFrame_filter, METH_O,
898
     "filter(ast) -> LazyFrame keeping rows where the predicate holds."},
899
    {"with_column", LazyFrame_with_column, METH_VARARGS,
900
     "with_column(name, ast) -> LazyFrame with a column added or replaced."},
901
    {"select", LazyFrame_select, METH_O,
902
     "select(names) -> LazyFrame projected to the given columns."},
903
    {"rename", LazyFrame_rename, METH_O,
904
     "rename(names) -> LazyFrame with columns renamed positionally."},
905
    {"drop", LazyFrame_drop, METH_O,
906
     "drop(names) -> LazyFrame without the named columns, including those "
907
     "a scan adds per batch."},
908
    {"rename_columns", LazyFrame_rename_columns, METH_VARARGS,
909
     "rename_columns(from, to) -> LazyFrame with each `from` column renamed "
910
     "to the `to` name at the same index."},
911
    {"slice", LazyFrame_slice, METH_VARARGS,
912
     "slice(offset, len) -> LazyFrame of the row window."},
913
    {"head", LazyFrame_head, METH_O,
914
     "head(n) -> LazyFrame of the first n rows."},
915
    {"tail", LazyFrame_tail, METH_O,
916
     "tail(n) -> LazyFrame of the last n rows."},
917
    {"drop_nulls", LazyFrame_drop_nulls, METH_NOARGS,
918
     "drop_nulls() -> LazyFrame with rows holding any null removed."},
919
    {"fill_null", LazyFrame_fill_null, METH_O,
920
     "fill_null(value) -> LazyFrame with nulls filled in every column."},
921
    {"with_row_index", LazyFrame_with_row_index, METH_O,
922
     "with_row_index(name) -> LazyFrame with a prepended Int64 index column."},
923
    {"null_count", LazyFrame_null_count, METH_NOARGS,
924
     "null_count() -> LazyFrame of each column's null count (one row)."},
925
    {"reduce", LazyFrame_reduce, METH_O,
926
     "reduce(agg) -> LazyFrame: the aggregate named `agg` over every eligible "
927
     "column, a streaming one-group group-by."},
928
    {"group_transform", DFTU_PYCFUNCTION(LazyFrame_group_transform),
929
     METH_VARARGS | METH_KEYWORDS,
930
     "group_transform(keys, kind, n=0, method='average', ascending=True) -> "
931
     "LazyFrame: the group-wise transform `kind` (cumsum, cummax, cummin, "
932
     "cumcount, shift, diff, pct_change, rank, ngroup, head, tail, nth) over "
933
     "the groups of `keys`, one value per input row in input order."},
934
    {"reduce_specs", LazyFrame_reduce_specs, METH_VARARGS,
935
     "reduce_specs(agg, keys=None) -> list[str]: the 'op:column:out' specs "
936
     "that broadcast `agg` over every eligible non-key column, for group_by."},
937
    {"explode", LazyFrame_explode, METH_O,
938
     "explode(column) -> LazyFrame with the List column expanded per element."},
939
    {"unnest", DFTU_PYCFUNCTION(LazyFrame_unnest), METH_VARARGS | METH_KEYWORDS,
940
     "unnest(column, keep_empty=False) -> LazyFrame expanding a List column "
941
     "one row per element; an empty/null list drops the row unless "
942
     "keep_empty, and a List<Struct> flattens into one column per field."},
943
    {"compare_agg", LazyFrame_compare_agg, METH_VARARGS,
944
     "compare_agg(variant, n_key) -> LazyFrame: DataFrame.compare_agg over "
945
     "the two collected plans."},
946
    {"window", DFTU_PYCFUNCTION(LazyFrame_window), METH_VARARGS | METH_KEYWORDS,
947
     "window(partition_by, order_by, specs) -> LazyFrame: SQL window "
948
     "functions over the collected plan; specs are normalized 12-tuples."},
949
    {"column_op", DFTU_PYCFUNCTION(LazyFrame_column_op),
950
     METH_VARARGS | METH_KEYWORDS,
951
     "column_op(column, op, column2=None, a=0, b=0, text=None) -> the "
952
     "registered column op over `column` as a plan step (a breaker)."},
953
    {"gap_fill", DFTU_PYCFUNCTION(LazyFrame_gap_fill),
954
     METH_VARARGS | METH_KEYWORDS,
955
     "gap_fill(partition_by, time, bucket, values, mode, start=None, "
956
     "end=None) -> LazyFrame: a regular time grid over the collected plan."},
957
    {"asof", DFTU_PYCFUNCTION(LazyFrame_asof), METH_VARARGS | METH_KEYWORDS,
958
     "asof(other, on, by, direction, tolerance) -> LazyFrame: temporal "
959
     "nearest-match join; under a memory budget both plans are sorted and "
960
     "merged without being collected."},
961
    {"interval", DFTU_PYCFUNCTION(LazyFrame_interval),
962
     METH_VARARGS | METH_KEYWORDS,
963
     "interval(other, point, lo, hi, by, outer) -> LazyFrame: point-in-range "
964
     "join; under a memory budget both plans are sorted and merged without "
965
     "being collected."},
966
    {"unpivot", LazyFrame_unpivot, METH_VARARGS,
967
     "unpivot(id_vars, value_vars) -> LazyFrame reshaped wide to long."},
968
    {"melt", LazyFrame_unpivot, METH_VARARGS, "melt(...) -> alias of unpivot."},
969
    {"topk", DFTU_PYCFUNCTION(LazyFrame_topk), METH_VARARGS | METH_KEYWORDS,
970
     "topk(name, k, largest=True) -> LazyFrame of the k extreme rows."},
971
    {"group_by", LazyFrame_group_by, METH_VARARGS,
972
     "group_by(key, aggs) -> LazyFrame grouped by key with string-spec aggs."},
973
    {"sort_by", DFTU_PYCFUNCTION(LazyFrame_sort_by),
974
     METH_VARARGS | METH_KEYWORDS,
975
     "sort_by(name, descending=False) -> LazyFrame sorted by one column."},
976
    {"take", LazyFrame_take, METH_O,
977
     "take(indices) -> LazyFrame keeping the rows at indices (any order, "
978
     "repeats allowed)."},
979
    {"filter_mask", LazyFrame_filter_mask, METH_O,
980
     "filter_mask(mask) -> LazyFrame keeping rows where the precomputed Bool "
981
     "mask is true."},
982
    {"reverse", LazyFrame_reverse, METH_NOARGS,
983
     "reverse() -> LazyFrame with rows in reverse order."},
984
    {"sort_by_multi", DFTU_PYCFUNCTION(LazyFrame_sort_by_multi),
985
     METH_VARARGS | METH_KEYWORDS,
986
     "sort_by_multi(names, descending=False) -> LazyFrame stably sorted "
987
     "lexicographically by several key columns."},
988
    {"join", DFTU_PYCFUNCTION(LazyFrame_join), METH_VARARGS | METH_KEYWORDS,
989
     "join(other, on=None, how='inner', left_on=None, right_on=None, "
990
     "suffix='_right') -> LazyFrame hash-joined with another LazyFrame; "
991
     "how=inner|left|right|outer|full|semi|anti|cross."},
992
    {"concat", LazyFrame_concat, METH_VARARGS,
993
     "concat(*others) -> LazyFrame with every row of this plan followed by "
994
     "every row of each other plan in turn; schemas must match."},
995
    {"unique", DFTU_PYCFUNCTION(LazyFrame_unique), METH_VARARGS | METH_KEYWORDS,
996
     "unique(subset=None) -> LazyFrame with duplicate rows removed (keep "
997
     "first), keyed on every column or on the subset names."},
998
    {"drop_duplicates", DFTU_PYCFUNCTION(LazyFrame_unique),
999
     METH_VARARGS | METH_KEYWORDS,
1000
     "drop_duplicates(subset=None) -> alias of unique."},
1001
    {"sample", DFTU_PYCFUNCTION(LazyFrame_sample), METH_VARARGS | METH_KEYWORDS,
1002
     "sample(n, seed=0) -> LazyFrame deterministic n-row sample."},
1003
    {"head_by", DFTU_PYCFUNCTION(LazyFrame_head_by),
1004
     METH_VARARGS | METH_KEYWORDS,
1005
     "head_by(keys, n) -> LazyFrame of the first n rows of each key, in "
1006
     "input order."},
1007
    {"is_duplicated", LazyFrame_is_duplicated, METH_NOARGS,
1008
     "is_duplicated() -> LazyFrame Bool column, true where the row repeats."},
1009
    {"is_unique", LazyFrame_is_unique, METH_NOARGS,
1010
     "is_unique() -> LazyFrame Bool column, true where the row is unique."},
1011
    {"group_by_dynamic", DFTU_PYCFUNCTION(LazyFrame_group_by_dynamic),
1012
     METH_VARARGS | METH_KEYWORDS,
1013
     "group_by_dynamic(time_col, every, period=None, aggs=[], origin=0, "
1014
     "origin_min=False) -> LazyFrame of time-window aggregates."},
1015
    {"pivot", DFTU_PYCFUNCTION(LazyFrame_pivot), METH_VARARGS | METH_KEYWORDS,
1016
     "pivot(index, on, values, agg='first') -> LazyFrame reshaped long to "
1017
     "wide."},
1018
    {"to_dummies", LazyFrame_to_dummies, METH_O,
1019
     "to_dummies(column) -> LazyFrame one-hot encoding of the column."},
1020
    {"describe", LazyFrame_describe, METH_NOARGS,
1021
     "describe() -> LazyFrame of per-column summary statistics."},
1022
    {"memory_budget", LazyFrame_memory_budget, METH_O,
1023
     "memory_budget(bytes) -> LazyFrame with the out-of-core spill budget "
1024
     "set."},
1025
    {"auto_spill", LazyFrame_auto_spill, METH_NOARGS,
1026
     "auto_spill() -> LazyFrame with the spill budget at ~1/3 of memory."},
1027
    {"output_schema", LazyFrame_output_schema, METH_NOARGS,
1028
     "output_schema() -> [(name, dtype id)] without running; a type the "
1029
     "plan cannot know statically is 0 (unknown)."},
1030
    {"stream", DFTU_PYCFUNCTION(LazyFrame_stream), METH_VARARGS | METH_KEYWORDS,
1031
     "stream(morsel_rows=0, runtime=None) -> iterator of DataFrame chunks."},
1032
    {"schema", LazyFrame_schema, METH_NOARGS,
1033
     "schema() -> list[str] of output column names, or [] if data-dependent."},
1034
    {"explain", LazyFrame_explain, METH_NOARGS,
1035
     "explain() -> str of the optimized plan."},
1036
    {"collect", DFTU_PYCFUNCTION(LazyFrame_collect),
1037
     METH_VARARGS | METH_KEYWORDS,
1038
     "collect(morsel_rows=65536) -> _DataFrame, running the pipeline."},
1039
    {nullptr, nullptr, 0, nullptr}};
1040

1041
PyObject* collect_all_py(PyObject*, PyObject* args, PyObject* kwds) {
70 ✔
1042
    PyObject* arg = nullptr;
70 ✔
1043
    PyObject* runtime_arg = nullptr;
70 ✔
1044
    static const char* kw[] = {"plans", "runtime", nullptr};
1045
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", const_cast<char**>(kw),
70 !
1046
                                     &arg, &runtime_arg))
1047
        return nullptr;
×
1048
    std::shared_ptr<dftracer::utils::Runtime> rt =
1049
        runtime_from_arg(runtime_arg);
70 !
1050
    if (!rt) return nullptr;
70 !
1051
    PyObject* seq = PySequence_Fast(arg, "collect_all expects a sequence");
70 !
1052
    if (!seq) return nullptr;
70 !
1053
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
70 !
1054
    std::vector<LazyFrame> plans;
70 ✔
1055
    plans.reserve(static_cast<std::size_t>(n));
70 !
1056
    for (Py_ssize_t i = 0; i < n; ++i) {
176 ✔
1057
        LazyFrameObject* b = as_lazyframe(PySequence_Fast_GET_ITEM(seq, i));
106 !
1058
        if (!b) {
106 !
1059
            Py_DECREF(seq);
1060
            return nullptr;
×
1061
        }
1062
        plans.push_back(b->lf);
106 !
1063
    }
1064
    Py_DECREF(seq);
1065
    std::vector<dataframe::DataFrame> frames;
70 ✔
1066
    if (!run_blocking([&] {
70 !
1067
            frames = rt->submit(dataframe::collect_all(std::move(plans))).get();
70 !
1068
        }))
70 ✔
1069
        return nullptr;
×
1070
    PyObject* out = PyList_New(static_cast<Py_ssize_t>(frames.size()));
70 !
1071
    if (!out) return nullptr;
70 !
1072
    for (std::size_t i = 0; i < frames.size(); ++i) {
176 ✔
1073
        PyObject* df =
1074
            dftracer::utils::python::wrap_dataframe(std::move(frames[i]));
106 !
1075
        if (!df) {
106 !
1076
            Py_DECREF(out);
1077
            return nullptr;
×
1078
        }
1079
        PyList_SET_ITEM(out, static_cast<Py_ssize_t>(i), df);
106 ✔
1080
    }
1081
    return out;
70 ✔
1082
}
70 ✔
1083

1084
PyMethodDef lazyframe_module_methods[] = {
1085
    {"collect_all", DFTU_PYCFUNCTION(collect_all_py),
1086
     METH_VARARGS | METH_KEYWORDS,
1087
     "collect_all(plans) -> list of DataFrames, one per plan in order; plans "
1088
     "over the same trace base share one scan."},
1089
    {nullptr, nullptr, 0, nullptr}};
1090

1091
}  // namespace
1092

1093
namespace dftracer::utils::python {
1094

1095
int init_lazyframe(PyObject* m) {
7 ✔
1096
    LazyFrameType = {};
7 ✔
1097
    LazyFrameType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
7 ✔
1098
    LazyFrameType.tp_name = "dftracer_utils_ext._LazyFrame";
7 ✔
1099
    LazyFrameType.tp_basicsize = sizeof(LazyFrameObject);
7 ✔
1100
    LazyFrameType.tp_flags = Py_TPFLAGS_DEFAULT;
7 ✔
1101
    LazyFrameType.tp_doc = "A deferred query over a native vec batch.";
7 ✔
1102
    LazyFrameType.tp_dealloc = reinterpret_cast<destructor>(LazyFrame_dealloc);
7 ✔
1103
    LazyFrameType.tp_methods = LazyFrame_methods;
7 ✔
1104
    LazyFrameType.tp_new = nullptr;  // created only by DataFrame.lazy()
7 ✔
1105
    if (register_type(m, &LazyFrameType, "_LazyFrame") < 0) return -1;
7 !
1106
    return PyModule_AddFunctions(m, lazyframe_module_methods);
7 ✔
1107
}
1108

1109
PyObject* wrap_lazyframe(dataframe::LazyFrame&& lf) {
2,355 ✔
1110
    return make_lazyframe(std::move(lf));
2,355 ✔
1111
}
1112

1113
const dataframe::LazyFrame* lazyframe_of(PyObject* o) {
32 ✔
1114
    LazyFrameObject* b = as_lazyframe(o);
32 ✔
1115
    return b ? &b->lf : nullptr;
32 !
1116
}
1117

1118
}  // namespace dftracer::utils::python
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