forked from Aider-AI/aider
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathbenchmark.py
More file actions
executable file
·1669 lines (1403 loc) · 60.4 KB
/
benchmark.py
File metadata and controls
executable file
·1669 lines (1403 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import asyncio
import datetime
import json
import logging
import os
import random
import re
import shutil
import subprocess
import sys
import tarfile
import time
import traceback
from collections import defaultdict
from json.decoder import JSONDecodeError
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
import importlib_resources
import yaml
"""
Performance-oriented refactors:
- Avoid heavy imports unless needed for a given code path.
- Fast path for `--stats` to skip GitPython and benchmarking deps.
- Use json.load for result file parsing to reduce memory churn.
- Cache git version lookups across a single invocation.
"""
# Heavy modules are lazily imported within the code paths that need them.
import typer
from dotenv import load_dotenv
from rich.console import Console
from cecli.dump import dump # noqa: F401
logger = logging.getLogger("cecli.benchmark")
# Cache for commit-hash -> version lookup
_VERSION_CACHE = {}
BENCHMARK_DNAME = Path(os.environ.get("CECLI_BENCHMARK_DIR", "tmp.benchmarks"))
EXERCISES_DIR_DEFAULT = "cecli-cat"
RESULTS_DIR_DEFAULT = "cat-results"
app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
load_dotenv(override=True)
def resolve_dirname(results_dir, use_single_prior, make_new):
"""
Determines the actual directory path used for storing benchmark results.
1. Resuming a previous run: If the --cont flag is used and exactly one matching previous run exists,
it selects that existing directory.
2. Safety check: If previous runs exist but the user didn't specify --new or --cont,
it warns the user and aborts to prevent accidental overwrites or confusion.
3. Creating a new run: If no prior run exists (or --new is used),
it prepends the current timestamp to the directory name to ensure a unique workspace.
"""
logger.debug(f"initial results_dir: {results_dir}")
results_dir = Path(results_dir)
logger.debug(f"dirname1: {results_dir}")
if len(results_dir.parts) > 1:
return results_dir
priors = list(BENCHMARK_DNAME.glob(f"*--{results_dir}"))
# BUG20251223
logger.debug(f"Found priors: {priors}")
logger.debug(f"use_single_prior: {use_single_prior}, make_new: {make_new}")
if len(priors) == 1 and use_single_prior:
results_dir = priors[0].name
logger.info(f"Using pre-existing {results_dir}")
elif len(priors):
if not make_new:
logger.warning(f"Prior runs of {results_dir} exist, use --new or name one explicitly")
for prior in priors:
logger.warning(prior)
sys.exit(1)
if not re.match(r"\d\d\d\d-\d\d-\d\d-", str(results_dir)):
now = datetime.datetime.now()
now = now.strftime("%Y-%m-%d-%H-%M-%S--")
results_dir = now + results_dir.name
logger.debug(f"resolved {results_dir}")
results_dir = BENCHMARK_DNAME / results_dir
logger.info(f"updated results_dir: {results_dir}")
return results_dir
@app.command()
def main(
results_dir: Optional[str] = typer.Argument("unnamed", help="Results directory slug"),
model: str = typer.Option("gemini/gemini-3-flash-preview", "--model", "-m", help="Model name"),
sleep: float = typer.Option(
0, "--sleep", help="Sleep seconds between tests when single threaded"
),
languages: str = typer.Option(
None,
"--languages",
"-l",
help="Only run tests for specific languages (comma separated)",
),
edit_format: str = typer.Option(None, "--edit-format", "-e", help="Edit format"),
editor_model: str = typer.Option(None, "--editor-model", help="Editor model name"),
editor_edit_format: str = typer.Option(None, "--editor-edit-format", help="Editor edit format"),
replay: str = typer.Option(
None,
"--replay",
help="Replay previous .cecli.dev.history.md responses from previous benchmark run",
),
keywords: str = typer.Option(
None,
"--keywords",
"-k",
help="Only run tests that contain keywords (comma sep)",
),
clean: bool = typer.Option(
False,
"--clean",
"-c",
help="Discard the existing testdir and make a clean copy",
),
cont: bool = typer.Option(False, "--cont", help="Continue the (single) matching testdir"),
make_new: bool = typer.Option(False, "--new", help="Make a new dated testdir"),
no_unit_tests: bool = typer.Option(False, "--no-unit-tests", help="Do not run unit tests"),
no_cecli: bool = typer.Option(False, "--no-cecli", help="Do not run cecli"),
verbose: int = typer.Option(0, "--verbose", "-v", count=True, help="Verbose output"),
quiet: bool = typer.Option(False, "--quiet", "-q", help="Quiet output"),
tries: int = typer.Option(2, "--tries", "-r", help="Number of tries for running tests"),
threads: int = typer.Option(1, "--threads", "-t", help="Number of threads to run in parallel"),
num_tests: int = typer.Option(-1, "--num-tests", "-n", help="Number of tests to run"),
num_ctx: Optional[int] = typer.Option(
None, "--num-ctx", help="Override model context window size"
),
read_model_settings: str = typer.Option(
None, "--read-model-settings", help="Load cecli model settings from YAML file"
),
reasoning_effort: Optional[str] = typer.Option(
None,
"--reasoning-effort",
help="Set reasoning effort for models that support it",
),
thinking_tokens: Optional[int] = typer.Option(
None, "--thinking-tokens", help="Set thinking tokens for models that support it"
),
map_tokens: Optional[int] = typer.Option(
None,
"--map-tokens",
help="Suggested number of tokens for repo map (0 to disable)",
),
exercises_dir: str = typer.Option(
EXERCISES_DIR_DEFAULT, "--exercises-dir", help="Directory with exercise files"
),
legacy: bool = typer.Option(False, "--legacy", help="Use legacy exercise directory structure"),
sets: Optional[str] = typer.Option(
None, "--sets", help="Only run tests for specific sets (comma separated)"
),
hash_re: Optional[str] = typer.Option(
None,
"--hash-re",
help=(
"Regex to filter exercise hashes. Useful for dividing the set into fractions using"
" hex chars: '^0' for 1/16, '^[01]' for 1/8, '^[0-3]' for 1/4. Use '^.{n}x' to"
" match the nth character (e.g., '^.{2}[4-7]' for the 3rd char in range 4-7)."
),
),
dry: bool = typer.Option(False, "--dry", help="Run in dry mode (no cecli, no tests)"),
stats: bool = typer.Option(
False, "--stats", help="Generate statistics YAML file from benchmark results"
),
aggregate: Optional[str] = typer.Option(
None, "--aggregate", help="Aggregate results from directories matching this pattern"
),
tar: Optional[str] = typer.Option(
None, "--tar", help="Create a tar.gz of directories matching this pattern"
),
):
# setup logging and verbosity
if quiet:
log_level = logging.WARNING
elif verbose > 0:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logging.basicConfig(level=log_level, format="%(message)s")
# Convert SimpleNamespace to dict for YAML serialization
def simple_namespace_to_dict(obj):
if isinstance(obj, SimpleNamespace):
return {k: simple_namespace_to_dict(v) for k, v in vars(obj).items()}
elif isinstance(obj, dict):
return {k: simple_namespace_to_dict(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [simple_namespace_to_dict(item) for item in obj]
else:
return obj
# Handle --stats flag: generate statistics YAML file and exit
if stats:
# Get statistics
stats_result = summarize_results(results_dir, verbose, stats_languages=languages)
# Convert to dict
stats_dict = simple_namespace_to_dict(stats_result)
# Write to results.yaml
results_yaml_path = Path(results_dir) / "results.yaml"
with open(results_yaml_path, "w") as f:
yaml.dump(stats_dict, f, default_flow_style=False)
print(f"Statistics written to: {results_yaml_path}")
return 0
if aggregate:
# Find matching directories
matching_dirs = [d for d in BENCHMARK_DNAME.iterdir() if d.is_dir() and aggregate in d.name]
if not matching_dirs:
print(f"No directories matching '{aggregate}' found in {BENCHMARK_DNAME}")
return 1
all_results = {}
for d in matching_dirs:
stats_result = summarize_results(d, verbose, stats_languages=languages)
if stats_result:
# Remove timestamp from directory name for the key
key = re.sub(r"^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}--", "", d.name)
all_results[key] = simple_namespace_to_dict(stats_result)
# Sort the results by the keys (directory names without timestamps)
all_results = dict(sorted(all_results.items()))
output_path = BENCHMARK_DNAME / f"all_results_{aggregate}.yml"
with open(output_path, "w") as f:
yaml.dump(all_results, f, default_flow_style=False)
print(f"Aggregated results written to: {output_path}")
return 0
if tar:
# Find matching directories
matching_dirs = [d for d in BENCHMARK_DNAME.iterdir() if d.is_dir() and tar in d.name]
if not matching_dirs:
print(f"No directories matching '{tar}' found in {BENCHMARK_DNAME}")
return 1
output_path = BENCHMARK_DNAME / f"benchmarks_{tar}.tar.gz"
print(f"Creating tarball: {output_path}")
with tarfile.open(output_path, "w:gz") as tar_handle:
for d in matching_dirs:
print(f" Adding {d.name}...")
tar_handle.add(d, arcname=d.name)
print(f"Tarball created at: {output_path}")
return 0
from cecli import models
if dry:
no_cecli = True
no_unit_tests = True
commit_hash = "???????"
else:
# Lazy imports for the actual benchmark run
import git # Heavy
import lox # Only needed for threaded runs
from cecli import sendchat
from cecli.coders import base_coder
repo = git.Repo(search_parent_directories=True)
commit_hash = repo.head.object.hexsha[:7]
if repo.is_dirty():
commit_hash += "-dirty"
resolved_results_dir = resolve_dirname(results_dir, cont, make_new)
if not resolved_results_dir:
logger.error(f"Could not resolve results directory from slug: {results_dir}")
logger.error(f"Checked in {BENCHMARK_DNAME}")
return 1
results_dir = resolved_results_dir
if not dry and "CECLI_DOCKER" not in os.environ:
logger.warning("Warning: Benchmarking runs unvetted code. Run in a docker container.")
logger.warning(
"Set CECLI_DOCKER in the environment to by-pass this check at your own risk."
)
return
# Check dirs exist
if not (BENCHMARK_DNAME.exists() and BENCHMARK_DNAME.is_dir()):
logger.error(f"Benchmark directory not found: {BENCHMARK_DNAME}")
sys.exit(1)
original_dname = BENCHMARK_DNAME / exercises_dir
if not (original_dname.exists() and original_dname.is_dir()):
logger.error(f"Exercises directory not found: {original_dname}")
sys.exit(1)
def legacy_get_exercise_dirs(base_dir, languages=None):
"""Get all exercise directories for specified languages (or all if none specified).
Uses the legacy `exercises/practice` pattern.
"""
base_dir = Path(base_dir)
logger.info(f"Looking for exercises in {base_dir}")
# Get available language dirs
lang_dirs = [d for d in base_dir.iterdir() if d.is_dir()]
# Filter to requested languages if specified
if languages:
requested = set(lang.strip().lower() for lang in languages.split(","))
lang_dirs = [d for d in lang_dirs if d.name.lower() in requested]
dump(lang_dirs)
if not lang_dirs:
logger.warning(f"No matching language directories found for: {languages}")
return []
# Get all exercise dirs under exercises/practice for each language
exercise_dirs = []
for lang_dir in lang_dirs:
practice_dir = lang_dir / "exercises" / "practice"
if practice_dir.exists():
exercise_dirs.extend(d for d in practice_dir.iterdir() if d.is_dir())
return exercise_dirs
def get_exercise_dirs(base_dir, languages=None, sets=None, hash_re=None, legacy=False):
if legacy:
return legacy_get_exercise_dirs(base_dir, languages)
base_dir = Path(base_dir)
logger.info(f"Scanning for cat.yaml in {base_dir}")
lang_filter = (
set(lang.strip().lower() for lang in languages.split(",")) if languages else None
)
set_filter = set(sf.strip().lower() for sf in sets.split(",")) if sets else None
exercise_dirs = []
for cat_file in base_dir.rglob("cat.yaml"):
try:
with open(cat_file, "r") as f:
metadata = yaml.safe_load(f)
if verbose > 1:
logger.debug(f"found {metadata['name']} ({metadata['language']})")
except Exception as e:
logger.warning(f"Failed to parse {cat_file}: {e}")
continue
if lang_filter and metadata.get("language", "").lower() not in lang_filter:
continue
if set_filter:
cat_sets = set(s.lower() for s in metadata.get("sets", []))
if not (set_filter & cat_sets):
continue
if hash_re and not re.search(hash_re, metadata.get("hash", "")):
continue
exercise_dirs.append(cat_file.parent)
logger.info(f"Found {len(exercise_dirs)} cats")
return exercise_dirs
exercise_dirs = get_exercise_dirs(original_dname, languages, sets, hash_re, legacy=legacy)
if not exercise_dirs:
logger.error("No exercise directories found")
return 1
if clean and results_dir.exists() and not dry:
logger.info(f"Cleaning up and replacing {results_dir}")
dir_files = set(fn.name for fn in results_dir.glob("*"))
original_files = set(fn.name for fn in original_dname.glob("*"))
if dir_files != original_files:
logger.error(
f"ERROR: will not delete dir that does not look like original tests {results_dir}"
)
return
dest = results_dir.parent / "OLD" / results_dir.name
if dest.exists():
old_now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
dest = results_dir.parent / "OLD" / (old_now + results_dir.name)
results_dir.rename(dest)
if not dry:
if not results_dir.exists():
logger.info(f"Copying {original_dname} -> {results_dir} ...")
os.makedirs(results_dir, exist_ok=True)
copied = False
for exercise_dir in exercise_dirs:
dest_dir = results_dir / exercise_dir.name
if not dest_dir.exists():
if not copied:
logger.info(f"Adding missing exercises to {results_dir} ...")
shutil.copytree(exercise_dir, dest_dir)
copied = True
if copied:
logger.info("...done")
test_dnames = sorted(d.name for d in exercise_dirs)
resource_metadata = importlib_resources.files("cecli.resources").joinpath("model-metadata.json")
model_metadata_files_loaded = models.register_litellm_models([resource_metadata])
dump(model_metadata_files_loaded)
if read_model_settings:
try:
files_loaded = models.register_models([read_model_settings])
if files_loaded:
logger.debug(f"Loaded model settings from: {files_loaded[0]}")
else:
logger.debug(f"No model settings loaded from: {read_model_settings}")
except Exception as e:
logger.error(f"Error loading model settings: {e}")
return 1
if keywords:
keywords = keywords.split(",")
test_dnames = [dn for dn in test_dnames for keyword in keywords if keyword in dn]
random.shuffle(test_dnames)
if num_tests > 0:
test_dnames = test_dnames[:num_tests]
if not no_cecli:
# Don't give up when benchmarking
LONG_TIMEOUT = 24 * 60 * 60
sendchat.RETRY_TIMEOUT = LONG_TIMEOUT
base_coder.RETRY_TIMEOUT = LONG_TIMEOUT
models.RETRY_TIMEOUT = LONG_TIMEOUT
# Enable in-memory RepoMap cache when running multiple threads to avoid SQLite contention
repomap_in_memory = threads > 1
test_args = dict(
model_name=model,
edit_format=edit_format,
tries=tries,
no_unit_tests=no_unit_tests,
no_cecli=no_cecli,
verbose=verbose,
commit_hash=commit_hash,
replay=replay,
editor_model=editor_model,
editor_edit_format=editor_edit_format,
num_ctx=num_ctx,
sleep=sleep,
reasoning_effort=reasoning_effort,
thinking_tokens=thinking_tokens,
map_tokens=map_tokens,
repomap_in_memory=repomap_in_memory,
dry=dry,
results_dir=results_dir,
)
if threads > 1:
run_test_threaded = lox.thread(threads)(run_test)
for test_path in test_dnames:
run_test_threaded.scatter(original_dname, results_dir / test_path, **test_args)
all_results = run_test_threaded.gather(tqdm=True)
else:
all_results = []
for test_path in sorted(test_dnames):
results = run_test(original_dname, results_dir / test_path, **test_args)
all_results.append(results)
summarize_results(results_dir, verbose)
if sleep:
time.sleep(sleep)
print()
print()
print()
summarize_results(results_dir, verbose)
return 0
def load_results(results_dir, stats_languages=None):
results_dir = Path(results_dir)
lang_to_results = {}
# BUG20251223
logger.debug(f"Globbing {results_dir} for results")
files = list(results_dir.glob("*/.cecli.results.json"))
logger.debug(f"Found {len(files)} files")
for fname in files:
try:
results = json.loads(fname.read_text())
# BUG20251223
logger.debug(f"Processing result file: {fname}")
# Check if test case counts are missing and compute them if needed
test_dir = fname.parent
logger.debug(f"Computing test case counts for {test_dir}")
total_cases, passed_cases = get_test_case_counts_from_directory(test_dir)
if total_cases is not None:
results["test_cases_total"] = total_cases
if passed_cases is not None:
results["test_cases_passed"] = passed_cases
# Update the JSON file immediately to keep data fresh
fname.write_text(json.dumps(results, indent=4))
logger.debug(f"Updated {fname} with test case counts")
# Try to get language from cat.yaml if it exists in the same dir
lang = "unknown"
cat_yaml = fname.parent / "cat.yaml"
if cat_yaml.exists():
try:
with open(cat_yaml, "r") as f:
metadata = yaml.safe_load(f)
lang = metadata.get("language", "unknown")
except Exception:
pass
if stats_languages:
languages = [lang.strip().lower() for lang in stats_languages.split(",")]
if lang.lower() not in languages:
continue
logger.debug(f"Derived lang: {lang}")
lang_to_results.setdefault(lang, []).append(results)
except json.JSONDecodeError:
logger.warning(f"json.JSONDecodeError {fname}")
continue
return lang_to_results
def summarize_results(results_dir, verbose, stats_languages=None):
# Convert results_dir to Path object if it's a string
results_dir = Path(results_dir)
lang_to_results = load_results(results_dir, stats_languages)
res = SimpleNamespace()
res.total_tests = len(list(results_dir.glob("*/.cecli.results.json")))
try:
tries = max(
len(results.get("tests_outcomes", []))
for results_list in lang_to_results.values()
for results in results_list
if results
)
except ValueError:
tries = 0
res.dir_name = str(results_dir)
passed_tests = [0] * tries
res.completed_tests = 0
res.duration = 0
res.cost = 0
res.error_outputs = 0
res.user_asks = 0
res.test_timeouts = 0
res.exhausted_context_windows = 0
res.num_malformed_responses = 0
res.num_with_malformed_responses = 0
res.syntax_errors = 0
res.indentation_errors = 0
res.lazy_comments = 0
res.prompt_tokens = 0
res.completion_tokens = 0
res.test_cases_total = 0
res.test_cases_passed = 0
res.reasoning_effort = None
res.thinking_tokens = None
res.map_tokens = None
variants = defaultdict(set)
def add(attr_name, increment, global_stats, lang_stats):
global_prev = getattr(global_stats, attr_name)
setattr(global_stats, attr_name, global_prev + increment)
lang_prev = getattr(lang_stats, attr_name)
setattr(lang_stats, attr_name, lang_prev + increment)
lang_to_stats = {}
lang_to_passed_tests = {}
for lang, results_list in lang_to_results.items():
lang_stats = SimpleNamespace()
lang_stats.completed_tests = 0
lang_stats.duration = 0
lang_stats.avg_duration_per_test = 0
lang_stats.cost = 0
for i in range(tries):
setattr(lang_stats, f"pass_rate_{i + 1}", 0)
for i in range(tries):
setattr(lang_stats, f"pass_num_{i + 1}", 0)
lang_stats.error_outputs = 0
lang_stats.user_asks = 0
lang_stats.test_timeouts = 0
lang_stats.exhausted_context_windows = 0
lang_stats.num_malformed_responses = 0
lang_stats.num_with_malformed_responses = 0
lang_stats.syntax_errors = 0
lang_stats.indentation_errors = 0
lang_stats.lazy_comments = 0
lang_stats.prompt_tokens = 0
lang_stats.completion_tokens = 0
lang_stats.test_cases_total = 0
lang_stats.test_cases_passed = 0
lang_to_stats[lang] = lang_stats
lang_to_passed_tests[lang] = [0] * tries
for results in results_list:
if not results:
continue
add("completed_tests", 1, res, lang_stats)
tests_outcomes = results.get("tests_outcomes", [])
passed = tests_outcomes and tests_outcomes[-1]
if passed:
for i in range(len(tests_outcomes) - 1, tries):
passed_tests[i] += 1
lang_to_passed_tests[lang][i] += 1
add("cost", results.get("cost", 0), res, lang_stats)
add("duration", results.get("duration", 0), res, lang_stats)
add("test_timeouts", results.get("test_timeouts", 0), res, lang_stats)
add("error_outputs", results.get("num_error_outputs", 0), res, lang_stats)
add("user_asks", results.get("num_user_asks", 0), res, lang_stats)
add(
"exhausted_context_windows",
results.get("num_exhausted_context_windows", 0),
res,
lang_stats,
)
add(
"num_malformed_responses",
results.get("num_malformed_responses", 0),
res,
lang_stats,
)
if results.get("num_malformed_responses"):
add("num_with_malformed_responses", 1, res, lang_stats)
add("lazy_comments", results.get("lazy_comments", 0), res, lang_stats)
add("syntax_errors", results.get("syntax_errors", 0), res, lang_stats)
add(
"indentation_errors",
results.get("indentation_errors", 0),
res,
lang_stats,
)
add("prompt_tokens", results.get("prompt_tokens", 0), res, lang_stats)
add(
"completion_tokens",
results.get("completion_tokens", 0),
res,
lang_stats,
)
# Collect test case statistics from pre-computed results
total_cases = results.get("test_cases_total")
passed_cases = results.get("test_cases_passed")
if total_cases is not None:
add("test_cases_total", total_cases, res, lang_stats)
if passed_cases is not None:
add("test_cases_passed", passed_cases, res, lang_stats)
res.reasoning_effort = results.get("reasoning_effort")
res.thinking_tokens = results.get("thinking_tokens")
res.map_tokens = results.get("map_tokens")
for key in "model edit_format commit_hash editor_model editor_edit_format".split():
val = results.get(key)
if val:
variants[key].add(val)
if not res.completed_tests:
return
# if res.completed_tests < 133:
# return
console = Console(highlight=False)
console.rule(title=str(results_dir))
commit_hashes = variants["commit_hash"]
versions = get_versions(commit_hashes)
date = results_dir.name[:10]
def show(stat, red="red"):
val = getattr(res, stat)
style = red if val else None
console.print(f" {stat}: {val}", style=style)
percents = dict()
for i in range(tries):
pass_rate = 100 * passed_tests[i] / res.completed_tests
percents[i] = pass_rate
# console.print(f"{pass_rate:.1f}% correct after try {i + 1}")
setattr(res, f"pass_rate_{i + 1}", f"{pass_rate:.1f}")
setattr(res, f"pass_num_{i + 1}", passed_tests[i])
print(f"- results_dir: {results_dir.name}")
style = None if res.completed_tests == res.total_tests else "red"
console.print(f" test_cases: {res.completed_tests}", style=style)
for key, val in variants.items():
if len(val) > 1:
style = "red"
else:
style = None
val = ", ".join(map(str, val))
setattr(res, key, val)
console.print(f" {key}: {val}", style=style)
if res.reasoning_effort is not None:
print(f" reasoning_effort: {res.reasoning_effort}")
if res.thinking_tokens is not None:
print(f" thinking_tokens: {res.thinking_tokens}")
if res.map_tokens is not None:
print(f" map_tokens: {res.map_tokens}")
for i in range(tries):
print(f" pass_rate_{i + 1}: {percents[i]:.1f}")
for i in range(tries):
print(f" pass_num_{i + 1}: {passed_tests[i]}")
pct_well_formed = 1.0 - res.num_with_malformed_responses / res.completed_tests
print(f" percent_cases_well_formed: {pct_well_formed * 100:.1f}")
show("error_outputs")
show("num_malformed_responses")
show("num_with_malformed_responses")
show("user_asks")
show("lazy_comments")
show("syntax_errors")
show("indentation_errors")
show("exhausted_context_windows")
show("prompt_tokens", red=None)
show("completion_tokens", red=None)
show("test_timeouts")
print(f" total_tests: {res.total_tests}")
# Add test case statistics and percentage
if res.test_cases_total > 0:
print(f" test_cases_total: {res.test_cases_total}")
print(f" test_cases_passed: {res.test_cases_passed}")
res.test_cases_percentage = 100 * res.test_cases_passed / res.test_cases_total
print(f" test_cases_percentage: {res.test_cases_percentage:.1f}")
if variants["model"]:
a_model = set(variants["model"]).pop()
command = f"cecli --model {a_model}"
print(f" command: {command}")
print(f" date: {date}")
print(" versions:", ",".join(versions))
res.avg_duration = res.duration / res.completed_tests
print(f" seconds_per_case: {res.avg_duration:.1f}")
print(f" total_cost: {res.cost:.4f}")
res.avg_cost = res.cost / res.completed_tests
projected_cost = res.avg_cost * res.total_tests
print()
print(
f"costs: ${res.avg_cost:.4f}/test-case, ${res.cost:.2f} total,"
f" ${projected_cost:.2f} projected"
)
if verbose and len(lang_to_stats) > 0:
def format_lang_stats(lang, lang_stats):
# First, postprocess attributes for easier printing
if lang_stats.completed_tests > 0:
lang_stats.avg_duration_per_test = lang_stats.duration / float(
lang_stats.completed_tests
)
for i in range(tries):
num_passed = lang_to_passed_tests[lang][i]
setattr(lang_stats, f"pass_num_{i + 1}", num_passed)
pass_rate = 100 * num_passed / float(lang_stats.completed_tests)
setattr(lang_stats, f"pass_rate_{i + 1}", pass_rate)
# Then format attributes into ready-to-print strings
for attr in lang_stats.__dict__:
val = getattr(lang_stats, attr)
if val == 0:
val = "-"
elif isinstance(val, float):
val = f"{val:,.2f}"
else:
val = f"{val:,}"
setattr(lang_stats, attr, val)
def compute_lang_to_col_widths(lang_to_stats):
lang_to_col_widths = {}
for lang, lang_stats in lang_to_stats.items():
lang_stat_attrs = [getattr(lang_stats, attr) for attr in lang_stats.__dict__]
lang_col_width = max(len(lang), len(max(lang_stat_attrs, key=len)))
lang_to_col_widths[lang] = lang_col_width
return lang_to_col_widths
print()
print("======== Stats by language ========")
print()
[format_lang_stats(lang, lang_stats) for lang, lang_stats in lang_to_stats.items()]
lang_to_col_widths = compute_lang_to_col_widths(lang_to_stats)
any_stats = list(lang_to_stats.values())[0]
attrs = list(any_stats.__dict__)
attr_col_width = len(max(["language"] + attrs, key=len))
langs = list(lang_to_stats.keys())
print("| " + ("-" * attr_col_width), end="")
for lang in langs:
col_width = lang_to_col_widths[lang]
print(" | " + ("-" * col_width), end="")
print(" |")
print(f"| {' '.center(attr_col_width)}", end="")
for lang in langs:
col_width = lang_to_col_widths[lang]
print(f" | {lang.center(col_width)}", end="")
print(" |")
print("| " + ("-" * attr_col_width), end="")
for lang in langs:
col_width = lang_to_col_widths[lang]
print(" | " + ("-" * col_width), end="")
print(" |")
for attr in attrs:
print(f"| {attr:<{attr_col_width}}", end="")
for lang in langs:
lang_stats = lang_to_stats[lang]
col_width = lang_to_col_widths[lang]
print(f" | {getattr(lang_stats, attr):>{col_width}}", end="")
print(" |")
print("| " + ("-" * attr_col_width), end="")
for lang in langs:
col_width = lang_to_col_widths[lang]
print(" | " + ("-" * col_width), end="")
print(" |")
print()
console.rule()
# print(json.dumps(vars(res), indent=4, sort_keys=True))
return res
def get_versions(commit_hashes):
versions = set()
for hsh in commit_hashes:
if not hsh:
continue
short = hsh.split("-")[0]
if short in _VERSION_CACHE:
ver = _VERSION_CACHE.get(short)
if ver:
versions.add(ver)
continue
try:
version_src = subprocess.check_output(
["git", "show", f"{short}:cecli/__init__.py"], universal_newlines=True
)
match = re.search(r'__version__ = "(.*)"', version_src)
ver = match.group(1) if match else None
_VERSION_CACHE[short] = ver
if ver:
versions.add(ver)
except subprocess.CalledProcessError:
_VERSION_CACHE[short] = None
pass
return versions
def get_replayed_content(replay_dname, test_dname):
replay_dname = Path(replay_dname)
test_dname = Path(test_dname)
dump(replay_dname, test_dname)
test_name = test_dname.name
replay_fname = replay_dname / test_name / ".cecli.dev.history.md"
dump(replay_fname)
res = replay_fname.read_text()
return res
res = res.splitlines(keepends=True)
res = [line for line in res if not line.startswith("> ") and not line.startswith("#### ")]
return "".join(res)
def run_test(original_dname, testdir, *args, **kwargs):
try:
return asyncio.run(run_test_real(original_dname, testdir, *args, **kwargs))
except Exception:
logger.error("=" * 40)
logger.error("Test failed")
logger.error(traceback.format_exc())
testdir = Path(testdir)
results_fname = testdir / ".cecli.results.json"
results_fname.write_text(json.dumps(dict(exception=traceback.format_exc())))
async def run_test_real(
original_dname,
testdir,
model_name,
edit_format,
tries,
no_unit_tests,
no_cecli,
verbose,
commit_hash,
replay,
editor_model,
editor_edit_format,
num_ctx=None,
sleep=0,
reasoning_effort: Optional[str] = None,
thinking_tokens: Optional[int] = None,
map_tokens: Optional[int] = None,
read_model_settings=None,
repomap_in_memory: bool = False,
dry: bool = False,
results_dir=None,
):
# Lazy imports: only needed in the actual benchmark execution path
import git
from cecli import models
from cecli.coders import Coder
from cecli.helpers.conversation import ConversationFiles, ConversationManager
from cecli.io import InputOutput
from cecli.main import SwitchCoderSignal
if not os.path.isdir(testdir):
if dry:
return
logger.error(f"Not a dir: {testdir}")
return
testdir = Path(testdir)
history_fname = testdir / ".cecli.dev.history.md"
results_fname = testdir / ".cecli.results.json"
if results_fname.exists():
try:
res = json.loads(results_fname.read_text())
# if res.get("test_timeouts", 0) > 0:
# print(f"{results_fname} test timeouts, redoing...")
# else:
return res
except JSONDecodeError:
logger.warning(f"{results_fname} failed to parse, redoing...")
# Read solution and test files from config
fnames = []
config_file = testdir / ".meta/config.json"
if not config_file.exists():
raise ValueError(f"No config file found: {config_file}")
with open(config_file) as f:
config = json.loads(f.read())
# Get file sets from config
test_files = config.get("files", {}).get("test", [])
example_files = config.get("files", {}).get("example", [])
solution_files = set(config.get("files", {}).get("solution", []))
# Forcibly ignore certain files not covered by test_files and example_files