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

llnl-asr / dftracer-utils / 38033748054

10 Oct 2026 07:14AM UTC coverage: 62.608% (+5.2%) from 57.391%
38033748054

push

github

rayandrew
ci: shard the test job

The coverage jobs ran 64 minutes of C++ tests in one process. Each shard
runs every n-th test with ctest -I, the Python tests and the type check
run in shard 1 only, and each shard uploads its own coverage report to
Coveralls, which merges the parallel uploads.

117733 of 235605 branches covered (49.97%)

Branch coverage included in aggregate %.

102379 of 115969 relevant lines covered (88.28%)

3014114.56 hits per line

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

61.45
/src/dftracer/utils/python/batch_indexer.cpp
1
#include <dftracer/utils/core/common/constants.h>
2
#include <dftracer/utils/core/common/filesystem.h>
3
#include <dftracer/utils/core/common/hash/hash_combine.h>
4
#include <dftracer/utils/core/common/string_intern.h>
5
#include <dftracer/utils/core/common/transparent_string_hash.h>
6
#include <dftracer/utils/core/coro/task.h>
7
#include <dftracer/utils/core/coro/when_all.h>
8
#include <dftracer/utils/core/runtime.h>
9
#include <dftracer/utils/core/tasks/coro_scope.h>
10
#include <dftracer/utils/duql/query.h>
11
#include <dftracer/utils/index/build/resolve_and_build.h>
12
#include <dftracer/utils/index/build/resolver.h>
13
#include <dftracer/utils/index/gzip/checkpoint_indexer_factory.h>
14
#include <dftracer/utils/index/indexer.h>
15
#include <dftracer/utils/index/record_schema.h>
16
#include <dftracer/utils/index/schemas/dft/agg/aggregation_config.h>
17
#include <dftracer/utils/index/schemas/dft/agg/aggregation_serialization.h>
18
#include <dftracer/utils/index/schemas/dft/agg/aggregator_types.h>
19
#include <dftracer/utils/index/schemas/dft/agg/event_aggregator.h>
20
#include <dftracer/utils/index/schemas/dft/agg/system_metrics.h>
21
#include <dftracer/utils/index/schemas/dft/agg/system_metrics_serialization.h>
22
#include <dftracer/utils/index/store/db_manager.h>
23
#include <dftracer/utils/index/store/index_database.h>
24
#include <dftracer/utils/python/batch_indexer.h>
25
#include <dftracer/utils/python/dataframe.h>
26
#include <dftracer/utils/python/indexer.h>
27
#include <dftracer/utils/python/py_dict_helpers.h>
28
#include <dftracer/utils/python/py_errors.h>
29
#include <dftracer/utils/python/py_list_helpers.h>
30
#include <dftracer/utils/python/py_method.h>
31
#include <dftracer/utils/python/py_runtime_mixin.h>
32
#include <dftracer/utils/python/py_seq_helpers.h>
33
#include <dftracer/utils/python/py_str_helpers.h>
34
#include <dftracer/utils/python/py_type_helpers.h>
35
#include <dftracer/utils/python/runtime.h>
36
#include <dftracer/utils/trace/internal/utils.h>
37

38
#include <algorithm>
39
#include <chrono>
40
#include <cstdio>
41
#include <optional>
42
#include <string>
43
#include <vector>
44

45
using dftracer::utils::CoroScope;
46
using dftracer::utils::Runtime;
47
using dftracer::utils::coro::CoroTask;
48
using namespace dftracer::utils::index::build;
49
using namespace dftracer::utils::index::schemas::dft::agg;
50

51
// ---------------------------------------------------------------------------
52
// BatchIndexer - directory-level indexer with resolve/build pattern
53
// ---------------------------------------------------------------------------
54

55
static void Indexer_dealloc(IndexerObject* self) {
210 ✔
56
    Py_XDECREF(self->runtime_obj);
210 ✔
57
    Py_XDECREF(self->directory);
210 ✔
58
    Py_XDECREF(self->files);
210 ✔
59
    Py_XDECREF(self->index_dir);
210 ✔
60
    Py_XDECREF(self->group_keys);
210 ✔
61
    Py_XDECREF(self->custom_metric_fields);
210 ✔
62
    Py_XDECREF(self->bloom_fields);
210 ✔
63
    Py_XDECREF(self->extensions);
210 ✔
64
    Py_XDECREF(self->schema);
210 ✔
65
    Py_TYPE(self)->tp_free((PyObject*)self);
210 ✔
66
}
210 ✔
67

68
static PyObject* Indexer_new(PyTypeObject* type, PyObject*, PyObject*) {
210 ✔
69
    IndexerObject* self = (IndexerObject*)type->tp_alloc(type, 0);
210 ✔
70
    if (self) {
210 !
71
        self->runtime_obj = nullptr;
210 ✔
72
        self->directory = nullptr;
210 ✔
73
        self->files = nullptr;
210 ✔
74
        self->index_dir = nullptr;
210 ✔
75
        self->require_checkpoint = 1;
210 ✔
76
        self->require_bloom = 1;
210 ✔
77
        self->build_bloom = 1;
210 ✔
78
        self->require_aggregation = 0;
210 ✔
79
        self->bloom_fields = nullptr;
210 ✔
80
        self->extensions = nullptr;
210 ✔
81
        self->memory_budget = 0;
210 ✔
82
        self->schema = nullptr;
210 ✔
83
        self->false_positive_rate = ChunkIndexerConfig{}.false_positive_rate;
210 !
84
        self->expected_entries =
210 ✔
85
            ChunkIndexerConfig{}.expected_entries_per_chunk;
210 !
86
        self->path_budget = ChunkIndexerConfig{}.path_budget;
210 !
87
        self->stats_share = ChunkIndexerConfig{}.stats_share;
210 !
88
        self->auto_max_distinct = ChunkIndexerConfig{}.auto_max_distinct;
210 !
89
        self->time_interval_ms = 5000.0;
210 ✔
90
        self->group_keys = nullptr;
210 ✔
91
        self->custom_metric_fields = nullptr;
210 ✔
92
        self->compute_percentiles = 0;
210 ✔
93
        self->group_by_file = 1;
210 ✔
94
        self->checkpoint_size =
210 ✔
95
            dftracer::utils::constants::indexer::DEFAULT_CHECKPOINT_SIZE;
96
        self->parallelism = 0;
210 ✔
97
        self->force_rebuild = 0;
210 ✔
98
    }
99
    return (PyObject*)self;
210 ✔
100
}
101

102
static int Indexer_init(IndexerObject* self, PyObject* args, PyObject* kwds) {
210 ✔
103
    static const char* kwlist[] = {"directory",
104
                                   "files",
105
                                   "index_dir",
106
                                   "require_checkpoint",
107
                                   "require_bloom",
108
                                   "build_bloom",
109
                                   "require_aggregation",
110
                                   "time_interval_ms",
111
                                   "group_keys",
112
                                   "custom_metric_fields",
113
                                   "compute_percentiles",
114
                                   "group_by_file",
115
                                   "checkpoint_size",
116
                                   "parallelism",
117
                                   "force_rebuild",
118
                                   "runtime",
119
                                   "bloom_fields",
120
                                   "false_positive_rate",
121
                                   "expected_entries",
122
                                   "path_budget",
123
                                   "stats_share",
124
                                   "auto_max_distinct",
125
                                   "extensions",
126
                                   "memory_budget",
127
                                   "schema",
128
                                   nullptr};
129

130
    const char* directory = "";
210 ✔
131
    PyObject* files_obj = Py_None;
210 ✔
132
    const char* index_dir = "";
210 ✔
133
    int require_checkpoint = 1;
210 ✔
134
    int require_bloom = 1;
210 ✔
135
    int build_bloom = 1;
210 ✔
136
    int require_aggregation = 0;
210 ✔
137
    double time_interval_ms = 5000.0;
210 ✔
138
    PyObject* group_keys_obj = Py_None;
210 ✔
139
    PyObject* custom_metrics_obj = Py_None;
210 ✔
140
    int compute_percentiles = 0;
210 ✔
141
    int group_by_file = 1;
210 ✔
142
    Py_ssize_t checkpoint_size = static_cast<Py_ssize_t>(
210 ✔
143
        dftracer::utils::constants::indexer::DEFAULT_CHECKPOINT_SIZE);
144
    Py_ssize_t parallelism = 0;
210 ✔
145
    int force_rebuild = 0;
210 ✔
146
    PyObject* runtime_arg = nullptr;
210 ✔
147
    PyObject* bloom_fields_obj = Py_None;
210 ✔
148
    double false_positive_rate = self->false_positive_rate;
210 ✔
149
    Py_ssize_t expected_entries =
210 ✔
150
        static_cast<Py_ssize_t>(self->expected_entries);
210 ✔
151
    Py_ssize_t path_budget = static_cast<Py_ssize_t>(self->path_budget);
210 ✔
152
    double stats_share = self->stats_share;
210 ✔
153
    Py_ssize_t auto_max_distinct =
210 ✔
154
        static_cast<Py_ssize_t>(self->auto_max_distinct);
210 ✔
155
    PyObject* extensions_obj = Py_None;
210 ✔
156
    unsigned long long memory_budget = 0;
210 ✔
157
    PyObject* schema_obj = Py_None;
210 ✔
158

159
    if (!PyArg_ParseTupleAndKeywords(
210 !
160
            args, kwds, "|sOsppppdOOppnnpOOdnndnOKO",
161
            const_cast<char**>(kwlist), &directory, &files_obj, &index_dir,
162
            &require_checkpoint, &require_bloom, &build_bloom,
163
            &require_aggregation, &time_interval_ms, &group_keys_obj,
164
            &custom_metrics_obj, &compute_percentiles, &group_by_file,
165
            &checkpoint_size, &parallelism, &force_rebuild, &runtime_arg,
166
            &bloom_fields_obj, &false_positive_rate, &expected_entries,
167
            &path_budget, &stats_share, &auto_max_distinct, &extensions_obj,
168
            &memory_budget, &schema_obj)) {
169
        return -1;
×
170
    }
171
    if (!(false_positive_rate > 0.0 && false_positive_rate < 1.0)) {
210 !
172
        PyErr_SetString(PyExc_ValueError,
1 !
173
                        "false_positive_rate must be in (0, 1)");
174
        return -1;
1 ✔
175
    }
176
    if (expected_entries <= 0) {
209 !
177
        PyErr_SetString(PyExc_ValueError, "expected_entries must be > 0");
×
178
        return -1;
×
179
    }
180
    if (auto_max_distinct <= 0) {
209 !
181
        PyErr_SetString(PyExc_ValueError, "auto_max_distinct must be > 0");
×
182
        return -1;
×
183
    }
184
    if (path_budget < 0) {
209 ✔
185
        PyErr_SetString(PyExc_ValueError, "path_budget must be >= 0");
1 !
186
        return -1;
1 ✔
187
    }
188
    if (!(stats_share > 0.0 && stats_share <= 1.0)) {
208 ✔
189
        PyErr_SetString(PyExc_ValueError, "stats_share must be in (0, 1]");
3 !
190
        return -1;
3 ✔
191
    }
192
    self->path_budget = static_cast<std::size_t>(path_budget);
205 ✔
193
    self->stats_share = stats_share;
205 ✔
194
    self->auto_max_distinct = static_cast<std::size_t>(auto_max_distinct);
205 ✔
195
    if (bloom_fields_obj != Py_None) {
205 !
196
        std::vector<std::string> check;
205 ✔
197
        if (!dftracer::utils::python::parse_string_seq(
205 !
198
                bloom_fields_obj, "bloom_fields must be a sequence of str",
199
                check))
200
            return -1;
×
201
        Py_INCREF(bloom_fields_obj);
205 !
202
        self->bloom_fields = bloom_fields_obj;
205 ✔
203
    }
205 !
204
    self->memory_budget = memory_budget;
205 ✔
205
    if (schema_obj != Py_None) {
205 ✔
206
        if (!PyUnicode_Check(schema_obj)) {
2 !
207
            PyErr_SetString(PyExc_TypeError, "schema must be a str or None");
×
208
            return -1;
×
209
        }
210
        Py_INCREF(schema_obj);
2 ✔
211
        Py_XSETREF(self->schema, schema_obj);
2 !
212
    }
213
    self->false_positive_rate = false_positive_rate;
205 ✔
214
    self->expected_entries = static_cast<std::size_t>(expected_entries);
205 ✔
215
    if (extensions_obj != Py_None) {
205 ✔
216
        std::vector<std::string> check;
1 ✔
217
        if (!dftracer::utils::python::parse_string_seq(
1 !
218
                extensions_obj, "extensions must be a sequence of str", check))
219
            return -1;
×
220
        Py_INCREF(extensions_obj);
1 !
221
        Py_XSETREF(self->extensions, extensions_obj);
1 !
222
    }
1 !
223

224
    // Validate: at least one of directory or files must be provided
225
    bool has_directory = directory && directory[0] != '\0';
205 !
226
    bool has_files = files_obj && files_obj != Py_None &&
390 !
227
                     PyList_Check(files_obj) && PyList_Size(files_obj) > 0;
595 !
228

229
    if (!has_directory && !has_files) {
205 ✔
230
        PyErr_SetString(PyExc_ValueError,
1 !
231
                        "At least one of 'directory' or 'files' must be "
232
                        "provided");
233
        return -1;
1 ✔
234
    }
235

236
    // Store runtime
237
    if (runtime_arg && runtime_arg != Py_None) {
204 !
238
        if (PyObject_TypeCheck(runtime_arg, &RuntimeType)) {
×
239
            Py_INCREF(runtime_arg);
×
240
            self->runtime_obj = runtime_arg;
×
241
        } else {
242
            PyObject* native = PyObject_GetAttrString(runtime_arg, "_native");
×
243
            if (native && PyObject_TypeCheck(native, &RuntimeType)) {
×
244
                self->runtime_obj = native;
×
245
            } else {
246
                Py_XDECREF(native);
×
247
                PyErr_SetString(PyExc_TypeError,
×
248
                                "runtime must be a Runtime instance or None");
249
                return -1;
×
250
            }
251
        }
252
    }
253

254
    self->directory = PyUnicode_FromString(directory);
204 !
255
    self->index_dir = PyUnicode_FromString(index_dir);
204 !
256
    self->require_checkpoint = require_checkpoint;
204 ✔
257
    self->require_bloom = require_bloom;
204 ✔
258
    self->build_bloom = build_bloom;
204 ✔
259
    self->require_aggregation = require_aggregation;
204 ✔
260
    self->time_interval_ms = time_interval_ms;
204 ✔
261
    self->compute_percentiles = compute_percentiles;
204 ✔
262
    self->group_by_file = group_by_file;
204 ✔
263
    self->checkpoint_size = static_cast<std::size_t>(checkpoint_size);
204 ✔
264
    self->parallelism = static_cast<std::size_t>(parallelism);
204 ✔
265
    self->force_rebuild = force_rebuild;
204 ✔
266

267
    // Store files list
268
    if (has_files) {
204 ✔
269
        Py_INCREF(files_obj);
185 !
270
        self->files = files_obj;
185 ✔
271
    } else {
272
        self->files = nullptr;
19 ✔
273
    }
274

275
    // Store group_keys
276
    if (group_keys_obj && group_keys_obj != Py_None) {
204 !
277
        Py_INCREF(group_keys_obj);
×
278
        self->group_keys = group_keys_obj;
×
279
    } else {
280
        self->group_keys = nullptr;
204 ✔
281
    }
282

283
    // Store custom_metric_fields
284
    if (custom_metrics_obj && custom_metrics_obj != Py_None) {
204 !
285
        Py_INCREF(custom_metrics_obj);
×
286
        self->custom_metric_fields = custom_metrics_obj;
×
287
    } else {
288
        self->custom_metric_fields = nullptr;
204 ✔
289
    }
290

291
    return 0;
204 ✔
292
}
293

294
// The args fields the bloom tier covers, as the index names them. False with
295
// a Python error set when bloom_fields holds a non-str.
296
static bool requested_bloom_fields(IndexerObject* self,
236 ✔
297
                                   std::vector<std::string>& out) {
298
    if (!self->bloom_fields) {
236 !
299
        out.clear();
×
300
        return true;
×
301
    }
302
    out.clear();
236 ✔
303
    if (!dftracer::utils::python::parse_string_seq(
236 !
304
            self->bloom_fields, "bloom_fields must be a sequence of str", out))
305
        return false;
×
306
    for (std::string& f : out) f = extra_dimension_name(f);
260 !
307
    return true;
236 ✔
308
}
309

310
static Runtime* get_batch_indexer_runtime(IndexerObject* self) {
236 ✔
311
    if (self->runtime_obj) {
236 !
312
        return ((RuntimeObject*)self->runtime_obj)->runtime.get();
×
313
    }
314
    return dftracer::utils::python::get_default_runtime();
236 ✔
315
}
316

317
static std::optional<AggregationConfig> build_aggregation_config(
236 ✔
318
    IndexerObject* self) {
319
    if (!self->require_aggregation) {
236 ✔
320
        return std::nullopt;
194 ✔
321
    }
322

323
    AggregationConfig config;
42 !
324
    config.time_interval_us =
42 ✔
325
        static_cast<std::uint64_t>(self->time_interval_ms * 1000.0);
42 ✔
326

327
    if (self->group_keys && PyList_Check(self->group_keys)) {
42 !
328
        Py_ssize_t n = PyList_Size(self->group_keys);
×
329
        for (Py_ssize_t i = 0; i < n; i++) {
×
330
            const char* s = as_utf8(PyList_GetItem(self->group_keys, i));
×
331
            if (s) config.extra_group_keys.emplace_back(s);
×
332
        }
333
    }
334
    if (self->custom_metric_fields &&
42 !
335
        PyList_Check(self->custom_metric_fields)) {
×
336
        Py_ssize_t n = PyList_Size(self->custom_metric_fields);
×
337
        for (Py_ssize_t i = 0; i < n; i++) {
×
338
            const char* s =
339
                as_utf8(PyList_GetItem(self->custom_metric_fields, i));
×
340
            if (s) config.custom_metric_fields.emplace_back(s);
×
341
        }
342
    }
343

344
    config.compute_percentiles = self->compute_percentiles != 0;
42 ✔
345
    config.group_by_file = self->group_by_file != 0;
42 ✔
346
    return config;
42 ✔
347
}
42 ✔
348

349
static std::optional<dftracer::utils::index::IndexerOptions> indexer_options(
236 ✔
350
    IndexerObject* self) {
351
    dftracer::utils::index::IndexerOptions o;
236 !
352
    const char* index_dir = as_utf8(self->index_dir);
236 !
353
    o.index_dir = index_dir ? index_dir : "";
236 !
354
    o.checkpoint_size = self->checkpoint_size;
236 ✔
355
    o.parallelism = self->parallelism;
236 ✔
356
    o.checkpoints = self->require_checkpoint;
236 ✔
357
    o.aggregation = build_aggregation_config(self);
236 !
358
    o.runtime = get_batch_indexer_runtime(self);
236 !
359
    o.memory_budget = self->memory_budget;
236 ✔
360
    if (self->schema) {
236 ✔
361
        const char* p = as_utf8(self->schema);
2 !
362
        o.schema = p ? p : "";
2 !
363
    }
364
    if (!self->build_bloom) {
236 !
365
        o.bloom.reset();
×
366
        return o;
×
367
    }
368
    auto& b = *o.bloom;
236 ✔
369
    if (!requested_bloom_fields(self, b.fields)) return std::nullopt;
236 !
370
    b.required = self->require_bloom;
236 ✔
371
    b.false_positive_rate = self->false_positive_rate;
236 ✔
372
    b.path_budget = self->path_budget;
236 ✔
373
    b.stats_share = self->stats_share;
236 ✔
374
    b.auto_max_distinct = self->auto_max_distinct;
236 ✔
375
    b.expected_entries_per_chunk = self->expected_entries;
236 ✔
376
    if (self->extensions) o.extensions.clear();
236 ✔
377
    if (self->extensions &&
239 !
378
        !dftracer::utils::python::parse_string_seq(
3 !
379
            self->extensions, "extensions must be a sequence of str",
380
            o.extensions))
381
        return std::nullopt;
×
382
    return o;
236 ✔
383
}
236 ✔
384

385
static std::vector<std::string> indexer_paths(IndexerObject* self) {
236 ✔
386
    const char* directory = as_utf8(self->directory);
236 !
387
    if (directory && directory[0] != '\0') return {directory};
256 !
388
    std::vector<std::string> paths;
216 ✔
389
    if (self->files && PyList_Check(self->files)) {
216 !
390
        Py_ssize_t n = PyList_Size(self->files);
216 !
391
        for (Py_ssize_t i = 0; i < n; i++) {
462 ✔
392
            const char* s = as_utf8(PyList_GetItem(self->files, i));
246 !
393
            if (s) paths.emplace_back(s);
246 !
394
        }
395
    }
396
    return paths;
216 ✔
397
}
216 ✔
398

399
// Runs `fn` on an Indexer over this object's paths and options, GIL released.
400
template <class Fn>
401
static bool with_indexer(IndexerObject* self, Fn fn) {
19 ✔
402
    auto options = indexer_options(self);
19 !
403
    if (!options) return false;
19 !
404
    auto paths = indexer_paths(self);
19 !
405
    return run_blocking([&] {
73 !
406
        fn(dftracer::utils::index::Indexer::open(std::move(paths),
25 !
407
                                                 std::move(*options)));
19 ✔
408
    });
19 ✔
409
}
19 ✔
410

411
enum class IndexerCall { STATUS, BUILD, REBUILD, ENSURE };
412

413
static bool run_indexer(IndexerObject* self, IndexerCall call,
217 ✔
414
                        dftracer::utils::index::IndexStatus& out) {
415
    auto options = indexer_options(self);
217 !
416
    if (!options) return false;
217 !
417
    auto paths = indexer_paths(self);
217 !
418
    const bool force = self->force_rebuild != 0;
217 ✔
419
    return run_blocking([&] {
217 !
420
        auto ix = dftracer::utils::index::Indexer::open(std::move(paths),
217 ✔
421
                                                        std::move(*options));
652 ✔
422
        switch (call) {
216 !
423
            case IndexerCall::STATUS:
23 ✔
424
                out = ix.status();
23 !
425
                break;
23 ✔
426
            case IndexerCall::BUILD:
1 ✔
427
                out = ix.build();
1 !
428
                break;
1 ✔
429
            case IndexerCall::REBUILD:
×
430
                out = ix.rebuild();
×
431
                break;
×
432
            case IndexerCall::ENSURE: {
192 ✔
433
                if (!force) {
192 ✔
434
                    out = ix.build();
174 !
435
                    break;
174 ✔
436
                }
437
                auto before = ix.status();
18 !
438
                out = before.needs_work.empty() &&
18 ✔
439
                              !before.aggregation_needs_rebuild
×
440
                          ? std::move(before)
36 !
441
                          : ix.rebuild();
18 ✔
442
                break;
18 ✔
443
            }
18 ✔
444
        }
445
    });
433 ✔
446
}
217 ✔
447

448
static PyObject* string_list(const std::vector<std::string>& items) {
654 ✔
449
    PyObject* list = PyList_New(static_cast<Py_ssize_t>(items.size()));
654 ✔
450
    if (!list) return nullptr;
654 !
451
    for (std::size_t i = 0; i < items.size(); ++i) {
908 ✔
452
        PyObject* s = PyUnicode_FromString(items[i].c_str());
254 ✔
453
        if (!s) {
254 !
454
            Py_DECREF(list);
455
            return nullptr;
×
456
        }
457
        PyList_SET_ITEM(list, static_cast<Py_ssize_t>(i), s);
254 ✔
458
    }
459
    return list;
654 ✔
460
}
461

462
static PyObject* status_dict(const dftracer::utils::index::IndexStatus& st) {
218 ✔
463
    PyObject* dict = PyDict_New();
218 ✔
464
    if (!dict) return nullptr;
218 !
465
    dict_set_steal(dict, "total_files", PyLong_FromSize_t(st.total));
218 ✔
466
    dict_set_steal(dict, "index_path",
218 ✔
467
                   PyUnicode_FromString(st.index_path.c_str()));
468
    dict_set_steal(dict, "aggregation_interval_us",
218 ✔
469
                   PyLong_FromUnsignedLongLong(st.aggregation_interval_us));
218 ✔
470
    dict_set_steal(dict, "needs_rebuild",
218 ✔
471
                   PyBool_FromLong(st.aggregation_needs_rebuild));
218 ✔
472
    dict_set_steal(dict, "ready", string_list(st.ready));
218 ✔
473
    dict_set_steal(dict, "needs_work", string_list(st.needs_work));
218 ✔
474
    dict_set_steal(dict, "truncated", string_list(st.truncated));
218 ✔
475
    return dict;
218 ✔
476
}
477

478
// ---------------------------------------------------------------------------
479
// resolve() - check what exists vs needs building
480
// ---------------------------------------------------------------------------
481

482
static PyObject* Indexer_resolve(IndexerObject* self,
24 ✔
483
                                 PyObject* Py_UNUSED(ignored)) {
484
    dftracer::utils::index::IndexStatus st;
24 ✔
485
    if (!run_indexer(self, IndexerCall::STATUS, st)) return nullptr;
24 !
486
    return status_dict(st);
23 !
487
}
24 ✔
488

489
// ---------------------------------------------------------------------------
490
// build() - build missing index tiers
491
// ---------------------------------------------------------------------------
492

493
static PyObject* Indexer_build(IndexerObject* self,
1 ✔
494
                               PyObject* Py_UNUSED(ignored)) {
495
    dftracer::utils::index::IndexStatus st;
1 ✔
496
    if (!run_indexer(
1 !
497
            self,
498
            self->force_rebuild ? IndexerCall::REBUILD : IndexerCall::BUILD,
1 !
499
            st))
500
        return nullptr;
×
501
    Py_RETURN_NONE;
1 ✔
502
}
1 ✔
503

504
// ---------------------------------------------------------------------------
505
// ensure_indexed() - resolve + build if needed
506
// ---------------------------------------------------------------------------
507

508
static PyObject* Indexer_ensure_indexed(IndexerObject* self,
192 ✔
509
                                        PyObject* Py_UNUSED(ignored)) {
510
    dftracer::utils::index::IndexStatus st;
192 ✔
511
    if (!run_indexer(self, IndexerCall::ENSURE, st)) return nullptr;
192 !
512
    return status_dict(st);
192 !
513
}
192 ✔
514

515
static PyObject* Indexer_manifest(IndexerObject* self,
4 ✔
516
                                  PyObject* Py_UNUSED(ignored)) {
517
    std::string json;
4 ✔
518
    if (!with_indexer(self, [&](dftracer::utils::index::Indexer ix) {
4 !
519
            json = dftracer::utils::index::to_json(ix.manifest());
4 !
520
        }))
4 ✔
521
        return nullptr;
×
522
    return PyUnicode_FromStringAndSize(json.data(),
4 !
523
                                       static_cast<Py_ssize_t>(json.size()));
8 ✔
524
}
4 ✔
525

526
static PyObject* Indexer_explain(IndexerObject* self, PyObject* args) {
6 ✔
527
    const char* query = nullptr;
6 ✔
528
    if (!PyArg_ParseTuple(args, "s", &query)) return nullptr;
6 !
529
    std::string json;
6 ✔
530
    if (!with_indexer(self, [&](dftracer::utils::index::Indexer ix) {
6 !
531
            json = dftracer::utils::index::to_json(ix.explain(query));
7 !
532
        }))
5 ✔
533
        return nullptr;
1 ✔
534
    return PyUnicode_FromStringAndSize(json.data(),
5 !
535
                                       static_cast<Py_ssize_t>(json.size()));
10 ✔
536
}
6 ✔
537

538
static PyObject* Indexer_rebuild_extension(IndexerObject* self,
1 ✔
539
                                           PyObject* args) {
540
    const char* name = nullptr;
1 ✔
541
    if (!PyArg_ParseTuple(args, "s", &name)) return nullptr;
1 !
542
    dftracer::utils::index::IndexStatus st;
1 ✔
543
    if (!with_indexer(self, [&](dftracer::utils::index::Indexer ix) {
1 !
544
            st = ix.rebuild_extension(name);
1 !
545
        }))
1 ✔
546
        return nullptr;
×
547
    return status_dict(st);
1 !
548
}
1 ✔
549

550
static PyObject* Indexer_drop_extension(IndexerObject* self, PyObject* args) {
3 ✔
551
    const char* name = nullptr;
3 ✔
552
    if (!PyArg_ParseTuple(args, "s", &name)) return nullptr;
3 !
553
    dftracer::utils::index::IndexStatus st;
3 ✔
554
    if (!with_indexer(self, [&](dftracer::utils::index::Indexer ix) {
3 !
555
            st = ix.drop_extension(name);
4 !
556
        }))
2 ✔
557
        return nullptr;
1 ✔
558
    return status_dict(st);
2 !
559
}
3 ✔
560

561
static PyObject* Indexer_get_checkpoint_indexer(IndexerObject* self,
5 ✔
562
                                                PyObject* args) {
563
    const char* file_path = nullptr;
5 ✔
564
    if (!PyArg_ParseTuple(args, "s", &file_path)) {
5 !
565
        return nullptr;
×
566
    }
567

568
    // Determine index path using BatchIndexer's index_dir setting
569
    const char* index_dir = as_utf8(self->index_dir);
5 !
570
    std::string index_path =
571
        dftracer::utils::trace::internal::determine_index_path(
572
            file_path, index_dir ? index_dir : "");
10 !
573

574
    // Create IndexerObject
575
    CheckpointIndexerObject* indexer =
576
        (CheckpointIndexerObject*)CheckpointIndexerType.tp_alloc(
5 !
577
            &CheckpointIndexerType, 0);
578
    if (!indexer) {
5 !
579
        return nullptr;
×
580
    }
581

582
    indexer->handle = nullptr;
5 ✔
583
    indexer->gz_path = PyUnicode_FromString(file_path);
5 !
584
    indexer->index_path = PyUnicode_FromString(index_path.c_str());
5 !
585
    indexer->checkpoint_size = self->checkpoint_size;
5 ✔
586
    indexer->build_bloom = 0;
5 ✔
587

588
    // Share runtime reference
589
    if (self->runtime_obj) {
5 !
590
        Py_INCREF(self->runtime_obj);
×
591
        indexer->runtime_obj = self->runtime_obj;
×
592
    } else {
593
        indexer->runtime_obj = nullptr;
5 ✔
594
    }
595

596
    // Create the native handle
597
    try {
598
        auto native =
599
            dftracer::utils::index::gzip::CheckpointIndexerFactory::create(
600
                file_path, index_path, self->checkpoint_size, false);
10 !
601
        if (!native) {
5 !
602
            Py_DECREF((PyObject*)indexer);
603
            PyErr_SetString(PyExc_RuntimeError, "Unsupported archive format");
×
604
            return nullptr;
×
605
        }
606
        indexer->handle = new std::shared_ptr<
5 ✔
607
            dftracer::utils::index::gzip::CheckpointIndexer>(std::move(native));
5 !
608
    } catch (const std::exception& e) {
5 !
609
        Py_DECREF((PyObject*)indexer);
610
        PyErr_SetString(PyExc_RuntimeError, e.what());
×
611
        return nullptr;
×
612
    }
×
613

614
    return (PyObject*)indexer;
5 ✔
615
}
5 ✔
616

617
static std::optional<std::string> resolve_index_path(IndexerObject* self) {
5 ✔
618
    PyObject* status = Indexer_resolve(self, nullptr);
5 !
619
    if (!status) return std::nullopt;
5 !
620
    PyObject* obj = PyDict_GetItemString(status, "index_path");
5 !
621
    const char* path = obj ? as_utf8(obj) : nullptr;
5 !
622
    if (!path || path[0] == '\0') {
5 !
623
        Py_DECREF(status);
624
        PyErr_SetString(PyExc_RuntimeError, "No index path available");
×
625
        return std::nullopt;
×
626
    }
627
    std::string result(path);
10 !
628
    Py_DECREF(status);
629
    return result;
5 ✔
630
}
5 ✔
631

632
static PyObject* Indexer_rowset(IndexerObject* self, PyObject* args) {
5 ✔
633
    const char* name = nullptr;
5 ✔
634
    if (!PyArg_ParseTuple(args, "s", &name)) return nullptr;
5 !
635
    dftracer::utils::dataframe::DataFrame frame;
5 ✔
636
    if (!with_indexer(self, [&](dftracer::utils::index::Indexer ix) {
5 !
637
            frame = ix.rowset(name);
6 !
638
        }))
4 ✔
639
        return nullptr;
1 ✔
640
    return dftracer::utils::python::wrap_dataframe(std::move(frame));
4 !
641
}
5 ✔
642

643
static PyObject* Indexer_query_file_pids(IndexerObject* self, PyObject* args) {
2 ✔
644
    int file_id;
645
    if (!PyArg_ParseTuple(args, "i", &file_id)) {
2 !
646
        return nullptr;
×
647
    }
648

649
    using dftracer::utils::index::store::IndexDatabase;
650

651
    auto idx_opt = resolve_index_path(self);
2 !
652
    if (!idx_opt) return nullptr;
2 !
653
    std::string index_path = std::move(*idx_opt);
2 ✔
654

655
    ankerl::unordered_dense::set<std::uint64_t> pids;
2 !
656
    if (!run_blocking_r(
2 !
657
            [&] {
2 ✔
658
                IndexDatabase db(
659
                    index_path,
2 ✔
660
                    dftracer::utils::index::store::IndexOpenMode::ReadOnly);
2 !
661
                return db.query_file_pids(file_id);
4 !
662
            },
2 ✔
663
            pids)) {
664
        return nullptr;
×
665
    }
666

667
    PyObject* set = PySet_New(nullptr);
2 !
668
    if (!set) return nullptr;
2 !
669

670
    for (auto pid : pids) {
3 ✔
671
        PyObject* val = PyLong_FromUnsignedLongLong(pid);
1 !
672
        PySet_Add(set, val);
1 !
673
        Py_DECREF(val);
674
    }
675

676
    return set;
2 ✔
677
}
2 ✔
678

679
static PyObject* Indexer_query_all_file_pids(IndexerObject* self,
3 ✔
680
                                             PyObject* Py_UNUSED(ignored)) {
681
    using dftracer::utils::index::store::IndexDatabase;
682

683
    auto idx_opt = resolve_index_path(self);
3 !
684
    if (!idx_opt) return nullptr;
3 !
685
    std::string index_path = std::move(*idx_opt);
3 ✔
686

687
    ankerl::unordered_dense::map<int,
688
                                 ankerl::unordered_dense::set<std::uint64_t>>
689
        all_pids;
3 !
690
    if (!run_blocking_r(
3 !
691
            [&] {
3 ✔
692
                IndexDatabase db(
693
                    index_path,
3 ✔
694
                    dftracer::utils::index::store::IndexOpenMode::ReadOnly);
3 !
695
                return db.query_all_file_pids();
6 !
696
            },
3 ✔
697
            all_pids)) {
698
        return nullptr;
×
699
    }
700

701
    PyObject* dict = PyDict_New();
3 !
702
    if (!dict) return nullptr;
3 !
703

704
    for (const auto& [file_id, pids] : all_pids) {
7 ✔
705
        PyObject* key = PyLong_FromLong(file_id);
4 !
706
        PyObject* set = PySet_New(nullptr);
4 !
707
        for (auto pid : pids) {
11 ✔
708
            PyObject* val = PyLong_FromUnsignedLongLong(pid);
7 !
709
            PySet_Add(set, val);
7 !
710
            Py_DECREF(val);
711
        }
712
        PyDict_SetItem(dict, key, set);
4 !
713
        Py_DECREF(key);
714
        Py_DECREF(set);
715
    }
716

717
    return dict;
3 ✔
718
}
3 ✔
719

720
static PyObject* Indexer_query_file_info(IndexerObject* self,
×
721
                                         PyObject* Py_UNUSED(ignored)) {
722
    using dftracer::utils::index::store::IndexDatabase;
723

724
    auto idx_opt = resolve_index_path(self);
×
725
    if (!idx_opt) return nullptr;
×
726
    std::string index_path = std::move(*idx_opt);
×
727

728
    dftracer::utils::StringViewMap<int> file_ids;
×
729
    ankerl::unordered_dense::map<int,
730
                                 ankerl::unordered_dense::set<std::uint64_t>>
731
        all_pids;
×
732

733
    if (!run_blocking([&] {
×
734
            IndexDatabase db(
735
                index_path,
×
736
                dftracer::utils::index::store::IndexOpenMode::ReadOnly);
×
737
            file_ids = db.query_all_file_info_ids();
×
738
            all_pids = db.query_all_file_pids();
×
739
        })) {
×
740
        return nullptr;
×
741
    }
742

743
    auto data_dir = fs::weakly_canonical(fs::path(index_path)).parent_path();
×
744

745
    PyObject* id_to_path = PyDict_New();
×
746
    if (!id_to_path) return nullptr;
×
747
    for (const auto& [logical_name, fid] : file_ids) {
×
748
        auto resolved = (data_dir / logical_name).string();
×
749
        PyObject* key = PyLong_FromLong(fid);
×
750
        PyObject* val = PyUnicode_FromStringAndSize(
×
751
            resolved.data(), static_cast<Py_ssize_t>(resolved.size()));
×
752
        PyDict_SetItem(id_to_path, key, val);
×
753
        Py_DECREF(key);
754
        Py_DECREF(val);
755
    }
×
756

757
    PyObject* pid_dict = PyDict_New();
×
758
    if (!pid_dict) {
×
759
        Py_DECREF(id_to_path);
760
        return nullptr;
×
761
    }
762
    for (const auto& [file_id, pids] : all_pids) {
×
763
        PyObject* key = PyLong_FromLong(file_id);
×
764
        PyObject* set = PySet_New(nullptr);
×
765
        for (auto pid : pids) {
×
766
            PyObject* val = PyLong_FromUnsignedLongLong(pid);
×
767
            PySet_Add(set, val);
×
768
            Py_DECREF(val);
769
        }
770
        PyDict_SetItem(pid_dict, key, set);
×
771
        Py_DECREF(key);
772
        Py_DECREF(set);
773
    }
774

775
    PyObject* result = PyTuple_Pack(2, id_to_path, pid_dict);
×
776
    Py_DECREF(id_to_path);
777
    Py_DECREF(pid_dict);
778
    return result;
×
779
}
×
780

781
static PyMethodDef Indexer_methods[] = {
782
    {"get_checkpoint_indexer", DFTU_PYCFUNCTION(Indexer_get_checkpoint_indexer),
783
     METH_VARARGS,
784
     "get_checkpoint_indexer(file_path)\n"
785
     "--\n\n"
786
     "Get a checkpoint indexer for a specific file.\n\n"
787
     "Args:\n"
788
     "    file_path: Path to the trace file (.pfw/.pfw.gz)\n\n"
789
     "Returns:\n"
790
     "    Indexer instance for checkpoint-level operations.\n"},
791
    {"resolve", DFTU_PYCFUNCTION(Indexer_resolve), METH_NOARGS,
792
     "resolve()\n"
793
     "--\n\n"
794
     "Check what files exist vs need indexing.\n\n"
795
     "Returns:\n"
796
     "    dict with 'total_files', 'ready', 'needs_work', 'index_path'\n"},
797
    {"build", DFTU_PYCFUNCTION(Indexer_build), METH_NOARGS,
798
     "build()\n"
799
     "--\n\n"
800
     "Build all missing index tiers based on require_* flags.\n"},
801
    {"ensure_indexed", DFTU_PYCFUNCTION(Indexer_ensure_indexed), METH_NOARGS,
802
     "ensure_indexed()\n"
803
     "--\n\n"
804
     "Resolve and build if needed.\n\n"
805
     "Returns:\n"
806
     "    dict with index status after building.\n"},
807
    {"manifest", DFTU_PYCFUNCTION(Indexer_manifest), METH_NOARGS,
808
     "manifest()\n"
809
     "--\n\n"
810
     "The manifest of every indexed file, as a JSON string.\n"},
811
    {"explain", DFTU_PYCFUNCTION(Indexer_explain), METH_VARARGS,
812
     "explain(query)\n"
813
     "--\n\n"
814
     "Per file, the chunks the query reads and what each pruning extension\n"
815
     "rules out alone, as a JSON string.\n"},
816
    {"rebuild_extension", DFTU_PYCFUNCTION(Indexer_rebuild_extension),
817
     METH_VARARGS,
818
     "rebuild_extension(name)\n"
819
     "--\n\n"
820
     "Rewrite one tier extension of every file; returns the status dict.\n"},
821
    {"drop_extension", DFTU_PYCFUNCTION(Indexer_drop_extension), METH_VARARGS,
822
     "drop_extension(name)\n"
823
     "--\n\n"
824
     "Remove one tier extension from every file; returns the status dict.\n"},
825
    {"rowset", DFTU_PYCFUNCTION(Indexer_rowset), METH_VARARGS,
826
     "rowset(name)\n"
827
     "--\n\n"
828
     "The rows the index build stored for row set `name` of the source\n"
829
     "(for example 'files'), as a DataFrame.\n"},
830
    {"query_file_pids", DFTU_PYCFUNCTION(Indexer_query_file_pids), METH_VARARGS,
831
     "query_file_pids(file_id)\n"
832
     "--\n\n"
833
     "Query PIDs observed in a specific file.\n\n"
834
     "Args:\n"
835
     "    file_id: Integer file ID from index.\n\n"
836
     "Returns:\n"
837
     "    set of PIDs.\n"},
838
    {"query_all_file_pids", DFTU_PYCFUNCTION(Indexer_query_all_file_pids),
839
     METH_NOARGS,
840
     "query_all_file_pids()\n"
841
     "--\n\n"
842
     "Query PIDs for all indexed files.\n\n"
843
     "Returns:\n"
844
     "    dict mapping file_id to set of PIDs.\n"},
845
    {"query_file_info", DFTU_PYCFUNCTION(Indexer_query_file_info), METH_NOARGS,
846
     "query_file_info()\n"
847
     "--\n\n"
848
     "Query file ID to path mapping and per-file PIDs in one call.\n\n"
849
     "Returns:\n"
850
     "    tuple of (dict[int, str], dict[int, set[int]]).\n"},
851
    {nullptr}};
852

853
static PyGetSetDef Indexer_getsetters[] = {{nullptr}};
854

855
PyTypeObject IndexerType = {
856
    PyVarObject_HEAD_INIT(nullptr, 0) "dftracer_utils_ext.Indexer",
857
    sizeof(IndexerObject),
858
    0,
859
    (destructor)Indexer_dealloc,
860
    0,
861
    0,
862
    0,
863
    0,
864
    0,
865
    0,
866
    0,
867
    0,
868
    0,
869
    0,
870
    0,
871
    0,
872
    0,
873
    0,
874
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
875
    "BatchIndexer(directory='', files=None, index_dir='',\n"
876
    "             require_checkpoint=True, require_bloom=True,\n"
877
    "             time_interval_ms=5000.0, group_keys=None,\n"
878
    "             custom_metric_fields=None, compute_percentiles=False,\n"
879
    "             parallelism=0, force_rebuild=False, runtime=None)\n"
880
    "--\n\n"
881
    "Indexer with tiered index building.\n\n"
882
    "At least one of 'directory' or 'files' must be provided.\n"
883
    "- directory: scan for .pfw/.jsonl/.ndjson/.json files, plain or gzip\n"
884
    "- files: list of specific file paths\n\n"
885
    "Supports:\n"
886
    "- Tier 1: Checkpoints (require_checkpoint)\n"
887
    "- Tier 2: Bloom filters (require_bloom)\n"
888
    "- Tier 3: Aggregation (require_aggregation + config params)\n",
889
    0,
890
    0,
891
    0,
892
    0,
893
    0,
894
    0,
895
    Indexer_methods,
896
    0,
897
    Indexer_getsetters,
898
    0,
899
    0,
900
    0,
901
    0,
902
    0,
903
    (initproc)Indexer_init,
904
    0,
905
    Indexer_new,
906
};
907

908
namespace {
909

910
template <class Fn>
911
PyObject* schema_str(Fn fn) {
34 ✔
912
    try {
913
        const std::string s = fn();
34 ✔
914
        return PyUnicode_FromStringAndSize(s.data(),
27 !
915
                                           static_cast<Py_ssize_t>(s.size()));
54 ✔
916
    } catch (const std::exception& e) {
34 !
917
        dftracer::utils::python::set_typed_py_error(e);
7 !
918
        return nullptr;
7 ✔
919
    }
920
}
921

922
PyObject* schema_register_fn(PyObject*, PyObject* args) {
19 ✔
923
    const char* text = nullptr;
19 ✔
924
    const char* source = "<text>";
19 ✔
925
    if (!PyArg_ParseTuple(args, "s|s", &text, &source)) return nullptr;
19 !
926
    return schema_str([&] {
19 !
927
        return dftracer::utils::index::register_schema(text, source).id;
31 !
928
    });
19 ✔
929
}
930

931
PyObject* schema_load_fn(PyObject*, PyObject* args) {
1 ✔
932
    const char* path = nullptr;
1 ✔
933
    if (!PyArg_ParseTuple(args, "s", &path)) return nullptr;
1 !
934
    return schema_str([&] {
1 !
935
        dftracer::utils::index::load_schemas(path);
1 !
936
        return dftracer::utils::index::schemas_json();
1 ✔
937
    });
1 ✔
938
}
939

940
PyObject* schema_list_fn(PyObject*, PyObject*) {
11 ✔
941
    return schema_str([] { return dftracer::utils::index::schemas_json(); });
22 ✔
942
}
943

944
PyObject* schema_detect_fn(PyObject*, PyObject* args) {
2 ✔
945
    const char* path = nullptr;
2 ✔
946
    if (!PyArg_ParseTuple(args, "s", &path)) return nullptr;
2 !
947
    return schema_str(
2 !
948
        [&] { return dftracer::utils::index::detect_file_schema(path).id; });
6 !
949
}
950

951
PyObject* schema_explain_fn(PyObject*, PyObject* args) {
1 ✔
952
    const char* path = nullptr;
1 ✔
953
    if (!PyArg_ParseTuple(args, "s", &path)) return nullptr;
1 !
954
    return schema_str([&] {
1 !
955
        return dftracer::utils::index::to_json(
956
            dftracer::utils::index::explain_file_schema(path));
2 !
957
    });
1 ✔
958
}
959

960
PyMethodDef SCHEMA_METHODS[] = {
961
    {"_schema_register", schema_register_fn, METH_VARARGS,
962
     "_schema_register(text, source='<text>')\n--\n\nRegister a YAML or "
963
     "JSON schema spec; returns its id.\n"},
964
    {"_schema_load", schema_load_fn, METH_VARARGS,
965
     "_schema_load(path)\n--\n\nRegister every spec at a file or "
966
     "directory; returns the registered schemas as JSON.\n"},
967
    {"_schema_list", schema_list_fn, METH_NOARGS,
968
     "_schema_list()\n--\n\nThe registered schemas as JSON.\n"},
969
    {"_schema_detect", schema_detect_fn, METH_VARARGS,
970
     "_schema_detect(path)\n--\n\nThe schema detected for a trace.\n"},
971
    {"_schema_explain", schema_explain_fn, METH_VARARGS,
972
     "_schema_explain(path)\n--\n\nEvery schema's detection share for a "
973
     "trace and the chosen one, as JSON.\n"},
974
    {nullptr, nullptr, 0, nullptr}};
975

976
}  // namespace
977

978
int dftracer::utils::python::init_indexer(PyObject* m) {
7 ✔
979
    if (register_type(m, &IndexerType, "Indexer") < 0) return -1;
7 !
980
    if (PyModule_AddFunctions(m, SCHEMA_METHODS) < 0) return -1;
7 !
981

982
    return 0;
7 ✔
983
}
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