• 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

63.78
/src/dftracer/utils/python/dataframe.cpp
1
// A native vec batch exposed to Python: a named set of dataframe::Columns (our
2
// SIMD columnar format) held as a single STRUCT column. Series access,
3
// filtering, and row ops stay in vec; Arrow/pandas/polars are produced only on
4
// an explicit to_arrow()/to_pandas()/to_polars(), zero-copy through the Arrow C
5
// interface.
6

7
#include <dftracer/utils/core/common/config.h>  // DFTRACER_UTILS_ENABLE_ARROW
8
#include <dftracer/utils/core/common/error.h>
9
#include <dftracer/utils/dataframe/agg_expr.h>
10
#include <dftracer/utils/dataframe/frame_ops.h>
11
#include <dftracer/utils/dataframe/internal/frame_native.h>
12
#include <dftracer/utils/python/dataframe.h>
13
#include <dftracer/utils/python/py_frame_op_helpers.h>
14
#ifdef DFTRACER_UTILS_ENABLE_ARROW
15
#include <dftracer/utils/dataframe/arrow_bridge.h>
16
#endif
17
#include <dftracer/utils/dataframe/batch_ops.h>
18
#include <dftracer/utils/dataframe/dataframe.h>
19
#include <dftracer/utils/dataframe/expr.h>
20
#include <dftracer/utils/dataframe/kernels/kernels.h>
21
#include <dftracer/utils/dataframe/lazyframe.h>
22
#include <dftracer/utils/dataframe/plan.h>
23
#include <dftracer/utils/duql/errc.h>
24
#include <dftracer/utils/duql/query.h>
25
#include <dftracer/utils/python/columnar_eval.h>
26
#include <dftracer/utils/python/lazyframe.h>
27
#include <dftracer/utils/python/py_agg_helpers.h>
28
#include <dftracer/utils/python/py_errors.h>
29
#include <dftracer/utils/python/py_join_helpers.h>
30
#include <dftracer/utils/python/py_method.h>
31
#include <dftracer/utils/python/py_scalar_helpers.h>
32
#include <dftracer/utils/python/py_type_helpers.h>
33
#include <dftracer/utils/python/series.h>
34

35
#include <cstdint>
36
#include <cstring>
37
#ifdef DFTRACER_UTILS_ENABLE_ARROW
38
#include <nanoarrow/nanoarrow.hpp>
39
#endif
40
#include <new>
41
#include <optional>
42
#include <stdexcept>
43
#include <string>
44
#include <utility>
45
#include <vector>
46

47
namespace dataframe = dftracer::utils::dataframe;
48

49
namespace {
50

51
using dataframe::DataFrame;
52
using dataframe::Series;
53
using dftracer::utils::python::aggs_from_seq;
54
using dftracer::utils::python::group_agg_from_spec;
55
using dftracer::utils::python::join_how_from_str;
56
using dftracer::utils::python::join_keys_from_objs;
57
using dftracer::utils::python::parse_int_seq;
58
using dftracer::utils::python::parse_seq;
59
using dftracer::utils::python::parse_string_seq;
60
using dftracer::utils::python::strings_from_str_or_seq;
61

62
// A DataFrame owns its columns as one STRUCT column: child(i) hands out a
63
// column sharing the struct's buffers (O(1)), and the struct exports to Arrow
64
// in one zero-copy step.
65
struct DataFrameObject {
66
    PyObject_HEAD Series st;
67
    std::vector<std::string> names;
68
};
69

70
PyTypeObject DataFrameType;
71

72
DataFrameObject* as_dataframe(PyObject* o) {
15,262 ✔
73
    if (!PyObject_TypeCheck(o, &DataFrameType)) {
15,262 !
74
        PyErr_SetString(PyExc_TypeError, "expected a DataFrame");
×
75
        return nullptr;
×
76
    }
77
    return reinterpret_cast<DataFrameObject*>(o);
15,262 ✔
78
}
79

80
PyObject* make_dataframe(DataFrame&& b) {
59,226 ✔
81
    Series st = Series::structs(b.names, std::move(b.columns));
118,452 !
82
    auto* self = reinterpret_cast<DataFrameObject*>(
83
        DataFrameType.tp_alloc(&DataFrameType, 0));
59,226 !
84
    if (!self) return nullptr;
59,226 !
85
    new (&self->st) Series(std::move(st));
59,226 ✔
86
    new (&self->names) std::vector<std::string>(std::move(b.names));
59,226 ✔
87
    return reinterpret_cast<PyObject*>(self);
59,226 ✔
88
}
59,226 ✔
89

90
void DataFrame_dealloc(DataFrameObject* self) {
59,226 ✔
91
    self->names.~vector();
59,226 ✔
92
    self->st.~Series();
59,226 ✔
93
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
59,226 ✔
94
}
59,226 ✔
95

96
std::int64_t index_of(const DataFrameObject* self, const std::string& name) {
8,397 ✔
97
    for (std::size_t i = 0; i < self->names.size(); ++i)
30,960 ✔
98
        if (self->names[i] == name) return static_cast<std::int64_t>(i);
30,911 ✔
99
    return -1;
49 ✔
100
}
101

102
// A dataframe::DataFrame view over the struct's children (shared buffers,
103
// zero-copy), for forwarding to the batch_ops frame kernels.
104
DataFrame to_dataframe(const DataFrameObject* self) {
3,335 ✔
105
    DataFrame b;
3,335 ✔
106
    b.names = self->names;
3,335 !
107
    b.columns.reserve(self->names.size());
3,335 !
108
    for (std::size_t i = 0; i < self->names.size(); ++i)
11,697 ✔
109
        b.columns.push_back(self->st.child(static_cast<std::int64_t>(i)));
8,362 !
110
    return b;
3,335 ✔
111
}
×
112

113
// Wrap a batch_ops call that may throw, turning C++ exceptions into Python
114
// errors.
115
template <class Fn>
116
PyObject* run_batch_op(Fn&& fn) {
1,931 ✔
117
    try {
118
        return make_dataframe(fn());
1,931 !
119
    } catch (const std::out_of_range& e) {
23 !
120
        PyErr_SetString(PyExc_KeyError, e.what());
5 !
121
        return nullptr;
5 ✔
122
    } catch (const std::exception& e) {
18 ✔
123
        PyErr_SetString(PyExc_ValueError, e.what());
18 !
124
        return nullptr;
18 ✔
125
    }
126
}
127

128
PyObject* DataFrame_subscript(PyObject* self, PyObject* key) {
7,864 ✔
129
    DataFrameObject* b = as_dataframe(self);
7,864 ✔
130
    if (!b) return nullptr;
7,864 !
131
    const char* name = PyUnicode_AsUTF8(key);
7,864 ✔
132
    if (!name) {
7,864 !
133
        PyErr_SetString(PyExc_TypeError, "DataFrame key must be a column name");
×
134
        return nullptr;
×
135
    }
136
    std::int64_t i = index_of(b, name);
7,864 !
137
    if (i < 0) {
7,864 !
138
        PyErr_Format(PyExc_KeyError, "no column named '%s'", name);
×
139
        return nullptr;
×
140
    }
141
    return dftracer::utils::python::wrap_vec_column(b->st.child(i));
7,864 !
142
}
143

144
int DataFrame_contains(PyObject* self, PyObject* key) {
534 ✔
145
    DataFrameObject* b = as_dataframe(self);
534 ✔
146
    if (!b) return -1;
534 !
147
    // Only a name can be a column; anything else is simply not in the
148
    // frame, with no error left behind.
149
    if (!PyUnicode_Check(key)) return 0;
534 ✔
150
    const char* name = PyUnicode_AsUTF8(key);
533 ✔
151
    if (!name) return -1;
533 !
152
    return index_of(b, name) >= 0 ? 1 : 0;
533 !
153
}
154

155
PyObject* DataFrame_keys(PyObject* self, PyObject*) {
1,954 ✔
156
    DataFrameObject* b = as_dataframe(self);
1,954 ✔
157
    if (!b) return nullptr;
1,954 !
158
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(b->names.size()));
1,954 ✔
159
    if (!list) return nullptr;
1,954 !
160
    for (std::size_t i = 0; i < b->names.size(); ++i) {
8,807 ✔
161
        PyObject* s = PyUnicode_FromString(b->names[i].c_str());
6,853 ✔
162
        if (!s) {
6,853 !
163
            Py_DECREF(list);
164
            return nullptr;
×
165
        }
166
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
6,853 ✔
167
    }
168
    return list;
1,954 ✔
169
}
170

171
PyObject* DataFrame_filter(PyObject* self, PyObject* mask) {
123 ✔
172
    DataFrameObject* b = as_dataframe(self);
123 !
173
    if (!b) return nullptr;
123 !
174
    const Series* m = dftracer::utils::python::unwrap_vec_column(mask);
123 !
175
    if (!m) {
123 !
176
        PyErr_SetString(PyExc_TypeError,
×
177
                        "filter() expects a Series boolean mask");
178
        return nullptr;
×
179
    }
180
    return run_batch_op([&] { return dataframe::filter(to_dataframe(b), *m); });
369 !
181
}
182

183
// query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None,
184
// descending=False, limit=None) -> DataFrame: a query plan over this batch -
185
// filter by the DSL predicate (a SIMD mask, pandas.query-style), group_by/aggs,
186
// project `select`, sort by `order_by`, cap at `limit`. Raises
187
// DFTUtilsDuqlError on a parse error or a predicate with no columnar lowering
188
// (regex/like/ordered-string/absent field).
189
PyObject* DataFrame_query(PyObject* self, PyObject* args, PyObject* kwds) {
8 ✔
190
    DataFrameObject* b = as_dataframe(self);
8 !
191
    if (!b) return nullptr;
8 !
192
    const char* dsl = nullptr;
8 ✔
193
    const char* group_by = nullptr;
8 ✔
194
    PyObject* aggs_obj = nullptr;
8 ✔
195
    PyObject* select_obj = nullptr;
8 ✔
196
    const char* order_by = nullptr;
8 ✔
197
    int descending = 0;
8 ✔
198
    PyObject* limit_obj = nullptr;
8 ✔
199
    static const char* kw[] = {"dsl",      "group_by",   "aggs",  "select",
200
                               "order_by", "descending", "limit", nullptr};
201
    if (!PyArg_ParseTupleAndKeywords(
8 !
202
            args, kwds, "|zzOOzpO", const_cast<char**>(kw), &dsl, &group_by,
203
            &aggs_obj, &select_obj, &order_by, &descending, &limit_obj))
204
        return nullptr;
×
205

206
    namespace duql = dftracer::utils::duql;
207
    namespace dataframe = dftracer::utils::dataframe;
208
    try {
209
        DataFrame bat = to_dataframe(b);
8 !
210
        dataframe::QueryPlan plan;
8 ✔
211
        std::optional<duql::Query> q;  // keep root() alive across execute
8 ✔
212
        if (dsl && *dsl) {
8 !
213
            auto parsed = duql::Query::from_string(dsl);
7 !
214
            if (!parsed)
7 !
215
                throw dftracer::utils::DFTUtilsException(
×
216
                    dftracer::utils::make_error(duql::DuqlErrc::Parse,
×
217
                                                parsed.error().format()));
×
218
            q.emplace(std::move(*parsed));
7 !
219
            plan.where = &q->root();
7 !
220
        }
7 ✔
221
        if (group_by && *group_by) plan.group_by = group_by;
8 !
222
        if (aggs_obj && aggs_obj != Py_None) {
8 ✔
223
            if (!parse_seq<dataframe::GroupAgg>(
1 !
224
                    aggs_obj, "aggs must be a sequence of strings", plan.aggs,
225
                    [](PyObject* item, std::vector<dataframe::GroupAgg>& o) {
2 ✔
226
                        const char* s = PyUnicode_AsUTF8(item);
2 ✔
227
                        if (!s) return false;
2 !
228
                        o.push_back(group_agg_from_spec(s));
2 !
229
                        return true;
2 ✔
230
                    }))
231
                return nullptr;
×
232
        }
233
        if (select_obj && select_obj != Py_None) {
8 ✔
234
            if (!parse_string_seq(select_obj,
2 !
235
                                  "select must be a sequence of column names",
236
                                  plan.select))
237
                return nullptr;
×
238
        }
239
        if (order_by && *order_by) plan.order_by = order_by;
8 !
240
        plan.descending = descending != 0;
8 ✔
241
        if (limit_obj && limit_obj != Py_None) {
8 ✔
242
            plan.limit = PyLong_AsLongLong(limit_obj);
2 !
243
            if (plan.limit == -1 && PyErr_Occurred()) return nullptr;
2 !
244
        }
245
        return make_dataframe(dataframe::execute(plan, bat));
8 !
246
    } catch (const std::exception& e) {
11 !
247
        dftracer::utils::python::set_typed_py_error(e);
1 !
248
        return nullptr;
1 ✔
249
    }
1 ✔
250
}
251

252
PyObject* DataFrame_select(PyObject* self, PyObject* args) {
201 ✔
253
    DataFrameObject* b = as_dataframe(self);
201 !
254
    if (!b) return nullptr;
201 !
255
    std::vector<std::string> names;
201 ✔
256
    Py_ssize_t n = PyTuple_GET_SIZE(args);
201 ✔
257
    for (Py_ssize_t i = 0; i < n; ++i) {
703 ✔
258
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
502 !
259
        if (!s) {
502 !
260
            PyErr_SetString(PyExc_TypeError, "select() names must be strings");
×
261
            return nullptr;
×
262
        }
263
        names.emplace_back(s);
502 !
264
    }
265
    return run_batch_op(
402 !
266
        [&] { return dataframe::select(to_dataframe(b), names); });
603 !
267
}
201 ✔
268

269
PyObject* DataFrame_rename(PyObject* self, PyObject* mapping) {
41 ✔
270
    DataFrameObject* b = as_dataframe(self);
41 !
271
    if (!b) return nullptr;
41 !
272
    if (!PyDict_Check(mapping)) {
41 !
273
        PyErr_SetString(PyExc_TypeError, "rename() expects a {old: new} dict");
×
274
        return nullptr;
×
275
    }
276
    std::vector<std::string> new_names;
41 ✔
277
    new_names.reserve(b->names.size());
41 !
278
    for (const std::string& name : b->names) {
152 ✔
279
        PyObject* v = PyDict_GetItemString(mapping, name.c_str());
111 !
280
        if (v) {
111 ✔
281
            const char* s = PyUnicode_AsUTF8(v);
60 !
282
            if (!s) {
60 !
283
                PyErr_SetString(PyExc_TypeError, "rename() values must be str");
×
284
                return nullptr;
×
285
            }
286
            new_names.emplace_back(s);
60 !
287
        } else {
288
            new_names.push_back(name);
51 !
289
        }
290
    }
291
    return run_batch_op(
82 !
292
        [&] { return dataframe::rename(to_dataframe(b), new_names); });
123 !
293
}
41 ✔
294

295
PyObject* DataFrame_with_column(PyObject* self, PyObject* args) {
651 ✔
296
    DataFrameObject* b = as_dataframe(self);
651 !
297
    if (!b) return nullptr;
651 !
298
    const char* name = nullptr;
651 ✔
299
    PyObject* col = nullptr;
651 ✔
300
    if (!PyArg_ParseTuple(args, "sO", &name, &col)) return nullptr;
651 !
301
    const Series* c = dftracer::utils::python::unwrap_vec_column(col);
651 !
302
    if (!c) {
651 !
303
        PyErr_SetString(PyExc_TypeError,
×
304
                        "with_column() expects (name, Series)");
305
        return nullptr;
×
306
    }
307
    return run_batch_op(
1,302 !
308
        [&] { return dataframe::with_column(to_dataframe(b), name, *c); });
1,953 !
309
}
310

311
PyObject* DataFrame_take(PyObject* self, PyObject* seq) {
38 ✔
312
    DataFrameObject* b = as_dataframe(self);
38 !
313
    if (!b) return nullptr;
38 !
314
    std::vector<std::int64_t> idx;
38 ✔
315
    if (!parse_int_seq(seq, "take() expects a sequence of ints", idx))
38 !
316
        return nullptr;
×
317
    return run_batch_op([&] { return to_dataframe(b).take(idx); });
114 !
318
}
38 ✔
319

320
PyObject* DataFrame_tail(PyObject* self, PyObject* arg) {
6 ✔
321
    DataFrameObject* b = as_dataframe(self);
6 !
322
    if (!b) return nullptr;
6 !
323
    long long n = PyLong_AsLongLong(arg);
6 !
324
    if (n == -1 && PyErr_Occurred()) return nullptr;
6 !
325
    return run_batch_op([&] { return dataframe::tail(to_dataframe(b), n); });
18 !
326
}
327

328
PyObject* DataFrame_reverse(PyObject* self, PyObject*) {
4 ✔
329
    DataFrameObject* b = as_dataframe(self);
4 !
330
    if (!b) return nullptr;
4 !
331
    return run_batch_op([&] { return dataframe::reverse(to_dataframe(b)); });
12 !
332
}
333

334
PyObject* DataFrame_drop_nulls(PyObject* self, PyObject*) {
5 ✔
335
    DataFrameObject* b = as_dataframe(self);
5 !
336
    if (!b) return nullptr;
5 !
337
    return run_batch_op([&] { return dataframe::drop_nulls(to_dataframe(b)); });
15 !
338
}
339

340
PyObject* DataFrame_fill_null(PyObject* self, PyObject* value) {
9 ✔
341
    DataFrameObject* b = as_dataframe(self);
9 !
342
    if (!b) return nullptr;
9 !
343
    dftu_scalar s{};
9 ✔
344
    if (!py_to_scalar(value, &s)) return nullptr;
9 !
345
    return run_batch_op(
18 !
346
        [&] { return dataframe::fill_null(to_dataframe(b), s); });
27 !
347
}
348

349
// Read a sequence (or single str) of column names into `out`. Returns false and
350
// sets a Python error on a non-string element.
351
bool names_from_obj(PyObject* obj, std::vector<std::string>& out) {
191 ✔
352
    if (PyUnicode_Check(obj)) {
191 ✔
353
        out.emplace_back(PyUnicode_AsUTF8(obj));
9 !
354
        return true;
9 ✔
355
    }
356
    return parse_string_seq(obj, "expected a str or sequence of str", out);
182 ✔
357
}
358

359
// unique(subset=None): subset is a name or a sequence of names; None or an
360
// empty sequence keys on every column.
361
PyObject* DataFrame_unique(PyObject* self, PyObject* args, PyObject* kwds) {
16 ✔
362
    DataFrameObject* b = as_dataframe(self);
16 !
363
    if (!b) return nullptr;
16 !
364
    PyObject* subset_obj = Py_None;
16 ✔
365
    static const char* kwlist[] = {"subset", nullptr};
366
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O",
16 !
367
                                     const_cast<char**>(kwlist), &subset_obj))
368
        return nullptr;
×
369
    std::vector<std::string> subset;
16 ✔
370
    if (subset_obj != Py_None && !names_from_obj(subset_obj, subset))
16 !
371
        return nullptr;
×
372
    return run_batch_op(
32 !
373
        [&] { return dataframe::unique(to_dataframe(b), subset); });
47 ✔
374
}
16 ✔
375

376
PyObject* DataFrame_sort_by_multi(PyObject* self, PyObject* args,
40 ✔
377
                                  PyObject* kwds) {
378
    DataFrameObject* b = as_dataframe(self);
40 !
379
    if (!b) return nullptr;
40 !
380
    PyObject* names_obj = nullptr;
40 ✔
381
    PyObject* descending_obj = nullptr;
40 ✔
382
    static const char* kwlist[] = {"names", "descending", nullptr};
383
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O",
40 !
384
                                     const_cast<char**>(kwlist), &names_obj,
385
                                     &descending_obj))
386
        return nullptr;
×
387
    std::vector<std::string> names;
40 ✔
388
    if (!parse_string_seq(names_obj, "names must be a sequence", names))
40 !
389
        return nullptr;
×
390

391
    // `descending` is either a single bool (broadcasts) or a sequence of bool,
392
    // one per name; a bare Python list is never truthy-coerced (that was the
393
    // old "any non-empty list sorts descending" bug).
394
    std::vector<bool> descending;
40 ✔
395
    if (!descending_obj) {
40 !
396
        descending.push_back(false);
×
397
    } else if (PyBool_Check(descending_obj) || PyLong_Check(descending_obj)) {
40 !
398
        descending.push_back(PyObject_IsTrue(descending_obj) != 0);
25 !
399
    } else {
400
        PyObject* dseq = PySequence_Fast(
15 !
401
            descending_obj, "descending must be a bool or a sequence of bool");
402
        if (!dseq) return nullptr;
15 !
403
        Py_ssize_t dn = PySequence_Fast_GET_SIZE(dseq);
15 !
404
        for (Py_ssize_t i = 0; i < dn; ++i) {
51 ✔
405
            int truth = PyObject_IsTrue(PySequence_Fast_GET_ITEM(dseq, i));
36 !
406
            if (truth < 0) {
36 !
407
                Py_DECREF(dseq);
408
                return nullptr;
×
409
            }
410
            descending.push_back(truth != 0);
36 !
411
        }
412
        Py_DECREF(dseq);
413
    }
414
    return run_batch_op([&] {
80 !
415
        return dataframe::sort_by_multi(to_dataframe(b), names, descending);
80 !
416
    });
40 ✔
417
}
40 ✔
418

419
PyObject* DataFrame_sample(PyObject* self, PyObject* args, PyObject* kwds) {
5 ✔
420
    DataFrameObject* b = as_dataframe(self);
5 !
421
    if (!b) return nullptr;
5 !
422
    Py_ssize_t n = 0;
5 ✔
423
    unsigned long long seed = 0;
5 ✔
424
    static const char* kwlist[] = {"n", "seed", nullptr};
425
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "n|K",
5 !
426
                                     const_cast<char**>(kwlist), &n, &seed))
427
        return nullptr;
×
428
    return run_batch_op([&] {
10 !
429
        return dataframe::sample(to_dataframe(b), static_cast<std::int64_t>(n),
5 ✔
430
                                 static_cast<std::uint64_t>(seed));
10 !
431
    });
5 ✔
432
}
433

434
PyObject* DataFrame_with_row_index(PyObject* self, PyObject* arg) {
46 ✔
435
    DataFrameObject* b = as_dataframe(self);
46 !
436
    if (!b) return nullptr;
46 !
437
    const char* name = PyUnicode_AsUTF8(arg);
46 !
438
    if (!name) {
46 !
439
        PyErr_SetString(PyExc_TypeError, "with_row_index() expects a str");
×
440
        return nullptr;
×
441
    }
442
    return run_batch_op(
92 !
443
        [&] { return dataframe::with_row_index(to_dataframe(b), name); });
138 !
444
}
445

446
PyObject* DataFrame_describe(PyObject* self, PyObject*) {
3 ✔
447
    DataFrameObject* b = as_dataframe(self);
3 !
448
    if (!b) return nullptr;
3 !
449
    return run_batch_op([&] { return dataframe::describe(to_dataframe(b)); });
9 !
450
}
451

452
PyObject* DataFrame_null_count(PyObject* self, PyObject*) {
1 ✔
453
    DataFrameObject* b = as_dataframe(self);
1 !
454
    if (!b) return nullptr;
1 !
455
    return run_batch_op([&] { return dataframe::null_count(to_dataframe(b)); });
3 !
456
}
457

458
// reduce(agg): `agg` is an aggregate name (sum, mean, ...) broadcast over
459
// every eligible column, one row.
460
PyObject* DataFrame_reduce(PyObject* self, PyObject* arg) {
7 ✔
461
    DataFrameObject* b = as_dataframe(self);
7 !
462
    if (!b) return nullptr;
7 !
463
    const char* agg = PyUnicode_AsUTF8(arg);
7 !
464
    if (!agg) return nullptr;
7 !
465
    return run_batch_op([&] {
14 !
466
        return dataframe::reduce(to_dataframe(b),
8 ✔
467
                                 dataframe::agg_from_string(agg));
13 !
468
    });
7 ✔
469
}
470

471
PyObject* DataFrame_group_transform(PyObject* self, PyObject* args,
60 ✔
472
                                    PyObject* kwds) {
473
    DataFrameObject* b = as_dataframe(self);
60 !
474
    if (!b) return nullptr;
60 !
475
    dftracer::utils::python::GroupwiseArgs a;
60 ✔
476
    if (!dftracer::utils::python::parse_groupwise_args(args, kwds,
60 !
477
                                                       names_from_obj, a))
478
        return nullptr;
1 ✔
479
    return run_batch_op([&] {
118 !
480
        return dataframe::GroupBy(to_dataframe(b), a.keys)
120 !
481
            .transform(static_cast<dataframe::GroupwiseOp>(a.kind), a.n,
59 ✔
482
                       static_cast<dataframe::RankMethod>(a.method),
59 ✔
483
                       a.ascending != 0);
117 ✔
484
    });
59 ✔
485
}
60 ✔
486

487
// reduce_specs(agg, keys) -> list[str]: the "op:column:out" specs that
488
// broadcast `agg` over every eligible non-key column, for group_by.
489
PyObject* DataFrame_reduce_specs(PyObject* self, PyObject* args) {
105 ✔
490
    DataFrameObject* b = as_dataframe(self);
105 !
491
    if (!b) return nullptr;
105 !
492
    const char* agg = nullptr;
105 ✔
493
    PyObject* keys_obj = Py_None;
105 ✔
494
    if (!PyArg_ParseTuple(args, "s|O", &agg, &keys_obj)) return nullptr;
105 !
495
    std::vector<std::string> keys;
105 ✔
496
    if (keys_obj != Py_None && !names_from_obj(keys_obj, keys)) return nullptr;
105 !
497
    std::vector<std::string> specs;
105 ✔
498
    try {
499
        specs = dftracer::utils::python::reduce_spec_strings(
208 !
500
            dataframe::reduce_specs(to_dataframe(b),
210 !
501
                                    dataframe::agg_from_string(agg), keys));
104 ✔
502
    } catch (const std::out_of_range& e) {
1 !
503
        PyErr_SetString(PyExc_KeyError, e.what());
×
504
        return nullptr;
×
505
    } catch (const std::exception& e) {
1 ✔
506
        PyErr_SetString(PyExc_ValueError, e.what());
1 !
507
        return nullptr;
1 ✔
508
    }
1 ✔
509
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(specs.size()));
104 !
510
    if (!list) return nullptr;
104 !
511
    for (std::size_t i = 0; i < specs.size(); ++i) {
295 ✔
512
        PyObject* s = PyUnicode_FromString(specs[i].c_str());
191 !
513
        if (!s) {
191 !
514
            Py_DECREF(list);
515
            return nullptr;
×
516
        }
517
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
191 ✔
518
    }
519
    return list;
104 ✔
520
}
105 ✔
521

522
PyObject* DataFrame_is_duplicated(PyObject* self, PyObject*) {
3 ✔
523
    DataFrameObject* b = as_dataframe(self);
3 ✔
524
    if (!b) return nullptr;
3 !
525
    try {
526
        return dftracer::utils::python::wrap_vec_column(
3 !
527
            dataframe::is_duplicated(to_dataframe(b)));
6 !
528
    } catch (const std::exception& e) {
×
529
        PyErr_SetString(PyExc_ValueError, e.what());
×
530
        return nullptr;
×
531
    }
×
532
}
533

534
PyObject* DataFrame_is_unique(PyObject* self, PyObject*) {
1 ✔
535
    DataFrameObject* b = as_dataframe(self);
1 ✔
536
    if (!b) return nullptr;
1 !
537
    try {
538
        return dftracer::utils::python::wrap_vec_column(
1 !
539
            dataframe::is_unique(to_dataframe(b)));
2 !
540
    } catch (const std::exception& e) {
×
541
        PyErr_SetString(PyExc_ValueError, e.what());
×
542
        return nullptr;
×
543
    }
×
544
}
545

546
PyObject* DataFrame_column_index(PyObject* self, PyObject* arg) {
2 ✔
547
    DataFrameObject* b = as_dataframe(self);
2 ✔
548
    if (!b) return nullptr;
2 !
549
    const char* name = PyUnicode_AsUTF8(arg);
2 ✔
550
    if (!name) {
2 !
551
        PyErr_SetString(PyExc_TypeError, "column_index() expects a str");
×
552
        return nullptr;
×
553
    }
554
    return PyLong_FromLongLong(to_dataframe(b).column_index(name));
2 !
555
}
556

557
PyObject* DataFrame_head(PyObject* self, PyObject* arg) {
36 ✔
558
    DataFrameObject* b = as_dataframe(self);
36 !
559
    if (!b) return nullptr;
36 !
560
    long long n = PyLong_AsLongLong(arg);
36 !
561
    if (n == -1 && PyErr_Occurred()) return nullptr;
36 !
562
    return run_batch_op([&] { return dataframe::head(to_dataframe(b), n); });
108 !
563
}
564

565
PyObject* DataFrame_slice(PyObject* self, PyObject* args) {
8 ✔
566
    DataFrameObject* b = as_dataframe(self);
8 !
567
    if (!b) return nullptr;
8 !
568
    long long offset = 0, length = 0;
8 ✔
569
    if (!PyArg_ParseTuple(args, "LL", &offset, &length)) return nullptr;
8 !
570
    return run_batch_op(
16 !
571
        [&] { return dataframe::slice(to_dataframe(b), offset, length); });
24 !
572
}
573

574
PyObject* DataFrame_sort_by(PyObject* self, PyObject* args, PyObject* kwds) {
81 ✔
575
    DataFrameObject* b = as_dataframe(self);
81 !
576
    if (!b) return nullptr;
81 !
577
    const char* name = nullptr;
81 ✔
578
    int descending = 0;
81 ✔
579
    static const char* kwlist[] = {"name", "descending", nullptr};
580
    if (!PyArg_ParseTupleAndKeywords(
81 !
581
            args, kwds, "s|p", const_cast<char**>(kwlist), &name, &descending))
582
        return nullptr;
×
583
    return run_batch_op([&] {
162 !
584
        return dataframe::sort_by(to_dataframe(b), name, descending != 0);
162 !
585
    });
81 ✔
586
}
587

588
PyObject* DataFrame_topk(PyObject* self, PyObject* args, PyObject* kwds) {
10 ✔
589
    DataFrameObject* b = as_dataframe(self);
10 !
590
    if (!b) return nullptr;
10 !
591
    const char* name = nullptr;
10 ✔
592
    Py_ssize_t k = 0;
10 ✔
593
    int largest = 1;
10 ✔
594
    static const char* kwlist[] = {"name", "k", "largest", nullptr};
595
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "sn|p",
10 !
596
                                     const_cast<char**>(kwlist), &name, &k,
597
                                     &largest))
598
        return nullptr;
×
599
    return run_batch_op([&] {
20 !
600
        return dataframe::topk(to_dataframe(b), name,
20 !
601
                               static_cast<std::int64_t>(k), largest != 0);
30 !
602
    });
10 ✔
603
}
604

605
PyObject* DataFrame_partition_id(PyObject* self, PyObject* args) {
3 ✔
606
    DataFrameObject* b = as_dataframe(self);
3 !
607
    if (!b) return nullptr;
3 !
608
    PyObject* keys_obj = nullptr;
3 ✔
609
    Py_ssize_t n_parts = 0;
3 ✔
610
    if (!PyArg_ParseTuple(args, "On", &keys_obj, &n_parts)) return nullptr;
3 !
611
    std::vector<std::string> keys;
3 ✔
612
    if (PyUnicode_Check(keys_obj)) {
3 !
613
        keys.emplace_back(PyUnicode_AsUTF8(keys_obj));
3 !
614
    } else if (!parse_string_seq(keys_obj, "keys must be a str or list",
×
615
                                 keys)) {
616
        return nullptr;
×
617
    }
618
    try {
619
        return dftracer::utils::python::wrap_vec_column(dataframe::partition_id(
4 !
620
            to_dataframe(b), keys, static_cast<std::int64_t>(n_parts)));
9 !
621
    } catch (const std::out_of_range& e) {
2 !
622
        PyErr_SetString(PyExc_KeyError, e.what());
1 !
623
        return nullptr;
1 ✔
624
    } catch (const std::exception& e) {
2 ✔
625
        PyErr_SetString(PyExc_ValueError, e.what());
1 !
626
        return nullptr;
1 ✔
627
    }
1 ✔
628
}
3 ✔
629

630
// hash_partition(keys, n_parts) -> list[DataFrame]; keys is a name or a
631
// sequence of names. The shuffle primitive for distributed group_by/join.
632
PyObject* DataFrame_hash_partition(PyObject* self, PyObject* args) {
1 ✔
633
    DataFrameObject* b = as_dataframe(self);
1 !
634
    if (!b) return nullptr;
1 !
635
    PyObject* keys_obj = nullptr;
1 ✔
636
    Py_ssize_t n_parts = 0;
1 ✔
637
    if (!PyArg_ParseTuple(args, "On", &keys_obj, &n_parts)) return nullptr;
1 !
638

639
    std::vector<std::string> keys;
1 ✔
640
    if (PyUnicode_Check(keys_obj)) {
1 !
641
        keys.emplace_back(PyUnicode_AsUTF8(keys_obj));
×
642
    } else if (!parse_string_seq(keys_obj, "keys must be a str or list",
1 !
643
                                 keys)) {
644
        return nullptr;
×
645
    }
646

647
    std::vector<DataFrame> parts;
1 ✔
648
    try {
649
        parts = dataframe::hash_partition(to_dataframe(b), keys,
2 !
650
                                          static_cast<std::int64_t>(n_parts));
1 ✔
651
    } catch (const std::exception& e) {
×
652
        PyErr_SetString(PyExc_ValueError, e.what());
×
653
        return nullptr;
×
654
    }
×
655
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(parts.size()));
1 !
656
    if (!list) return nullptr;
1 !
657
    for (std::size_t i = 0; i < parts.size(); ++i) {
5 ✔
658
        PyObject* vb = make_dataframe(std::move(parts[i]));
4 !
659
        if (!vb) {
4 !
660
            Py_DECREF(list);
661
            return nullptr;
×
662
        }
663
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), vb);
4 ✔
664
    }
665
    return list;
1 ✔
666
}
1 ✔
667

668
// _group_agg_expr(key, specs): the expression-aggregate workhorse. `key` is a
669
// column name or a sequence of names (composite key). `specs` is a list of
670
// (op_int, value_ast_or_None, out_name[, param[, by_ast]]); value ASTs
671
// reference this batch's columns by index. `by_ast` is ArgMax's maximized
672
// value. All value expressions compile in one CSE'd, pruned pass
673
// (dataframe::group_agg_expr). The Python GroupBy serializes to this.
674
PyObject* DataFrame_group_agg_expr(PyObject* self, PyObject* args) {
70 ✔
675
    DataFrameObject* b = as_dataframe(self);
70 !
676
    if (!b) return nullptr;
70 !
677
    PyObject* key_obj = nullptr;
70 ✔
678
    PyObject* specs = nullptr;
70 ✔
679
    if (!PyArg_ParseTuple(args, "OO", &key_obj, &specs)) return nullptr;
70 !
680
    std::vector<std::string> keys;
70 ✔
681
    if (!strings_from_str_or_seq(key_obj, keys)) return nullptr;
70 !
682
    PyObject* seq = PySequence_Fast(specs, "specs must be a sequence");
70 !
683
    if (!seq) return nullptr;
70 !
684

685
    DataFrame bat = to_dataframe(b);
70 !
686
    std::vector<dataframe::Expr> key_exprs;
70 ✔
687
    key_exprs.reserve(keys.size());
70 !
688
    for (const std::string& key : keys) {
108 ✔
689
        std::int32_t ki = -1;
38 ✔
690
        for (std::size_t i = 0; i < bat.names.size(); ++i)
44 !
691
            if (bat.names[i] == key) {
44 ✔
692
                ki = static_cast<std::int32_t>(i);
38 ✔
693
                break;
38 ✔
694
            }
695
        if (ki < 0) {
38 !
696
            Py_DECREF(seq);
697
            PyErr_Format(PyExc_KeyError, "group_by: no column named %s",
×
698
                         key.c_str());
699
            return nullptr;
×
700
        }
701
        key_exprs.push_back(dataframe::expr_col(ki));
38 !
702
    }
703

704
    std::vector<dataframe::AggExprSpec> aggs;
70 ✔
705
    Py_ssize_t ns = PySequence_Fast_GET_SIZE(seq);
70 !
706
    aggs.reserve(static_cast<std::size_t>(ns));
70 !
707
    for (Py_ssize_t i = 0; i < ns; ++i) {
206 ✔
708
        PyObject* t = PySequence_Fast_GET_ITEM(seq, i);
136 !
709
        const Py_ssize_t tn = PyTuple_Check(t) ? PyTuple_GET_SIZE(t) : 0;
136 !
710
        if (tn != 3 && tn != 4 && tn != 5) {
136 !
711
            Py_DECREF(seq);
712
            PyErr_SetString(PyExc_TypeError,
×
713
                            "each spec is (op, ast, out[, param[, by_ast]])");
714
            return nullptr;
×
715
        }
716
        dataframe::AggExprSpec s;
136 ✔
717
        s.op = static_cast<dataframe::AggOp>(
136 ✔
718
            PyLong_AsLong(PyTuple_GET_ITEM(t, 0)));
136 !
719
        if (tn >= 4) {
136 !
720
            s.param = PyFloat_AsDouble(PyTuple_GET_ITEM(t, 3));
136 !
721
            if (s.param == -1.0 && PyErr_Occurred()) {
136 !
722
                Py_DECREF(seq);
723
                return nullptr;
×
724
            }
725
        }
726
        PyObject* ast = PyTuple_GET_ITEM(t, 1);
136 !
727
        if (ast != Py_None) {
136 ✔
728
            dataframe::Expr v;
134 ✔
729
            if (!dftracer::utils::python::build_expr_from_ast(ast, &v)) {
134 !
730
                Py_DECREF(seq);
731
                return nullptr;
×
732
            }
733
            s.value = std::move(v);
134 ✔
734
        }
134 !
735
        if (tn == 5) {
136 ✔
736
            PyObject* by_ast = PyTuple_GET_ITEM(t, 4);
82 !
737
            if (by_ast != Py_None) {
82 !
738
                dataframe::Expr by;
82 ✔
739
                if (!dftracer::utils::python::build_expr_from_ast(by_ast,
82 !
740
                                                                  &by)) {
741
                    Py_DECREF(seq);
742
                    return nullptr;
×
743
                }
744
                s.by = std::move(by);
82 ✔
745
            }
82 !
746
        }
747
        const char* out = PyUnicode_AsUTF8(PyTuple_GET_ITEM(t, 2));
136 !
748
        if (!out) {
136 !
749
            Py_DECREF(seq);
750
            return nullptr;
×
751
        }
752
        s.out = out;
136 !
753
        aggs.push_back(std::move(s));
136 !
754
    }
136 !
755
    Py_DECREF(seq);
756

757
    std::vector<const Series*> inputs;
70 ✔
758
    inputs.reserve(bat.columns.size());
70 !
759
    for (const Series& c : bat.columns) inputs.push_back(&c);
298 !
760
    return run_batch_op([&] {
70 !
761
        return dataframe::group_agg_expr(key_exprs, aggs, inputs, keys);
70 ✔
762
    });
70 ✔
763
}
70 ✔
764

765
// Two-step / expression forms delegate to the Python GroupBy, which serializes
766
// each spec and calls _group_agg_expr. `args[0:nk]` are the key names (a tuple,
767
// even for one key); `args[nk:]` are the specs.
768
PyObject* delegate_groupby(PyObject* self, PyObject* args, Py_ssize_t nk) {
2 ✔
769
    PyObject* mod = PyImport_ImportModule("dftracer.utils.columnar");
2 ✔
770
    if (!mod) return nullptr;
2 !
771
    PyObject* gb_type = PyObject_GetAttrString(mod, "GroupBy");
2 ✔
772
    Py_DECREF(mod);
773
    if (!gb_type) return nullptr;
2 !
774
    PyObject* keys = PyTuple_GetSlice(args, 0, nk);
2 ✔
775
    if (!keys) {
2 !
776
        Py_DECREF(gb_type);
777
        return nullptr;
×
778
    }
779
    PyObject* gb = PyObject_CallFunctionObjArgs(gb_type, self, keys, nullptr);
2 ✔
780
    Py_DECREF(keys);
781
    Py_DECREF(gb_type);
782
    if (!gb) return nullptr;
2 !
783
    Py_ssize_t n = PyTuple_GET_SIZE(args);
2 ✔
784
    if (n == nk) return gb;             // two-step: hand back the GroupBy
2 ✔
785
    PyObject* rest =
786
        PyTuple_GetSlice(args, nk, n);  // the specs, as an arg tuple
1 ✔
787
    PyObject* aggm = rest ? PyObject_GetAttrString(gb, "agg") : nullptr;
1 !
788
    Py_DECREF(gb);
789
    PyObject* res = aggm ? PyObject_Call(aggm, rest, nullptr) : nullptr;
1 !
790
    Py_XDECREF(aggm);
1 ✔
791
    Py_XDECREF(rest);
1 ✔
792
    return res;
1 ✔
793
}
794

795
// group_by(*keys_and_specs). The leading run of plain column-name strings
796
// (not "count" and not containing ':') are the (possibly composite) key; a
797
// trailing run of legacy "op[:column]" strings runs inline, anything else
798
// (no specs, or an expression/Agg spec) delegates to the Python GroupBy and
799
// the expression-aggregate path (CSE + pruner).
800
PyObject* DataFrame_group_by(PyObject* self, PyObject* args) {
204 ✔
801
    DataFrameObject* b = as_dataframe(self);
204 !
802
    if (!b) return nullptr;
204 !
803
    Py_ssize_t n = PyTuple_GET_SIZE(args);
204 ✔
804
    if (n < 1) {
204 !
805
        PyErr_SetString(PyExc_TypeError, "group_by(*keys, *aggs) needs a key");
×
806
        return nullptr;
×
807
    }
808
    Py_ssize_t nk = 0;
204 ✔
809
    for (; nk < n; ++nk) {
437 ✔
810
        PyObject* a = PyTuple_GET_ITEM(args, nk);
436 !
811
        if (!PyUnicode_Check(a)) break;
638 ✔
812
        const char* s = PyUnicode_AsUTF8(a);
435 !
813
        if (!s) return nullptr;
435 !
814
        const std::string sv(s);
435 !
815
        if (sv == "count" || sv.find(':') != std::string::npos) break;
435 ✔
816
    }
435 ✔
817
    if (nk == 0) nk = 1;  // args[0] is always at least one key
204 !
818
    bool rest_legacy = n > nk;
204 ✔
819
    for (Py_ssize_t i = nk; i < n && rest_legacy; ++i)
889 ✔
820
        rest_legacy = PyUnicode_Check(PyTuple_GET_ITEM(args, i)) != 0;
685 !
821
    if (n == nk || !rest_legacy) return delegate_groupby(self, args, nk);
204 !
822

823
    std::vector<std::string> keys;
202 ✔
824
    keys.reserve(static_cast<std::size_t>(nk));
202 !
825
    for (Py_ssize_t i = 0; i < nk; ++i) {
432 ✔
826
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
230 !
827
        if (!s) return nullptr;
230 !
828
        keys.emplace_back(s);
230 !
829
    }
830
    std::vector<std::string> specs;
202 ✔
831
    specs.reserve(static_cast<std::size_t>(n - nk));
202 !
832
    for (Py_ssize_t i = nk; i < n; ++i) {
886 ✔
833
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
684 !
834
        if (!s) return nullptr;
684 !
835
        specs.emplace_back(s);
684 !
836
    }
837
    return run_batch_op([&] {
404 !
838
        std::vector<dataframe::GroupAgg> aggs;
202 ✔
839
        aggs.reserve(specs.size());
202 !
840
        for (const std::string& spec : specs)
886 ✔
841
            aggs.push_back(group_agg_from_spec(spec));
684 !
842
        return dataframe::group_by(to_dataframe(b), keys, aggs);
599 !
843
    });
404 ✔
844
}
202 ✔
845

846
// join(other, how="inner", on=1): equi-join on the first `on` (leading) key
847
// columns; how is inner|left|right|full|semi|anti.
848
PyObject* DataFrame_join(PyObject* self, PyObject* args, PyObject* kwds) {
111 ✔
849
    DataFrameObject* b = as_dataframe(self);
111 !
850
    if (!b) return nullptr;
111 !
851
    PyObject* other = nullptr;
111 ✔
852
    PyObject* on = nullptr;
111 ✔
853
    const char* how = "inner";
111 ✔
854
    PyObject* left_on = nullptr;
111 ✔
855
    PyObject* right_on = nullptr;
111 ✔
856
    const char* suffix = "_right";
111 ✔
857
    int nulls_equal = 0;
111 ✔
858
    static const char* kwlist[] = {"other",       "on",       "how",
859
                                   "left_on",     "right_on", "suffix",
860
                                   "nulls_equal", nullptr};
861
    if (!PyArg_ParseTupleAndKeywords(
111 !
862
            args, kwds, "O|OsOOsp", const_cast<char**>(kwlist), &other, &on,
863
            &how, &left_on, &right_on, &suffix, &nulls_equal))
864
        return nullptr;
×
865
    DataFrameObject* o = as_dataframe(other);
111 !
866
    if (!o) return nullptr;
111 !
867
    dataframe::JoinHow jh;
868
    if (!join_how_from_str(how, jh)) return nullptr;
111 !
869
    std::vector<std::string> l;
110 ✔
870
    std::vector<std::string> r;
110 ✔
871
    if (!join_keys_from_objs(on, left_on, right_on, jh, l, r)) return nullptr;
110 !
872
    return run_batch_op([&] {
210 !
873
        return dataframe::join(to_dataframe(b), to_dataframe(o), l, r, jh,
220 !
874
                               suffix, nulls_equal != 0);
320 !
875
    });
105 ✔
876
}
110 ✔
877

878
PyObject* DataFrame_compare_agg(PyObject* self, PyObject* args) {
5 ✔
879
    DataFrameObject* b = as_dataframe(self);
5 !
880
    if (!b) return nullptr;
5 !
881
    PyObject* other = nullptr;
5 ✔
882
    Py_ssize_t n_key = 1;
5 ✔
883
    if (!PyArg_ParseTuple(args, "On", &other, &n_key)) return nullptr;
5 !
884
    DataFrameObject* o = as_dataframe(other);
5 !
885
    if (!o) return nullptr;
5 !
886
    return run_batch_op([&] {
10 !
887
        return dataframe::compare_agg(to_dataframe(b), to_dataframe(o),
11 !
888
                                      static_cast<std::int64_t>(n_key));
14 ✔
889
    });
5 ✔
890
}
891

892
// unpivot(id_vars, value_vars) / melt: reshape wide -> long.
893
PyObject* DataFrame_unpivot(PyObject* self, PyObject* args, PyObject* kwds) {
8 ✔
894
    DataFrameObject* b = as_dataframe(self);
8 !
895
    if (!b) return nullptr;
8 !
896
    PyObject* id_obj = nullptr;
8 ✔
897
    PyObject* val_obj = nullptr;
8 ✔
898
    static const char* kwlist[] = {"id_vars", "value_vars", nullptr};
899
    if (!PyArg_ParseTupleAndKeywords(
8 !
900
            args, kwds, "OO", const_cast<char**>(kwlist), &id_obj, &val_obj))
901
        return nullptr;
×
902
    std::vector<std::string> id_vars, value_vars;
8 ✔
903
    if (!names_from_obj(id_obj, id_vars)) return nullptr;
8 !
904
    if (!names_from_obj(val_obj, value_vars)) return nullptr;
8 !
905
    return run_batch_op([&] {
16 !
906
        return dataframe::unpivot(to_dataframe(b), id_vars, value_vars);
16 !
907
    });
8 ✔
908
}
8 ✔
909

910
PyObject* DataFrame_explode(PyObject* self, PyObject* arg) {
7 ✔
911
    DataFrameObject* b = as_dataframe(self);
7 !
912
    if (!b) return nullptr;
7 !
913
    const char* name = PyUnicode_AsUTF8(arg);
7 !
914
    if (!name) {
7 !
915
        PyErr_SetString(PyExc_TypeError, "explode() expects a column name");
×
916
        return nullptr;
×
917
    }
918
    return run_batch_op(
14 !
919
        [&] { return dataframe::explode(to_dataframe(b), name); });
21 !
920
}
921

922
PyObject* DataFrame_window(PyObject* self, PyObject* args, PyObject* kwds) {
28 ✔
923
    DataFrameObject* b = as_dataframe(self);
28 !
924
    if (!b) return nullptr;
28 !
925
    static const char* kwlist[] = {"partition_by", "order_by", "specs",
926
                                   nullptr};
927
    PyObject* part = nullptr;
28 ✔
928
    PyObject* order = nullptr;
28 ✔
929
    PyObject* specs = nullptr;
28 ✔
930
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO",
28 !
931
                                     const_cast<char**>(kwlist), &part, &order,
932
                                     &specs))
933
        return nullptr;
×
934
    std::vector<std::string> pcols;
28 ✔
935
    std::vector<std::string> ocols;
28 ✔
936
    if (!parse_string_seq(part, "window: partition_by must be names", pcols) ||
56 !
937
        !parse_string_seq(order, "window: order_by must be names", ocols))
28 !
938
        return nullptr;
×
939
    dftracer::utils::python::WindowSpecs parsed;
28 !
940
    if (!dftracer::utils::python::parse_window_specs(specs, parsed))
28 !
941
        return nullptr;
×
942
    std::vector<dataframe::WindowColumn> specv;
28 ✔
943
    specv.reserve(parsed.specs.size());
28 !
944
    for (const dftu_window_spec& w : parsed.specs)
102 ✔
945
        specv.push_back(dataframe::window_column(w));
74 !
946
    return run_batch_op([&] {
28 !
947
        return dataframe::window(to_dataframe(b), pcols, ocols, specv);
50 ✔
948
    });
28 ✔
949
}
28 ✔
950

951
PyObject* DataFrame_gap_fill(PyObject* self, PyObject* args, PyObject* kwds) {
10 ✔
952
    DataFrameObject* b = as_dataframe(self);
10 !
953
    if (!b) return nullptr;
10 !
954
    static const char* kwlist[] = {"partition_by", "time",  "bucket", "values",
955
                                   "mode",         "start", "end",    nullptr};
956
    PyObject* part = nullptr;
10 ✔
957
    const char* time = nullptr;
10 ✔
958
    long long bucket = 0;
10 ✔
959
    PyObject* values = nullptr;
10 ✔
960
    const char* mode = nullptr;
10 ✔
961
    PyObject* start_obj = Py_None;
10 ✔
962
    PyObject* end_obj = Py_None;
10 ✔
963
    if (!PyArg_ParseTupleAndKeywords(
10 !
964
            args, kwds, "OsLOs|OO", const_cast<char**>(kwlist), &part, &time,
965
            &bucket, &values, &mode, &start_obj, &end_obj))
966
        return nullptr;
×
967
    dftu_gap_fill_mode mode_code;
968
    if (!dftracer::utils::python::gap_fill_mode_from_str(mode, &mode_code))
10 !
969
        return nullptr;
1 ✔
970
    const auto m = static_cast<dataframe::GapFillMode>(mode_code);
9 ✔
971
    std::vector<std::string> pcols;
9 ✔
972
    std::vector<std::string> vcols;
9 ✔
973
    if (!parse_string_seq(part, "gap_fill: partition_by must be names",
9 !
974
                          pcols) ||
18 !
975
        !parse_string_seq(values, "gap_fill: values must be names", vcols))
9 !
976
        return nullptr;
×
977
    std::optional<std::pair<std::int64_t, std::int64_t>> range;
9 ✔
978
    if (start_obj != Py_None) {
9 ✔
979
        const long long s = PyLong_AsLongLong(start_obj);
2 !
980
        const long long e = PyLong_AsLongLong(end_obj);
2 !
981
        if (PyErr_Occurred()) return nullptr;
2 !
982
        range = std::make_pair(static_cast<std::int64_t>(s),
×
983
                               static_cast<std::int64_t>(e));
2 !
984
    }
985
    return run_batch_op([&] {
18 !
986
        return dataframe::gap_fill(to_dataframe(b), pcols, time,
18 !
987
                                   static_cast<std::int64_t>(bucket), vcols, m,
9 ✔
988
                                   range);
27 !
989
    });
9 ✔
990
}
9 ✔
991

992
PyObject* DataFrame_asof(PyObject* self, PyObject* args, PyObject* kwds) {
27 ✔
993
    DataFrameObject* b = as_dataframe(self);
27 !
994
    if (!b) return nullptr;
27 !
995
    static const char* kwlist[] = {"other",     "on",        "by",
996
                                   "direction", "tolerance", nullptr};
997
    PyObject* other = nullptr;
27 ✔
998
    const char* on = nullptr;
27 ✔
999
    PyObject* by = nullptr;
27 ✔
1000
    const char* direction = nullptr;
27 ✔
1001
    PyObject* tol_obj = Py_None;
27 ✔
1002
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OsOsO",
27 !
1003
                                     const_cast<char**>(kwlist), &other, &on,
1004
                                     &by, &direction, &tol_obj))
1005
        return nullptr;
×
1006
    DataFrameObject* o = as_dataframe(other);
27 !
1007
    if (!o) return nullptr;
27 !
1008
    dftu_asof_direction dir_code;
1009
    if (!dftracer::utils::python::asof_direction_from_str(direction, &dir_code))
27 !
1010
        return nullptr;
1 ✔
1011
    const auto dir = static_cast<dataframe::AsofDirection>(dir_code);
26 ✔
1012
    std::vector<std::string> equi;
26 ✔
1013
    if (!parse_string_seq(by, "asof: by must be names", equi)) return nullptr;
26 !
1014
    std::optional<double> tol;
26 ✔
1015
    if (tol_obj != Py_None) {
26 ✔
1016
        const double t = PyFloat_AsDouble(tol_obj);
14 !
1017
        if (PyErr_Occurred()) return nullptr;
14 !
1018
        if (!(t >= 0)) {
14 !
1019
            PyErr_SetString(PyExc_ValueError,
×
1020
                            "asof: tolerance must not be negative");
1021
            return nullptr;
×
1022
        }
1023
        tol = t;
14 ✔
1024
    }
1025
    return run_batch_op([&] {
52 !
1026
        return dataframe::asof(to_dataframe(b), to_dataframe(o), on, equi, dir,
52 !
1027
                               tol);
78 !
1028
    });
26 ✔
1029
}
26 ✔
1030

1031
PyObject* DataFrame_interval(PyObject* self, PyObject* args, PyObject* kwds) {
10 ✔
1032
    DataFrameObject* b = as_dataframe(self);
10 !
1033
    if (!b) return nullptr;
10 !
1034
    static const char* kwlist[] = {"other", "point", "lo",   "hi",
1035
                                   "by",    "outer", nullptr};
1036
    PyObject* other = nullptr;
10 ✔
1037
    const char* point = nullptr;
10 ✔
1038
    const char* lo = nullptr;
10 ✔
1039
    const char* hi = nullptr;
10 ✔
1040
    PyObject* by = nullptr;
10 ✔
1041
    int outer = 0;
10 ✔
1042
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OsssOp",
10 !
1043
                                     const_cast<char**>(kwlist), &other, &point,
1044
                                     &lo, &hi, &by, &outer))
1045
        return nullptr;
×
1046
    DataFrameObject* o = as_dataframe(other);
10 !
1047
    if (!o) return nullptr;
10 !
1048
    std::vector<std::string> equi;
10 ✔
1049
    if (!parse_string_seq(by, "interval: by must be names", equi))
10 !
1050
        return nullptr;
×
1051
    return run_batch_op([&] {
20 !
1052
        return dataframe::interval(to_dataframe(b), to_dataframe(o), point, lo,
20 !
1053
                                   hi, equi, outer != 0);
30 !
1054
    });
10 ✔
1055
}
10 ✔
1056

1057
PyObject* DataFrame_unnest(PyObject* self, PyObject* args, PyObject* kwds) {
8 ✔
1058
    DataFrameObject* b = as_dataframe(self);
8 !
1059
    if (!b) return nullptr;
8 !
1060
    const char* name = nullptr;
8 ✔
1061
    int keep_empty = 0;
8 ✔
1062
    static const char* kwlist[] = {"column", "keep_empty", nullptr};
1063
    if (!PyArg_ParseTupleAndKeywords(
8 !
1064
            args, kwds, "s|p", const_cast<char**>(kwlist), &name, &keep_empty))
1065
        return nullptr;
×
1066
    return run_batch_op([&] {
16 !
1067
        return dataframe::unnest(to_dataframe(b), name, keep_empty != 0);
17 !
1068
    });
8 ✔
1069
}
1070

1071
PyObject* DataFrame_to_dummies(PyObject* self, PyObject* arg) {
3 ✔
1072
    DataFrameObject* b = as_dataframe(self);
3 !
1073
    if (!b) return nullptr;
3 !
1074
    const char* name = PyUnicode_AsUTF8(arg);
3 !
1075
    if (!name) {
3 !
1076
        PyErr_SetString(PyExc_TypeError, "to_dummies() expects a column name");
×
1077
        return nullptr;
×
1078
    }
1079
    return run_batch_op(
6 !
1080
        [&] { return dataframe::to_dummies(to_dataframe(b), name); });
9 !
1081
}
1082

1083
// pivot(index, columns, values, agg="first"): long -> wide.
1084
PyObject* DataFrame_pivot(PyObject* self, PyObject* args, PyObject* kwds) {
9 ✔
1085
    DataFrameObject* b = as_dataframe(self);
9 !
1086
    if (!b) return nullptr;
9 !
1087
    const char* index = nullptr;
9 ✔
1088
    const char* columns = nullptr;
9 ✔
1089
    const char* values = nullptr;
9 ✔
1090
    const char* agg = "first";
9 ✔
1091
    static const char* kwlist[] = {"index", "columns", "values", "agg",
1092
                                   nullptr};
1093
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "sss|s",
9 !
1094
                                     const_cast<char**>(kwlist), &index,
1095
                                     &columns, &values, &agg))
1096
        return nullptr;
×
1097
    return run_batch_op([&] {
18 !
1098
        return dataframe::pivot(to_dataframe(b), index, columns, values, agg);
18 !
1099
    });
9 ✔
1100
}
1101

1102
// group_by_dynamic(time_col, every, period=None, aggs=[...]): tumbling/sliding
1103
// time-window aggregation. aggs mirror the group_by string-spec format.
1104
PyObject* DataFrame_group_by_dynamic(PyObject* self, PyObject* args,
18 ✔
1105
                                     PyObject* kwds) {
1106
    DataFrameObject* b = as_dataframe(self);
18 !
1107
    if (!b) return nullptr;
18 !
1108
    const char* time_col = nullptr;
18 ✔
1109
    long long every = 0;
18 ✔
1110
    PyObject* period_obj = Py_None;
18 ✔
1111
    PyObject* aggs_obj = Py_None;
18 ✔
1112
    PyObject* origin_obj = Py_None;  // int (explicit) or "min"
18 ✔
1113
    static const char* kwlist[] = {"time_col", "every",  "period",
1114
                                   "aggs",     "origin", nullptr};
1115
    if (!PyArg_ParseTupleAndKeywords(
18 !
1116
            args, kwds, "sL|OOO", const_cast<char**>(kwlist), &time_col, &every,
1117
            &period_obj, &aggs_obj, &origin_obj))
1118
        return nullptr;
×
1119
    std::int64_t period = 0;
18 ✔
1120
    if (period_obj && period_obj != Py_None) {
18 !
1121
        period = PyLong_AsLongLong(period_obj);
1 !
1122
        if (period == -1 && PyErr_Occurred()) return nullptr;
1 !
1123
    }
1124
    std::int64_t origin = 0;
18 ✔
1125
    bool origin_min = false;
18 ✔
1126
    if (origin_obj && origin_obj != Py_None) {
18 !
1127
        if (PyUnicode_Check(origin_obj)) {
2 ✔
1128
            const char* s = PyUnicode_AsUTF8(origin_obj);
1 !
1129
            if (!s) return nullptr;
1 !
1130
            if (std::string(s) != "min") {
1 !
1131
                PyErr_SetString(PyExc_ValueError,
×
1132
                                "group_by_dynamic: origin must be an int or "
1133
                                "\"min\"");
1134
                return nullptr;
×
1135
            }
1136
            origin_min = true;
1 ✔
1137
        } else {
1138
            origin = PyLong_AsLongLong(origin_obj);
1 !
1139
            if (origin == -1 && PyErr_Occurred()) return nullptr;
1 !
1140
        }
1141
    }
1142
    std::vector<dataframe::GroupAgg> aggs;
18 ✔
1143
    if (aggs_obj && aggs_obj != Py_None && !aggs_from_seq(aggs_obj, aggs))
18 !
1144
        return nullptr;
×
1145
    return run_batch_op([&] {
36 !
1146
        return dataframe::group_by_dynamic(to_dataframe(b), time_col,
36 !
1147
                                           static_cast<std::int64_t>(every),
18 ✔
1148
                                           period, aggs, origin, origin_min);
54 !
1149
    });
18 ✔
1150
}
18 ✔
1151

1152
PyObject* DataFrame_concat(PyObject* self, PyObject* args, PyObject* kwds) {
34 ✔
1153
    DataFrameObject* b = as_dataframe(self);
34 !
1154
    if (!b) return nullptr;
34 !
1155
    // `how` is the only keyword; every positional arg is another DataFrame.
1156
    dataframe::ConcatHow how = dataframe::ConcatHow::Vertical;
34 ✔
1157
    if (kwds) {
34 ✔
1158
        if (PyObject* h = PyDict_GetItemString(kwds, "how")) {
32 !
1159
            const char* s = PyUnicode_AsUTF8(h);
32 !
1160
            if (!s) return nullptr;
32 !
1161
            if (std::strcmp(s, "diagonal") == 0)
32 ✔
1162
                how = dataframe::ConcatHow::Diagonal;
4 ✔
1163
            else if (std::strcmp(s, "vertical") != 0) {
28 ✔
1164
                PyErr_SetString(PyExc_ValueError,
1 !
1165
                                "how must be 'vertical' or 'diagonal'");
1166
                return nullptr;
1 ✔
1167
            }
1168
        }
1169
        if (PyDict_Size(kwds) > (PyDict_GetItemString(kwds, "how") ? 1 : 0)) {
31 !
1170
            PyErr_SetString(PyExc_TypeError,
×
1171
                            "concat() got an unexpected keyword argument");
1172
            return nullptr;
×
1173
        }
1174
    }
1175
    std::vector<DataFrame> owned;
33 ✔
1176
    owned.reserve(1 + static_cast<std::size_t>(PyTuple_GET_SIZE(args)));
33 !
1177
    owned.push_back(to_dataframe(b));
33 !
1178
    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(args); ++i) {
94 ✔
1179
        DataFrameObject* o = as_dataframe(PyTuple_GET_ITEM(args, i));
61 !
1180
        if (!o) return nullptr;
61 !
1181
        owned.push_back(to_dataframe(o));
61 !
1182
    }
1183
    std::vector<const DataFrame*> parts;
33 ✔
1184
    parts.reserve(owned.size());
33 !
1185
    for (const DataFrame& x : owned) parts.push_back(&x);
127 !
1186
    return run_batch_op([&] { return dataframe::concat(parts, how); });
66 !
1187
}
33 ✔
1188

1189
#ifdef DFTRACER_UTILS_ENABLE_ARROW
1190
// Arrow/pandas/polars conversion and pickling live in the Python wrapper
1191
// (dftracer.utils.frame); the native handle only exposes the zero-copy
1192
// __arrow_c_array__ / __arrow_c_stream__ capsules.
1193

1194
// The batch is one STRUCT column, so a single struct array carries every field.
1195

1196
void schema_capsule_destructor(PyObject* cap) {
1 ✔
1197
    auto* s =
1198
        static_cast<ArrowSchema*>(PyCapsule_GetPointer(cap, "arrow_schema"));
1 ✔
1199
    if (s) {
1 !
1200
        if (s->release) s->release(s);
1 !
1201
        delete s;
1 !
1202
    }
1203
}
1 ✔
1204
void array_capsule_destructor(PyObject* cap) {
1 ✔
1205
    auto* a =
1206
        static_cast<ArrowArray*>(PyCapsule_GetPointer(cap, "arrow_array"));
1 ✔
1207
    if (a) {
1 !
1208
        if (a->release) a->release(a);
1 !
1209
        delete a;
1 !
1210
    }
1211
}
1 ✔
1212

1213
PyObject* DataFrame_arrow_c_array(PyObject* self, PyObject*) {
1 ✔
1214
    DataFrameObject* b = as_dataframe(self);
1 ✔
1215
    if (!b) return nullptr;
1 !
1216
    auto* schema = new (std::nothrow) ArrowSchema{};
1 !
1217
    auto* array = new (std::nothrow) ArrowArray{};
1 !
1218
    if (!schema || !array) {
1 !
1219
        delete schema;
×
1220
        delete array;
×
1221
        return PyErr_NoMemory();
×
1222
    }
1223
    try {
1224
        dataframe::to_arrow(b->st, schema, array);
1 !
1225
    } catch (const std::exception& e) {
×
1226
        delete schema;
×
1227
        delete array;
×
1228
        PyErr_SetString(PyExc_RuntimeError, e.what());
×
1229
        return nullptr;
×
1230
    }
×
1231
    PyObject* scap =
1232
        PyCapsule_New(schema, "arrow_schema", schema_capsule_destructor);
1 ✔
1233
    if (!scap) {
1 !
1234
        if (schema->release) schema->release(schema);
×
1235
        delete schema;
×
1236
        if (array->release) array->release(array);
×
1237
        delete array;
×
1238
        return nullptr;
×
1239
    }
1240
    PyObject* acap =
1241
        PyCapsule_New(array, "arrow_array", array_capsule_destructor);
1 ✔
1242
    if (!acap) {
1 !
1243
        Py_DECREF(scap);
1244
        if (array->release) array->release(array);
×
1245
        delete array;
×
1246
        return nullptr;
×
1247
    }
1248
    PyObject* result = PyTuple_Pack(2, scap, acap);
1 ✔
1249
    Py_DECREF(scap);
1250
    Py_DECREF(acap);
1251
    return result;
1 ✔
1252
}
1253

1254
void array_stream_capsule_destructor(PyObject* cap) {
1,133 ✔
1255
    auto* s = static_cast<ArrowArrayStream*>(
1256
        PyCapsule_GetPointer(cap, "arrow_array_stream"));
1,133 ✔
1257
    if (s) {
1,133 !
1258
        if (s->release) s->release(s);
1,133 !
1259
        delete s;
1,133 !
1260
    }
1261
}
1,133 ✔
1262

1263
// __arrow_c_stream__: a stream of the struct (one batch per chunk of a
1264
// collected frame), so pa.table(batch) / pl.from_arrow(batch) import every
1265
// column zero-copy without an explicit to_arrow(). The single struct array
1266
// carries all fields.
1267
PyObject* DataFrame_arrow_c_stream(PyObject* self, PyObject*) {
1,133 ✔
1268
    DataFrameObject* b = as_dataframe(self);
1,133 !
1269
    if (!b) return nullptr;
1,133 !
1270
    ArrowSchema schema{};
1,133 ✔
1271
    std::vector<ArrowArray> arrays;
1,133 ✔
1272
    auto drop = [&] {
×
1273
        if (schema.release) schema.release(&schema);
×
1274
        for (auto& a : arrays)
×
1275
            if (a.release) a.release(&a);
×
1276
    };
×
1277
    try {
1278
        arrays = dataframe::to_arrow_batches(b->st, &schema);
1,133 !
1279
    } catch (const std::exception& e) {
×
1280
        drop();
×
1281
        PyErr_SetString(PyExc_RuntimeError, e.what());
×
1282
        return nullptr;
×
1283
    }
×
1284
    auto* stream = new (std::nothrow) ArrowArrayStream{};
1,133 !
1285
    if (!stream) {
1,133 !
1286
        drop();
×
1287
        return PyErr_NoMemory();
×
1288
    }
1289
    if (ArrowBasicArrayStreamInit(stream, &schema,
1,133 !
1290
                                  static_cast<std::int64_t>(arrays.size())) !=
2,266 !
1291
        NANOARROW_OK) {
1292
        drop();
×
1293
        delete stream;
×
1294
        PyErr_SetString(PyExc_RuntimeError,
×
1295
                        "failed to init arrow array stream");
1296
        return nullptr;
×
1297
    }
1298
    for (std::size_t i = 0; i < arrays.size(); ++i)
55,941 ✔
1299
        ArrowBasicArrayStreamSetArray(stream, static_cast<std::int64_t>(i),
54,808 !
1300
                                      &arrays[i]);
54,808 ✔
1301
    PyObject* cap = PyCapsule_New(stream, "arrow_array_stream",
1,133 !
1302
                                  array_stream_capsule_destructor);
1303
    if (!cap) {
1,133 !
1304
        if (stream->release) stream->release(stream);
×
1305
        delete stream;
×
1306
        return nullptr;
×
1307
    }
1308
    return cap;
1,133 ✔
1309
}
1,133 ✔
1310

1311
#ifdef DFTRACER_UTILS_ENABLE_ARROW_IPC
1312
// to_ipc() -> bytes: the frame serialized as an Arrow IPC stream (schema + one
1313
// record batch + EOS), so a consumer needs no pyarrow to produce .arrow bytes.
1314
PyObject* DataFrame_to_ipc(PyObject* self, PyObject*) {
2 ✔
1315
    DataFrameObject* b = as_dataframe(self);
2 ✔
1316
    if (!b) return nullptr;
2 !
1317
    try {
1318
        std::vector<std::uint8_t> bytes = to_dataframe(b).to_ipc();
2 !
1319
        return PyBytes_FromStringAndSize(
2 !
1320
            reinterpret_cast<const char*>(bytes.data()),
2 ✔
1321
            static_cast<Py_ssize_t>(bytes.size()));
4 ✔
1322
    } catch (const std::exception& e) {
2 !
1323
        PyErr_SetString(PyExc_RuntimeError, e.what());
×
1324
        return nullptr;
×
1325
    }
×
1326
}
1327
#endif
1328

1329
#endif  // DFTRACER_UTILS_ENABLE_ARROW
1330

1331
PyObject* DataFrame_to_bytes(PyObject* self, PyObject*) {
2 ✔
1332
    DataFrameObject* b = as_dataframe(self);
2 ✔
1333
    if (!b) return nullptr;
2 !
1334
    try {
1335
        const std::string bytes = dataframe::frame_to_native(to_dataframe(b));
2 !
1336
        return PyBytes_FromStringAndSize(bytes.data(),
2 !
1337
                                         static_cast<Py_ssize_t>(bytes.size()));
4 ✔
1338
    } catch (const std::exception& e) {
2 !
1339
        PyErr_SetString(PyExc_TypeError, e.what());
×
1340
        return nullptr;
×
1341
    }
×
1342
}
1343

1344
PyObject* dataframe_from_bytes(PyObject* /*self*/, PyObject* obj) {
2 ✔
1345
    Py_buffer view;
1346
    if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) return nullptr;
2 !
1347
    auto f = dataframe::frame_from_native(
1348
        std::string_view(static_cast<const char*>(view.buf),
2 ✔
1349
                         static_cast<std::size_t>(view.len)));
2 ✔
1350
    PyBuffer_Release(&view);
2 !
1351
    if (!f) {
2 !
1352
        PyErr_SetString(PyExc_ValueError,
×
1353
                        "not a DataFrame written by this version");
1354
        return nullptr;
×
1355
    }
1356
    return make_dataframe(std::move(*f));
2 !
1357
}
2 ✔
1358

1359
PyObject* DataFrame_get_num_rows(PyObject* self, void*) {
420 ✔
1360
    DataFrameObject* b = as_dataframe(self);
420 ✔
1361
    if (!b) return nullptr;
420 !
1362
    return PyLong_FromLongLong(b->st.length());
420 ✔
1363
}
1364
PyObject* DataFrame_get_num_columns(PyObject* self, void*) {
2 ✔
1365
    DataFrameObject* b = as_dataframe(self);
2 ✔
1366
    if (!b) return nullptr;
2 !
1367
    return PyLong_FromSsize_t(static_cast<Py_ssize_t>(b->names.size()));
2 ✔
1368
}
1369
PyObject* DataFrame_get_column_names(PyObject* self, void*) {
1,944 ✔
1370
    return DataFrame_keys(self, nullptr);
1,944 ✔
1371
}
1372

1373
// lazy() -> _LazyFrame: start a deferred query over a copy of this batch.
1374
PyObject* DataFrame_lazy(PyObject* self, PyObject*) {
1,070 ✔
1375
    DataFrameObject* b = as_dataframe(self);
1,070 ✔
1376
    if (!b) return nullptr;
1,070 !
1377
    try {
1378
        return dftracer::utils::python::wrap_lazyframe(
1,070 !
1379
            dataframe::lazy(to_dataframe(b)));
2,140 !
1380
    } catch (const std::exception& e) {
×
1381
        PyErr_SetString(PyExc_ValueError, e.what());
×
1382
        return nullptr;
×
1383
    }
×
1384
}
1385

1386
PyMethodDef DataFrame_methods[] = {
1387
    {"lazy", DataFrame_lazy, METH_NOARGS,
1388
     "lazy() -> _LazyFrame, a deferred query over this batch."},
1389
    {"keys", DataFrame_keys, METH_NOARGS, "Series names, in order."},
1390
    {"filter", DataFrame_filter, METH_O,
1391
     "filter(mask) -> DataFrame keeping rows where the Bool mask is true."},
1392
    {"select", DataFrame_select, METH_VARARGS,
1393
     "select(*names) -> DataFrame projecting the named columns (zero-copy)."},
1394
    {"rename", DataFrame_rename, METH_O,
1395
     "rename({old: new}) -> DataFrame with columns renamed (zero-copy)."},
1396
    {"with_column", DataFrame_with_column, METH_VARARGS,
1397
     "with_column(name, Series) -> DataFrame adding/replacing a column."},
1398
    {"take", DataFrame_take, METH_O,
1399
     "take(indices) -> DataFrame gathered at the given row indices."},
1400
    {"column_index", DataFrame_column_index, METH_O,
1401
     "column_index(name) -> int index of a column, or -1 if absent."},
1402
    {"head", DataFrame_head, METH_O,
1403
     "head(n) -> DataFrame of the first n rows."},
1404
    {"tail", DataFrame_tail, METH_O,
1405
     "tail(n) -> DataFrame of the last n rows."},
1406
    {"reverse", DataFrame_reverse, METH_NOARGS,
1407
     "reverse() -> DataFrame with rows reversed."},
1408
    {"drop_nulls", DataFrame_drop_nulls, METH_NOARGS,
1409
     "drop_nulls() -> DataFrame dropping rows null in any column."},
1410
    {"fill_null", DataFrame_fill_null, METH_O,
1411
     "fill_null(value) -> DataFrame with nulls filled in every column."},
1412
    {"unique", DFTU_PYCFUNCTION(DataFrame_unique), METH_VARARGS | METH_KEYWORDS,
1413
     "unique(subset=None) -> DataFrame with duplicate rows removed (keep "
1414
     "first), keyed on every column or on the subset names."},
1415
    {"drop_duplicates", DFTU_PYCFUNCTION(DataFrame_unique),
1416
     METH_VARARGS | METH_KEYWORDS,
1417
     "drop_duplicates(subset=None) -> DataFrame with duplicate rows removed "
1418
     "(alias of unique)."},
1419
    {"sort_by_multi", DFTU_PYCFUNCTION(DataFrame_sort_by_multi),
1420
     METH_VARARGS | METH_KEYWORDS,
1421
     "sort_by_multi(names, descending=False) -> DataFrame stably sorted "
1422
     "lexicographically by several key columns."},
1423
    {"sample", DFTU_PYCFUNCTION(DataFrame_sample), METH_VARARGS | METH_KEYWORDS,
1424
     "sample(n, seed=0) -> DataFrame deterministic n-row sample."},
1425
    {"with_row_index", DataFrame_with_row_index, METH_O,
1426
     "with_row_index(name) -> DataFrame with a prepended Int64 index column."},
1427
    {"describe", DataFrame_describe, METH_NOARGS,
1428
     "describe() -> DataFrame of per-column summary statistics."},
1429
    {"null_count", DataFrame_null_count, METH_NOARGS,
1430
     "null_count() -> 1-row DataFrame of each column's null count."},
1431
    {"reduce", DataFrame_reduce, METH_O,
1432
     "reduce(agg) -> one-row DataFrame: the aggregate named `agg` over every "
1433
     "eligible column."},
1434
    {"group_transform", DFTU_PYCFUNCTION(DataFrame_group_transform),
1435
     METH_VARARGS | METH_KEYWORDS,
1436
     "group_transform(keys, kind, n=0, method='average', ascending=True) -> "
1437
     "DataFrame: the group-wise transform `kind` (cumsum, cummax, cummin, "
1438
     "cumcount, shift, diff, pct_change, rank, ngroup, head, tail, nth) over "
1439
     "the groups of `keys`, one value per input row in input order."},
1440
    {"reduce_specs", DataFrame_reduce_specs, METH_VARARGS,
1441
     "reduce_specs(agg, keys=None) -> list[str]: the 'op:column:out' specs "
1442
     "that broadcast `agg` over every eligible non-key column, for group_by."},
1443
    {"is_duplicated", DataFrame_is_duplicated, METH_NOARGS,
1444
     "is_duplicated() -> Bool Series, true where the whole row is duplicated."},
1445
    {"is_unique", DataFrame_is_unique, METH_NOARGS,
1446
     "is_unique() -> Bool Series, true where the whole row is unique."},
1447
    {"slice", DataFrame_slice, METH_VARARGS,
1448
     "slice(offset, length) -> DataFrame of a row range."},
1449
    {"sort_by", DFTU_PYCFUNCTION(DataFrame_sort_by),
1450
     METH_VARARGS | METH_KEYWORDS,
1451
     "sort_by(name, descending=False) -> DataFrame ordered by a column."},
1452
    {"topk", DFTU_PYCFUNCTION(DataFrame_topk), METH_VARARGS | METH_KEYWORDS,
1453
     "topk(name, k, largest=True) -> DataFrame of the k best rows by a "
1454
     "column."},
1455
    {"concat", DFTU_PYCFUNCTION(DataFrame_concat), METH_VARARGS | METH_KEYWORDS,
1456
     "concat(*others, how='vertical') -> DataFrame concatenating batches. "
1457
     "how='diagonal' unions columns (null-fill absent, promote numeric)."},
1458
    {"unpivot", DFTU_PYCFUNCTION(DataFrame_unpivot),
1459
     METH_VARARGS | METH_KEYWORDS,
1460
     "unpivot(id_vars, value_vars) -> DataFrame reshaped wide->long, stacking "
1461
     "value_vars into 'variable'/'value' columns."},
1462
    {"melt", DFTU_PYCFUNCTION(DataFrame_unpivot), METH_VARARGS | METH_KEYWORDS,
1463
     "melt(id_vars, value_vars) -> DataFrame (alias of unpivot)."},
1464
    {"explode", DataFrame_explode, METH_O,
1465
     "explode(column) -> DataFrame expanding a List column, one row per "
1466
     "element (empty/null list -> one null row)."},
1467
    {"window", DFTU_PYCFUNCTION(DataFrame_window), METH_VARARGS | METH_KEYWORDS,
1468
     "window(partition_by, order_by, specs) -> DataFrame: SQL window "
1469
     "functions; specs are normalized 12-tuples."},
1470
    {"gap_fill", DFTU_PYCFUNCTION(DataFrame_gap_fill),
1471
     METH_VARARGS | METH_KEYWORDS,
1472
     "gap_fill(partition_by, time, bucket, values, mode, start=None, "
1473
     "end=None) -> DataFrame: a regular time grid with none/locf/linear "
1474
     "fills."},
1475
    {"asof", DFTU_PYCFUNCTION(DataFrame_asof), METH_VARARGS | METH_KEYWORDS,
1476
     "asof(other, on, by, direction, tolerance) -> DataFrame: temporal "
1477
     "nearest-match join."},
1478
    {"interval", DFTU_PYCFUNCTION(DataFrame_interval),
1479
     METH_VARARGS | METH_KEYWORDS,
1480
     "interval(other, point, lo, hi, by, outer) -> DataFrame: point-in-range "
1481
     "join."},
1482
    {"unnest", DFTU_PYCFUNCTION(DataFrame_unnest), METH_VARARGS | METH_KEYWORDS,
1483
     "unnest(column, keep_empty=False) -> DataFrame expanding a List column "
1484
     "one row per element; an empty/null list drops the row unless "
1485
     "keep_empty, and a List<Struct> flattens into one column per field."},
1486
    {"to_dummies", DataFrame_to_dummies, METH_O,
1487
     "to_dummies(column) -> DataFrame one-hot encoding a column into one Int8 "
1488
     "column per distinct value, named <column>_<value>."},
1489
    {"pivot", DFTU_PYCFUNCTION(DataFrame_pivot), METH_VARARGS | METH_KEYWORDS,
1490
     "pivot(index, columns, values, agg='first') -> DataFrame reshaping "
1491
     "long->wide; agg is first|last|sum|min|max|mean."},
1492
    {"group_by_dynamic", DFTU_PYCFUNCTION(DataFrame_group_by_dynamic),
1493
     METH_VARARGS | METH_KEYWORDS,
1494
     "group_by_dynamic(time_col, every, period=None, aggs=[...]) -> DataFrame "
1495
     "tumbling/sliding time-window aggregation; aggs are 'count' / "
1496
     "'<op>:<column>'."},
1497
    {"query", DFTU_PYCFUNCTION(DataFrame_query), METH_VARARGS | METH_KEYWORDS,
1498
     "query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None, "
1499
     "descending=False, limit=None) -> DataFrame; a query plan "
1500
     "(filter/group-by/select/sort/limit) over the batch. The DSL predicate is "
1501
     "evaluated as a SIMD mask (pandas.query-style); aggs are 'count' or "
1502
     "'<op>:<column>'."},
1503
    {"group_by", DataFrame_group_by, METH_VARARGS,
1504
     "group_by(key, *aggs) -> DataFrame or GroupBy; aggs are 'count', "
1505
     "'<op>:<column>' (sum|min|max|mean|var|std|skew|kurt), or aggregate "
1506
     "expressions (F.x.sum(), ...); no aggs returns a GroupBy for .agg(...)."},
1507
    {"_group_agg_expr", DataFrame_group_agg_expr, METH_VARARGS,
1508
     "_group_agg_expr(key, specs) -> DataFrame; specs is a list of "
1509
     "(op_int, value_ast|None, out_name[, param[, by_ast]]). Internal: the "
1510
     "GroupBy expression path (CSE across value expressions + pruner)."},
1511
    {"join", DFTU_PYCFUNCTION(DataFrame_join), METH_VARARGS | METH_KEYWORDS,
1512
     "join(other, on=None, how='inner', left_on=None, right_on=None, "
1513
     "suffix='_right') -> DataFrame hash-joined on the key columns; "
1514
     "how=inner|left|right|outer|full|semi|anti|cross."},
1515
    {"compare_agg", DataFrame_compare_agg, METH_VARARGS,
1516
     "compare_agg(variant, n_key) -> DataFrame: FULL-join two aggregation "
1517
     "results on the first n_key group-key columns and append delta_/pct_ per "
1518
     "numeric metric (the CompareView result)."},
1519
    {"partition_id", DataFrame_partition_id, METH_VARARGS,
1520
     "partition_id(keys, n_parts) -> Int32 Series: the part in [0, n_parts) "
1521
     "each row lands in under a stable hash of the key columns."},
1522
    {"hash_partition", DataFrame_hash_partition, METH_VARARGS,
1523
     "hash_partition(keys, n_parts) -> list[DataFrame] partitioned by a stable "
1524
     "hash of the key columns (the distributed shuffle primitive)."},
1525
#ifdef DFTRACER_UTILS_ENABLE_ARROW
1526
    {"__arrow_c_array__", DataFrame_arrow_c_array, METH_VARARGS,
1527
     "Arrow PyCapsule export of the struct: (schema_capsule, array_capsule)."},
1528
    {"__arrow_c_stream__", DataFrame_arrow_c_stream, METH_VARARGS,
1529
     "Arrow PyCapsule stream export (one struct batch); pa.table(batch) uses "
1530
     "this to import every column zero-copy."},
1531
#endif
1532
#ifdef DFTRACER_UTILS_ENABLE_ARROW_IPC
1533
    {"to_ipc", DataFrame_to_ipc, METH_NOARGS,
1534
     "to_ipc() -> bytes: the frame as an Arrow IPC stream (schema + one record "
1535
     "batch + EOS); no pyarrow needed to produce .arrow bytes."},
1536
#endif
1537
    {"to_bytes", DataFrame_to_bytes, METH_NOARGS,
1538
     "to_bytes() -> bytes: the frame in the native frame format."},
1539
    {nullptr, nullptr, 0, nullptr}};
1540

1541
PyGetSetDef DataFrame_getset[] = {
1542
    {"num_rows", DataFrame_get_num_rows, nullptr, "Row count.", nullptr},
1543
    {"num_columns", DataFrame_get_num_columns, nullptr, "Series count.",
1544
     nullptr},
1545
    {"column_names", DataFrame_get_column_names, nullptr, "Series names.",
1546
     nullptr},
1547
    {nullptr, nullptr, nullptr, nullptr, nullptr}};
1548

1549
PyMappingMethods DataFrame_as_mapping = {};
1550
PySequenceMethods DataFrame_as_sequence = {};
1551

1552
#ifdef DFTRACER_UTILS_ENABLE_ARROW
1553
// Whether field `i` of `obj`'s schema carries the `arrow.json` extension in
1554
// its metadata. A pyarrow without the registered extension type (before 18)
1555
// keeps the name only there, and an Array's own export has no field metadata.
1556
bool field_is_json(PyObject* obj, Py_ssize_t i) {
91 ✔
1557
    PyObject* schema = PyObject_GetAttrString(obj, "schema");
91 ✔
1558
    if (!schema) {
91 !
1559
        PyErr_Clear();
×
1560
        return false;
×
1561
    }
1562
    PyObject* field = PyObject_CallMethod(schema, "field", "n", i);
91 ✔
1563
    Py_DECREF(schema);
1564
    if (!field) {
91 !
1565
        PyErr_Clear();
×
1566
        return false;
×
1567
    }
1568
    PyObject* md = PyObject_GetAttrString(field, "metadata");
91 ✔
1569
    Py_DECREF(field);
1570
    if (!md) {
91 !
1571
        PyErr_Clear();
×
1572
        return false;
×
1573
    }
1574
    bool json = false;
91 ✔
1575
    if (PyDict_Check(md)) {
91 !
1576
        // pyarrow keys the metadata dict by bytes.
1577
        PyObject* key = PyBytes_FromString("ARROW:extension:name");
×
1578
        PyObject* name = key ? PyDict_GetItem(md, key) : nullptr;
×
1579
        json = name && PyBytes_Check(name) &&
×
1580
               std::strcmp(PyBytes_AsString(name), "arrow.json") == 0;
×
1581
        Py_XDECREF(key);
×
1582
    }
1583
    Py_DECREF(md);
1584
    return json;
91 ✔
1585
}
1586

1587
// vec_batch_from_arrow(table) -> DataFrame: import each column of a pyarrow
1588
// Table (or RecordBatch) into vec. Used to reconstruct a pickled DataFrame and
1589
// to lift Arrow into the native format.
1590
PyObject* vec_batch_from_arrow(PyObject* /*self*/, PyObject* obj) {
264 ✔
1591
    PyObject* names = PyObject_GetAttrString(obj, "column_names");
264 !
1592
    if (!names) return nullptr;
264 !
1593
    Py_ssize_t n = PySequence_Size(names);
264 !
1594
    if (n < 0) {
264 !
1595
        Py_DECREF(names);
1596
        return nullptr;
×
1597
    }
1598
    DataFrame b;
264 ✔
1599
    for (Py_ssize_t i = 0; i < n; ++i) {
951 ✔
1600
        PyObject* nm = PySequence_GetItem(names, i);
688 !
1601
        const char* s = nm ? PyUnicode_AsUTF8(nm) : nullptr;
688 !
1602
        PyObject* ca = s ? PyObject_CallMethod(obj, "column", "n", i) : nullptr;
688 !
1603
        PyObject* arr = nullptr;
688 ✔
1604
        if (ca) {
688 !
1605
            if (PyObject_HasAttrString(ca, "combine_chunks"))
688 !
1606
                arr = PyObject_CallMethod(ca, "combine_chunks", nullptr);
688 !
1607
            else {
1608
                arr = ca;
×
1609
                Py_INCREF(arr);
1610
            }
1611
        }
1612
        Series col =
1613
            arr ? dftracer::utils::python::column_from_arrow(arr) : Series{};
688 !
1614
        Py_XDECREF(arr);
688 !
1615
        Py_XDECREF(ca);
688 !
1616
        if (col.valid() && !col.is_json() &&
2,061 ✔
1617
            col.type() == dftracer::utils::dataframe::TypeId::String &&
2,061 !
1618
            field_is_json(obj, i))
91 !
1619
            col = col.as_json();
×
1620
        if (!col.valid()) {
688 ✔
1621
            Py_XDECREF(nm);
1 !
1622
            Py_DECREF(names);
1623
            return nullptr;
1 ✔
1624
        }
1625
        b.names.emplace_back(s);
687 !
1626
        b.columns.push_back(std::move(col));
687 !
1627
        Py_DECREF(nm);
1628
    }
688 ✔
1629
    Py_DECREF(names);
1630
    return make_dataframe(std::move(b));
263 !
1631
}
264 ✔
1632
#endif  // DFTRACER_UTILS_ENABLE_ARROW
1633

1634
// _dataframe_from_columns(names, series) -> DataFrame: a frame of native
1635
// Series, no Arrow involved.
1636
PyObject* dataframe_from_columns(PyObject* /*self*/, PyObject* args) {
1,642 ✔
1637
    PyObject* names_obj = nullptr;
1,642 ✔
1638
    PyObject* series_obj = nullptr;
1,642 ✔
1639
    if (!PyArg_ParseTuple(args, "OO", &names_obj, &series_obj)) return nullptr;
1,642 !
1640
    std::vector<std::string> names;
1,642 ✔
1641
    if (!parse_string_seq(names_obj, "names must be strings", names))
1,642 !
1642
        return nullptr;
×
1643
    PyObject* seq = PySequence_Fast(series_obj, "series must be a sequence");
1,642 !
1644
    if (!seq) return nullptr;
1,642 !
1645
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
1,642 !
1646
    if (static_cast<std::size_t>(n) != names.size()) {
1,642 !
1647
        Py_DECREF(seq);
1648
        PyErr_SetString(PyExc_ValueError, "names and series differ in length");
×
1649
        return nullptr;
×
1650
    }
1651
    DataFrame b;
1,642 ✔
1652
    for (Py_ssize_t i = 0; i < n; ++i) {
4,836 ✔
1653
        const Series* col = dftracer::utils::python::unwrap_vec_column(
6,388 !
1654
            PySequence_Fast_GET_ITEM(seq, i));
6,388 !
1655
        if (!col) {
3,194 !
1656
            Py_DECREF(seq);
1657
            PyErr_SetString(PyExc_TypeError, "expected native Series");
×
1658
            return nullptr;
×
1659
        }
1660
        b.names.push_back(names[static_cast<std::size_t>(i)]);
3,194 !
1661
        b.columns.push_back(col->share());
3,194 !
1662
    }
1663
    Py_DECREF(seq);
1664
    if (!b.columns.empty()) {
1,642 !
1665
        const std::int64_t rows = b.columns.front().length();
1,642 ✔
1666
        for (const Series& c : b.columns)
4,836 ✔
1667
            if (c.length() != rows) {
3,194 !
1668
                PyErr_SetString(PyExc_ValueError, "columns differ in length");
×
1669
                return nullptr;
×
1670
            }
1671
    }
1672
    return make_dataframe(std::move(b));
1,642 !
1673
}
1,642 ✔
1674

1675
}  // namespace
1676

1677
namespace dftracer::utils::python {
1678

1679
PyObject* wrap_dataframe(dftracer::utils::dataframe::DataFrame&& batch) {
55,400 ✔
1680
    return make_dataframe(std::move(batch));
55,400 ✔
1681
}
1682

1683
int init_dataframe(PyObject* m) {
7 ✔
1684
    DataFrame_as_mapping.mp_subscript = DataFrame_subscript;
7 ✔
1685
    DataFrame_as_sequence.sq_contains = DataFrame_contains;
7 ✔
1686
    DataFrameType = {};
7 ✔
1687
    DataFrameType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
7 ✔
1688
    DataFrameType.tp_name = "dftracer_utils_ext._DataFrame";
7 ✔
1689
    DataFrameType.tp_basicsize = sizeof(DataFrameObject);
7 ✔
1690
    DataFrameType.tp_flags = Py_TPFLAGS_DEFAULT;
7 ✔
1691
    DataFrameType.tp_doc =
7 ✔
1692
        "A native vec batch (named vec columns; Arrow only at the edge).";
1693
    DataFrameType.tp_dealloc = reinterpret_cast<destructor>(DataFrame_dealloc);
7 ✔
1694
    DataFrameType.tp_as_mapping = &DataFrame_as_mapping;
7 ✔
1695
    DataFrameType.tp_as_sequence = &DataFrame_as_sequence;
7 ✔
1696
    DataFrameType.tp_methods = DataFrame_methods;
7 ✔
1697
    DataFrameType.tp_getset = DataFrame_getset;
7 ✔
1698
    DataFrameType.tp_new = nullptr;  // created only by a trace view
7 ✔
1699
    if (register_type(m, &DataFrameType, "_DataFrame") < 0) return -1;
7 !
1700

1701
#ifdef DFTRACER_UTILS_ENABLE_ARROW
1702
    static PyMethodDef from_arrow_def = {
1703
        "_dataframe_from_arrow", vec_batch_from_arrow, METH_O,
1704
        "vec_batch_from_arrow(table) -> DataFrame: import a pyarrow Table's "
1705
        "columns into a native vec batch."};
1706
    PyObject* fn = PyCFunction_NewEx(&from_arrow_def, nullptr, nullptr);
7 ✔
1707
    if (!fn) return -1;
7 !
1708
    if (PyModule_AddObject(m, "_dataframe_from_arrow", fn) < 0) {
7 !
1709
        Py_DECREF(fn);
1710
        return -1;
×
1711
    }
1712
#endif
1713
    static PyMethodDef from_columns_def = {
1714
        "_dataframe_from_columns", dataframe_from_columns, METH_VARARGS,
1715
        "_dataframe_from_columns(names, series) -> DataFrame of native "
1716
        "Series."};
1717
    PyObject* cols_fn = PyCFunction_NewEx(&from_columns_def, nullptr, nullptr);
7 ✔
1718
    if (!cols_fn) return -1;
7 !
1719
    if (PyModule_AddObject(m, "_dataframe_from_columns", cols_fn) < 0) {
7 !
1720
        Py_DECREF(cols_fn);
1721
        return -1;
×
1722
    }
1723
    static PyMethodDef from_bytes_def = {
1724
        "_dataframe_from_bytes", dataframe_from_bytes, METH_O,
1725
        "_dataframe_from_bytes(bytes) -> DataFrame written by "
1726
        "DataFrame.to_bytes."};
1727
    PyObject* bytes_fn = PyCFunction_NewEx(&from_bytes_def, nullptr, nullptr);
7 ✔
1728
    if (!bytes_fn) return -1;
7 !
1729
    if (PyModule_AddObject(m, "_dataframe_from_bytes", bytes_fn) < 0) {
7 !
1730
        Py_DECREF(bytes_fn);
1731
        return -1;
×
1732
    }
1733
    return 0;
7 ✔
1734
}
1735

1736
}  // 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