-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathfunction_optimizer.py
More file actions
3318 lines (2967 loc) · 155 KB
/
function_optimizer.py
File metadata and controls
3318 lines (2967 loc) · 155 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
from __future__ import annotations
import concurrent.futures
import dataclasses
import logging
import os
import queue
import random
import subprocess
import uuid
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING, Callable
import libcst as cst
from git import Repo as GitRepo
from rich.console import Group
from rich.panel import Panel
from rich.syntax import Syntax
from rich.text import Text
from rich.tree import Tree
from codeflash.api.aiservice import AiServiceClient, AIServiceRefinerRequest, LocalAiServiceClient
from codeflash.api.cfapi import add_code_context_hash, create_staging, get_cfapi_base_urls, mark_optimization_success
from codeflash.benchmarking.utils import process_benchmark_data
from codeflash.cli_cmds.console import (
code_print,
console,
logger,
lsp_log,
progress_bar,
subagent_log_optimization_result,
)
from codeflash.code_utils import env_utils
from codeflash.code_utils.code_utils import (
choose_weights,
cleanup_paths,
create_rank_dictionary_compact,
create_score_dictionary_from_metrics,
diff_length,
encoded_tokens_len,
extract_unique_errors,
file_name_from_test_module_name,
get_run_tmp_file,
module_name_from_file_path,
normalize_by_max,
restore_conftest,
unified_diff_strings,
)
from codeflash.code_utils.config_consts import (
COVERAGE_THRESHOLD,
INDIVIDUAL_TESTCASE_TIMEOUT,
MAX_TEST_REPAIR_CYCLES,
MIN_CORRECT_CANDIDATES,
OPTIMIZATION_CONTEXT_TOKEN_LIMIT,
REFINED_CANDIDATE_RANKING_WEIGHTS,
REPEAT_OPTIMIZATION_PROBABILITY,
TOTAL_LOOPING_TIME_EFFECTIVE,
EffortKeys,
EffortLevel,
get_effort_value,
)
from codeflash.code_utils.env_utils import get_pr_number
from codeflash.code_utils.formatter import format_code, format_generated_code, sort_imports
from codeflash.code_utils.git_utils import git_root_dir
from codeflash.code_utils.shell_utils import make_env_with_project_root
from codeflash.code_utils.time_utils import humanize_runtime
from codeflash.discovery.functions_to_optimize import was_function_previously_optimized
from codeflash.either import Failure, Success, is_successful
from codeflash.languages.base import Language
from codeflash.languages.current import current_language_support
from codeflash.languages.javascript.test_runner import clear_created_config_files, get_created_config_files
from codeflash.lsp.helpers import is_LSP_enabled, is_subagent_mode, report_to_markdown_table, tree_to_markdown
from codeflash.lsp.lsp_message import LspCodeMessage, LspMarkdownMessage, LSPMessageId
from codeflash.models.ExperimentMetadata import ExperimentMetadata
from codeflash.models.models import (
AdaptiveOptimizedCandidate,
AIServiceAdaptiveOptimizeRequest,
AIServiceCodeRepairRequest,
BestOptimization,
CandidateEvaluationContext,
GeneratedTests,
GeneratedTestsList,
OptimizationReviewResult,
OptimizationSet,
OptimizedCandidate,
OptimizedCandidateResult,
OptimizedCandidateSource,
OriginalCodeBaseline,
TestFile,
TestFiles,
TestingMode,
TestResults,
TestType,
)
from codeflash.result.create_pr import check_create_pr, existing_tests_source_for
from codeflash.result.critic import (
concurrency_gain,
coverage_critic,
get_acceptance_reason,
performance_gain,
quantity_of_tests_critic,
speedup_critic,
throughput_gain,
)
from codeflash.result.explanation import Explanation
from codeflash.telemetry.posthog_cf import ph
from codeflash.verification.equivalence import compare_test_results
from codeflash.verification.parse_test_output import parse_concurrency_metrics, parse_test_results
from codeflash.verification.verification_utils import get_test_file_path
from codeflash.verification.verifier import generate_tests
if TYPE_CHECKING:
import ast
from argparse import Namespace
from typing import Any
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.either import Result
from codeflash.languages.base import DependencyResolver
from codeflash.models.function_types import FunctionParent
from codeflash.models.models import (
BenchmarkKey,
CodeOptimizationContext,
CodeStringsMarkdown,
ConcurrencyMetrics,
CoverageData,
FunctionCalledInTest,
FunctionSource,
TestDiff,
TestFileReview,
)
from codeflash.verification.verification_utils import TestConfig
def log_optimization_context(function_name: str, code_context: CodeOptimizationContext) -> None:
"""Log optimization context details when in verbose mode using Rich formatting."""
if logger.getEffectiveLevel() > logging.DEBUG:
return
console.rule()
read_writable_tokens = encoded_tokens_len(code_context.read_writable_code.markdown)
read_only_tokens = (
encoded_tokens_len(code_context.read_only_context_code) if code_context.read_only_context_code else 0
)
total_tokens = read_writable_tokens + read_only_tokens
token_pct = min(total_tokens / OPTIMIZATION_CONTEXT_TOKEN_LIMIT, 1.0)
# Token bar color based on usage
bar_color = "green" if token_pct < 0.7 else "yellow" if token_pct < 0.9 else "red"
# Build compact info line
helper_names = [hf.qualified_name for hf in code_context.helper_functions]
helpers_str = f"[magenta]{', '.join(helper_names)}[/]" if helper_names else "[dim]none[/]"
read_writable_files = [str(cs.file_path) for cs in code_context.read_writable_code.code_strings]
# Create a tree view for the context
tree = Tree(f"[bold cyan]Context for {function_name}[/]")
tree.add(
Text.assemble(
("Tokens: ", "dim"),
(f"{total_tokens:,}", "bold " + bar_color),
(f"/{OPTIMIZATION_CONTEXT_TOKEN_LIMIT:,} ", "dim"),
(f"({token_pct:.0%})", bar_color),
(" [", "dim"),
(f"{read_writable_tokens:,}", "green"),
(" rw", "dim green"),
(" + ", "dim"),
(f"{read_only_tokens:,}", "yellow"),
(" ro", "dim yellow"),
("]", "dim"),
)
)
tree.add(f"[dim]Helpers:[/] {helpers_str}")
files_branch = tree.add("[dim]Files:[/]")
for f in read_writable_files:
files_branch.add(f"[blue]{f}[/]")
console.print(tree)
console.print(
Panel(
Syntax(code_context.read_writable_code.markdown, "markdown", theme="monokai", word_wrap=True),
title="[green]Read-Writable Code[/]",
border_style="green",
)
)
if code_context.read_only_context_code:
console.print(
Panel(
Syntax(code_context.read_only_context_code, "markdown", theme="monokai", word_wrap=True),
title="[yellow]Read-Only Dependencies[/]",
border_style="yellow",
)
)
class CandidateNode:
__slots__ = ("candidate", "children", "parent")
def __init__(self, candidate: OptimizedCandidate) -> None:
self.candidate = candidate
self.parent: CandidateNode | None = None
self.children: list[CandidateNode] = []
def is_leaf(self) -> bool:
return not self.children
def path_to_root(self) -> list[OptimizedCandidate]:
path = []
node: CandidateNode | None = self
while node:
path.append(node.candidate)
node = node.parent
return path[::-1]
class CandidateForest:
def __init__(self) -> None:
self.nodes: dict[str, CandidateNode] = {}
def add(self, candidate: OptimizedCandidate) -> CandidateNode:
cid = candidate.optimization_id
pid = candidate.parent_id
node = self.nodes.get(cid)
if node is None:
node = CandidateNode(candidate)
self.nodes[cid] = node
if pid is not None:
parent = self.nodes.get(pid)
if parent is None:
parent = CandidateNode(candidate=None) # placeholder
self.nodes[pid] = parent
node.parent = parent
parent.children.append(node)
return node
def get_node(self, cid: str) -> CandidateNode | None:
return self.nodes.get(cid)
class CandidateProcessor:
"""Handles candidate processing using a queue-based approach."""
def __init__(
self,
initial_candidates: list[OptimizedCandidate],
future_line_profile_results: concurrent.futures.Future,
eval_ctx: CandidateEvaluationContext,
effort: str,
original_markdown_code: str,
future_all_refinements: list[concurrent.futures.Future],
future_all_code_repair: list[concurrent.futures.Future],
future_adaptive_optimizations: list[concurrent.futures.Future],
normalize_fn: Callable[[str], str],
normalized_original: str,
original_flat_code: str,
) -> None:
self.candidate_queue = queue.Queue()
self.forest = CandidateForest()
self.line_profiler_done = False
self.refinement_done = False
self.eval_ctx = eval_ctx
self.effort = effort
self.refinement_calls_count = 0
self.original_markdown_code = original_markdown_code
self.normalize_fn = normalize_fn
self.normalized_original = normalized_original
self.original_flat_code = original_flat_code
self.seen_normalized: set[str] = set()
self.normalized_cache: dict[str, str] = {} # optimization_id -> normalized_code
deduped = self.dedup_candidates(initial_candidates)
self.candidate_len = len(deduped)
for candidate in deduped:
self.forest.add(candidate)
self.candidate_queue.put(candidate)
self.future_line_profile_results = future_line_profile_results
self.future_all_refinements = future_all_refinements
self.future_all_code_repair = future_all_code_repair
self.future_adaptive_optimizations = future_adaptive_optimizations
def dedup_candidates(self, candidates: list[OptimizedCandidate]) -> list[OptimizedCandidate]:
unique: list[OptimizedCandidate] = []
removed_original = 0
removed_cross_batch = 0
removed_duplicate = 0
for candidate in candidates:
normalized = self.normalize_fn(candidate.source_code.flat.strip())
if normalized == self.normalized_original:
removed_original += 1
continue
if normalized in self.eval_ctx.ast_code_to_id:
self.eval_ctx.handle_duplicate_candidate(candidate, normalized, self.original_flat_code)
removed_cross_batch += 1
continue
if normalized in self.seen_normalized:
# Intra-batch duplicate: no results exist yet to copy, so just drop it.
# Its optimization_id will be absent from eval_ctx results — this is intentional.
removed_duplicate += 1
continue
self.seen_normalized.add(normalized)
self.normalized_cache[candidate.optimization_id] = normalized
unique.append(candidate)
total_removed = removed_original + removed_cross_batch + removed_duplicate
if total_removed > 0:
logger.info(
f"Early dedup removed {total_removed} candidate(s) "
f"({removed_original} identical to original, "
f"{removed_cross_batch} already-benchmarked duplicates, "
f"{removed_duplicate} duplicates)"
)
return unique
def get_total_llm_calls(self) -> int:
return self.refinement_calls_count
def get_next_candidate(self) -> CandidateNode | None:
"""Get the next candidate from the queue, handling async results as needed."""
try:
return self.forest.get_node(self.candidate_queue.get_nowait().optimization_id)
except queue.Empty:
return self._handle_empty_queue()
def _handle_empty_queue(self) -> CandidateNode | None:
"""Handle empty queue by checking for pending async results."""
if not self.line_profiler_done:
return self._process_candidates(
[self.future_line_profile_results],
"all candidates processed, await candidates from line profiler",
"Added results from line profiler to candidates, total candidates now: {1}",
lambda: setattr(self, "line_profiler_done", True),
)
if len(self.future_all_code_repair) > 0:
return self._process_candidates(
self.future_all_code_repair,
"Repairing {0} candidates",
"Added {0} candidates from repair, total candidates now: {1}",
self.future_all_code_repair.clear,
)
if self.line_profiler_done and not self.refinement_done:
return self._process_candidates(
self.future_all_refinements,
"Refining generated code for improved quality and performance...",
"Added {0} candidates from refinement, total candidates now: {1}",
lambda: setattr(self, "refinement_done", True),
filter_candidates_func=self._filter_refined_candidates,
)
if len(self.future_adaptive_optimizations) > 0:
return self._process_candidates(
self.future_adaptive_optimizations,
"Applying adaptive optimizations to {0} candidates",
"Added {0} candidates from adaptive optimization, total candidates now: {1}",
self.future_adaptive_optimizations.clear,
)
return None # All done
def _process_candidates(
self,
future_candidates: list[concurrent.futures.Future],
loading_msg: str,
success_msg: str,
callback: Callable[[], None],
filter_candidates_func: Callable[[list[OptimizedCandidate]], list[OptimizedCandidate]] | None = None,
) -> CandidateNode | None:
if len(future_candidates) == 0:
return None
with progress_bar(
loading_msg.format(len(future_candidates)), transient=True, revert_to_print=bool(get_pr_number())
):
concurrent.futures.wait(future_candidates)
candidates: list[OptimizedCandidate] = []
for future_c in future_candidates:
candidate_result = future_c.result()
if not candidate_result:
continue
if isinstance(candidate_result, list):
candidates.extend(candidate_result)
else:
candidates.append(candidate_result)
candidates = filter_candidates_func(candidates) if filter_candidates_func else candidates
candidates = self.dedup_candidates(candidates)
for candidate in candidates:
self.forest.add(candidate)
self.candidate_queue.put(candidate)
self.candidate_len += 1
if len(candidates) > 0:
logger.info(success_msg.format(len(candidates), self.candidate_len))
callback()
return self.get_next_candidate()
def _filter_refined_candidates(self, candidates: list[OptimizedCandidate]) -> list[OptimizedCandidate]:
"""We generate a weighted ranking based on the runtime and diff lines and select the best of valid optimizations to be tested."""
self.refinement_calls_count += len(candidates)
top_n_candidates = int(
min(int(get_effort_value(EffortKeys.TOP_VALID_CANDIDATES_FOR_REFINEMENT, self.effort)), len(candidates))
)
if len(candidates) == top_n_candidates:
# no need for ranking since we will return all candidates
return candidates
diff_lens_list = []
runtimes_list = []
for c in candidates:
# current refined candidates is not benchmarked yet, a close values we would expect to be the parent candidate
parent_id = c.parent_id
parent_candidate_node = self.forest.get_node(parent_id)
parent_optimized_runtime = self.eval_ctx.get_optimized_runtime(parent_id)
if not parent_optimized_runtime or not parent_candidate_node:
continue
diff_lens_list.append(
diff_length(self.original_markdown_code, parent_candidate_node.candidate.source_code.markdown)
)
runtimes_list.append(parent_optimized_runtime)
if not runtimes_list or not diff_lens_list:
# should not happen
logger.warning("No valid candidates for refinement while filtering")
return candidates
runtime_w, diff_w = REFINED_CANDIDATE_RANKING_WEIGHTS
weights = choose_weights(runtime=runtime_w, diff=diff_w)
runtime_norm = normalize_by_max(runtimes_list)
diffs_norm = normalize_by_max(diff_lens_list)
# the lower the better
score_dict = create_score_dictionary_from_metrics(weights, runtime_norm, diffs_norm)
top_indecies = sorted(score_dict, key=score_dict.get)[:top_n_candidates]
return [candidates[idx] for idx in top_indecies]
def is_done(self) -> bool:
"""Check if processing is complete."""
return (
self.line_profiler_done
and self.refinement_done
and len(self.future_all_code_repair) == 0
and len(self.future_adaptive_optimizations) == 0
and self.candidate_queue.empty()
)
class FunctionOptimizer:
def __init__(
self,
function_to_optimize: FunctionToOptimize,
test_cfg: TestConfig,
function_to_optimize_source_code: str = "",
function_to_tests: dict[str, set[FunctionCalledInTest]] | None = None,
function_to_optimize_ast: ast.FunctionDef | ast.AsyncFunctionDef | None = None,
aiservice_client: AiServiceClient | None = None,
function_benchmark_timings: dict[BenchmarkKey, int] | None = None,
total_benchmark_timings: dict[BenchmarkKey, int] | None = None,
args: Namespace | None = None,
replay_tests_dir: Path | None = None,
call_graph: DependencyResolver | None = None,
effort_override: str | None = None,
) -> None:
self.project_root = test_cfg.project_root_path.resolve()
self.test_cfg = test_cfg
self.aiservice_client = aiservice_client if aiservice_client else AiServiceClient()
resolved_file_path = function_to_optimize.file_path.resolve()
if resolved_file_path != function_to_optimize.file_path:
function_to_optimize = dataclasses.replace(function_to_optimize, file_path=resolved_file_path)
self.function_to_optimize = function_to_optimize
self.function_to_optimize_source_code = (
function_to_optimize_source_code
if function_to_optimize_source_code
else function_to_optimize.file_path.read_text(encoding="utf8")
)
self.language_support = current_language_support()
if not function_to_optimize_ast:
self.function_to_optimize_ast = self._resolve_function_ast(
self.function_to_optimize_source_code, function_to_optimize.function_name, function_to_optimize.parents
)
else:
self.function_to_optimize_ast = function_to_optimize_ast
self.function_to_tests = function_to_tests if function_to_tests else {}
self.experiment_id = os.getenv("CODEFLASH_EXPERIMENT_ID", None)
self.local_aiservice_client = LocalAiServiceClient() if self.experiment_id else None
self.test_files = TestFiles(test_files=[])
default_effort = getattr(args, "effort", EffortLevel.MEDIUM.value) if args else EffortLevel.MEDIUM.value
self.effort = effort_override or default_effort
self.args = args # Check defaults for these
self.function_trace_id: str = str(uuid.uuid4())
# Get module path using language support (handles Python vs JavaScript differences)
self.original_module_path = self.language_support.get_module_path(
source_file=self.function_to_optimize.file_path,
project_root=self.project_root,
tests_root=test_cfg.tests_root,
)
self.function_benchmark_timings = function_benchmark_timings if function_benchmark_timings else {}
self.total_benchmark_timings = total_benchmark_timings if total_benchmark_timings else {}
self.replay_tests_dir = replay_tests_dir if replay_tests_dir else None
self.call_graph = call_graph
n_tests = get_effort_value(EffortKeys.N_GENERATED_TESTS, self.effort)
self.executor = concurrent.futures.ThreadPoolExecutor(
max_workers=n_tests + 3 if self.experiment_id is None else n_tests + 4
)
self.optimization_review = ""
self.future_all_code_repair: list[concurrent.futures.Future] = []
self.future_all_refinements: list[concurrent.futures.Future] = []
self.future_adaptive_optimizations: list[concurrent.futures.Future] = []
self.repair_counter = 0 # track how many repairs we did for each function
self.adaptive_optimization_counter = 0 # track how many adaptive optimizations we did for each function
self.is_numerical_code: bool | None = None
self.code_already_exists: bool = False
# --- Hooks for language-specific subclasses ---
def _resolve_function_ast(
self, source_code: str, function_name: str, parents: list[FunctionParent]
) -> ast.FunctionDef | ast.AsyncFunctionDef | None:
return None
def requires_function_ast(self) -> bool:
return False
def analyze_code_characteristics(self, code_context: CodeOptimizationContext) -> None:
pass
def get_optimization_review_metrics(
self,
source_code: str,
file_path: Path,
qualified_name: str,
project_root: Path,
tests_root: Path,
language: Language,
) -> str:
return ""
def instrument_test_fixtures(self, test_paths: list[Path]) -> dict[Path, list[str]] | None:
return None
def instrument_async_for_mode(self, mode: TestingMode) -> None:
pass
def instrument_capture(self, file_path_to_helper_classes: dict[Path, set[str]]) -> None:
pass
def should_check_coverage(self) -> bool:
return False
def collect_async_metrics(
self,
benchmarking_results: TestResults,
code_context: CodeOptimizationContext,
helper_code: dict[Path, str],
test_env: dict[str, str],
) -> tuple[int | None, ConcurrencyMetrics | None]:
return None, None
def compare_candidate_results(
self,
baseline_results: OriginalCodeBaseline,
candidate_behavior_results: TestResults,
optimization_candidate_index: int,
) -> tuple[bool, list[TestDiff]]:
return compare_test_results(
baseline_results.behavior_test_results, candidate_behavior_results, pass_fail_only=True
)
def should_skip_sqlite_cleanup(self, testing_type: TestingMode, optimization_iteration: int) -> bool:
return False
def parse_line_profile_test_results(
self, line_profiler_output_file: Path | None
) -> tuple[TestResults | dict, CoverageData | None]:
return TestResults(test_results=[]), None
def fixup_generated_tests(self, generated_tests: GeneratedTestsList) -> GeneratedTestsList:
return generated_tests
# --- End hooks ---
def can_be_optimized(self) -> Result[tuple[bool, CodeOptimizationContext, dict[Path, str]], str]:
should_run_experiment = self.experiment_id is not None
logger.info(f"!lsp|Function Trace ID: {self.function_trace_id}")
ph("cli-optimize-function-start", {"function_trace_id": self.function_trace_id})
# Early check: if --no-gen-tests is set, verify there are existing tests for this function
if self.args.no_gen_tests:
func_qualname = self.function_to_optimize.qualified_name_with_modules_from_root(self.project_root)
if not self.function_to_tests.get(func_qualname):
return Failure(
f"No existing tests found for '{self.function_to_optimize.function_name}'. "
f"Cannot optimize without tests when --no-gen-tests is set."
)
self.cleanup_leftover_test_return_values()
file_name_from_test_module_name.cache_clear()
ctx_result = self.get_code_optimization_context()
if not is_successful(ctx_result):
return Failure(ctx_result.failure())
code_context: CodeOptimizationContext = ctx_result.unwrap()
log_optimization_context(self.function_to_optimize.function_name, code_context)
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
# Random here means that we still attempt optimization with a fractional chance to see if
# last time we could not find an optimization, maybe this time we do.
# Random is before as a performance optimization, swapping the two 'and' statements has the same effect
self.code_already_exists = was_function_previously_optimized(self.function_to_optimize, code_context, self.args)
if random.random() > REPEAT_OPTIMIZATION_PROBABILITY and self.code_already_exists: # noqa: S311
return Failure("Function optimization previously attempted, skipping.")
return Success((should_run_experiment, code_context, original_helper_code))
def generate_and_instrument_tests(
self, code_context: CodeOptimizationContext
) -> Result[
tuple[
GeneratedTestsList,
dict[str, set[FunctionCalledInTest]],
str,
list[Path],
list[Path],
set[Path],
dict | None,
],
str,
]:
"""Generate and instrument tests for the function."""
n_tests = get_effort_value(EffortKeys.N_GENERATED_TESTS, self.effort)
source_file = Path(self.function_to_optimize.file_path)
generated_test_paths = [
get_test_file_path(
self.test_cfg.tests_root,
self.function_to_optimize.function_name,
test_index,
test_type="unit",
source_file_path=source_file,
)
for test_index in range(n_tests)
]
generated_perf_test_paths = [
get_test_file_path(
self.test_cfg.tests_root,
self.function_to_optimize.function_name,
test_index,
test_type="perf",
source_file_path=source_file,
)
for test_index in range(n_tests)
]
# Note: JavaScript/TypeScript runtime is provided by codeflash npm package
# which is installed automatically by test_runner.py._ensure_runtime_files()
# No manual file copying is needed here.
test_results = self.generate_tests(
testgen_context=code_context.testgen_context,
helper_functions=code_context.helper_functions,
testgen_helper_fqns=code_context.testgen_helper_fqns,
generated_test_paths=generated_test_paths,
generated_perf_test_paths=generated_perf_test_paths,
)
if not is_successful(test_results):
return Failure(test_results.failure())
count_tests, generated_tests, function_to_concolic_tests, concolic_test_str = test_results.unwrap()
# Language-specific postprocessing for generated tests
generated_tests = self.language_support.postprocess_generated_tests(
generated_tests,
test_framework=self.test_cfg.test_framework,
project_root=self.project_root,
source_file_path=self.function_to_optimize.file_path,
)
generated_tests = self.fixup_generated_tests(generated_tests)
logger.debug(f"[PIPELINE] Processing {count_tests} generated tests")
for i, generated_test in enumerate(generated_tests.generated_tests):
logger.debug(
f"[PIPELINE] Test {i + 1}: behavior_path={generated_test.behavior_file_path}, perf_path={generated_test.perf_file_path}"
)
with generated_test.behavior_file_path.open("w", encoding="utf8") as f:
f.write(generated_test.instrumented_behavior_test_source)
logger.debug(f"[PIPELINE] Wrote behavioral test to {generated_test.behavior_file_path}")
# Save perf test source for debugging
debug_file_path = get_run_tmp_file(Path("perf_test_debug.test.ts"))
with debug_file_path.open("w", encoding="utf-8") as debug_f:
debug_f.write(generated_test.instrumented_perf_test_source)
with generated_test.perf_file_path.open("w", encoding="utf8") as f:
f.write(generated_test.instrumented_perf_test_source)
logger.debug(f"[PIPELINE] Wrote perf test to {generated_test.perf_file_path}")
# File paths are expected to be absolute - resolved at their source (CLI, TestConfig, etc.)
test_file_obj = TestFile(
instrumented_behavior_file_path=generated_test.behavior_file_path,
benchmarking_file_path=generated_test.perf_file_path,
original_file_path=None,
original_source=generated_test.generated_original_test_source,
test_type=TestType.GENERATED_REGRESSION,
tests_in_file=None, # This is currently unused. We can discover the tests in the file if needed.
)
self.test_files.add(test_file_obj)
logger.debug(
f"[PIPELINE] Added test file to collection: behavior={test_file_obj.instrumented_behavior_file_path}, perf={test_file_obj.benchmarking_file_path}"
)
logger.info(f"Generated test {i + 1}/{count_tests}:")
# Use correct extension based on language
test_ext = self.language_support.get_test_file_suffix()
# Show the raw LLM output when available, otherwise the post-processed source
display_source = generated_test.raw_generated_test_source or generated_test.generated_original_test_source
code_print(display_source, file_name=f"test_{i + 1}{test_ext}", language=self.function_to_optimize.language)
if concolic_test_str:
logger.info(f"Generated test {count_tests}/{count_tests}:")
code_print(concolic_test_str, language=self.function_to_optimize.language)
function_to_all_tests = {
key: self.function_to_tests.get(key, set()) | function_to_concolic_tests.get(key, set())
for key in set(self.function_to_tests) | set(function_to_concolic_tests)
}
instrumented_unittests_created_for_function = self.instrument_existing_tests(function_to_all_tests)
original_conftest_content = None
if self.args.override_fixtures:
original_conftest_content = self.instrument_test_fixtures(generated_test_paths + generated_perf_test_paths)
return Success(
(
generated_tests,
function_to_concolic_tests,
concolic_test_str,
generated_test_paths,
generated_perf_test_paths,
instrumented_unittests_created_for_function,
original_conftest_content,
)
)
# note: this isn't called by the lsp, only called by cli
def optimize_function(self) -> Result[BestOptimization, str]:
initialization_result = self.can_be_optimized()
if not is_successful(initialization_result):
return Failure(initialization_result.failure())
should_run_experiment, code_context, original_helper_code = initialization_result.unwrap()
self.analyze_code_characteristics(code_context)
code_print(
code_context.read_writable_code.flat,
file_name=self.function_to_optimize.file_path,
function_name=self.function_to_optimize.function_name,
language=self.function_to_optimize.language,
)
with progress_bar(
f"Generating new tests and optimizations for function '{self.function_to_optimize.function_name}'",
transient=True,
revert_to_print=bool(get_pr_number()),
):
console.rule()
new_code_context = code_context
# Generate tests and optimizations in parallel
future_tests = self.executor.submit(self.generate_and_instrument_tests, new_code_context)
future_optimizations = self.executor.submit(
self.generate_optimizations,
read_writable_code=code_context.read_writable_code,
read_only_context_code=code_context.read_only_context_code,
run_experiment=should_run_experiment,
is_numerical_code=self.is_numerical_code and not self.args.no_jit_opts,
)
concurrent.futures.wait([future_tests, future_optimizations])
test_setup_result = future_tests.result()
optimization_result = future_optimizations.result()
console.rule()
if not is_successful(test_setup_result):
return Failure(test_setup_result.failure())
if not is_successful(optimization_result):
return Failure(optimization_result.failure())
(
generated_tests,
function_to_concolic_tests,
concolic_test_str,
generated_test_paths,
generated_perf_test_paths,
instrumented_unittests_created_for_function,
original_conftest_content,
) = test_setup_result.unwrap()
optimizations_set, function_references = optimization_result.unwrap()
precomputed_behavioral: tuple[TestResults, CoverageData | None] | None = None
if generated_tests.generated_tests and self.args.testgen_review:
review_result = self.review_and_repair_tests(
generated_tests=generated_tests, code_context=code_context, original_helper_code=original_helper_code
)
if not is_successful(review_result):
return Failure(review_result.failure())
generated_tests, review_behavioral, review_coverage = review_result.unwrap()
if review_behavioral is not None:
precomputed_behavioral = (review_behavioral, review_coverage)
# Full baseline (behavioral + benchmarking) runs once on the final approved tests
baseline_setup_result = self.setup_and_establish_baseline(
code_context=code_context,
original_helper_code=original_helper_code,
function_to_concolic_tests=function_to_concolic_tests,
generated_test_paths=generated_test_paths,
generated_perf_test_paths=generated_perf_test_paths,
instrumented_unittests_created_for_function=instrumented_unittests_created_for_function,
original_conftest_content=original_conftest_content,
precomputed_behavioral=precomputed_behavioral,
)
if not is_successful(baseline_setup_result):
return Failure(baseline_setup_result.failure())
(
function_to_optimize_qualified_name,
function_to_all_tests,
original_code_baseline,
test_functions_to_remove,
file_path_to_helper_classes,
) = baseline_setup_result.unwrap()
best_optimization = self.find_and_process_best_optimization(
optimizations_set=optimizations_set,
code_context=code_context,
original_code_baseline=original_code_baseline,
original_helper_code=original_helper_code,
file_path_to_helper_classes=file_path_to_helper_classes,
function_to_optimize_qualified_name=function_to_optimize_qualified_name,
function_to_all_tests=function_to_all_tests,
generated_tests=generated_tests,
test_functions_to_remove=test_functions_to_remove,
concolic_test_str=concolic_test_str,
function_references=function_references,
)
# Add function to code context hash if in gh actions and code doesn't already exist
if not self.code_already_exists:
add_code_context_hash(code_context.hashing_code_context_hash)
if self.args.override_fixtures:
restore_conftest(original_conftest_content)
if not best_optimization:
return Failure(f"No best optimizations found for function {self.function_to_optimize.qualified_name}")
return Success(best_optimization)
@property
def rerun_trace_id(self) -> str | None:
return getattr(self.args, "rerun", None) if self.args else None
def get_trace_id(self, exp_type: str) -> str:
"""Get the trace ID for the current experiment type."""
if self.experiment_id:
return self.function_trace_id[:-4] + exp_type
return self.function_trace_id
def build_runtime_info_tree(
self,
candidate_index: int,
candidate_result: OptimizedCandidateResult,
original_code_baseline: OriginalCodeBaseline,
perf_gain: float,
*,
is_successful_candidate: bool,
) -> Tree:
"""Build a Tree display for runtime information of a candidate."""
tree = Tree(f"Candidate #{candidate_index} - Runtime Information ⌛")
is_async = original_code_baseline.async_throughput is not None and candidate_result.async_throughput is not None
if is_successful_candidate:
if is_async:
throughput_gain_value = throughput_gain(
original_throughput=original_code_baseline.async_throughput,
optimized_throughput=candidate_result.async_throughput,
)
tree.add("This candidate has better async throughput than the original code. 🚀")
tree.add(f"Original async throughput: {original_code_baseline.async_throughput} executions")
tree.add(f"Optimized async throughput: {candidate_result.async_throughput} executions")
tree.add(f"Throughput improvement: {throughput_gain_value * 100:.1f}%")
tree.add(f"Throughput ratio: {throughput_gain_value + 1:.3f}X")
# Display concurrency metrics if available
if candidate_result.concurrency_metrics and original_code_baseline.concurrency_metrics:
orig_ratio = original_code_baseline.concurrency_metrics.concurrency_ratio
cand_ratio = candidate_result.concurrency_metrics.concurrency_ratio
conc_gain = ((cand_ratio - orig_ratio) / orig_ratio * 100) if orig_ratio > 0 else 0
tree.add(f"Concurrency ratio: {orig_ratio:.2f}x → {cand_ratio:.2f}x ({conc_gain:+.1f}%)")
else:
tree.add("This candidate is faster than the original code. 🚀")
tree.add(f"Original summed runtime: {humanize_runtime(original_code_baseline.runtime)}")
tree.add(
f"Best summed runtime: {humanize_runtime(candidate_result.best_test_runtime)} "
f"(measured over {candidate_result.max_loop_count} "
f"loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
tree.add(f"Speedup percentage: {perf_gain * 100:.1f}%")
tree.add(f"Speedup ratio: {perf_gain + 1:.3f}X")
# Not a successful optimization candidate
elif is_async:
throughput_gain_value = throughput_gain(
original_throughput=original_code_baseline.async_throughput,
optimized_throughput=candidate_result.async_throughput,
)
tree.add(f"Async throughput: {candidate_result.async_throughput} executions")
tree.add(f"Throughput change: {throughput_gain_value * 100:.1f}%")
# Display concurrency metrics if available
if candidate_result.concurrency_metrics and original_code_baseline.concurrency_metrics:
orig_ratio = original_code_baseline.concurrency_metrics.concurrency_ratio
cand_ratio = candidate_result.concurrency_metrics.concurrency_ratio
conc_gain = ((cand_ratio - orig_ratio) / orig_ratio * 100) if orig_ratio > 0 else 0
tree.add(f"Concurrency ratio: {orig_ratio:.2f}x → {cand_ratio:.2f}x ({conc_gain:+.1f}%)")
tree.add(
f"(Runtime for reference: {humanize_runtime(candidate_result.best_test_runtime)} over "
f"{candidate_result.max_loop_count} loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
else:
tree.add(
f"Summed runtime: {humanize_runtime(candidate_result.best_test_runtime)} "
f"(measured over {candidate_result.max_loop_count} "
f"loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
tree.add(f"Speedup percentage: {perf_gain * 100:.1f}%")
tree.add(f"Speedup ratio: {perf_gain + 1:.3f}X")
return tree
def handle_successful_candidate(
self,
candidate: OptimizedCandidate,
candidate_result: OptimizedCandidateResult,
code_context: CodeOptimizationContext,
original_code_baseline: OriginalCodeBaseline,
original_helper_code: dict[Path, str],
candidate_index: int,
eval_ctx: CandidateEvaluationContext,
) -> tuple[BestOptimization, Tree | None]:
"""Handle a successful optimization candidate.
Returns the BestOptimization and optional benchmark tree.
"""
with progress_bar("Running line-by-line profiling"):
line_profile_test_results = self.line_profiler_step(
code_context=code_context, original_helper_code=original_helper_code, candidate_index=candidate_index
)
eval_ctx.record_line_profiler_result(candidate.optimization_id, line_profile_test_results["str_out"])
replay_perf_gain = {}
benchmark_tree = None
if self.args.benchmark:
test_results_by_benchmark = candidate_result.benchmarking_test_results.group_by_benchmarks(
self.total_benchmark_timings.keys(), self.replay_tests_dir, self.project_root
)
if len(test_results_by_benchmark) > 0:
benchmark_tree = Tree("Speedup percentage on benchmarks:")
for benchmark_key, candidate_test_results in test_results_by_benchmark.items():
original_code_replay_runtime = original_code_baseline.replay_benchmarking_test_results[
benchmark_key
].total_passed_runtime()
candidate_replay_runtime = candidate_test_results.total_passed_runtime()
replay_perf_gain[benchmark_key] = performance_gain(
original_runtime_ns=original_code_replay_runtime, optimized_runtime_ns=candidate_replay_runtime
)