From 50f03919866c0209062126a5c3791517d14f4aa5 Mon Sep 17 00:00:00 2001 From: jty1128 Date: Tue, 24 Nov 2026 16:01:49 +0800 Subject: [PATCH] Remove obsolete evaluation scripts and unreachable repair branches --- docs/usage/competitive_runs.md | 26 ------ docs/usage/containers_sentinel.sh | 22 ----- docs/usage/memory_sentinel.py | 140 ---------------------------- evaluation/run_evaluation.py | 135 --------------------------- phoenix/adaptive_io.py | 21 +---- phoenix/pipeline.py | 7 +- phoenix/prompts.py | 150 ++++++------------------------ phoenix/recovery_profiles.py | 1 - phoenix/summary.py | 86 ++++------------- tackle_pred.py | 46 --------- tests/test_repair.py | 34 ++++++- 11 files changed, 82 insertions(+), 586 deletions(-) delete mode 100644 docs/usage/containers_sentinel.sh delete mode 100644 docs/usage/memory_sentinel.py delete mode 100644 evaluation/run_evaluation.py delete mode 100644 tackle_pred.py diff --git a/docs/usage/competitive_runs.md b/docs/usage/competitive_runs.md index 4ebc116..1896513 100644 --- a/docs/usage/competitive_runs.md +++ b/docs/usage/competitive_runs.md @@ -52,32 +52,6 @@ limiting the maximum amount of memory per worker. In our case, this completely avoided any instances of running OOM. -However, OOM situations can potentially lock you out of the server, so -you might want to use a script like the following as a second layer -defense to kill any process that hogs too much memory (note that this will affect _any_ script and not just swe-agent): - -
-Memory sentinel - -```python ---8<-- "docs/usage/memory_sentinel.py" -``` - -
- -If swe-agent dies or you frequently abort it, you might have leftover docker containers -(they are cleaned up by normal termination of swe-agent but can be left over if it is killed). -You can use a sentinel script like the following to clean them up periodically -(note that this will affect _any_ long running container and not just those from swe-agent): - -
-Container sentinel - -```bash ---8<-- "docs/usage/containers_sentinel.sh" -``` -
- ## Tradeoffs between resolution rate and cost * Running multi-attempt configurations will always be _very_ expensive. Don't use them if cost is of importance. diff --git a/docs/usage/containers_sentinel.sh b/docs/usage/containers_sentinel.sh deleted file mode 100644 index 1bd9d21..0000000 --- a/docs/usage/containers_sentinel.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -while true; do - echo "Checking for long-running containers..." - # List all running containers with their uptime - docker ps --format "{{.ID}} {{.RunningFor}}" | while read -r id running_for; do - # Extract the number and unit from the running time - if [[ $running_for =~ ([0-9]+)\ (hour|hours) ]]; then - hours=${BASH_REMATCH[1]} - if (( hours >= 2 )); then - echo "Killing container $id (running for $running_for)..." - docker kill "$id" - fi - elif [[ $running_for =~ ([0-9]+)\ (day|days) ]]; then - # If it's running for at least a day, it's definitely over 2 hours - echo "Killing container $id (running for $running_for)..." - docker kill "$id" - fi - done - echo "Sleeping for 10 minutes..." - sleep 600 # Wait 600 seconds (10 minutes) before running again -done \ No newline at end of file diff --git a/docs/usage/memory_sentinel.py b/docs/usage/memory_sentinel.py deleted file mode 100644 index aba49bd..0000000 --- a/docs/usage/memory_sentinel.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -""" -Memory Sentinel Script - -This script monitors the system's RAM usage and kills the process with the highest -memory consumption if available RAM drops below 5GB. - -Usage: - python memory_sentinel.py - -The script runs continuously, checking memory usage every second. - -Script was generated by Claude 3.7 with the following prompt: - -I'm working on a server and I have one script that sometimes consumes so much memory that the entire server becomes unresponsive. This is a hue problem because then I cannot log in to it anymore. - -Could you write a sentinel script in python that does the following: - -Check the total available RAM of the system (disregarding swap) -Check the currently used RAM of the system -If we have more than 5G left, do nothing -Else, find the process with the highest RAM consumption and kill it. Note: Use the SIGKILL command -Check every second -""" - -import logging -import os -import signal -import time - -import psutil - -# Set up logging -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", filename="memory_sentinel.log", filemode="a" -) - -# Memory threshold in GB -MEMORY_THRESHOLD_GB = 5 -# Convert to bytes for comparison -MEMORY_THRESHOLD_BYTES = MEMORY_THRESHOLD_GB * 1024 * 1024 * 1024 - - -def get_available_ram(): - """Get the available RAM in bytes, excluding swap.""" - return psutil.virtual_memory().available - - -def get_total_ram(): - """Get the total RAM in bytes, excluding swap.""" - return psutil.virtual_memory().total - - -def get_used_ram(): - """Get the used RAM in bytes.""" - return psutil.virtual_memory().used - - -def get_process_with_highest_memory(): - """Find the process with the highest memory consumption.""" - processes = [] - for proc in psutil.process_iter(["pid", "name", "memory_info"]): - try: - processes.append((proc.info["pid"], proc.info["name"], proc.info["memory_info"].rss)) - except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): - pass - - # Sort by memory usage (descending) - processes.sort(key=lambda x: x[2], reverse=True) - - if processes: - return processes[0] - return None - - -def kill_process(pid): - """Kill a process using SIGKILL.""" - try: - os.kill(pid, signal.SIGKILL) - return True - except OSError as e: - logging.error(f"Failed to kill process {pid}: {e}") - return False - - -def format_bytes(bytes_value): - """Format bytes to a human-readable string.""" - for unit in ["B", "KB", "MB", "GB", "TB"]: - if bytes_value < 1024.0: - return f"{bytes_value:.2f} {unit}" - bytes_value /= 1024.0 - return f"{bytes_value:.2f} PB" - - -def main(): - """Main function that runs the memory monitoring loop.""" - logging.info("Memory Sentinel started") - logging.info(f"Memory threshold set to {MEMORY_THRESHOLD_GB}GB") - - try: - while True: - available_ram = get_available_ram() - total_ram = get_total_ram() - used_ram = get_used_ram() - - logging.debug( - f"Total RAM: {format_bytes(total_ram)}, " - + f"Used RAM: {format_bytes(used_ram)}, " - + f"Available RAM: {format_bytes(available_ram)}" - ) - - if available_ram < MEMORY_THRESHOLD_BYTES: - logging.warning( - f"Available RAM ({format_bytes(available_ram)}) " + f"below threshold of {MEMORY_THRESHOLD_GB}GB" - ) - - process = get_process_with_highest_memory() - if process: - pid, name, memory = process - logging.warning(f"Killing process {pid} ({name}) " + f"using {format_bytes(memory)}") - - if kill_process(pid): - logging.info(f"Successfully killed process {pid} ({name})") - else: - logging.error(f"Failed to kill process {pid} ({name})") - else: - logging.warning("No process found to kill") - - # Sleep for 1 second - time.sleep(1) - - except KeyboardInterrupt: - logging.info("Memory Sentinel stopped by user") - except Exception as e: - logging.error(f"Unexpected error: {e}") - raise - - -if __name__ == "__main__": - main() diff --git a/evaluation/run_evaluation.py b/evaluation/run_evaluation.py deleted file mode 100644 index 260958b..0000000 --- a/evaluation/run_evaluation.py +++ /dev/null @@ -1,135 +0,0 @@ -import os -import sys -import json -import argparse -import subprocess -from typing import Any -from pathlib import Path -from datetime import datetime -from utils import BENCHMARK_CONFIG - -class BenchmarkEvaluation: - """ - Simplified class for running evaluations only. - Handles evaluation using pre-generated patches. - """ - - def __init__( - self, - benchmark: str, - dataset: str = "SWE-bench_Verified", - run_id: str | None = None, - max_workers: int = 4, - instance_ids: list[str] | None = None, - results_dir: str = "", - benchmark_harness_path: str = "SWE-bench" - ): - """ - Initialize the BenchmarkEvaluation class. - - Args: - benchmark: Benchmark name. - dataset: Dataset name. - benchmark_harness_path: Path to benchmark harness (for evaluation). - run_id: Unique run identifier (if None, will use timestamp). - max_workers: Maximum number of parallel workers. - instance_ids: List of instance IDs to run (optional). - """ - assert benchmark in BENCHMARK_CONFIG, f"Invalid benchmark name: {benchmark}" - self.config = BENCHMARK_CONFIG[benchmark] - self.dataset_name = dataset - assert self.dataset_name in self.config.valid_datasets, (f"Invalid dataset name: {self.dataset_name}") - self.benchmark = benchmark - self.max_workers = max_workers - if run_id is None: - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - self.run_id = f"trae-agent-{timestamp}" - else: - self.run_id = run_id - self.results_dir = results_dir - self.benchmark_harness_path = benchmark_harness_path - - def run_eval(self): - """ - Run evaluation using the SWE-bench harness. - """ - print(f"Running evaluation with run_id: {self.run_id}") - # swebench_harness_path = Path(self.benchmark_harness_path) - swebench_harness_path = Path(self.benchmark_harness_path).resolve() - # swebench_python_path = "swebench_venv/bin/python" - swebench_python_path = sys.executable - predictions_path = os.path.abspath(os.path.join(self.results_dir, "final_answer1.json")) - print(f"Looking for predictions.json at: {predictions_path}") - print(f"File exists: {os.path.exists(predictions_path)}") - print(f"Working directory: {os.getcwd()}") - cmd = [ - swebench_python_path, - "-m", - "swebench.harness.run_evaluation", - "--dataset_name", - f"princeton-nlp/{self.dataset_name}", - "--predictions_path", - predictions_path, - "--run_id", - self.run_id, - "--cache_level", - "instance", - "--instance_image_tag", - "latest", - ] - process = subprocess.run(cmd, capture_output=True, cwd=swebench_harness_path.as_posix()) - print(process.stdout.decode()) - print(process.stderr.decode()) - result_filename = f"{self.run_id}.json" - print(f"Evaluation completed and file saved to {result_filename}") - - def get_all_preds(self, instance_ids: list[str] | None = None): - """ - Collect all generated patches and write predictions.json to results directory. - - Args: - instance_ids: List of instance IDs to collect (optional). - """ - preds: list[dict[str, str]] = [] - patch_path = os.path.join(self.results_dir, "answer_final.json") - print(f"patch_path:{patch_path}") - with open(patch_path, 'r') as f: - dict1 = json.load(f) - for k, v in dict1.items(): - preds.append({"instance_id": k, "model_name_or_path": "PhoenixRepair", "model_patch": v['model_patch']}) - print(f"Collected {len(preds)} predictions") - with open(os.path.join(self.results_dir, "final_answer1.json"), "w") as f: - json.dump(preds, f) - -def main(): - """ - Main entry point for benchmark evaluation script. - Parses command-line arguments and runs evaluation only. - """ - argument_parser = argparse.ArgumentParser() - argument_parser.add_argument("--benchmark", type=str, default="SWE-bench", help="Benchmark name.") - argument_parser.add_argument("--dataset", type=str, default="SWE-bench_Verified", help="Dataset name.") - argument_parser.add_argument("--run-id", type=str, required=False, help="Run ID for SWE-bench evaluation (deprecated, use --run_id).") - argument_parser.add_argument("--instance_ids", nargs="+", type=str, help="Instance IDs to run (space separated).") - argument_parser.add_argument("--run_id", type=str, required=False, help="Run ID for benchmark evaluation. If not provided, will use timestamp.") - argument_parser.add_argument("--max_workers", type=int, default=5, help="Maximum number of parallel workers.") - argument_parser.add_argument("--results_dir", type=str, default="") - argument_parser.add_argument("--benchmark_harness_path", type=str, default="SWE-bench", help="Benchmark name.") - args = argument_parser.parse_args() - # Use --run_id if provided, otherwise use --run-id for backward compatibility, otherwise None (will generate timestamp) - run_id = args.run_id or args.run_id - evaluation = BenchmarkEvaluation( - args.benchmark, - args.dataset, - run_id, # This will be None if not provided, triggering timestamp generation - args.max_workers, - args.instance_ids, - args.results_dir, - args.benchmark_harness_path - ) - # Evaluation only - evaluation.get_all_preds(args.instance_ids) - evaluation.run_eval() - -if __name__ == "__main__": - main() diff --git a/phoenix/adaptive_io.py b/phoenix/adaptive_io.py index cf76367..b3b34a3 100644 --- a/phoenix/adaptive_io.py +++ b/phoenix/adaptive_io.py @@ -45,26 +45,10 @@ def __init__(self, initial=12, maximum=30, minimum=4): self.low_since = None self.high_since = None self.last_change = None - self.last_failure = None self.last = None self.reason = 'initial_limit' - self.last_request_id = None - def apply_request(self, request, wall_time): - if not request or request.get('id') == self.last_request_id or request.get('expires_at', 0) < wall_time: - return False - target = request.get('total') - if type(target) is not int or not self.minimum <= target <= self.maximum: - return False - self.limit = target - self.last_request_id = request['id'] - self.last_change = None - self.reason = 'user_capacity_probe' - return True - - def update(self, metrics, now, active, infrastructure_failure=False): - if infrastructure_failure: - self.last_failure = now + def update(self, metrics, now, active): if metrics is None: return self.settings() self.last = metrics @@ -91,7 +75,6 @@ def update(self, metrics, now, active, infrastructure_failure=False): self.low_since = None elif (low and self.low_since is not None and now - self.low_since >= 600 and (self.last_change is None or now - self.last_change >= 600) - and (self.last_failure is None or now - self.last_failure >= 600) and active >= self.limit - 1 and self.limit < self.maximum): self.limit = min(self.maximum, self.limit + 2) self.last_change = now @@ -105,6 +88,6 @@ def settings(self, high=False): 'environment_start_concurrency': 1 if high else 2, 'local_command_concurrency': 2 if high else 4, 'pause_new_image_imports': high, 'reason': self.reason, - 'last_request_id': self.last_request_id, + 'last_request_id': None, 'sample': self.last, 'evaluation_enabled': False, 'running_workers_are_preserved': True, 'updated_at': time.time()} diff --git a/phoenix/pipeline.py b/phoenix/pipeline.py index cb96530..3424515 100644 --- a/phoenix/pipeline.py +++ b/phoenix/pipeline.py @@ -89,13 +89,12 @@ def run_task(task, settings, backend, key, candidates=None, summary_fn=summarize for job in jobs: stage = directory / job["stage"] if job["kind"] == "summary": - summary = summary_fn(task, results, settings, stage, key, shared_budget=method in REPAIR_METHODS) - if method in REPAIR_METHODS: - used += 1 + summary = summary_fn(task, results, settings, stage, key) + used += 1 continue candidate = candidates[len(results)] if job["kind"] == "candidate" else None allowance = job["allowance"] - if method in REPAIR_METHODS and job["kind"] == "final": + if job["kind"] == "final": allowance = settings["max_steps"] - used if allowance < 1: raise RuntimeError("No generation budget remains for final PhoenixRepair") diff --git a/phoenix/prompts.py b/phoenix/prompts.py index a30a61b..b711206 100644 --- a/phoenix/prompts.py +++ b/phoenix/prompts.py @@ -8,11 +8,8 @@ class PromptBuilder: def __init__(self): self.logger = logging.getLogger("phoenix.prompts") - def _build_comparison_prompt(self, problem_statement: str, samples: list[dict], num_samples: int, select_top_half: bool = False) -> str: - if select_top_half: - import math - top_n = math.ceil(num_samples / 2) - prompt = f"""You are an expert code debugging analyst. Compare multiple solution attempts for the same SWE-bench task and select the TOP {top_n} best patches (approximately half). + def _build_comparison_prompt(self, problem_statement: str, samples: list[dict], num_samples: int) -> str: + prompt = f"""You are an expert code debugging analyst. Compare multiple solution attempts for the same SWE-bench task and identify the best generation patch. ## Problem Statement {problem_statement} @@ -20,60 +17,12 @@ def _build_comparison_prompt(self, problem_statement: str, samples: list[dict], ## Solution Attempts **IMPORTANT:** The samples are presented in RANDOM ORDER to avoid position bias. Evaluate each solution independently based on technical merit only. """ - for sample in samples: - prompt += f"""### Sample {sample['index']} -**Execution Summary:** {len(sample['trajectory'])} steps, Exit: {sample['exit_status']}, Patch: {'Yes' if sample['submission'] else 'No'} + for sample in samples: + prompt += f"""### Sample {sample['index']} +**Execution Summary:** {len(sample['trajectory'])} steps, Exit: {sample['exit_status']}, Patch: Yes """ - if sample.get('regression_evidence'): - prompt += '\n**Measured repository regression evidence:**\n' + json.dumps(sample['regression_evidence'], ensure_ascii=False) + '\n' - if sample["submission"]: - prompt += f"\n**Patch:**\n```\n{sample['submission']}\n```\n\n" - else: - prompt += "\n**Patch:** No submission\n\n" - - prompt += f"""## Analysis Requirements - -Compare all samples and provide: - -1. **Select Top {top_n} Samples:** Which sample numbers have the most correct solutions? - -2. **Reasoning:** Why is this sample better than others? Consider: - - Patch correctness and completeness - - Problem understanding accuracy - - Edge case handling - -3. **Key Insights for Next Attempt:** What can we learn from all attempts to guide the next solution? Be specific about: - - Which approaches worked well - - Specific files/functions that need attention - -## Output Format -**You MUST strictly follow this format:** - -**TOP_SAMPLES:** [comma-separated list, e.g., "1,3,5,7"] - -**REASONING:** -[Explanation of why these {top_n} samples are best] -""" - else: - prompt = f"""You are an expert code debugging analyst. Compare multiple solution attempts for the same SWE-bench task and identify the best generation patch. - -## Problem Statement -{problem_statement} - -## Solution Attempts -**IMPORTANT:** The samples are presented in RANDOM ORDER to avoid position bias. Evaluate each solution independently based on technical merit only. -""" - for sample in samples: - prompt += f"""### Sample {sample['index']} -**Execution Summary:** {len(sample['trajectory'])} steps, Exit: {sample['exit_status']}, Patch: {'Yes' if sample['submission'] else 'No'} -""" - if sample.get('regression_evidence'): - prompt += '\n**Measured repository regression evidence:**\n' + json.dumps(sample['regression_evidence'], ensure_ascii=False) + '\n' - if sample['submission']: - prompt += f"\n**Patch:**\n```\n{sample['submission']}\n```\n\n" - else: - prompt += "\n**Patch:** No submission\n\n" - prompt += f"""## Analysis Requirements + prompt += f"\n**Patch:**\n```\n{sample['submission']}\n```\n\n" + prompt += f"""## Analysis Requirements Compare all samples and provide: @@ -102,8 +51,8 @@ def _build_comparison_prompt(self, problem_statement: str, samples: list[dict], """ return "You are PhoenixRepair.\n" + prompt - def _generate_location_insights_from_patch(self, patch_data: dict, previous_round_info: dict = None) -> str: - """从 patch data 生成 location insights,包含前一轮的反思""" + def _generate_location_insights_from_patch(self, patch_data: dict) -> str: + """Render the complete localization plan for the patch author.""" insights_parts = [] compiled = patch_data.get('schema_version') in ('location_candidate_v3', 'location_candidate_v4') if patch_data.get('hypothesis'): @@ -131,22 +80,18 @@ def _generate_location_insights_from_patch(self, patch_data: dict, previous_roun if patch_data.get('requirement_coverage'): insights_parts.append('**Coverage of the issue requirements:**') for item in patch_data['requirement_coverage']: - if patch_data.get('planning_mode') == 'complete_strategy_v1': - requirement = next(r['text'] for r in patch_data['requirements'] if r['id'] == item['requirement_id']) - else: - requirement = patch_data['requirements'][item['requirement_index']-1] + requirement = next(r['text'] for r in patch_data['requirements'] if r['id'] == item['requirement_id']) refs = ', '.join(item['location_ids']) or 'already satisfied; verify evidence' insights_parts.append(f"- {requirement} [{refs}]: {item['explanation']}") if item.get('evidence'): insights_parts.append(' Current-source evidence: ' + json.dumps(item['evidence'], ensure_ascii=False)) - if patch_data.get('planning_mode') == 'complete_strategy_v1': - insights_parts.append('**Whole repair mechanism:**\n' + patch_data['implementation_outline']) - insights_parts.append('**Cooperating changes and unchanged dependencies:**') - for item in patch_data['dependency_review']: - insights_parts.append(f"- {item['area']} ({item['status']}): {item['explanation']} " - f"[{', '.join(item['location_ids'])}]") - if item.get('evidence'): - insights_parts.append(' Evidence: ' + json.dumps(item['evidence'], ensure_ascii=False)) + insights_parts.append('**Whole repair mechanism:**\n' + patch_data['implementation_outline']) + insights_parts.append('**Cooperating changes and unchanged dependencies:**') + for item in patch_data['dependency_review']: + insights_parts.append(f"- {item['area']} ({item['status']}): {item['explanation']} " + f"[{', '.join(item['location_ids'])}]") + if item.get('evidence'): + insights_parts.append(' Evidence: ' + json.dumps(item['evidence'], ensure_ascii=False)) insights_parts.append( 'This is one complete alternative repair plan, not a proven fix. Evaluate its hypothesis ' 'and unresolved questions against the issue and current source while implementing the patch. ' @@ -155,39 +100,14 @@ def _generate_location_insights_from_patch(self, patch_data: dict, previous_roun 'Do not claim validation without evidence or redesign unrelated behavior.') if patch_data.get('schema_version') == 'location_checks_v1': insights_parts.append(f"Candidate: {patch_data['id']} (one complete location set)") - if patch_data.get('planning_mode') in ('locations_only_v1', 'complete_strategy_v1'): - insights_parts.append('Localization supplied locations and short intentions only, not an implementation or tests. ' - 'Implement this complete plan and derive the necessary tests and verification from the issue ' - 'and current source during patch generation. If it cannot address the issue, report why.') - else: - insights_parts.append('**Verification points for this location set:**') - for q in patch_data['unresolved_questions']: - insights_parts.append(f"- [{', '.join(q['location_ids'])}] {q['question']}") - insights_parts.append('Implement the cooperating changes at the complete locations below and verify these points. ' - 'If the set cannot address the issue, report the concrete problem.') - if previous_round_info: - prev_round = previous_round_info.get('round', -1) - prev_patch = previous_round_info.get('patch', '') - prev_status = previous_round_info.get('exit_status', 'unknown') - insights_parts.append("**Previous Attempt Reflection:**\n") - insights_parts.append(f"In Round {prev_round}, we attempted to fix this location with the following approach:\n") - insights_parts.append(f"- Exit Status: {prev_status}") - if prev_patch: - insights_parts.append(f"\n**Previous Patch:**") - insights_parts.append("```") - insights_parts.append(prev_patch) - insights_parts.append("```\n") - insights_parts.append("**Instructions for This Round:**") - insights_parts.append("- Reflect on the previous patch") - insights_parts.append("- Improve upon the previous solution") + insights_parts.append('Localization supplied locations and short intentions only, not an implementation or tests. ' + 'Implement this complete plan and derive the necessary tests and verification from the issue ' + 'and current source during patch generation. If it cannot address the issue, report why.') files_to_modify = patch_data.get('files_to_modify', []) insights_parts.append("**Error Code Location Information:**\n") insights_parts.append("I will provide you with the location information of the buggy code below. ") - if patch_data.get('planning_mode') == 'complete_strategy_v1': - insights_parts.append("Use these locations as starting points; inspect affected callers and consumers " - "and include necessary cooperating edits supported by the issue and source.\n\n") - else: - insights_parts.append("Please make your modifications at the locations specify for the erroneous code.\n\n") + insights_parts.append("Use these locations as starting points; inspect affected callers and consumers " + "and include necessary cooperating edits supported by the issue and source.\n\n") for file_info in files_to_modify: file_path = file_info.get('file_path', 'unknown') modifications = file_info.get('modifications', []) @@ -213,28 +133,20 @@ def _generate_location_insights_from_patch(self, patch_data: dict, previous_roun insights_parts.append(current_code) insights_parts.append("```\n") insights_parts.append("\n**Final Instructions:**") - if previous_round_info: - insights_parts.append("- Learn from the previous attempt and improve your solution") - if patch_data.get('planning_mode') == 'complete_strategy_v1': - insights_parts.append('- Implement this strategy as a whole and check every requirement, including unchanged behavior. ' - 'The plan is a hypothesis, not an oracle. If current source reveals a necessary cooperating ' - 'edit outside its anchors, inspect and include it; explain that addition and its requirement. ' - 'Correct the mechanism when evidence requires it and explain why; do not omit ' - 'a requirement to fit the listed ranges. ' - 'Run relevant current-repository checks, record results honestly, and inspect the final diff ' - 'against the requirement coverage before submission.') - else: - insights_parts.append("- Please make modifications at the code locations mentioned above") - insights_parts.append("- Do NOT make changes outside these locations") + insights_parts.append('- Implement this strategy as a whole and check every requirement, including unchanged behavior. ' + 'The plan is a hypothesis, not an oracle. If current source reveals a necessary cooperating ' + 'edit outside its anchors, inspect and include it; explain that addition and its requirement. ' + 'Correct the mechanism when evidence requires it and explain why; do not omit ' + 'a requirement to fit the listed ranges. ' + 'Run relevant current-repository checks, record results honestly, and inspect the final diff ' + 'against the requirement coverage before submission.') return "\n".join(insights_parts) def _enhance_agent_config_with_insights(self, original_config: AgentConfig, insights: str, num_samples: int) -> AgentConfig: """使用insights增强agent配置""" enhanced_config = original_config.model_copy(deep=True) - # enhanced_config.use_change_history_method = False original_instance_template = enhanced_config.templates.instance_template - if insights.strip(): - enhanced_instance_template = f"""Based on {num_samples} previous solution attempts at different code locations for this task, we have conducted a comparative analysis to identify the best approach and key learnings: + enhanced_instance_template = f"""Based on {num_samples} previous solution attempts at different code locations for this task, we have conducted a comparative analysis to identify the best approach and key learnings: {insights} @@ -246,8 +158,6 @@ def _enhance_agent_config_with_insights(self, original_config: AgentConfig, insi # Original Task Instructions {original_instance_template} """ - else: - enhanced_instance_template = original_instance_template enhanced_config.templates.instance_template = enhanced_instance_template self.logger.info(f"Enhanced instance template with comparison insights (length: {len(insights)} chars)") return enhanced_config diff --git a/phoenix/recovery_profiles.py b/phoenix/recovery_profiles.py index c34609a..54f70e1 100644 --- a/phoenix/recovery_profiles.py +++ b/phoenix/recovery_profiles.py @@ -9,7 +9,6 @@ def recovery_profile(settings): spec = PROFILES[model] result = dict(model=model, method=settings["method"], api_timeout_seconds=spec["timeout"], wall_time_seconds=settings.get("task_timeout", spec["task_timeout"]), thinking=spec["thinking"], - summary_timeout_seconds=120, summary_transport_attempts=5, summary_format_rounds=3, generation_supported=True, same_model_only=True, budget_reset=False, review_calls=0, environment_start_retries=3 if settings["method"] in REPAIR_METHODS else 1, terminal_session_retries=1, submission_replay_attempts=2) diff --git a/phoenix/summary.py b/phoenix/summary.py index cc9b28d..8cc376a 100644 --- a/phoenix/summary.py +++ b/phoenix/summary.py @@ -1,78 +1,37 @@ """Same-model comparison of PhoenixRepair candidate patches.""" import hashlib from pathlib import Path -import re -import time import os import requests from phoenix.prompts import PromptBuilder from phoenix.repair_guidance import SUMMARY_GUIDANCE -from phoenix.settings import LEGACY_METHOD, REPAIR_METHODS, PROFILES, inference_fields, write_json +from phoenix.settings import LEGACY_METHOD, PROFILES, inference_fields, write_json from phoenix.run_state import bind, read, digest -def sha(path): - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - -def patch_for_prompt(path, limit=180_000): - """Keep ordinary diffs intact and compact oversized generated files for comparison.""" - original = Path(path).read_text() - if len(original) <= limit: - return original, dict(original_chars=len(original), prompt_chars=len(original), compacted=False) - sections = re.split(r'(?=^diff --git )', original, flags=re.MULTILINE) - budget = limit - 2_000 - selected = [] - for section in sections: - if not section: - continue - if len(section) > 40_000: - header = section.splitlines()[0] - digest = hashlib.sha256(section.encode()).hexdigest() - section = (section[:6_000] + '\n[Oversized diff section compacted: ' + header + - '; SHA256=' + digest + '; omitted ' + str(len(section) - 8_000) + - ' characters]\n' + section[-2_000:]) - if len(section) > budget: - header = section.splitlines()[0] - section = ('[Diff section omitted from comparison prompt: ' + header + - '; SHA256=' + hashlib.sha256(section.encode()).hexdigest() + ']\n') - selected.append(section) - budget -= len(section) - preview = ('[Full patch SHA256=' + sha(path) + '; original characters=' + - str(len(original)) + '; oversized sections compacted for comparison]\n' + - ''.join(selected)) - return preview, dict(original_chars=len(original), prompt_chars=len(preview), compacted=True) - - -def summarize(task, candidates, settings, directory, key, *, shared_budget=False): +def summarize(task, candidates, settings, directory, key): directory.mkdir(parents=True, exist_ok=True) - shared_budget_mode = settings["method"] in REPAIR_METHODS - if shared_budget_mode and not shared_budget: - raise ValueError("PhoenixRepair summary must use the shared one-call budget") inputs = [] for index, row in enumerate(candidates, 1): patch = Path(row["patch"]) - if not patch.is_file() or not patch.read_text().strip(): - raise ValueError("Summary requires every candidate patch to be present and nonempty") - if shared_budget_mode: - preview = patch.read_text() - metadata = dict(original_chars=len(preview), prompt_chars=len(preview), compacted=False) - else: - preview, metadata = patch_for_prompt(patch) + preview = patch.read_text() + if not preview.strip(): + raise ValueError("Summary requires every candidate patch to be nonempty") + metadata = dict(original_chars=len(preview), prompt_chars=len(preview), compacted=False) inputs.append(dict(index=index, trajectory=[None] * row["steps"], submission=preview, - exit_status="submitted" if shared_budget_mode else row["exit_status"], patch_sha256=sha(patch), preview=metadata)) + exit_status="submitted", patch_sha256=digest(patch), preview=metadata)) prompt = PromptBuilder()._build_comparison_prompt(task["problem_statement"], inputs, len(inputs)) if settings["method"] == LEGACY_METHOD: prompt = prompt.removeprefix("You are PhoenixRepair.\n") - if shared_budget_mode: - prompt += SUMMARY_GUIDANCE + prompt += SUMMARY_GUIDANCE (directory / "prompt.txt").write_text(prompt) write_json(directory / "inputs.json", [{k: v for k, v in row.items() if k != "submission"} for row in inputs]) kimi = settings["model"] == "kimi-k2.7-code" payload = dict(inference_fields(settings["model"]), messages=[{"role": "user", "content": prompt}]) - timeout = (30, PROFILES[settings["model"]]["timeout"]) if shared_budget_mode else (240 if kimi else 120) + timeout = (30, PROFILES[settings["model"]]["timeout"]) bind(directory / "identity.json", {"payload": payload, "api_base": settings["api_base"], - "shared_budget": shared_budget}) + "shared_budget": True}) write_json(directory / "request.json", payload) state = read(directory / "state.json") or { "attempts": 0, "format_attempt": 0, "transport_attempt": 0, "phase": "ready", @@ -94,10 +53,8 @@ def publish_trajectory(response): return (directory / "summary.txt").read_text() if state["phase"] == "failed": raise RuntimeError("Summary exhausted its original bounded attempts; no budget reset on resume") - exclude_rate_limits = shared_budget_mode and settings.get("exclude_rate_limit_from_budget", False) + exclude_rate_limits = settings.get("exclude_rate_limit_from_budget", False) state.setdefault("rate_limit_retries", 0) - transport_limit = 1 if shared_budget else (3 if kimi else 5) - format_limit = 1 if shared_budget else 3 session = requests.Session() session.trust_env = False def persist(): @@ -108,19 +65,11 @@ def persist(): "unknown_requests": state["unknown_requests"]}) def transport_failure(): - if state["transport_attempt"] >= transport_limit: - if shared_budget_mode or kimi: - state["phase"] = "failed" - else: - state["format_attempt"] += 1 - state["transport_attempt"] = 0 - state["phase"] = "ready" if state["format_attempt"] < format_limit else "failed" - else: - state["phase"] = "ready" + state["phase"] = "failed" persist() try: - while state["format_attempt"] < format_limit and state["phase"] != "failed": + while state["format_attempt"] < 1 and state["phase"] != "failed": response_path = directory / f"response-{state['attempts']}.json" if state["phase"] == "inflight": # A response persisted before a crash is consumed exactly once. @@ -132,10 +81,9 @@ def transport_failure(): transport_failure() continue if state["phase"] == "ready": - if shared_budget_mode: - from sweagent.agent.request_pacing import wait_for_request - account = settings.get("account_id") or os.environ.get("PHOENIX_ACCOUNT_ID") or "env-" + hashlib.sha256(key.encode()).hexdigest()[:16] - wait_for_request(account, "openai/" + settings["model"], settings.get("api_request_interval", 2)) + from sweagent.agent.request_pacing import wait_for_request + account = settings.get("account_id") or os.environ.get("PHOENIX_ACCOUNT_ID") or "env-" + hashlib.sha256(key.encode()).hexdigest()[:16] + wait_for_request(account, "openai/" + settings["model"], settings.get("api_request_interval", 2)) state["attempts"] += 1 state["transport_attempt"] += 1 state["phase"] = "inflight" @@ -166,8 +114,6 @@ def transport_failure(): write_json(directory / f"transport-error-{state['attempts']}.json", {"error_type": type(exc).__name__, "attempt": state["attempts"]}) transport_failure() - if state["phase"] == "ready" and state["transport_attempt"]: - time.sleep(2) continue try: response = read(response_path) diff --git a/tackle_pred.py b/tackle_pred.py deleted file mode 100644 index 85942cd..0000000 --- a/tackle_pred.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python3 -import os -import json -from pathlib import Path - - -def find_patch_files_in_final_folders(root_path): - result = {} - root = Path(root_path) - final_folders = [folder for folder in root.iterdir() if folder.is_dir() and folder.name.endswith('-final')] - print(f"找到 {len(final_folders)} 个 -final 文件夹:") - for folder in final_folders: - print(f"处理文件夹: {folder.name}") - patch_files = list(folder.glob('*.patch')) - if patch_files: - patch_file = patch_files[0] - try: - with open(patch_file, 'r', encoding='utf-8') as f: - patch_content = f.read() - original_id = folder.name.replace('-sample-final', '') - result[original_id] = { - "model_name_or_path": "PhoenixRepair", - "instance_id": original_id, - "model_patch": patch_content - } - print(f"✓ 成功读取 {patch_file.name}") - except Exception as e: - print(f"✗ 读取文件失败 {patch_file}: {e}") - else: - print(f"未找到 .patch 文件") - return result - -def main(): - root_directory = "" # Please Enter The absolute path obtained in Phase 2 - patches_data = find_patch_files_in_final_folders(root_directory) - if patches_data: - output_file = os.path.join(root_directory, "answer_final.json") - with open(output_file, 'w', encoding='utf-8') as f: - json.dump(patches_data, f, indent=4, ensure_ascii=False) - print(f"\n✓ 成功生成 {output_file}") - print(f"共处理了 {len(patches_data)} 个patch文件") - else: - print("未找到任何patch文件") - -if __name__ == "__main__": - main() diff --git a/tests/test_repair.py b/tests/test_repair.py index 5170313..0ae3267 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -26,8 +26,8 @@ def test_multicandidate_shared_budget_and_fresh_final(task, candidate, settings) backend = Backend() observed = [] - def summary(task, rows, cfg, stage, key, **kw): - assert len(rows) == 2 and kw["shared_budget"] + def summary(task, rows, cfg, stage, key): + assert len(rows) == 2 observed.append(cfg["model"]) return "Both strategies suggest changing the constant." @@ -234,10 +234,38 @@ def test_resume_uses_bound_stage_paths(task, candidate, settings): job["stage"] = stage bind(directory / "task-identity.json", dict(task=task, jobs=jobs, candidates=candidates, model=settings["model"], method=settings["method"])) - def compare(task, results, settings, stage, key, *, shared_budget): + def compare(task, results, settings, stage, key): assert stage == directory / "summary" return "Use the second strategy." result = run_task(task, settings, Backend(), "fixture", candidates, summary_fn=compare) assert result["status"] == "completed" assert json.loads((directory / "plan.json").read_text()) == jobs assert not (directory / "location-1").exists() + + +@pytest.mark.parametrize("interrupted", [False, True]) +def test_failed_or_unknown_summary_request_stays_charged(tmp_path, monkeypatch, task, settings, interrupted): + from phoenix import summary + from sweagent.agent import request_pacing + + directory = tmp_path / "final/comparison" + patch = tmp_path / "candidate.patch" + patch.write_text("nonempty candidate") + rows = [dict(patch=str(patch), steps=1)] * 2 + sent = [] + class Session: + def post(self, *args, **kwargs): + sent.append(kwargs["json"]) + raise summary.requests.Timeout("fixture") + def close(self): + pass + monkeypatch.setattr(summary.requests, "Session", Session) + monkeypatch.setattr(request_pacing, "wait_for_request", lambda *args: None) + if interrupted: + write_json(directory / "state.json", dict(phase="inflight", attempts=1, transport_attempt=1, + format_attempt=0, usage={}, usage_applied=[], unknown_requests=[])) + for _ in range(2): + with pytest.raises(RuntimeError, match="Summary"): + summary.summarize(task, rows, settings, directory, "fixture") + assert len(sent) == (0 if interrupted else 1) + assert json.loads((directory / "usage.json").read_text())["budget_calls"] == 1