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

llnl-asr / dftracer-utils / 46236434631

29 Nov 2026 07:06AM UTC coverage: 77.562% (+0.09%) from 77.475%
46236434631

Pull #121

github

web-flow
Merge 14e69625e into 053bcaf14
Pull Request #121: fix: close the dataframe and table gaps the dfanalyzer port works around

165864 of 256708 branches covered (64.61%)

Branch coverage included in aggregate %.

371 of 377 new or added lines in 20 files covered. (98.41%)

25 existing lines in 14 files now uncovered.

188777 of 200529 relevant lines covered (94.14%)

4821905.58 hits per line

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

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

8
#include <dftracer/utils/arrow/arrow.h>
9
#include <dftracer/utils/arrow/internal.h>
10
#include <dftracer/utils/arrow/ipc.h>
11
#include <dftracer/utils/arrow/stream.h>
12
#include <dftracer/utils/common/config.h>
13
#include <dftracer/utils/common/error.h>
14
#include <dftracer/utils/dataframe/agg_expr.h>
15
#include <dftracer/utils/dataframe/batch_ops.h>
16
#include <dftracer/utils/dataframe/dataframe.h>
17
#include <dftracer/utils/dataframe/expr.h>
18
#include <dftracer/utils/dataframe/frame_ops.h>
19
#include <dftracer/utils/dataframe/internal/frame_buffers.h>
20
#include <dftracer/utils/dataframe/internal/frame_native.h>
21
#include <dftracer/utils/dataframe/kernels/kernels.h>
22
#include <dftracer/utils/dataframe/lazyframe.h>
23
#include <dftracer/utils/dataframe/plan.h>
24
#include <dftracer/utils/dstd/hash/xxh3.h>
25
#include <dftracer/utils/dstd/memory.h>
26
#include <dftracer/utils/dstd/optional.h>
27
#include <dftracer/utils/dstd/pair.h>
28
#include <dftracer/utils/dstd/span.h>
29
#include <dftracer/utils/dstd/string.h>
30
#include <dftracer/utils/dstd/vector.h>
31
#include <dftracer/utils/duql/errc.h>
32
#include <dftracer/utils/duql/query.h>
33
#include <dftracer/utils/python/core/arrow_helpers.h>
34
#include <dftracer/utils/python/core/call.h>
35
#include <dftracer/utils/python/core/errors.h>
36
#include <dftracer/utils/python/core/list_helpers.h>
37
#include <dftracer/utils/python/core/method.h>
38
#include <dftracer/utils/python/core/scalar_helpers.h>
39
#include <dftracer/utils/python/core/type_helpers.h>
40
#include <dftracer/utils/python/frame/agg_helpers.h>
41
#include <dftracer/utils/python/frame/columnar_eval.h>
42
#include <dftracer/utils/python/frame/dataframe.h>
43
#include <dftracer/utils/python/frame/frame_args.h>
44
#include <dftracer/utils/python/frame/frame_op_helpers.h>
45
#include <dftracer/utils/python/frame/join_helpers.h>
46
#include <dftracer/utils/python/frame/lazyframe.h>
47
#include <dftracer/utils/python/frame/series.h>
48
#include <dftracer/utils/python/runtime/task_handle.h>
49

50
#include <atomic>
51
#include <cstdint>
52
#include <cstring>
53
#include <nanoarrow/nanoarrow.hpp>
54
#include <new>
55
#include <stdexcept>
56
#include <utility>
57

58
using dftracer::utils::python::core::as_native;
59
using dftracer::utils::python::core::guard;
60
using dftracer::utils::python::core::parse_kw;
61
using dftracer::utils::python::core::release_gil;
62
using dftracer::utils::python::core::without_gil;
63

64
using namespace dftracer::utils;
65

66
namespace {
67

68
using dataframe::DataFrame;
69
using dataframe::Series;
70
using dftracer::utils::python::core::parse_seq;
71
using dftracer::utils::python::core::parse_string_seq;
72
using dftracer::utils::python::frame::aggs_from_seq;
73
using dftracer::utils::python::frame::descending_from_obj;
74
using dftracer::utils::python::frame::group_agg_from_spec;
75
using dftracer::utils::python::frame::join_how_from_str;
76
using dftracer::utils::python::frame::join_keys_from_objs;
77
using dftracer::utils::python::frame::strings_from_str_or_seq;
78

79
// A DataFrame owns its columns as one STRUCT column: child(i) hands out a
80
// column sharing the struct's buffers (O(1)), and the struct exports to Arrow
81
// in one zero-copy step.
82

83
// The position of a name among the names of one DataFrameObject, as a hash
84
// built on the first lookup of a wide frame. The names of the object change in
85
// make_dataframe and DataFrame_replace only, and each of them calls reset().
86
class NameLookup {
87
   public:
88
    NameLookup() noexcept = default;
1,229,541 ✔
89
    NameLookup(const NameLookup&) = delete;
90
    NameLookup& operator=(const NameLookup&) = delete;
91
    ~NameLookup() { reset(); }
1,144,234 ✔
92

93
    void reset() noexcept {
5,409,831 ✔
94
        dftracer::utils::dstd::UniquePtr<Table> old(
7,846,428 ✔
95
            table_.exchange(nullptr, std::memory_order_acq_rel));
5,409,831 ✔
96
    }
5,409,831 ✔
97

98
    std::int64_t find(
324,676 ✔
99
        dftracer::utils::dstd::Span<const dftracer::utils::dstd::SharedString>
100
            names,
101
        dftracer::utils::dstd::StringView name) const {
102
        if (names.size() >= TABLE_MIN) {
324,676 ✔
103
            Table* t = table_.load(std::memory_order_acquire);
18,406 ✔
104
            if (!t) {
18,406 ✔
105
                Table* fresh = build(names);
72 ✔
106
                if (table_.compare_exchange_strong(t, fresh,
72 ✔
107
                                                   std::memory_order_acq_rel)) {
108
                    t = fresh;
36 ✔
109
                } else {
36 ✔
110
                    dftracer::utils::dstd::UniquePtr<Table> lost(fresh);
×
111
                }
×
112
            }
36 ✔
113
            std::size_t h = hash(name) & t->mask;
18,406 ✔
114
            while (t->slots[h] != EMPTY_SLOT) {
21,734 ✔
115
                const std::uint32_t pos = t->slots[h];
21,706 ✔
116
                if (dftracer::utils::dstd::StringView(names[pos]) == name)
21,706 ✔
117
                    return static_cast<std::int64_t>(pos);
18,378 ✔
118
                h = (h + 1) & t->mask;
3,328 ✔
119
            }
10,853 ✔
120
            return -1;
14 ✔
121
        }
9,203 ✔
122
        for (std::size_t i = 0; i < names.size(); ++i)
971,457 ✔
123
            if (names[i] == name) return static_cast<std::int64_t>(i);
815,642 ✔
124
        return -1;
2,680 ✔
125
    }
162,338 ✔
126

127
   private:
128
    struct Table {
72 ✔
129
        std::uint32_t mask = 0;
36 ✔
130
        dftracer::utils::dstd::Vector<std::uint32_t> slots;
131
    };
132
    static constexpr std::size_t TABLE_MIN = 64;
133
    static constexpr std::uint32_t EMPTY_SLOT = 0xFFFFFFFFu;
134

135
    static std::size_t hash(dftracer::utils::dstd::StringView name) {
31,336 ✔
136
        return static_cast<std::size_t>(
31,336 ✔
137
            dftracer::utils::dstd::hash::xxh3_64(name));
31,336 ✔
138
    }
139

140
    static Table* build(
72 ✔
141
        dftracer::utils::dstd::Span<const dftracer::utils::dstd::SharedString>
142
            names) {
143
        std::size_t cap = 16;
72 ✔
144
        while (cap < names.size() * 2) cap <<= 1;
370 ✔
145
        Table* t = dftracer::utils::dstd::make_unique<Table>().release();
72 ✔
146
        t->mask = static_cast<std::uint32_t>(cap - 1);
72 ✔
147
        t->slots.resize(cap, EMPTY_SLOT);
72 ✔
148
        for (std::size_t i = 0; i < names.size(); ++i) {
13,002 ✔
149
            const dftracer::utils::dstd::StringView n(names[i]);
12,930 ✔
150
            std::size_t h = hash(n) & t->mask;
12,930 ✔
151
            bool dup = false;
12,930 ✔
152
            while (t->slots[h] != EMPTY_SLOT) {
16,582 ✔
153
                if (dftracer::utils::dstd::StringView(names[t->slots[h]]) ==
5,478 !
154
                    n) {
1,826 ✔
155
                    dup = true;
156
                    break;
157
                }
158
                h = (h + 1) & t->mask;
3,652 ✔
159
            }
160
            if (!dup) t->slots[h] = static_cast<std::uint32_t>(i);
12,930 ✔
161
        }
6,465 ✔
162
        return t;
108 ✔
163
    }
36 ✔
164

165
    mutable std::atomic<Table*> table_{nullptr};
328,707 ✔
166
};
167

168
struct DataFrameObject {
169
    PyObject_HEAD PyObject* weaklist;
170
    Series st;
171
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString> names;
172
    // The row index names, empty for none (DataFrame::index_names).
173
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString>
174
        index_names;
175
    // The lookup hash of the index labels (RowIndex::cache), kept here because
176
    // each call rebuilds a DataFrame view of this object.
177
    dftracer::utils::dstd::SharedPtr<dftracer::utils::dataframe::LabelCache>
178
        label_cache;
179
    // The name lookup of `names`, reset where `names` is assigned.
180
    NameLookup name_lookup;
181
};
182

183
PyTypeObject DataFrameType;
184
// The type the factories allocate: DataFrameType until _bind_types gives the
185
// Python subclass.
186
PyTypeObject* g_dataframe_type = &DataFrameType;
187

188
}  // namespace
189

190
template <>
191
struct dftracer::utils::python::core::NativeTraits<DataFrameObject> {
192
    static PyTypeObject* type() { return &DataFrameType; }
13,026,623 ✔
193
    static constexpr const char* EXPECTED = "expected a DataFrame";
194
    static DataFrameObject* get(PyObject* o) {
5,778,774 ✔
195
        return reinterpret_cast<DataFrameObject*>(o);
5,778,774 ✔
196
    }
197
};
198

199
namespace {
200

201
PyObject* make_dataframe(DataFrame&& b) {
572,127 ✔
202
    // A column of a frame is labelled by the frame's row index alone.
203
    for (Series& column : b.columns)
2,405,697 ✔
204
        if (column.has_index()) column = column.without_index();
1,833,570 !
205
    Series st = Series::structs(b.names, std::move(b.columns));
572,127 !
206
    auto* self = reinterpret_cast<DataFrameObject*>(
572,127 ✔
207
        g_dataframe_type->tp_alloc(g_dataframe_type, 0));
572,127 !
208
    if (!self) return nullptr;
572,127 !
209
    new (&self->st) Series(std::move(st));
572,127 ✔
210
    new (&self->names)
572,127 ✔
211
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString>(
328,707 ✔
212
            std::move(b.names));
572,127 ✔
213
    new (&self->index_names)
572,127 ✔
214
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString>();
328,707 ✔
215
    new (&self->label_cache) dftracer::utils::dstd::SharedPtr<
572,127 ✔
216
        dftracer::utils::dataframe::LabelCache>();
217
    new (&self->name_lookup) NameLookup();
572,127 ✔
218
    if (b.row_index) {
572,127 ✔
219
        self->index_names = std::move(b.row_index->names);
28,631 ✔
220
        self->label_cache = std::move(b.row_index->cache);
272,051 !
221
    }
14,319 ✔
222
    return reinterpret_cast<PyObject*>(self);
328,707 ✔
223
}
572,127 ✔
224

225
bool is_dataframe(PyObject* o) {
8,232 ✔
226
    return as_native<DataFrameObject>(o) != nullptr;
8,232 ✔
227
}
228

229
void DataFrame_dealloc(DataFrameObject* self) {
572,117 ✔
230
    if (self->weaklist)
572,117 ✔
231
        PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
4 ✔
232
    self->name_lookup.~NameLookup();
572,117 ✔
233
    self->label_cache.~SharedPtr();
572,117 ✔
234
    self->index_names.~vector();
572,117 ✔
235
    self->names.~vector();
572,117 ✔
236
    self->st.~Series();
572,117 !
237
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
572,117 ✔
238
}
572,117 ✔
239

240
std::int64_t index_of(const DataFrameObject* self,
324,676 ✔
241
                      dftracer::utils::dstd::StringView name) {
242
    return self->name_lookup.find(self->names, name);
324,676 ✔
243
}
244

245
// A dataframe::DataFrame view over the struct's children (shared buffers,
246
// zero-copy), for forwarding to the batch_ops frame kernels.
247
DataFrame to_dataframe(const DataFrameObject* self) {
7,666,863 ✔
248
    DataFrame b;
7,666,863 ✔
249
    b.names = self->names;
7,666,863 !
250
    b.columns.reserve(self->names.size());
7,666,863 !
251
    for (std::size_t i = 0; i < self->names.size(); ++i)
25,701,958 ✔
252
        b.columns.push_back(self->st.child(static_cast<std::int64_t>(i)));
18,035,095 !
253
    if (!self->index_names.empty()) {
7,666,863 ✔
254
        b.row_index = dftracer::utils::dstd::make_unique<dataframe::RowIndex>();
13,401 !
255
        b.row_index->names = self->index_names;
13,401 !
256
        b.row_index->cache = self->label_cache;
13,401 ✔
257
    }
6,704 ✔
258
    return b;
7,666,863 ✔
259
}
3,409,857 !
260

261
// Wrap a batch_ops call over the frame `b` that returns a frame or a frame
262
// result, turning its error and any C++ exception into a typed Python error.
263
// `fn` runs with the GIL released for a large frame, so it touches no Python
264
// object. It reads a view of the frame taken under the GIL, as `_replace`
265
// rebinds a DataFrame object's columns in place, and a Series argument is
266
// shared under the GIL first, as `s.name = x` renames a Series object in place.
267
template <class Fn>
268
PyObject* run_batch_op(const DataFrameObject* b, Fn&& fn) {
292,690 ✔
269
    return guard([&]() -> PyObject* {
688,862 ✔
270
        const DataFrame frame = to_dataframe(b);
292,690 ✔
271
        auto out = without_gil(frame.num_rows(), [&] {
541,655 !
272
            if constexpr (std::is_invocable_v<Fn&, const DataFrame&>)
273
                return fn(frame);
227,904 !
274
            else
275
                return fn();
810 !
276
        });
189,207 ✔
277
        if constexpr (std::is_same_v<decltype(out), DataFrame>) {
278
            return make_dataframe(std::move(out));
284,668 !
279
        } else {
280
            if (!out) {
74,334 !
281
                dftracer::utils::python::core::set_py_error(out.error());
132 !
282
                return nullptr;
66 ✔
283
            }
284
            return make_dataframe(std::move(*out));
74,202 !
285
        }
286
    });
396,172 ✔
287
}
288

289
// A method over `Args`, which `a.parse(args, kwds, parse...)` reads;
290
// `build(frame, a)` runs the frame op.
291
template <class Args, class Build, class... Parse>
292
PyObject* batch_args(PyObject* self, PyObject* args, PyObject* kwds,
3,484 ✔
293
                     Build build, Parse... parse) {
294
    DataFrameObject* b = as_native<DataFrameObject>(self);
3,484 ✔
295
    if (!b) return nullptr;
3,484 !
296
    Args a;
3,484 ✔
297
    if (!a.parse(args, kwds, parse...)) return nullptr;
3,484 !
298
    return run_batch_op(
3,482 !
299
        b, [&](const DataFrame& frame) { return build(frame, a); });
6,957 !
300
}
3,459 ✔
301

302
// The same for a method whose `a.other` is a second DataFrame, taken under the
303
// GIL before the op runs: `build(frame, other, a)`.
304
template <class Args, class Build>
305
PyObject* batch_other_args(PyObject* self, PyObject* args, PyObject* kwds,
8,232 ✔
306
                           Build build) {
307
    DataFrameObject* b = as_native<DataFrameObject>(self);
8,232 ✔
308
    if (!b) return nullptr;
8,232 !
309
    Args a;
8,232 ✔
310
    if (!a.parse(args, kwds, is_dataframe)) return nullptr;
8,232 !
311
    const DataFrame other = to_dataframe(as_native<DataFrameObject>(a.other));
8,214 !
312
    return run_batch_op(
8,214 !
313
        b, [&](const DataFrame& frame) { return build(frame, other, a); });
16,428 !
314
}
12,339 ✔
315

316
// A method that takes nothing and runs the frame op `Op`.
317
template <auto Op>
318
PyObject* batch_noarg(PyObject* self, PyObject*) {
992 ✔
319
    DataFrameObject* b = as_native<DataFrameObject>(self);
992 ✔
320
    if (!b) return nullptr;
992 !
321
    return run_batch_op(b, [](const DataFrame& frame) { return Op(frame); });
1,984 !
322
}
496 ✔
323

324
// A method that takes a row count.
325
template <auto Op>
326
PyObject* batch_count(PyObject* self, PyObject* arg) {
201,756 ✔
327
    DataFrameObject* b = as_native<DataFrameObject>(self);
201,756 ✔
328
    if (!b) return nullptr;
201,756 !
329
    long long n = PyLong_AsLongLong(arg);
201,756 ✔
330
    if (n == -1 && PyErr_Occurred()) return nullptr;
201,756 !
331
    return run_batch_op(b,
345,497 ✔
332
                        [&](const DataFrame& frame) { return Op(frame, n); });
403,511 ✔
333
}
143,741 ✔
334

335
PyObject* DataFrame_filter(PyObject* self, PyObject* mask);
336
PyObject* DataFrame_select(PyObject* self, PyObject* args);
337

338
// df["a"] is a column; df[["a", "b"]] a projection and df[mask] the rows where
339
// a Bool Series holds (the pandas spellings), both under the frame op index
340
// rules.
341
PyObject* DataFrame_subscript(PyObject* self, PyObject* key) {
199,982 ✔
342
    DataFrameObject* b = as_native<DataFrameObject>(self);
199,982 ✔
343
    if (!b) return nullptr;
199,982 !
344
    if (!PyUnicode_Check(key)) {
199,982 ✔
345
        if (dftracer::utils::python::frame::unwrap_vec_column(key))
254 ✔
346
            return DataFrame_filter(self, key);
176 ✔
347
        PyObject* names = PySequence_Tuple(key);
78 ✔
348
        if (!names) {
78 ✔
349
            PyErr_SetString(PyExc_TypeError,
×
350
                            "DataFrame key must be a column name, a list of "
351
                            "names or a Bool Series");
352
            return nullptr;
×
353
        }
354
        for (Py_ssize_t k = 0; k < PyTuple_GET_SIZE(names); ++k) {
258 !
355
            PyObject* text = PyObject_Str(PyTuple_GET_ITEM(names, k));
180 ✔
356
            if (!text) {
180 ✔
357
                Py_DECREF(names);
×
358
                return nullptr;
×
359
            }
360
            PyTuple_SET_ITEM(names, k, text);
180 ✔
361
        }
90 !
362
        PyObject* out = DataFrame_select(self, names);
78 ✔
363
        Py_DECREF(names);
78 !
364
        return out;
78 ✔
365
    }
39 ✔
366
    const char* name = PyUnicode_AsUTF8(key);
199,728 ✔
367
    if (!name) return nullptr;
199,728 !
368
    std::int64_t i = index_of(b, name);
199,728 ✔
369
    if (i < 0) {
199,728 ✔
370
        PyErr_Format(PyExc_KeyError, "no column named '%s'", name);
×
371
        return nullptr;
×
372
    }
373
    // The labels a column was built with are not the frame's: only its own
374
    // row index labels it.
375
    Series column = b->st.child(i).rename(name);
199,728 !
376
    if (column.has_index()) column = column.without_index();
199,728 !
377
    if (b->index_names.empty())
199,728 ✔
378
        return dftracer::utils::python::frame::wrap_vec_column(
108,322 !
379
            std::move(column));
380
    // The frame's row index travels with the column as its labels.
381
    dstd::Vector<dstd::StringView> level_names;
91,406 ✔
382
    dstd::Vector<Series> levels;
91,406 ✔
383
    for (const dstd::SharedString& index_name : b->index_names) {
194,388 ✔
384
        const std::int64_t at = index_of(b, index_name.c_str());
154,473 !
385
        if (at < 0) continue;
102,982 ✔
386
        level_names.emplace_back(index_name);
102,982 !
387
        levels.push_back(b->st.child(at));
102,982 !
388
    }
51,491 !
389
    Series labelled = column.with_index(level_names, levels);
91,406 !
390
    return dftracer::utils::python::frame::wrap_vec_column(
91,406 !
391
        labelled.valid() ? std::move(labelled) : std::move(column));
91,406 ✔
392
}
245,685 ✔
393

394
int DataFrame_contains(PyObject* self, PyObject* key) {
21,968 ✔
395
    DataFrameObject* b = as_native<DataFrameObject>(self);
21,968 ✔
396
    if (!b) return -1;
21,968 !
397
    // Only a name can be a column; anything else is simply not in the
398
    // frame, with no error left behind.
399
    if (!PyUnicode_Check(key)) return 0;
21,968 ✔
400
    const char* name = PyUnicode_AsUTF8(key);
21,966 ✔
401
    if (!name) return -1;
21,966 !
402
    return index_of(b, name) >= 0 ? 1 : 0;
24,660 ✔
403
}
10,984 ✔
404

405
// _replace(other): this frame takes the columns and the index names of
406
// `other`, in place. Kernels read a
407
// view taken under the GIL, so one running on another thread keeps the old
408
// columns.
409
PyObject* DataFrame_replace(PyObject* self, PyObject* other) {
4,837,718 ✔
410
    DataFrameObject* b = as_native<DataFrameObject>(self);
4,837,718 ✔
411
    DataFrameObject* o = as_native<DataFrameObject>(other);
4,837,718 ✔
412
    if (!b || !o) return nullptr;
4,837,718 !
413
    if (b == o) Py_RETURN_NONE;
4,837,716 ✔
414
    return guard([&]() -> PyObject* {
6,945,609 ✔
415
        DataFrame f = to_dataframe(o);
4,837,714 ✔
416
        Series st = Series::structs(f.names, std::move(f.columns));
4,837,714 !
417
        b->names = o->names;
4,837,714 !
418
        b->name_lookup.reset();
4,837,714 ✔
419
        b->index_names = o->index_names;
4,837,714 !
420
        b->label_cache = o->label_cache;
4,837,714 ✔
421
        b->st = std::move(st);
4,837,714 ✔
422
        Py_RETURN_NONE;
5,459,638 !
423
    });
4,837,714 ✔
424
}
2,107,897 ✔
425

426
// share() -> DataFrame: a new object over the same columns and index names.
427
PyObject* DataFrame_share(PyObject* self, PyObject*) {
102 ✔
428
    DataFrameObject* b = as_native<DataFrameObject>(self);
102 ✔
429
    if (!b) return nullptr;
102 !
430
    return guard(
102 ✔
431
        [&]() -> PyObject* { return make_dataframe(to_dataframe(b)); });
204 !
432
}
51 ✔
433

434
// index_names() -> list[str]: the row index columns, in order; [] for none.
435
PyObject* DataFrame_index_names(PyObject* self, PyObject*) {
145,968 ✔
436
    DataFrameObject* b = as_native<DataFrameObject>(self);
145,968 ✔
437
    if (!b) return nullptr;
145,968 !
438
    return str_list_from(b->index_names);
145,968 ✔
439
}
72,984 ✔
440

441
// with_index(names) -> DataFrame: this frame's columns under the row index
442
// `names` (a list of str; [] drops it). KeyError for a name that is no column,
443
// ValueError for a repeated name or a column of a nested type.
444
PyObject* DataFrame_with_index(PyObject* self, PyObject* names) {
22,156 ✔
445
    DataFrameObject* b = as_native<DataFrameObject>(self);
22,156 ✔
446
    if (!b) return nullptr;
22,156 !
447
    PyObject* seq =
33,234 ✔
448
        PySequence_Fast(names, "with_index() expects a list of names");
22,156 ✔
449
    if (!seq) return nullptr;
22,156 ✔
450
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
22,156 ✔
451
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
22,156 !
452
    for (Py_ssize_t k = 0; k < n; ++k) {
46,914 !
453
        PyObject* item = PySequence_Fast_GET_ITEM(seq, k);
24,758 !
454
        const char* text =
37,137 !
455
            PyUnicode_Check(item) ? PyUnicode_AsUTF8(item) : nullptr;
24,758 !
456
        if (!text) {
24,758 !
457
            if (!PyErr_Occurred())
×
458
                PyErr_SetString(PyExc_TypeError,
×
459
                                "with_index() names must be str");
460
            Py_DECREF(seq);
×
461
            return nullptr;
×
462
        }
463
        keys.emplace_back(text);
24,758 !
464
    }
12,379 !
465
    Py_DECREF(seq);
22,156 !
466
    return guard([&]() -> PyObject* {
33,234 !
467
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::StringView> views;
22,156 ✔
468
        views.reserve(keys.size());
22,156 !
469
        for (const auto& key : keys) views.emplace_back(key);
46,914 ✔
470
        auto out = to_dataframe(b).with_index(views);
22,156 !
471
        if (!out) {
22,156 ✔
472
            dftracer::utils::python::core::set_py_error(out.error());
4 !
473
            return nullptr;
2 ✔
474
        }
475
        return make_dataframe(std::move(*out));
22,152 !
476
    });
22,156 ✔
477
}
22,156 ✔
478

479
PyObject* column_name_list(PyObject* self, bool hide_index) {
54,442 ✔
480
    DataFrameObject* b = as_native<DataFrameObject>(self);
54,442 ✔
481
    if (!b) return nullptr;
54,442 !
482
    PyObject* list = PyList_New(0);
54,442 ✔
483
    if (!list) return nullptr;
54,442 !
484
    for (std::size_t i = 0; i < b->names.size(); ++i) {
238,950 !
485
        bool is_index = false;
184,508 ✔
486
        if (hide_index)
184,508 ✔
487
            for (const auto& index_name : b->index_names)
96 ✔
488
                if (dftracer::utils::dstd::StringView(index_name) ==
27 ✔
489
                    dftracer::utils::dstd::StringView(b->names[i]))
18 ✔
490
                    is_index = true;
51 ✔
491
        if (is_index) continue;
92,293 ✔
492
        PyObject* s = PyUnicode_FromString(b->names[i].c_str());
276,750 ✔
493
        if (!s || PyList_Append(list, s) < 0) {
184,502 !
494
            Py_XDECREF(s);
×
495
            Py_DECREF(list);
×
496
            return nullptr;
×
497
        }
498
        Py_DECREF(s);
204,696 ✔
499
    }
92,254 !
500
    return list;
27,221 ✔
501
}
27,221 ✔
502

503
PyObject* DataFrame_keys(PyObject* self, PyObject*) {
26 ✔
504
    return column_name_list(self, true);
26 ✔
505
}
506

507
PyObject* DataFrame_filter(PyObject* self, PyObject* mask) {
4,284 ✔
508
    DataFrameObject* b = as_native<DataFrameObject>(self);
4,284 ✔
509
    if (!b) return nullptr;
4,284 !
510
    const Series* m = dftracer::utils::python::frame::unwrap_vec_column(mask);
4,284 ✔
511
    if (!m) {
4,284 ✔
512
        PyErr_SetString(PyExc_TypeError,
×
513
                        "filter() expects a Series boolean mask");
514
        return nullptr;
×
515
    }
516
    const Series mask_copy = m->share();
4,284 ✔
517
    return run_batch_op(b, [&](const DataFrame& frame) {
6,426 !
518
        return dataframe::filter(frame, mask_copy);
4,284 !
519
    });
2,142 ✔
520
}
4,284 ✔
521

522
// query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None,
523
// descending=False, limit=None) -> DataFrame: a query plan over this batch -
524
// filter by the DSL predicate (a SIMD mask, pandas.query-style), group_by/aggs,
525
// project `select`, sort by `order_by`, cap at `limit`. Raises
526
// DFTUtilsDuqlError on a parse error or a predicate with no columnar lowering
527
// (regex/like/ordered-string/absent field).
528
PyObject* DataFrame_query(PyObject* self, PyObject* args, PyObject* kwds) {
34 ✔
529
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
530
    if (!b) return nullptr;
34 !
531
    const char* dsl = nullptr;
34 ✔
532
    const char* group_by = nullptr;
34 ✔
533
    PyObject* aggs_obj = nullptr;
34 ✔
534
    PyObject* select_obj = nullptr;
34 ✔
535
    const char* order_by = nullptr;
34 ✔
536
    int descending = 0;
34 ✔
537
    PyObject* limit_obj = nullptr;
34 ✔
538
    if (!parse_kw<"|zzOOzpO">(args, kwds,
51 !
539
                              {"dsl", "group_by", "aggs", "select", "order_by",
17 ✔
540
                               "descending", "limit"},
541
                              &dsl, &group_by, &aggs_obj, &select_obj,
542
                              &order_by, &descending, &limit_obj))
543
        return nullptr;
544

545
    return guard([&]() -> PyObject* {
51 ✔
546
        DataFrame bat = to_dataframe(b);
34 ✔
547
        dataframe::QueryPlan plan;
34 ✔
548
        dftracer::utils::dstd::Optional<duql::Query>
34 ✔
549
            q;  // keep root() alive across execute
34 ✔
550
        if (dsl && *dsl) {
34 ✔
551
            auto parsed = duql::Query::from_string(dsl);
19 !
552
            if (!parsed)
18 ✔
553
                throw dftracer::utils::python::core::PyErrorException(
2 !
554
                    dftracer::utils::dstd::Error{duql::DuqlErrc::Parse,
3 !
555
                                                 parsed.error().format()});
4 !
556
            q.emplace(std::move(*parsed));
16 !
557
            plan.where = &duql::detail::QueryAccess::root(*q);
16 !
558
        }
18 ✔
559
        if (group_by && *group_by) plan.group_by = group_by;
32 !
560
        if (aggs_obj && aggs_obj != Py_None) {
32 ✔
561
            if (!parse_seq<dataframe::GroupAgg>(
6 !
562
                    aggs_obj, "aggs must be a sequence of strings", plan.aggs,
3 ✔
563
                    [](PyObject* item,
12 ✔
564
                       dftracer::utils::dstd::Vector<dataframe::GroupAgg>& o) {
565
                        const char* s = PyUnicode_AsUTF8(item);
12 ✔
566
                        if (!s) return false;
12 !
567
                        return guard([&] {
18 ✔
568
                            o.push_back(group_agg_from_spec(s));
18 !
569
                            return true;
12 ✔
570
                        });
571
                    }))
6 ✔
572
                return nullptr;
573
        }
3 ✔
574
        if (select_obj && select_obj != Py_None) {
32 ✔
575
            if (!parse_string_seq(select_obj,
15 !
576
                                  "select must be a sequence of column names",
577
                                  plan.select))
5 ✔
578
                return nullptr;
579
        }
5 ✔
580
        if (order_by && *order_by) plan.order_by = order_by;
32 !
581
        plan.descending = descending != 0;
32 ✔
582
        if (limit_obj && limit_obj != Py_None) {
32 ✔
583
            plan.limit = PyLong_AsLongLong(limit_obj);
8 !
584
            if (plan.limit == -1 && PyErr_Occurred()) return nullptr;
8 !
585
        }
4 ✔
586
        auto out = dataframe::execute(plan, bat);
32 !
587
        if (!out) {
32 ✔
588
            dftracer::utils::python::core::set_py_error(out.error());
2 !
589
            return nullptr;
1 ✔
590
        }
591
        return make_dataframe(std::move(*out));
30 !
592
    });
44 ✔
593
}
17 ✔
594

595
PyObject* DataFrame_select(PyObject* self, PyObject* args) {
18,854 ✔
596
    DataFrameObject* b = as_native<DataFrameObject>(self);
18,854 ✔
597
    if (!b) return nullptr;
18,854 !
598
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> names;
18,854 ✔
599
    Py_ssize_t n = PyTuple_GET_SIZE(args);
18,854 !
600
    for (Py_ssize_t i = 0; i < n; ++i) {
67,780 !
601
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
48,926 !
602
        if (!s) {
48,926 !
603
            PyErr_SetString(PyExc_TypeError, "select() names must be strings");
×
604
            return nullptr;
×
605
        }
606
        names.emplace_back(s);
48,926 !
607
    }
24,463 !
608
    return run_batch_op(b, [&](const DataFrame& frame) {
28,281 !
609
        return dataframe::select(frame, names);
18,854 ✔
610
    });
9,427 ✔
611
}
18,854 ✔
612

613
PyObject* DataFrame_rename(PyObject* self, PyObject* mapping) {
2,436 ✔
614
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,436 ✔
615
    if (!b) return nullptr;
2,436 !
616
    if (!PyDict_Check(mapping)) {
2,436 ✔
617
        PyErr_SetString(PyExc_TypeError, "rename() expects a {old: new} dict");
×
618
        return nullptr;
×
619
    }
620
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> new_names;
2,436 ✔
621
    new_names.reserve(b->names.size());
2,436 !
622
    for (const dftracer::utils::dstd::SharedString& name : b->names) {
8,330 !
623
        PyObject* v = PyDict_GetItemString(mapping, name.c_str());
8,841 !
624
        if (v) {
5,894 ✔
625
            const char* s = PyUnicode_AsUTF8(v);
3,244 !
626
            if (!s) {
3,244 !
627
                PyErr_SetString(PyExc_TypeError, "rename() values must be str");
×
628
                return nullptr;
×
629
            }
630
            new_names.emplace_back(s);
3,244 !
631
        } else {
1,622 !
632
            new_names.emplace_back(name.view());
2,650 ✔
633
        }
634
    }
2,947 !
635
    return run_batch_op(b, [&](const DataFrame& frame) {
3,654 !
636
        return dataframe::rename(frame, new_names);
2,436 ✔
637
    });
1,218 ✔
638
}
2,436 ✔
639

640
PyObject* DataFrame_with_column(PyObject* self, PyObject* args) {
24,828 ✔
641
    DataFrameObject* b = as_native<DataFrameObject>(self);
24,828 ✔
642
    if (!b) return nullptr;
24,828 !
643
    const char* name = nullptr;
24,828 ✔
644
    PyObject* col = nullptr;
24,828 ✔
645
    if (!PyArg_ParseTuple(args, "sO", &name, &col)) return nullptr;
24,828 !
646
    const Series* c = dftracer::utils::python::frame::unwrap_vec_column(col);
24,828 ✔
647
    if (!c) {
24,828 ✔
648
        PyErr_SetString(PyExc_TypeError,
×
649
                        "with_column() expects (name, Series)");
650
        return nullptr;
×
651
    }
652
    const Series col_copy = c->share();
24,828 ✔
653
    return run_batch_op(b, [&](const DataFrame& frame) {
37,242 !
654
        return dataframe::with_column(frame, name, col_copy);
24,828 ✔
655
    });
12,414 ✔
656
}
24,828 ✔
657

658
PyObject* DataFrame_take(PyObject* self, PyObject* seq) {
3,212 ✔
659
    DataFrameObject* b = as_native<DataFrameObject>(self);
3,212 ✔
660
    if (!b) return nullptr;
3,212 !
661
    Series holder;
3,212 ✔
662
    dstd::Vector<std::int64_t> parsed;
3,212 ✔
663
    dstd::Span<const std::int64_t> idx;
3,212 ✔
664
    if (!dftracer::utils::python::frame::row_indices_from_py(
3,212 !
665
            seq, "take() expects a sequence of ints", holder, parsed, idx))
1,606 ✔
666
        return nullptr;
667
    // A take past the end would read outside the columns.
668
    const std::int64_t rows = to_dataframe(b).num_rows();
3,212 !
669
    for (const std::int64_t i : idx) {
17,455 ✔
670
        if (i >= rows) {
14,244 ✔
671
            PyErr_SetString(PyExc_IndexError,
2 ✔
672
                            "take: an index is at or past the frame's length");
673
            return nullptr;
2 ✔
674
        }
675
    }
7,122 ✔
676
    return run_batch_op(
3,210 !
677
        b, [&](const DataFrame& frame) { return frame.take(idx); });
6,420 !
678
}
4,818 ✔
679

680
// _locate(keys) -> (positions, missing): the rows whose index labels equal the
681
// key columns, one per level (see DataFrame::locate).
682
PyObject* DataFrame_locate(PyObject* self, PyObject* keys_obj) {
400 ✔
683
    DataFrameObject* b = as_native<DataFrameObject>(self);
400 ✔
684
    if (!b) return nullptr;
400 !
685
    dstd::Vector<Series> keys;
400 ✔
686
    if (!dftracer::utils::python::frame::series_list_from_py(
400 !
687
            keys_obj, "_locate: keys must be Series", keys))
200 ✔
688
        return nullptr;
689
    return guard([&]() -> PyObject* {
600 !
690
        const DataFrame frame = to_dataframe(b);
400 ✔
691
        return dftracer::utils::python::frame::located_to_py(
400 !
692
            without_gil(frame.num_rows(), [&] { return frame.locate(keys); }));
1,000 !
693
    });
400 ✔
694
}
400 ✔
695

696
// _locate_range(start, stop) -> (offset, length): the rows between two index
697
// label bounds (lists of one-row Series, empty for an open end).
698
PyObject* DataFrame_locate_range(PyObject* self, PyObject* args) {
106 ✔
699
    DataFrameObject* b = as_native<DataFrameObject>(self);
106 ✔
700
    if (!b) return nullptr;
106 !
701
    dftracer::utils::python::frame::LocateRangeArgs a;
106 ✔
702
    if (!a.parse(args)) return nullptr;
106 !
703
    return guard([&]() -> PyObject* {
159 !
704
        const DataFrame frame = to_dataframe(b);
106 ✔
705
        return dftracer::utils::python::frame::label_span_to_py(
106 !
706
            without_gil(frame.num_rows(),
159 !
707
                        [&] { return frame.locate_range(a.start, a.stop); }));
265 ✔
708
    });
106 ✔
709
}
106 ✔
710

711
// _reindex(keys, method, limit, tolerance, fill) -> DataFrame on the index
712
// label key Series (one per level); see DataFrame::reindex.
713
PyObject* DataFrame_reindex(PyObject* self, PyObject* args) {
496 ✔
714
    DataFrameObject* b = as_native<DataFrameObject>(self);
496 ✔
715
    if (!b) return nullptr;
496 !
716
    dftracer::utils::python::frame::ReindexArgs a;
496 ✔
717
    if (!a.parse(args)) return nullptr;
496 !
718
    return run_batch_op(b, [&](const DataFrame& frame) {
744 !
719
        return frame.reindex(a.keys, a.options, a.fill);
496 ✔
720
    });
248 ✔
721
}
496 ✔
722

723
// _align_rows(other, how, fill) -> (left, right): the rows of two frames on
724
// the joined index labels; see dataframe::align_rows.
725
PyObject* DataFrame_align_rows(PyObject* self, PyObject* args) {
422 ✔
726
    DataFrameObject* b = as_native<DataFrameObject>(self);
422 ✔
727
    if (!b) return nullptr;
422 !
728
    PyObject* other_obj = nullptr;
422 ✔
729
    PyObject* fill_obj = nullptr;
422 ✔
730
    int how = 0;
422 ✔
731
    if (!PyArg_ParseTuple(args, "OiO", &other_obj, &how, &fill_obj))
422 !
732
        return nullptr;
733
    DataFrameObject* o = as_native<DataFrameObject>(other_obj);
422 ✔
734
    if (!o) return nullptr;
422 !
735
    Series fill;
422 ✔
736
    if (!dftracer::utils::python::frame::fill_series_from(
422 !
737
            fill_obj, "_align_rows: fill must be a Series", fill))
211 ✔
738
        return nullptr;
739
    return guard([&]() -> PyObject* {
633 !
740
        const DataFrame left = to_dataframe(b);
422 ✔
741
        const DataFrame right = to_dataframe(o);
422 !
742
        auto r = without_gil(left.num_rows() + right.num_rows(), [&] {
633 !
743
            return dataframe::align_rows(
422 ✔
744
                left, right, static_cast<dataframe::JoinHow>(how), fill);
633 ✔
745
        });
422 !
746
        if (!r) {
422 ✔
747
            dftracer::utils::python::core::set_py_error(r.error());
×
748
            return nullptr;
749
        }
750
        PyObject* l = make_dataframe(std::move(r->left));
422 !
751
        PyObject* rt = l ? make_dataframe(std::move(r->right)) : nullptr;
633 !
752
        if (!rt) {
422 !
753
            Py_XDECREF(l);
×
754
            return nullptr;
755
        }
756
        return Py_BuildValue("NN", l, rt);
422 !
757
    });
422 ✔
758
}
422 ✔
759

760
PyObject* DataFrame_fill_null(PyObject* self, PyObject* value) {
48 ✔
761
    DataFrameObject* b = as_native<DataFrameObject>(self);
48 ✔
762
    if (!b) return nullptr;
48 !
763
    dftu_scalar s{};
48 ✔
764
    if (!py_to_scalar(value, &s)) return nullptr;
48 !
765
    return run_batch_op(b, [&](const DataFrame& frame) {
72 ✔
766
        return dataframe::fill_null(frame, s);
48 !
767
    });
24 ✔
768
}
24 ✔
769

770
PyObject* DataFrame_fill_nan(PyObject* self, PyObject* args, PyObject* kwds) {
38 ✔
771
    DataFrameObject* b = as_native<DataFrameObject>(self);
38 ✔
772
    if (!b) return nullptr;
38 !
773
    dftu_scalar s{};
38 ✔
774
    if (!dftracer::utils::python::frame::parse_fill_nan(args, kwds, s))
38 !
775
        return nullptr;
776
    return run_batch_op(b, [&](const DataFrame& frame) {
57 ✔
777
        return dataframe::fill_nan(frame, s);
38 !
778
    });
19 ✔
779
}
19 ✔
780

781
// Read a sequence (or single str) of column names into `out`. Returns false and
782
// sets a Python error on a non-string element.
783
bool names_from_obj(
3,830 ✔
784
    PyObject* obj,
785
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String>& out) {
786
    return dftracer::utils::python::core::parse_str_or_seq(
3,830 ✔
787
        obj, "expected a str or sequence of str", out);
3,830 ✔
788
}
789

790
// unique(subset=None): subset is a name or a sequence of names; None or an
791
// empty sequence keys on every column.
792
PyObject* DataFrame_unique(PyObject* self, PyObject* args, PyObject* kwds) {
114 ✔
793
    DataFrameObject* b = as_native<DataFrameObject>(self);
114 ✔
794
    if (!b) return nullptr;
114 !
795
    PyObject* subset_obj = Py_None;
114 ✔
796
    if (!parse_kw<"|O">(args, kwds, {"subset"}, &subset_obj)) return nullptr;
114 ✔
797
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> subset;
114 ✔
798
    if (subset_obj != Py_None && !names_from_obj(subset_obj, subset))
114 !
799
        return nullptr;
800
    return run_batch_op(b, [&](const DataFrame& frame) {
171 !
801
        return dataframe::unique(frame, subset);
114 ✔
802
    });
57 ✔
803
}
114 ✔
804

805
PyObject* DataFrame_sort_by_multi(PyObject* self, PyObject* args,
3,354 ✔
806
                                  PyObject* kwds) {
807
    return batch_args<dftracer::utils::python::frame::SortByMultiArgs>(
3,354 ✔
808
        self, args, kwds,
1,677 ✔
809
        [](const DataFrame& frame,
3,354 ✔
810
           dftracer::utils::python::frame::SortByMultiArgs& a) {
811
            dftracer::utils::dstd::Vector<std::uint8_t> desc_flags, last_flags;
3,354 ✔
812
            for (bool d : a.descending) desc_flags.push_back(d ? 1 : 0);
13,516 !
813
            for (bool l : a.nulls_last) last_flags.push_back(l ? 1 : 0);
10,110 !
814
            return dataframe::sort_by_multi(frame, a.names, desc_flags,
3,354 !
815
                                            last_flags);
5,031 !
816
        },
3,354 ✔
817
        [](PyObject* names_obj,
3,354 ✔
818
           dftracer::utils::dstd::Vector<dftracer::utils::dstd::String>&
819
               names) {
820
            return parse_string_seq(names_obj, "names must be a sequence",
5,031 ✔
821
                                    names);
1,677 ✔
822
        });
1,677 ✔
823
}
824

825
PyObject* DataFrame_sample(PyObject* self, PyObject* args, PyObject* kwds) {
14 ✔
826
    return batch_args<dftracer::utils::python::frame::SampleArgs>(
14 ✔
827
        self, args, kwds,
7 ✔
828
        [](const DataFrame& frame,
14 ✔
829
           dftracer::utils::python::frame::SampleArgs& a) {
830
            return dataframe::sample(frame, static_cast<std::int64_t>(a.n),
21 ✔
831
                                     static_cast<std::uint64_t>(a.seed));
14 ✔
832
        });
14 ✔
833
}
834

835
PyObject* DataFrame_with_row_index(PyObject* self, PyObject* arg) {
7,894 ✔
836
    DataFrameObject* b = as_native<DataFrameObject>(self);
7,894 ✔
837
    if (!b) return nullptr;
7,894 !
838
    const char* name = PyUnicode_AsUTF8(arg);
7,894 ✔
839
    if (!name) {
7,894 ✔
840
        PyErr_SetString(PyExc_TypeError, "with_row_index() expects a str");
×
841
        return nullptr;
×
842
    }
843
    return run_batch_op(b, [&](const DataFrame& frame) {
11,841 ✔
844
        return dataframe::with_row_index(frame, name);
7,894 ✔
845
    });
3,947 ✔
846
}
3,947 ✔
847

848
// reduce(agg): `agg` is an aggregate name (sum, mean, ...) broadcast over
849
// every eligible column, one row.
850
PyObject* DataFrame_reduce(PyObject* self, PyObject* arg) {
70 ✔
851
    DataFrameObject* b = as_native<DataFrameObject>(self);
70 ✔
852
    if (!b) return nullptr;
70 !
853
    const char* agg = PyUnicode_AsUTF8(arg);
70 ✔
854
    if (!agg) return nullptr;
70 !
855
    return run_batch_op(b,
105 ✔
856
                        [&](const DataFrame& frame)
105 ✔
857
                            -> dftracer::utils::dstd::Result<DataFrame> {
858
                            const auto op = dataframe::agg_from_string(agg);
70 ✔
859
                            if (!op) return op.error();
105 !
860
                            return dataframe::reduce(frame, *op);
70 !
861
                        });
70 ✔
862
}
35 ✔
863

864
PyObject* DataFrame_group_transform(PyObject* self, PyObject* args,
2,034 ✔
865
                                    PyObject* kwds) {
866
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,034 ✔
867
    if (!b) return nullptr;
2,034 !
868
    dftracer::utils::python::frame::GroupwiseArgs a;
2,034 ✔
869
    if (!dftracer::utils::python::frame::parse_groupwise_args(
2,034 !
870
            args, kwds, names_from_obj, a))
1,017 ✔
871
        return nullptr;
1 ✔
872
    return run_batch_op(b, [&](const DataFrame& frame) {
3,048 !
873
        return dataframe::GroupBy(frame, a.keys)
4,064 !
874
            .transform(static_cast<dataframe::GroupwiseOp>(a.kind), a.n,
3,048 !
875
                       static_cast<dataframe::RankMethod>(a.method),
2,032 ✔
876
                       a.ascending != 0);
3,048 !
877
    });
1,016 ✔
878
}
2,034 ✔
879

880
// reduce_specs(agg, keys) -> list[str]: the "op:column:out" specs that
881
// broadcast `agg` over every eligible non-key column, for group_by.
882
PyObject* DataFrame_reduce_specs(PyObject* self, PyObject* args) {
1,036 ✔
883
    DataFrameObject* b = as_native<DataFrameObject>(self);
1,036 ✔
884
    if (!b) return nullptr;
1,036 !
885
    dftracer::utils::python::frame::ReduceSpecsArgs a;
1,036 ✔
886
    if (!a.parse(args, names_from_obj)) return nullptr;
1,036 !
887
    const auto op = dataframe::agg_from_string(a.agg);
1,036 !
888
    if (!op) {
1,036 ✔
889
        dftracer::utils::python::core::set_py_error(op.error());
×
890
        return nullptr;
891
    }
892
    const auto found = dataframe::reduce_specs(to_dataframe(b), *op, a.keys);
1,036 !
893
    if (!found) {
1,036 ✔
894
        dftracer::utils::python::core::set_py_error(found.error());
2 !
895
        return nullptr;
1 ✔
896
    }
897
    return str_list_from(
1,034 !
898
        dftracer::utils::python::frame::reduce_spec_strings(*found));
1,551 !
899
}
2,072 ✔
900

901
PyObject* DataFrame_is_duplicated(PyObject* self, PyObject*) {
14 ✔
902
    DataFrameObject* b = as_native<DataFrameObject>(self);
14 ✔
903
    if (!b) return nullptr;
14 !
904
    auto out = dataframe::is_duplicated(to_dataframe(b));
14 !
905
    if (!out) {
14 !
906
        dftracer::utils::python::core::set_py_error(out.error());
×
907
        return nullptr;
908
    }
909
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
14 !
910
}
14 ✔
911

912
PyObject* DataFrame_is_unique(PyObject* self, PyObject*) {
2 ✔
913
    DataFrameObject* b = as_native<DataFrameObject>(self);
2 ✔
914
    if (!b) return nullptr;
2 !
915
    auto out = dataframe::is_unique(to_dataframe(b));
2 !
916
    if (!out) {
2 !
917
        dftracer::utils::python::core::set_py_error(out.error());
×
918
        return nullptr;
919
    }
920
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
2 !
921
}
2 ✔
922

923
PyObject* DataFrame_column_index(PyObject* self, PyObject* arg) {
10 ✔
924
    DataFrameObject* b = as_native<DataFrameObject>(self);
10 ✔
925
    if (!b) return nullptr;
10 !
926
    const char* name = PyUnicode_AsUTF8(arg);
10 ✔
927
    if (!name) {
10 ✔
928
        PyErr_SetString(PyExc_TypeError, "column_index() expects a str");
2 ✔
929
        return nullptr;
2 ✔
930
    }
931
    return PyLong_FromLongLong(to_dataframe(b).column_index(name));
8 !
932
}
5 ✔
933

934
PyObject* DataFrame_slice(PyObject* self, PyObject* args) {
158 ✔
935
    DataFrameObject* b = as_native<DataFrameObject>(self);
158 ✔
936
    if (!b) return nullptr;
158 !
937
    long long offset = 0, length = 0;
158 ✔
938
    if (!PyArg_ParseTuple(args, "LL", &offset, &length)) return nullptr;
158 !
939
    return run_batch_op(b, [&](const DataFrame& frame) {
237 ✔
940
        return dataframe::slice(frame, offset, length);
158 ✔
941
    });
79 ✔
942
}
79 ✔
943

944
PyObject* DataFrame_sort_by(PyObject* self, PyObject* args, PyObject* kwds) {
2,402 ✔
945
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,402 ✔
946
    if (!b) return nullptr;
2,402 !
947
    dftracer::utils::python::frame::SortByArgs a;
2,402 ✔
948
    if (!a.parse(args, kwds)) return nullptr;
2,402 !
949
    return run_batch_op(b, [&](const DataFrame& frame) {
3,603 ✔
950
        return dataframe::sort_by(frame, a.name, a.descending != 0,
3,603 ✔
951
                                  a.nulls_last != 0);
2,402 ✔
952
    });
1,201 ✔
953
}
1,201 ✔
954

955
PyObject* DataFrame_topk(PyObject* self, PyObject* args, PyObject* kwds) {
34 ✔
956
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
957
    if (!b) return nullptr;
34 !
958
    dftracer::utils::python::frame::TopkArgs a;
34 ✔
959
    if (!a.parse(args, kwds)) return nullptr;
34 !
960
    return run_batch_op(b, [&](const DataFrame& frame) {
51 ✔
961
        return dataframe::topk(frame, a.name, static_cast<std::int64_t>(a.k),
51 ✔
962
                               a.largest != 0);
34 ✔
963
    });
17 ✔
964
}
17 ✔
965

966
// (keys, n_parts) of the partitioning calls; keys is a name or a sequence of
967
// names.
968
bool partition_args(
2,264 ✔
969
    PyObject* args,
970
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String>& keys,
971
    std::int64_t& n_parts) {
972
    PyObject* keys_obj = nullptr;
2,264 ✔
973
    Py_ssize_t n = 0;
2,264 ✔
974
    if (!PyArg_ParseTuple(args, "On", &keys_obj, &n)) return false;
2,264 ✔
975
    if (!dftracer::utils::python::core::parse_str_or_seq(
2,262 ✔
976
            keys_obj, "keys must be a str or list", keys))
1,131 ✔
977
        return false;
1 ✔
978
    n_parts = static_cast<std::int64_t>(n);
2,260 ✔
979
    return true;
2,260 ✔
980
}
1,132 ✔
981

982
PyObject* DataFrame_partition_id(PyObject* self, PyObject* args) {
14 ✔
983
    DataFrameObject* b = as_native<DataFrameObject>(self);
14 ✔
984
    if (!b) return nullptr;
14 !
985
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
14 ✔
986
    std::int64_t n_parts = 0;
14 ✔
987
    if (!partition_args(args, keys, n_parts)) return nullptr;
14 !
988
    auto out = dataframe::partition_id(to_dataframe(b), keys, n_parts);
10 !
989
    if (!out) {
10 ✔
990
        dftracer::utils::python::core::set_py_error(out.error());
4 !
991
        return nullptr;
2 ✔
992
    }
993
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
6 !
994
}
14 ✔
995

996
// hash_partition(keys, n_parts) -> list[DataFrame]; keys is a name or a
997
// sequence of names. The shuffle primitive for distributed group_by/join.
998
PyObject* DataFrame_hash_partition(PyObject* self, PyObject* args) {
2,250 ✔
999
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,250 ✔
1000
    if (!b) return nullptr;
2,250 !
1001
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
2,250 ✔
1002
    std::int64_t n_parts = 0;
2,250 ✔
1003
    if (!partition_args(args, keys, n_parts)) return nullptr;
2,250 !
1004
    auto found = dataframe::hash_partition(to_dataframe(b), keys, n_parts);
2,250 !
1005
    if (!found) {
2,250 !
1006
        dftracer::utils::python::core::set_py_error(found.error());
×
1007
        return nullptr;
1008
    }
1009
    return list_from(*found, [](DataFrame& part) {
34,304 !
1010
        return make_dataframe(std::move(part));
64,108 ✔
1011
    });
1012
}
2,250 ✔
1013

1014
// The expression of an AST, or the empty one for None.
1015
bool optional_expr(PyObject* ast, dataframe::Expr& out) {
5,264 ✔
1016
    return ast == Py_None ||
6,750 !
1017
           dftracer::utils::python::frame::build_expr_from_ast(ast, &out);
2,972 ✔
1018
}
1019

1020
// One (op, ast, out[, param[, by_ast[, udaf[, interp[, form]]]]]) spec tuple,
1021
// appended to `out`; `by_ast` and `udaf` may be None, `interp` is the
1022
// interpolation code of a quantile and `form` its QuantileForm code.
1023
bool agg_expr_spec_from_tuple(
2,732 ✔
1024
    PyObject* t, dftracer::utils::dstd::Vector<dataframe::AggExprSpec>& out) {
1025
    const Py_ssize_t tn = PyTuple_Check(t) ? PyTuple_GET_SIZE(t) : 0;
2,732 !
1026
    if (tn < 3 || tn > 8) {
2,732 !
NEW
1027
        PyErr_SetString(PyExc_TypeError,
×
1028
                        "each spec is (op, ast, out[, param[, by_ast[, udaf[, "
1029
                        "interp[, form]]]]])");
UNCOV
1030
        return false;
×
1031
    }
1032
    dataframe::AggExprSpec s;
2,732 ✔
1033
    s.op = static_cast<dataframe::AggOp>(PyLong_AsLong(PyTuple_GET_ITEM(t, 0)));
2,732 !
1034
    if (tn >= 4) {
2,732 ✔
1035
        s.param = PyFloat_AsDouble(PyTuple_GET_ITEM(t, 3));
2,732 !
1036
        if (s.param == -1.0 && PyErr_Occurred()) return false;
2,732 !
1037
    }
1,366 ✔
1038
    if (!optional_expr(PyTuple_GET_ITEM(t, 1), s.value)) return false;
2,732 !
1039
    if (tn >= 5 && !optional_expr(PyTuple_GET_ITEM(t, 4), s.by)) return false;
2,732 !
1040
    if (tn >= 6 && PyTuple_GET_ITEM(t, 5) != Py_None) {
2,732 !
1041
        // (name, [arg_ast, ...]): the UDAF the spec calls and its
1042
        // arguments after `value`.
1043
        PyObject* call = PyTuple_GET_ITEM(t, 5);
×
1044
        PyObject* fn = PyTuple_Check(call) && PyTuple_GET_SIZE(call) == 2
×
1045
                           ? PyTuple_GET_ITEM(call, 0)
×
1046
                           : nullptr;
1047
        PyObject* arg_asts = fn ? PyTuple_GET_ITEM(call, 1) : nullptr;
×
1048
        if (!fn || !PyList_Check(arg_asts)) {
×
1049
            PyErr_SetString(PyExc_TypeError,
×
1050
                            "a udaf spec is (name, [arg_ast, ...])");
1051
            return false;
1052
        }
1053
        const char* fn_name = PyUnicode_AsUTF8(fn);
×
1054
        if (!fn_name) return false;
×
1055
        s.fn = fn_name;
×
1056
        for (Py_ssize_t j = 0; j < PyList_GET_SIZE(arg_asts); ++j) {
×
1057
            dataframe::Expr arg;
×
1058
            if (!dftracer::utils::python::frame::build_expr_from_ast(
×
1059
                    PyList_GET_ITEM(arg_asts, j), &arg))
×
1060
                return false;
×
1061
            s.args.push_back(std::move(arg));
×
1062
        }
×
1063
    }
×
1064
    if (tn >= 7) {
2,732 ✔
1065
        const long interp = PyLong_AsLong(PyTuple_GET_ITEM(t, 6));
2,286 !
1066
        if (interp == -1 && PyErr_Occurred()) return false;
2,286 !
1067
        if (interp < 0 || interp > 4) {
2,286 !
1068
            PyErr_SetString(PyExc_ValueError,
×
1069
                            "a quantile interpolation code is 0 to 4");
1070
            return false;
1071
        }
1072
        s.interp = static_cast<dataframe::Interpolation>(interp);
2,286 ✔
1073
    }
1,143 !
1074
    if (tn == 8) {
2,509 ✔
1075
        const long form = PyLong_AsLong(PyTuple_GET_ITEM(t, 7));
2,286 !
1076
        if (form == -1 && PyErr_Occurred()) return false;
2,286 !
1077
        if (form < 0 || form > 1) {
2,286 !
NEW
1078
            PyErr_SetString(PyExc_ValueError, "a quantile form code is 0 or 1");
×
1079
            return false;
1080
        }
1081
        s.form = static_cast<dataframe::QuantileForm>(form);
2,286 ✔
1082
    }
1,143 !
1083
    const char* out_name = PyUnicode_AsUTF8(PyTuple_GET_ITEM(t, 2));
2,732 !
1084
    if (!out_name) return false;
2,732 !
1085
    s.out = out_name;
2,732 !
1086
    out.push_back(std::move(s));
2,732 !
1087
    return true;
1,366 ✔
1088
}
2,732 ✔
1089

1090
// _group_agg_expr(key, specs): the expression-aggregate workhorse. `key` is a
1091
// column name or a sequence of names (composite key). `specs` is a list of
1092
// (op_int, value_ast_or_None, out_name[, param[, by_ast]]); value ASTs
1093
// reference this batch's columns by index. `by_ast` is ArgMax's maximized
1094
// value. All value expressions compile in one CSE'd, pruned pass
1095
// (dataframe::group_agg_expr). The Python GroupBy serializes to this.
1096
PyObject* DataFrame_group_agg_expr(PyObject* self, PyObject* args) {
402 ✔
1097
    DataFrameObject* b = as_native<DataFrameObject>(self);
402 ✔
1098
    if (!b) return nullptr;
402 ✔
1099
    PyObject* key_obj = nullptr;
402 ✔
1100
    PyObject* specs = nullptr;
402 ✔
1101
    if (!PyArg_ParseTuple(args, "OO", &key_obj, &specs)) return nullptr;
402 ✔
1102
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
402 ✔
1103
    if (!strings_from_str_or_seq(key_obj, keys)) return nullptr;
402 !
1104
    DataFrame bat = to_dataframe(b);
402 !
1105
    dftracer::utils::dstd::Vector<dataframe::Expr> key_exprs;
402 ✔
1106
    key_exprs.reserve(keys.size());
402 !
1107
    for (const dftracer::utils::dstd::String& key : keys) {
702 !
1108
        std::int32_t ki = -1;
424 ✔
1109
        for (std::size_t i = 0; i < bat.names.size(); ++i)
698 !
1110
            if (bat.names[i] == key) {
548 ✔
1111
                ki = static_cast<std::int32_t>(i);
300 ✔
1112
                break;
300 ✔
1113
            }
1114
        if (ki < 0) {
300 ✔
1115
            PyErr_Format(PyExc_KeyError, "group_by: no column named %s",
×
1116
                         key.c_str());
1117
            return nullptr;
×
1118
        }
1119
        key_exprs.push_back(dataframe::expr_col(ki));
450 !
1120
    }
150 !
1121

1122
    dftracer::utils::dstd::Vector<dataframe::AggExprSpec> aggs;
402 ✔
1123
    if (!parse_seq<dataframe::AggExprSpec>(
402 !
1124
            specs, "specs must be a sequence", aggs,
201 ✔
1125
            [](PyObject* t,
2,732 ✔
1126
               dftracer::utils::dstd::Vector<dataframe::AggExprSpec>& o) {
1127
                return agg_expr_spec_from_tuple(t, o);
2,732 ✔
1128
            }))
1129
        return nullptr;
1130

1131
    dftracer::utils::dstd::Vector<const Series*> inputs;
402 ✔
1132
    inputs.reserve(bat.columns.size());
402 !
1133
    for (const Series& c : bat.columns) inputs.push_back(&c);
1,608 ✔
1134
    // An aggregate over a per-batch Python udf runs on the Python lane, which
1135
    // needs the GIL; nothing in this region touches Python.
1136
    auto grouped = release_gil([&] {
1,005 !
1137
        return dataframe::group_agg_expr(key_exprs, aggs, inputs, keys);
402 ✔
1138
    });
402 !
1139
    if (!grouped) {
402 !
1140
        dftracer::utils::python::core::set_py_error(grouped.error());
×
1141
        return nullptr;
1142
    }
1143
    return make_dataframe(std::move(*grouped));
402 !
1144
}
402 ✔
1145

1146
// Two-step / expression forms delegate to the Python GroupBy, which serializes
1147
// each spec and calls _group_agg_expr. `args[0:nk]` are the key names (a tuple,
1148
// even for one key); `args[nk:]` are the specs.
1149
PyObject* delegate_groupby(PyObject* self, PyObject* args, Py_ssize_t nk) {
2 ✔
1150
    PyObject* mod = PyImport_ImportModule("dftracer.utils._groupby");
2 ✔
1151
    if (!mod) return nullptr;
2 !
1152
    PyObject* gb_type = PyObject_GetAttrString(mod, "GroupBy");
2 ✔
1153
    Py_DECREF(mod);
2 !
1154
    if (!gb_type) return nullptr;
2 !
1155
    PyObject* keys = PyTuple_GetSlice(args, 0, nk);
2 ✔
1156
    if (!keys) {
2 ✔
1157
        Py_DECREF(gb_type);
×
1158
        return nullptr;
×
1159
    }
1160
    PyObject* gb = PyObject_CallFunctionObjArgs(gb_type, self, keys, nullptr);
2 ✔
1161
    Py_DECREF(keys);
2 !
1162
    Py_DECREF(gb_type);
2 !
1163
    if (!gb) return nullptr;
2 !
1164
    Py_ssize_t n = PyTuple_GET_SIZE(args);
2 ✔
1165
    if (n == nk) return gb;             // two-step: hand back the GroupBy
2 ✔
1166
    PyObject* rest =
3 ✔
1167
        PyTuple_GetSlice(args, nk, n);  // the specs, as an arg tuple
2 ✔
1168
    PyObject* aggm = rest ? PyObject_GetAttrString(gb, "agg") : nullptr;
2 !
1169
    Py_DECREF(gb);
2 !
1170
    PyObject* res = aggm ? PyObject_Call(aggm, rest, nullptr) : nullptr;
2 !
1171
    Py_XDECREF(aggm);
2 ✔
1172
    Py_XDECREF(rest);
2 ✔
1173
    return res;
2 ✔
1174
}
1 ✔
1175

1176
// group_by(*keys_and_specs). The leading run of plain column-name strings
1177
// (not "count" and not containing ':') are the (possibly composite) key; a
1178
// trailing run of legacy "op[:column]" strings runs inline, anything else
1179
// (no specs, or an expression/Agg spec) delegates to the Python GroupBy and
1180
// the expression-aggregate path (CSE + pruner).
1181
PyObject* DataFrame_group_by(PyObject* self, PyObject* args) {
10,072 ✔
1182
    DataFrameObject* b = as_native<DataFrameObject>(self);
10,072 ✔
1183
    if (!b) return nullptr;
10,072 !
1184
    Py_ssize_t n = PyTuple_GET_SIZE(args);
10,072 ✔
1185
    if (n < 1) {
10,072 ✔
1186
        PyErr_SetString(PyExc_TypeError, "group_by(*keys, *aggs) needs a key");
×
1187
        return nullptr;
×
1188
    }
1189
    Py_ssize_t nk = 0;
5,036 ✔
1190
    for (; nk < n; ++nk) {
21,298 ✔
1191
        PyObject* a = PyTuple_GET_ITEM(args, nk);
21,298 !
1192
        if (!PyUnicode_Check(a)) break;
21,298 ✔
1193
        const char* s = PyUnicode_AsUTF8(a);
21,296 ✔
1194
        if (!s) return nullptr;
21,296 ✔
1195
        const dftracer::utils::dstd::String sv(s);
21,296 ✔
1196
        if (sv == "count" ||
21,296 ✔
1197
            sv.find(':') != dftracer::utils::dstd::String::npos)
18,704 ✔
1198
            break;
5,035 ✔
1199
    }
21,298 !
1200
    if (nk == 0) nk = 1;  // args[0] is always at least one key
10,072 ✔
1201
    bool rest_legacy = n > nk;
10,072 ✔
1202
    for (Py_ssize_t i = nk; i < n && rest_legacy; ++i)
28,642 ✔
1203
        rest_legacy = PyUnicode_Check(PyTuple_GET_ITEM(args, i)) != 0;
18,570 ✔
1204
    if (n == nk || !rest_legacy) return delegate_groupby(self, args, nk);
10,072 ✔
1205

1206
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
10,070 ✔
1207
    keys.reserve(static_cast<std::size_t>(nk));
10,070 !
1208
    for (Py_ssize_t i = 0; i < nk; ++i) {
21,294 !
1209
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
11,224 !
1210
        if (!s) return nullptr;
11,224 !
1211
        keys.emplace_back(s);
11,224 !
1212
    }
5,612 !
1213
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> specs;
10,070 ✔
1214
    specs.reserve(static_cast<std::size_t>(n - nk));
10,070 !
1215
    for (Py_ssize_t i = nk; i < n; ++i) {
28,638 !
1216
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
18,568 !
1217
        if (!s) return nullptr;
18,568 ✔
1218
        specs.emplace_back(s);
18,568 !
1219
    }
9,284 !
1220
    return run_batch_op(b, [&](const DataFrame& frame) {
15,105 !
1221
        dftracer::utils::dstd::Vector<dataframe::GroupAgg> aggs;
10,070 ✔
1222
        aggs.reserve(specs.size());
10,070 !
1223
        for (const dftracer::utils::dstd::String& spec : specs)
28,637 ✔
1224
            aggs.push_back(group_agg_from_spec(spec));
27,852 !
1225
        return dataframe::group_by(frame, keys, aggs);
15,102 !
1226
    });
10,071 ✔
1227
}
10,071 ✔
1228

1229
// join(other, how="inner", on=1): equi-join on the first `on` (leading) key
1230
// columns; how is inner|left|right|full|semi|anti.
1231
PyObject* DataFrame_join(PyObject* self, PyObject* args, PyObject* kwds) {
8,158 ✔
1232
    return batch_other_args<dftracer::utils::python::frame::JoinArgs>(
8,158 ✔
1233
        self, args, kwds,
4,079 ✔
1234
        [](const DataFrame& frame, const DataFrame& other,
8,142 ✔
1235
           dftracer::utils::python::frame::JoinArgs& a) {
1236
            return dataframe::join(frame, other, a.left, a.right, a.how,
12,213 ✔
1237
                                   a.suffix, a.nulls_equal != 0);
8,142 ✔
1238
        });
8,150 ✔
1239
}
1240

1241
PyObject* DataFrame_compare_agg(PyObject* self, PyObject* args) {
18 ✔
1242
    DataFrameObject* b = as_native<DataFrameObject>(self);
18 ✔
1243
    if (!b) return nullptr;
18 !
1244
    PyObject* other = nullptr;
18 ✔
1245
    Py_ssize_t n_key = 1;
18 ✔
1246
    if (!PyArg_ParseTuple(args, "On", &other, &n_key)) return nullptr;
18 !
1247
    DataFrameObject* o = as_native<DataFrameObject>(other);
18 ✔
1248
    if (!o) return nullptr;
18 !
1249
    const DataFrame other_frame = to_dataframe(o);
18 ✔
1250
    return run_batch_op(b, [&](const DataFrame& frame) {
27 !
1251
        return dataframe::compare_agg(frame, other_frame,
27 ✔
1252
                                      static_cast<std::int64_t>(n_key));
18 ✔
1253
    });
9 ✔
1254
}
18 ✔
1255

1256
// unpivot(id_vars, value_vars) / melt: reshape wide -> long.
1257
PyObject* DataFrame_unpivot(PyObject* self, PyObject* args, PyObject* kwds) {
336 ✔
1258
    DataFrameObject* b = as_native<DataFrameObject>(self);
336 ✔
1259
    if (!b) return nullptr;
336 !
1260
    PyObject* id_obj = nullptr;
336 ✔
1261
    PyObject* val_obj = nullptr;
336 ✔
1262
    if (!parse_kw<"OO">(args, kwds, {"id_vars", "value_vars"}, &id_obj,
336 ✔
1263
                        &val_obj))
1264
        return nullptr;
1265
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> id_vars,
336 ✔
1266
        value_vars;
336 ✔
1267
    if (!names_from_obj(id_obj, id_vars)) return nullptr;
336 !
1268
    if (!names_from_obj(val_obj, value_vars)) return nullptr;
336 !
1269
    return run_batch_op(b, [&](const DataFrame& frame) {
504 !
1270
        return dataframe::unpivot(frame, id_vars, value_vars);
336 ✔
1271
    });
168 ✔
1272
}
336 ✔
1273

1274
PyObject* DataFrame_explode(PyObject* self, PyObject* arg) {
40 ✔
1275
    DataFrameObject* b = as_native<DataFrameObject>(self);
40 ✔
1276
    if (!b) return nullptr;
40 !
1277
    const char* name = PyUnicode_AsUTF8(arg);
40 ✔
1278
    if (!name) {
40 ✔
1279
        PyErr_SetString(PyExc_TypeError, "explode() expects a column name");
×
1280
        return nullptr;
×
1281
    }
1282
    return run_batch_op(b, [&](const DataFrame& frame) {
60 ✔
1283
        return dataframe::explode(frame, name);
40 ✔
1284
    });
20 ✔
1285
}
20 ✔
1286

1287
PyObject* DataFrame_window(PyObject* self, PyObject* args, PyObject* kwds) {
56 ✔
1288
    return batch_args<dftracer::utils::python::frame::WindowArgs>(
56 ✔
1289
        self, args, kwds,
28 ✔
1290
        [](const DataFrame& frame,
56 ✔
1291
           dftracer::utils::python::frame::WindowArgs& a) {
1292
            dftracer::utils::dstd::Vector<dataframe::WindowColumn> specv;
56 ✔
1293
            specv.reserve(a.specs.specs.size());
56 !
1294
            for (const dftu_window_spec& w : a.specs.specs)
204 ✔
1295
                specv.push_back(dataframe::window_column(w));
296 !
1296
            return dataframe::window(frame, a.partition, a.order, specv);
84 !
1297
        });
56 ✔
1298
}
1299

1300
PyObject* DataFrame_gap_fill(PyObject* self, PyObject* args, PyObject* kwds) {
24 ✔
1301
    return batch_args<dftracer::utils::python::frame::GapFillArgs>(
24 ✔
1302
        self, args, kwds,
12 ✔
1303
        [](const DataFrame& frame,
22 ✔
1304
           dftracer::utils::python::frame::GapFillArgs& a) {
1305
            dftracer::utils::dstd::Optional<
22 ✔
1306
                dftracer::utils::dstd::Pair<std::int64_t, std::int64_t>>
1307
                range;
22 ✔
1308
            if (a.has_range)
22 ✔
1309
                range = dftracer::utils::dstd::Pair<std::int64_t, std::int64_t>{
6 ✔
1310
                    a.start, a.end};
4 ✔
1311
            return dataframe::gap_fill(
66 ✔
1312
                frame, a.partition, a.time, static_cast<std::int64_t>(a.bucket),
44 ✔
1313
                a.values, static_cast<dataframe::GapFillMode>(a.mode), range);
33 ✔
1314
        });
23 ✔
1315
}
1316

1317
PyObject* DataFrame_asof(PyObject* self, PyObject* args, PyObject* kwds) {
54 ✔
1318
    return batch_other_args<dftracer::utils::python::frame::AsofArgs>(
54 ✔
1319
        self, args, kwds,
27 ✔
1320
        [](const DataFrame& frame, const DataFrame& other,
52 ✔
1321
           dftracer::utils::python::frame::AsofArgs& a) {
1322
            return dataframe::asof(
130 ✔
1323
                frame, other, a.on, a.by,
104 ✔
1324
                static_cast<dataframe::AsofDirection>(a.direction),
52 ✔
1325
                a.tolerance);
52 ✔
1326
        });
53 ✔
1327
}
1328

1329
PyObject* DataFrame_interval(PyObject* self, PyObject* args, PyObject* kwds) {
20 ✔
1330
    return batch_other_args<dftracer::utils::python::frame::IntervalArgs>(
20 ✔
1331
        self, args, kwds,
10 ✔
1332
        [](const DataFrame& frame, const DataFrame& other,
20 ✔
1333
           dftracer::utils::python::frame::IntervalArgs& a) {
1334
            return dataframe::interval(frame, other, a.point, a.lo, a.hi, a.by,
30 ✔
1335
                                       a.outer != 0);
20 ✔
1336
        });
20 ✔
1337
}
1338

1339
PyObject* DataFrame_unnest(PyObject* self, PyObject* args, PyObject* kwds) {
36 ✔
1340
    return batch_args<dftracer::utils::python::frame::UnnestArgs>(
36 ✔
1341
        self, args, kwds,
18 ✔
1342
        [](const DataFrame& frame,
36 ✔
1343
           dftracer::utils::python::frame::UnnestArgs& a) {
1344
            return dataframe::unnest(frame, a.column, a.keep_empty != 0);
36 ✔
1345
        });
36 ✔
1346
}
1347

1348
PyObject* DataFrame_to_dummies(PyObject* self, PyObject* arg) {
8 ✔
1349
    DataFrameObject* b = as_native<DataFrameObject>(self);
8 ✔
1350
    if (!b) return nullptr;
8 !
1351
    const char* name = PyUnicode_AsUTF8(arg);
8 ✔
1352
    if (!name) {
8 ✔
1353
        PyErr_SetString(PyExc_TypeError, "to_dummies() expects a column name");
×
1354
        return nullptr;
×
1355
    }
1356
    return run_batch_op(b, [&](const DataFrame& frame) {
12 ✔
1357
        return dataframe::to_dummies(frame, name);
8 ✔
1358
    });
4 ✔
1359
}
4 ✔
1360

1361
// pivot(index, columns, values, agg="first"): long -> wide.
1362
PyObject* DataFrame_pivot(PyObject* self, PyObject* args, PyObject* kwds) {
30 ✔
1363
    DataFrameObject* b = as_native<DataFrameObject>(self);
30 ✔
1364
    if (!b) return nullptr;
30 !
1365
    const char* index = nullptr;
30 ✔
1366
    const char* columns = nullptr;
30 ✔
1367
    const char* values = nullptr;
30 ✔
1368
    const char* agg = "first";
30 ✔
1369
    if (!parse_kw<"sss|s">(args, kwds, {"index", "columns", "values", "agg"},
30 ✔
1370
                           &index, &columns, &values, &agg))
1371
        return nullptr;
1372
    return run_batch_op(b, [&](const DataFrame& frame) {
45 ✔
1373
        return dataframe::pivot(frame, index, columns, values, agg);
30 ✔
1374
    });
15 ✔
1375
}
15 ✔
1376

1377
// group_by_dynamic(time_col, every, period=None, aggs=[...]): tumbling/sliding
1378
// time-window aggregation. aggs mirror the group_by string-spec format.
1379
PyObject* DataFrame_group_by_dynamic(PyObject* self, PyObject* args,
36 ✔
1380
                                     PyObject* kwds) {
1381
    DataFrameObject* b = as_native<DataFrameObject>(self);
36 ✔
1382
    if (!b) return nullptr;
36 !
1383
    const char* time_col = nullptr;
36 ✔
1384
    long long every = 0;
36 ✔
1385
    PyObject* period_obj = Py_None;
36 ✔
1386
    PyObject* aggs_obj = Py_None;
36 ✔
1387
    PyObject* origin_obj = Py_None;  // int (explicit) or "min"
36 ✔
1388
    if (!parse_kw<"sL|OOO">(
36 ✔
1389
            args, kwds, {"time_col", "every", "period", "aggs", "origin"},
18 ✔
1390
            &time_col, &every, &period_obj, &aggs_obj, &origin_obj))
1391
        return nullptr;
1392
    std::int64_t period = 0;
36 ✔
1393
    if (period_obj && period_obj != Py_None) {
36 !
1394
        period = PyLong_AsLongLong(period_obj);
2 ✔
1395
        if (period == -1 && PyErr_Occurred()) return nullptr;
2 !
1396
    }
1 ✔
1397
    std::int64_t origin = 0;
36 ✔
1398
    bool origin_min = false;
36 ✔
1399
    if (origin_obj && origin_obj != Py_None) {
36 !
1400
        if (PyUnicode_Check(origin_obj)) {
4 ✔
1401
            const char* s = PyUnicode_AsUTF8(origin_obj);
2 ✔
1402
            if (!s) return nullptr;
2 !
1403
            if (dftracer::utils::dstd::String(s) != "min") {
2 !
1404
                PyErr_SetString(PyExc_ValueError,
×
1405
                                "group_by_dynamic: origin must be an int or "
1406
                                "\"min\"");
1407
                return nullptr;
×
1408
            }
1409
            origin_min = true;
2 ✔
1410
        } else {
1 !
1411
            origin = PyLong_AsLongLong(origin_obj);
2 ✔
1412
            if (origin == -1 && PyErr_Occurred()) return nullptr;
2 !
1413
        }
1414
    }
2 ✔
1415
    dftracer::utils::dstd::Vector<dataframe::GroupAgg> aggs;
36 ✔
1416
    if (aggs_obj && aggs_obj != Py_None && !aggs_from_seq(aggs_obj, aggs))
36 !
1417
        return nullptr;
1418
    return run_batch_op(b, [&](const DataFrame& frame) {
54 !
1419
        return dataframe::group_by_dynamic(frame, time_col,
72 ✔
1420
                                           static_cast<std::int64_t>(every),
36 ✔
1421
                                           period, aggs, origin, origin_min);
54 ✔
1422
    });
18 ✔
1423
}
36 ✔
1424

1425
PyObject* DataFrame_concat(PyObject* self, PyObject* args, PyObject* kwds) {
812 ✔
1426
    DataFrameObject* b = as_native<DataFrameObject>(self);
812 ✔
1427
    if (!b) return nullptr;
812 !
1428
    // `how` is the only keyword; every positional arg is another DataFrame.
1429
    dataframe::ConcatHow how = dataframe::ConcatHow::Vertical;
812 ✔
1430
    if (kwds) {
812 ✔
1431
        if (PyObject* h = PyDict_GetItemString(kwds, "how")) {
888 ✔
1432
            const char* s = PyUnicode_AsUTF8(h);
592 ✔
1433
            if (!s) return nullptr;
592 !
1434
            if (std::strcmp(s, "diagonal") == 0)
592 ✔
1435
                how = dataframe::ConcatHow::Diagonal;
46 ✔
1436
            else if (std::strcmp(s, "vertical") != 0) {
546 ✔
1437
                PyErr_SetString(PyExc_ValueError,
2 ✔
1438
                                "how must be 'vertical' or 'diagonal'");
1439
                return nullptr;
2 ✔
1440
            }
1441
        }
296 ✔
1442
        if (PyDict_Size(kwds) > (PyDict_GetItemString(kwds, "how") ? 1 : 0)) {
590 !
1443
            PyErr_SetString(PyExc_TypeError,
×
1444
                            "concat() got an unexpected keyword argument");
1445
            return nullptr;
×
1446
        }
1447
    }
295 ✔
1448
    dftracer::utils::dstd::Vector<DataFrame> owned;
810 ✔
1449
    owned.reserve(1 + static_cast<std::size_t>(PyTuple_GET_SIZE(args)));
810 !
1450
    owned.push_back(to_dataframe(b));
1,215 !
1451
    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(args); ++i) {
2,006 !
1452
        DataFrameObject* o =
1,794 !
1453
            as_native<DataFrameObject>(PyTuple_GET_ITEM(args, i));
1,196 !
1454
        if (!o) return nullptr;
1,196 !
1455
        owned.push_back(to_dataframe(o));
1,794 !
1456
    }
598 !
1457
    dftracer::utils::dstd::Vector<const DataFrame*> parts;
810 ✔
1458
    parts.reserve(owned.size());
810 !
1459
    for (const DataFrame& x : owned) parts.push_back(&x);
2,816 ✔
1460
    return run_batch_op(b, [&] { return dataframe::concat(parts, how); });
1,620 !
1461
}
811 ✔
1462

1463
// Arrow/pandas/polars conversion and pickling live in the Python wrapper
1464
// (dftracer.utils.frame); the native handle only exposes the zero-copy
1465
// __arrow_c_array__ / __arrow_c_stream__ capsules.
1466

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

1469
PyObject* DataFrame_arrow_c_array(PyObject* self, PyObject*) {
34 ✔
1470
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
1471
    if (!b) return nullptr;
34 !
1472
    return dftracer::utils::python::core::array_capsules(
34 !
1473
        arrow::to_arrow(to_dataframe(b)));
51 !
1474
}
17 ✔
1475

1476
// __arrow_c_stream__: a stream of the struct (one batch per chunk of a
1477
// collected frame), so pa.table(batch) / pl.from_arrow(batch) import every
1478
// column zero-copy without an explicit to_arrow(). The single struct array
1479
// carries all fields.
1480
PyObject* DataFrame_arrow_c_stream(PyObject* self, PyObject* args,
4,402 ✔
1481
                                   PyObject* kwds) {
1482
    PyObject* requested_schema = Py_None;
4,402 ✔
1483
    if (!parse_kw<"|O">(args, kwds, {"requested_schema"}, &requested_schema))
4,402 ✔
1484
        return nullptr;
1485
    if (!dftracer::utils::python::core::no_requested_schema(requested_schema))
4,402 ✔
1486
        return nullptr;
1 ✔
1487
    DataFrameObject* b = as_native<DataFrameObject>(self);
4,400 ✔
1488
    if (!b) return nullptr;
4,400 !
1489
    const dataframe::DataFrame frame = to_dataframe(b);
4,400 ✔
1490
    auto stream = dftracer::utils::dstd::make_unique<ArrowArrayStream>();
4,400 !
1491
    auto status = arrow::to_arrow_stream(frame, stream.get());
4,400 !
1492
    if (!status) {
4,400 ✔
1493
        dftracer::utils::python::core::set_py_error(status.error());
×
1494
        return nullptr;
1495
    }
1496
    return dftracer::utils::python::core::stream_capsule(std::move(stream));
4,400 !
1497
}
4,401 ✔
1498

1499
// to_ipc() -> bytes: the frame serialized as an Arrow IPC stream (schema + one
1500
// record batch + EOS), so a consumer needs no pyarrow to produce .arrow bytes.
1501
PyObject* DataFrame_to_ipc(PyObject* self, PyObject*) {
4 ✔
1502
    DataFrameObject* b = as_native<DataFrameObject>(self);
4 ✔
1503
    if (!b) return nullptr;
4 !
1504
    return guard([&]() -> PyObject* {
6 ✔
1505
        auto writer = arrow::Writer::to_buffer();
4 ✔
1506
        const DataFrame frame = to_dataframe(b);
4 !
1507
        auto status = without_gil(frame.num_rows(), [&] {
10 !
1508
            auto written = writer.write(frame);
4 ✔
1509
            if (written) written = writer.finish();
4 !
1510
            return written;
4 ✔
1511
        });
4 !
1512
        if (!status) {
4 ✔
1513
            dftracer::utils::python::core::set_py_error(status.error());
×
1514
            return nullptr;
1515
        }
1516
        const auto bytes = writer.take_bytes();
4 !
1517
        return PyBytes_FromStringAndSize(
4 !
1518
            reinterpret_cast<const char*>(bytes.data()),
4 ✔
1519
            static_cast<Py_ssize_t>(bytes.size()));
4 !
1520
    });
6 ✔
1521
}
2 ✔
1522

1523
PyObject* DataFrame_to_bytes(PyObject* self, PyObject*) {
866 ✔
1524
    DataFrameObject* b = as_native<DataFrameObject>(self);
866 ✔
1525
    if (!b) return nullptr;
866 !
1526
    return guard([&]() -> PyObject* {
1,299 ✔
1527
        return dftracer::utils::python::frame::frame_bytes(to_dataframe(b));
866 !
1528
    });
1529
}
433 ✔
1530

1531
PyObject* dataframe_from_bytes(PyObject* /*self*/, PyObject* obj) {
866 ✔
1532
    dftracer::utils::dstd::Optional<DataFrame> f;
866 ✔
1533
    if (!dftracer::utils::python::frame::frame_from_buffer(obj, f))
866 !
1534
        return nullptr;
1535
    if (!f) {
866 !
1536
        PyErr_SetString(PyExc_ValueError,
×
1537
                        "not a DataFrame written by this version");
1538
        return nullptr;
1539
    }
1540
    return make_dataframe(std::move(*f));
866 !
1541
}
866 ✔
1542

1543
// One column buffer of a frame, read only, that a pickle carries out of band.
1544
// The view holds its block, so the bytes live as long as this object.
1545
struct FrameBufferObject {
1546
    PyObject_HEAD dataframe::BufferView view;
1547
};
1548

1549
void FrameBuffer_dealloc(PyObject* self) {
11,024 ✔
1550
    reinterpret_cast<FrameBufferObject*>(self)->view.~BufferView();
11,024 ✔
1551
    Py_TYPE(self)->tp_free(self);
11,024 ✔
1552
}
11,024 ✔
1553

1554
int FrameBuffer_getbuffer(PyObject* self, Py_buffer* view, int flags) {
22,202 ✔
1555
    static std::uint8_t empty = 0;
11,071 ✔
1556
    const dataframe::BufferView& v =
33,333 ✔
1557
        reinterpret_cast<FrameBufferObject*>(self)->view;
11,131 ✔
1558
    auto* data = const_cast<std::uint8_t*>(v.data());
22,202 ✔
1559
    return PyBuffer_FillInfo(view, self, data != nullptr ? data : &empty,
22,234 ✔
1560
                             static_cast<Py_ssize_t>(v.size()), 1, flags);
22,202 ✔
1561
}
11,131 ✔
1562

1563
PyBufferProcs FrameBuffer_as_buffer = {FrameBuffer_getbuffer, nullptr};
1564

1565
PyTypeObject FrameBufferType = [] {
1566
    PyTypeObject t{.ob_base = PyVarObject_HEAD_INIT(nullptr, 0)};
1567
    t.tp_name = "dftracer.utils.dftracer_utils_ext._FrameBuffer";
1568
    t.tp_basicsize = sizeof(FrameBufferObject);
1569
    t.tp_dealloc = FrameBuffer_dealloc;
1570
    t.tp_flags = Py_TPFLAGS_DEFAULT;
1571
    t.tp_doc = "One read-only column buffer of a pickled DataFrame.";
1572
    t.tp_as_buffer = &FrameBuffer_as_buffer;
1573
    return t;
1574
}();
1575

1576
PyObject* dataframe_to_buffers(PyObject* /*self*/, PyObject* obj) {
3,643 ✔
1577
    DataFrameObject* b = as_native<DataFrameObject>(obj);
3,643 ✔
1578
    if (!b) return nullptr;
3,643 !
1579
    return guard([&]() -> PyObject* {
5,470 ✔
1580
        const DataFrame frame = to_dataframe(b);
3,643 ✔
1581
        auto out = without_gil(frame.num_rows(), [&] {
9,102 !
1582
            return dataframe::frame_to_buffers(frame);
3,643 !
1583
        });
3,643 !
1584
        if (!out) {
3,643 ✔
1585
            PyErr_SetString(PyExc_TypeError, out.error().c_str());
×
1586
            return nullptr;
1587
        }
1588
        PyObject* header = PyBytes_FromStringAndSize(
5,470 !
1589
            out->header.data(), static_cast<Py_ssize_t>(out->header.size()));
3,643 !
1590
        if (!header) return nullptr;
3,643 !
1591
        PyObject* list =
3,643 ✔
1592
            PyList_New(static_cast<Py_ssize_t>(out->buffers.size()));
3,643 !
1593
        if (!list) {
3,643 !
1594
            Py_DECREF(header);
×
1595
            return nullptr;
×
1596
        }
1597
        for (std::size_t i = 0; i < out->buffers.size(); ++i) {
14,667 !
1598
            auto* item = PyObject_New(FrameBufferObject, &FrameBufferType);
11,024 !
1599
            if (!item) {
11,024 !
1600
                Py_DECREF(header);
×
1601
                Py_DECREF(list);
×
1602
                return nullptr;
×
1603
            }
1604
            new (&item->view) dataframe::BufferView(std::move(out->buffers[i]));
11,024 ✔
1605
            PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i),
11,024 !
1606
                            reinterpret_cast<PyObject*>(item));
1607
        }
5,527 !
1608
        return Py_BuildValue("(NN)", header, list);
3,643 !
1609
    });
3,643 ✔
1610
}
1,827 ✔
1611

1612
struct HeldPyBuffer {
1613
    Py_buffer view;
1614
};
1615

1616
// A received buffer is released when the last column that reads it goes,
1617
// which may be on a thread that does not hold the GIL. After the interpreter
1618
// exits the buffer is left to the process exit.
1619
void release_held_buffer(const void* p) {
11,230 ✔
1620
    dstd::UniquePtr<HeldPyBuffer> held(
16,860 !
1621
        static_cast<HeldPyBuffer*>(const_cast<void*>(p)));
11,230 ✔
1622
    if (PyGILState_Check()) {
11,230 !
1623
        PyBuffer_Release(&held->view);
11,230 !
1624
        return;
5,630 ✔
1625
    }
1626
    if (!python::runtime::enter_python()) {
×
1627
        (void)held.release();
×
1628
        return;
×
1629
    }
1630
    PyGILState_STATE gil = PyGILState_Ensure();
×
1631
    PyBuffer_Release(&held->view);
×
1632
    PyGILState_Release(gil);
×
1633
    python::runtime::leave_python();
×
1634
}
11,230 !
1635

1636
PyObject* dataframe_from_buffers(PyObject* /*self*/, PyObject* args) {
3,651 ✔
1637
    PyObject* header_obj = nullptr;
3,651 ✔
1638
    PyObject* buffers_obj = nullptr;
3,651 ✔
1639
    if (!PyArg_ParseTuple(args, "OO", &header_obj, &buffers_obj))
3,651 !
1640
        return nullptr;
1641
    PyObject* seq = PySequence_Fast(buffers_obj, "buffers must be a sequence");
3,651 ✔
1642
    if (!seq) return nullptr;
3,651 !
1643
    const Py_ssize_t count = PySequence_Fast_GET_SIZE(seq);
3,651 ✔
1644
    dstd::Vector<dataframe::ReceivedBuffer> received;
3,651 ✔
1645
    received.reserve(static_cast<std::size_t>(count));
3,651 !
1646
    for (Py_ssize_t i = 0; i < count; ++i) {
14,881 !
1647
        auto held = dstd::make_unique<HeldPyBuffer>();
11,230 !
1648
        if (PyObject_GetBuffer(PySequence_Fast_GET_ITEM(seq, i), &held->view,
11,230 !
1649
                               PyBUF_SIMPLE) < 0) {
5,630 !
1650
            Py_DECREF(seq);
×
1651
            return nullptr;
×
1652
        }
1653
        const auto* data = static_cast<const std::uint8_t*>(held->view.buf);
11,230 !
1654
        const auto size = static_cast<std::size_t>(held->view.len);
11,230 ✔
1655
        const bool fixed = held->view.readonly != 0;
11,230 ✔
1656
        received.push_back(
11,230 ✔
1657
            {data, size, fixed,
5,630 ✔
1658
             dstd::adopt_shared_ptr(static_cast<const void*>(held.release()),
11,230 !
1659
                                    release_held_buffer)});
1660
    }
11,230 !
1661
    Py_DECREF(seq);
3,651 !
1662
    Py_buffer header;
3,651 ✔
1663
    if (PyObject_GetBuffer(header_obj, &header, PyBUF_SIMPLE) < 0)
3,651 !
1664
        return nullptr;
1665
    auto f = dataframe::frame_from_buffers(
5,482 ✔
1666
        dstd::StringView(static_cast<const char*>(header.buf),
5,482 ✔
1667
                         static_cast<std::size_t>(header.len)),
3,651 ✔
1668
        received);
3,651 !
1669
    PyBuffer_Release(&header);
3,651 !
1670
    if (!f) {
3,651 ✔
1671
        PyErr_SetString(PyExc_ValueError,
8 !
1672
                        "not a DataFrame pickled by this version");
1673
        return nullptr;
4 ✔
1674
    }
1675
    return make_dataframe(std::move(*f));
3,643 !
1676
}
9,251 !
1677

1678
PyObject* DataFrame_get_num_rows(PyObject* self, void*) {
95,434 ✔
1679
    DataFrameObject* b = as_native<DataFrameObject>(self);
95,434 ✔
1680
    if (!b) return nullptr;
95,434 !
1681
    return PyLong_FromLongLong(b->st.length());
95,434 ✔
1682
}
47,717 ✔
1683
PyObject* DataFrame_get_num_columns(PyObject* self, void*) {
×
1684
    DataFrameObject* b = as_native<DataFrameObject>(self);
×
1685
    if (!b) return nullptr;
×
1686
    return PyLong_FromSsize_t(static_cast<Py_ssize_t>(b->names.size()));
×
1687
}
1688
PyObject* DataFrame_get_column_names(PyObject* self, void*) {
54,416 ✔
1689
    return column_name_list(self, false);
54,416 ✔
1690
}
1691

1692
// lazy() -> LazyFrame: start a deferred query over a copy of this batch.
1693
PyObject* DataFrame_lazy(PyObject* self, PyObject*) {
2,486,698 ✔
1694
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,486,698 ✔
1695
    if (!b) return nullptr;
2,486,698 !
1696
    return guard([&] {
3,574,566 ✔
1697
        return dftracer::utils::python::frame::wrap_lazyframe(
2,486,698 !
1698
            dataframe::lazy(to_dataframe(b)));
3,885,528 !
1699
    });
1700
}
1,087,868 ✔
1701

1702
PyMethodDef DataFrame_methods[] = {
1703
    {"lazy", DataFrame_lazy, METH_NOARGS,
1704
     "lazy() -> LazyFrame, a deferred query over this batch."},
1705
    {"keys", DataFrame_keys, METH_NOARGS,
1706
     "Series names, in order; the row index columns are not listed."},
1707
    {"_replace", DataFrame_replace, METH_O,
1708
     "_replace(other) -> None\n\nTake the columns of `other`, in place."},
1709
    {"share", DataFrame_share, METH_NOARGS,
1710
     "share() -> DataFrame\n\nA new DataFrame over the same columns and "
1711
     "index names."},
1712
    {"index_names", DataFrame_index_names, METH_NOARGS,
1713
     "index_names() -> list[str]\n\nThe row index columns, in order; [] "
1714
     "when the frame has no index."},
1715
    {"with_index", DataFrame_with_index, METH_O,
1716
     "with_index(names) -> DataFrame\n\nThe same columns under the row index "
1717
     "`names` ([] drops the index)."},
1718
    {"filter", DataFrame_filter, METH_O,
1719
     "filter(mask) -> DataFrame keeping rows where the Bool mask is true."},
1720
    {"select", DataFrame_select, METH_VARARGS,
1721
     "select(*names) -> DataFrame projecting the named columns (zero-copy)."},
1722
    {"rename", DataFrame_rename, METH_O,
1723
     "rename({old: new}) -> DataFrame with columns renamed (zero-copy)."},
1724
    {"with_column", DataFrame_with_column, METH_VARARGS,
1725
     "with_column(name, Series) -> DataFrame adding/replacing a column."},
1726
    {"_locate", DataFrame_locate, METH_O,
1727
     "_locate(keys) -> (positions, missing): the rows whose index labels equal "
1728
     "the key Series (one per level), and the keys no label matches."},
1729
    {"_locate_range", DataFrame_locate_range, METH_VARARGS,
1730
     "_locate_range(start, stop) -> (offset, length): the rows between two "
1731
     "index label bounds (lists of one-row Series, empty for an open end)."},
1732
    {"_reindex", DataFrame_reindex, METH_VARARGS,
1733
     "_reindex(keys, method, limit, tolerance, fill, nanos=None) -> DataFrame "
1734
     "on the index "
1735
     "label key Series (one per level); method 0 none, 1 pad, 2 backfill, 3 "
1736
     "nearest, limit -1 for none, tolerance infinite for none, fill a one-row "
1737
     "Series or None, nanos a tolerance as whole nanoseconds for temporal "
1738
     "labels."},
1739
    {"_align_rows", DataFrame_align_rows, METH_VARARGS,
1740
     "_align_rows(other, how, fill) -> (left, right): the rows of two frames "
1741
     "on the joined index labels; how is 0 inner, 1 left, 2 right, 3 outer."},
1742
    {"take", DataFrame_take, METH_O,
1743
     "take(indices) -> DataFrame gathered at the given row indices."},
1744
    {"column_index",
1745
     DFTRACER_UTILS_PYCFUNCTION(
1746
         (dftracer::utils::python::core::kw_one<"column_index", "name",
1747
                                                DataFrame_column_index>)),
1748
     METH_VARARGS | METH_KEYWORDS,
1749
     "column_index(name) -> int index of a column, or -1 if absent."},
1750
    {"head", batch_count<dataframe::head>, METH_O,
1751
     "head(n) -> DataFrame of the first n rows."},
1752
    {"tail", batch_count<dataframe::tail>, METH_O,
1753
     "tail(n) -> DataFrame of the last n rows."},
1754
    {"reverse", batch_noarg<dataframe::reverse>, METH_NOARGS,
1755
     "reverse() -> DataFrame with rows reversed."},
1756
    {"drop_nulls", batch_noarg<dataframe::drop_nulls>, METH_NOARGS,
1757
     "drop_nulls() -> DataFrame dropping rows null in any column."},
1758
    {"fill_null", DataFrame_fill_null, METH_O,
1759
     "fill_null(value) -> DataFrame with nulls filled in every column."},
1760
    {"drop_nans", batch_noarg<dataframe::drop_nans>, METH_NOARGS,
1761
     "drop_nans() -> DataFrame dropping rows with a NaN in any float column."},
1762
    {"fill_nan", DFTRACER_UTILS_PYCFUNCTION(DataFrame_fill_nan),
1763
     METH_VARARGS | METH_KEYWORDS,
1764
     "fill_nan(value) -> DataFrame with the NaN of every float column "
1765
     "replaced (null for None)."},
1766
    {"unique", DFTRACER_UTILS_PYCFUNCTION(DataFrame_unique),
1767
     METH_VARARGS | METH_KEYWORDS,
1768
     "unique(subset=None) -> DataFrame with duplicate rows removed (keep "
1769
     "first), keyed on every column or on the subset names."},
1770
    {"drop_duplicates", DFTRACER_UTILS_PYCFUNCTION(DataFrame_unique),
1771
     METH_VARARGS | METH_KEYWORDS,
1772
     "drop_duplicates(subset=None) -> DataFrame with duplicate rows removed "
1773
     "(alias of unique)."},
1774
    {"sort_by_multi", DFTRACER_UTILS_PYCFUNCTION(DataFrame_sort_by_multi),
1775
     METH_VARARGS | METH_KEYWORDS,
1776
     "sort_by_multi(names, descending=False, nulls_last=True) -> DataFrame "
1777
     "stably sorted "
1778
     "lexicographically by several key columns."},
1779
    {"sample", DFTRACER_UTILS_PYCFUNCTION(DataFrame_sample),
1780
     METH_VARARGS | METH_KEYWORDS,
1781
     "sample(n, seed=0) -> DataFrame deterministic n-row sample."},
1782
    {"with_row_index", DataFrame_with_row_index, METH_O,
1783
     "with_row_index(name) -> DataFrame with a prepended Int64 index column."},
1784
    {"describe", batch_noarg<dataframe::describe>, METH_NOARGS,
1785
     "describe() -> DataFrame of per-column summary statistics."},
1786
    {"null_count", batch_noarg<dataframe::null_count>, METH_NOARGS,
1787
     "null_count() -> 1-row DataFrame of each column's null count."},
1788
    {"reduce", DataFrame_reduce, METH_O,
1789
     "reduce(agg) -> one-row DataFrame: the aggregate named `agg` over every "
1790
     "eligible column."},
1791
    {"_group_transform", DFTRACER_UTILS_PYCFUNCTION(DataFrame_group_transform),
1792
     METH_VARARGS | METH_KEYWORDS,
1793
     "_group_transform(keys, kind, n=0, method='average', ascending=True) -> "
1794
     "DataFrame: the group-wise transform `kind` (cumsum, cummax, cummin, "
1795
     "cumcount, shift, diff, pct_change, rank, ngroup, head, tail, nth) over "
1796
     "the groups of `keys`, one value per input row in input order."},
1797
    {"_reduce_specs", DataFrame_reduce_specs, METH_VARARGS,
1798
     "_reduce_specs(agg, keys=None) -> list[str]: the 'op:column:out' specs "
1799
     "that broadcast `agg` over every eligible non-key column, for group_by."},
1800
    {"is_duplicated", DataFrame_is_duplicated, METH_NOARGS,
1801
     "is_duplicated() -> Bool Series, true where the whole row is duplicated."},
1802
    {"is_unique", DataFrame_is_unique, METH_NOARGS,
1803
     "is_unique() -> Bool Series, true where the whole row is unique."},
1804
    {"slice", DataFrame_slice, METH_VARARGS,
1805
     "slice(offset, length) -> DataFrame of a row range."},
1806
    {"sort_by", DFTRACER_UTILS_PYCFUNCTION(DataFrame_sort_by),
1807
     METH_VARARGS | METH_KEYWORDS,
1808
     "sort_by(name, descending=False, nulls_last=True) -> DataFrame ordered "
1809
     "by a column."},
1810
    {"topk", DFTRACER_UTILS_PYCFUNCTION(DataFrame_topk),
1811
     METH_VARARGS | METH_KEYWORDS,
1812
     "topk(name, k, largest=True) -> DataFrame of the k best rows by a "
1813
     "column."},
1814
    {"concat", DFTRACER_UTILS_PYCFUNCTION(DataFrame_concat),
1815
     METH_VARARGS | METH_KEYWORDS,
1816
     "concat(*others, how='vertical') -> DataFrame concatenating batches. "
1817
     "how='diagonal' unions columns (null-fill absent, promote numeric)."},
1818
    {"unpivot", DFTRACER_UTILS_PYCFUNCTION(DataFrame_unpivot),
1819
     METH_VARARGS | METH_KEYWORDS,
1820
     "unpivot(id_vars, value_vars) -> DataFrame reshaped wide->long, stacking "
1821
     "value_vars into 'variable'/'value' columns."},
1822
    {"melt", DFTRACER_UTILS_PYCFUNCTION(DataFrame_unpivot),
1823
     METH_VARARGS | METH_KEYWORDS,
1824
     "melt(id_vars, value_vars) -> DataFrame (alias of unpivot)."},
1825
    {"explode", DataFrame_explode, METH_O,
1826
     "explode(column) -> DataFrame expanding a List column, one row per "
1827
     "element (empty/null list -> one null row)."},
1828
    {"window", DFTRACER_UTILS_PYCFUNCTION(DataFrame_window),
1829
     METH_VARARGS | METH_KEYWORDS,
1830
     "window(partition_by, order_by, specs) -> DataFrame: SQL window "
1831
     "functions; specs are normalized 12-tuples."},
1832
    {"gap_fill", DFTRACER_UTILS_PYCFUNCTION(DataFrame_gap_fill),
1833
     METH_VARARGS | METH_KEYWORDS,
1834
     "gap_fill(partition_by, time, bucket, values, mode, start=None, "
1835
     "end=None) -> DataFrame: a regular time grid with none/locf/linear "
1836
     "fills."},
1837
    {"asof", DFTRACER_UTILS_PYCFUNCTION(DataFrame_asof),
1838
     METH_VARARGS | METH_KEYWORDS,
1839
     "asof(other, on, by, direction, tolerance) -> DataFrame: temporal "
1840
     "nearest-match join."},
1841
    {"interval", DFTRACER_UTILS_PYCFUNCTION(DataFrame_interval),
1842
     METH_VARARGS | METH_KEYWORDS,
1843
     "interval(other, point, lo, hi, by, outer) -> DataFrame: point-in-range "
1844
     "join."},
1845
    {"unnest", DFTRACER_UTILS_PYCFUNCTION(DataFrame_unnest),
1846
     METH_VARARGS | METH_KEYWORDS,
1847
     "unnest(column, keep_empty=False) -> DataFrame expanding a List column "
1848
     "one row per element; an empty/null list drops the row unless "
1849
     "keep_empty, and a List<Struct> flattens into one column per field."},
1850
    {"to_dummies", DataFrame_to_dummies, METH_O,
1851
     "to_dummies(column) -> DataFrame one-hot encoding a column into one Int8 "
1852
     "column per distinct value, named <column>_<value>."},
1853
    {"pivot", DFTRACER_UTILS_PYCFUNCTION(DataFrame_pivot),
1854
     METH_VARARGS | METH_KEYWORDS,
1855
     "pivot(index, columns, values, agg='first') -> DataFrame reshaping "
1856
     "long->wide; agg is first|last|sum|min|max|mean."},
1857
    {"group_by_dynamic", DFTRACER_UTILS_PYCFUNCTION(DataFrame_group_by_dynamic),
1858
     METH_VARARGS | METH_KEYWORDS,
1859
     "group_by_dynamic(time_col, every, period=None, aggs=[...]) -> DataFrame "
1860
     "tumbling/sliding time-window aggregation; aggs are 'count' / "
1861
     "'<op>:<column>'."},
1862
    {"query", DFTRACER_UTILS_PYCFUNCTION(DataFrame_query),
1863
     METH_VARARGS | METH_KEYWORDS,
1864
     "query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None, "
1865
     "descending=False, limit=None) -> DataFrame; a query plan "
1866
     "(filter/group-by/select/sort/limit) over the batch. The DSL predicate is "
1867
     "evaluated as a SIMD mask (pandas.query-style); aggs are 'count' or "
1868
     "'<op>:<column>'."},
1869
    {"group_by", DataFrame_group_by, METH_VARARGS,
1870
     "group_by(key, *aggs) -> DataFrame or GroupBy; aggs are 'count', "
1871
     "'<op>:<column>' (sum|min|max|mean|var|std|skew|kurt), or aggregate "
1872
     "expressions (F.x.sum(), ...); no aggs returns a GroupBy for .agg(...)."},
1873
    {"_group_agg_expr", DataFrame_group_agg_expr, METH_VARARGS,
1874
     "_group_agg_expr(key, specs) -> DataFrame; specs is a list of "
1875
     "(op_int, value_ast|None, out_name[, param[, by_ast[, udaf[, interp[, "
1876
     "form]]]]]). "
1877
     "Internal: the "
1878
     "GroupBy expression path (CSE across value expressions + pruner)."},
1879
    {"join", DFTRACER_UTILS_PYCFUNCTION(DataFrame_join),
1880
     METH_VARARGS | METH_KEYWORDS,
1881
     "join(other, on=None, how='inner', left_on=None, right_on=None, "
1882
     "suffix='_right') -> DataFrame hash-joined on the key columns; "
1883
     "how=inner|left|right|outer|full|semi|anti|cross."},
1884
    {"compare_agg", DataFrame_compare_agg, METH_VARARGS,
1885
     "compare_agg(variant, n_key) -> DataFrame: FULL-join two aggregation "
1886
     "results on the first n_key group-key columns and append delta_/pct_ per "
1887
     "numeric metric (the CompareView result)."},
1888
    {"partition_id",
1889
     DFTRACER_UTILS_PYCFUNCTION(
1890
         (dftracer::utils::python::core::kw_pair<
1891
             "partition_id", DataFrame_partition_id, "keys", "n_parts">)),
1892
     METH_VARARGS | METH_KEYWORDS,
1893
     "partition_id(keys, n_parts) -> Int32 Series: the part in [0, n_parts) "
1894
     "each row lands in under a stable hash of the key columns."},
1895
    {"hash_partition", DataFrame_hash_partition, METH_VARARGS,
1896
     "hash_partition(keys, n_parts) -> list[DataFrame] partitioned by a stable "
1897
     "hash of the key columns (the distributed shuffle primitive)."},
1898
    {"__arrow_c_array__", DataFrame_arrow_c_array, METH_VARARGS,
1899
     "Arrow PyCapsule export of the struct: (schema_capsule, array_capsule)."},
1900
    {"__arrow_c_stream__", DFTRACER_UTILS_PYCFUNCTION(DataFrame_arrow_c_stream),
1901
     METH_VARARGS | METH_KEYWORDS,
1902
     "Arrow PyCapsule stream export (one struct batch); pa.table(batch) uses "
1903
     "this to import every column zero-copy."},
1904
    {"to_ipc", DataFrame_to_ipc, METH_NOARGS,
1905
     "to_ipc() -> bytes: the frame as an Arrow IPC stream (schema + one record "
1906
     "batch + EOS); no pyarrow needed to produce .arrow bytes."},
1907
    {"to_bytes", DataFrame_to_bytes, METH_NOARGS,
1908
     "to_bytes() -> bytes: the frame in the native frame format."},
1909
    {nullptr, nullptr, 0, nullptr}};
1910

1911
PyGetSetDef DataFrame_getset[] = {
1912
    {"num_rows", DataFrame_get_num_rows, nullptr, "Row count.", nullptr},
1913
    {"num_columns", DataFrame_get_num_columns, nullptr, "Series count.",
1914
     nullptr},
1915
    {"column_names", DataFrame_get_column_names, nullptr, "Series names.",
1916
     nullptr},
1917
    {nullptr, nullptr, nullptr, nullptr, nullptr}};
1918

1919
PyMappingMethods DataFrame_as_mapping = {};
1920
PySequenceMethods DataFrame_as_sequence = {};
1921

1922
// Whether field `i` of `obj`'s schema carries the `arrow.json` extension in
1923
// its metadata. A pyarrow without the registered extension type (before 18)
1924
// keeps the name only there, and an Array's own export has no field metadata.
1925
bool field_is_json(PyObject* obj, Py_ssize_t i) {
×
1926
    PyObject* schema = PyObject_GetAttrString(obj, "schema");
×
1927
    if (!schema) {
×
1928
        PyErr_Clear();
×
1929
        return false;
×
1930
    }
1931
    PyObject* field = PyObject_CallMethod(schema, "field", "n", i);
×
1932
    Py_DECREF(schema);
×
1933
    if (!field) {
×
1934
        PyErr_Clear();
×
1935
        return false;
×
1936
    }
1937
    PyObject* md = PyObject_GetAttrString(field, "metadata");
×
1938
    Py_DECREF(field);
×
1939
    if (!md) {
×
1940
        PyErr_Clear();
×
1941
        return false;
×
1942
    }
1943
    bool json = false;
×
1944
    if (PyDict_Check(md)) {
×
1945
        // pyarrow keys the metadata dict by bytes.
1946
        PyObject* key = PyBytes_FromString("ARROW:extension:name");
×
1947
        PyObject* name = key ? PyDict_GetItem(md, key) : nullptr;
×
1948
        json = name && PyBytes_Check(name) &&
×
1949
               std::strcmp(PyBytes_AsString(name), "arrow.json") == 0;
×
1950
        Py_XDECREF(key);
×
1951
    }
1952
    Py_DECREF(md);
×
1953
    return json;
1954
}
1955

1956
// A provider of __arrow_c_stream__ (a pyarrow Table or RecordBatchReader, a
1957
// polars frame): one chunk per batch, nothing joined or copied.
1958
PyObject* frame_from_arrow_stream(PyObject* obj) {
1,238 ✔
1959
    auto moved = dftracer::utils::python::core::take_arrow_stream(obj);
1,238 ✔
1960
    if (!moved) return nullptr;
1,238 ✔
1961
    auto imported =
1,238 !
1962
        dftracer::utils::arrow::dataframe_from_arrow_stream(moved.get());
1,238 !
1963
    if (!imported) {
1,238 ✔
1964
        dftracer::utils::python::core::set_py_error(imported.error());
2 !
1965
        return nullptr;
1 ✔
1966
    }
1967
    return make_dataframe(std::move(*imported));
1,236 !
1968
}
1,238 ✔
1969

1970
// vec_batch_from_arrow(table) -> DataFrame: import an Arrow table into vec
1971
// with no copy. Used to reconstruct a pickled DataFrame and to lift Arrow into
1972
// the native format.
1973
PyObject* vec_batch_from_arrow(PyObject* /*self*/, PyObject* obj) {
1,238 ✔
1974
    if (PyObject_HasAttrString(obj, "__arrow_c_stream__"))
1,238 !
1975
        return frame_from_arrow_stream(obj);
1,238 ✔
1976
    PyObject* names = PyObject_GetAttrString(obj, "column_names");
×
1977
    if (!names) return nullptr;
×
1978
    Py_ssize_t n = PySequence_Size(names);
×
1979
    if (n < 0) {
×
1980
        Py_DECREF(names);
×
1981
        return nullptr;
×
1982
    }
1983
    DataFrame b;
×
1984
    for (Py_ssize_t i = 0; i < n; ++i) {
×
1985
        PyObject* nm = PySequence_GetItem(names, i);
×
1986
        const char* s = nm ? PyUnicode_AsUTF8(nm) : nullptr;
×
1987
        PyObject* ca = s ? PyObject_CallMethod(obj, "column", "n", i) : nullptr;
×
1988
        Series col = ca ? dftracer::utils::python::frame::column_from_arrow(ca)
×
1989
                        : Series{};
×
1990
        Py_XDECREF(ca);
×
1991
        if (col.valid() && !col.is_json() &&
×
1992
            col.type() == dftracer::utils::dataframe::TypeId::String &&
×
1993
            field_is_json(obj, i))
×
1994
            col = col.as_json();
×
1995
        if (!col.valid()) {
×
1996
            Py_XDECREF(nm);
×
1997
            Py_DECREF(names);
×
1998
            return nullptr;
×
1999
        }
2000
        b.names.emplace_back(s);
×
2001
        b.columns.push_back(std::move(col));
×
2002
        Py_DECREF(nm);
×
2003
    }
×
2004
    Py_DECREF(names);
×
2005
    return make_dataframe(std::move(b));
×
2006
}
619 ✔
2007

2008
// _dataframe_from_columns(names, series) -> DataFrame: a frame of native
2009
// Series, no Arrow involved.
2010
PyObject* dataframe_from_columns(PyObject* /*self*/, PyObject* args) {
55,562 ✔
2011
    PyObject* names_obj = nullptr;
55,562 ✔
2012
    PyObject* series_obj = nullptr;
55,562 ✔
2013
    if (!PyArg_ParseTuple(args, "OO", &names_obj, &series_obj)) return nullptr;
55,562 !
2014
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> names;
55,562 ✔
2015
    if (!parse_string_seq(names_obj, "names must be strings", names))
55,562 !
2016
        return nullptr;
2017
    dftracer::utils::dstd::Vector<Series> cols;
55,562 ✔
2018
    if (!parse_seq<Series>(
55,562 !
2019
            series_obj, "series must be a sequence", cols,
27,781 ✔
2020
            [](PyObject* item, dftracer::utils::dstd::Vector<Series>& o) {
142,484 ✔
2021
                const Series* col =
213,726 ✔
2022
                    dftracer::utils::python::frame::unwrap_vec_column(item);
142,484 ✔
2023
                if (!col) {
142,484 ✔
2024
                    PyErr_SetString(PyExc_TypeError, "expected native Series");
×
2025
                    return false;
×
2026
                }
2027
                o.push_back(col->share());
142,484 !
2028
                return true;
142,484 ✔
2029
            }))
71,242 ✔
2030
        return nullptr;
2031
    if (cols.size() != names.size()) {
55,562 !
2032
        PyErr_SetString(PyExc_ValueError, "names and series differ in length");
×
2033
        return nullptr;
2034
    }
2035
    DataFrame b;
55,562 ✔
2036
    for (std::size_t i = 0; i < cols.size(); ++i) {
198,046 ✔
2037
        b.names.push_back(dstd::SharedString{names[i]});
142,484 !
2038
        b.columns.push_back(std::move(cols[i]));
142,484 ✔
2039
    }
71,242 ✔
2040
    if (!b.columns.empty()) {
55,562 ✔
2041
        const std::int64_t rows = b.columns.front().length();
55,558 ✔
2042
        for (const Series& c : b.columns)
198,042 !
2043
            if (c.length() != rows) {
142,484 !
2044
                PyErr_SetString(PyExc_ValueError, "columns differ in length");
×
2045
                return nullptr;
×
2046
            }
71,242 !
2047
    }
27,779 !
2048
    return make_dataframe(std::move(b));
55,562 !
2049
}
55,562 ✔
2050

2051
}  // namespace
2052

2053
namespace dftracer::utils::python::frame {
2054

2055
TypeBinding dataframe_binding() {
900 ✔
2056
    return {"DataFrame", &DataFrameType, &g_dataframe_type};
900 ✔
2057
}
2058

2059
PyObject* wrap_dataframe(dftracer::utils::dataframe::DataFrame&& batch) {
130,626 ✔
2060
    return make_dataframe(std::move(batch));
130,626 ✔
2061
}
2062

2063
bool unwrap_dataframe(PyObject* obj,
×
2064
                      dftracer::utils::dataframe::DataFrame& out) {
2065
    const DataFrameObject* self =
×
2066
        dftracer::utils::python::core::as_native<DataFrameObject>(obj);
×
2067
    if (!self) return false;
×
2068
    out = to_dataframe(self);
×
2069
    return true;
×
2070
}
2071

2072
int init_dataframe(PyObject* m) {
222 ✔
2073
    DataFrame_as_mapping.mp_subscript = DataFrame_subscript;
222 ✔
2074
    DataFrame_as_sequence.sq_contains = DataFrame_contains;
222 ✔
2075
    DataFrameType = {};
222 ✔
2076
    DataFrameType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
222 ✔
2077
    DataFrameType.tp_name = "dftracer.utils.dftracer_utils_ext.DataFrame";
222 ✔
2078
    DataFrameType.tp_basicsize = sizeof(DataFrameObject);
222 ✔
2079
    DataFrameType.tp_weaklistoffset = WEAKLIST_OFFSET;
222 ✔
2080
    DataFrameType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
222 ✔
2081
    DataFrameType.tp_doc =
222 ✔
2082
        "A native vec batch (named vec columns; Arrow only at the edge).";
2083
    DataFrameType.tp_dealloc = reinterpret_cast<destructor>(DataFrame_dealloc);
222 ✔
2084
    DataFrameType.tp_as_mapping = &DataFrame_as_mapping;
222 ✔
2085
    DataFrameType.tp_as_sequence = &DataFrame_as_sequence;
222 ✔
2086
    DataFrameType.tp_methods = DataFrame_methods;
222 ✔
2087
    DataFrameType.tp_getset = DataFrame_getset;
222 ✔
2088
    DataFrameType.tp_new = nullptr;  // created only by a trace view
222 ✔
2089
    if (register_type(m, &DataFrameType, "DataFrame") < 0) return -1;
222 !
2090

2091
    static PyMethodDef defs[] = {
111 ✔
2092
        {"_dataframe_from_arrow", vec_batch_from_arrow, METH_O,
2093
         "vec_batch_from_arrow(table) -> DataFrame: import a pyarrow Table's "
2094
         "columns into a native vec batch."},
2095
        {"_dataframe_from_columns", dataframe_from_columns, METH_VARARGS,
2096
         "_dataframe_from_columns(names, series) -> DataFrame of native "
2097
         "Series."},
2098
        {"_dataframe_from_bytes", dataframe_from_bytes, METH_O,
2099
         "_dataframe_from_bytes(bytes) -> DataFrame written by "
2100
         "DataFrame.to_bytes."}};
2101
    if (add_functions(m, defs) < 0) return -1;
222 !
2102
    if (register_type(m, &FrameBufferType, "_FrameBuffer") < 0) return -1;
222 !
2103
    static PyMethodDef buffer_defs[] = {
111 ✔
2104
        {"_dataframe_to_buffers", dataframe_to_buffers, METH_O,
2105
         "_dataframe_to_buffers(frame) -> (header, buffers): the frame as a "
2106
         "header and read-only column buffers, with no copy."},
2107
        {"_dataframe_from_buffers", dataframe_from_buffers, METH_VARARGS,
2108
         "_dataframe_from_buffers(header, buffers) -> DataFrame that reads the "
2109
         "buffers in place and keeps them alive."}};
2110
    if (add_functions(m, buffer_defs) < 0) return -1;
222 ✔
2111
    return 0;
111 ✔
2112
}
111 ✔
2113

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