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

llnl-asr / dftracer-utils / 45996541911

27 Nov 2026 12:11PM UTC coverage: 77.548% (-0.04%) from 77.591%
45996541911

push

github

rayandrew
test(trace): bound the scan alone in the small-unit budget test

The memory budget bounds the scan, not the frame that collect returns,
so the test measured memory the budget never promised to bound. A filter
that the scan applies and that matches no row leaves the scan alone.

166775 of 258053 branches covered (64.63%)

Branch coverage included in aggregate %.

192744 of 205558 relevant lines covered (93.77%)

4613634.78 hits per line

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

63.76
/src/dftracer/utils/python/frame/columnar_eval.cpp
1
// SPDX-License-Identifier: MIT
2
// Binding for the native columnar expression engine. Python serializes its
3
// expression tree to a flat post-order AST; this rebuilds it as a
4
// dataframe::Expr and evaluates it - all the compiler work (type inference,
5
// CSE, lowering, fused chunked + parallel evaluation) lives in vec, so C/C++
6
// consumers get the same engine. This TU also installs the runtime-backed
7
// parallel backend so vec's parallelism seam fans out across the coroutine
8
// pool.
9

10
#include <dftracer/utils/common/config.h>
11
#include <dftracer/utils/dataframe/c_api.h>
12
#include <dftracer/utils/dataframe/dataframe.h>
13
#include <dftracer/utils/dataframe/expr.h>
14
#include <dftracer/utils/dataframe/parallel.h>
15
#include <dftracer/utils/dataframe/udaf_registry.h>
16
#include <dftracer/utils/dataframe/udf.h>
17
#include <dftracer/utils/dataframe/udf_registry.h>
18
#include <dftracer/utils/dstd/fatal.h>
19
#include <dftracer/utils/dstd/memory.h>
20
#include <dftracer/utils/dstd/string.h>
21
#include <dftracer/utils/dstd/vector.h>
22
#include <dftracer/utils/python/core/call.h>
23
#include <dftracer/utils/python/core/method.h>
24
#include <dftracer/utils/python/core/scalar_helpers.h>
25
#include <dftracer/utils/python/core/seq_helpers.h>
26
#include <dftracer/utils/python/frame/columnar_eval.h>
27
#include <dftracer/utils/python/frame/series.h>
28
#include <dftracer/utils/runtime/runtime.h>
29

30
#include <cstdint>
31
#include <utility>
32

33
using dftracer::utils::python::core::release_gil;
34

35
using namespace dftracer::utils;
36

37
namespace {
38

39
// AST node opcodes (mirror the serializer in expr.py).
40
enum {
41
    AstCol = 0,
42
    AstLitI = 1,
43
    AstLitF = 2,
44
    AstBin = 3,
45
    AstPrim = 4,
46
    AstCmp = 5,
47
    AstLogical = 6,
48
    AstNot = 7,
49
    AstCast = 8,
50
    AstUnary = 9,
51
    AstClip = 10,
52
    AstFillna = 11,
53
    AstStrPred = 12,
54
    AstStrMap = 13,
55
    AstStrLen = 14,
56
    AstStrFind = 15,
57
    AstStrReplace = 16,
58
    AstStrSlice = 17,
59
    AstIsIn = 18,
60
    AstSelect = 19,
61
    AstIsNull = 20,
62
    AstCmpExpr = 21,
63
    AstStrFn = 22,  // (fn, text, text2, i0, i1, operand count)
64
    AstStrPredCol = 23,
65
    AstStrReplaceCol = 24,
66
    AstLitS = 25,
67
    AstUdf = 26,  // (udf capsule, operand count)
68
};
69

70
const char* const UDF_CAPSULE = "dftu.udf";
71

72
void free_udf_capsule(PyObject* capsule) {
100 ✔
73
    dftracer::utils::dstd::UniquePtr<dataframe::Udf> owner(
150 ✔
74
        static_cast<dataframe::Udf*>(
75
            PyCapsule_GetPointer(capsule, UDF_CAPSULE)));
100 ✔
76
}
100 ✔
77

78
const char* const UDAF_CAPSULE = "dftu.udaf";
79

80
using UdafHold = dftracer::utils::dstd::SharedPtr<const dataframe::UdafRecord>;
81

82
void free_udaf_capsule(PyObject* capsule) {
×
83
    dftracer::utils::dstd::UniquePtr<UdafHold> owner(
×
84
        static_cast<UdafHold*>(PyCapsule_GetPointer(capsule, UDAF_CAPSULE)));
×
85
}
×
86

87
// A borrowed view of a Python str; valid while `o` lives, which the ast list
88
// guarantees for the duration of build_expr.
89
bool py_str_view(PyObject* o, dftracer::utils::dstd::StringView* out) {
2,302 ✔
90
    Py_ssize_t n = 0;
2,302 ✔
91
    const char* s = PyUnicode_AsUTF8AndSize(o, &n);
2,302 ✔
92
    if (!s) return false;
2,302 !
93
    *out = dftracer::utils::dstd::StringView(s, static_cast<std::size_t>(n));
2,302 ✔
94
    return true;
2,302 ✔
95
}
1,151 ✔
96

97
// The is_in value list as a Series: all strs (String); otherwise numbers,
98
// where a bool is 0 or 1. Ints alone are Int64, or Uint64 when one is above
99
// the int64 range; a float among them makes Float64. An empty list is an
100
// empty Int64, which matches nothing.
101
bool py_values_series(PyObject* list, dataframe::Series* out) {
726 ✔
102
    dftracer::utils::python::core::FastSeq items;
726 ✔
103
    if (!items.open(list, "is_in values must be a sequence")) return false;
726 !
104
    const auto n = static_cast<std::size_t>(items.size());
726 !
105
    bool all_str = n > 0;
726 ✔
106
    bool any_str = false;
726 ✔
107
    bool any_float = false;
726 ✔
108
    for (Py_ssize_t i = 0; i < items.size(); ++i) {
3,076 !
109
        PyObject* v = items.item(i);
2,350 !
110
        const bool str = PyUnicode_Check(v);
2,350 !
111
        all_str = all_str && str;
2,350 ✔
112
        any_str = any_str || str;
2,350 ✔
113
        if (PyFloat_Check(v)) {
2,350 !
114
            any_float = true;
4 ✔
115
        } else if (!str && !PyLong_Check(v)) {
2,346 !
116
            PyErr_SetString(PyExc_TypeError,
×
117
                            "is_in values must be strings, numbers or bools");
118
            return false;
119
        }
120
    }
1,175 !
121
    if (all_str) {
726 ✔
122
        dftracer::utils::dstd::Vector<dftracer::utils::dstd::String> values;
326 ✔
123
        values.reserve(n);
326 !
124
        for (Py_ssize_t i = 0; i < items.size(); ++i) {
1,270 !
125
            dftracer::utils::dstd::StringView s;
944 ✔
126
            if (!py_str_view(items.item(i), &s)) return false;
944 !
127
            values.emplace_back(s);
944 !
128
        }
472 !
129
        *out = dataframe::Series::strings(values);
326 !
130
        return true;
326 ✔
131
    }
326 ✔
132
    if (any_str) {
400 !
133
        PyErr_SetString(PyExc_TypeError,
×
134
                        "is_in values must be all strings or all numbers");
135
        return false;
136
    }
137
    if (any_float) {
400 ✔
138
        dftracer::utils::dstd::Vector<double> values;
6 ✔
139
        values.reserve(n);
6 !
140
        for (Py_ssize_t i = 0; i < items.size(); ++i) {
16 !
141
            values.push_back(PyFloat_AsDouble(items.item(i)));
10 !
142
            if (PyErr_Occurred()) return false;
10 !
143
        }
5 ✔
144
        *out = dataframe::Series::flat_f64(values.data(),
9 !
145
                                           static_cast<std::int64_t>(n));
6 !
146
        return true;
6 ✔
147
    }
6 ✔
148
    dftracer::utils::dstd::Vector<std::int64_t> values;
394 ✔
149
    values.reserve(n);
394 !
150
    bool wide = false;
197 ✔
151
    for (Py_ssize_t i = 0; i < items.size() && !wide; ++i) {
1,790 !
152
        int overflow = 0;
1,396 ✔
153
        const long long x =
2,094 ✔
154
            PyLong_AsLongLongAndOverflow(items.item(i), &overflow);
1,396 !
155
        if (overflow < 0) {
1,396 !
156
            PyErr_SetString(PyExc_OverflowError,
×
157
                            "is_in value is below the int64 range");
158
            return false;
×
159
        }
160
        if (overflow > 0) wide = true;
1,396 ✔
161
        if (x == -1 && PyErr_Occurred()) return false;
1,396 !
162
        values.push_back(static_cast<std::int64_t>(x));
1,396 !
163
    }
698 !
164
    if (!wide) {
394 ✔
165
        *out = dataframe::Series::flat_i64(values.data(),
585 !
166
                                           static_cast<std::int64_t>(n));
390 !
167
        return true;
390 ✔
168
    }
169
    dftracer::utils::dstd::Vector<std::uint64_t> unsigned_values;
4 ✔
170
    unsigned_values.reserve(n);
4 !
171
    for (Py_ssize_t i = 0; i < items.size(); ++i) {
7 ✔
172
        const unsigned long long x = PyLong_AsUnsignedLongLong(items.item(i));
4 !
173
        if (PyErr_Occurred()) {
4 !
174
            PyErr_Clear();
2 !
175
            PyErr_SetString(PyExc_OverflowError,
2 !
176
                            "is_in values mix negative ints and ints above "
177
                            "the int64 range, or one is above the uint64 "
178
                            "range");
179
            return false;
1 ✔
180
        }
181
        unsigned_values.push_back(static_cast<std::uint64_t>(x));
2 !
182
    }
2 ✔
183
    *out = dataframe::Series::flat(dataframe::TypeId::Uint64,
3 !
184
                                   unsigned_values.data(),
2 !
185
                                   static_cast<std::int64_t>(n));
2 !
186
    return true;
2 ✔
187
}
923 ✔
188

189
// Rebuild a dataframe::Expr from a post-order list of (op, arg0[, arg1])
190
// tuples.
191
bool build_expr(PyObject* ast, dataframe::Expr* out) {
8,748 ✔
192
    if (!PyList_Check(ast)) {
8,748 ✔
193
        PyErr_SetString(PyExc_TypeError, "ast must be a list");
×
194
        return false;
×
195
    }
196
    dftracer::utils::dstd::Vector<dataframe::Expr> stack;
8,748 ✔
197
    Py_ssize_t n = PyList_GET_SIZE(ast);
8,748 !
198
    for (Py_ssize_t k = 0; k < n; ++k) {
35,405 ✔
199
        PyObject* t = PyList_GET_ITEM(ast, k);
18,038 !
200
        if (!PyTuple_Check(t) || PyTuple_GET_SIZE(t) < 1) {
18,038 !
201
            PyErr_SetString(PyExc_TypeError, "each ast node is a tuple");
×
202
            return false;
1 ✔
203
        }
204
        int op = static_cast<int>(PyLong_AsLong(PyTuple_GET_ITEM(t, 0)));
18,038 !
205
        auto arg = [&](int i) { return PyTuple_GET_ITEM(t, i); };
31,595 ✔
206
        auto pop = [&]() {
27,162 ✔
207
            dataframe::Expr e = std::move(stack.back());
9,124 ✔
208
            stack.pop_back();
9,124 !
209
            return e;
9,124 ✔
210
        };
13,581 !
211
        switch (op) {
18,038 ✔
212
            case AstCol:
4,731 ✔
213
                stack.push_back(dataframe::expr_col(
18,924 !
214
                    static_cast<std::int32_t>(PyLong_AsLong(arg(1)))));
9,462 !
215
                break;
9,462 ✔
216
            case AstLitI:
837 ✔
217
                stack.push_back(dataframe::expr_lit(
3,348 !
218
                    static_cast<std::int64_t>(PyLong_AsLongLong(arg(1)))));
1,674 !
219
                break;
1,674 ✔
220
            case AstLitF:
14 ✔
221
                stack.push_back(dataframe::expr_lit(PyFloat_AsDouble(arg(1))));
42 !
222
                break;
28 ✔
223
            case AstLitS: {
5 ✔
224
                dftracer::utils::dstd::StringView v;
10 ✔
225
                if (!py_str_view(arg(1), &v)) return false;
10 !
226
                stack.push_back(dataframe::expr_lit_str(v));
15 !
227
                break;
10 ✔
228
            }
5 ✔
229
            case AstUdf: {
63 ✔
230
                auto* udf = static_cast<dataframe::Udf*>(
189 ✔
231
                    PyCapsule_GetPointer(arg(1), UDF_CAPSULE));
126 !
232
                if (!udf) return false;
126 ✔
233
                const long count = PyLong_AsLong(arg(2));
126 !
234
                if (count < 0 ||
126 !
235
                    static_cast<std::size_t>(count) > stack.size()) {
126 !
236
                    PyErr_SetString(PyExc_ValueError,
×
237
                                    "a udf call needs its operands");
238
                    return false;
239
                }
240
                dftracer::utils::dstd::Vector<dataframe::Expr> operands(
252 !
241
                    stack.end() - count, stack.end());
189 !
242
                stack.resize(stack.size() - static_cast<std::size_t>(count));
126 !
243
                stack.push_back((*udf)(operands));
189 !
244
                break;
63 ✔
245
            }
126 ✔
246
            case AstBin: {
917 ✔
247
                dataframe::Expr b = pop(), a = pop();
1,834 !
248
                stack.push_back(dataframe::expr_binary(
3,668 !
249
                    static_cast<dataframe::BinaryOp>(PyLong_AsLong(arg(1))), a,
1,834 !
250
                    b));
251
                break;
917 !
252
            }
2,751 !
253
            case AstPrim: {
11 ✔
254
                dataframe::Expr a = pop();
22 !
255
                stack.push_back(dataframe::expr_prim(
44 !
256
                    static_cast<dataframe::PrimOp>(PyLong_AsLong(arg(1))), a));
22 !
257
                break;
11 !
258
            }
22 ✔
259
            case AstCmp: {
563 ✔
260
                dftu_scalar rhs{};
1,126 ✔
261
                if (PyUnicode_Check(arg(2))) {
1,126 !
262
                    // expr_cmp copies the text into the node, so the borrow
263
                    // ends with this call.
264
                    dftracer::utils::dstd::StringView s;
78 ✔
265
                    if (!py_str_view(arg(2), &s)) return false;
78 !
266
                    rhs.kind = DFTU_SCALAR_TAG_STR;
78 ✔
267
                    rhs.len = static_cast<std::uint32_t>(s.size());
78 ✔
268
                    rhs.value.s = s.data();
78 ✔
269
                } else if (!py_to_scalar(arg(2), &rhs)) {
1,087 !
270
                    return false;
271
                }
272
                dataframe::Expr a = pop();
1,126 !
273
                stack.push_back(dataframe::expr_cmp(
3,378 !
274
                    static_cast<dataframe::CmpOp>(PyLong_AsLong(arg(1))), a,
1,126 !
275
                    rhs));
563 ✔
276
                break;
563 !
277
            }
1,126 ✔
278
            case AstCmpExpr: {
31 ✔
279
                dataframe::Expr b = pop(), a = pop();
62 !
280
                stack.push_back(dataframe::expr_cmp_expr(
124 !
281
                    static_cast<dataframe::CmpOp>(PyLong_AsLong(arg(1))), a,
62 !
282
                    b));
283
                break;
31 !
284
            }
93 !
285
            case AstLogical: {
101 ✔
286
                dataframe::Expr b = pop(), a = pop();
202 !
287
                stack.push_back(dataframe::expr_logical(
404 !
288
                    static_cast<dataframe::LogicalOp>(PyLong_AsLong(arg(1))), a,
202 !
289
                    b));
290
                break;
101 !
291
            }
303 !
292
            case AstNot: {
33 ✔
293
                dataframe::Expr a = pop();
66 !
294
                stack.push_back(dataframe::expr_not(a));
99 !
295
                break;
33 !
296
            }
66 ✔
297
            case AstCast: {
51 ✔
298
                dataframe::Expr a = pop();
102 !
299
                stack.push_back(dataframe::expr_cast(
204 !
300
                    static_cast<dataframe::TypeId>(PyLong_AsLong(arg(1))), a));
102 !
301
                break;
51 !
302
            }
102 ✔
303
            case AstUnary: {
40 ✔
304
                dataframe::Expr a = pop();
80 !
305
                stack.push_back(dataframe::expr_unary(
160 !
306
                    static_cast<dataframe::UnaryOp>(PyLong_AsLong(arg(1))), a));
80 !
307
                break;
40 !
308
            }
80 ✔
309
            case AstClip: {
8 ✔
310
                dftu_scalar lo{}, hi{};
16 ✔
311
                if (!py_to_scalar(arg(1), &lo) || !py_to_scalar(arg(2), &hi))
16 !
312
                    return false;
×
313
                dataframe::Expr a = pop();
16 !
314
                stack.push_back(dataframe::expr_clip(a, lo, hi));
24 !
315
                break;
8 !
316
            }
16 ✔
317
            case AstFillna: {
20 ✔
318
                dftu_scalar fill{};
40 ✔
319
                if (!py_to_scalar(arg(1), &fill)) return false;
40 !
320
                dataframe::Expr a = pop();
40 !
321
                const bool nan =
60 ✔
322
                    PyTuple_GET_SIZE(t) > 2 && PyObject_IsTrue(arg(2)) == 1;
40 !
323
                stack.push_back(dataframe::expr_fillna(a, fill, nan));
60 !
324
                break;
20 !
325
            }
40 ✔
326
            case AstStrPred: {
86 ✔
327
                dftracer::utils::dstd::StringView pattern;
172 ✔
328
                if (!py_str_view(arg(2), &pattern)) return false;
172 !
329
                dataframe::Expr a = pop();
172 !
330
                stack.push_back(dataframe::expr_str_pred(
430 !
331
                    static_cast<dataframe::StrPredOp>(PyLong_AsLong(arg(1))), a,
172 !
332
                    pattern));
86 ✔
333
                break;
86 !
334
            }
172 ✔
335
            case AstStrPredCol: {
16 ✔
336
                if (stack.size() < 2) {
32 !
337
                    PyErr_SetString(PyExc_ValueError,
×
338
                                    "string predicate needs its operands");
339
                    return false;
×
340
                }
341
                dataframe::Expr needle = pop();
32 !
342
                dataframe::Expr a = pop();
32 !
343
                auto pred = dataframe::expr_str_pred_col(
48 !
344
                    static_cast<dataframe::StrPredOp>(PyLong_AsLong(arg(1))), a,
32 !
345
                    needle);
16 !
346
                if (!pred) {
32 !
347
                    dftracer::utils::python::core::set_py_error(pred.error());
×
348
                    return false;
×
349
                }
350
                stack.push_back(std::move(*pred));
32 !
351
                break;
32 ✔
352
            }
64 !
353
            case AstStrReplaceCol: {
8 ✔
354
                if (stack.size() < 3) {
16 !
355
                    PyErr_SetString(PyExc_ValueError,
×
356
                                    "replace needs its operands");
357
                    return false;
×
358
                }
359
                dataframe::Expr to = pop();
16 !
360
                dataframe::Expr from = pop();
16 !
361
                dataframe::Expr a = pop();
16 !
362
                stack.push_back(dataframe::expr_str_replace_col(a, from, to));
24 !
363
                break;
8 !
364
            }
32 !
365
            case AstStrMap: {
53 ✔
366
                dataframe::Expr a = pop();
106 !
367
                stack.push_back(dataframe::expr_str_map(
212 !
368
                    static_cast<dataframe::StrMapOp>(PyLong_AsLong(arg(1))),
106 !
369
                    a));
370
                break;
53 !
371
            }
106 ✔
372
            case AstStrFn: {
257 ✔
373
                dftracer::utils::dstd::StringView text, text2;
514 ✔
374
                if (PyTuple_GET_SIZE(t) != 7 || !py_str_view(arg(2), &text) ||
1,028 !
375
                    !py_str_view(arg(3), &text2))
514 !
376
                    return false;
×
377
                const long fn = PyLong_AsLong(arg(1));
514 !
378
                const long long i0 = PyLong_AsLongLong(arg(4));
514 !
379
                const long long i1 = PyLong_AsLongLong(arg(5));
514 !
380
                const long nargs = PyLong_AsLong(arg(6));
514 !
381
                if (PyErr_Occurred()) return false;
514 !
382
                if (nargs < 1 || nargs > 2 ||
514 !
383
                    stack.size() < static_cast<std::size_t>(nargs)) {
514 !
384
                    PyErr_SetString(PyExc_ValueError,
×
385
                                    "string method needs its operands");
386
                    return false;
387
                }
388
                dataframe::Expr b;
514 ✔
389
                if (nargs == 2) b = pop();
514 ✔
390
                dataframe::Expr a = pop();
514 !
391
                stack.push_back(dataframe::expr_str_fn(
1,794 !
392
                    static_cast<dataframe::StrFn>(fn), a,
257 ✔
393
                    nargs == 2 ? &b : nullptr, text, text2, i0, i1));
257 ✔
394
                break;
257 !
395
            }
519 ✔
396
            case AstStrLen: {
9 ✔
397
                dataframe::Expr a = pop();
18 !
398
                stack.push_back(
18 !
399
                    dataframe::expr_str_size(a, PyLong_AsLong(arg(1)) != 0));
18 !
400
                break;
9 !
401
            }
18 ✔
402
            case AstStrFind: {
19 ✔
403
                dftracer::utils::dstd::StringView needle;
38 ✔
404
                if (!py_str_view(arg(1), &needle)) return false;
38 !
405
                dataframe::Expr a = pop();
38 !
406
                dataframe::Expr found = dataframe::expr_str_find(a, needle);
38 !
407
                // A third item asks for null where the needle is absent.
408
                if (PyTuple_GET_SIZE(t) > 2 && PyObject_IsTrue(arg(2))) {
38 !
409
                    found = dataframe::expr_select(
76 !
410
                        dataframe::expr_cmp(
57 !
411
                            dataframe::CmpOp::Ge, found,
412
                            dataframe::to_scalar<std::int64_t>(0)),
19 !
413
                        found,
414
                        dataframe::expr_lit_null(dataframe::TypeId::Int64));
76 !
415
                }
19 ✔
416
                stack.push_back(std::move(found));
38 !
417
                break;
19 !
418
            }
57 !
419
            case AstStrReplace: {
8 ✔
420
                dftracer::utils::dstd::StringView from, to;
16 ✔
421
                if (!py_str_view(arg(1), &from) || !py_str_view(arg(2), &to))
16 !
422
                    return false;
×
423
                dataframe::Expr a = pop();
16 !
424
                stack.push_back(dataframe::expr_str_replace(
40 !
425
                    a, from, to, PyLong_AsLong(arg(3)) != 0));
24 !
426
                break;
8 !
427
            }
16 ✔
428
            case AstStrSlice: {
3 ✔
429
                const long long start = PyLong_AsLongLong(arg(1));
6 !
430
                const long long len = PyLong_AsLongLong(arg(2));
6 !
431
                if (PyErr_Occurred()) return false;
6 !
432
                dataframe::Expr a = pop();
6 !
433
                stack.push_back(dataframe::expr_str_slice(a, start, len));
9 !
434
                break;
3 !
435
            }
6 ✔
436
            case AstIsIn: {
363 ✔
437
                dataframe::Series values;
726 ✔
438
                if (!py_values_series(arg(1), &values)) return false;
726 !
439
                dataframe::Expr a = pop();
724 !
440
                stack.push_back(dataframe::expr_is_in(a, std::move(values)));
1,086 !
441
                break;
362 !
442
            }
726 !
443
            case AstSelect: {
54 ✔
444
                if (stack.size() < 3) {
108 !
445
                    PyErr_SetString(PyExc_ValueError,
×
446
                                    "select needs three operands");
447
                    return false;
×
448
                }
449
                dataframe::Expr b = pop(), a = pop(), cond = pop();
108 !
450
                stack.push_back(dataframe::expr_select(cond, a, b));
162 !
451
                break;
54 !
452
            }
216 !
453
            case AstIsNull: {
718 ✔
454
                if (stack.empty()) {
1,436 !
455
                    PyErr_SetString(PyExc_ValueError,
×
456
                                    "is_null needs an operand");
457
                    return false;
×
458
                }
459
                const long null = PyLong_AsLong(arg(1));
1,436 !
460
                if (null == -1 && PyErr_Occurred()) return false;
1,436 !
461
                dataframe::Expr a = pop();
1,436 !
462
                stack.push_back(null >= 2
2,154 !
463
                                    ? dataframe::expr_is_na(a, null == 2)
771 !
464
                                    : dataframe::expr_is_null(a, null != 0));
665 !
465
                break;
718 !
466
            }
1,436 ✔
467
            default:
468
                PyErr_Format(PyExc_ValueError, "bad ast op %d", op);
×
469
                return false;
470
        }
471
        if (PyErr_Occurred()) return false;
18,036 !
472
    }
13,265 ✔
473
    if (stack.size() != 1) {
8,746 !
474
        PyErr_SetString(PyExc_ValueError,
×
475
                        "ast did not reduce to one expression");
476
        return false;
477
    }
478
    *out = std::move(stack.back());
8,746 ✔
479
    return true;
8,746 ✔
480
}
12,994 ✔
481

482
// The runtime-backed backend for vec's parallel_for seam: fan chunks across the
483
// process default runtime (lazily created, so import stays cheap).
484
void runtime_backend(void*, std::int64_t n, std::int64_t grain,
67,990 ✔
485
                     void (*body)(void*, std::int64_t, std::int64_t),
486
                     void* bctx) {
487
    const auto ran = dftracer::utils::default_runtime().parallel_for(
136,454 ✔
488
        n, grain, [&](std::int64_t b, std::int64_t e) { body(bctx, b, e); });
1,170,371 !
489
    if (!ran) {
67,990 ✔
490
        dftracer::utils::dstd::fatal(
×
491
            "parallel_for: the runtime stopped during a fork-join");
×
492
    }
493
}
67,989 ✔
494

495
}  // namespace
496

497
namespace dftracer::utils::python::frame {
498

499
bool build_expr_from_ast(PyObject* ast, dataframe::Expr* out) {
5,818 ✔
500
    return build_expr(ast, out);
5,818 ✔
501
}
502

503
// udf_lookup(name) -> capsule holding a dataframe::Udf. The capsule keeps the
504
// UDF, and so its plugin library, alive for as long as an expression holds it.
505
static PyObject* udf_lookup(PyObject* /*self*/, PyObject* arg) {
270 ✔
506
    Py_ssize_t n = 0;
270 ✔
507
    const char* name = PyUnicode_AsUTF8AndSize(arg, &n);
270 ✔
508
    if (!name) return nullptr;
270 !
509
    auto found = dataframe::udf(
405 ✔
510
        dftracer::utils::dstd::StringView(name, static_cast<std::size_t>(n)));
270 ✔
511
    if (!found) {
270 ✔
512
        const dftracer::utils::dstd::String message(found.error().message());
154 !
513
        PyErr_SetString(PyExc_LookupError, message.c_str());
154 !
514
        return nullptr;
154 ✔
515
    }
154 ✔
516
    auto held =
116 ✔
517
        dftracer::utils::dstd::make_unique<dataframe::Udf>(std::move(*found));
116 !
518
    PyObject* capsule =
116 !
519
        PyCapsule_New(held.get(), UDF_CAPSULE, free_udf_capsule);
116 !
520
    if (capsule) held.release();
116 ✔
521
    return capsule;
116 ✔
522
}
328 ✔
523

524
static PyObject* udf_names(PyObject* /*self*/, PyObject* /*unused*/) {
4 ✔
525
    PyObject* list = PyList_New(0);
4 ✔
526
    if (!list) return nullptr;
4 ✔
527
    for (const auto& name : dataframe::udf_names()) {
8 !
528
        PyObject* item = PyUnicode_FromStringAndSize(
6 !
529
            name.data(), static_cast<Py_ssize_t>(name.size()));
4 !
530
        if (!item || PyList_Append(list, item) < 0) {
4 !
531
            Py_XDECREF(item);
×
532
            Py_DECREF(list);
×
533
            return nullptr;
×
534
        }
535
        Py_DECREF(item);
6 !
536
    }
4 !
537
    return list;
4 ✔
538
}
2 ✔
539

540
// udaf_lookup(name) -> (capsule, min_args, max_args, flags). The capsule holds
541
// the UDAF record, and so its plugin library, for as long as an aggregate made
542
// from it lives.
543
static PyObject* udaf_lookup(PyObject* /*self*/, PyObject* arg) {
×
544
    Py_ssize_t n = 0;
×
545
    const char* name = PyUnicode_AsUTF8AndSize(arg, &n);
×
546
    if (!name) return nullptr;
×
547
    auto record = dataframe::find_udaf(
×
548
        dftracer::utils::dstd::StringView(name, static_cast<std::size_t>(n)));
×
549
    if (!record) {
×
550
        PyErr_Format(PyExc_LookupError, "no udaf named %s", name);
×
551
        return nullptr;
552
    }
553
    const dftu_udaf_desc& desc = record->desc();
×
554
    const int min_args = desc.min_args;
×
555
    const int max_args = desc.max_args;
×
556
    const unsigned long flags = static_cast<unsigned long>(desc.flags);
×
557
    auto held = dftracer::utils::dstd::make_unique<UdafHold>(std::move(record));
×
558
    PyObject* capsule =
×
559
        PyCapsule_New(held.get(), UDAF_CAPSULE, free_udaf_capsule);
×
560
    if (!capsule) return nullptr;
×
561
    held.release();
×
562
    return Py_BuildValue("(Niik)", capsule, min_args, max_args, flags);
×
563
}
×
564

565
static PyObject* udaf_names(PyObject* /*self*/, PyObject* /*unused*/) {
×
566
    PyObject* list = PyList_New(0);
×
567
    if (!list) return nullptr;
×
568
    for (const auto& name : dataframe::udaf_names()) {
×
569
        PyObject* item = PyUnicode_FromStringAndSize(
×
570
            name.data(), static_cast<Py_ssize_t>(name.size()));
×
571
        if (!item || PyList_Append(list, item) < 0) {
×
572
            Py_XDECREF(item);
×
573
            Py_DECREF(list);
×
574
            return nullptr;
×
575
        }
576
        Py_DECREF(item);
×
577
    }
×
578
    return list;
×
579
}
580

581
// A share of the Series behind each item of `obj`, as pointers into `copies`,
582
// which must outlive their use; `msg` is the TypeError for an item that is not
583
// a Series. The caller evaluates with the GIL released, and `s.name = x` swaps
584
// the name of a Series object's own handle, so the evaluation reads the shares.
585
static bool columns_from_seq(
2,924 ✔
586
    PyObject* obj, const char* msg,
587
    dftracer::utils::python::core::FastSeq& held,
588
    dftracer::utils::dstd::Vector<dataframe::Series>& copies,
589
    dftracer::utils::dstd::Vector<const dataframe::Series*>& out) {
590
    if (!held.open(obj, "columns must be a sequence")) return false;
2,924 !
591
    copies.reserve(static_cast<std::size_t>(held.size()));
2,924 ✔
592
    out.reserve(static_cast<std::size_t>(held.size()));
2,924 ✔
593
    for (Py_ssize_t i = 0; i < held.size(); ++i) {
6,214 !
594
        const dataframe::Series* c = unwrap_vec_column(held.item(i));
3,290 ✔
595
        if (!c) {
3,290 ✔
596
            PyErr_SetString(PyExc_TypeError, msg);
×
597
            return false;
×
598
        }
599
        copies.push_back(c->share());
3,290 !
600
        out.push_back(&copies.back());
3,290 ✔
601
    }
1,645 !
602
    return true;
1,462 ✔
603
}
1,462 ✔
604

605
// vec_eval(ast, [Series, ...]) -> Series
606
static PyObject* vec_eval(PyObject* /*self*/, PyObject* args) {
2,624 ✔
607
    PyObject* ast = nullptr;
2,624 ✔
608
    PyObject* cols_obj = nullptr;
2,624 ✔
609
    if (!PyArg_ParseTuple(args, "OO", &ast, &cols_obj)) return nullptr;
2,624 !
610

611
    dataframe::Expr expr;
2,624 ✔
612
    if (!build_expr(ast, &expr)) return nullptr;
2,624 !
613

614
    dftracer::utils::python::core::FastSeq held;
2,622 ✔
615
    dftracer::utils::dstd::Vector<dataframe::Series> copies;
2,622 ✔
616
    dftracer::utils::dstd::Vector<const dataframe::Series*> inputs;
2,622 ✔
617
    if (!columns_from_seq(cols_obj, "columns must be SeriesList", held, copies,
2,622 !
618
                          inputs))
619
        return nullptr;
620

621
    // A per-batch Python udf runs on the Python lane, which needs the GIL.
622
    auto out = release_gil([&] { return dataframe::eval(expr, inputs); });
5,244 !
623
    if (!out) {
2,622 ✔
624
        dftracer::utils::python::core::set_py_error(out.error());
34 !
625
        return nullptr;
17 ✔
626
    }
627
    return wrap_vec_column(std::move(*out));
2,588 !
628
}
5,247 ✔
629

630
// vec_eval_many([ast, ...], [Series, ...]) -> [Series, ...]
631
// Compiles all roots into one program so CSE spans them (a subexpression shared
632
// across outputs is computed once), sharing the same input column list.
633
static PyObject* vec_eval_many(PyObject* /*self*/, PyObject* args) {
302 ✔
634
    PyObject* asts_obj = nullptr;
302 ✔
635
    PyObject* cols_obj = nullptr;
302 ✔
636
    if (!PyArg_ParseTuple(args, "OO", &asts_obj, &cols_obj)) return nullptr;
302 !
637

638
    dftracer::utils::dstd::Vector<dataframe::Expr> roots;
302 ✔
639
    if (!dftracer::utils::python::core::parse_seq<dataframe::Expr>(
302 !
640
            asts_obj, "asts must be a sequence", roots,
151 ✔
641
            [](PyObject* item,
306 ✔
642
               dftracer::utils::dstd::Vector<dataframe::Expr>& o) {
643
                dataframe::Expr root;
306 ✔
644
                if (!build_expr(item, &root)) return false;
306 !
645
                o.push_back(std::move(root));
306 !
646
                return true;
153 ✔
647
            }))
306 ✔
648
        return nullptr;
649

650
    dftracer::utils::python::core::FastSeq held;
302 ✔
651
    dftracer::utils::dstd::Vector<dataframe::Series> copies;
302 ✔
652
    dftracer::utils::dstd::Vector<const dataframe::Series*> inputs;
302 ✔
653
    if (!columns_from_seq(cols_obj, "columns must be Series", held, copies,
302 !
654
                          inputs))
655
        return nullptr;
656

657
    auto res = release_gil([&] { return dataframe::eval_many(roots, inputs); });
604 !
658
    if (!res) {
302 ✔
659
        dftracer::utils::python::core::set_py_error(res.error());
×
660
        return nullptr;
661
    }
662
    dftracer::utils::dstd::Vector<dataframe::Series>& outs = *res;
302 ✔
663
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(outs.size()));
302 !
664
    if (!list) return nullptr;
302 !
665
    for (std::size_t i = 0; i < outs.size(); ++i) {
608 !
666
        PyObject* s = wrap_vec_column(std::move(outs[i]));
306 !
667
        if (!s) {
306 !
668
            Py_DECREF(list);
×
669
            return nullptr;
×
670
        }
671
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
306 !
672
    }
153 !
673
    return list;
151 ✔
674
}
453 ✔
675

676
int init_columnar_eval(PyObject* m) {
222 ✔
677
    dataframe::set_parallel_backend(runtime_backend, nullptr);
222 ✔
678
    static PyMethodDef def = {
111 ✔
679
        "vec_eval", vec_eval, METH_VARARGS,
680
        "vec_eval(ast, columns) -> Series: compile (type inference + CSE) "
681
        "and fused chunked evaluation of a columnar expression."};
682
    PyObject* fn = PyCFunction_NewEx(&def, nullptr, nullptr);
222 ✔
683
    if (!fn) return -1;
222 !
684
    if (PyModule_AddObject(m, "vec_eval", fn) < 0) {
222 ✔
685
        Py_DECREF(fn);
×
686
        return -1;
×
687
    }
688
    static PyMethodDef def_many = {
111 ✔
689
        "vec_eval_many", vec_eval_many, METH_VARARGS,
690
        "vec_eval_many(asts, columns) -> [Series]: compile several roots into "
691
        "one CSE'd program over a shared input list and evaluate in one pass."};
692
    PyObject* fn_many = PyCFunction_NewEx(&def_many, nullptr, nullptr);
222 ✔
693
    if (!fn_many) return -1;
222 !
694
    if (PyModule_AddObject(m, "vec_eval_many", fn_many) < 0) {
222 ✔
695
        Py_DECREF(fn_many);
×
696
        return -1;
×
697
    }
698
    static PyMethodDef def_udf = {
111 ✔
699
        "udf_lookup", udf_lookup, METH_O,
700
        "udf_lookup(name) -> capsule: the registered scalar UDF `name`, for "
701
        "the udf node of a columnar ast. Raises LookupError for an unknown "
702
        "name."};
703
    PyObject* fn_udf = PyCFunction_NewEx(&def_udf, nullptr, nullptr);
222 ✔
704
    if (!fn_udf) return -1;
222 !
705
    if (PyModule_AddObject(m, "udf_lookup", fn_udf) < 0) {
222 ✔
706
        Py_DECREF(fn_udf);
×
707
        return -1;
×
708
    }
709
    static PyMethodDef def_names = {
111 ✔
710
        "udf_names", udf_names, METH_NOARGS,
711
        "udf_names() -> [str]: the names of the registered scalar UDFs."};
712
    PyObject* fn_names = PyCFunction_NewEx(&def_names, nullptr, nullptr);
222 ✔
713
    if (!fn_names) return -1;
222 !
714
    if (PyModule_AddObject(m, "udf_names", fn_names) < 0) {
222 ✔
715
        Py_DECREF(fn_names);
×
716
        return -1;
×
717
    }
718
    static PyMethodDef def_udaf = {
111 ✔
719
        "udaf_lookup", udaf_lookup, METH_O,
720
        "udaf_lookup(name) -> (capsule, min_args, max_args, flags): the "
721
        "registered UDAF `name`. Raises LookupError for an unknown name."};
722
    PyObject* fn_udaf = PyCFunction_NewEx(&def_udaf, nullptr, nullptr);
222 ✔
723
    if (!fn_udaf) return -1;
222 !
724
    if (PyModule_AddObject(m, "udaf_lookup", fn_udaf) < 0) {
222 ✔
725
        Py_DECREF(fn_udaf);
×
726
        return -1;
×
727
    }
728
    static PyMethodDef def_udaf_names = {
111 ✔
729
        "udaf_names", udaf_names, METH_NOARGS,
730
        "udaf_names() -> [str]: the names of the registered UDAFs."};
731
    PyObject* fn_udaf_names =
333 ✔
732
        PyCFunction_NewEx(&def_udaf_names, nullptr, nullptr);
222 ✔
733
    if (!fn_udaf_names) return -1;
222 !
734
    if (PyModule_AddObject(m, "udaf_names", fn_udaf_names) < 0) {
222 ✔
735
        Py_DECREF(fn_udaf_names);
×
736
        return -1;
×
737
    }
738
    return 0;
111 ✔
739
}
111 ✔
740

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