-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathrun_patch_pipeline.py
More file actions
1614 lines (1331 loc) · 66.2 KB
/
run_patch_pipeline.py
File metadata and controls
1614 lines (1331 loc) · 66.2 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
"""
Main script for patch generation and test verification
Extracts patch generation functionality from the original run_agent_on_swebench_problem.py,
and can optionally invoke test generation and validation functions.
"""
from functools import partial
import os
import logging
import threading
import sys
import json
import argparse
import shutil
from pathlib import Path
from multiprocessing import Pool, Manager
import time
import numpy as np
from typing import Optional, Dict, List, Tuple
from rich.console import Console
from rich.panel import Panel
from datasets import load_dataset
from utils.docker_utils import MAX_RUNTIME_PARALLELISM, configure_project_space, terminate_runtime_pod
from utils.common import create_modification
from utils.trajectory_recorder import create_execution_path_tracker
from cli import main as cli_main
from test import execute_tests_in_container, validate_diff_quality
import uuid
def get_dataset_name(dataset: str) -> str:
"""Get the dataset name for the specified dataset."""
return {
"verified": "princeton-nlp/SWE-bench_Verified",
"full": "princeton-nlp/SWE-bench",
"lite": "princeton-nlp/SWE-bench_Lite",
}[dataset]
def generate_tests_if_needed(
problem_id: str,
problem_statement: str,
container_id: str,
workspace_path: Path,
console: Console,
generate_tests: bool = True
) -> Tuple[Dict, Dict]:
"""
Generate test cases if needed
Args:
problem_id: Problem ID
problem_statement: Problem description
container_id: Docker container ID
workspace_path: Workspace path
console: Console object
generate_tests: Whether to generate tests
Returns:
tuple: (test generation result, pre-validation result)
"""
if not generate_tests:
console.print(f"[bold blue]{problem_id}[/bold blue] Skipping test generation (disabled)")
return {"test_generation_success": False, "skipped": True}, {"validation_success": False, "skipped": True}
# Check if test cases already exist
output_dir = Path(f"output_files/{problem_id}")
test_result_file = output_dir / "test_generation_result.json"
if test_result_file.exists():
console.print(f"[bold blue]{problem_id}[/bold blue] Found existing test generation results")
try:
with open(test_result_file, 'r') as f:
existing_result = json.load(f)
if existing_result.get("test_generation_success", False):
console.print(f"[bold blue]{problem_id}[/bold blue] Using existing test cases")
return existing_result.get("test_generation_result", {}), existing_result.get("pre_validation_result", {})
except Exception as e:
console.print(f"[bold blue]{problem_id}[/bold blue] Failed to load existing test results: {e}")
# Generate new test cases
console.print(f"[bold blue]{problem_id}[/bold blue] Generating new test cases...")
try:
from test_case_generator import (
generate_test_cases_in_container,
copy_test_cases_to_output,
validate_test_cases_against_original_code
)
test_generation_result = generate_test_cases_in_container(
container_id=container_id,
problem_statement=problem_statement,
problem_id=problem_id,
console=console,
workspace_path=workspace_path / problem_id,
output_file=workspace_path / "test_generation_logs.txt",
quiet=True # Reduce verbose output
)
pre_validation_result = {"validation_success": False}
if test_generation_result["test_generation_success"]:
console.print(f"[bold blue]{problem_id}[/bold blue] Test cases generated successfully")
# Pre-execute test cases for validation
console.print(f"[bold blue]{problem_id}[/bold blue] Pre-executing test cases to validate expected behavior...")
pre_validation_result = validate_test_cases_against_original_code(container_id, console)
# Copy test cases to output directory
copy_success = copy_test_cases_to_output(container_id, problem_id, console)
if copy_success:
console.print(f"[bold blue]{problem_id}[/bold blue] ✅ Test cases copied to output directory")
# Save test generation result
test_result_data = {
"instance_id": problem_id,
"test_generation_success": True,
"test_generation_result": test_generation_result,
"pre_validation_result": pre_validation_result,
"generated_at": time.strftime('%Y-%m-%d %H:%M:%S')
}
output_dir.mkdir(parents=True, exist_ok=True)
with open(test_result_file, "w") as f:
json.dump(test_result_data, f, indent=2)
else:
console.print(f"[bold blue]{problem_id}[/bold blue] Test case generation failed")
return test_generation_result, pre_validation_result
except Exception as e:
console.print(f"[bold blue]{problem_id}[/bold blue] Test case generation failed: {e}")
return {"test_generation_success": False, "error": str(e)}, {"validation_success": False}
def run_patch_generation_with_test(
problem_id: str,
problem_statement: str,
rollout_idx: int,
workspace_base_path: Path,
lock: threading.Lock,
semaphore: threading.Semaphore,
generate_tests: bool = True,
validate_with_tests: bool = True
) -> tuple[str, float]:
"""
Run patch generation, optionally generate and validate tests
Args:
problem_id: Problem ID
problem_statement: Problem description
rollout_idx: rollout index
workspace_base_path: Workspace base path
lock: Thread lock
semaphore: Semaphore
generate_tests: Whether to generate tests
validate_with_tests: Whether to validate the patch with tests
Returns:
tuple: (generated diff, duration)
"""
console = Console()
logs_prefix = f"[bold blue]{problem_id}[/bold blue]"
workspace_path = workspace_base_path / problem_id / f"rollout_{rollout_idx}"
output_file = workspace_path / "agent_logs.txt"
# Ensure workspace directory exists
workspace_path.mkdir(parents=True, exist_ok=True)
# Create trajectory recorder
trajectory_recorder = create_execution_path_tracker(problem_id, problem_statement)
# Start Docker container
container_id = None
diff = ""
try:
env, container_id = configure_project_space(workspace_path, problem_id, lock, semaphore)
console.print(f"{logs_prefix} Docker container started with ID: {container_id}")
# Set environment variables
for key, value in env.items():
os.environ[key] = value
# Generate test cases (if enabled)
test_generation_result, pre_validation_result = generate_tests_if_needed(
problem_id, problem_statement, container_id, workspace_path, console, generate_tests
)
# Record test generation stage
trajectory_recorder.record_test_generation(test_generation_result, pre_validation_result)
# Save original sys.argv
original_argv = sys.argv.copy()
# Create new sys.argv for cli.py
cli_args = [
"cli.py",
"--workspace",
str(workspace_path / problem_id),
"--problem-statement",
problem_statement,
"--docker-container-id",
container_id,
"--use-container-workspace",
"/testbed",
"--minimize-stdout-logs",
]
# If output file is specified, set the log path
if output_file:
cli_args.extend(["--logs-path", str(output_file)])
# Replace sys.argv with our custom arguments
sys.argv = cli_args
# Now run the main agent to generate diff
console.print(f"{logs_prefix} Starting agent run to generate diff...")
start_time = time.time()
cli_main()
agent_duration = time.time() - start_time
console.print(f"{logs_prefix} Agent run completed in {agent_duration:.2f}s.")
# Restore original sys.argv
sys.argv = original_argv
# Generate patch from Docker container
console.print(f"{logs_prefix} Generating patch from container {container_id}...")
try:
# First try generating patch from the container
diff = create_modification(None, container_id=container_id)
console.print(f"{logs_prefix} Patch generated successfully from container")
except Exception as container_e:
console.print(f"{logs_prefix} ⚠️ Failed to generate patch from container: {container_e}")
# Fallback: try generating from host path
repo_path = str(workspace_path / problem_id)
console.print(f"{logs_prefix} Trying fallback: generating patch from host path {repo_path}...")
try:
diff = create_modification(repo_path)
console.print(f"{logs_prefix} Patch generated successfully from host path")
except (FileNotFoundError, ValueError) as e:
console.print(f"{logs_prefix} ❌ Failed to generate patch from both container and host: {e}")
diff = ""
# Record diff generation stage
trajectory_recorder.record_diff_generation(diff, agent_duration, output_file)
# Save predictions.json
with (workspace_path / "predictions.json").open("w") as f:
json.dump(
[
{
"instance_id": problem_id,
"model_name_or_path": "JoyCode-agent",
"model_patch": diff,
}
],
f,
indent=2,
)
# Execute test validation (if enabled and tests exist)
if validate_with_tests and test_generation_result.get("test_generation_success", False):
console.print(f"{logs_prefix} Running test validation on generated test cases...")
try:
# Run tests to validate diff quality
_, test_results = execute_tests_in_container(container_id, console)
# Validate diff quality
validation_result = validate_diff_quality(test_results, console)
test_validation_passed = validation_result.get("validation_passed", False)
if test_validation_passed:
console.print(f"{logs_prefix} Test validation completed: PASS")
else:
console.print(f"{logs_prefix} Test validation completed: FAIL")
# Record test validation stage
trajectory_recorder.record_test_validation(test_validation_passed, test_results, validation_result)
# Update predictions.json with validation results
predictions_data = json.loads((workspace_path / "predictions.json").read_text())
predictions_data[0]["pre_execution_validation"] = pre_validation_result
predictions_data[0]["post_execution_validation"] = {
"test_results": test_results,
"validation_summary": validation_result
}
with (workspace_path / "predictions.json").open("w") as f:
json.dump(predictions_data, f, indent=2)
except Exception as e:
console.print(f"{logs_prefix} Test validation failed: {e}")
else:
if not validate_with_tests:
console.print(f"{logs_prefix} Skipping test validation (disabled)")
else:
console.print(f"{logs_prefix} Skipping test validation - no test cases generated")
# Save important output files
console.print(f"{logs_prefix} Saving important output files...")
try:
# Create output directory
output_dir = Path(f"output_files/{problem_id}")
output_dir.mkdir(parents=True, exist_ok=True)
# Save predictions.json
predictions_source = workspace_path / "predictions.json"
predictions_dest = output_dir / "predictions.json"
if predictions_source.exists():
shutil.copy2(predictions_source, predictions_dest)
console.print(f"{logs_prefix} Predictions saved to {predictions_dest}")
# Save agent_logs.txt
agent_logs_source = workspace_path / "agent_logs.txt"
agent_logs_dest = output_dir / "agent_logs.txt"
if agent_logs_source.exists():
shutil.copy2(agent_logs_source, agent_logs_dest)
console.print(f"{logs_prefix} Agent logs saved to {agent_logs_dest}")
# Set final result to the trajectory recorder
final_result = {
"model_patch": diff,
"predictions_file_saved": predictions_dest.exists() if predictions_dest else False,
"agent_logs_saved": agent_logs_dest.exists() if agent_logs_dest else False
}
trajectory_recorder.set_final_result(final_result)
console.print(f"{logs_prefix} Key output files saved")
console.print(f"{logs_prefix} Complete trajectory saved to: {trajectory_recorder.trajectory_file}")
except Exception as e:
console.print(f"{logs_prefix} Warning: Failed to save some output files: {e}")
finally:
# Stop and clean up Docker container
if container_id is not None:
console.print(f"{logs_prefix} Stopping Docker container...")
terminate_runtime_pod(container_id)
console.print(f"{logs_prefix} Docker container stopped")
assert diff is not None
return diff, agent_duration
def _save_case_id_lists(successful: List[str], failed: List[str], empty: List[str]):
"""
Save the IDs of successful, failed, and empty-diff cases to text files under the output_files directory.
Args:
successful: List of IDs of successful cases
failed: List of IDs of failed cases
empty: List of IDs of empty-diff cases
"""
try:
# Ensure output_files directory exists
output_files_dir = Path("output_files")
output_files_dir.mkdir(parents=True, exist_ok=True)
with open(output_files_dir / "successful_cases.txt", "w") as f:
f.write("Successful Cases:\n")
for case_id in successful:
f.write(f"- {case_id}\n")
with open(output_files_dir / "failed_cases.txt", "w") as f:
f.write("Failed Cases:\n")
for case_id in failed:
f.write(f"- {case_id}\n")
with open(output_files_dir / "empty_diff_cases.txt", "w") as f:
f.write("Empty Diff Cases:\n")
for case_id in empty:
f.write(f"- {case_id}\n")
console = Console()
console.print("✅ Case ID lists have been saved to files under the output_files directory.")
console.print(" - output_files/successful_cases.txt")
console.print(" - output_files/failed_cases.txt")
console.print(" - output_files/empty_diff_cases.txt")
except Exception as e:
console = Console()
console.print(f"💥 Failed to save case ID lists: {e}")
def _build_experience_prompt(similar_case: Optional[Dict] = None) -> str:
"""
Build experience prompts based on a similar case
Args:
similar_case: Compressed trajectory info of the similar case; if None, return an empty prompt
Returns:
Experience prompt string
"""
if not similar_case:
return ""
instance_id = similar_case.get("instance", "unknown")
strategy = similar_case.get("strategy", "N/A")
key_changes = similar_case.get("key_changes", "N/A")
similarity_score = similar_case.get("similarity_score", -1)
experience_prompt = f"""
Based on the experience from high-quality similar case {instance_id} (similarity: {similarity_score}), please retry solving the current problem:
**Successful Strategy**: {strategy}
**Key Changes**: {key_changes}
Please refer to this successful case's approach, re-analyze the current problem and generate a fix.
"""
return experience_prompt
def _retry_generate_diff_with_experience(
instance_id: str,
original_problem_statement: str,
experience_prompt: str,
workspace_base_path: Path,
lock,
semaphore
) -> tuple[Optional[str], Optional[str]]:
"""
Regenerate diff based on experience prompts (no test generation)
Args:
instance_id: Instance ID
original_problem_statement: Original problem description
experience_prompt: Experience prompt
workspace_base_path: Workspace base path
lock: Thread lock
semaphore: Semaphore
Returns:
tuple: (generated diff string, retry log file path); (None, None) if failed
"""
try:
import os
console = Console()
logs_prefix = f"[bold blue]{instance_id}[/bold blue]"
# 🔥 Use the same workspace path structure, but mark as retry
workspace_path = workspace_base_path / instance_id / "retry"
# Ensure workspace directory exists
workspace_path.mkdir(parents=True, exist_ok=True)
# Start Docker container (reuse main workflow's startup logic)
container_id = None
try:
env, container_id = configure_project_space(workspace_path, instance_id, lock, semaphore)
console.print(f"{logs_prefix} Docker container started with ID: {container_id}")
# Set environment variables
for key, value in env.items():
os.environ[key] = value
# Save original sys.argv
original_argv = sys.argv.copy()
# Add experience guidance to the full prompt template
if experience_prompt:
problem_statement = original_problem_statement + f"\n\n--- Experience Guidance from Successful Case ---\n{experience_prompt}"
else:
problem_statement = original_problem_statement + "\n\n--- Retry Mode ---\nThis is retry mode, please re-analyze the current problem and generate a fix."
cli_args = [
"cli.py",
"--agent-purpose", "retry_agent", # Use retry_agent-specific configuration
"--workspace",
str(workspace_path / instance_id),
"--problem-statement",
problem_statement,
"--docker-container-id",
container_id,
"--use-container-workspace",
"/testbed",
"--minimize-stdout-logs",
]
# Set logs path
output_file = workspace_path / "retry_agent_logs.txt"
cli_args.extend(["--logs-path", str(output_file)])
# Replace sys.argv
sys.argv = cli_args
# Run the agent to generate diff
start_time = time.time()
cli_main()
agent_duration = time.time() - start_time
console.print(f"{logs_prefix} Agent run completed in {agent_duration:.2f}s.")
# Restore original sys.argv
sys.argv = original_argv
# Generate patch - prefer from container
console.print(f"{logs_prefix} Generating patch from container {container_id}...")
try:
diff = create_modification(None, container_id=container_id)
console.print(f"{logs_prefix} Patch generated successfully from container")
except Exception as container_e:
console.print(f"{logs_prefix} ⚠️ Failed to generate patch from container: {container_e}")
# Fallback to host path
repo_path = str(workspace_path / instance_id)
console.print(f"{logs_prefix} Trying fallback: generating patch from host path {repo_path}...")
console.print(f"{logs_prefix} Debug: repo_path exists: {os.path.exists(repo_path)}")
if os.path.exists(repo_path):
console.print(f"{logs_prefix} Debug: repo_path is symlink: {os.path.islink(repo_path)}")
if os.path.islink(repo_path):
real_path = os.path.realpath(repo_path)
console.print(f"{logs_prefix} Debug: real_path: {real_path}")
console.print(f"{logs_prefix} Debug: real_path exists: {os.path.exists(real_path)}")
try:
diff = create_modification(repo_path)
console.print(f"{logs_prefix} Patch generated successfully from host path")
except Exception as host_e:
console.print(f"{logs_prefix} ❌ Failed to generate patch from both container and host: {host_e}")
diff = None
if diff:
console.print(f"{logs_prefix} ✅ Retry diff generation succeeded, time: {agent_duration:.2f}s")
return diff, str(output_file)
else:
console.print(f"{logs_prefix} ❌ Retry diff generation failed")
return None, str(output_file) if output_file.exists() else None
finally:
# Stop Docker container
if container_id is not None:
console.print(f"{logs_prefix} Stopping Docker container...")
terminate_runtime_pod(container_id)
console.print(f"{logs_prefix} Docker container stopped")
except Exception as e:
console.print(f"{logs_prefix} 💥 Retry process error: {e}")
return None, None
def _save_similar_case_match_record(failed_instance_id: str, similar_case: Optional[Dict]):
"""
Save similar-case matching record (simplified)
Args:
failed_instance_id: Failed instance ID
similar_case: Compressed trajectory info of similar case
"""
try:
console = Console()
# Build simplified match record
if similar_case:
similarity_score = similar_case.get("similarity_score", -1)
threshold_met = similarity_score >= 80
match_record = {
"failed_instance_id": failed_instance_id,
"similar_instance_id": similar_case.get("instance", "unknown"),
"similarity_score": similarity_score,
"similarity_threshold_met": threshold_met,
"similarity_reasoning": similar_case.get("similarity_reasoning", "N/A"),
"similar_case_strategy": similar_case.get("strategy", "N/A"),
"similar_case_key_changes": similar_case.get("key_changes", "N/A")
}
console.print(f"📋 Match record: {failed_instance_id} -> {similar_case.get('instance', 'unknown')}")
else:
match_record = {
"failed_instance_id": failed_instance_id,
"similar_instance_id": None,
"similarity_score": -1,
"similarity_threshold_met": False,
"similarity_reasoning": "N/A",
"similar_case_strategy": "N/A",
"similar_case_key_changes": "N/A"
}
console.print(f"📋 Match record: {failed_instance_id} -> No similar case found")
# Save to file
match_record_file = Path(f"output_files/{failed_instance_id}/similar_case_match.json")
match_record_file.parent.mkdir(parents=True, exist_ok=True)
with open(match_record_file, 'w', encoding='utf-8') as f:
json.dump(match_record, f, indent=2, ensure_ascii=False)
except Exception as e:
console.print(f"❌ Failed to save similar-case matching record {failed_instance_id}: {e}")
def _generate_similar_case_summary_report(retry_instances: List[str]):
"""
Generate summary report of similar-case matching (simplified)
Args:
retry_instances: List of instances to retry
"""
try:
console = Console()
console.print("📊 Generating summary report for similar-case matching...")
match_records = []
successful_matches = 0
# Collect all match records
for instance_id in retry_instances:
match_file = Path(f"output_files/{instance_id}/similar_case_match.json")
if match_file.exists():
try:
with open(match_file, 'r', encoding='utf-8') as f:
match_record = json.load(f)
match_records.append(match_record)
if match_record.get("similar_instance_id"):
successful_matches += 1
except Exception as e:
console.print(f"⚠️ Failed to read match record {instance_id}: {e}")
# Save simplified summary report
summary_data = {
"total_retry_instances": len(retry_instances),
"successful_matches": successful_matches,
"failed_matches": len(retry_instances) - successful_matches,
"match_records": match_records
}
# Ensure output_files directory exists
output_files_dir = Path("output_files")
output_files_dir.mkdir(parents=True, exist_ok=True)
summary_file = output_files_dir / "similar_case_matches_summary.json"
with open(summary_file, 'w', encoding='utf-8') as f:
json.dump(summary_data, f, indent=2, ensure_ascii=False)
console.print(f"📋 Similar-case matching summary report saved: {summary_file}")
console.print(f"📊 Match stats: {successful_matches}/{len(retry_instances)} successful")
except Exception as e:
console.print(f"❌ Failed to generate similar-case matching summary report: {e}")
def _find_similar_case_for_retry(instance_id: str, successful: List[str]) -> Optional[Dict]:
"""
Find a similar case for a single instance (pipeline mode)
Args:
instance_id: Instance ID
successful: List of successful cases
Returns:
Similar case info or None
"""
try:
from search_zip.flow import find_similar_case
return find_similar_case(instance_id, successful)
except Exception as e:
console = Console()
console.print(f"❌ Error finding similar case {instance_id}: {e}")
return None
def _get_problem_statement_for_retry(instance_id: str, all_tasks: List[Tuple]) -> str:
"""
Get problem statement for an instance (pipeline mode)
Args:
instance_id: Instance ID
all_tasks: List of all tasks
Returns:
Problem description string
"""
for task in all_tasks:
if task[1] == instance_id: # task[1] is problem_id
return task[2] # task[2] is problem_statement
# If not found, use default description
return f"Fix the issue for {instance_id}"
def _copy_retry_logs_to_output(instance_id: str, retry_logs_path: str) -> bool:
"""
Copy retry agent logs to the output_files directory
Args:
instance_id: Instance ID
retry_logs_path: Path to the retry log file
Returns:
Whether copying succeeded
"""
try:
console = Console()
if not retry_logs_path or not Path(retry_logs_path).exists():
console.print(f"⚠️ Retry log file does not exist: {retry_logs_path}")
return False
# Target directory
output_dir = Path(f"output_files/{instance_id}")
if not output_dir.exists():
console.print(f"⚠️ Output directory does not exist: {output_dir}")
return False
# Copy retry logs to output_files directory
retry_logs_dest = output_dir / "agent_logs_retry.txt"
shutil.copy2(retry_logs_path, retry_logs_dest)
console.print(f"📁 Copied retry logs: {instance_id} -> agent_logs_retry.txt")
# Also copy as the current agent_logs.txt (replace original)
current_logs_dest = output_dir / "agent_logs.txt"
shutil.copy2(retry_logs_path, current_logs_dest)
console.print(f"📁 Updated current logs: {instance_id} -> agent_logs.txt")
return True
except Exception as e:
console.print(f"❌ Failed to copy retry logs {instance_id}: {e}")
return False
def _update_single_retry_result(instance_id: str, retry_diff: str) -> bool:
"""
Immediately update a single retry result (file replacement and backup)
Args:
instance_id: Instance ID
retry_diff: Diff generated by the retry
Returns:
Whether update succeeded
"""
try:
console = Console()
# Find the corresponding output_files subdirectory
output_dir = Path(f"output_files/{instance_id}")
if not output_dir.exists():
console.print(f"⚠️ Directory does not exist: {output_dir}")
return False
predictions_file = output_dir / "predictions.json"
if not predictions_file.exists():
console.print(f"⚠️ predictions.json does not exist: {instance_id}")
return False
# 1. Back up the original predictions.json file
original_backup = output_dir / "predictions_original.json"
if not original_backup.exists():
# Rename the original file
predictions_file.rename(original_backup)
console.print(f"📁 Backed up original predictions.json: {instance_id}")
# 1.1 Back up the original agent_logs.txt file
agent_logs_file = output_dir / "agent_logs.txt"
agent_logs_original = output_dir / "agent_logs_original.txt"
if agent_logs_file.exists() and not agent_logs_original.exists():
# Rename original agent logs
agent_logs_file.rename(agent_logs_original)
console.print(f"📁 Backed up original agent_logs.txt: {instance_id}")
# 2. Read original data
with open(original_backup, 'r') as f:
original_data = json.load(f)
# 3. Create retried data
retry_data = original_data.copy()
if retry_data and isinstance(retry_data, list) and len(retry_data) > 0:
# Update the first prediction's model_patch
retry_data[0]["model_patch"] = retry_diff
# Add retry flags
retry_data[0]["retry_success"] = True
retry_data[0]["retry_timestamp"] = time.strftime("%Y-%m-%d %H:%M:%S")
retry_data[0]["original_patch"] = original_data[0].get("model_patch", "")
# 4. Save retried predictions.json
with open(predictions_file, 'w') as f:
json.dump(retry_data, f, indent=2)
# 5. Save retry record
retry_record = {
"instance_id": instance_id,
"retry_timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"original_patch": original_data[0].get("model_patch", ""),
"retry_patch": retry_diff,
"patch_changed": original_data[0].get("model_patch", "") != retry_diff
}
retry_record_file = output_dir / "predictions_retry.json"
with open(retry_record_file, 'w') as f:
json.dump(retry_record, f, indent=2)
return True
else:
console.print(f"⚠️ Invalid predictions.json format: {instance_id}")
return False
except Exception as e:
console.print(f"❌ Update failed {instance_id}: {e}")
# If update fails, try to restore the original file
try:
if 'original_backup' in locals() and original_backup.exists() and not predictions_file.exists():
original_backup.rename(predictions_file)
console.print(f"🔄 Restored original file: {instance_id}")
except:
pass
return False
def _execute_classified_retry(
test_gen_failed: List[str],
test_validation_failed: List[str],
empty: List[str],
successful: List[str],
all_tasks: List[Tuple],
workspace_base_path: Path,
lock,
semaphore,
pool
) -> int:
"""
Execute classified retry with judgment and conditional retry strategies.
Args:
test_gen_failed: List of test generation failed instances
test_validation_failed: List of test validation failed instances
empty: List of empty patch instances
successful: List of successful instances
all_tasks: List of all tasks
workspace_base_path: Base path of workspace
lock: Thread lock
semaphore: Semaphore
pool: Process pool
Returns:
Number of successful retries
"""
from utils.dynamic_agent import execute_basic_retry_agent, execute_experience_retry_agent
from utils.file_backup import backup_and_replace_instance_files
from validate_retry_necessity import judge_failure_root_cause
from search_zip.flow import find_similar_case
console = Console()
success_count = 0
# 1. Handle empty patches and test generation failures with basic retry
basic_retry_instances = empty + test_gen_failed
if basic_retry_instances:
console.print(f"🔄 Basic retry for {len(basic_retry_instances)} instances (empty patch + test gen failed)")
# Execute basic retry in parallel
retry_tasks = []
for instance_id in basic_retry_instances:
problem_statement = _get_problem_statement_for_retry(instance_id, all_tasks)
retry_tasks.append((instance_id, problem_statement, workspace_base_path, lock, semaphore))
# Use pool.starmap for parallel execution
results = pool.starmap(execute_basic_retry_agent, retry_tasks)
# Process results
for instance_id, (new_diff, logs_path) in zip(basic_retry_instances, results):
if new_diff:
retry_type = "empty_patch" if instance_id in empty else "test_gen_failed"
if backup_and_replace_instance_files(instance_id, new_diff, logs_path, f"basic_{retry_type}"):
success_count += 1
console.print(f"✅ Basic retry success: {instance_id}")
else:
console.print(f"❌ Basic retry file update failed: {instance_id}")
else:
console.print(f"❌ Basic retry failed: {instance_id}")
# 2. Handle test validation failures with judgment and conditional retry
if test_validation_failed:
console.print(f"🔍 Analyzing {len(test_validation_failed)} test validation failures...")
# Judge each validation failure
judgment_results = {}
for instance_id in test_validation_failed:
judgment = judge_failure_root_cause(instance_id, "output_files")
judgment_results[instance_id] = judgment
console.print(f"⚖️ {instance_id}: {judgment['root_cause']} (confidence: {judgment['confidence']:.2f})")
# Separate by judgment
test_problem_instances = [id for id, j in judgment_results.items() if j['root_cause'] == 'TEST']
patch_problem_instances = [id for id, j in judgment_results.items() if j['root_cause'] == 'PATCH']
# Handle TEST problems with basic retry
if test_problem_instances:
console.print(f"🔄 Basic retry for {len(test_problem_instances)} TEST problem instances")
test_retry_tasks = []
for instance_id in test_problem_instances:
problem_statement = _get_problem_statement_for_retry(instance_id, all_tasks)
test_retry_tasks.append((instance_id, problem_statement, workspace_base_path, lock, semaphore))
test_results = pool.starmap(execute_basic_retry_agent, test_retry_tasks)
for instance_id, (new_diff, logs_path) in zip(test_problem_instances, test_results):
if new_diff:
if backup_and_replace_instance_files(instance_id, new_diff, logs_path, "test_problem"):
success_count += 1
console.print(f"✅ TEST problem retry success: {instance_id}")
else:
console.print(f"❌ TEST problem file update failed: {instance_id}")
else:
console.print(f"❌ TEST problem retry failed: {instance_id}")
# Handle PATCH problems with experience retry
if patch_problem_instances:
console.print(f"🧠 Experience retry for {len(patch_problem_instances)} PATCH problem instances")
# Find similar cases and execute experience retry
patch_retry_tasks = []
patch_metadata = []
for instance_id in patch_problem_instances:
problem_statement = _get_problem_statement_for_retry(instance_id, all_tasks)
# Find similar case
similar_case = find_similar_case(instance_id, successful) if successful else None
# Load current trajectory
current_trajectory = _load_compressed_trajectory(instance_id)
# Debug info
console.print(f"🔍 {instance_id}: similar_case={'Yes' if similar_case else 'No'}, trajectory={'Yes' if current_trajectory else 'No'}")
# Prepare task data
if similar_case and current_trajectory:
patch_retry_tasks.append((
instance_id, problem_statement, current_trajectory,
similar_case, workspace_base_path, lock, semaphore
))
patch_metadata.append({"instance_id": instance_id, "has_similar": True})
else:
# Fallback to basic retry if no similar case or trajectory
patch_retry_tasks.append((instance_id, problem_statement, workspace_base_path, lock, semaphore))
patch_metadata.append({"instance_id": instance_id, "has_similar": False})
# Execute experience retry for those with similar cases
experience_tasks = [task for task, meta in zip(patch_retry_tasks, patch_metadata) if meta["has_similar"]]
basic_fallback_tasks = [task for task, meta in zip(patch_retry_tasks, patch_metadata) if not meta["has_similar"]]
if experience_tasks:
experience_results = pool.starmap(execute_experience_retry_agent, experience_tasks)
for i, (new_diff, logs_path) in enumerate(experience_results):
instance_id = experience_tasks[i][0]
if new_diff:
if backup_and_replace_instance_files(instance_id, new_diff, logs_path, "patch_experience"):
success_count += 1
console.print(f"✅ Experience retry success: {instance_id}")
else:
console.print(f"❌ Experience retry file update failed: {instance_id}")
else:
console.print(f"❌ Experience retry failed: {instance_id}")
if basic_fallback_tasks:
fallback_results = pool.starmap(execute_basic_retry_agent, basic_fallback_tasks)
for i, (new_diff, logs_path) in enumerate(fallback_results):
instance_id = basic_fallback_tasks[i][0]
if new_diff:
if backup_and_replace_instance_files(instance_id, new_diff, logs_path, "patch_fallback"):
success_count += 1
console.print(f"✅ Fallback retry success: {instance_id}")
else:
console.print(f"❌ Fallback retry file update failed: {instance_id}")
else:
console.print(f"❌ Fallback retry failed: {instance_id}")
return success_count
def _load_compressed_trajectory(instance_id: str) -> Optional[str]:
"""Load compressed trajectory for an instance."""
try:
trajectory_file = Path("output_files") / instance_id / "compressed_trajectory.txt"
if trajectory_file.exists():
with open(trajectory_file, 'r') as f:
return f.read().strip()
except Exception:
pass
return None
def _retry_with_concurrency(
retry_instances: List[str],
successful: List[str],
all_tasks: List[Tuple],
workspace_base_path: Path,
lock,
semaphore,