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

llnl / dftracer-utils / 29191674125

12 Jul 2026 11:54AM UTC coverage: 52.751% (-0.003%) from 52.754%
29191674125

push

github

rayandrew
perf(dfanalyzer): skip already-indexed files in distributed_index

Resolve required tiers up front and skip files that need no work; return early when none do. Warm re-index calls no longer re-parse the whole trace.

40027 of 98354 branches covered (40.7%)

Branch coverage included in aggregate %.

35420 of 44670 relevant lines covered (79.29%)

21594.1 hits per line

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

54.89
/src/dftracer/utils/python/utilities/comparator.cpp
1
#define PY_SSIZE_T_CLEAN
2
#include <dftracer/utils/core/common/error.h>
3
#include <dftracer/utils/core/common/filesystem.h>
4
#include <dftracer/utils/core/common/platform_compat.h>
5
#include <dftracer/utils/core/coro/channel.h>
6
#include <dftracer/utils/core/coro/task.h>
7
#include <dftracer/utils/core/coro/when_all.h>
8
#include <dftracer/utils/core/pipeline/pipeline.h>
9
#include <dftracer/utils/core/pipeline/pipeline_config.h>
10
#include <dftracer/utils/core/runtime.h>
11
#include <dftracer/utils/core/tasks/coro_scope.h>
12
#include <dftracer/utils/core/tasks/task.h>
13
#include <dftracer/utils/python/arrow_helpers.h>
14
#include <dftracer/utils/python/py_runtime_mixin.h>
15
#include <dftracer/utils/python/py_type_helpers.h>
16
#include <dftracer/utils/python/runtime.h>
17
#include <dftracer/utils/python/utilities/comparator.h>
18
#include <dftracer/utils/utilities/common/query/query.h>
19
#include <dftracer/utils/utilities/composites/dft/aggregators/aggregators.h>
20
#include <dftracer/utils/utilities/composites/dft/comparator/comparison_config.h>
21
#include <dftracer/utils/utilities/composites/dft/comparator/comparison_result.h>
22
#include <dftracer/utils/utilities/composites/dft/comparator/comparison_utility.h>
23
#include <dftracer/utils/utilities/composites/dft/comparator/tree_table_formatter.h>
24
#include <dftracer/utils/utilities/composites/dft/indexing/index_resolver_utility.h>
25
#include <dftracer/utils/utilities/composites/dft/indexing/resolve_and_build.h>
26
#include <dftracer/utils/utilities/composites/dft/internal/utils.h>
27
#include <dftracer/utils/utilities/composites/dft/metadata_collector_utility.h>
28
#include <dftracer/utils/utilities/filesystem/pattern_directory_scanner_utility.h>
29
#include <dftracer/utils/utilities/indexer/index_builder_utility.h>
30
#include <dftracer/utils/utilities/indexer/internal/indexer.h>
31

32
#include <atomic>
33
#include <chrono>
34
#include <cstdio>
35
#include <ctime>
36
#include <stdexcept>
37
#include <string>
38
#include <vector>
39

40
using dftracer::utils::Runtime;
41
using dftracer::utils::coro::CoroTask;
42
using namespace dftracer::utils;
43
using namespace dftracer::utils::utilities;
44
using namespace dftracer::utils::utilities::composites::dft::aggregators;
45
using namespace dftracer::utils::utilities::composites::dft::comparator;
46

47
#include <dftracer/utils/core/common/config.h>
48
#ifdef DFTRACER_UTILS_ENABLE_ARROW
49
using dftracer::utils::python::arrow_result_to_table;
50
#endif
51

52
DFTRACER_UTILS_RUNTIME_BACKED_SLOTS(Comparator, ComparatorObject)
78✔
53

54
// -----------------------------------------------------------------------
55
// Helpers
56
// -----------------------------------------------------------------------
57

58
struct ComparatorArgs {
39!
59
    std::string baseline;
60
    std::string variant;
61
    std::string query;
62
    std::string group_by;
63
    std::string format;
64
    double time_interval_ms = 5000.0;
13✔
65
    double threshold = 0.0;
13✔
66
    std::size_t executor_threads = 0;
13✔
67
    std::string baseline_index_dir;
68
    std::string variant_index_dir;
69
    bool force_rebuild = false;
13✔
70
    std::string config_path;
71
};
72

73
static int parse_comparator_args(PyObject *args, PyObject *kwds,
26✔
74
                                 ComparatorArgs &out) {
75
    static const char *kwlist[] = {"baseline",
76
                                   "variant",
77
                                   "query",
78
                                   "group_by",
79
                                   "format",
80
                                   "time_interval_ms",
81
                                   "threshold",
82
                                   "executor_threads",
83
                                   "baseline_index_dir",
84
                                   "variant_index_dir",
85
                                   "force_rebuild",
86
                                   "config",
87
                                   NULL};
88

89
    const char *baseline = NULL;
26✔
90
    const char *variant = NULL;
26✔
91
    const char *query = "";
26✔
92
    const char *group_by = "";
26✔
93
    const char *format = "table";
26✔
94
    double time_interval_ms = 5000.0;
26✔
95
    double threshold = 0.0;
26✔
96
    Py_ssize_t executor_threads = 0;
26✔
97
    const char *baseline_index_dir = "";
26✔
98
    const char *variant_index_dir = "";
26✔
99
    int force_rebuild = 0;
26✔
100
    const char *config = "";
26✔
101

102
    if (!PyArg_ParseTupleAndKeywords(
26!
103
            args, kwds, "ss|sssddnssps", (char **)kwlist, &baseline, &variant,
13✔
104
            &query, &group_by, &format, &time_interval_ms, &threshold,
105
            &executor_threads, &baseline_index_dir, &variant_index_dir,
106
            &force_rebuild, &config))
107
        return -1;
×
108

109
    out.baseline = baseline;
26!
110
    out.variant = variant;
26!
111
    out.query = query;
26!
112
    out.group_by = group_by;
26!
113
    out.format = format;
26!
114
    out.time_interval_ms = time_interval_ms;
26✔
115
    out.threshold = threshold;
26✔
116
    out.executor_threads = static_cast<std::size_t>(executor_threads);
26✔
117
    out.baseline_index_dir = baseline_index_dir;
26!
118
    out.variant_index_dir = variant_index_dir;
26!
119
    out.force_rebuild = force_rebuild != 0;
26✔
120
    out.config_path = config;
26!
121

122
    return 0;
26✔
123
}
13✔
124

125
namespace {
126

127
void flatten_nodes(const ComparisonNode &node,
26✔
128
                   std::vector<const ComparisonNode *> &out) {
129
    out.push_back(&node);
26!
130
    for (const auto &child : node.children) {
26!
131
        flatten_nodes(child, out);
×
132
    }
133
}
26✔
134

135
CoroTask<EventAggregatorOutput> run_aggregation(
156!
136
    std::vector<std::string> input_files, AggregationConfig agg_config,
137
    std::optional<common::query::Query> query, std::string index_dir,
138
    std::size_t checkpoint_size, bool force_rebuild,
139
    std::size_t executor_threads) {
26!
140
    constexpr std::size_t CHUNK_SIZE_MB = 4;
26✔
141
    constexpr std::size_t BATCH_SIZE_MB = 4;
26✔
142

143
    auto pipeline_config = PipelineConfig()
52!
144
                               .with_name("DFTracer Comparator Aggregation")
26!
145
                               .with_compute_threads(executor_threads)
26!
146
                               .with_watchdog(false);
26!
147
    Pipeline pipeline(pipeline_config);
26!
148

149
    EventAggregator merger;
26!
150
    std::atomic<int> global_chunk_idx{0};
26✔
151

152
    auto streaming_task = make_task(
52!
153
        [&](CoroScope &ctx) -> CoroTask<void> {
234!
154
            auto chunk_chan = coro::make_channel<ChunkAggregatorInput>(0);
78!
155
            auto result_chan = coro::make_channel<ChunkAggregationOutput>(2);
78!
156

157
            co_await ctx.scope([&](CoroScope &scope) -> CoroTask<void> {
286!
158
                for (const auto &file_path : input_files) {
54✔
159
                    auto *global_chunk_idx_ptr = &global_chunk_idx;
28✔
160
                    scope.spawn([file_path, ch = chunk_chan->producer(),
472!
161
                                 index_dir, checkpoint_size, force_rebuild,
28!
162
                                 agg_config, query, global_chunk_idx_ptr](
28!
163
                                    CoroScope & /*fctx*/) mutable
164
                                    -> CoroTask<void> {
28!
165
                        [[maybe_unused]] auto producer_guard = ch.guard();
80!
166

167
                        std::string index_path =
80✔
168
                            composites::dft::internal::determine_index_path(
80!
169
                                file_path, index_dir);
80✔
170

171
                        auto meta_input =
80✔
172
                            composites::dft::MetadataCollectorUtilityInput::
160!
173
                                from_file(file_path)
80!
174
                                    .with_checkpoint_size(checkpoint_size)
80✔
175
                                    .with_force_rebuild(force_rebuild)
28!
176
                                    .with_index(index_path);
28✔
177
                        auto metadata =
80✔
178
                            co_await composites::dft::MetadataCollectorUtility{}
214!
179
                                .process(meta_input);
80!
180

181
                        if (!metadata.success) {
84!
182
                            co_return;
183
                        }
184

185
                        FileChunkMapperUtility file_mapper;
84!
186
                        auto mapper_input =
84✔
187
                            FileChunkMapperInput::from_metadata(metadata)
168!
188
                                .with_config(agg_config)
84✔
189
                                .with_checkpoint_size(checkpoint_size)
28!
190
                                .with_target_chunk_size(CHUNK_SIZE_MB)
28!
191
                                .with_batch_size(BATCH_SIZE_MB * 1024 * 1024);
28!
192
                        mapper_input.query = query;
84!
193
                        auto file_chunks =
84✔
194
                            co_await file_mapper.process(mapper_input);
112!
195

196
                        int start_idx = global_chunk_idx_ptr->fetch_add(
168✔
197
                            static_cast<int>(file_chunks.size()));
84✔
198
                        for (int i = 0;
112✔
199
                             i < static_cast<int>(file_chunks.size()); ++i) {
112✔
200
                            file_chunks[i].chunk_index = start_idx + i;
28✔
201
                        }
28✔
202

203
                        for (auto &chunk : file_chunks) {
112!
204
                            if (!co_await ch.send(std::move(chunk))) {
112!
205
                                co_return;
206
                            }
207
                        }
28!
208
                        co_return;
28✔
209
                    });
736!
210
                }
28✔
211

212
                for (std::size_t w = 0; w < executor_threads; ++w) {
104✔
213
                    (void)w;
214
                    scope.spawn([chunk_chan, rp = result_chan->producer(),
771!
215
                                 result_chan](
78✔
216
                                    CoroScope &wctx) mutable -> CoroTask<void> {
78✔
217
                        [[maybe_unused]] auto producer_guard = rp.guard();
78!
218
                        while (auto input = co_await wctx.receive(chunk_chan)) {
502!
219
                            ChunkAggregatorUtility agg;
84!
220
                            auto output = co_await agg.process(*input);
112!
221
                            if (!co_await result_chan->send(
112!
222
                                    std::move(output))) {
223
                                co_return;
224
                            }
225
                        }
218✔
226
                        co_return;
78✔
227
                    });
978!
228
                }
78✔
229

230
                auto *merger_ptr = &merger;
26✔
231
                scope.spawn([result_chan,
324!
232
                             merger_ptr](CoroScope &mctx) -> CoroTask<void> {
52!
233
                    while (auto output = co_await mctx.receive(result_chan)) {
167!
234
                        merger_ptr->merge_chunk(std::move(*output));
28!
235
                    }
54✔
236
                    co_return;
26✔
237
                });
168!
238

239
                co_return;
52✔
240
            });
78!
241

242
            co_return;
26✔
243
        },
130!
244
        "StreamingAggregate");
26!
245

246
    EventAggregatorOutput result;
26✔
247
    auto post_task = make_task(
52!
248
        [&](CoroScope & /*ctx*/) -> CoroTask<bool> {
182!
249
            result = merger.finalize();
26!
250
            co_return result.success;
52!
251
        },
52!
252
        "Finalize");
26!
253

254
    post_task->depends_on(streaming_task);
26!
255
    pipeline.set_source(streaming_task);
26!
256
    pipeline.set_destination(post_task);
26!
257
    pipeline.execute();
26!
258

259
    co_return result;
52!
260
}
78!
261

262
}  // namespace
263

264
static bool run_comparison_pipeline(ComparatorObject *self,
26✔
265
                                    const ComparatorArgs &cargs,
266
                                    ComparisonOutput &output) {
267
    ComparatorArgs args_copy = cargs;
26!
268
    auto *output_ptr = &output;
26✔
269

270
    return run_blocking([&] {
39!
271
        ComparisonConfig config;
26!
272
        if (!args_copy.config_path.empty()) {
26✔
273
            std::string parse_error;
×
274
            auto parsed = ComparisonConfig::from_json_file(
×
275
                args_copy.config_path, parse_error);
×
276
            if (!parsed) {
×
277
                throw DFTUtilsException(ErrorCode::PARSE,
×
278
                                        "Config error: " + parse_error);
×
279
            }
280
            config = std::move(*parsed);
×
281
        } else {
×
282
            config = ComparisonConfig::from_cli(
26!
283
                args_copy.baseline, args_copy.variant, args_copy.query,
26✔
284
                args_copy.group_by);
26!
285
        }
286

287
        config.format = args_copy.format;
26!
288
        config.no_color = true;
26✔
289
        if (args_copy.executor_threads > 0)
26✔
290
            config.executor_threads = args_copy.executor_threads;
×
291
        if (!args_copy.baseline_index_dir.empty())
26!
292
            config.baseline_index_dir = args_copy.baseline_index_dir;
×
293
        if (!args_copy.variant_index_dir.empty())
26!
294
            config.variant_index_dir = args_copy.variant_index_dir;
×
295
        if (args_copy.force_rebuild)
26✔
296
            config.force_rebuild = args_copy.force_rebuild;
×
297
        if (args_copy.threshold > 0.0)
26✔
298
            config.defaults.threshold_pct = args_copy.threshold;
×
299
        if (args_copy.time_interval_ms > 0.0)
26✔
300
            config.defaults.time_interval_ms = args_copy.time_interval_ms;
26✔
301

302
        config.resolve();
26!
303

304
        if (config.executor_threads == 0) {
26!
305
            config.executor_threads = dftracer_utils_hardware_concurrency();
26!
306
        }
13✔
307
        if (config.checkpoint_size == 0) {
26✔
308
            config.checkpoint_size =
26✔
309
                indexer::internal::Indexer::DEFAULT_CHECKPOINT_SIZE;
310
        }
13✔
311

312
        using composites::dft::indexing::IndexResolverUtility;
313
        using composites::dft::indexing::ResolverInput;
314
        using indexer::IndexBatchBuilderUtility;
315
        using indexer::IndexBuildBatchConfig;
316

317
        Runtime *rt = resolve_runtime(self);
26!
318

319
        auto task = [config, output_ptr, rt]() -> CoroTask<void> {
169!
320
            auto resolve_and_build =
39✔
321
                [&config](
143!
322
                    CoroScope &scope, const std::string &path,
323
                    const std::string &index_dir,
324
                    std::vector<std::string> &out_files) -> CoroTask<void> {
13!
325
                if (fs::is_regular_file(path)) {
39!
326
                    co_await composites::dft::indexing::ensure_index_fresh(
97!
327
                        &scope, "", path, index_dir, config.force_rebuild);
36!
328
                } else {
12✔
329
                    co_await composites::dft::indexing::ensure_index_fresh(
7!
330
                        &scope, path, "", index_dir, config.force_rebuild);
3!
331
                }
332

333
                IndexResolverUtility resolver;
13!
334
                ResolverInput resolve_input;
13✔
335
                resolve_input.index_dir = index_dir;
13!
336
                resolve_input.require_checkpoints = !config.force_rebuild;
13✔
337
                if (fs::is_regular_file(path)) {
13!
338
                    resolve_input.files = {path};
12!
339
                } else {
12✔
340
                    resolve_input.directory = path;
1!
341
                }
342

343
                auto result = co_await resolver.process(resolve_input);
26!
344
                out_files = std::move(result.all_files);
13✔
345

346
                if (out_files.empty() || result.needs_checkpoint.empty()) {
13!
347
                    co_return;
13✔
348
                }
349

350
                auto batch_cfg = std::make_shared<IndexBuildBatchConfig>();
×
351
                batch_cfg->file_paths.reserve(result.needs_checkpoint.size());
×
352
                for (const auto &item : result.needs_checkpoint) {
×
353
                    batch_cfg->file_paths.push_back(item.file_path);
×
354
                }
355
                batch_cfg->index_dir = index_dir;
×
356
                batch_cfg->checkpoint_size = config.checkpoint_size;
357
                batch_cfg->parallelism = config.executor_threads;
358
                batch_cfg->force_rebuild = config.force_rebuild;
359
                batch_cfg->use_batch_write = true;
360
                batch_cfg->rebuild_root_summaries = true;
361

362
                co_await IndexBatchBuilderUtility::process(
×
363
                    &scope, std::move(batch_cfg));
364
            };
91!
365

366
            std::vector<std::string> baseline_files;
39✔
367
            std::vector<std::string> variant_files;
39✔
368

369
            bool shared_index =
78✔
370
                composites::dft::internal::determine_index_path(
117!
371
                    config.baseline, config.baseline_index_dir) ==
78✔
372
                composites::dft::internal::determine_index_path(
78!
373
                    config.variant, config.variant_index_dir);
39✔
374

375
            co_await run_coro_scope(
52!
376
                rt->executor(), [&](CoroScope &scope) -> CoroTask<void> {
169!
377
                    if (shared_index) {
39!
378
                        co_await resolve_and_build(scope, config.baseline,
104!
379
                                                   config.baseline_index_dir,
39✔
380
                                                   baseline_files);
39✔
381
                        if (config.baseline == config.variant) {
13!
382
                            variant_files = baseline_files;
13!
383
                        } else {
13✔
384
                            co_await resolve_and_build(scope, config.variant,
×
385
                                                       config.variant_index_dir,
386
                                                       variant_files);
387
                        }
388
                    } else {
13✔
389
                        scope.spawn([&](CoroScope &s) -> CoroTask<void> {
×
390
                            co_await resolve_and_build(
×
391
                                s, config.baseline, config.baseline_index_dir,
392
                                baseline_files);
393
                        });
×
394
                        co_await resolve_and_build(scope, config.variant,
×
395
                                                   config.variant_index_dir,
396
                                                   variant_files);
397
                    }
398
                });
52!
399

400
            if (baseline_files.empty()) {
39!
401
                throw DFTUtilsException(
×
402
                    ErrorCode::NOT_FOUND,
403
                    "No trace files found in baseline: " + config.baseline);
×
404
            }
405
            if (variant_files.empty()) {
39!
406
                throw DFTUtilsException(
×
407
                    ErrorCode::NOT_FOUND,
408
                    "No trace files found in variant: " + config.variant);
×
409
            }
410

411
            output_ptr->baseline_path = config.baseline;
39✔
412
            output_ptr->variant_path = config.variant;
13✔
413

414
            auto start_time = std::chrono::high_resolution_clock::now();
39✔
415

416
            std::size_t b_files_actual = 0;
39✔
417
            std::size_t v_files_actual = 0;
39✔
418
            bool metadata_set = false;
39✔
419

420
            for (auto &node : config.nodes) {
52!
421
                std::vector<const ComparisonNode *> visitors;
39✔
422
                flatten_nodes(node, visitors);
39!
423

424
                std::vector<ComparisonVisitorPair> pairs;
39✔
425
                pairs.reserve(visitors.size());
39!
426

427
                for (const auto *visitor : visitors) {
78!
428
                    std::optional<common::query::Query> query;
39✔
429
                    if (!visitor->composed_query.empty()) {
39✔
430
                        auto result = common::query::Query::from_string(
26!
431
                            visitor->composed_query);
13✔
432
                        if (!result) {
13!
433
                            throw DFTUtilsException(
×
434
                                ErrorCode::QUERY,
435
                                "Invalid query for node '" + visitor->name +
×
436
                                    "': " + result.error().format());
×
437
                        }
438
                        query = std::move(*result);
13!
439
                    }
13✔
440

441
                    AggregationConfig agg_cfg;
39!
442
                    agg_cfg.time_interval_us = static_cast<std::uint64_t>(
39✔
443
                        config.defaults.time_interval_ms * 1000.0);
39✔
444
                    agg_cfg.extra_group_keys = {};
39✔
445
                    agg_cfg.compute_statistics = true;
13✔
446
                    agg_cfg.compute_percentiles = true;
13✔
447
                    agg_cfg.percentiles = visitor->resolved_percentiles;
13✔
448
                    agg_cfg.sketch_accuracy = 0.01;
39✔
449
                    agg_cfg.track_process_parents = false;
39✔
450

451
                    auto [base_result, var_result] = co_await coro::when_all(
91!
452
                        run_aggregation(
78!
453
                            baseline_files, agg_cfg, query,
39!
454
                            config.baseline_index_dir, config.checkpoint_size,
39!
455
                            config.force_rebuild, config.executor_threads),
39✔
456
                        run_aggregation(
78!
457
                            variant_files, agg_cfg, query,
39!
458
                            config.variant_index_dir, config.checkpoint_size,
39!
459
                            config.force_rebuild, config.executor_threads));
39✔
460

461
                    if (!metadata_set) {
13!
462
                        b_files_actual = base_result.total_files_processed;
13✔
463
                        v_files_actual = var_result.total_files_processed;
13✔
464
                        output_ptr->baseline_file_count = b_files_actual;
13✔
465
                        output_ptr->variant_file_count = v_files_actual;
13✔
466
                        output_ptr->baseline_meta = extract_metadata(
26!
467
                            base_result.aggregations, b_files_actual);
13✔
468
                        output_ptr->variant_meta = extract_metadata(
26!
469
                            var_result.aggregations, v_files_actual);
13✔
470
                        metadata_set = true;
13✔
471
                    }
13✔
472

473
                    ComparisonVisitorPair pair;
13✔
474
                    pair.baseline = std::move(base_result);
13✔
475
                    pair.variant = std::move(var_result);
13✔
476
                    pair.node = *visitor;
13!
477
                    pairs.push_back(std::move(pair));
13!
478
                }
13!
479

480
                ComparisonUtilityInput cmp_input;
39✔
481
                cmp_input.visitors = std::move(pairs);
39✔
482
                cmp_input.root_node = node;
39!
483
                cmp_input.baseline_file_count = b_files_actual;
39✔
484
                cmp_input.variant_file_count = v_files_actual;
39✔
485

486
                ComparisonUtility cmp;
39!
487
                auto cmp_output = co_await cmp.process(cmp_input);
52!
488
                output_ptr->nodes.push_back(std::move(cmp_output->result));
13!
489
            }
13!
490

491
            // Inject metadata rows into root SUMMARY.
492
            auto meta_rows = build_metadata_metrics(output_ptr->baseline_meta,
26!
493
                                                    output_ptr->variant_meta);
13✔
494
            for (auto &node : output_ptr->nodes) {
26✔
495
                node.summary.metrics.insert(node.summary.metrics.begin(),
39!
496
                                            meta_rows.begin(), meta_rows.end());
26✔
497
            }
13✔
498

499
            auto end_time = std::chrono::high_resolution_clock::now();
13✔
500
            std::chrono::duration<double, std::milli> duration =
13✔
501
                end_time - start_time;
13!
502
            output_ptr->execution_time_ms = duration.count();
13!
503
        };
338!
504

505
        rt->submit(task(), "comparator").get();
26!
506
    });
52✔
507
}
26✔
508

509
// -----------------------------------------------------------------------
510
// compare() -- returns ArrowTable
511
// -----------------------------------------------------------------------
512

513
static PyObject *Comparator_compare(ComparatorObject *self, PyObject *args,
12✔
514
                                    PyObject *kwds) {
515
    ComparatorArgs cargs;
12✔
516
    if (parse_comparator_args(args, kwds, cargs) < 0) return NULL;
12!
517

518
    ComparisonOutput output;
12✔
519
    if (!run_comparison_pipeline(self, cargs, output)) {
12!
520
        return NULL;
×
521
    }
522

523
#ifdef DFTRACER_UTILS_ENABLE_ARROW
524
    auto arrow_result = output.to_arrow();
12!
525
    if (!arrow_result.valid()) {
12!
526
        PyErr_SetString(PyExc_RuntimeError,
×
527
                        "Failed to convert comparison output "
528
                        "to Arrow");
529
        return NULL;
×
530
    }
531
    return arrow_result_to_table(std::move(arrow_result));
12!
532
#else
533
    PyErr_SetString(PyExc_RuntimeError,
534
                    "dftracer-utils was built without Arrow support");
535
    return NULL;
536
#endif
537
}
12✔
538

539
// -----------------------------------------------------------------------
540
// compare_json() -- returns JSON string
541
// -----------------------------------------------------------------------
542

543
static PyObject *Comparator_compare_json(ComparatorObject *self, PyObject *args,
8✔
544
                                         PyObject *kwds) {
545
    ComparatorArgs cargs;
8✔
546
    if (parse_comparator_args(args, kwds, cargs) < 0) return NULL;
8!
547

548
    ComparisonOutput output;
8✔
549
    if (!run_comparison_pipeline(self, cargs, output)) {
8!
550
        return NULL;
×
551
    }
552

553
    TreeTableFormatter formatter;
8!
554
    std::string json = formatter.render_json(output);
8!
555
    return PyUnicode_FromStringAndSize(json.data(), (Py_ssize_t)json.size());
8!
556
}
8✔
557

558
// -----------------------------------------------------------------------
559
// compare_table() -- returns formatted table string
560
// -----------------------------------------------------------------------
561

562
static PyObject *Comparator_compare_table(ComparatorObject *self,
6✔
563
                                          PyObject *args, PyObject *kwds) {
564
    ComparatorArgs cargs;
6✔
565
    if (parse_comparator_args(args, kwds, cargs) < 0) return NULL;
6!
566

567
    ComparisonOutput output;
6✔
568
    if (!run_comparison_pipeline(self, cargs, output)) {
6!
569
        return NULL;
×
570
    }
571

572
    FormatterOptions fmt_opts;
6✔
573
    fmt_opts.use_color = false;
6✔
574
    fmt_opts.use_unicode = false;
6✔
575
    TreeTableFormatter formatter(fmt_opts);
6!
576

577
    // Render to a temporary file and read back as string
578
    char *buf = NULL;
6✔
579
    std::size_t buf_size = 0;
6✔
580
    FILE *memstream = open_memstream(&buf, &buf_size);
6!
581
    if (!memstream) {
6!
582
        PyErr_SetString(PyExc_RuntimeError, "Failed to create memory stream");
×
583
        return NULL;
×
584
    }
585

586
    formatter.render(memstream, output);
6!
587
    fflush(memstream);
6!
588
    fclose(memstream);
6!
589

590
    PyObject *result = PyUnicode_FromStringAndSize(buf, (Py_ssize_t)buf_size);
6!
591
    free(buf);
6!
592
    return result;
6✔
593
}
6✔
594

595
// -----------------------------------------------------------------------
596
// __call__ delegates to compare()
597
// -----------------------------------------------------------------------
598

599
static PyObject *Comparator_call(PyObject *self, PyObject *args,
2✔
600
                                 PyObject *kwds) {
601
    return Comparator_compare((ComparatorObject *)self, args, kwds);
2✔
602
}
603

604
// -----------------------------------------------------------------------
605
// Method table
606
// -----------------------------------------------------------------------
607

608
static const char *COMPARE_DOC =
609
    "compare(baseline, variant, query='', group_by='',\n"
610
    "        format='table', time_interval_ms=5000.0,\n"
611
    "        threshold=0.0, executor_threads=0,\n"
612
    "        index_dir='', force_rebuild=False, config='')\n"
613
    "--\n"
614
    "\n"
615
    "Run comparison pipeline, return materialized ArrowTable.\n"
616
    "\n"
617
    "Args:\n"
618
    "    baseline (str): Baseline trace file or directory.\n"
619
    "    variant (str): Variant trace file or directory.\n"
620
    "    query (str): Query filter (default: all events).\n"
621
    "    group_by (str): Comma-separated group keys.\n"
622
    "    format (str): Output format (default 'table').\n"
623
    "    time_interval_ms (float): Time bucket in ms "
624
    "(default 5000).\n"
625
    "    threshold (float): Hide changes below this pct.\n"
626
    "    executor_threads (int): Parallel threads (0=auto).\n"
627
    "    index_dir (str): Directory for .dftindex stores.\n"
628
    "    force_rebuild (bool): Force index rebuild.\n"
629
    "    config (str): JSON config file path.\n"
630
    "\n"
631
    "Returns:\n"
632
    "    ArrowTable: Comparison results.\n";
633

634
static const char *COMPARE_JSON_DOC =
635
    "compare_json(baseline, variant, query='', group_by='',\n"
636
    "             format='table', time_interval_ms=5000.0,\n"
637
    "             threshold=0.0, executor_threads=0,\n"
638
    "             index_dir='', force_rebuild=False, "
639
    "config='')\n"
640
    "--\n"
641
    "\n"
642
    "Run comparison pipeline, return JSON string.\n"
643
    "\n"
644
    "Args:\n"
645
    "    baseline (str): Baseline trace file or directory.\n"
646
    "    variant (str): Variant trace file or directory.\n"
647
    "    query (str): Query filter (default: all events).\n"
648
    "    group_by (str): Comma-separated group keys.\n"
649
    "    format (str): Output format (default 'table').\n"
650
    "    time_interval_ms (float): Time bucket in ms "
651
    "(default 5000).\n"
652
    "    threshold (float): Hide changes below this pct.\n"
653
    "    executor_threads (int): Parallel threads (0=auto).\n"
654
    "    index_dir (str): Directory for .dftindex stores.\n"
655
    "    force_rebuild (bool): Force index rebuild.\n"
656
    "    config (str): JSON config file path.\n"
657
    "\n"
658
    "Returns:\n"
659
    "    str: JSON representation of comparison results.\n";
660

661
static const char *COMPARE_TABLE_DOC =
662
    "compare_table(baseline, variant, query='', group_by='',\n"
663
    "              format='table', time_interval_ms=5000.0,\n"
664
    "              threshold=0.0, executor_threads=0,\n"
665
    "              index_dir='', force_rebuild=False, "
666
    "config='')\n"
667
    "--\n"
668
    "\n"
669
    "Run comparison pipeline, return formatted table string.\n"
670
    "\n"
671
    "Args:\n"
672
    "    baseline (str): Baseline trace file or directory.\n"
673
    "    variant (str): Variant trace file or directory.\n"
674
    "    query (str): Query filter (default: all events).\n"
675
    "    group_by (str): Comma-separated group keys.\n"
676
    "    format (str): Output format (default 'table').\n"
677
    "    time_interval_ms (float): Time bucket in ms "
678
    "(default 5000).\n"
679
    "    threshold (float): Hide changes below this pct.\n"
680
    "    executor_threads (int): Parallel threads (0=auto).\n"
681
    "    index_dir (str): Directory for .dftindex stores.\n"
682
    "    force_rebuild (bool): Force index rebuild.\n"
683
    "    config (str): JSON config file path.\n"
684
    "\n"
685
    "Returns:\n"
686
    "    str: Formatted ASCII table of comparison results.\n";
687

688
static PyMethodDef Comparator_methods[] = {
1✔
689
    {"compare", (PyCFunction)Comparator_compare, METH_VARARGS | METH_KEYWORDS,
2✔
690
     COMPARE_DOC},
1✔
691
    {"compare_json", (PyCFunction)Comparator_compare_json,
2✔
692
     METH_VARARGS | METH_KEYWORDS, COMPARE_JSON_DOC},
1✔
693
    {"compare_table", (PyCFunction)Comparator_compare_table,
2✔
694
     METH_VARARGS | METH_KEYWORDS, COMPARE_TABLE_DOC},
1✔
695
    {NULL}};
1✔
696

697
PyTypeObject ComparatorType = {
698
    PyVarObject_HEAD_INIT(
699
        NULL, 0) "dftracer_utils_ext.ComparatorUtility", /* tp_name */
700
    sizeof(ComparatorObject),                            /* tp_basicsize */
701
    0,                                                   /* tp_itemsize */
702
    (destructor)Comparator_dealloc,                      /* tp_dealloc */
703
    0,                                        /* tp_vectorcall_offset */
704
    0,                                        /* tp_getattr */
705
    0,                                        /* tp_setattr */
706
    0,                                        /* tp_as_async */
707
    0,                                        /* tp_repr */
708
    0,                                        /* tp_as_number */
709
    0,                                        /* tp_as_sequence */
710
    0,                                        /* tp_as_mapping */
711
    0,                                        /* tp_hash */
712
    Comparator_call,                          /* tp_call */
713
    0,                                        /* tp_str */
714
    0,                                        /* tp_getattro */
715
    0,                                        /* tp_setattro */
716
    0,                                        /* tp_as_buffer */
717
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
718
    "ComparatorUtility(runtime: Runtime | None = None)\n"
719
    "--\n\n"
720
    "Compare DFTracer trace metrics between baseline and "
721
    "variant.\n\n"
722
    "Args:\n"
723
    "    runtime (Runtime or None): Runtime for thread pool "
724
    "control.\n"
725
    "        If None, uses the default global Runtime.\n\n"
726
    "compare(baseline, variant, ...) -> ArrowTable\n"
727
    "    Run comparison and return a materialized Arrow "
728
    "table.\n\n"
729
    "compare_json(baseline, variant, ...) -> str\n"
730
    "    Run comparison and return JSON string.\n\n"
731
    "compare_table(baseline, variant, ...) -> str\n"
732
    "    Run comparison and return formatted table "
733
    "string.\n",               /* tp_doc */
734
    0,                         /* tp_traverse */
735
    0,                         /* tp_clear */
736
    0,                         /* tp_richcompare */
737
    0,                         /* tp_weaklistoffset */
738
    0,                         /* tp_iter */
739
    0,                         /* tp_iternext */
740
    Comparator_methods,        /* tp_methods */
741
    0,                         /* tp_members */
742
    0,                         /* tp_getset */
743
    0,                         /* tp_base */
744
    0,                         /* tp_dict */
745
    0,                         /* tp_descr_get */
746
    0,                         /* tp_descr_set */
747
    0,                         /* tp_dictoffset */
748
    (initproc)Comparator_init, /* tp_init */
749
    0,                         /* tp_alloc */
750
    Comparator_new,            /* tp_new */
751
};
752

753
int init_comparator(PyObject *m) {
2✔
754
    if (register_type(m, &ComparatorType, "ComparatorUtility") < 0) return -1;
2✔
755

756
    return 0;
2✔
757
}
1✔
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