• 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

0.51
/src/dftracer/utils/python/sst_distribution.cpp
1
#include <dftracer/utils/core/common/constants.h>
2
#include <dftracer/utils/core/runtime.h>
3
#include <dftracer/utils/core/tasks/coro_scope.h>
4
#include <dftracer/utils/index/build/batch_builder.h>
5
#include <dftracer/utils/index/build/file_partition.h>
6
#include <dftracer/utils/index/gzip/gzip_member_scanner.h>
7
#include <dftracer/utils/index/schemas/dft/agg/aggregation_config.h>
8
#include <dftracer/utils/index/schemas/dft/agg/aggregation_fold.h>
9
#include <dftracer/utils/index/schemas/dft/agg/aggregation_key.h>
10
#include <dftracer/utils/index/schemas/dft/agg/association_tracker.h>
11
#include <dftracer/utils/index/store/index_database_sst_writer_context.h>
12
#include <dftracer/utils/index/store/index_write.h>
13
#include <dftracer/utils/index/store/layout.h>
14
#include <dftracer/utils/python/py_agg_config.h>
15
#include <dftracer/utils/python/py_errors.h>
16
#include <dftracer/utils/python/py_method.h>
17
#include <dftracer/utils/python/py_runtime_mixin.h>
18
#include <dftracer/utils/python/py_seq_helpers.h>
19
#include <dftracer/utils/python/py_str_helpers.h>
20
#include <dftracer/utils/python/py_type_helpers.h>
21
#include <dftracer/utils/python/runtime.h>
22
#include <dftracer/utils/python/sst_distribution.h>
23
#include <dftracer/utils/utilities/filesystem/pattern_directory_scanner_utility.h>
24
#include <fcntl.h>
25
#include <sys/stat.h>
26
#include <unistd.h>
27

28
#include <algorithm>
29
#include <atomic>
30
#include <cstdint>
31
#include <memory>
32
#include <mutex>
33
#include <new>
34
#include <optional>
35
#include <string>
36
#include <unordered_set>
37
#include <vector>
38

39
using dftracer::utils::Runtime;
40
using dftracer::utils::index::build::BatchBuilder;
41
using dftracer::utils::index::build::IndexBuildBatchConfig;
42
using dftracer::utils::index::build::IndexBuildBatchResult;
43
using dftracer::utils::index::build::plan_lpt_partition;
44
using dftracer::utils::index::gzip::enumerate_gzip_member_candidates;
45
using dftracer::utils::index::gzip::GzipMember;
46
using dftracer::utils::index::store::IndexDatabaseSstWriterContext;
47
using dftracer::utils::index::store::IndexWrite;
48
using dftracer::utils::index::store::SstArtifactRegistry;
49
using dftracer::utils::python::parse_string_seq;
50
using dftracer::utils::utilities::filesystem::FileEntry;
51
using dftracer::utils::utilities::filesystem::PatternDirectoryScannerUtility;
52
using dftracer::utils::utilities::filesystem::
53
    PatternDirectoryScannerUtilityInput;
54

55
// ---------------------------------------------------------------------------
56
// SstArtifactRegistry type
57
// ---------------------------------------------------------------------------
58

59
typedef struct {
60
    PyObject_HEAD std::shared_ptr<SstArtifactRegistry> registry;
61
} SstArtifactRegistryObject;
62

63
static void SstArtifactRegistry_dealloc(SstArtifactRegistryObject *self) {
×
64
    self->registry.~shared_ptr<SstArtifactRegistry>();
×
65
    Py_TYPE(self)->tp_free((PyObject *)self);
×
66
}
×
67

68
static PyObject *SstArtifactRegistry_new(PyTypeObject *type,
×
69
                                         PyObject * /*args*/,
70
                                         PyObject * /*kwds*/) {
71
    auto *self = (SstArtifactRegistryObject *)type->tp_alloc(type, 0);
×
72
    if (!self) return NULL;
×
73
    new (&self->registry) std::shared_ptr<SstArtifactRegistry>(
×
74
        std::make_shared<SstArtifactRegistry>());
×
75
    return (PyObject *)self;
×
76
}
77

78
namespace {
79

80
// Artifacts dicts map "<family>_sst" to an SST path (or None), one entry per
81
// layout::Family.
82
std::string artifact_field(std::size_t family) {
×
83
    return std::string(dftracer::utils::index::store::layout::family_name(
×
84
               static_cast<dftracer::utils::index::store::layout::Family>(
85
                   family))) +
86
           "_sst";
×
87
}
88

89
/// Convert a Python artifacts dict to the C++ Artifacts struct. Missing,
90
/// None, or empty-string entries become nullopt. Returns false on type
91
/// errors (exception set).
92
bool artifacts_from_dict(PyObject *dict,
×
93
                         IndexDatabaseSstWriterContext::Artifacts *out) {
94
    if (!PyDict_Check(dict)) {
×
95
        PyErr_SetString(PyExc_TypeError, "artifacts must be a dict");
×
96
        return false;
×
97
    }
98
    for (std::size_t f = 0; f < out->sst.size(); ++f) {
×
99
        const auto field = artifact_field(f);
×
100
        PyObject *val = PyDict_GetItemString(dict, field.c_str());  // borrowed
×
101
        if (!val || val == Py_None) continue;
×
102
        if (!PyUnicode_Check(val)) {
×
103
            PyErr_Format(PyExc_TypeError, "artifacts['%s'] must be str or None",
×
104
                         field.c_str());
105
            return false;
×
106
        }
107
        const char *s = as_utf8(val);
×
108
        if (!s) return false;
×
109
        if (s[0] == '\0') continue;
×
110
        out->sst[f] = std::string(s);
×
111
    }
×
112
    return true;
×
113
}
114

115
PyObject *artifacts_to_dict(const IndexDatabaseSstWriterContext::Artifacts &a) {
×
116
    PyObject *dict = PyDict_New();
×
117
    if (!dict) return NULL;
×
118
    for (std::size_t f = 0; f < a.sst.size(); ++f) {
×
119
        const auto &slot = a.sst[f];
×
120
        PyObject *v = slot.has_value() ? PyUnicode_FromString(slot->c_str())
×
121
                                       : (Py_INCREF(Py_None), Py_None);
×
122
        if (!v ||
×
123
            PyDict_SetItemString(dict, artifact_field(f).c_str(), v) != 0) {
×
124
            Py_XDECREF(v);
×
125
            Py_DECREF(dict);
126
            return NULL;
×
127
        }
128
        Py_DECREF(v);
129
    }
130
    return dict;
×
131
}
132

133
}  // namespace
134

135
static PyObject *SstArtifactRegistry_append(SstArtifactRegistryObject *self,
×
136
                                            PyObject *args) {
137
    PyObject *dict;
138
    if (!PyArg_ParseTuple(args, "O", &dict)) return NULL;
×
139
    IndexDatabaseSstWriterContext::Artifacts a;
×
140
    if (!artifacts_from_dict(dict, &a)) return NULL;
×
141
    self->registry->append(std::move(a));
×
142
    Py_RETURN_NONE;
×
143
}
×
144

145
static PyMethodDef SstArtifactRegistry_methods[] = {
146
    {"append", DFTU_PYCFUNCTION(SstArtifactRegistry_append), METH_VARARGS,
147
     "append(artifacts_dict) -> None\n"
148
     "Add a per-batch Artifacts dict (as returned by build_sst_batch or "
149
     "IndexDatabaseSstWriterContext.commit) to the registry."},
150
    {NULL}};
151

152
static PyTypeObject SstArtifactRegistryType = {
153
    PyVarObject_HEAD_INIT(NULL, 0) "dftracer_utils_ext.SstArtifactRegistry",
154
    sizeof(SstArtifactRegistryObject),
155
    0,
156
    (destructor)SstArtifactRegistry_dealloc,
157
    0,
158
    0,
159
    0,
160
    0,
161
    0,
162
    0,
163
    0,
164
    0,
165
    0,
166
    0,
167
    0,
168
    0,
169
    0,
170
    0,
171
    Py_TPFLAGS_DEFAULT,
172
    "Thread-safe collector for SST artifact paths.",
173
    0,
174
    0,
175
    0,
176
    0,
177
    0,
178
    0,
179
    SstArtifactRegistry_methods,
180
    0,
181
    0,
182
    0,
183
    0,
184
    0,
185
    0,
186
    0,
187
    0,
188
    0,
189
    SstArtifactRegistry_new,
190
};
191

192
SstArtifactRegistry *dftracer::utils::python::sst_artifact_registry_get(
×
193
    PyObject *obj) {
194
    if (!PyObject_TypeCheck(obj, &SstArtifactRegistryType)) return nullptr;
×
195
    return ((SstArtifactRegistryObject *)obj)->registry.get();
×
196
}
197

198
// ---------------------------------------------------------------------------
199
// scan_files: parallel directory scan with size info
200
// ---------------------------------------------------------------------------
201

202
static PyObject *scan_files_fn(PyObject * /*self*/, PyObject *args,
×
203
                               PyObject *kwds) {
204
    static const char *kwlist[] = {"directory", "patterns", "recursive",
205
                                   "runtime", NULL};
206
    const char *directory;
207
    PyObject *patterns_obj = NULL;
×
208
    int recursive = 0;
×
209
    PyObject *runtime_arg = NULL;
×
210
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OpO",
×
211
                                     const_cast<char **>(kwlist), &directory,
212
                                     &patterns_obj, &recursive, &runtime_arg)) {
213
        return NULL;
×
214
    }
215

216
    std::vector<std::string> patterns;
×
217
    if (patterns_obj && patterns_obj != Py_None) {
×
218
        if (!parse_string_seq(patterns_obj, "patterns must be a sequence",
×
219
                              patterns))
220
            return NULL;
×
221
    }
222

223
    Runtime *rt = nullptr;
×
224
    if (runtime_arg && runtime_arg != Py_None) {
×
225
        if (!PyObject_TypeCheck(runtime_arg, &RuntimeType)) {
×
226
            PyObject *native = PyObject_GetAttrString(runtime_arg, "_native");
×
227
            if (!native || !PyObject_TypeCheck(native, &RuntimeType)) {
×
228
                Py_XDECREF(native);
×
229
                PyErr_SetString(PyExc_TypeError,
×
230
                                "runtime must be a Runtime instance or None");
231
                return NULL;
×
232
            }
233
            rt = ((RuntimeObject *)native)->runtime.get();
×
234
            Py_DECREF(native);
235
        } else {
236
            rt = ((RuntimeObject *)runtime_arg)->runtime.get();
×
237
        }
238
    } else {
×
239
        rt = dftracer::utils::python::get_default_runtime();
×
240
    }
241

242
    PatternDirectoryScannerUtilityInput input(directory, patterns,
243
                                              recursive != 0, true);
×
244
    std::vector<FileEntry> entries;
×
245
    if (!run_blocking([&] {
×
246
            rt->submit(dftracer::utils::run_coro_scope(
×
247
                           rt->executor(),
×
248
                           [](dftracer::utils::CoroScope &scope,
×
249
                              PatternDirectoryScannerUtilityInput in,
250
                              std::vector<FileEntry> *out)
251
                               -> dftracer::utils::coro::CoroTask<void> {
252
                               PatternDirectoryScannerUtility scanner;
253
                               *out = co_await scanner(scope, in);
254
                           },
×
255
                           std::move(input), &entries),
×
256
                       "scan-files")
257
                .get();
×
258
        })) {
×
259
        return NULL;
×
260
    }
261

262
    PyObject *out = PyList_New(static_cast<Py_ssize_t>(entries.size()));
×
263
    if (!out) return NULL;
×
264
    for (std::size_t i = 0; i < entries.size(); ++i) {
×
265
        PyObject *t = Py_BuildValue("(sn)", entries[i].path.c_str(),
×
266
                                    (Py_ssize_t)entries[i].size);
×
267
        if (!t) {
×
268
            Py_DECREF(out);
269
            return NULL;
×
270
        }
271
        PyList_SET_ITEM(out, i, t);
×
272
    }
273
    return out;
×
274
}
×
275

276
// ---------------------------------------------------------------------------
277
// plan_lpt_partition: LPT bin-packing of (path, size) pairs
278
// ---------------------------------------------------------------------------
279

280
static PyObject *plan_lpt_partition_fn(PyObject * /*self*/, PyObject *args) {
×
281
    PyObject *entries_obj;
282
    Py_ssize_t num_workers;
283
    if (!PyArg_ParseTuple(args, "On", &entries_obj, &num_workers)) return NULL;
×
284
    if (num_workers <= 0) num_workers = 1;
×
285

286
    std::vector<FileEntry> entries;
×
287
    PyObject *seq = PySequence_Fast(entries_obj,
×
288
                                    "entries must be a sequence of "
289
                                    "(path, size) tuples");
290
    if (!seq) return NULL;
×
291
    Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
×
292
    entries.reserve(n);
×
293
    for (Py_ssize_t i = 0; i < n; ++i) {
×
294
        PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
×
295
        const char *path = nullptr;
×
296
        Py_ssize_t size = 0;
×
297
        if (!PyArg_ParseTuple(item, "sn", &path, &size)) {
×
298
            Py_DECREF(seq);
299
            return NULL;
×
300
        }
301
        FileEntry fe;
×
302
        fe.path = path;
×
303
        fe.size = static_cast<std::size_t>(size);
×
304
        fe.is_regular_file = true;
×
305
        entries.push_back(std::move(fe));
×
306
    }
×
307
    Py_DECREF(seq);
308

309
    auto buckets = plan_lpt_partition(std::move(entries),
×
310
                                      static_cast<std::size_t>(num_workers));
×
311

312
    PyObject *out = PyList_New(static_cast<Py_ssize_t>(buckets.size()));
×
313
    if (!out) return NULL;
×
314
    for (std::size_t i = 0; i < buckets.size(); ++i) {
×
315
        PyObject *lst = PyList_New(static_cast<Py_ssize_t>(buckets[i].size()));
×
316
        if (!lst) {
×
317
            Py_DECREF(out);
318
            return NULL;
×
319
        }
320
        for (std::size_t j = 0; j < buckets[i].size(); ++j) {
×
321
            PyObject *t = Py_BuildValue("(sn)", buckets[i][j].path.c_str(),
×
322
                                        (Py_ssize_t)buckets[i][j].size);
×
323
            if (!t) {
×
324
                Py_DECREF(lst);
325
                Py_DECREF(out);
326
                return NULL;
×
327
            }
328
            PyList_SET_ITEM(lst, j, t);
×
329
        }
330
        PyList_SET_ITEM(out, i, lst);
×
331
    }
332
    return out;
×
333
}
×
334

335
// ---------------------------------------------------------------------------
336
// build_sst_batch: run the indexer pipeline with an SST sink and return
337
// the merged Artifacts dict.
338
// ---------------------------------------------------------------------------
339

340
static PyObject *build_sst_batch_fn(PyObject * /*self*/, PyObject *args,
×
341
                                    PyObject *kwds) {
342
    static const char *kwlist[] = {"files",
343
                                   "file_ids",
344
                                   "staging_dir",
345
                                   "batch_id",
346
                                   "index_dir",
347
                                   "checkpoint_size",
348
                                   "force_rebuild",
349
                                   "build_bloom",
350
                                   "bloom_dimensions",
351
                                   "parallelism",
352
                                   "flush_every_files",
353
                                   "runtime",
354
                                   "aggregation_config",
355
                                   "file_slices",
356
                                   "progress",
357
                                   NULL};
358
    PyObject *files_obj;
359
    PyObject *file_ids_obj;
360
    const char *staging_dir;
361
    const char *batch_id;
362
    const char *index_dir = "";
×
363
    Py_ssize_t checkpoint_size = static_cast<Py_ssize_t>(
×
364
        dftracer::utils::constants::indexer::DEFAULT_CHECKPOINT_SIZE);
365
    int force_rebuild = 0;
×
366
    int build_bloom = 1;
×
367
    PyObject *bloom_dims_obj = NULL;
×
368
    Py_ssize_t parallelism = 0;
×
369
    Py_ssize_t flush_every_files = 0;
×
370
    PyObject *runtime_arg = NULL;
×
371
    PyObject *aggregation_config_obj = NULL;
×
372
    PyObject *file_slices_obj = NULL;
×
373
    PyObject *progress_obj = NULL;
×
374

375
    if (!PyArg_ParseTupleAndKeywords(
×
376
            args, kwds, "OOss|snppOnnOOOO", const_cast<char **>(kwlist),
377
            &files_obj, &file_ids_obj, &staging_dir, &batch_id, &index_dir,
378
            &checkpoint_size, &force_rebuild, &build_bloom, &bloom_dims_obj,
379
            &parallelism, &flush_every_files, &runtime_arg,
380
            &aggregation_config_obj, &file_slices_obj, &progress_obj)) {
381
        return NULL;
×
382
    }
383

384
    // Unpack files.
385
    std::vector<std::string> files;
×
386
    {
387
        if (!parse_string_seq(files_obj, "files must be a sequence", files))
×
388
            return NULL;
×
389
    }
390
    if (files.empty()) {
×
391
        return PyDict_New();
×
392
    }
393

394
    // Unpack file_ids, parallel to files.
395
    std::vector<int> file_ids;
×
396
    {
397
        PyObject *seq =
398
            PySequence_Fast(file_ids_obj, "file_ids must be a sequence");
×
399
        if (!seq) return NULL;
×
400
        Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
×
401
        if (static_cast<std::size_t>(n) != files.size()) {
×
402
            Py_DECREF(seq);
403
            PyErr_SetString(PyExc_ValueError,
×
404
                            "file_ids must have the same length as files");
405
            return NULL;
×
406
        }
407
        file_ids.reserve(n);
×
408
        for (Py_ssize_t i = 0; i < n; ++i) {
×
409
            long v = PyLong_AsLong(PySequence_Fast_GET_ITEM(seq, i));
×
410
            if (v == -1 && PyErr_Occurred()) {
×
411
                Py_DECREF(seq);
412
                return NULL;
×
413
            }
414
            file_ids.push_back(static_cast<int>(v));
×
415
        }
416
        Py_DECREF(seq);
417
    }
418

419
    // Optional bloom dimensions override.
420
    std::vector<std::string> bloom_dims;
×
421
    if (bloom_dims_obj && bloom_dims_obj != Py_None) {
×
422
        if (!parse_string_seq(bloom_dims_obj,
×
423
                              "bloom_dimensions must be a sequence",
424
                              bloom_dims))
425
            return NULL;
×
426
    }
427

428
    // Resolve Runtime (matching CheckpointIndexer pattern).
429
    Runtime *rt = nullptr;
×
430
    if (runtime_arg && runtime_arg != Py_None) {
×
431
        if (PyObject_TypeCheck(runtime_arg, &RuntimeType)) {
×
432
            rt = ((RuntimeObject *)runtime_arg)->runtime.get();
×
433
        } else {
434
            PyObject *native = PyObject_GetAttrString(runtime_arg, "_native");
×
435
            if (!native || !PyObject_TypeCheck(native, &RuntimeType)) {
×
436
                Py_XDECREF(native);
×
437
                PyErr_SetString(PyExc_TypeError,
×
438
                                "runtime must be a Runtime instance or None");
439
                return NULL;
×
440
            }
441
            rt = ((RuntimeObject *)native)->runtime.get();
×
442
            Py_DECREF(native);
443
        }
444
    } else {
×
445
        rt = dftracer::utils::python::get_default_runtime();
×
446
    }
447

448
    // Build config + sink factory shared state.
449
    struct SharedArtifacts {
450
        std::mutex mu;
451
        std::vector<IndexDatabaseSstWriterContext::Artifacts> list;
452
    };
453
    auto artifacts = std::make_shared<SharedArtifacts>();
×
454
    auto staging = std::string(staging_dir);
×
455
    auto batch = std::string(batch_id);
×
456

457
    // Optional aggregation config, extracted from the Python dataclass.
458
    std::shared_ptr<
459
        dftracer::utils::index::schemas::dft::agg::AggregationConfig>
460
        agg_config_ptr;
×
461
    if (aggregation_config_obj && aggregation_config_obj != Py_None)
×
462
        agg_config_ptr = std::make_shared<
463
            dftracer::utils::index::schemas::dft::agg::AggregationConfig>(
×
464
            dftracer::utils::python::agg_config_from_py(
×
465
                aggregation_config_obj));
×
466

467
    // owned_member_maps must outlive rt->submit: FileSlice::members is raw.
468
    std::vector<std::vector<GzipMember>> owned_member_maps;
×
469
    std::vector<IndexBuildBatchConfig::FileSlice> parsed_slices;
×
470
    if (file_slices_obj && file_slices_obj != Py_None) {
×
471
        PyObject *seq =
472
            PySequence_Fast(file_slices_obj, "file_slices must be a sequence");
×
473
        if (!seq) return NULL;
×
474
        Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
×
475
        if (static_cast<std::size_t>(n) != files.size()) {
×
476
            Py_DECREF(seq);
477
            PyErr_SetString(PyExc_ValueError,
×
478
                            "file_slices must match files length");
479
            return NULL;
×
480
        }
481
        owned_member_maps.resize(n);
×
482
        parsed_slices.resize(n);
×
483
        for (Py_ssize_t i = 0; i < n; ++i) {
×
484
            PyObject *entry = PySequence_Fast_GET_ITEM(seq, i);
×
485
            if (entry == Py_None) {
×
486
                continue;  // leave slice default-constructed (members=null)
×
487
            }
488
            Py_ssize_t mb = 0, me = 0;
×
489
            int skip_scoped = 0;
×
490
            PyObject *members_obj = nullptr;
×
491
            if (!PyArg_ParseTuple(entry, "nnpO", &mb, &me, &skip_scoped,
×
492
                                  &members_obj)) {
493
                Py_DECREF(seq);
494
                return NULL;
×
495
            }
496
            PyObject *mseq = PySequence_Fast(
×
497
                members_obj, "file_slices[i].members must be a sequence");
498
            if (!mseq) {
×
499
                Py_DECREF(seq);
500
                return NULL;
×
501
            }
502
            Py_ssize_t mn = PySequence_Fast_GET_SIZE(mseq);
×
503
            auto &mv = owned_member_maps[i];
×
504
            mv.resize(mn);
×
505
            for (Py_ssize_t j = 0; j < mn; ++j) {
×
506
                PyObject *m = PySequence_Fast_GET_ITEM(mseq, j);
×
507
                unsigned long long c_offset = 0, c_size = 0;
×
508
                if (!PyArg_ParseTuple(m, "KK", &c_offset, &c_size)) {
×
509
                    Py_DECREF(mseq);
510
                    Py_DECREF(seq);
511
                    return NULL;
×
512
                }
513
                mv[j].c_offset = static_cast<std::uint64_t>(c_offset);
×
514
                mv[j].c_size = static_cast<std::uint64_t>(c_size);
×
515
            }
516
            Py_DECREF(mseq);
517
            parsed_slices[i].members = &mv;
×
518
            parsed_slices[i].member_begin = static_cast<std::size_t>(mb);
×
519
            parsed_slices[i].member_end = static_cast<std::size_t>(me);
×
520
            parsed_slices[i].skip_file_scoped_writes = skip_scoped != 0;
×
521
        }
522
        Py_DECREF(seq);
523
    }
524

525
    auto batch_config = std::make_shared<IndexBuildBatchConfig>();
×
526
    batch_config->file_paths = std::move(files);
×
527
    batch_config->preassigned_file_ids = std::move(file_ids);
×
528
    if (!parsed_slices.empty()) {
×
529
        batch_config->file_slices = parsed_slices;
×
530
    }
531
    batch_config->index_dir = index_dir;
×
532
    batch_config->build_bloom = build_bloom != 0;
×
533
    batch_config->checkpoint_size = static_cast<std::size_t>(checkpoint_size);
×
534
    batch_config->force_rebuild = force_rebuild != 0;
×
535
    batch_config->bloom_dimensions = std::move(bloom_dims);
×
536
    batch_config->parallelism =
×
537
        parallelism > 0 ? static_cast<std::size_t>(parallelism)
×
538
                        : (rt ? std::max<std::size_t>(rt->threads(), 1) : 1);
×
539
    batch_config->flush_every_files =
×
540
        static_cast<std::size_t>(flush_every_files);
×
541

542
    // The build runs with the GIL released; re-acquire it per call. The
543
    // GIL-holding deleter drops the ref safely after the build.
544
    if (progress_obj && progress_obj != Py_None) {
×
545
        Py_INCREF(progress_obj);
×
546
        std::shared_ptr<PyObject> cb(progress_obj, [](PyObject *p) {
×
547
            PyGILState_STATE g = PyGILState_Ensure();
×
548
            Py_DECREF(p);
549
            PyGILState_Release(g);
×
550
        });
×
551
        batch_config->progress = [cb](std::size_t done, std::size_t total) {
×
552
            PyGILState_STATE g = PyGILState_Ensure();
×
553
            PyObject *r = PyObject_CallFunction(cb.get(), "nn",
×
554
                                                static_cast<Py_ssize_t>(done),
555
                                                static_cast<Py_ssize_t>(total));
556
            if (r) {
×
557
                Py_DECREF(r);
558
            } else {
559
                // A failing progress callback must not abort the build.
560
                PyErr_Clear();
×
561
            }
562
            PyGILState_Release(g);
×
563
        };
×
564
    }
×
565

566
    if (agg_config_ptr) {
×
567
        auto agg_intern =
568
            dftracer::utils::index::schemas::dft::agg::intern_for_index(
569
                index_dir);
×
570
        // The fold writes aggregation SSTs through the batch build's own SST
571
        // sink (routed to aggregation.sst / system_metrics.sst), so they land
572
        // in `artifacts->list` with bloom/dict - no separate per-file sink.
573
        batch_config->agg_fold_factory =
×
574
            [agg_config_ptr, agg_intern](
×
575
                dftracer::utils::StringIntern &build_intern, int file_id)
576
            -> std::unique_ptr<
577
                dftracer::utils::index::schemas::dft::agg::AggregationFold> {
578
            return std::make_unique<
579
                dftracer::utils::index::schemas::dft::agg::AggregationFold>(
580
                build_intern, agg_intern, *agg_config_ptr, file_id);
×
581
        };
×
582
    }
×
583

584
    // Atomic: write phase calls sink_factory from N coroutines concurrently.
585
    auto batch_counter = std::make_shared<std::atomic<std::size_t>>(0);
×
586
    batch_config->sink_factory =
×
587
        [staging, batch, batch_counter]() -> std::unique_ptr<IndexWrite> {
×
588
        const std::size_t idx =
589
            batch_counter->fetch_add(1, std::memory_order_relaxed);
×
590
        std::string sub_batch = batch + "_" + std::to_string(idx);
×
591
        return std::make_unique<IndexDatabaseSstWriterContext>(staging,
×
592
                                                               sub_batch);
×
593
    };
×
594
    batch_config->sink_commit = [artifacts](IndexWrite &sink) {
×
595
        auto &sst = static_cast<IndexDatabaseSstWriterContext &>(sink);
×
596
        auto batch_artifacts = sst.commit();
×
597
        std::lock_guard<std::mutex> lock(artifacts->mu);
×
598
        if (!batch_artifacts.empty()) {
×
599
            artifacts->list.push_back(std::move(batch_artifacts));
×
600
        }
601
    };
×
602

603
    IndexBuildBatchResult result;
×
604
    if (!run_blocking([&] {
×
605
            rt->submit(dftracer::utils::run_coro_scope(
×
606
                           rt->executor(),
×
607
                           [](dftracer::utils::CoroScope &scope,
×
608
                              std::shared_ptr<IndexBuildBatchConfig> cfg,
609
                              IndexBuildBatchResult *out)
610
                               -> dftracer::utils::coro::CoroTask<void> {
611
                               *out = co_await BatchBuilder::process(
612
                                   &scope, std::move(cfg));
613
                           },
×
614
                           batch_config, &result),
×
615
                       "build-sst-batch")
616
                .get();
×
617
        })) {
×
618
        return NULL;
×
619
    }
620

621
    // If any file failed, surface the first error.
622
    if (result.failed > 0) {
×
623
        for (const auto &r : result.results) {
×
624
            if (!r.success) {
×
625
                PyErr_SetString(PyExc_RuntimeError, r.error_message.c_str());
×
626
                return NULL;
×
627
            }
628
        }
629
    }
630

631
    // One dict per committed sink + per-file aggregation below.
632
    PyObject *out_list = PyList_New(0);
×
633
    if (!out_list) return NULL;
×
634
    {
635
        std::lock_guard<std::mutex> lock(artifacts->mu);
×
636
        for (const auto &a : artifacts->list) {
×
637
            PyObject *main_dict = artifacts_to_dict(a);
×
638
            if (!main_dict || PyList_Append(out_list, main_dict) < 0) {
×
639
                Py_XDECREF(main_dict);
×
640
                Py_DECREF(out_list);
641
                return NULL;
×
642
            }
643
            Py_DECREF(main_dict);
644
        }
645
    }
×
646
    // The fold wrote its aggregation SSTs through the batch build's sink, so
647
    // they are already in `artifacts->list` above (no separate per-visitor
648
    // harvest). Combine the per-file trackers the folds produced out-of-band.
649
    using dftracer::utils::index::schemas::dft::agg::AssociationTracker;
650
    AssociationTracker combined;
×
651
    bool any_tracker = false;
×
652
    for (auto &ao : result.agg_outputs) {
×
653
        if (ao.tracker) {
×
654
            ao.tracker->finalize();
×
655
            combined.merge(*ao.tracker);
×
656
            any_tracker = true;
×
657
        }
658
    }
659
    PyObject *tracker_bytes = nullptr;
×
660
    if (any_tracker) {
×
661
        combined.finalize();
×
662
        std::string blob = combined.serialize();
×
663
        tracker_bytes = PyBytes_FromStringAndSize(
×
664
            blob.data(), static_cast<Py_ssize_t>(blob.size()));
×
665
    } else {
×
666
        tracker_bytes = PyBytes_FromStringAndSize(nullptr, 0);
×
667
    }
668
    if (!tracker_bytes) {
×
669
        Py_DECREF(out_list);
670
        return NULL;
×
671
    }
672
    PyObject *ret = PyTuple_Pack(2, out_list, tracker_bytes);
×
673
    Py_DECREF(out_list);
674
    Py_DECREF(tracker_bytes);
675
    return ret;
×
676
}
×
677

678
static PyObject *enable_aggregation_deterministic_ids_fn(PyObject * /*self*/,
×
679
                                                         PyObject * /*args*/) {
680
    dftracer::utils::index::schemas::dft::agg::
681
        enable_deterministic_intern_ids();
×
682
    Py_RETURN_NONE;
×
683
}
684

685
static PyObject *move_artifacts_fn(PyObject * /*self*/, PyObject *args,
×
686
                                   PyObject *kwds) {
687
    static const char *kwlist[] = {"artifacts", "dest_dir", NULL};
688
    PyObject *dict = NULL;
×
689
    const char *dest_dir = NULL;
×
690
    if (!PyArg_ParseTupleAndKeywords(
×
691
            args, kwds, "Os", const_cast<char **>(kwlist), &dict, &dest_dir)) {
692
        return NULL;
×
693
    }
694
    IndexDatabaseSstWriterContext::Artifacts a;
×
695
    if (!artifacts_from_dict(dict, &a)) return NULL;
×
696
    IndexDatabaseSstWriterContext::Artifacts moved;
×
697
    if (!run_blocking_r([&] { return std::move(a).move_to(dest_dir); }, moved))
×
698
        return NULL;
×
699
    return artifacts_to_dict(moved);
×
700
}
×
701

702
namespace {
703

704
dftracer::utils::coro::CoroTask<void> scan_one_gzip_file(
×
705
    std::string path, std::vector<GzipMember> *out) {
706
    out->clear();
707
    int fd = ::open(path.c_str(), O_RDONLY);
708
    if (fd < 0) co_return;
709
    struct stat st;
710
    if (::fstat(fd, &st) == 0 && st.st_size >= 18) {
711
        co_await enumerate_gzip_member_candidates(
712
            fd, static_cast<std::uint64_t>(st.st_size), *out);
713
    }
714
    ::close(fd);
715
}
×
716

717
}  // namespace
718

719
static PyObject *enumerate_gzip_members_fn(PyObject * /*self*/, PyObject *args,
×
720
                                           PyObject *kwds) {
721
    static const char *kwlist[] = {"files", "runtime", NULL};
722
    PyObject *files_obj = NULL;
×
723
    PyObject *runtime_arg = NULL;
×
724
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O",
×
725
                                     const_cast<char **>(kwlist), &files_obj,
726
                                     &runtime_arg)) {
727
        return NULL;
×
728
    }
729

730
    std::vector<std::string> files;
×
731
    {
732
        if (!parse_string_seq(files_obj, "files must be a sequence", files))
×
733
            return NULL;
×
734
    }
735

736
    Runtime *rt = nullptr;
×
737
    if (runtime_arg && runtime_arg != Py_None) {
×
738
        if (PyObject_TypeCheck(runtime_arg, &RuntimeType)) {
×
739
            rt = ((RuntimeObject *)runtime_arg)->runtime.get();
×
740
        } else {
741
            PyObject *native = PyObject_GetAttrString(runtime_arg, "_native");
×
742
            if (!native || !PyObject_TypeCheck(native, &RuntimeType)) {
×
743
                Py_XDECREF(native);
×
744
                PyErr_SetString(PyExc_TypeError,
×
745
                                "runtime must be a Runtime instance or None");
746
                return NULL;
×
747
            }
748
            rt = ((RuntimeObject *)native)->runtime.get();
×
749
            Py_DECREF(native);
750
        }
751
    } else {
×
752
        rt = dftracer::utils::python::get_default_runtime();
×
753
    }
754

755
    std::vector<std::vector<GzipMember>> results(files.size());
×
756
    if (!run_blocking([&] {
×
757
            rt->submit(
×
758
                  dftracer::utils::run_coro_scope(
×
759
                      rt->executor(),
×
760
                      [](dftracer::utils::CoroScope &scope,
×
761
                         const std::vector<std::string> *paths,
762
                         std::vector<std::vector<GzipMember>> *out)
763
                          -> dftracer::utils::coro::CoroTask<void> {
764
                          co_await scope.scope(
765
                              [paths, out](dftracer::utils::CoroScope &child)
×
766
                                  -> dftracer::utils::coro::CoroTask<void> {
767
                                  for (std::size_t i = 0; i < paths->size();
768
                                       ++i) {
769
                                      const std::string &path = (*paths)[i];
770
                                      auto *slot = &(*out)[i];
771
                                      child.spawn(
772
                                          [path,
×
773
                                           slot](dftracer::utils::CoroScope &)
774
                                              -> dftracer::utils::coro::CoroTask<
775
                                                  void> {
776
                                              co_await scan_one_gzip_file(path,
777
                                                                          slot);
778
                                          });
×
779
                                  }
780
                                  co_return;
781
                              });
×
782
                          co_return;
783
                      },
×
784
                      &files, &results),
×
785
                  "enumerate-gzip-members")
786
                .get();
×
787
        })) {
×
788
        return NULL;
×
789
    }
790

791
    PyObject *out_list = PyList_New(static_cast<Py_ssize_t>(results.size()));
×
792
    if (!out_list) return NULL;
×
793
    for (std::size_t i = 0; i < results.size(); ++i) {
×
794
        const auto &mv = results[i];
×
795
        PyObject *inner = PyList_New(static_cast<Py_ssize_t>(mv.size()));
×
796
        if (!inner) {
×
797
            Py_DECREF(out_list);
798
            return NULL;
×
799
        }
800
        for (std::size_t j = 0; j < mv.size(); ++j) {
×
801
            PyObject *t =
802
                Py_BuildValue("(KK)", (unsigned long long)mv[j].c_offset,
×
803
                              (unsigned long long)mv[j].c_size);
×
804
            if (!t) {
×
805
                Py_DECREF(inner);
806
                Py_DECREF(out_list);
807
                return NULL;
×
808
            }
809
            PyList_SET_ITEM(inner, j, t);
×
810
        }
811
        PyList_SET_ITEM(out_list, i, inner);
×
812
    }
813
    return out_list;
×
814
}
×
815

816
// LPT (longest-processing-time) work assignment for balanced SST distribution.
817
// so the Dask backend produces identical work distribution to MPI.
818
static PyObject *plan_work_units_fn(PyObject * /*self*/, PyObject *args,
×
819
                                    PyObject *kwds) {
820
    static const char *kwlist[] = {"member_map", "num_workers", "target_c_size",
821
                                   NULL};
822
    PyObject *map_obj = NULL;
×
823
    Py_ssize_t num_workers = 0;
×
824
    unsigned long long target_c_size = 0;
×
825
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "On|K",
×
826
                                     const_cast<char **>(kwlist), &map_obj,
827
                                     &num_workers, &target_c_size)) {
828
        return NULL;
×
829
    }
830
    if (num_workers <= 0) num_workers = 1;
×
831

832
    std::vector<std::vector<GzipMember>> member_map;
×
833
    {
834
        PyObject *seq =
835
            PySequence_Fast(map_obj, "member_map must be a sequence");
×
836
        if (!seq) return NULL;
×
837
        Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
×
838
        member_map.resize(n);
×
839
        for (Py_ssize_t i = 0; i < n; ++i) {
×
840
            PyObject *inner = PySequence_Fast_GET_ITEM(seq, i);
×
841
            PyObject *iseq =
842
                PySequence_Fast(inner, "member_map[i] must be a sequence");
×
843
            if (!iseq) {
×
844
                Py_DECREF(seq);
845
                return NULL;
×
846
            }
847
            Py_ssize_t ni = PySequence_Fast_GET_SIZE(iseq);
×
848
            member_map[i].resize(ni);
×
849
            for (Py_ssize_t j = 0; j < ni; ++j) {
×
850
                PyObject *t = PySequence_Fast_GET_ITEM(iseq, j);
×
851
                unsigned long long c_offset = 0, c_size = 0;
×
852
                if (!PyTuple_Check(t)) {
×
853
                    PyErr_SetString(
×
854
                        PyExc_TypeError,
855
                        "each member must be an (offset, size) tuple");
856
                    Py_DECREF(iseq);
857
                    Py_DECREF(seq);
858
                    return NULL;
×
859
                }
860
                if (!PyArg_ParseTuple(t, "KK", &c_offset, &c_size)) {
×
861
                    Py_DECREF(iseq);
862
                    Py_DECREF(seq);
863
                    return NULL;
×
864
                }
865
                member_map[i][j].c_offset =
×
866
                    static_cast<std::uint64_t>(c_offset);
867
                member_map[i][j].c_size = static_cast<std::uint64_t>(c_size);
×
868
            }
869
            Py_DECREF(iseq);
870
        }
871
        Py_DECREF(seq);
872
    }
873

874
    // Fallback: treat empty/non-gzip files as a single whole-file member.
875
    std::uint64_t total_c = 0;
×
876
    for (auto &mv : member_map) {
×
877
        if (mv.empty()) mv.push_back({0, 0});
×
878
        for (const auto &m : mv) total_c += m.c_size;
×
879
    }
880

881
    if (target_c_size == 0) {
×
882
        target_c_size =
×
883
            (total_c + static_cast<std::uint64_t>(num_workers) - 1) /
×
884
            std::max<std::uint64_t>(static_cast<std::uint64_t>(num_workers), 1);
×
885
    }
886

887
    struct Unit {
888
        std::size_t file_idx;
889
        std::size_t member_begin;
890
        std::size_t member_end;
891
        std::uint64_t c_size;
892
    };
893
    std::vector<Unit> units;
×
894
    for (std::size_t fi = 0; fi < member_map.size(); ++fi) {
×
895
        const auto &members = member_map[fi];
×
896
        if (members.empty()) continue;
×
897
        std::size_t begin = 0;
×
898
        std::uint64_t accum = 0;
×
899
        for (std::size_t i = 0; i < members.size(); ++i) {
×
900
            accum += members[i].c_size;
×
901
            const bool is_last = (i + 1 == members.size());
×
902
            if ((target_c_size > 0 && accum >= target_c_size) || is_last) {
×
903
                units.push_back({fi, begin, i + 1, accum});
×
904
                begin = i + 1;
×
905
                accum = 0;
×
906
            }
907
        }
908
    }
909

910
    std::vector<std::size_t> order(units.size());
×
911
    for (std::size_t i = 0; i < order.size(); ++i) order[i] = i;
×
912
    std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
×
913
        if (units[a].c_size != units[b].c_size)
×
914
            return units[a].c_size > units[b].c_size;
×
915
        if (units[a].file_idx != units[b].file_idx)
×
916
            return units[a].file_idx < units[b].file_idx;
×
917
        return units[a].member_begin < units[b].member_begin;
×
918
    });
919
    const std::size_t nw = static_cast<std::size_t>(num_workers);
×
920
    std::vector<std::uint64_t> loads(nw, 0);
×
921
    std::vector<std::vector<std::size_t>> per_worker(nw);
×
922
    for (std::size_t ord : order) {
×
923
        std::size_t best = 0;
×
924
        for (std::size_t r = 1; r < nw; ++r)
×
925
            if (loads[r] < loads[best]) best = r;
×
926
        per_worker[best].push_back(ord);
×
927
        loads[best] += std::max<std::uint64_t>(units[ord].c_size, 1);
×
928
    }
929

930
    PyObject *out = PyList_New(static_cast<Py_ssize_t>(nw));
×
931
    if (!out) return NULL;
×
932
    for (std::size_t w = 0; w < nw; ++w) {
×
933
        // Keep per-worker slices sorted by (file_idx, member_begin) for
934
        // deterministic, file-group-friendly iteration downstream.
935
        auto &lst = per_worker[w];
×
936
        std::sort(lst.begin(), lst.end(), [&](std::size_t a, std::size_t b) {
×
937
            if (units[a].file_idx != units[b].file_idx)
×
938
                return units[a].file_idx < units[b].file_idx;
×
939
            return units[a].member_begin < units[b].member_begin;
×
940
        });
941
        PyObject *inner = PyList_New(static_cast<Py_ssize_t>(lst.size()));
×
942
        if (!inner) {
×
943
            Py_DECREF(out);
944
            return NULL;
×
945
        }
946
        for (std::size_t k = 0; k < lst.size(); ++k) {
×
947
            const auto &u = units[lst[k]];
×
948
            PyObject *t = Py_BuildValue(
×
949
                "(nnnK)", (Py_ssize_t)u.file_idx, (Py_ssize_t)u.member_begin,
×
950
                (Py_ssize_t)u.member_end, (unsigned long long)u.c_size);
×
951
            if (!t) {
×
952
                Py_DECREF(inner);
953
                Py_DECREF(out);
954
                return NULL;
×
955
            }
956
            PyList_SET_ITEM(inner, k, t);
×
957
        }
958
        PyList_SET_ITEM(out, w, inner);
×
959
    }
960
    return out;
×
961
}
×
962

963
// ---------------------------------------------------------------------------
964
// Module registration
965
// ---------------------------------------------------------------------------
966

967
static PyMethodDef SstDistributionMethods[] = {
968
    {"build_sst_batch", DFTU_PYCFUNCTION(build_sst_batch_fn),
969
     METH_VARARGS | METH_KEYWORDS,
970
     "build_sst_batch(files, file_ids, staging_dir, batch_id, ...) "
971
     "-> (list[dict], bytes)\n"
972
     "Run the indexer pipeline with an SST sink and return "
973
     "(artifact_dicts, tracker_blob). The tracker blob is the serialized "
974
     "merged AssociationTracker from this batch's aggregation visitors "
975
     "(empty bytes when no aggregation_config was passed)."},
976
    {"plan_lpt_partition", DFTU_PYCFUNCTION(plan_lpt_partition_fn),
977
     METH_VARARGS,
978
     "plan_lpt_partition(entries, num_workers) -> list[list[(path, size)]]\n"
979
     "Greedy Longest-Processing-Time-first bin-packing of (path, size) "
980
     "tuples across num_workers buckets. Minimises the maximum per-worker "
981
     "total size."},
982
    {"scan_files", DFTU_PYCFUNCTION(scan_files_fn),
983
     METH_VARARGS | METH_KEYWORDS,
984
     "scan_files(directory, patterns=None, recursive=False, runtime=None) "
985
     "-> list[(path, size)]\n"
986
     "Parallel directory scan returning (path, size) tuples for regular "
987
     "files matching the patterns."},
988
    {"enable_aggregation_deterministic_ids",
989
     DFTU_PYCFUNCTION(enable_aggregation_deterministic_ids_fn), METH_NOARGS,
990
     "enable_aggregation_deterministic_ids() -> None\n"
991
     "Flip the global aggregation StringIntern into deterministic-id mode "
992
     "so the same string maps to the same 32-bit id in every worker "
993
     "process. Call once at worker startup BEFORE any aggregation work."},
994
    {"move_artifacts", DFTU_PYCFUNCTION(move_artifacts_fn),
995
     METH_VARARGS | METH_KEYWORDS,
996
     "move_artifacts(artifacts, dest_dir) -> dict\n"
997
     "Move every populated SST in `artifacts` (as returned by "
998
     "`build_sst_batch`) into `dest_dir` via the C++ rename/copy helper, "
999
     "returning a fresh dict with the new paths. Single GIL release, no "
1000
     "per-file Python shutil.move overhead."},
1001
    {"enumerate_gzip_members", DFTU_PYCFUNCTION(enumerate_gzip_members_fn),
1002
     METH_VARARGS | METH_KEYWORDS,
1003
     "enumerate_gzip_members(files, runtime=None) -> list[list[(c_offset, "
1004
     "c_size)]]\n"
1005
     "Cooperative async scan of gzip member offsets across `files`. "
1006
     "Returns lists of (c_offset, c_size) parallel to `files`; empty for "
1007
     "non-gzip / unreadable files."},
1008
    {"plan_work_units", DFTU_PYCFUNCTION(plan_work_units_fn),
1009
     METH_VARARGS | METH_KEYWORDS,
1010
     "plan_work_units(member_map, num_workers, target_c_size=0) "
1011
     "-> list[list[(file_idx, member_begin, member_end, c_size)]]\n"
1012
     "Deterministic LPT assignment of intra-file gzip-member slices "
1013
     "across workers. Each worker's list contains (file_idx, "
1014
     "member_begin, member_end, c_size) tuples; a file sliced across "
1015
     "multiple workers appears in each owner's list with disjoint "
1016
     "[member_begin, member_end) ranges."},
1017
    {NULL, NULL, 0, NULL}};
1018

1019
int dftracer::utils::python::init_sst_distribution(PyObject *m) {
7 ✔
1020
    if (register_type(m, &SstArtifactRegistryType, "SstArtifactRegistry") < 0)
7 !
1021
        return -1;
×
1022
    if (PyModule_AddFunctions(m, SstDistributionMethods) < 0) return -1;
7 !
1023
    return 0;
7 ✔
1024
}
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