@@ -409,6 +409,12 @@ def run(self) -> None:
409409 if self .args .worktree :
410410 self .worktree_mode ()
411411
412+ if not self .args .replay_test and self .test_cfg .tests_root .exists ():
413+ leftover_trace_files = list (self .test_cfg .tests_root .glob ("*.trace" ))
414+ if leftover_trace_files :
415+ logger .debug (f"Cleaning up { len (leftover_trace_files )} leftover trace file(s) from previous runs" )
416+ cleanup_paths (leftover_trace_files )
417+
412418 cleanup_paths (Optimizer .find_leftover_instrumented_test_files (self .test_cfg .tests_root ))
413419
414420 function_optimizer = None
@@ -519,6 +525,8 @@ def run(self) -> None:
519525 )
520526 if self .functions_checkpoint :
521527 self .functions_checkpoint .cleanup ()
528+ if hasattr (self .args , "command" ) and self .args .command == "optimize" :
529+ self .cleanup_replay_tests ()
522530 if optimizations_found == 0 :
523531 logger .info ("❌ No optimizations found." )
524532 elif self .args .all :
@@ -554,6 +562,17 @@ def find_leftover_instrumented_test_files(test_root: Path) -> list[Path]:
554562 file_path for file_path in test_root .rglob ("*" ) if file_path .is_file () and pattern .match (file_path .name )
555563 ]
556564
565+ def cleanup_replay_tests (self ) -> None :
566+ paths_to_cleanup = []
567+ if self .replay_tests_dir and self .replay_tests_dir .exists ():
568+ logger .debug (f"Cleaning up replay tests directory: { self .replay_tests_dir } " )
569+ paths_to_cleanup .append (self .replay_tests_dir )
570+ if self .trace_file and self .trace_file .exists ():
571+ logger .debug (f"Cleaning up trace file: { self .trace_file } " )
572+ paths_to_cleanup .append (self .trace_file )
573+ if paths_to_cleanup :
574+ cleanup_paths (paths_to_cleanup )
575+
557576 def cleanup_temporary_paths (self ) -> None :
558577 if hasattr (get_run_tmp_file , "tmpdir" ):
559578 get_run_tmp_file .tmpdir .cleanup ()
@@ -568,6 +587,14 @@ def cleanup_temporary_paths(self) -> None:
568587
569588 if self .current_function_optimizer :
570589 self .current_function_optimizer .cleanup_generated_files ()
590+ paths_to_cleanup = [self .replay_tests_dir ]
591+ if self .trace_file :
592+ paths_to_cleanup .append (self .trace_file )
593+ if self .test_cfg .tests_root .exists ():
594+ for trace_file in self .test_cfg .tests_root .glob ("*.trace" ):
595+ if trace_file not in paths_to_cleanup :
596+ paths_to_cleanup .append (trace_file )
597+ cleanup_paths (paths_to_cleanup )
571598
572599 def worktree_mode (self ) -> None :
573600 if self .current_worktree :
0 commit comments