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

llnl-asr / dftracer-utils / 45735107228

26 Nov 2026 01:20AM UTC coverage: 77.696% (+0.4%) from 77.313%
45735107228

push

github

rayandrew
fix: convert natively at the edge and read chunked nested columns safely

to_pandas, from_pandas, table files, loc, reindex, where, unnest and the
dask viewer called pyarrow kernels to convert columns, so they failed
without pyarrow and copied text twice. They now use native codes, masks
and buffers, and pyarrow appears only when a user asks for Arrow.
Readers of list offsets and struct children now go through flat pieces
of a column, so a chunked, selected or dictionary nested column no
longer crashes explode, the CLI printer or child access.

164371 of 253360 branches covered (64.88%)

Branch coverage included in aggregate %.

1455 of 1580 new or added lines in 20 files covered. (92.09%)

795 existing lines in 33 files now uncovered.

190713 of 203655 relevant lines covered (93.65%)

4484549.26 hits per line

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

67.69
/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/method.h>
37
#include <dftracer/utils/python/core/scalar_helpers.h>
38
#include <dftracer/utils/python/core/type_helpers.h>
39
#include <dftracer/utils/python/frame/agg_helpers.h>
40
#include <dftracer/utils/python/frame/columnar_eval.h>
41
#include <dftracer/utils/python/frame/dataframe.h>
42
#include <dftracer/utils/python/frame/frame_op_helpers.h>
43
#include <dftracer/utils/python/frame/join_helpers.h>
44
#include <dftracer/utils/python/frame/lazyframe.h>
45
#include <dftracer/utils/python/frame/series.h>
46
#include <dftracer/utils/python/runtime/task_handle.h>
47

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

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

62
using namespace dftracer::utils;
63

64
namespace {
65

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

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

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

91
    void reset() noexcept {
6,030,986 ✔
92
        dftracer::utils::dstd::UniquePtr<Table> old(
9,799,575 ✔
93
            table_.exchange(nullptr, std::memory_order_acq_rel));
6,030,986 ✔
94
    }
6,030,986 ✔
95

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

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

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

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

163
    mutable std::atomic<Table*> table_{nullptr};
197,459 ✔
164
};
165

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

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

186
}  // namespace
187

188
template <>
189
struct dftracer::utils::python::core::NativeTraits<DataFrameObject> {
190
    static PyTypeObject* type() { return &DataFrameType; }
14,760,573 ✔
191
    static constexpr const char* EXPECTED = "expected a DataFrame";
192
    static DataFrameObject* get(PyObject* o) {
9,299,322 ✔
193
        return reinterpret_cast<DataFrameObject*>(o);
9,299,322 ✔
194
    }
195
};
196

197
namespace {
198

199
PyObject* make_dataframe(DataFrame&& b) {
442,806 ✔
200
    // A column of a frame is labelled by the frame's row index alone.
201
    for (Series& column : b.columns)
1,914,392 ✔
202
        if (column.has_index()) column = column.without_index();
1,471,586 !
203
    Series st = Series::structs(b.names, std::move(b.columns));
442,806 !
204
    auto* self = reinterpret_cast<DataFrameObject*>(
442,806 ✔
205
        g_dataframe_type->tp_alloc(g_dataframe_type, 0));
442,806 !
206
    if (!self) return nullptr;
442,806 !
207
    new (&self->st) Series(std::move(st));
442,806 ✔
208
    new (&self->names)
442,806 ✔
209
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString>(
197,459 ✔
210
            std::move(b.names));
442,806 ✔
211
    new (&self->index_names)
442,806 ✔
212
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::SharedString>();
197,459 ✔
213
    new (&self->label_cache) dftracer::utils::dstd::SharedPtr<
442,806 ✔
214
        dftracer::utils::dataframe::LabelCache>();
215
    new (&self->name_lookup) NameLookup();
442,806 ✔
216
    if (b.row_index) {
442,806 ✔
217
        self->index_names = std::move(b.row_index->names);
28,256 ✔
218
        self->label_cache = std::move(b.row_index->cache);
273,603 !
219
    }
14,122 ✔
220
    return reinterpret_cast<PyObject*>(self);
197,459 ✔
221
}
442,806 ✔
222

223
void DataFrame_dealloc(DataFrameObject* self) {
442,796 ✔
224
    if (self->weaklist)
442,796 ✔
225
        PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
4 ✔
226
    self->name_lookup.~NameLookup();
442,796 ✔
227
    self->label_cache.~SharedPtr();
442,796 ✔
228
    self->index_names.~vector();
442,796 ✔
229
    self->names.~vector();
442,796 ✔
230
    self->st.~Series();
442,796 !
231
    Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
442,796 ✔
232
}
442,796 ✔
233

234
std::int64_t index_of(const DataFrameObject* self,
321,668 ✔
235
                      dftracer::utils::dstd::StringView name) {
236
    return self->name_lookup.find(self->names, name);
321,668 ✔
237
}
238

239
// A dataframe::DataFrame view over the struct's children (shared buffers,
240
// zero-copy), for forwarding to the batch_ops frame kernels.
241
DataFrame to_dataframe(const DataFrameObject* self) {
8,663,885 ✔
242
    DataFrame b;
8,663,885 ✔
243
    b.names = self->names;
8,663,885 !
244
    b.columns.reserve(self->names.size());
8,663,885 !
245
    for (std::size_t i = 0; i < self->names.size(); ++i)
28,965,116 ✔
246
        b.columns.push_back(self->st.child(static_cast<std::int64_t>(i)));
20,301,231 !
247
    if (!self->index_names.empty()) {
8,663,885 ✔
248
        b.row_index = dftracer::utils::dstd::make_unique<dataframe::RowIndex>();
13,136 !
249
        b.row_index->names = self->index_names;
13,136 !
250
        b.row_index->cache = self->label_cache;
13,136 ✔
251
    }
6,562 ✔
252
    return b;
8,663,885 ✔
253
}
5,473,939 !
254

255
// Wrap a batch_ops call over the frame `b` that returns a frame or a frame
256
// result, turning its error and any C++ exception into a typed Python error.
257
// `fn` runs with the GIL released for a large frame, so it touches no Python
258
// object. It reads a view of the frame taken under the GIL, as `_replace`
259
// rebinds a DataFrame object's columns in place, and a Series argument is
260
// shared under the GIL first, as `s.name = x` renames a Series object in place.
261
template <class Fn>
262
PyObject* run_batch_op(const DataFrameObject* b, Fn&& fn) {
164,607 ✔
263
    return guard([&]() -> PyObject* {
435,045 ✔
264
        const DataFrame frame = to_dataframe(b);
164,607 ✔
265
        auto out = without_gil(frame.num_rows(), [&] {
284,166 !
266
            if constexpr (std::is_invocable_v<Fn&, const DataFrame&>)
267
                return fn(frame);
98,861 !
268
            else
269
                return fn();
810 !
270
        });
58,774 ✔
271
        if constexpr (std::is_same_v<decltype(out), DataFrame>) {
272
            return make_dataframe(std::move(out));
159,822 !
273
        } else {
274
            if (!out) {
73,742 !
275
                dftracer::utils::python::core::set_py_error(out.error());
132 !
276
                return nullptr;
66 ✔
277
            }
278
            return make_dataframe(std::move(*out));
73,610 !
279
        }
280
    });
270,438 ✔
281
}
282

283
PyObject* DataFrame_filter(PyObject* self, PyObject* mask);
284
PyObject* DataFrame_select(PyObject* self, PyObject* args);
285

286
// df["a"] is a column; df[["a", "b"]] a projection and df[mask] the rows where
287
// a Bool Series holds (the pandas spellings), both under the frame op index
288
// rules.
289
PyObject* DataFrame_subscript(PyObject* self, PyObject* key) {
197,366 ✔
290
    DataFrameObject* b = as_native<DataFrameObject>(self);
197,366 ✔
291
    if (!b) return nullptr;
197,366 !
292
    if (!PyUnicode_Check(key)) {
197,366 ✔
293
        if (dftracer::utils::python::frame::unwrap_vec_column(key))
158 ✔
294
            return DataFrame_filter(self, key);
80 ✔
295
        PyObject* names = PySequence_Tuple(key);
78 ✔
296
        if (!names) {
78 ✔
UNCOV
297
            PyErr_SetString(PyExc_TypeError,
×
298
                            "DataFrame key must be a column name, a list of "
299
                            "names or a Bool Series");
UNCOV
300
            return nullptr;
×
301
        }
302
        for (Py_ssize_t k = 0; k < PyTuple_GET_SIZE(names); ++k) {
258 !
303
            PyObject* text = PyObject_Str(PyTuple_GET_ITEM(names, k));
180 ✔
304
            if (!text) {
180 ✔
UNCOV
305
                Py_DECREF(names);
×
UNCOV
306
                return nullptr;
×
307
            }
308
            PyTuple_SET_ITEM(names, k, text);
180 ✔
309
        }
90 !
310
        PyObject* out = DataFrame_select(self, names);
78 ✔
311
        Py_DECREF(names);
78 !
312
        return out;
78 ✔
313
    }
39 ✔
314
    const char* name = PyUnicode_AsUTF8(key);
197,208 ✔
315
    if (!name) return nullptr;
197,208 !
316
    std::int64_t i = index_of(b, name);
197,208 ✔
317
    if (i < 0) {
197,208 ✔
UNCOV
318
        PyErr_Format(PyExc_KeyError, "no column named '%s'", name);
×
UNCOV
319
        return nullptr;
×
320
    }
321
    // The labels a column was built with are not the frame's: only its own
322
    // row index labels it.
323
    Series column = b->st.child(i).rename(name);
197,208 !
324
    if (column.has_index()) column = column.without_index();
197,208 !
325
    if (b->index_names.empty())
197,208 ✔
326
        return dftracer::utils::python::frame::wrap_vec_column(
105,928 !
327
            std::move(column));
328
    // The frame's row index travels with the column as its labels.
329
    dstd::Vector<dstd::StringView> level_names;
91,280 ✔
330
    dstd::Vector<Series> levels;
91,280 ✔
331
    for (const dstd::SharedString& index_name : b->index_names) {
194,132 ✔
332
        const std::int64_t at = index_of(b, index_name.c_str());
154,278 !
333
        if (at < 0) continue;
102,852 ✔
334
        level_names.emplace_back(index_name);
102,852 !
335
        levels.push_back(b->st.child(at));
102,852 !
336
    }
51,426 !
337
    Series labelled = column.with_index(level_names, levels);
91,280 !
338
    return dftracer::utils::python::frame::wrap_vec_column(
91,280 !
339
        labelled.valid() ? std::move(labelled) : std::move(column));
91,280 ✔
340
}
243,006 ✔
341

342
int DataFrame_contains(PyObject* self, PyObject* key) {
21,610 ✔
343
    DataFrameObject* b = as_native<DataFrameObject>(self);
21,610 ✔
344
    if (!b) return -1;
21,610 !
345
    // Only a name can be a column; anything else is simply not in the
346
    // frame, with no error left behind.
347
    if (!PyUnicode_Check(key)) return 0;
21,610 ✔
348
    const char* name = PyUnicode_AsUTF8(key);
21,608 ✔
349
    if (!name) return -1;
21,608 !
350
    return index_of(b, name) >= 0 ? 1 : 0;
24,280 ✔
351
}
10,805 ✔
352

353
// _replace(other): this frame takes the columns and the index names of
354
// `other`, in place. Kernels read a
355
// view taken under the GIL, so one running on another thread keeps the old
356
// columns.
357
PyObject* DataFrame_replace(PyObject* self, PyObject* other) {
5,588,194 ✔
358
    DataFrameObject* b = as_native<DataFrameObject>(self);
5,588,194 ✔
359
    DataFrameObject* o = as_native<DataFrameObject>(other);
5,588,194 ✔
360
    if (!b || !o) return nullptr;
5,588,194 !
361
    if (b == o) Py_RETURN_NONE;
5,588,192 ✔
362
    return guard([&]() -> PyObject* {
9,159,325 ✔
363
        DataFrame f = to_dataframe(o);
5,588,190 ✔
364
        Series st = Series::structs(f.names, std::move(f.columns));
5,588,190 !
365
        b->names = o->names;
5,588,190 !
366
        b->name_lookup.reset();
5,588,190 ✔
367
        b->index_names = o->index_names;
5,588,190 !
368
        b->label_cache = o->label_cache;
5,588,190 ✔
369
        b->st = std::move(st);
5,588,190 ✔
370
        Py_RETURN_NONE;
4,034,110 !
371
    });
5,588,190 ✔
372
}
3,571,137 ✔
373

374
// share() -> DataFrame: a new object over the same columns and index names.
375
PyObject* DataFrame_share(PyObject* self, PyObject*) {
98 ✔
376
    DataFrameObject* b = as_native<DataFrameObject>(self);
98 ✔
377
    if (!b) return nullptr;
98 !
378
    return guard(
98 ✔
379
        [&]() -> PyObject* { return make_dataframe(to_dataframe(b)); });
196 !
380
}
49 ✔
381

382
// index_names() -> list[str]: the row index columns, in order; [] for none.
383
PyObject* DataFrame_index_names(PyObject* self, PyObject*) {
145,286 ✔
384
    DataFrameObject* b = as_native<DataFrameObject>(self);
145,286 ✔
385
    if (!b) return nullptr;
145,286 !
386
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(b->index_names.size()));
145,286 ✔
387
    if (!list) return nullptr;
145,286 !
388
    for (std::size_t i = 0; i < b->index_names.size(); ++i) {
210,954 !
389
        PyObject* s = PyUnicode_FromString(b->index_names[i].c_str());
98,502 !
390
        if (!s) {
65,668 ✔
UNCOV
391
            Py_DECREF(list);
×
UNCOV
392
            return nullptr;
×
393
        }
394
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
65,668 ✔
395
    }
32,834 !
396
    return list;
72,643 ✔
397
}
72,643 ✔
398

399
// with_index(names) -> DataFrame: this frame's columns under the row index
400
// `names` (a list of str; [] drops it). KeyError for a name that is no column,
401
// ValueError for a repeated name or a column of a nested type.
402
PyObject* DataFrame_with_index(PyObject* self, PyObject* names) {
21,838 ✔
403
    DataFrameObject* b = as_native<DataFrameObject>(self);
21,838 ✔
404
    if (!b) return nullptr;
21,838 !
405
    PyObject* seq =
32,757 ✔
406
        PySequence_Fast(names, "with_index() expects a list of names");
21,838 ✔
407
    if (!seq) return nullptr;
21,838 ✔
408
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
21,838 ✔
409
    const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
21,838 !
410
    for (Py_ssize_t k = 0; k < n; ++k) {
46,344 !
411
        PyObject* item = PySequence_Fast_GET_ITEM(seq, k);
24,506 !
412
        const char* text =
36,759 !
413
            PyUnicode_Check(item) ? PyUnicode_AsUTF8(item) : nullptr;
24,506 !
414
        if (!text) {
24,506 !
UNCOV
415
            if (!PyErr_Occurred())
×
416
                PyErr_SetString(PyExc_TypeError,
×
417
                                "with_index() names must be str");
UNCOV
418
            Py_DECREF(seq);
×
UNCOV
419
            return nullptr;
×
420
        }
421
        keys.emplace_back(text);
24,506 !
422
    }
12,253 !
423
    Py_DECREF(seq);
21,838 !
424
    return guard([&]() -> PyObject* {
32,757 !
425
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::StringView> views;
21,838 ✔
426
        views.reserve(keys.size());
21,838 !
427
        for (const auto& key : keys) views.emplace_back(key);
46,344 ✔
428
        auto out = to_dataframe(b).with_index(views);
21,838 !
429
        if (!out) {
21,838 ✔
430
            dftracer::utils::python::core::set_py_error(out.error());
4 !
431
            return nullptr;
2 ✔
432
        }
433
        return make_dataframe(std::move(*out));
21,834 !
434
    });
21,838 ✔
435
}
21,838 ✔
436

437
PyObject* column_name_list(PyObject* self, bool hide_index) {
53,544 ✔
438
    DataFrameObject* b = as_native<DataFrameObject>(self);
53,544 ✔
439
    if (!b) return nullptr;
53,544 !
440
    PyObject* list = PyList_New(0);
53,544 ✔
441
    if (!list) return nullptr;
53,544 !
442
    for (std::size_t i = 0; i < b->names.size(); ++i) {
235,416 !
443
        bool is_index = false;
181,872 ✔
444
        if (hide_index)
181,872 ✔
445
            for (const auto& index_name : b->index_names)
96 ✔
446
                if (dftracer::utils::dstd::StringView(index_name) ==
27 ✔
447
                    dftracer::utils::dstd::StringView(b->names[i]))
18 ✔
448
                    is_index = true;
51 ✔
449
        if (is_index) continue;
90,975 ✔
450
        PyObject* s = PyUnicode_FromString(b->names[i].c_str());
272,796 ✔
451
        if (!s || PyList_Append(list, s) < 0) {
181,866 !
452
            Py_XDECREF(s);
×
UNCOV
453
            Py_DECREF(list);
×
UNCOV
454
            return nullptr;
×
455
        }
456
        Py_DECREF(s);
201,389 ✔
457
    }
90,936 !
458
    return list;
26,772 ✔
459
}
26,772 ✔
460

461
PyObject* DataFrame_keys(PyObject* self, PyObject*) {
26 ✔
462
    return column_name_list(self, true);
26 ✔
463
}
464

465
PyObject* DataFrame_filter(PyObject* self, PyObject* mask) {
4,148 ✔
466
    DataFrameObject* b = as_native<DataFrameObject>(self);
4,148 ✔
467
    if (!b) return nullptr;
4,148 !
468
    const Series* m = dftracer::utils::python::frame::unwrap_vec_column(mask);
4,148 ✔
469
    if (!m) {
4,148 ✔
470
        PyErr_SetString(PyExc_TypeError,
×
471
                        "filter() expects a Series boolean mask");
UNCOV
472
        return nullptr;
×
473
    }
474
    const Series mask_copy = m->share();
4,148 ✔
475
    return run_batch_op(b, [&](const DataFrame& frame) {
6,222 !
476
        return dataframe::filter(frame, mask_copy);
4,148 !
477
    });
2,074 ✔
478
}
4,148 ✔
479

480
// query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None,
481
// descending=False, limit=None) -> DataFrame: a query plan over this batch -
482
// filter by the DSL predicate (a SIMD mask, pandas.query-style), group_by/aggs,
483
// project `select`, sort by `order_by`, cap at `limit`. Raises
484
// DFTUtilsDuqlError on a parse error or a predicate with no columnar lowering
485
// (regex/like/ordered-string/absent field).
486
PyObject* DataFrame_query(PyObject* self, PyObject* args, PyObject* kwds) {
34 ✔
487
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
488
    if (!b) return nullptr;
34 !
489
    const char* dsl = nullptr;
34 ✔
490
    const char* group_by = nullptr;
34 ✔
491
    PyObject* aggs_obj = nullptr;
34 ✔
492
    PyObject* select_obj = nullptr;
34 ✔
493
    const char* order_by = nullptr;
34 ✔
494
    int descending = 0;
34 ✔
495
    PyObject* limit_obj = nullptr;
34 ✔
496
    if (!parse_kw<"|zzOOzpO">(args, kwds,
51 !
497
                              {"dsl", "group_by", "aggs", "select", "order_by",
17 ✔
498
                               "descending", "limit"},
499
                              &dsl, &group_by, &aggs_obj, &select_obj,
500
                              &order_by, &descending, &limit_obj))
501
        return nullptr;
502

503
    return guard([&]() -> PyObject* {
51 ✔
504
        DataFrame bat = to_dataframe(b);
34 ✔
505
        dataframe::QueryPlan plan;
34 ✔
506
        dftracer::utils::dstd::Optional<duql::Query>
34 ✔
507
            q;  // keep root() alive across execute
34 ✔
508
        if (dsl && *dsl) {
34 ✔
509
            auto parsed = duql::Query::from_string(dsl);
29 !
510
            if (!parsed)
28 ✔
511
                throw dftracer::utils::python::core::PyErrorException(
2 !
512
                    dftracer::utils::dstd::Error{duql::DuqlErrc::Parse,
3 !
513
                                                 parsed.error().format()});
4 !
514
            q.emplace(std::move(*parsed));
26 !
515
            plan.where = &duql::detail::QueryAccess::root(*q);
26 !
516
        }
28 ✔
517
        if (group_by && *group_by) plan.group_by = group_by;
32 !
518
        if (aggs_obj && aggs_obj != Py_None) {
32 ✔
519
            if (!parse_seq<dataframe::GroupAgg>(
2 !
520
                    aggs_obj, "aggs must be a sequence of strings", plan.aggs,
1 ✔
521
                    [](PyObject* item,
4 ✔
522
                       dftracer::utils::dstd::Vector<dataframe::GroupAgg>& o) {
523
                        const char* s = PyUnicode_AsUTF8(item);
4 ✔
524
                        if (!s) return false;
4 !
525
                        return guard([&] {
6 ✔
526
                            o.push_back(group_agg_from_spec(s));
6 !
527
                            return true;
4 ✔
528
                        });
529
                    }))
2 ✔
530
                return nullptr;
531
        }
1 ✔
532
        if (select_obj && select_obj != Py_None) {
32 ✔
533
            if (!parse_string_seq(select_obj,
12 !
534
                                  "select must be a sequence of column names",
535
                                  plan.select))
4 ✔
536
                return nullptr;
537
        }
4 ✔
538
        if (order_by && *order_by) plan.order_by = order_by;
32 !
539
        plan.descending = descending != 0;
32 ✔
540
        if (limit_obj && limit_obj != Py_None) {
32 ✔
541
            plan.limit = PyLong_AsLongLong(limit_obj);
6 !
542
            if (plan.limit == -1 && PyErr_Occurred()) return nullptr;
6 !
543
        }
3 ✔
544
        auto out = dataframe::execute(plan, bat);
32 !
545
        if (!out) {
32 ✔
546
            dftracer::utils::python::core::set_py_error(out.error());
2 !
547
            return nullptr;
1 ✔
548
        }
549
        return make_dataframe(std::move(*out));
30 !
550
    });
49 ✔
551
}
17 ✔
552

553
PyObject* DataFrame_select(PyObject* self, PyObject* args) {
18,626 ✔
554
    DataFrameObject* b = as_native<DataFrameObject>(self);
18,626 ✔
555
    if (!b) return nullptr;
18,626 !
556
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> names;
18,626 ✔
557
    Py_ssize_t n = PyTuple_GET_SIZE(args);
18,626 !
558
    for (Py_ssize_t i = 0; i < n; ++i) {
66,758 !
559
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
48,132 !
560
        if (!s) {
48,132 !
UNCOV
561
            PyErr_SetString(PyExc_TypeError, "select() names must be strings");
×
UNCOV
562
            return nullptr;
×
563
        }
564
        names.emplace_back(s);
48,132 !
565
    }
24,066 !
566
    return run_batch_op(b, [&](const DataFrame& frame) {
27,939 !
567
        return dataframe::select(frame, names);
18,626 ✔
568
    });
9,313 ✔
569
}
18,626 ✔
570

571
PyObject* DataFrame_rename(PyObject* self, PyObject* mapping) {
2,384 ✔
572
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,384 ✔
573
    if (!b) return nullptr;
2,384 !
574
    if (!PyDict_Check(mapping)) {
2,384 ✔
UNCOV
575
        PyErr_SetString(PyExc_TypeError, "rename() expects a {old: new} dict");
×
UNCOV
576
        return nullptr;
×
577
    }
578
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> new_names;
2,384 ✔
579
    new_names.reserve(b->names.size());
2,384 !
580
    for (const dftracer::utils::dstd::SharedString& name : b->names) {
8,146 !
581
        PyObject* v = PyDict_GetItemString(mapping, name.c_str());
8,643 !
582
        if (v) {
5,762 ✔
583
            const char* s = PyUnicode_AsUTF8(v);
3,174 !
584
            if (!s) {
3,174 !
UNCOV
585
                PyErr_SetString(PyExc_TypeError, "rename() values must be str");
×
UNCOV
586
                return nullptr;
×
587
            }
588
            new_names.emplace_back(s);
3,174 !
589
        } else {
1,587 !
590
            new_names.emplace_back(name.view());
2,588 ✔
591
        }
592
    }
2,881 !
593
    return run_batch_op(b, [&](const DataFrame& frame) {
3,576 !
594
        return dataframe::rename(frame, new_names);
2,384 ✔
595
    });
1,192 ✔
596
}
2,384 ✔
597

598
PyObject* DataFrame_with_column(PyObject* self, PyObject* args) {
24,846 ✔
599
    DataFrameObject* b = as_native<DataFrameObject>(self);
24,846 ✔
600
    if (!b) return nullptr;
24,846 !
601
    const char* name = nullptr;
24,846 ✔
602
    PyObject* col = nullptr;
24,846 ✔
603
    if (!PyArg_ParseTuple(args, "sO", &name, &col)) return nullptr;
24,846 !
604
    const Series* c = dftracer::utils::python::frame::unwrap_vec_column(col);
24,846 ✔
605
    if (!c) {
24,846 ✔
606
        PyErr_SetString(PyExc_TypeError,
×
607
                        "with_column() expects (name, Series)");
UNCOV
608
        return nullptr;
×
609
    }
610
    const Series col_copy = c->share();
24,846 ✔
611
    return run_batch_op(b, [&](const DataFrame& frame) {
37,269 !
612
        return dataframe::with_column(frame, name, col_copy);
24,846 ✔
613
    });
12,423 ✔
614
}
24,846 ✔
615

616
PyObject* DataFrame_take(PyObject* self, PyObject* seq) {
3,212 ✔
617
    DataFrameObject* b = as_native<DataFrameObject>(self);
3,212 ✔
618
    if (!b) return nullptr;
3,212 !
619
    Series holder;
3,212 ✔
620
    dstd::Vector<std::int64_t> parsed;
3,212 ✔
621
    dstd::Span<const std::int64_t> idx;
3,212 ✔
622
    if (!dftracer::utils::python::frame::row_indices_from_py(
3,212 !
623
            seq, "take() expects a sequence of ints", holder, parsed, idx))
1,606 ✔
624
        return nullptr;
625
    // A take past the end would read outside the columns.
626
    const std::int64_t rows = to_dataframe(b).num_rows();
3,212 !
627
    for (const std::int64_t i : idx) {
17,455 ✔
628
        if (i >= rows) {
14,244 ✔
629
            PyErr_SetString(PyExc_IndexError,
2 ✔
630
                            "take: an index is at or past the frame's length");
631
            return nullptr;
2 ✔
632
        }
633
    }
7,122 ✔
634
    return run_batch_op(
3,210 !
635
        b, [&](const DataFrame& frame) { return frame.take(idx); });
6,420 !
636
}
4,818 ✔
637

638
// _locate(keys) -> (positions, missing): the rows whose index labels equal the
639
// key columns, one per level (see DataFrame::locate).
640
PyObject* DataFrame_locate(PyObject* self, PyObject* keys_obj) {
400 ✔
641
    DataFrameObject* b = as_native<DataFrameObject>(self);
400 ✔
642
    if (!b) return nullptr;
400 !
643
    dstd::Vector<Series> keys;
400 ✔
644
    if (!dftracer::utils::python::frame::series_list_from_py(
400 !
645
            keys_obj, "_locate: keys must be Series", keys))
200 ✔
646
        return nullptr;
647
    return guard([&]() -> PyObject* {
600 !
648
        const DataFrame frame = to_dataframe(b);
400 ✔
649
        return dftracer::utils::python::frame::located_to_py(
400 !
650
            without_gil(frame.num_rows(), [&] { return frame.locate(keys); }));
1,000 !
651
    });
400 ✔
652
}
400 ✔
653

654
// _locate_range(start, stop) -> (offset, length): the rows between two index
655
// label bounds (lists of one-row Series, empty for an open end).
656
PyObject* DataFrame_locate_range(PyObject* self, PyObject* args) {
106 ✔
657
    DataFrameObject* b = as_native<DataFrameObject>(self);
106 ✔
658
    if (!b) return nullptr;
106 !
659
    PyObject* start_obj = nullptr;
106 ✔
660
    PyObject* stop_obj = nullptr;
106 ✔
661
    if (!PyArg_ParseTuple(args, "OO", &start_obj, &stop_obj)) return nullptr;
106 !
662
    dstd::Vector<Series> start;
106 ✔
663
    dstd::Vector<Series> stop;
106 ✔
664
    if (!dftracer::utils::python::frame::series_list_from_py(
106 !
665
            start_obj, "_locate_range: bounds must be Series", start) ||
212 !
666
        !dftracer::utils::python::frame::series_list_from_py(
106 !
667
            stop_obj, "_locate_range: bounds must be Series", stop))
53 ✔
UNCOV
668
        return nullptr;
×
669
    return guard([&]() -> PyObject* {
159 !
670
        const DataFrame frame = to_dataframe(b);
106 ✔
671
        return dftracer::utils::python::frame::label_span_to_py(without_gil(
159 !
672
            frame.num_rows(), [&] { return frame.locate_range(start, stop); }));
265 ✔
673
    });
106 ✔
674
}
106 ✔
675

676
// _reindex(keys, method, limit, tolerance, fill) -> DataFrame on the index
677
// label key Series (one per level); see DataFrame::reindex.
678
PyObject* DataFrame_reindex(PyObject* self, PyObject* args) {
496 ✔
679
    DataFrameObject* b = as_native<DataFrameObject>(self);
496 ✔
680
    if (!b) return nullptr;
496 !
681
    PyObject* keys_obj = nullptr;
496 ✔
682
    PyObject* fill_obj = nullptr;
496 ✔
683
    PyObject* nanos_obj = Py_None;
496 ✔
684
    int method = 0;
496 ✔
685
    long long limit = -1;
496 ✔
686
    double tolerance = 0;
496 ✔
687
    if (!PyArg_ParseTuple(args, "OiLdO|O", &keys_obj, &method, &limit,
496 !
688
                          &tolerance, &fill_obj, &nanos_obj))
689
        return nullptr;
690
    dstd::Vector<Series> keys;
496 ✔
691
    if (!dftracer::utils::python::frame::series_list_from_py(
496 !
692
            keys_obj, "_reindex: keys must be Series", keys))
248 ✔
693
        return nullptr;
694
    if (method < 0 || method > 3) {
496 !
UNCOV
695
        PyErr_SetString(PyExc_ValueError, "_reindex: method must be 0..3");
×
696
        return nullptr;
697
    }
698
    dataframe::ReindexOptions options;
496 ✔
699
    options.method = static_cast<dataframe::FillMethod>(method);
496 ✔
700
    options.limit = limit;
496 ✔
701
    options.tolerance = tolerance;
496 ✔
702
    if (nanos_obj != Py_None) {
496 ✔
703
        options.tolerance_nanos = PyLong_AsLongLong(nanos_obj);
×
UNCOV
704
        if (options.tolerance_nanos == -1 && PyErr_Occurred()) return nullptr;
×
UNCOV
705
        options.tolerance_is_nanos = true;
×
706
    }
707
    Series fill;
496 ✔
708
    if (fill_obj != Py_None) {
496 ✔
709
        const Series* f =
70 ✔
710
            dftracer::utils::python::frame::unwrap_vec_column(fill_obj);
70 !
711
        if (!f) {
70 !
UNCOV
712
            PyErr_SetString(PyExc_TypeError, "_reindex: fill must be a Series");
×
713
            return nullptr;
714
        }
715
        fill = f->share();
70 !
716
    }
35 !
717
    return run_batch_op(b, [&](const DataFrame& frame) {
744 !
718
        return frame.reindex(keys, options, fill);
496 ✔
719
    });
248 ✔
720
}
496 ✔
721

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

766
PyObject* DataFrame_tail(PyObject* self, PyObject* arg) {
114 ✔
767
    DataFrameObject* b = as_native<DataFrameObject>(self);
114 ✔
768
    if (!b) return nullptr;
114 !
769
    long long n = PyLong_AsLongLong(arg);
114 ✔
770
    if (n == -1 && PyErr_Occurred()) return nullptr;
114 !
771
    return run_batch_op(
114 ✔
772
        b, [&](const DataFrame& frame) { return dataframe::tail(frame, n); });
228 ✔
773
}
57 ✔
774

775
PyObject* DataFrame_reverse(PyObject* self, PyObject*) {
962 ✔
776
    DataFrameObject* b = as_native<DataFrameObject>(self);
962 ✔
777
    if (!b) return nullptr;
962 !
778
    return run_batch_op(
962 ✔
779
        b, [&](const DataFrame& frame) { return dataframe::reverse(frame); });
1,924 !
780
}
481 ✔
781

782
PyObject* DataFrame_drop_nulls(PyObject* self, PyObject*) {
12 ✔
783
    DataFrameObject* b = as_native<DataFrameObject>(self);
12 ✔
784
    if (!b) return nullptr;
12 !
785
    return run_batch_op(b, [&](const DataFrame& frame) {
18 ✔
786
        return dataframe::drop_nulls(frame);
12 !
787
    });
6 ✔
788
}
6 ✔
789

790
PyObject* DataFrame_fill_null(PyObject* self, PyObject* value) {
48 ✔
791
    DataFrameObject* b = as_native<DataFrameObject>(self);
48 ✔
792
    if (!b) return nullptr;
48 !
793
    dftu_scalar s{};
48 ✔
794
    if (!py_to_scalar(value, &s)) return nullptr;
48 !
795
    return run_batch_op(b, [&](const DataFrame& frame) {
72 ✔
796
        return dataframe::fill_null(frame, s);
48 !
797
    });
24 ✔
798
}
24 ✔
799

800
PyObject* DataFrame_drop_nans(PyObject* self, PyObject*) {
2 ✔
801
    DataFrameObject* b = as_native<DataFrameObject>(self);
2 ✔
802
    if (!b) return nullptr;
2 !
803
    return run_batch_op(
2 ✔
804
        b, [&](const DataFrame& frame) { return dataframe::drop_nans(frame); });
4 !
805
}
1 ✔
806

807
PyObject* DataFrame_fill_nan(PyObject* self, PyObject* args, PyObject* kwds) {
38 ✔
808
    DataFrameObject* b = as_native<DataFrameObject>(self);
38 ✔
809
    if (!b) return nullptr;
38 !
810
    PyObject* value = nullptr;
38 ✔
811
    if (!parse_kw<"O">(args, kwds, {"value"}, &value)) return nullptr;
38 ✔
812
    dftu_scalar s{};
38 ✔
813
    if (!py_to_fill_scalar(value, &s)) return nullptr;
38 !
814
    return run_batch_op(b, [&](const DataFrame& frame) {
57 ✔
815
        return dataframe::fill_nan(frame, s);
38 !
816
    });
19 ✔
817
}
19 ✔
818

819
// Read a sequence (or single str) of column names into `out`. Returns false and
820
// sets a Python error on a non-string element.
821
bool names_from_obj(
3,734 ✔
822
    PyObject* obj,
823
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String>& out) {
824
    if (PyUnicode_Check(obj)) {
3,734 ✔
825
        out.emplace_back(PyUnicode_AsUTF8(obj));
20 ✔
826
        return true;
20 ✔
827
    }
828
    return parse_string_seq(obj, "expected a str or sequence of str", out);
3,714 ✔
829
}
1,867 ✔
830

831
// unique(subset=None): subset is a name or a sequence of names; None or an
832
// empty sequence keys on every column.
833
PyObject* DataFrame_unique(PyObject* self, PyObject* args, PyObject* kwds) {
114 ✔
834
    DataFrameObject* b = as_native<DataFrameObject>(self);
114 ✔
835
    if (!b) return nullptr;
114 !
836
    PyObject* subset_obj = Py_None;
114 ✔
837
    if (!parse_kw<"|O">(args, kwds, {"subset"}, &subset_obj)) return nullptr;
114 ✔
838
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> subset;
114 ✔
839
    if (subset_obj != Py_None && !names_from_obj(subset_obj, subset))
114 !
840
        return nullptr;
841
    return run_batch_op(b, [&](const DataFrame& frame) {
171 !
842
        return dataframe::unique(frame, subset);
114 ✔
843
    });
57 ✔
844
}
114 ✔
845

846
PyObject* DataFrame_sort_by_multi(PyObject* self, PyObject* args,
3,242 ✔
847
                                  PyObject* kwds) {
848
    DataFrameObject* b = as_native<DataFrameObject>(self);
3,242 ✔
849
    if (!b) return nullptr;
3,242 !
850
    PyObject* names_obj = nullptr;
3,242 ✔
851
    PyObject* descending_obj = nullptr;
3,242 ✔
852
    PyObject* nulls_last_obj = nullptr;
3,242 ✔
853
    if (!parse_kw<"O|OO">(args, kwds, {"names", "descending", "nulls_last"},
3,242 ✔
854
                          &names_obj, &descending_obj, &nulls_last_obj))
855
        return nullptr;
856
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> names;
3,242 ✔
857
    if (!parse_string_seq(names_obj, "names must be a sequence", names))
3,242 !
858
        return nullptr;
859

860
    // `descending` is either a single bool (broadcasts) or a sequence of bool,
861
    // one per name; a bare Python list is never truthy-coerced (that was the
862
    // old "any non-empty list sorts descending" bug).
863
    dftracer::utils::dstd::Vector<bool> descending;
3,242 ✔
864
    if (!descending_from_obj(descending_obj, descending)) return nullptr;
3,242 !
865
    dftracer::utils::dstd::Vector<bool> nulls_last;
3,242 ✔
866
    if (!nulls_last_obj)
3,242 ✔
UNCOV
867
        nulls_last.push_back(true);
×
868
    else if (!descending_from_obj(
3,242 !
869
                 nulls_last_obj, nulls_last,
1,621 ✔
870
                 "nulls_last must be a bool or a sequence of bool"))
871
        return nullptr;
872
    dftracer::utils::dstd::Vector<std::uint8_t> desc_flags, last_flags;
3,242 ✔
873
    for (bool d : descending) desc_flags.push_back(d ? 1 : 0);
10,970 !
874
    for (bool l : nulls_last) last_flags.push_back(l ? 1 : 0);
8,153 !
875
    return run_batch_op(b, [&](const DataFrame& frame) {
4,863 !
876
        return dataframe::sort_by_multi(frame, names, desc_flags, last_flags);
3,242 ✔
877
    });
1,621 ✔
878
}
6,484 ✔
879

880
PyObject* DataFrame_sample(PyObject* self, PyObject* args, PyObject* kwds) {
14 ✔
881
    DataFrameObject* b = as_native<DataFrameObject>(self);
14 ✔
882
    if (!b) return nullptr;
14 !
883
    Py_ssize_t n = 0;
14 ✔
884
    unsigned long long seed = 0;
14 ✔
885
    if (!parse_kw<"n|K">(args, kwds, {"n", "seed"}, &n, &seed)) return nullptr;
14 ✔
886
    return run_batch_op(b, [&](const DataFrame& frame) {
21 ✔
887
        return dataframe::sample(frame, static_cast<std::int64_t>(n),
21 ✔
888
                                 static_cast<std::uint64_t>(seed));
14 ✔
889
    });
7 ✔
890
}
7 ✔
891

892
PyObject* DataFrame_with_row_index(PyObject* self, PyObject* arg) {
7,798 ✔
893
    DataFrameObject* b = as_native<DataFrameObject>(self);
7,798 ✔
894
    if (!b) return nullptr;
7,798 !
895
    const char* name = PyUnicode_AsUTF8(arg);
7,798 ✔
896
    if (!name) {
7,798 ✔
UNCOV
897
        PyErr_SetString(PyExc_TypeError, "with_row_index() expects a str");
×
UNCOV
898
        return nullptr;
×
899
    }
900
    return run_batch_op(b, [&](const DataFrame& frame) {
11,697 ✔
901
        return dataframe::with_row_index(frame, name);
7,798 ✔
902
    });
3,899 ✔
903
}
3,899 ✔
904

905
PyObject* DataFrame_describe(PyObject* self, PyObject*) {
12 ✔
906
    DataFrameObject* b = as_native<DataFrameObject>(self);
12 ✔
907
    if (!b) return nullptr;
12 !
908
    return run_batch_op(
12 ✔
909
        b, [&](const DataFrame& frame) { return dataframe::describe(frame); });
24 !
910
}
6 ✔
911

912
PyObject* DataFrame_null_count(PyObject* self, PyObject*) {
4 ✔
913
    DataFrameObject* b = as_native<DataFrameObject>(self);
4 ✔
914
    if (!b) return nullptr;
4 !
915
    return run_batch_op(b, [&](const DataFrame& frame) {
6 ✔
916
        return dataframe::null_count(frame);
4 !
917
    });
2 ✔
918
}
2 ✔
919

920
// reduce(agg): `agg` is an aggregate name (sum, mean, ...) broadcast over
921
// every eligible column, one row.
922
PyObject* DataFrame_reduce(PyObject* self, PyObject* arg) {
70 ✔
923
    DataFrameObject* b = as_native<DataFrameObject>(self);
70 ✔
924
    if (!b) return nullptr;
70 !
925
    const char* agg = PyUnicode_AsUTF8(arg);
70 ✔
926
    if (!agg) return nullptr;
70 !
927
    return run_batch_op(b,
105 ✔
928
                        [&](const DataFrame& frame)
105 ✔
929
                            -> dftracer::utils::dstd::Result<DataFrame> {
930
                            const auto op = dataframe::agg_from_string(agg);
70 ✔
931
                            if (!op) return op.error();
105 !
932
                            return dataframe::reduce(frame, *op);
70 !
933
                        });
70 ✔
934
}
35 ✔
935

936
PyObject* DataFrame_group_transform(PyObject* self, PyObject* args,
2,022 ✔
937
                                    PyObject* kwds) {
938
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,022 ✔
939
    if (!b) return nullptr;
2,022 !
940
    dftracer::utils::python::frame::GroupwiseArgs a;
2,022 ✔
941
    if (!dftracer::utils::python::frame::parse_groupwise_args(
2,022 !
942
            args, kwds, names_from_obj, a))
1,011 ✔
943
        return nullptr;
1 ✔
944
    return run_batch_op(b, [&](const DataFrame& frame) {
3,030 !
945
        return dataframe::GroupBy(frame, a.keys)
4,040 !
946
            .transform(static_cast<dataframe::GroupwiseOp>(a.kind), a.n,
3,030 !
947
                       static_cast<dataframe::RankMethod>(a.method),
2,020 ✔
948
                       a.ascending != 0);
3,030 !
949
    });
1,010 ✔
950
}
2,022 ✔
951

952
// reduce_specs(agg, keys) -> list[str]: the "op:column:out" specs that
953
// broadcast `agg` over every eligible non-key column, for group_by.
954
PyObject* DataFrame_reduce_specs(PyObject* self, PyObject* args) {
952 ✔
955
    DataFrameObject* b = as_native<DataFrameObject>(self);
952 ✔
956
    if (!b) return nullptr;
952 !
957
    const char* agg = nullptr;
952 ✔
958
    PyObject* keys_obj = Py_None;
952 ✔
959
    if (!PyArg_ParseTuple(args, "s|O", &agg, &keys_obj)) return nullptr;
952 !
960
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
952 ✔
961
    if (keys_obj != Py_None && !names_from_obj(keys_obj, keys)) return nullptr;
952 !
962
    const auto op = dataframe::agg_from_string(agg);
952 !
963
    if (!op) {
952 ✔
UNCOV
964
        dftracer::utils::python::core::set_py_error(op.error());
×
965
        return nullptr;
966
    }
967
    const auto found = dataframe::reduce_specs(to_dataframe(b), *op, keys);
952 !
968
    if (!found) {
952 ✔
969
        dftracer::utils::python::core::set_py_error(found.error());
2 !
970
        return nullptr;
1 ✔
971
    }
972
    const dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> specs =
950 ✔
973
        dftracer::utils::python::frame::reduce_spec_strings(*found);
950 !
974
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(specs.size()));
950 !
975
    if (!list) return nullptr;
950 !
976
    for (std::size_t i = 0; i < specs.size(); ++i) {
2,340 !
977
        PyObject* s = PyUnicode_FromString(specs[i].c_str());
1,390 !
978
        if (!s) {
1,390 !
UNCOV
979
            Py_DECREF(list);
×
UNCOV
980
            return nullptr;
×
981
        }
982
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
1,390 !
983
    }
695 !
984
    return list;
475 ✔
985
}
1,903 ✔
986

987
PyObject* DataFrame_is_duplicated(PyObject* self, PyObject*) {
14 ✔
988
    DataFrameObject* b = as_native<DataFrameObject>(self);
14 ✔
989
    if (!b) return nullptr;
14 !
990
    auto out = dataframe::is_duplicated(to_dataframe(b));
14 !
991
    if (!out) {
14 !
UNCOV
992
        dftracer::utils::python::core::set_py_error(out.error());
×
993
        return nullptr;
994
    }
995
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
14 !
996
}
14 ✔
997

998
PyObject* DataFrame_is_unique(PyObject* self, PyObject*) {
2 ✔
999
    DataFrameObject* b = as_native<DataFrameObject>(self);
2 ✔
1000
    if (!b) return nullptr;
2 !
1001
    auto out = dataframe::is_unique(to_dataframe(b));
2 !
1002
    if (!out) {
2 !
UNCOV
1003
        dftracer::utils::python::core::set_py_error(out.error());
×
1004
        return nullptr;
1005
    }
1006
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
2 !
1007
}
2 ✔
1008

1009
PyObject* DataFrame_column_index(PyObject* self, PyObject* arg) {
10 ✔
1010
    DataFrameObject* b = as_native<DataFrameObject>(self);
10 ✔
1011
    if (!b) return nullptr;
10 !
1012
    const char* name = PyUnicode_AsUTF8(arg);
10 ✔
1013
    if (!name) {
10 ✔
1014
        PyErr_SetString(PyExc_TypeError, "column_index() expects a str");
2 ✔
1015
        return nullptr;
2 ✔
1016
    }
1017
    return PyLong_FromLongLong(to_dataframe(b).column_index(name));
8 !
1018
}
5 ✔
1019

1020
PyObject* DataFrame_head(PyObject* self, PyObject* arg) {
74,383 ✔
1021
    DataFrameObject* b = as_native<DataFrameObject>(self);
74,383 ✔
1022
    if (!b) return nullptr;
74,383 !
1023
    long long n = PyLong_AsLongLong(arg);
74,383 ✔
1024
    if (n == -1 && PyErr_Occurred()) return nullptr;
74,383 !
1025
    return run_batch_op(
74,383 ✔
1026
        b, [&](const DataFrame& frame) { return dataframe::head(frame, n); });
148,764 ✔
1027
}
13,664 ✔
1028

1029
PyObject* DataFrame_slice(PyObject* self, PyObject* args) {
158 ✔
1030
    DataFrameObject* b = as_native<DataFrameObject>(self);
158 ✔
1031
    if (!b) return nullptr;
158 !
1032
    long long offset = 0, length = 0;
158 ✔
1033
    if (!PyArg_ParseTuple(args, "LL", &offset, &length)) return nullptr;
158 !
1034
    return run_batch_op(b, [&](const DataFrame& frame) {
237 ✔
1035
        return dataframe::slice(frame, offset, length);
158 ✔
1036
    });
79 ✔
1037
}
79 ✔
1038

1039
PyObject* DataFrame_sort_by(PyObject* self, PyObject* args, PyObject* kwds) {
2,392 ✔
1040
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,392 ✔
1041
    if (!b) return nullptr;
2,392 !
1042
    const char* name = nullptr;
2,392 ✔
1043
    int descending = 0;
2,392 ✔
1044
    int nulls_last = 1;
2,392 ✔
1045
    if (!parse_kw<"s|pp">(args, kwds, {"name", "descending", "nulls_last"},
2,392 ✔
1046
                          &name, &descending, &nulls_last))
1047
        return nullptr;
1048
    return run_batch_op(b, [&](const DataFrame& frame) {
3,588 ✔
1049
        return dataframe::sort_by(frame, name, descending != 0,
3,588 ✔
1050
                                  nulls_last != 0);
2,392 ✔
1051
    });
1,196 ✔
1052
}
1,196 ✔
1053

1054
PyObject* DataFrame_topk(PyObject* self, PyObject* args, PyObject* kwds) {
34 ✔
1055
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
1056
    if (!b) return nullptr;
34 !
1057
    const char* name = nullptr;
34 ✔
1058
    Py_ssize_t k = 0;
34 ✔
1059
    int largest = 1;
34 ✔
1060
    if (!parse_kw<"sn|p">(args, kwds, {"name", "k", "largest"}, &name, &k,
34 ✔
1061
                          &largest))
1062
        return nullptr;
1063
    return run_batch_op(b, [&](const DataFrame& frame) {
51 ✔
1064
        return dataframe::topk(frame, name, static_cast<std::int64_t>(k),
51 ✔
1065
                               largest != 0);
34 ✔
1066
    });
17 ✔
1067
}
17 ✔
1068

1069
PyObject* DataFrame_partition_id(PyObject* self, PyObject* args) {
14 ✔
1070
    DataFrameObject* b = as_native<DataFrameObject>(self);
14 ✔
1071
    if (!b) return nullptr;
14 !
1072
    PyObject* keys_obj = nullptr;
14 ✔
1073
    Py_ssize_t n_parts = 0;
14 ✔
1074
    if (!PyArg_ParseTuple(args, "On", &keys_obj, &n_parts)) return nullptr;
14 ✔
1075
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
12 ✔
1076
    if (PyUnicode_Check(keys_obj)) {
12 ✔
1077
        keys.emplace_back(PyUnicode_AsUTF8(keys_obj));
10 !
1078
    } else if (!parse_string_seq(keys_obj, "keys must be a str or list",
7 !
1079
                                 keys)) {
1080
        return nullptr;
1 ✔
1081
    }
1082
    auto out = dataframe::partition_id(to_dataframe(b), keys,
10 !
1083
                                       static_cast<std::int64_t>(n_parts));
10 !
1084
    if (!out) {
10 ✔
1085
        dftracer::utils::python::core::set_py_error(out.error());
4 !
1086
        return nullptr;
2 ✔
1087
    }
1088
    return dftracer::utils::python::frame::wrap_vec_column(std::move(*out));
6 !
1089
}
13 ✔
1090

1091
// hash_partition(keys, n_parts) -> list[DataFrame]; keys is a name or a
1092
// sequence of names. The shuffle primitive for distributed group_by/join.
1093
PyObject* DataFrame_hash_partition(PyObject* self, PyObject* args) {
2,250 ✔
1094
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,250 ✔
1095
    if (!b) return nullptr;
2,250 !
1096
    PyObject* keys_obj = nullptr;
2,250 ✔
1097
    Py_ssize_t n_parts = 0;
2,250 ✔
1098
    if (!PyArg_ParseTuple(args, "On", &keys_obj, &n_parts)) return nullptr;
2,250 !
1099

1100
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
2,250 ✔
1101
    if (PyUnicode_Check(keys_obj)) {
2,250 !
UNCOV
1102
        keys.emplace_back(PyUnicode_AsUTF8(keys_obj));
×
1103
    } else if (!parse_string_seq(keys_obj, "keys must be a str or list",
2,250 !
1104
                                 keys)) {
1105
        return nullptr;
1106
    }
1107

1108
    auto found = dataframe::hash_partition(to_dataframe(b), keys,
2,250 !
1109
                                           static_cast<std::int64_t>(n_parts));
2,250 !
1110
    if (!found) {
2,250 ✔
UNCOV
1111
        dftracer::utils::python::core::set_py_error(found.error());
×
1112
        return nullptr;
1113
    }
1114
    dftracer::utils::dstd::Vector<DataFrame> parts = std::move(*found);
2,250 !
1115
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(parts.size()));
2,250 !
1116
    if (!list) return nullptr;
2,250 !
1117
    for (std::size_t i = 0; i < parts.size(); ++i) {
66,358 !
1118
        PyObject* vb = make_dataframe(std::move(parts[i]));
64,108 !
1119
        if (!vb) {
64,108 !
UNCOV
1120
            Py_DECREF(list);
×
UNCOV
1121
            return nullptr;
×
1122
        }
1123
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), vb);
64,108 !
1124
    }
32,054 !
1125
    return list;
1,125 ✔
1126
}
3,375 ✔
1127

1128
// One (op, ast, out[, param[, by_ast[, udaf[, interp]]]]) spec tuple, appended
1129
// to `out`; `by_ast` and `udaf` may be None, `interp` is the interpolation code
1130
// of a quantile.
1131
bool agg_expr_spec_from_tuple(
2,688 ✔
1132
    PyObject* t, dftracer::utils::dstd::Vector<dataframe::AggExprSpec>& out) {
1133
    const Py_ssize_t tn = PyTuple_Check(t) ? PyTuple_GET_SIZE(t) : 0;
2,688 !
1134
    if (tn < 3 || tn > 7) {
2,688 !
UNCOV
1135
        PyErr_SetString(
×
1136
            PyExc_TypeError,
1137
            "each spec is (op, ast, out[, param[, by_ast[, udaf[, interp]]]])");
UNCOV
1138
        return false;
×
1139
    }
1140
    dataframe::AggExprSpec s;
2,688 ✔
1141
    s.op = static_cast<dataframe::AggOp>(PyLong_AsLong(PyTuple_GET_ITEM(t, 0)));
2,688 !
1142
    if (tn >= 4) {
2,688 ✔
1143
        s.param = PyFloat_AsDouble(PyTuple_GET_ITEM(t, 3));
2,688 !
1144
        if (s.param == -1.0 && PyErr_Occurred()) return false;
2,688 !
1145
    }
1,344 ✔
1146
    PyObject* ast = PyTuple_GET_ITEM(t, 1);
2,688 !
1147
    if (ast != Py_None) {
2,688 ✔
1148
        dataframe::Expr v;
2,684 ✔
1149
        if (!dftracer::utils::python::frame::build_expr_from_ast(ast, &v))
2,684 !
UNCOV
1150
            return false;
×
1151
        s.value = std::move(v);
2,684 !
1152
    }
2,684 !
1153
    if (tn >= 5) {
2,688 ✔
1154
        PyObject* by_ast = PyTuple_GET_ITEM(t, 4);
2,496 !
1155
        if (by_ast != Py_None) {
2,496 ✔
1156
            dataframe::Expr by;
246 ✔
1157
            if (!dftracer::utils::python::frame::build_expr_from_ast(by_ast,
246 !
1158
                                                                     &by))
UNCOV
1159
                return false;
×
1160
            s.by = std::move(by);
246 !
1161
        }
246 !
1162
    }
1,248 !
1163
    if (tn >= 6 && PyTuple_GET_ITEM(t, 5) != Py_None) {
2,592 !
1164
        // (name, [arg_ast, ...]): the UDAF the spec calls and its
1165
        // arguments after `value`.
1166
        PyObject* call = PyTuple_GET_ITEM(t, 5);
×
UNCOV
1167
        PyObject* fn = PyTuple_Check(call) && PyTuple_GET_SIZE(call) == 2
×
1168
                           ? PyTuple_GET_ITEM(call, 0)
×
1169
                           : nullptr;
1170
        PyObject* arg_asts = fn ? PyTuple_GET_ITEM(call, 1) : nullptr;
×
UNCOV
1171
        if (!fn || !PyList_Check(arg_asts)) {
×
UNCOV
1172
            PyErr_SetString(PyExc_TypeError,
×
1173
                            "a udaf spec is (name, [arg_ast, ...])");
1174
            return false;
1175
        }
1176
        const char* fn_name = PyUnicode_AsUTF8(fn);
×
1177
        if (!fn_name) return false;
×
1178
        s.fn = fn_name;
×
1179
        for (Py_ssize_t j = 0; j < PyList_GET_SIZE(arg_asts); ++j) {
×
1180
            dataframe::Expr arg;
×
1181
            if (!dftracer::utils::python::frame::build_expr_from_ast(
×
1182
                    PyList_GET_ITEM(arg_asts, j), &arg))
×
1183
                return false;
×
UNCOV
1184
            s.args.push_back(std::move(arg));
×
UNCOV
1185
        }
×
1186
    }
×
1187
    if (tn == 7) {
2,688 ✔
1188
        const long interp = PyLong_AsLong(PyTuple_GET_ITEM(t, 6));
2,250 !
1189
        if (interp == -1 && PyErr_Occurred()) return false;
2,250 !
1190
        if (interp < 0 || interp > 4) {
2,250 !
UNCOV
1191
            PyErr_SetString(PyExc_ValueError,
×
1192
                            "a quantile interpolation code is 0 to 4");
1193
            return false;
1194
        }
1195
        s.interp = static_cast<dataframe::Interpolation>(interp);
2,250 ✔
1196
    }
1,125 !
1197
    const char* out_name = PyUnicode_AsUTF8(PyTuple_GET_ITEM(t, 2));
2,688 !
1198
    if (!out_name) return false;
2,688 ✔
1199
    s.out = out_name;
2,688 !
1200
    out.push_back(std::move(s));
2,688 !
1201
    return true;
1,344 ✔
1202
}
2,688 ✔
1203

1204
// _group_agg_expr(key, specs): the expression-aggregate workhorse. `key` is a
1205
// column name or a sequence of names (composite key). `specs` is a list of
1206
// (op_int, value_ast_or_None, out_name[, param[, by_ast]]); value ASTs
1207
// reference this batch's columns by index. `by_ast` is ArgMax's maximized
1208
// value. All value expressions compile in one CSE'd, pruned pass
1209
// (dataframe::group_agg_expr). The Python GroupBy serializes to this.
1210
PyObject* DataFrame_group_agg_expr(PyObject* self, PyObject* args) {
366 ✔
1211
    DataFrameObject* b = as_native<DataFrameObject>(self);
366 ✔
1212
    if (!b) return nullptr;
366 ✔
1213
    PyObject* key_obj = nullptr;
366 ✔
1214
    PyObject* specs = nullptr;
366 ✔
1215
    if (!PyArg_ParseTuple(args, "OO", &key_obj, &specs)) return nullptr;
366 ✔
1216
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
366 ✔
1217
    if (!strings_from_str_or_seq(key_obj, keys)) return nullptr;
366 !
1218
    DataFrame bat = to_dataframe(b);
366 !
1219
    dftracer::utils::dstd::Vector<dataframe::Expr> key_exprs;
366 ✔
1220
    key_exprs.reserve(keys.size());
366 !
1221
    for (const dftracer::utils::dstd::String& key : keys) {
632 !
1222
        std::int32_t ki = -1;
388 ✔
1223
        for (std::size_t i = 0; i < bat.names.size(); ++i)
643 !
1224
            if (bat.names[i] == key) {
510 ✔
1225
                ki = static_cast<std::int32_t>(i);
266 ✔
1226
                break;
266 ✔
1227
            }
1228
        if (ki < 0) {
266 ✔
1229
            PyErr_Format(PyExc_KeyError, "group_by: no column named %s",
×
1230
                         key.c_str());
UNCOV
1231
            return nullptr;
×
1232
        }
1233
        key_exprs.push_back(dataframe::expr_col(ki));
399 !
1234
    }
133 !
1235

1236
    dftracer::utils::dstd::Vector<dataframe::AggExprSpec> aggs;
366 ✔
1237
    if (!parse_seq<dataframe::AggExprSpec>(
366 !
1238
            specs, "specs must be a sequence", aggs,
183 ✔
1239
            [](PyObject* t,
2,688 ✔
1240
               dftracer::utils::dstd::Vector<dataframe::AggExprSpec>& o) {
1241
                return agg_expr_spec_from_tuple(t, o);
2,688 ✔
1242
            }))
1243
        return nullptr;
1244

1245
    dftracer::utils::dstd::Vector<const Series*> inputs;
366 ✔
1246
    inputs.reserve(bat.columns.size());
366 !
1247
    for (const Series& c : bat.columns) inputs.push_back(&c);
1,486 ✔
1248
    // An aggregate over a per-batch Python udf runs on the Python lane, which
1249
    // needs the GIL; nothing in this region touches Python.
1250
    auto grouped = release_gil([&] {
915 !
1251
        return dataframe::group_agg_expr(key_exprs, aggs, inputs, keys);
366 ✔
1252
    });
366 !
1253
    if (!grouped) {
366 !
UNCOV
1254
        dftracer::utils::python::core::set_py_error(grouped.error());
×
1255
        return nullptr;
1256
    }
1257
    return make_dataframe(std::move(*grouped));
366 !
1258
}
366 ✔
1259

1260
// Two-step / expression forms delegate to the Python GroupBy, which serializes
1261
// each spec and calls _group_agg_expr. `args[0:nk]` are the key names (a tuple,
1262
// even for one key); `args[nk:]` are the specs.
1263
PyObject* delegate_groupby(PyObject* self, PyObject* args, Py_ssize_t nk) {
6 ✔
1264
    PyObject* mod = PyImport_ImportModule("dftracer.utils._groupby");
6 ✔
1265
    if (!mod) return nullptr;
6 !
1266
    PyObject* gb_type = PyObject_GetAttrString(mod, "GroupBy");
6 ✔
1267
    Py_DECREF(mod);
6 !
1268
    if (!gb_type) return nullptr;
6 !
1269
    PyObject* keys = PyTuple_GetSlice(args, 0, nk);
6 ✔
1270
    if (!keys) {
6 ✔
UNCOV
1271
        Py_DECREF(gb_type);
×
UNCOV
1272
        return nullptr;
×
1273
    }
1274
    PyObject* gb = PyObject_CallFunctionObjArgs(gb_type, self, keys, nullptr);
6 ✔
1275
    Py_DECREF(keys);
6 !
1276
    Py_DECREF(gb_type);
6 !
1277
    if (!gb) return nullptr;
6 !
1278
    Py_ssize_t n = PyTuple_GET_SIZE(args);
6 ✔
1279
    if (n == nk) return gb;             // two-step: hand back the GroupBy
6 ✔
1280
    PyObject* rest =
3 ✔
1281
        PyTuple_GetSlice(args, nk, n);  // the specs, as an arg tuple
2 ✔
1282
    PyObject* aggm = rest ? PyObject_GetAttrString(gb, "agg") : nullptr;
2 !
1283
    Py_DECREF(gb);
2 !
1284
    PyObject* res = aggm ? PyObject_Call(aggm, rest, nullptr) : nullptr;
2 !
1285
    Py_XDECREF(aggm);
2 ✔
1286
    Py_XDECREF(rest);
2 ✔
1287
    return res;
2 ✔
1288
}
3 ✔
1289

1290
// group_by(*keys_and_specs). The leading run of plain column-name strings
1291
// (not "count" and not containing ':') are the (possibly composite) key; a
1292
// trailing run of legacy "op[:column]" strings runs inline, anything else
1293
// (no specs, or an expression/Agg spec) delegates to the Python GroupBy and
1294
// the expression-aggregate path (CSE + pruner).
1295
PyObject* DataFrame_group_by(PyObject* self, PyObject* args) {
9,980 ✔
1296
    DataFrameObject* b = as_native<DataFrameObject>(self);
9,980 ✔
1297
    if (!b) return nullptr;
9,980 !
1298
    Py_ssize_t n = PyTuple_GET_SIZE(args);
9,980 ✔
1299
    if (n < 1) {
9,980 ✔
UNCOV
1300
        PyErr_SetString(PyExc_TypeError, "group_by(*keys, *aggs) needs a key");
×
UNCOV
1301
        return nullptr;
×
1302
    }
1303
    Py_ssize_t nk = 0;
4,990 ✔
1304
    for (; nk < n; ++nk) {
21,094 ✔
1305
        PyObject* a = PyTuple_GET_ITEM(args, nk);
21,090 !
1306
        if (!PyUnicode_Check(a)) break;
21,090 ✔
1307
        const char* s = PyUnicode_AsUTF8(a);
21,088 ✔
1308
        if (!s) return nullptr;
21,088 ✔
1309
        const dftracer::utils::dstd::String sv(s);
21,088 ✔
1310
        if (sv == "count" ||
21,088 ✔
1311
            sv.find(':') != dftracer::utils::dstd::String::npos)
18,570 ✔
1312
            break;
4,987 ✔
1313
    }
21,090 !
1314
    if (nk == 0) nk = 1;  // args[0] is always at least one key
9,980 ✔
1315
    bool rest_legacy = n > nk;
9,980 ✔
1316
    for (Py_ssize_t i = nk; i < n && rest_legacy; ++i)
28,446 ✔
1317
        rest_legacy = PyUnicode_Check(PyTuple_GET_ITEM(args, i)) != 0;
18,466 ✔
1318
    if (n == nk || !rest_legacy) return delegate_groupby(self, args, nk);
9,980 ✔
1319

1320
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> keys;
9,974 ✔
1321
    keys.reserve(static_cast<std::size_t>(nk));
9,974 !
1322
    for (Py_ssize_t i = 0; i < nk; ++i) {
21,078 !
1323
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
11,104 !
1324
        if (!s) return nullptr;
11,104 !
1325
        keys.emplace_back(s);
11,104 !
1326
    }
5,552 !
1327
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> specs;
9,974 ✔
1328
    specs.reserve(static_cast<std::size_t>(n - nk));
9,974 !
1329
    for (Py_ssize_t i = nk; i < n; ++i) {
28,438 !
1330
        const char* s = PyUnicode_AsUTF8(PyTuple_GET_ITEM(args, i));
18,464 !
1331
        if (!s) return nullptr;
18,464 ✔
1332
        specs.emplace_back(s);
18,464 !
1333
    }
9,232 !
1334
    return run_batch_op(b, [&](const DataFrame& frame) {
14,961 !
1335
        dftracer::utils::dstd::Vector<dataframe::GroupAgg> aggs;
9,974 ✔
1336
        aggs.reserve(specs.size());
9,974 !
1337
        for (const dftracer::utils::dstd::String& spec : specs)
28,437 ✔
1338
            aggs.push_back(group_agg_from_spec(spec));
27,696 !
1339
        return dataframe::group_by(frame, keys, aggs);
14,958 !
1340
    });
9,975 ✔
1341
}
9,977 ✔
1342

1343
// join(other, how="inner", on=1): equi-join on the first `on` (leading) key
1344
// columns; how is inner|left|right|full|semi|anti.
1345
PyObject* DataFrame_join(PyObject* self, PyObject* args, PyObject* kwds) {
8,074 ✔
1346
    DataFrameObject* b = as_native<DataFrameObject>(self);
8,074 ✔
1347
    if (!b) return nullptr;
8,074 !
1348
    PyObject* other = nullptr;
8,074 ✔
1349
    PyObject* on = nullptr;
8,074 ✔
1350
    const char* how = "inner";
8,074 ✔
1351
    PyObject* left_on = nullptr;
8,074 ✔
1352
    PyObject* right_on = nullptr;
8,074 ✔
1353
    const char* suffix = "_right";
8,074 ✔
1354
    int nulls_equal = 0;
8,074 ✔
1355
    if (!parse_kw<"O|OsOOsp">(args, kwds,
12,111 !
1356
                              {"other", "on", "how", "left_on", "right_on",
4,037 ✔
1357
                               "suffix", "nulls_equal"},
1358
                              &other, &on, &how, &left_on, &right_on, &suffix,
1359
                              &nulls_equal))
1360
        return nullptr;
1361
    DataFrameObject* o = as_native<DataFrameObject>(other);
8,074 ✔
1362
    if (!o) return nullptr;
8,074 !
1363
    dataframe::JoinHow jh;
8,074 ✔
1364
    if (!join_how_from_str(how, jh)) return nullptr;
8,074 ✔
1365
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> l;
8,072 ✔
1366
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> r;
8,072 ✔
1367
    if (!join_keys_from_objs(on, left_on, right_on, jh, l, r)) return nullptr;
8,072 !
1368
    const DataFrame other_frame = to_dataframe(o);
8,058 !
1369
    return run_batch_op(b, [&](const DataFrame& frame) {
12,087 !
1370
        return dataframe::join(frame, other_frame, l, r, jh, suffix,
12,087 ✔
1371
                               nulls_equal != 0);
8,058 ✔
1372
    });
4,029 ✔
1373
}
8,073 ✔
1374

1375
PyObject* DataFrame_compare_agg(PyObject* self, PyObject* args) {
18 ✔
1376
    DataFrameObject* b = as_native<DataFrameObject>(self);
18 ✔
1377
    if (!b) return nullptr;
18 !
1378
    PyObject* other = nullptr;
18 ✔
1379
    Py_ssize_t n_key = 1;
18 ✔
1380
    if (!PyArg_ParseTuple(args, "On", &other, &n_key)) return nullptr;
18 !
1381
    DataFrameObject* o = as_native<DataFrameObject>(other);
18 ✔
1382
    if (!o) return nullptr;
18 !
1383
    const DataFrame other_frame = to_dataframe(o);
18 ✔
1384
    return run_batch_op(b, [&](const DataFrame& frame) {
27 !
1385
        return dataframe::compare_agg(frame, other_frame,
27 ✔
1386
                                      static_cast<std::int64_t>(n_key));
18 ✔
1387
    });
9 ✔
1388
}
18 ✔
1389

1390
// unpivot(id_vars, value_vars) / melt: reshape wide -> long.
1391
PyObject* DataFrame_unpivot(PyObject* self, PyObject* args, PyObject* kwds) {
336 ✔
1392
    DataFrameObject* b = as_native<DataFrameObject>(self);
336 ✔
1393
    if (!b) return nullptr;
336 !
1394
    PyObject* id_obj = nullptr;
336 ✔
1395
    PyObject* val_obj = nullptr;
336 ✔
1396
    if (!parse_kw<"OO">(args, kwds, {"id_vars", "value_vars"}, &id_obj,
336 ✔
1397
                        &val_obj))
1398
        return nullptr;
1399
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> id_vars,
336 ✔
1400
        value_vars;
336 ✔
1401
    if (!names_from_obj(id_obj, id_vars)) return nullptr;
336 !
1402
    if (!names_from_obj(val_obj, value_vars)) return nullptr;
336 !
1403
    return run_batch_op(b, [&](const DataFrame& frame) {
504 !
1404
        return dataframe::unpivot(frame, id_vars, value_vars);
336 ✔
1405
    });
168 ✔
1406
}
336 ✔
1407

1408
PyObject* DataFrame_explode(PyObject* self, PyObject* arg) {
32 ✔
1409
    DataFrameObject* b = as_native<DataFrameObject>(self);
32 ✔
1410
    if (!b) return nullptr;
32 !
1411
    const char* name = PyUnicode_AsUTF8(arg);
32 ✔
1412
    if (!name) {
32 ✔
UNCOV
1413
        PyErr_SetString(PyExc_TypeError, "explode() expects a column name");
×
UNCOV
1414
        return nullptr;
×
1415
    }
1416
    return run_batch_op(b, [&](const DataFrame& frame) {
48 ✔
1417
        return dataframe::explode(frame, name);
32 ✔
1418
    });
16 ✔
1419
}
16 ✔
1420

1421
PyObject* DataFrame_window(PyObject* self, PyObject* args, PyObject* kwds) {
56 ✔
1422
    DataFrameObject* b = as_native<DataFrameObject>(self);
56 ✔
1423
    if (!b) return nullptr;
56 !
1424
    PyObject* part = nullptr;
56 ✔
1425
    PyObject* order = nullptr;
56 ✔
1426
    PyObject* specs = nullptr;
56 ✔
1427
    if (!parse_kw<"OOO">(args, kwds, {"partition_by", "order_by", "specs"},
56 ✔
1428
                         &part, &order, &specs))
1429
        return nullptr;
1430
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> pcols;
56 ✔
1431
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> ocols;
56 ✔
1432
    if (!parse_string_seq(part, "window: partition_by must be names", pcols) ||
112 !
1433
        !parse_string_seq(order, "window: order_by must be names", ocols))
56 !
UNCOV
1434
        return nullptr;
×
1435
    dftracer::utils::python::frame::WindowSpecs parsed;
56 !
1436
    if (!dftracer::utils::python::frame::parse_window_specs(specs, parsed))
56 !
1437
        return nullptr;
1438
    dftracer::utils::dstd::Vector<dataframe::WindowColumn> specv;
56 ✔
1439
    specv.reserve(parsed.specs.size());
56 !
1440
    for (const dftu_window_spec& w : parsed.specs)
204 ✔
1441
        specv.push_back(dataframe::window_column(w));
296 !
1442
    return run_batch_op(b, [&](const DataFrame& frame) {
84 !
1443
        return dataframe::window(frame, pcols, ocols, specv);
56 ✔
1444
    });
28 ✔
1445
}
84 ✔
1446

1447
PyObject* DataFrame_gap_fill(PyObject* self, PyObject* args, PyObject* kwds) {
24 ✔
1448
    DataFrameObject* b = as_native<DataFrameObject>(self);
24 ✔
1449
    if (!b) return nullptr;
24 !
1450
    PyObject* part = nullptr;
24 ✔
1451
    const char* time = nullptr;
24 ✔
1452
    long long bucket = 0;
24 ✔
1453
    PyObject* values = nullptr;
24 ✔
1454
    const char* mode = nullptr;
24 ✔
1455
    PyObject* start_obj = Py_None;
24 ✔
1456
    PyObject* end_obj = Py_None;
24 ✔
1457
    if (!parse_kw<"OsLOs|OO">(args, kwds,
36 !
1458
                              {"partition_by", "time", "bucket", "values",
12 ✔
1459
                               "mode", "start", "end"},
1460
                              &part, &time, &bucket, &values, &mode, &start_obj,
1461
                              &end_obj))
1462
        return nullptr;
1463
    dftu_gap_fill_mode mode_code;
24 ✔
1464
    if (!dftracer::utils::python::frame::gap_fill_mode_from_str(mode,
24 ✔
1465
                                                                &mode_code))
1466
        return nullptr;
1 ✔
1467
    const auto m = static_cast<dataframe::GapFillMode>(mode_code);
22 ✔
1468
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> pcols;
22 ✔
1469
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> vcols;
22 ✔
1470
    if (!parse_string_seq(part, "gap_fill: partition_by must be names",
22 !
1471
                          pcols) ||
44 !
1472
        !parse_string_seq(values, "gap_fill: values must be names", vcols))
22 !
UNCOV
1473
        return nullptr;
×
1474
    dftracer::utils::dstd::Optional<
22 ✔
1475
        dftracer::utils::dstd::Pair<std::int64_t, std::int64_t>>
1476
        range;
22 ✔
1477
    if (start_obj != Py_None) {
22 ✔
1478
        const long long s = PyLong_AsLongLong(start_obj);
4 !
1479
        const long long e = PyLong_AsLongLong(end_obj);
4 !
1480
        if (PyErr_Occurred()) return nullptr;
4 !
1481
        range = dftracer::utils::dstd::Pair<std::int64_t, std::int64_t>{
8 !
1482
            static_cast<std::int64_t>(s), static_cast<std::int64_t>(e)};
6 !
1483
    }
2 !
1484
    return run_batch_op(b, [&](const DataFrame& frame) {
33 !
1485
        return dataframe::gap_fill(frame, pcols, time,
55 ✔
1486
                                   static_cast<std::int64_t>(bucket), vcols, m,
33 ✔
1487
                                   range);
22 ✔
1488
    });
11 ✔
1489
}
23 ✔
1490

1491
PyObject* DataFrame_asof(PyObject* self, PyObject* args, PyObject* kwds) {
54 ✔
1492
    DataFrameObject* b = as_native<DataFrameObject>(self);
54 ✔
1493
    if (!b) return nullptr;
54 !
1494
    PyObject* other = nullptr;
54 ✔
1495
    const char* on = nullptr;
54 ✔
1496
    PyObject* by = nullptr;
54 ✔
1497
    const char* direction = nullptr;
54 ✔
1498
    PyObject* tol_obj = Py_None;
54 ✔
1499
    if (!parse_kw<"OsOsO">(args, kwds,
81 !
1500
                           {"other", "on", "by", "direction", "tolerance"},
27 ✔
1501
                           &other, &on, &by, &direction, &tol_obj))
1502
        return nullptr;
1503
    DataFrameObject* o = as_native<DataFrameObject>(other);
54 ✔
1504
    if (!o) return nullptr;
54 !
1505
    dftu_asof_direction dir_code;
54 ✔
1506
    if (!dftracer::utils::python::frame::asof_direction_from_str(direction,
54 ✔
1507
                                                                 &dir_code))
1508
        return nullptr;
1 ✔
1509
    const auto dir = static_cast<dataframe::AsofDirection>(dir_code);
52 ✔
1510
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> equi;
52 ✔
1511
    if (!parse_string_seq(by, "asof: by must be names", equi)) return nullptr;
52 !
1512
    dftracer::utils::dstd::Optional<double> tol;
52 ✔
1513
    if (tol_obj != Py_None) {
52 ✔
1514
        const double t = PyFloat_AsDouble(tol_obj);
28 !
1515
        if (PyErr_Occurred()) return nullptr;
28 !
1516
        if (!(t >= 0)) {
28 !
UNCOV
1517
            PyErr_SetString(PyExc_ValueError,
×
1518
                            "asof: tolerance must not be negative");
1519
            return nullptr;
1520
        }
1521
        tol = t;
28 !
1522
    }
14 !
1523
    const DataFrame other_frame = to_dataframe(o);
52 !
1524
    return run_batch_op(b, [&](const DataFrame& frame) {
78 !
1525
        return dataframe::asof(frame, other_frame, on, equi, dir, tol);
52 ✔
1526
    });
26 ✔
1527
}
53 ✔
1528

1529
PyObject* DataFrame_interval(PyObject* self, PyObject* args, PyObject* kwds) {
20 ✔
1530
    DataFrameObject* b = as_native<DataFrameObject>(self);
20 ✔
1531
    if (!b) return nullptr;
20 !
1532
    PyObject* other = nullptr;
20 ✔
1533
    const char* point = nullptr;
20 ✔
1534
    const char* lo = nullptr;
20 ✔
1535
    const char* hi = nullptr;
20 ✔
1536
    PyObject* by = nullptr;
20 ✔
1537
    int outer = 0;
20 ✔
1538
    if (!parse_kw<"OsssOp">(args, kwds,
30 !
1539
                            {"other", "point", "lo", "hi", "by", "outer"},
10 ✔
1540
                            &other, &point, &lo, &hi, &by, &outer))
1541
        return nullptr;
1542
    DataFrameObject* o = as_native<DataFrameObject>(other);
20 ✔
1543
    if (!o) return nullptr;
20 !
1544
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> equi;
20 ✔
1545
    if (!parse_string_seq(by, "interval: by must be names", equi))
20 !
1546
        return nullptr;
1547
    const DataFrame other_frame = to_dataframe(o);
20 !
1548
    return run_batch_op(b, [&](const DataFrame& frame) {
30 !
1549
        return dataframe::interval(frame, other_frame, point, lo, hi, equi,
30 ✔
1550
                                   outer != 0);
20 ✔
1551
    });
10 ✔
1552
}
20 ✔
1553

1554
PyObject* DataFrame_unnest(PyObject* self, PyObject* args, PyObject* kwds) {
28 ✔
1555
    DataFrameObject* b = as_native<DataFrameObject>(self);
28 ✔
1556
    if (!b) return nullptr;
28 !
1557
    const char* name = nullptr;
28 ✔
1558
    int keep_empty = 0;
28 ✔
1559
    if (!parse_kw<"s|p">(args, kwds, {"column", "keep_empty"}, &name,
28 ✔
1560
                         &keep_empty))
1561
        return nullptr;
1562
    return run_batch_op(b, [&](const DataFrame& frame) {
42 ✔
1563
        return dataframe::unnest(frame, name, keep_empty != 0);
28 ✔
1564
    });
14 ✔
1565
}
14 ✔
1566

1567
PyObject* DataFrame_to_dummies(PyObject* self, PyObject* arg) {
8 ✔
1568
    DataFrameObject* b = as_native<DataFrameObject>(self);
8 ✔
1569
    if (!b) return nullptr;
8 !
1570
    const char* name = PyUnicode_AsUTF8(arg);
8 ✔
1571
    if (!name) {
8 ✔
UNCOV
1572
        PyErr_SetString(PyExc_TypeError, "to_dummies() expects a column name");
×
UNCOV
1573
        return nullptr;
×
1574
    }
1575
    return run_batch_op(b, [&](const DataFrame& frame) {
12 ✔
1576
        return dataframe::to_dummies(frame, name);
8 ✔
1577
    });
4 ✔
1578
}
4 ✔
1579

1580
// pivot(index, columns, values, agg="first"): long -> wide.
1581
PyObject* DataFrame_pivot(PyObject* self, PyObject* args, PyObject* kwds) {
30 ✔
1582
    DataFrameObject* b = as_native<DataFrameObject>(self);
30 ✔
1583
    if (!b) return nullptr;
30 !
1584
    const char* index = nullptr;
30 ✔
1585
    const char* columns = nullptr;
30 ✔
1586
    const char* values = nullptr;
30 ✔
1587
    const char* agg = "first";
30 ✔
1588
    if (!parse_kw<"sss|s">(args, kwds, {"index", "columns", "values", "agg"},
30 ✔
1589
                           &index, &columns, &values, &agg))
1590
        return nullptr;
1591
    return run_batch_op(b, [&](const DataFrame& frame) {
45 ✔
1592
        return dataframe::pivot(frame, index, columns, values, agg);
30 ✔
1593
    });
15 ✔
1594
}
15 ✔
1595

1596
// group_by_dynamic(time_col, every, period=None, aggs=[...]): tumbling/sliding
1597
// time-window aggregation. aggs mirror the group_by string-spec format.
1598
PyObject* DataFrame_group_by_dynamic(PyObject* self, PyObject* args,
36 ✔
1599
                                     PyObject* kwds) {
1600
    DataFrameObject* b = as_native<DataFrameObject>(self);
36 ✔
1601
    if (!b) return nullptr;
36 !
1602
    const char* time_col = nullptr;
36 ✔
1603
    long long every = 0;
36 ✔
1604
    PyObject* period_obj = Py_None;
36 ✔
1605
    PyObject* aggs_obj = Py_None;
36 ✔
1606
    PyObject* origin_obj = Py_None;  // int (explicit) or "min"
36 ✔
1607
    if (!parse_kw<"sL|OOO">(
36 ✔
1608
            args, kwds, {"time_col", "every", "period", "aggs", "origin"},
18 ✔
1609
            &time_col, &every, &period_obj, &aggs_obj, &origin_obj))
1610
        return nullptr;
1611
    std::int64_t period = 0;
36 ✔
1612
    if (period_obj && period_obj != Py_None) {
36 !
1613
        period = PyLong_AsLongLong(period_obj);
2 ✔
1614
        if (period == -1 && PyErr_Occurred()) return nullptr;
2 !
1615
    }
1 ✔
1616
    std::int64_t origin = 0;
36 ✔
1617
    bool origin_min = false;
36 ✔
1618
    if (origin_obj && origin_obj != Py_None) {
36 !
1619
        if (PyUnicode_Check(origin_obj)) {
4 ✔
1620
            const char* s = PyUnicode_AsUTF8(origin_obj);
2 ✔
1621
            if (!s) return nullptr;
2 !
1622
            if (dftracer::utils::dstd::String(s) != "min") {
2 !
UNCOV
1623
                PyErr_SetString(PyExc_ValueError,
×
1624
                                "group_by_dynamic: origin must be an int or "
1625
                                "\"min\"");
UNCOV
1626
                return nullptr;
×
1627
            }
1628
            origin_min = true;
2 ✔
1629
        } else {
1 !
1630
            origin = PyLong_AsLongLong(origin_obj);
2 ✔
1631
            if (origin == -1 && PyErr_Occurred()) return nullptr;
2 !
1632
        }
1633
    }
2 ✔
1634
    dftracer::utils::dstd::Vector<dataframe::GroupAgg> aggs;
36 ✔
1635
    if (aggs_obj && aggs_obj != Py_None && !aggs_from_seq(aggs_obj, aggs))
36 !
1636
        return nullptr;
1637
    return run_batch_op(b, [&](const DataFrame& frame) {
54 !
1638
        return dataframe::group_by_dynamic(frame, time_col,
72 ✔
1639
                                           static_cast<std::int64_t>(every),
36 ✔
1640
                                           period, aggs, origin, origin_min);
54 ✔
1641
    });
18 ✔
1642
}
36 ✔
1643

1644
PyObject* DataFrame_concat(PyObject* self, PyObject* args, PyObject* kwds) {
812 ✔
1645
    DataFrameObject* b = as_native<DataFrameObject>(self);
812 ✔
1646
    if (!b) return nullptr;
812 !
1647
    // `how` is the only keyword; every positional arg is another DataFrame.
1648
    dataframe::ConcatHow how = dataframe::ConcatHow::Vertical;
812 ✔
1649
    if (kwds) {
812 ✔
1650
        if (PyObject* h = PyDict_GetItemString(kwds, "how")) {
888 ✔
1651
            const char* s = PyUnicode_AsUTF8(h);
592 ✔
1652
            if (!s) return nullptr;
592 !
1653
            if (std::strcmp(s, "diagonal") == 0)
592 ✔
1654
                how = dataframe::ConcatHow::Diagonal;
46 ✔
1655
            else if (std::strcmp(s, "vertical") != 0) {
546 ✔
1656
                PyErr_SetString(PyExc_ValueError,
2 ✔
1657
                                "how must be 'vertical' or 'diagonal'");
1658
                return nullptr;
2 ✔
1659
            }
1660
        }
296 ✔
1661
        if (PyDict_Size(kwds) > (PyDict_GetItemString(kwds, "how") ? 1 : 0)) {
590 !
1662
            PyErr_SetString(PyExc_TypeError,
×
1663
                            "concat() got an unexpected keyword argument");
UNCOV
1664
            return nullptr;
×
1665
        }
1666
    }
295 ✔
1667
    dftracer::utils::dstd::Vector<DataFrame> owned;
810 ✔
1668
    owned.reserve(1 + static_cast<std::size_t>(PyTuple_GET_SIZE(args)));
810 !
1669
    owned.push_back(to_dataframe(b));
1,215 !
1670
    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(args); ++i) {
2,006 !
1671
        DataFrameObject* o =
1,794 !
1672
            as_native<DataFrameObject>(PyTuple_GET_ITEM(args, i));
1,196 !
1673
        if (!o) return nullptr;
1,196 !
1674
        owned.push_back(to_dataframe(o));
1,794 !
1675
    }
598 !
1676
    dftracer::utils::dstd::Vector<const DataFrame*> parts;
810 ✔
1677
    parts.reserve(owned.size());
810 !
1678
    for (const DataFrame& x : owned) parts.push_back(&x);
2,816 ✔
1679
    return run_batch_op(b, [&] { return dataframe::concat(parts, how); });
1,620 !
1680
}
811 ✔
1681

1682
// Arrow/pandas/polars conversion and pickling live in the Python wrapper
1683
// (dftracer.utils.frame); the native handle only exposes the zero-copy
1684
// __arrow_c_array__ / __arrow_c_stream__ capsules.
1685

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

1688
void schema_capsule_destructor(PyObject* cap) {
34 ✔
1689
    auto* s =
51 ✔
1690
        static_cast<ArrowSchema*>(PyCapsule_GetPointer(cap, "arrow_schema"));
34 ✔
1691
    if (s) {
34 ✔
1692
        if (s->release) s->release(s);
34 ✔
1693
        dftracer::utils::dstd::UniquePtr<ArrowSchema>(s).reset();
34 ✔
1694
    }
17 ✔
1695
}
34 ✔
1696
void array_capsule_destructor(PyObject* cap) {
34 ✔
1697
    auto* a =
51 ✔
1698
        static_cast<ArrowArray*>(PyCapsule_GetPointer(cap, "arrow_array"));
34 ✔
1699
    if (a) {
34 ✔
1700
        if (a->release) a->release(a);
34 ✔
1701
        dftracer::utils::dstd::UniquePtr<ArrowArray>(a).reset();
34 ✔
1702
    }
17 ✔
1703
}
34 ✔
1704

1705
PyObject* DataFrame_arrow_c_array(PyObject* self, PyObject*) {
34 ✔
1706
    DataFrameObject* b = as_native<DataFrameObject>(self);
34 ✔
1707
    if (!b) return nullptr;
34 !
1708
    dftracer::utils::dstd::UniquePtr<ArrowSchema> schema;
34 ✔
1709
    dftracer::utils::dstd::UniquePtr<ArrowArray> array;
34 ✔
1710
    schema = dftracer::utils::dstd::make_unique<ArrowSchema>();
51 !
1711
    array = dftracer::utils::dstd::make_unique<ArrowArray>();
51 !
1712
    auto batch = arrow::to_arrow(to_dataframe(b));
34 !
1713
    if (!batch) {
34 ✔
UNCOV
1714
        dftracer::utils::python::core::set_py_error(batch.error());
×
1715
        return nullptr;
1716
    }
1717
    batch->release_into(schema.get(), array.get());
34 ✔
1718
    PyObject* scap =
34 !
1719
        PyCapsule_New(schema.get(), "arrow_schema", schema_capsule_destructor);
34 !
1720
    if (!scap) {
34 ✔
1721
        if (schema->release) schema->release(schema.get());
×
UNCOV
1722
        if (array->release) array->release(array.get());
×
UNCOV
1723
        return nullptr;
×
1724
    }
1725
    schema.release();
34 !
1726
    PyObject* acap =
34 !
1727
        PyCapsule_New(array.get(), "arrow_array", array_capsule_destructor);
34 !
1728
    if (!acap) {
34 !
1729
        Py_DECREF(scap);
×
UNCOV
1730
        if (array->release) array->release(array.get());
×
UNCOV
1731
        return nullptr;
×
1732
    }
1733
    array.release();
34 !
1734
    PyObject* result = PyTuple_Pack(2, scap, acap);
34 !
1735
    Py_DECREF(scap);
34 !
1736
    Py_DECREF(acap);
51 !
1737
    return result;
17 ✔
1738
}
34 ✔
1739

1740
// __arrow_c_stream__: a stream of the struct (one batch per chunk of a
1741
// collected frame), so pa.table(batch) / pl.from_arrow(batch) import every
1742
// column zero-copy without an explicit to_arrow(). The single struct array
1743
// carries all fields.
1744
PyObject* DataFrame_arrow_c_stream(PyObject* self, PyObject* args,
4,394 ✔
1745
                                   PyObject* kwds) {
1746
    PyObject* requested_schema = Py_None;
4,394 ✔
1747
    if (!parse_kw<"|O">(args, kwds, {"requested_schema"}, &requested_schema))
4,394 ✔
1748
        return nullptr;
1749
    if (!dftracer::utils::python::core::no_requested_schema(requested_schema))
4,394 ✔
1750
        return nullptr;
1 ✔
1751
    DataFrameObject* b = as_native<DataFrameObject>(self);
4,392 ✔
1752
    if (!b) return nullptr;
4,392 !
1753
    const dataframe::DataFrame frame = to_dataframe(b);
4,392 ✔
1754
    auto stream = dftracer::utils::dstd::make_unique<ArrowArrayStream>();
4,392 !
1755
    auto status = arrow::to_arrow_stream(frame, stream.get());
4,392 !
1756
    if (!status) {
4,392 ✔
UNCOV
1757
        dftracer::utils::python::core::set_py_error(status.error());
×
1758
        return nullptr;
1759
    }
1760
    return dftracer::utils::python::core::stream_capsule(std::move(stream));
4,392 !
1761
}
4,393 ✔
1762

1763
// to_ipc() -> bytes: the frame serialized as an Arrow IPC stream (schema + one
1764
// record batch + EOS), so a consumer needs no pyarrow to produce .arrow bytes.
1765
PyObject* DataFrame_to_ipc(PyObject* self, PyObject*) {
4 ✔
1766
    DataFrameObject* b = as_native<DataFrameObject>(self);
4 ✔
1767
    if (!b) return nullptr;
4 !
1768
    return guard([&]() -> PyObject* {
6 ✔
1769
        auto writer = arrow::Writer::to_buffer();
4 ✔
1770
        const DataFrame frame = to_dataframe(b);
4 !
1771
        auto status = without_gil(frame.num_rows(), [&] {
10 !
1772
            auto written = writer.write(frame);
4 ✔
1773
            if (written) written = writer.finish();
4 !
1774
            return written;
4 ✔
1775
        });
4 !
1776
        if (!status) {
4 ✔
UNCOV
1777
            dftracer::utils::python::core::set_py_error(status.error());
×
1778
            return nullptr;
1779
        }
1780
        const auto bytes = writer.take_bytes();
4 !
1781
        return PyBytes_FromStringAndSize(
4 !
1782
            reinterpret_cast<const char*>(bytes.data()),
4 ✔
1783
            static_cast<Py_ssize_t>(bytes.size()));
4 !
1784
    });
6 ✔
1785
}
2 ✔
1786

1787
PyObject* DataFrame_to_bytes(PyObject* self, PyObject*) {
866 ✔
1788
    DataFrameObject* b = as_native<DataFrameObject>(self);
866 ✔
1789
    if (!b) return nullptr;
866 !
1790
    return guard([&]() -> PyObject* {
1,299 ✔
1791
        const DataFrame frame = to_dataframe(b);
866 ✔
1792
        const auto bytes = without_gil(frame.num_rows(), [&] {
2,165 !
1793
            return dataframe::frame_to_native(frame);
866 !
1794
        });
866 !
1795
        if (!bytes) {
866 !
UNCOV
1796
            PyErr_SetString(PyExc_TypeError, bytes.error().c_str());
×
1797
            return nullptr;
1798
        }
1799
        return PyBytes_FromStringAndSize(
866 !
1800
            bytes->data(), static_cast<Py_ssize_t>(bytes->size()));
866 ✔
1801
    });
866 ✔
1802
}
433 ✔
1803

1804
PyObject* dataframe_from_bytes(PyObject* /*self*/, PyObject* obj) {
866 ✔
1805
    Py_buffer view;
866 ✔
1806
    if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) return nullptr;
866 !
1807
    auto f = dataframe::frame_from_native(
1,299 ✔
1808
        dftracer::utils::dstd::StringView(static_cast<const char*>(view.buf),
1,299 ✔
1809
                                          static_cast<std::size_t>(view.len)));
866 ✔
1810
    PyBuffer_Release(&view);
866 !
1811
    if (!f) {
866 !
UNCOV
1812
        PyErr_SetString(PyExc_ValueError,
×
1813
                        "not a DataFrame written by this version");
1814
        return nullptr;
1815
    }
1816
    return make_dataframe(std::move(*f));
866 !
1817
}
866 ✔
1818

1819
// One column buffer of a frame, read only, that a pickle carries out of band.
1820
// The view holds its block, so the bytes live as long as this object.
1821
struct FrameBufferObject {
1822
    PyObject_HEAD dataframe::BufferView view;
1823
};
1824

1825
void FrameBuffer_dealloc(PyObject* self) {
11,118 ✔
1826
    reinterpret_cast<FrameBufferObject*>(self)->view.~BufferView();
11,118 ✔
1827
    Py_TYPE(self)->tp_free(self);
11,118 ✔
1828
}
11,118 ✔
1829

1830
int FrameBuffer_getbuffer(PyObject* self, Py_buffer* view, int flags) {
22,390 ✔
1831
    static std::uint8_t empty = 0;
11,379 ✔
1832
    const dataframe::BufferView& v =
33,401 ✔
1833
        reinterpret_cast<FrameBufferObject*>(self)->view;
11,011 ✔
1834
    auto* data = const_cast<std::uint8_t*>(v.data());
22,390 ✔
1835
    return PyBuffer_FillInfo(view, self, data != nullptr ? data : &empty,
22,422 ✔
1836
                             static_cast<Py_ssize_t>(v.size()), 1, flags);
22,390 ✔
1837
}
11,011 ✔
1838

1839
PyBufferProcs FrameBuffer_as_buffer = {FrameBuffer_getbuffer, nullptr};
1840

1841
PyTypeObject FrameBufferType = [] {
1842
    PyTypeObject t{.ob_base = PyVarObject_HEAD_INIT(nullptr, 0)};
1843
    t.tp_name = "dftracer.utils.dftracer_utils_ext._FrameBuffer";
1844
    t.tp_basicsize = sizeof(FrameBufferObject);
1845
    t.tp_dealloc = FrameBuffer_dealloc;
1846
    t.tp_flags = Py_TPFLAGS_DEFAULT;
1847
    t.tp_doc = "One read-only column buffer of a pickled DataFrame.";
1848
    t.tp_as_buffer = &FrameBuffer_as_buffer;
1849
    return t;
1850
}();
1851

1852
PyObject* dataframe_to_buffers(PyObject* /*self*/, PyObject* obj) {
3,678 ✔
1853
    DataFrameObject* b = as_native<DataFrameObject>(obj);
3,678 ✔
1854
    if (!b) return nullptr;
3,678 !
1855
    return guard([&]() -> PyObject* {
5,481 ✔
1856
        const DataFrame frame = to_dataframe(b);
3,678 ✔
1857
        auto out = without_gil(frame.num_rows(), [&] {
9,231 !
1858
            return dataframe::frame_to_buffers(frame);
3,678 !
1859
        });
3,678 !
1860
        if (!out) {
3,678 ✔
UNCOV
1861
            PyErr_SetString(PyExc_TypeError, out.error().c_str());
×
1862
            return nullptr;
1863
        }
1864
        PyObject* header = PyBytes_FromStringAndSize(
5,481 !
1865
            out->header.data(), static_cast<Py_ssize_t>(out->header.size()));
3,678 !
1866
        if (!header) return nullptr;
3,678 !
1867
        PyObject* list =
3,678 ✔
1868
            PyList_New(static_cast<Py_ssize_t>(out->buffers.size()));
3,678 !
1869
        if (!list) {
3,678 !
UNCOV
1870
            Py_DECREF(header);
×
UNCOV
1871
            return nullptr;
×
1872
        }
1873
        for (std::size_t i = 0; i < out->buffers.size(); ++i) {
14,796 !
1874
            auto* item = PyObject_New(FrameBufferObject, &FrameBufferType);
11,118 !
1875
            if (!item) {
11,118 !
UNCOV
1876
                Py_DECREF(header);
×
UNCOV
1877
                Py_DECREF(list);
×
UNCOV
1878
                return nullptr;
×
1879
            }
1880
            new (&item->view) dataframe::BufferView(std::move(out->buffers[i]));
11,118 ✔
1881
            PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i),
11,118 !
1882
                            reinterpret_cast<PyObject*>(item));
1883
        }
5,467 !
1884
        return Py_BuildValue("(NN)", header, list);
3,678 !
1885
    });
3,678 ✔
1886
}
1,803 ✔
1887

1888
struct HeldPyBuffer {
1889
    Py_buffer view;
1890
};
1891

1892
// A received buffer is released when the last column that reads it goes,
1893
// which may be on a thread that does not hold the GIL. After the interpreter
1894
// exits the buffer is left to the process exit.
1895
void release_held_buffer(const void* p) {
11,324 ✔
1896
    dstd::UniquePtr<HeldPyBuffer> held(
16,894 !
1897
        static_cast<HeldPyBuffer*>(const_cast<void*>(p)));
11,324 ✔
1898
    if (PyGILState_Check()) {
11,324 !
1899
        PyBuffer_Release(&held->view);
11,324 !
1900
        return;
5,570 ✔
1901
    }
UNCOV
1902
    if (!python::runtime::enter_python()) {
×
UNCOV
1903
        (void)held.release();
×
UNCOV
1904
        return;
×
1905
    }
UNCOV
1906
    PyGILState_STATE gil = PyGILState_Ensure();
×
UNCOV
1907
    PyBuffer_Release(&held->view);
×
UNCOV
1908
    PyGILState_Release(gil);
×
UNCOV
1909
    python::runtime::leave_python();
×
1910
}
11,324 !
1911

1912
PyObject* dataframe_from_buffers(PyObject* /*self*/, PyObject* args) {
3,686 ✔
1913
    PyObject* header_obj = nullptr;
3,686 ✔
1914
    PyObject* buffers_obj = nullptr;
3,686 ✔
1915
    if (!PyArg_ParseTuple(args, "OO", &header_obj, &buffers_obj))
3,686 !
1916
        return nullptr;
1917
    PyObject* seq = PySequence_Fast(buffers_obj, "buffers must be a sequence");
3,686 ✔
1918
    if (!seq) return nullptr;
3,686 !
1919
    const Py_ssize_t count = PySequence_Fast_GET_SIZE(seq);
3,686 ✔
1920
    dstd::Vector<dataframe::ReceivedBuffer> received;
3,686 ✔
1921
    received.reserve(static_cast<std::size_t>(count));
3,686 !
1922
    for (Py_ssize_t i = 0; i < count; ++i) {
15,010 !
1923
        auto held = dstd::make_unique<HeldPyBuffer>();
11,324 !
1924
        if (PyObject_GetBuffer(PySequence_Fast_GET_ITEM(seq, i), &held->view,
11,324 !
1925
                               PyBUF_SIMPLE) < 0) {
5,570 !
UNCOV
1926
            Py_DECREF(seq);
×
UNCOV
1927
            return nullptr;
×
1928
        }
1929
        const auto* data = static_cast<const std::uint8_t*>(held->view.buf);
11,324 !
1930
        const auto size = static_cast<std::size_t>(held->view.len);
11,324 ✔
1931
        const bool fixed = held->view.readonly != 0;
11,324 ✔
1932
        received.push_back(
11,324 ✔
1933
            {data, size, fixed,
5,570 ✔
1934
             dstd::adopt_shared_ptr(static_cast<const void*>(held.release()),
11,324 !
1935
                                    release_held_buffer)});
1936
    }
11,324 !
1937
    Py_DECREF(seq);
3,686 !
1938
    Py_buffer header;
3,686 ✔
1939
    if (PyObject_GetBuffer(header_obj, &header, PyBUF_SIMPLE) < 0)
3,686 !
1940
        return nullptr;
1941
    auto f = dataframe::frame_from_buffers(
5,493 ✔
1942
        dstd::StringView(static_cast<const char*>(header.buf),
5,493 ✔
1943
                         static_cast<std::size_t>(header.len)),
3,686 ✔
1944
        received);
3,686 !
1945
    PyBuffer_Release(&header);
3,686 !
1946
    if (!f) {
3,686 ✔
1947
        PyErr_SetString(PyExc_ValueError,
8 !
1948
                        "not a DataFrame pickled by this version");
1949
        return nullptr;
4 ✔
1950
    }
1951
    return make_dataframe(std::move(*f));
3,678 !
1952
}
9,440 !
1953

1954
PyObject* DataFrame_get_num_rows(PyObject* self, void*) {
94,650 ✔
1955
    DataFrameObject* b = as_native<DataFrameObject>(self);
94,650 ✔
1956
    if (!b) return nullptr;
94,650 !
1957
    return PyLong_FromLongLong(b->st.length());
94,650 ✔
1958
}
47,325 ✔
UNCOV
1959
PyObject* DataFrame_get_num_columns(PyObject* self, void*) {
×
UNCOV
1960
    DataFrameObject* b = as_native<DataFrameObject>(self);
×
UNCOV
1961
    if (!b) return nullptr;
×
UNCOV
1962
    return PyLong_FromSsize_t(static_cast<Py_ssize_t>(b->names.size()));
×
1963
}
1964
PyObject* DataFrame_get_column_names(PyObject* self, void*) {
53,518 ✔
1965
    return column_name_list(self, false);
53,518 ✔
1966
}
1967

1968
// lazy() -> LazyFrame: start a deferred query over a copy of this batch.
1969
PyObject* DataFrame_lazy(PyObject* self, PyObject*) {
2,861,826 ✔
1970
    DataFrameObject* b = as_native<DataFrameObject>(self);
2,861,826 ✔
1971
    if (!b) return nullptr;
2,861,826 !
1972
    return guard([&] {
4,681,259 ✔
1973
        return dftracer::utils::python::frame::wrap_lazyframe(
2,861,826 !
1974
            dataframe::lazy(to_dataframe(b)));
3,904,219 !
1975
    });
1976
}
1,819,433 ✔
1977

1978
PyMethodDef DataFrame_methods[] = {
1979
    {"lazy", DataFrame_lazy, METH_NOARGS,
1980
     "lazy() -> LazyFrame, a deferred query over this batch."},
1981
    {"keys", DataFrame_keys, METH_NOARGS,
1982
     "Series names, in order; the row index columns are not listed."},
1983
    {"_replace", DataFrame_replace, METH_O,
1984
     "_replace(other) -> None\n\nTake the columns of `other`, in place."},
1985
    {"share", DataFrame_share, METH_NOARGS,
1986
     "share() -> DataFrame\n\nA new DataFrame over the same columns and "
1987
     "index names."},
1988
    {"index_names", DataFrame_index_names, METH_NOARGS,
1989
     "index_names() -> list[str]\n\nThe row index columns, in order; [] "
1990
     "when the frame has no index."},
1991
    {"with_index", DataFrame_with_index, METH_O,
1992
     "with_index(names) -> DataFrame\n\nThe same columns under the row index "
1993
     "`names` ([] drops the index)."},
1994
    {"filter", DataFrame_filter, METH_O,
1995
     "filter(mask) -> DataFrame keeping rows where the Bool mask is true."},
1996
    {"select", DataFrame_select, METH_VARARGS,
1997
     "select(*names) -> DataFrame projecting the named columns (zero-copy)."},
1998
    {"rename", DataFrame_rename, METH_O,
1999
     "rename({old: new}) -> DataFrame with columns renamed (zero-copy)."},
2000
    {"with_column", DataFrame_with_column, METH_VARARGS,
2001
     "with_column(name, Series) -> DataFrame adding/replacing a column."},
2002
    {"_locate", DataFrame_locate, METH_O,
2003
     "_locate(keys) -> (positions, missing): the rows whose index labels equal "
2004
     "the key Series (one per level), and the keys no label matches."},
2005
    {"_locate_range", DataFrame_locate_range, METH_VARARGS,
2006
     "_locate_range(start, stop) -> (offset, length): the rows between two "
2007
     "index label bounds (lists of one-row Series, empty for an open end)."},
2008
    {"_reindex", DataFrame_reindex, METH_VARARGS,
2009
     "_reindex(keys, method, limit, tolerance, fill, nanos=None) -> DataFrame "
2010
     "on the index "
2011
     "label key Series (one per level); method 0 none, 1 pad, 2 backfill, 3 "
2012
     "nearest, limit -1 for none, tolerance infinite for none, fill a one-row "
2013
     "Series or None, nanos a tolerance as whole nanoseconds for temporal "
2014
     "labels."},
2015
    {"_align_rows", DataFrame_align_rows, METH_VARARGS,
2016
     "_align_rows(other, how, fill) -> (left, right): the rows of two frames "
2017
     "on the joined index labels; how is 0 inner, 1 left, 2 right, 3 outer."},
2018
    {"take", DataFrame_take, METH_O,
2019
     "take(indices) -> DataFrame gathered at the given row indices."},
2020
    {"column_index",
2021
     DFTU_PYCFUNCTION((dftracer::utils::python::core::kw_one<
2022
                       "column_index", "name", DataFrame_column_index>)),
2023
     METH_VARARGS | METH_KEYWORDS,
2024
     "column_index(name) -> int index of a column, or -1 if absent."},
2025
    {"head", DataFrame_head, METH_O,
2026
     "head(n) -> DataFrame of the first n rows."},
2027
    {"tail", DataFrame_tail, METH_O,
2028
     "tail(n) -> DataFrame of the last n rows."},
2029
    {"reverse", DataFrame_reverse, METH_NOARGS,
2030
     "reverse() -> DataFrame with rows reversed."},
2031
    {"drop_nulls", DataFrame_drop_nulls, METH_NOARGS,
2032
     "drop_nulls() -> DataFrame dropping rows null in any column."},
2033
    {"fill_null", DataFrame_fill_null, METH_O,
2034
     "fill_null(value) -> DataFrame with nulls filled in every column."},
2035
    {"drop_nans", DataFrame_drop_nans, METH_NOARGS,
2036
     "drop_nans() -> DataFrame dropping rows with a NaN in any float column."},
2037
    {"fill_nan", DFTU_PYCFUNCTION(DataFrame_fill_nan),
2038
     METH_VARARGS | METH_KEYWORDS,
2039
     "fill_nan(value) -> DataFrame with the NaN of every float column "
2040
     "replaced (null for None)."},
2041
    {"unique", DFTU_PYCFUNCTION(DataFrame_unique), METH_VARARGS | METH_KEYWORDS,
2042
     "unique(subset=None) -> DataFrame with duplicate rows removed (keep "
2043
     "first), keyed on every column or on the subset names."},
2044
    {"drop_duplicates", DFTU_PYCFUNCTION(DataFrame_unique),
2045
     METH_VARARGS | METH_KEYWORDS,
2046
     "drop_duplicates(subset=None) -> DataFrame with duplicate rows removed "
2047
     "(alias of unique)."},
2048
    {"sort_by_multi", DFTU_PYCFUNCTION(DataFrame_sort_by_multi),
2049
     METH_VARARGS | METH_KEYWORDS,
2050
     "sort_by_multi(names, descending=False, nulls_last=True) -> DataFrame "
2051
     "stably sorted "
2052
     "lexicographically by several key columns."},
2053
    {"sample", DFTU_PYCFUNCTION(DataFrame_sample), METH_VARARGS | METH_KEYWORDS,
2054
     "sample(n, seed=0) -> DataFrame deterministic n-row sample."},
2055
    {"with_row_index", DataFrame_with_row_index, METH_O,
2056
     "with_row_index(name) -> DataFrame with a prepended Int64 index column."},
2057
    {"describe", DataFrame_describe, METH_NOARGS,
2058
     "describe() -> DataFrame of per-column summary statistics."},
2059
    {"null_count", DataFrame_null_count, METH_NOARGS,
2060
     "null_count() -> 1-row DataFrame of each column's null count."},
2061
    {"reduce", DataFrame_reduce, METH_O,
2062
     "reduce(agg) -> one-row DataFrame: the aggregate named `agg` over every "
2063
     "eligible column."},
2064
    {"_group_transform", DFTU_PYCFUNCTION(DataFrame_group_transform),
2065
     METH_VARARGS | METH_KEYWORDS,
2066
     "_group_transform(keys, kind, n=0, method='average', ascending=True) -> "
2067
     "DataFrame: the group-wise transform `kind` (cumsum, cummax, cummin, "
2068
     "cumcount, shift, diff, pct_change, rank, ngroup, head, tail, nth) over "
2069
     "the groups of `keys`, one value per input row in input order."},
2070
    {"_reduce_specs", DataFrame_reduce_specs, METH_VARARGS,
2071
     "_reduce_specs(agg, keys=None) -> list[str]: the 'op:column:out' specs "
2072
     "that broadcast `agg` over every eligible non-key column, for group_by."},
2073
    {"is_duplicated", DataFrame_is_duplicated, METH_NOARGS,
2074
     "is_duplicated() -> Bool Series, true where the whole row is duplicated."},
2075
    {"is_unique", DataFrame_is_unique, METH_NOARGS,
2076
     "is_unique() -> Bool Series, true where the whole row is unique."},
2077
    {"slice", DataFrame_slice, METH_VARARGS,
2078
     "slice(offset, length) -> DataFrame of a row range."},
2079
    {"sort_by", DFTU_PYCFUNCTION(DataFrame_sort_by),
2080
     METH_VARARGS | METH_KEYWORDS,
2081
     "sort_by(name, descending=False, nulls_last=True) -> DataFrame ordered "
2082
     "by a column."},
2083
    {"topk", DFTU_PYCFUNCTION(DataFrame_topk), METH_VARARGS | METH_KEYWORDS,
2084
     "topk(name, k, largest=True) -> DataFrame of the k best rows by a "
2085
     "column."},
2086
    {"concat", DFTU_PYCFUNCTION(DataFrame_concat), METH_VARARGS | METH_KEYWORDS,
2087
     "concat(*others, how='vertical') -> DataFrame concatenating batches. "
2088
     "how='diagonal' unions columns (null-fill absent, promote numeric)."},
2089
    {"unpivot", DFTU_PYCFUNCTION(DataFrame_unpivot),
2090
     METH_VARARGS | METH_KEYWORDS,
2091
     "unpivot(id_vars, value_vars) -> DataFrame reshaped wide->long, stacking "
2092
     "value_vars into 'variable'/'value' columns."},
2093
    {"melt", DFTU_PYCFUNCTION(DataFrame_unpivot), METH_VARARGS | METH_KEYWORDS,
2094
     "melt(id_vars, value_vars) -> DataFrame (alias of unpivot)."},
2095
    {"explode", DataFrame_explode, METH_O,
2096
     "explode(column) -> DataFrame expanding a List column, one row per "
2097
     "element (empty/null list -> one null row)."},
2098
    {"window", DFTU_PYCFUNCTION(DataFrame_window), METH_VARARGS | METH_KEYWORDS,
2099
     "window(partition_by, order_by, specs) -> DataFrame: SQL window "
2100
     "functions; specs are normalized 12-tuples."},
2101
    {"gap_fill", DFTU_PYCFUNCTION(DataFrame_gap_fill),
2102
     METH_VARARGS | METH_KEYWORDS,
2103
     "gap_fill(partition_by, time, bucket, values, mode, start=None, "
2104
     "end=None) -> DataFrame: a regular time grid with none/locf/linear "
2105
     "fills."},
2106
    {"asof", DFTU_PYCFUNCTION(DataFrame_asof), METH_VARARGS | METH_KEYWORDS,
2107
     "asof(other, on, by, direction, tolerance) -> DataFrame: temporal "
2108
     "nearest-match join."},
2109
    {"interval", DFTU_PYCFUNCTION(DataFrame_interval),
2110
     METH_VARARGS | METH_KEYWORDS,
2111
     "interval(other, point, lo, hi, by, outer) -> DataFrame: point-in-range "
2112
     "join."},
2113
    {"unnest", DFTU_PYCFUNCTION(DataFrame_unnest), METH_VARARGS | METH_KEYWORDS,
2114
     "unnest(column, keep_empty=False) -> DataFrame expanding a List column "
2115
     "one row per element; an empty/null list drops the row unless "
2116
     "keep_empty, and a List<Struct> flattens into one column per field."},
2117
    {"to_dummies", DataFrame_to_dummies, METH_O,
2118
     "to_dummies(column) -> DataFrame one-hot encoding a column into one Int8 "
2119
     "column per distinct value, named <column>_<value>."},
2120
    {"pivot", DFTU_PYCFUNCTION(DataFrame_pivot), METH_VARARGS | METH_KEYWORDS,
2121
     "pivot(index, columns, values, agg='first') -> DataFrame reshaping "
2122
     "long->wide; agg is first|last|sum|min|max|mean."},
2123
    {"group_by_dynamic", DFTU_PYCFUNCTION(DataFrame_group_by_dynamic),
2124
     METH_VARARGS | METH_KEYWORDS,
2125
     "group_by_dynamic(time_col, every, period=None, aggs=[...]) -> DataFrame "
2126
     "tumbling/sliding time-window aggregation; aggs are 'count' / "
2127
     "'<op>:<column>'."},
2128
    {"query", DFTU_PYCFUNCTION(DataFrame_query), METH_VARARGS | METH_KEYWORDS,
2129
     "query(dsl=None, *, group_by=None, aggs=None, select=None, order_by=None, "
2130
     "descending=False, limit=None) -> DataFrame; a query plan "
2131
     "(filter/group-by/select/sort/limit) over the batch. The DSL predicate is "
2132
     "evaluated as a SIMD mask (pandas.query-style); aggs are 'count' or "
2133
     "'<op>:<column>'."},
2134
    {"group_by", DataFrame_group_by, METH_VARARGS,
2135
     "group_by(key, *aggs) -> DataFrame or GroupBy; aggs are 'count', "
2136
     "'<op>:<column>' (sum|min|max|mean|var|std|skew|kurt), or aggregate "
2137
     "expressions (F.x.sum(), ...); no aggs returns a GroupBy for .agg(...)."},
2138
    {"_group_agg_expr", DataFrame_group_agg_expr, METH_VARARGS,
2139
     "_group_agg_expr(key, specs) -> DataFrame; specs is a list of "
2140
     "(op_int, value_ast|None, out_name[, param[, by_ast[, udaf[, interp]]]]). "
2141
     "Internal: the "
2142
     "GroupBy expression path (CSE across value expressions + pruner)."},
2143
    {"join", DFTU_PYCFUNCTION(DataFrame_join), METH_VARARGS | METH_KEYWORDS,
2144
     "join(other, on=None, how='inner', left_on=None, right_on=None, "
2145
     "suffix='_right') -> DataFrame hash-joined on the key columns; "
2146
     "how=inner|left|right|outer|full|semi|anti|cross."},
2147
    {"compare_agg", DataFrame_compare_agg, METH_VARARGS,
2148
     "compare_agg(variant, n_key) -> DataFrame: FULL-join two aggregation "
2149
     "results on the first n_key group-key columns and append delta_/pct_ per "
2150
     "numeric metric (the CompareView result)."},
2151
    {"partition_id",
2152
     DFTU_PYCFUNCTION(
2153
         (dftracer::utils::python::core::kw_pair<
2154
             "partition_id", DataFrame_partition_id, "keys", "n_parts">)),
2155
     METH_VARARGS | METH_KEYWORDS,
2156
     "partition_id(keys, n_parts) -> Int32 Series: the part in [0, n_parts) "
2157
     "each row lands in under a stable hash of the key columns."},
2158
    {"hash_partition", DataFrame_hash_partition, METH_VARARGS,
2159
     "hash_partition(keys, n_parts) -> list[DataFrame] partitioned by a stable "
2160
     "hash of the key columns (the distributed shuffle primitive)."},
2161
    {"__arrow_c_array__", DataFrame_arrow_c_array, METH_VARARGS,
2162
     "Arrow PyCapsule export of the struct: (schema_capsule, array_capsule)."},
2163
    {"__arrow_c_stream__", DFTU_PYCFUNCTION(DataFrame_arrow_c_stream),
2164
     METH_VARARGS | METH_KEYWORDS,
2165
     "Arrow PyCapsule stream export (one struct batch); pa.table(batch) uses "
2166
     "this to import every column zero-copy."},
2167
    {"to_ipc", DataFrame_to_ipc, METH_NOARGS,
2168
     "to_ipc() -> bytes: the frame as an Arrow IPC stream (schema + one record "
2169
     "batch + EOS); no pyarrow needed to produce .arrow bytes."},
2170
    {"to_bytes", DataFrame_to_bytes, METH_NOARGS,
2171
     "to_bytes() -> bytes: the frame in the native frame format."},
2172
    {nullptr, nullptr, 0, nullptr}};
2173

2174
PyGetSetDef DataFrame_getset[] = {
2175
    {"num_rows", DataFrame_get_num_rows, nullptr, "Row count.", nullptr},
2176
    {"num_columns", DataFrame_get_num_columns, nullptr, "Series count.",
2177
     nullptr},
2178
    {"column_names", DataFrame_get_column_names, nullptr, "Series names.",
2179
     nullptr},
2180
    {nullptr, nullptr, nullptr, nullptr, nullptr}};
2181

2182
PyMappingMethods DataFrame_as_mapping = {};
2183
PySequenceMethods DataFrame_as_sequence = {};
2184

2185
// Whether field `i` of `obj`'s schema carries the `arrow.json` extension in
2186
// its metadata. A pyarrow without the registered extension type (before 18)
2187
// keeps the name only there, and an Array's own export has no field metadata.
2188
bool field_is_json(PyObject* obj, Py_ssize_t i) {
×
2189
    PyObject* schema = PyObject_GetAttrString(obj, "schema");
×
2190
    if (!schema) {
×
UNCOV
2191
        PyErr_Clear();
×
UNCOV
2192
        return false;
×
2193
    }
UNCOV
2194
    PyObject* field = PyObject_CallMethod(schema, "field", "n", i);
×
UNCOV
2195
    Py_DECREF(schema);
×
UNCOV
2196
    if (!field) {
×
UNCOV
2197
        PyErr_Clear();
×
UNCOV
2198
        return false;
×
2199
    }
UNCOV
2200
    PyObject* md = PyObject_GetAttrString(field, "metadata");
×
UNCOV
2201
    Py_DECREF(field);
×
UNCOV
2202
    if (!md) {
×
UNCOV
2203
        PyErr_Clear();
×
UNCOV
2204
        return false;
×
2205
    }
UNCOV
2206
    bool json = false;
×
UNCOV
2207
    if (PyDict_Check(md)) {
×
2208
        // pyarrow keys the metadata dict by bytes.
UNCOV
2209
        PyObject* key = PyBytes_FromString("ARROW:extension:name");
×
UNCOV
2210
        PyObject* name = key ? PyDict_GetItem(md, key) : nullptr;
×
UNCOV
2211
        json = name && PyBytes_Check(name) &&
×
UNCOV
2212
               std::strcmp(PyBytes_AsString(name), "arrow.json") == 0;
×
UNCOV
2213
        Py_XDECREF(key);
×
2214
    }
UNCOV
2215
    Py_DECREF(md);
×
2216
    return json;
2217
}
2218

2219
// A provider of __arrow_c_stream__ (a pyarrow Table or RecordBatchReader, a
2220
// polars frame): one chunk per batch, nothing joined or copied.
2221
PyObject* frame_from_arrow_stream(PyObject* obj) {
1,214 ✔
2222
    PyObject* cap = PyObject_CallMethod(obj, "__arrow_c_stream__", nullptr);
1,214 ✔
2223
    if (!cap) return nullptr;
1,214 !
2224
    auto* stream = static_cast<ArrowArrayStream*>(
1,821 ✔
2225
        PyCapsule_GetPointer(cap, "arrow_array_stream"));
1,214 ✔
2226
    if (!stream) {
1,214 ✔
NEW
2227
        Py_DECREF(cap);
×
NEW
2228
        return nullptr;
×
2229
    }
2230
    auto moved = dftracer::utils::dstd::make_unique<ArrowArrayStream>(*stream);
1,214 ✔
2231
    stream->release = nullptr;
1,214 ✔
2232
    Py_DECREF(cap);
1,214 !
2233
    auto imported =
1,214 !
2234
        dftracer::utils::arrow::dataframe_from_arrow_stream(moved.get());
1,214 !
2235
    if (!imported) {
1,214 ✔
2236
        dftracer::utils::python::core::set_py_error(imported.error());
2 !
2237
        return nullptr;
1 ✔
2238
    }
2239
    return make_dataframe(std::move(*imported));
1,212 !
2240
}
1,214 ✔
2241

2242
// vec_batch_from_arrow(table) -> DataFrame: import an Arrow table into vec
2243
// with no copy. Used to reconstruct a pickled DataFrame and to lift Arrow into
2244
// the native format.
2245
PyObject* vec_batch_from_arrow(PyObject* /*self*/, PyObject* obj) {
1,214 ✔
2246
    if (PyObject_HasAttrString(obj, "__arrow_c_stream__"))
1,214 !
2247
        return frame_from_arrow_stream(obj);
1,214 ✔
UNCOV
2248
    PyObject* names = PyObject_GetAttrString(obj, "column_names");
×
UNCOV
2249
    if (!names) return nullptr;
×
UNCOV
2250
    Py_ssize_t n = PySequence_Size(names);
×
UNCOV
2251
    if (n < 0) {
×
UNCOV
2252
        Py_DECREF(names);
×
UNCOV
2253
        return nullptr;
×
2254
    }
2255
    DataFrame b;
×
UNCOV
2256
    for (Py_ssize_t i = 0; i < n; ++i) {
×
UNCOV
2257
        PyObject* nm = PySequence_GetItem(names, i);
×
UNCOV
2258
        const char* s = nm ? PyUnicode_AsUTF8(nm) : nullptr;
×
UNCOV
2259
        PyObject* ca = s ? PyObject_CallMethod(obj, "column", "n", i) : nullptr;
×
NEW
2260
        Series col = ca ? dftracer::utils::python::frame::column_from_arrow(ca)
×
NEW
2261
                        : Series{};
×
UNCOV
2262
        Py_XDECREF(ca);
×
UNCOV
2263
        if (col.valid() && !col.is_json() &&
×
UNCOV
2264
            col.type() == dftracer::utils::dataframe::TypeId::String &&
×
UNCOV
2265
            field_is_json(obj, i))
×
UNCOV
2266
            col = col.as_json();
×
UNCOV
2267
        if (!col.valid()) {
×
UNCOV
2268
            Py_XDECREF(nm);
×
UNCOV
2269
            Py_DECREF(names);
×
UNCOV
2270
            return nullptr;
×
2271
        }
UNCOV
2272
        b.names.emplace_back(s);
×
UNCOV
2273
        b.columns.push_back(std::move(col));
×
UNCOV
2274
        Py_DECREF(nm);
×
UNCOV
2275
    }
×
UNCOV
2276
    Py_DECREF(names);
×
UNCOV
2277
    return make_dataframe(std::move(b));
×
2278
}
607 ✔
2279

2280
// _dataframe_from_columns(names, series) -> DataFrame: a frame of native
2281
// Series, no Arrow involved.
2282
PyObject* dataframe_from_columns(PyObject* /*self*/, PyObject* args) {
55,128 ✔
2283
    PyObject* names_obj = nullptr;
55,128 ✔
2284
    PyObject* series_obj = nullptr;
55,128 ✔
2285
    if (!PyArg_ParseTuple(args, "OO", &names_obj, &series_obj)) return nullptr;
55,128 !
2286
    dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> names;
55,128 ✔
2287
    if (!parse_string_seq(names_obj, "names must be strings", names))
55,128 !
2288
        return nullptr;
2289
    dftracer::utils::dstd::Vector<Series> cols;
55,128 ✔
2290
    if (!parse_seq<Series>(
55,128 !
2291
            series_obj, "series must be a sequence", cols,
27,564 ✔
2292
            [](PyObject* item, dftracer::utils::dstd::Vector<Series>& o) {
141,388 ✔
2293
                const Series* col =
212,082 ✔
2294
                    dftracer::utils::python::frame::unwrap_vec_column(item);
141,388 ✔
2295
                if (!col) {
141,388 ✔
UNCOV
2296
                    PyErr_SetString(PyExc_TypeError, "expected native Series");
×
UNCOV
2297
                    return false;
×
2298
                }
2299
                o.push_back(col->share());
141,388 !
2300
                return true;
141,388 ✔
2301
            }))
70,694 ✔
2302
        return nullptr;
2303
    if (cols.size() != names.size()) {
55,128 !
UNCOV
2304
        PyErr_SetString(PyExc_ValueError, "names and series differ in length");
×
2305
        return nullptr;
2306
    }
2307
    DataFrame b;
55,128 ✔
2308
    for (std::size_t i = 0; i < cols.size(); ++i) {
196,516 ✔
2309
        b.names.push_back(dstd::SharedString{names[i]});
141,388 !
2310
        b.columns.push_back(std::move(cols[i]));
141,388 ✔
2311
    }
70,694 ✔
2312
    if (!b.columns.empty()) {
55,128 ✔
2313
        const std::int64_t rows = b.columns.front().length();
55,124 ✔
2314
        for (const Series& c : b.columns)
196,512 !
2315
            if (c.length() != rows) {
141,388 !
UNCOV
2316
                PyErr_SetString(PyExc_ValueError, "columns differ in length");
×
UNCOV
2317
                return nullptr;
×
2318
            }
70,694 !
2319
    }
27,562 !
2320
    return make_dataframe(std::move(b));
55,128 !
2321
}
55,128 ✔
2322

2323
}  // namespace
2324

2325
namespace dftracer::utils::python::frame {
2326

2327
TypeBinding dataframe_binding() {
884 ✔
2328
    return {"DataFrame", &DataFrameType, &g_dataframe_type};
884 ✔
2329
}
2330

2331
PyObject* wrap_dataframe(dftracer::utils::dataframe::DataFrame&& batch) {
130,169 ✔
2332
    return make_dataframe(std::move(batch));
130,169 ✔
2333
}
2334

UNCOV
2335
bool unwrap_dataframe(PyObject* obj,
×
2336
                      dftracer::utils::dataframe::DataFrame& out) {
UNCOV
2337
    const DataFrameObject* self =
×
UNCOV
2338
        dftracer::utils::python::core::as_native<DataFrameObject>(obj);
×
UNCOV
2339
    if (!self) return false;
×
UNCOV
2340
    out = to_dataframe(self);
×
UNCOV
2341
    return true;
×
2342
}
2343

2344
int init_dataframe(PyObject* m) {
218 ✔
2345
    DataFrame_as_mapping.mp_subscript = DataFrame_subscript;
218 ✔
2346
    DataFrame_as_sequence.sq_contains = DataFrame_contains;
218 ✔
2347
    DataFrameType = {};
218 ✔
2348
    DataFrameType.ob_base = {PyObject_HEAD_INIT(nullptr) 0};
218 ✔
2349
    DataFrameType.tp_name = "dftracer.utils.dftracer_utils_ext.DataFrame";
218 ✔
2350
    DataFrameType.tp_basicsize = sizeof(DataFrameObject);
218 ✔
2351
    DataFrameType.tp_weaklistoffset = WEAKLIST_OFFSET;
218 ✔
2352
    DataFrameType.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
218 ✔
2353
    DataFrameType.tp_doc =
218 ✔
2354
        "A native vec batch (named vec columns; Arrow only at the edge).";
2355
    DataFrameType.tp_dealloc = reinterpret_cast<destructor>(DataFrame_dealloc);
218 ✔
2356
    DataFrameType.tp_as_mapping = &DataFrame_as_mapping;
218 ✔
2357
    DataFrameType.tp_as_sequence = &DataFrame_as_sequence;
218 ✔
2358
    DataFrameType.tp_methods = DataFrame_methods;
218 ✔
2359
    DataFrameType.tp_getset = DataFrame_getset;
218 ✔
2360
    DataFrameType.tp_new = nullptr;  // created only by a trace view
218 ✔
2361
    if (register_type(m, &DataFrameType, "DataFrame") < 0) return -1;
218 !
2362

2363
    static PyMethodDef from_arrow_def = {
109 ✔
2364
        "_dataframe_from_arrow", vec_batch_from_arrow, METH_O,
2365
        "vec_batch_from_arrow(table) -> DataFrame: import a pyarrow Table's "
2366
        "columns into a native vec batch."};
2367
    PyObject* fn = PyCFunction_NewEx(&from_arrow_def, nullptr, nullptr);
218 ✔
2368
    if (!fn) return -1;
218 !
2369
    if (PyModule_AddObject(m, "_dataframe_from_arrow", fn) < 0) {
218 ✔
UNCOV
2370
        Py_DECREF(fn);
×
UNCOV
2371
        return -1;
×
2372
    }
2373
    static PyMethodDef from_columns_def = {
109 ✔
2374
        "_dataframe_from_columns", dataframe_from_columns, METH_VARARGS,
2375
        "_dataframe_from_columns(names, series) -> DataFrame of native "
2376
        "Series."};
2377
    PyObject* cols_fn = PyCFunction_NewEx(&from_columns_def, nullptr, nullptr);
218 ✔
2378
    if (!cols_fn) return -1;
218 !
2379
    if (PyModule_AddObject(m, "_dataframe_from_columns", cols_fn) < 0) {
218 ✔
UNCOV
2380
        Py_DECREF(cols_fn);
×
UNCOV
2381
        return -1;
×
2382
    }
2383
    static PyMethodDef from_bytes_def = {
109 ✔
2384
        "_dataframe_from_bytes", dataframe_from_bytes, METH_O,
2385
        "_dataframe_from_bytes(bytes) -> DataFrame written by "
2386
        "DataFrame.to_bytes."};
2387
    PyObject* bytes_fn = PyCFunction_NewEx(&from_bytes_def, nullptr, nullptr);
218 ✔
2388
    if (!bytes_fn) return -1;
218 !
2389
    if (PyModule_AddObject(m, "_dataframe_from_bytes", bytes_fn) < 0) {
218 ✔
UNCOV
2390
        Py_DECREF(bytes_fn);
×
UNCOV
2391
        return -1;
×
2392
    }
2393
    if (register_type(m, &FrameBufferType, "_FrameBuffer") < 0) return -1;
218 !
2394
    static PyMethodDef to_buffers_def = {
109 ✔
2395
        "_dataframe_to_buffers", dataframe_to_buffers, METH_O,
2396
        "_dataframe_to_buffers(frame) -> (header, buffers): the frame as a "
2397
        "header and read-only column buffers, with no copy."};
2398
    PyObject* to_buffers_fn =
327 ✔
2399
        PyCFunction_NewEx(&to_buffers_def, nullptr, nullptr);
218 ✔
2400
    if (!to_buffers_fn) return -1;
218 !
2401
    if (PyModule_AddObject(m, "_dataframe_to_buffers", to_buffers_fn) < 0) {
218 ✔
UNCOV
2402
        Py_DECREF(to_buffers_fn);
×
UNCOV
2403
        return -1;
×
2404
    }
2405
    static PyMethodDef from_buffers_def = {
109 ✔
2406
        "_dataframe_from_buffers", dataframe_from_buffers, METH_VARARGS,
2407
        "_dataframe_from_buffers(header, buffers) -> DataFrame that reads the "
2408
        "buffers in place and keeps them alive."};
2409
    PyObject* from_buffers_fn =
327 ✔
2410
        PyCFunction_NewEx(&from_buffers_def, nullptr, nullptr);
218 ✔
2411
    if (!from_buffers_fn) return -1;
218 !
2412
    if (PyModule_AddObject(m, "_dataframe_from_buffers", from_buffers_fn) < 0) {
218 ✔
UNCOV
2413
        Py_DECREF(from_buffers_fn);
×
UNCOV
2414
        return -1;
×
2415
    }
2416
    return 0;
109 ✔
2417
}
109 ✔
2418

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