import shutil import uuid import time import copy import logging import os import re import yaml from rich.logging import RichHandler from rich.table import Table from rich.console import Console import rich.box from typing import List, Optional, Union, cast, Dict, Any from datetime import datetime from pathlib import Path from dataclasses import dataclass, field, asdict, is_dataclass from subprocess import Popen # Optional wandb import try: import wandb WANDB_AVAILABLE = True except ImportError: WANDB_AVAILABLE = False wandb = None from shinka.launch import JobScheduler, JobConfig, ProcessWithLogging from shinka.database import ProgramDatabase, DatabaseConfig, Program from shinka.llm import ( LLMClient, extract_between, EmbeddingClient, BanditBase, AsymmetricUCB, QueryResult, ) from shinka.edit import ( apply_diff_patch, apply_full_patch, summarize_diff, redact_immutable, ) from shinka.core.sampler import PromptSampler from shinka.core.summarizer import MetaSummarizer from shinka.core.novelty_judge import NoveltyJudge from shinka.logo import print_gradient_logo from shinka.utils.trajectory_logger import ( resolve_trajectory_dir, build_openhands_like_completion_payload, write_openhands_like_completion_file, ) FOLDER_PREFIX = "gen" @dataclass class EvolutionConfig: task_sys_msg: Optional[str] = None patch_types: List[str] = field(default_factory=lambda: ["diff"]) patch_type_probs: List[float] = field(default_factory=lambda: [1.0]) num_generations: int = 10 max_parallel_jobs: int = 2 max_patch_resamples: int = 3 max_patch_attempts: int = 5 job_type: str = "local" language: str = "python" llm_models: List[str] = field(default_factory=lambda: ["azure-gpt-4.1-mini"]) llm_dynamic_selection: Optional[Union[str, BanditBase]] = None llm_dynamic_selection_kwargs: dict = field(default_factory=lambda: {}) llm_kwargs: dict = field(default_factory=lambda: {}) meta_rec_interval: Optional[int] = None meta_llm_models: Optional[List[str]] = None meta_llm_kwargs: dict = field(default_factory=lambda: {}) meta_max_recommendations: int = 5 embedding_model: Optional[str] = None init_program_path: Optional[str] = "initial.py" results_dir: Optional[str] = None max_novelty_attempts: int = 3 code_embed_sim_threshold: float = 1.0 novelty_llm_models: Optional[List[str]] = None novelty_llm_kwargs: dict = field(default_factory=lambda: {}) use_text_feedback: bool = False eval_service_url: Optional[str] = None # EV2 eval service URL (e.g., "http://localhost:8765") use_eval_service: bool = False # Use eval service for evaluation (not just notification) evaluator_module: Optional[str] = None # Evaluator module path (e.g., "examples.circle_packing.evaluate_ori") evaluator_function: str = "main" # Evaluator function name evaluator_kwargs: Optional[Dict[str, Any]] = None # Extra kwargs forwarded to evaluator (e.g., {"problem_id": "0"}) eval_service_trigger_mode: Optional[str] = None # Optional override for eval service trigger mode eval_service_trigger_interval: Optional[int] = None # Optional override for eval service trigger interval # WandB logging configuration enable_wandb: bool = False wandb_project: Optional[str] = "ev2" wandb_entity: Optional[str] = "tengxiao" wandb_run_name: Optional[str] = None wandb_tags: Optional[List[str]] = None # Per-LLM-call trajectory logging for Shinka mutation loop trajectory_log: bool = False trajectory_log_dir: str = "llm_trajectories" # Edit backend for mutation attempts edit_backend: str = "openhands_agent" # OpenHands-specific options used when edit_backend=openhands_agent openhands_model: Optional[str] = None openhands_max_iterations_per_run: int = 120 openhands_max_message_chars: int = 120000 openhands_log_completions: bool = False openhands_log_completions_dir: Optional[str] = None openhands_system_prompt_path: Optional[str] = None openhands_system_prompt_suffix_path: Optional[str] = ( "shinka/prompts/openhands_mutation_system_prompt.j2" ) openhands_ev2_prompt_path: Optional[str] = "eval_agent/ev2_prompt.j2" # Optional persistent-agent knobs (kept for launcher compatibility) persistent_agents_enabled: bool = False persistent_context_refresh_interval: int = 10 persistent_context_max_recent_attempts: int = 12 persistent_context_max_recent_insights: int = 8 persistent_invalid_burst_threshold: int = 3 # Recent attempt summary in mutation prompts (0 disables) recent_attempts_k: int = 10 persistent_invalid_burst_window: int = 5 @dataclass class RunningJob: """Represents a running job in the queue.""" job_id: Union[str, Popen, ProcessWithLogging] exec_fname: str results_dir: str start_time: float generation: int parent_id: Optional[str] archive_insp_ids: List[str] top_k_insp_ids: List[str] code_diff: Optional[str] meta_patch_data: Optional[dict] code_embedding: List[float] = field(default_factory=list) embed_cost: float = 0.0 novelty_cost: float = 0.0 use_eval_service: bool = False # Whether this job uses eval service # Set up logging logger = logging.getLogger(__name__) def _to_serializable(value: Any) -> Any: """Convert nested config values into WandB-safe primitives.""" if isinstance(value, (str, int, float, bool)) or value is None: return value if isinstance(value, Path): return str(value) if isinstance(value, dict): return {str(k): _to_serializable(v) for k, v in value.items()} if isinstance(value, (list, tuple, set)): return [_to_serializable(v) for v in value] return repr(value) def _extract_config_dict(obj: Any) -> dict: if is_dataclass(obj): return asdict(obj) if hasattr(obj, "__dict__"): return dict(vars(obj)) return {"repr": repr(obj)} class EvolutionRunner: def __init__( self, evo_config: EvolutionConfig, job_config: JobConfig, db_config: DatabaseConfig, verbose: bool = True, ): self.evo_config = evo_config self.job_config = job_config self.db_config = db_config self.verbose = verbose print_gradient_logo((255, 0, 0), (255, 255, 255)) if evo_config.results_dir is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") self.results_dir = f"results_{timestamp}" else: self.results_dir = Path(evo_config.results_dir) if self.verbose: # Create log file path in results directory log_filename = f"{self.results_dir}/evolution_run.log" Path(self.results_dir).mkdir(parents=True, exist_ok=True) # Set up logging with both console and file handlers logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", handlers=[ RichHandler( show_time=False, show_level=False, show_path=False ), # Console output (clean) logging.FileHandler( log_filename, mode="a", encoding="utf-8" ), # File output (detailed) ], ) # Also log the initial setup information logger.info("=" * 80) start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") logger.info(f"Evolution run started at {start_time}") logger.info(f"Results directory: {self.results_dir}") logger.info(f"Log file: {log_filename}") logger.info("=" * 80) # Initialize eval service notifier (if configured) self.eval_service_url = evo_config.eval_service_url if self.eval_service_url and self.verbose: logger.info(f"EV2 Eval Service enabled: {self.eval_service_url}") # Check if we are resuming a run resuming_run = False db_path = Path(f"{self.results_dir}/{db_config.db_path}") if self.evo_config.results_dir is not None and db_path.exists(): resuming_run = True # Initialize WandB logging (if configured) self.wandb_enabled = False self.wandb_run = None self.island_best_scores: Dict[int, float] = {} # Track best score per island if evo_config.enable_wandb: if not WANDB_AVAILABLE: logger.warning( "WandB logging is enabled but wandb is not installed. " "Install with: pip install wandb" ) else: try: # Prepare full config snapshot for reproducibility. wandb_config = { "evolution_config": _to_serializable( _extract_config_dict(evo_config) ), "database_config": _to_serializable( _extract_config_dict(db_config) ), "job_config": _to_serializable( _extract_config_dict(job_config) ), "results_dir": str(self.results_dir), "resuming_run": resuming_run, } # Initialize wandb self.wandb_run = wandb.init( project=evo_config.wandb_project or "shinka-evolve", entity=evo_config.wandb_entity, name=evo_config.wandb_run_name, tags=evo_config.wandb_tags, config=wandb_config, resume="allow" if resuming_run else None, id=str(Path(self.results_dir).name) if resuming_run else None, ) self.wandb_enabled = True if self.verbose: logger.info( f"WandB logging enabled: project={self.wandb_run.project}, " f"run={self.wandb_run.name}" ) except Exception as e: logger.warning(f"Failed to initialize WandB: {e}") self.wandb_enabled = False # Initialize LLM selection strategy if evo_config.llm_dynamic_selection is None: self.llm_selection = None elif isinstance(evo_config.llm_dynamic_selection, BanditBase): self.llm_selection = evo_config.llm_dynamic_selection elif (evo_config.llm_dynamic_selection.lower() == "ucb") or ( evo_config.llm_dynamic_selection.lower() == "ucb1" ): self.llm_selection = AsymmetricUCB( arm_names=evo_config.llm_models, **evo_config.llm_dynamic_selection_kwargs, ) else: raise ValueError("Invalid llm_dynamic_selection") # Initialize database and scheduler db_config.db_path = str(db_path) embedding_model_to_use = ( evo_config.embedding_model or "text-embedding-3-small" ) self.db = ProgramDatabase( config=db_config, embedding_model=embedding_model_to_use ) self.scheduler = JobScheduler( job_type=evo_config.job_type, config=job_config, # type: ignore verbose=verbose, ) self.llm = LLMClient( model_names=evo_config.llm_models, model_selection=self.llm_selection, **evo_config.llm_kwargs, verbose=verbose, ) if evo_config.embedding_model is not None: self.embedding = EmbeddingClient( model_name=evo_config.embedding_model, verbose=verbose, ) else: self.embedding = None if evo_config.meta_llm_models is not None: self.meta_llm = LLMClient( model_names=evo_config.meta_llm_models, **evo_config.meta_llm_kwargs, verbose=verbose, ) else: self.meta_llm = None if evo_config.novelty_llm_models is not None: self.novelty_llm = LLMClient( model_names=evo_config.novelty_llm_models, **evo_config.novelty_llm_kwargs, verbose=verbose, ) else: self.novelty_llm = None # Initialize PromptSampler for handling LLM code prompts self.prompt_sampler = PromptSampler( task_sys_msg=evo_config.task_sys_msg, language=evo_config.language, patch_types=evo_config.patch_types, patch_type_probs=evo_config.patch_type_probs, use_text_feedback=evo_config.use_text_feedback, results_dir=self.results_dir, ) # Initialize MetaSummarizer for meta-recommendations self.meta_summarizer = MetaSummarizer( meta_llm_client=self.meta_llm, language=evo_config.language, use_text_feedback=evo_config.use_text_feedback, max_recommendations=evo_config.meta_max_recommendations, ) # Initialize NoveltyJudge for novelty assessment self.novelty_judge = NoveltyJudge( novelty_llm_client=self.novelty_llm, language=evo_config.language, similarity_threshold=evo_config.code_embed_sim_threshold, max_novelty_attempts=evo_config.max_novelty_attempts, ) # Initialize rich console for formatted output self.console = Console() if self.evo_config.language == "cuda": self.lang_ext = "cu" elif self.evo_config.language == "cpp": self.lang_ext = "cpp" elif self.evo_config.language == "python": self.lang_ext = "py" elif self.evo_config.language == "rust": self.lang_ext = "rs" elif self.evo_config.language == "swift": self.lang_ext = "swift" elif self.evo_config.language in ["json", "json5"]: self.lang_ext = "json" else: msg = f"Language {self.evo_config.language} not supported" raise ValueError(msg) # Queue for managing parallel jobs self.running_jobs: List[RunningJob] = [] self.best_program_id: Optional[str] = None self.next_generation_to_submit = 0 if resuming_run: self.completed_generations = self.db.last_iteration + 1 self.next_generation_to_submit = self.completed_generations logger.info("=" * 80) logger.info("RESUMING PREVIOUS EVOLUTION RUN") logger.info("=" * 80) logger.info( f"Resuming evolution from: {self.results_dir}\n" f"Found {self.completed_generations} " "previously completed generations." ) logger.info("=" * 80) self._update_best_solution() # Restore meta memory state when resuming self._restore_meta_memory() else: self.completed_generations = 0 # Save experiment configuration to a YAML file self._save_experiment_config(evo_config, job_config, db_config) def _save_experiment_config( self, evo_config: EvolutionConfig, job_config: JobConfig, db_config: DatabaseConfig, ) -> None: """Save experiment configuration to a YAML file.""" config_data = { "evolution_config": asdict(evo_config), "job_config": asdict(job_config), "database_config": asdict(db_config), "timestamp": datetime.now().isoformat(), "results_directory": str(self.results_dir), } config_path = Path(self.results_dir) / "experiment_config.yaml" config_path.parent.mkdir(parents=True, exist_ok=True) with config_path.open("w", encoding="utf-8") as f: yaml.dump(config_data, f, default_flow_style=False, indent=2) logger.info(f"Experiment configuration saved to {config_path}") def _log_patch_trajectory( self, generation: int, novelty_attempt: int, resample_attempt: int, patch_attempt: int, patch_type: str, parent_id: str, system_msg: str, pre_msg_history: List[Dict[str, Any]], user_msg: str, response: Optional[Any], llm_kwargs: Dict[str, Any], latency_sec: float, apply_outcome: Dict[str, Any], ) -> Optional[str]: """Write one OpenHands-style trajectory JSON for a single patch attempt.""" if not self.evo_config.trajectory_log: return None try: output_dir = resolve_trajectory_dir( Path(self.results_dir), generation, self.evo_config.trajectory_log_dir, ) metadata = { "generation": generation, "novelty_attempt": novelty_attempt, "resample_attempt": resample_attempt, "patch_attempt": patch_attempt, "patch_type": patch_type, "parent_id": parent_id, **apply_outcome, } payload = build_openhands_like_completion_payload( system_msg=system_msg, pre_msg_history=pre_msg_history, user_msg=user_msg, response=response, llm_kwargs=llm_kwargs, latency_sec=latency_sec, metadata=metadata, ) model_name = str( llm_kwargs.get( "model_name", getattr(response, "model_name", "unknown-model") if response else "unknown-model", ) ) out_path = write_openhands_like_completion_file( output_dir=output_dir, model_name=model_name, generation=generation, novelty_attempt=novelty_attempt, resample_attempt=resample_attempt, patch_attempt=patch_attempt, payload=payload, ) return str(out_path) except Exception as e: logger.warning( "Failed to persist patch trajectory for " f"gen={generation}, novelty={novelty_attempt}, " f"resample={resample_attempt}, patch={patch_attempt}: {e}" ) return None def run(self): """Run evolution with parallel job queue.""" max_jobs = self.evo_config.max_parallel_jobs target_gens = self.evo_config.num_generations logger.info( f"Starting evolution with {max_jobs} parallel jobs, " f"target: {target_gens} generations" ) # Initialize eval service for this experiment (if enabled) if self.eval_service_url and self.evo_config.use_eval_service: self._initialize_eval_service() # First, run generation 0 sequentially to populate the database if self.completed_generations == 0 and target_gens > 0: logger.info("Running generation 0 sequentially to initialize database...") self._run_generation_0() self.completed_generations = 1 self.next_generation_to_submit = 1 logger.info(f"Completed generation 0, total: 1/{target_gens}") # Log generation 0 to wandb self._log_generation_to_wandb(0) # Now start parallel execution for remaining generations if self.completed_generations < target_gens: logger.info("Starting parallel execution for remaining generations...") # Track which generations we've logged to wandb last_logged_generation = 0 if self.completed_generations > 0 else -1 # Main loop: monitor jobs and submit new ones while ( self.completed_generations < target_gens or len(self.running_jobs) > 0 ): # Check for completed jobs completed_jobs = self._check_completed_jobs() # Process completed jobs if completed_jobs: for job in completed_jobs: self._process_completed_job(job) # Update completed generations count prev_completed = self.completed_generations self._update_completed_generations() if self.verbose: logger.info( f"Processed {len(completed_jobs)} jobs. " f"Total completed generations: " f"{self.completed_generations}/{target_gens}" ) # Log newly completed generations to wandb if self.completed_generations > prev_completed: for gen in range(last_logged_generation + 1, self.completed_generations): self._log_generation_to_wandb(gen) last_logged_generation = self.completed_generations - 1 # Check if we've completed all generations if self.completed_generations >= target_gens: logger.info("All generations completed, exiting...") break # Submit new jobs to fill the queue (only if we have capacity) if ( len(self.running_jobs) < max_jobs and self.next_generation_to_submit < target_gens ): self._submit_new_job() # Wait a bit before checking again time.sleep(2) # All jobs are now handled by the main loop above # Perform final meta summary for any remaining unprocessed programs best_program = self.db.get_best_program() self.meta_summarizer.perform_final_summary(str(self.results_dir), best_program) # Save final meta memory state self._save_meta_memory() self.db.print_summary() logger.info(f"Evolution completed! {self.completed_generations} generations") logger.info("=" * 80) end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") logger.info(f"Evolution run ended at {end_time}") logger.info("=" * 80) # Finalize wandb logging if self.wandb_enabled and self.wandb_run is not None: try: wandb.finish() logger.info("WandB run finished successfully") except Exception as e: logger.warning(f"Error finishing WandB run: {e}") def generate_initial_program(self): """Generate initial program with LLM, with retries.""" llm_kwargs = self.llm.get_kwargs() sys_msg, user_msg = self.prompt_sampler.initial_program_prompt() msg_history = [] total_costs = 0.0 for attempt in range(self.evo_config.max_patch_attempts): response = self.llm.query( msg=user_msg, system_msg=sys_msg, llm_kwargs=llm_kwargs, msg_history=msg_history, ) if response is None or response.content is None: if self.verbose: logger.info( f" INITIAL PROGRAM ATTEMPT {attempt + 1}/" f"{self.evo_config.max_patch_attempts} " "FAILURE. Error: LLM response content was None." ) if attempt < self.evo_config.max_patch_attempts - 1: user_msg = ( "The previous response was empty. Please try again " "and provide the full code." ) if response and response.new_msg_history: msg_history = response.new_msg_history continue else: break total_costs += response.cost or 0 initial_code = extract_between( response.content, f"```{self.evo_config.language}", "```", False, ) if initial_code: patch_name = extract_between( response.content, "", "", False ) patch_description = extract_between( response.content, "", "", False ) if self.evo_config.language == "python": comment_char = "#" else: comment_char = "//" initial_code = ( f"{comment_char} EVOLVE-BLOCK-START\n" f"{initial_code}\n" f"{comment_char} EVOLVE-BLOCK-END\n" ) if self.verbose: logger.info( f" INITIAL PROGRAM ATTEMPT {attempt + 1}/" f"{self.evo_config.max_patch_attempts} " "SUCCESS." ) return initial_code, patch_name, patch_description, total_costs else: # code extraction failed if self.verbose: logger.info( f" INITIAL PROGRAM ATTEMPT {attempt + 1}/" f"{self.evo_config.max_patch_attempts} " "FAILURE. Error: Could not extract code from response." ) if attempt < self.evo_config.max_patch_attempts - 1: user_msg = ( "Could not extract code from your last response. " "Please make sure to enclose the code in " "``...`` tags." ) msg_history = response.new_msg_history else: # last attempt break raise ValueError( "LLM failed to generate a valid initial program after " f"{self.evo_config.max_patch_attempts} attempts." ) def _run_generation_0(self): """Setup and run generation 0 to initialize the database.""" initial_dir = f"{self.results_dir}/{FOLDER_PREFIX}_0" Path(initial_dir).mkdir(parents=True, exist_ok=True) exec_fname = f"{initial_dir}/main.{self.lang_ext}" results_dir = f"{self.results_dir}/{FOLDER_PREFIX}_0/results" Path(results_dir).mkdir(parents=True, exist_ok=True) api_costs = 0.0 patch_name = "initial_program" patch_description = "Initial program from file." patch_type = "init" if self.evo_config.init_program_path: if self.verbose: logger.info( f"Copying initial program from {self.evo_config.init_program_path}" ) shutil.copy(self.evo_config.init_program_path, exec_fname) else: if self.verbose: logger.info( "`init_program_path` not provided, " "generating initial program with LLM..." ) initial_code, patch_name, patch_description, api_costs = ( self.generate_initial_program() ) with open(exec_fname, "w", encoding="utf-8") as f: f.write(initial_code) if self.verbose: logger.info(f"Initial program generated and saved to {exec_fname}") # Run the evaluation synchronously results, rtime = self.scheduler.run(exec_fname, results_dir) code_embedding, e_cost = self.get_code_embedding(exec_fname) # Read the evaluated code for database insertion try: evaluated_code = Path(exec_fname).read_text(encoding="utf-8") except Exception as e: logger.warning(f"Could not read code for job {exec_fname}. Error: {e}") evaluated_code = "" correct_val = False metrics_val = {} stdout_log = "" stderr_log = "" if results: correct_val = results.get("correct", {}).get("correct", False) metrics_val = results.get("metrics", {}) stdout_log = results.get("stdout_log", "") stderr_log = results.get("stderr_log", "") combined_score = metrics_val.get("combined_score", 0.0) public_metrics = metrics_val.get("public", {}) private_metrics = metrics_val.get("private", {}) text_feedback = metrics_val.get("text_feedback", "") # Add the program to the database db_program = Program( id=str(uuid.uuid4()), code=evaluated_code, language=self.evo_config.language, parent_id=None, generation=0, archive_inspiration_ids=[], top_k_inspiration_ids=[], code_diff=None, embedding=code_embedding, correct=correct_val, combined_score=combined_score, public_metrics=public_metrics, private_metrics=private_metrics, text_feedback=text_feedback, metadata={ "compute_time": rtime, "api_costs": api_costs, "embed_cost": e_cost, "novelty_cost": 0.0, # No novelty cost for generation 0 "patch_type": patch_type, "patch_name": patch_name, "patch_description": patch_description, "stdout_log": stdout_log, "stderr_log": stderr_log, }, ) self.db.add(db_program, verbose=True) if self.llm_selection is not None: self.llm_selection.set_baseline_score( db_program.combined_score if correct_val else 0.0, ) self.db.save() self._update_best_solution() # Add the evaluated program to meta memory tracking self.meta_summarizer.add_evaluated_program(db_program) # Check if we should update meta memory after adding this program if self.meta_summarizer.should_update_meta(self.evo_config.meta_rec_interval): logger.info( f"Updating meta memory after processing " f"{len(self.meta_summarizer.evaluated_since_last_meta)} programs..." ) best_program = self.db.get_best_program() updated_recs, meta_cost = self.meta_summarizer.update_meta_memory( best_program ) if updated_recs: # Write meta output file for generation 0 self.meta_summarizer.write_meta_output(str(self.results_dir)) # Store meta cost for tracking if meta_cost > 0: logger.info( f"Meta recommendation generation cost: ${meta_cost:.4f}" ) # Add meta cost to this program's metadata (the one that triggered the update) if db_program.metadata is None: db_program.metadata = {} db_program.metadata["meta_cost"] = meta_cost # Update the program in the database with the new metadata import json metadata_json = json.dumps(db_program.metadata) self.db.cursor.execute( "UPDATE programs SET metadata = ? WHERE id = ?", (metadata_json, db_program.id), ) self.db.conn.commit() # Save meta memory state after each job completion self._save_meta_memory() def _update_completed_generations(self): """ Update the count of completed generations from the database. A generation `g` is considered complete if all generations from 0..g have at least one program in the database. This ensures the count advances sequentially without gaps. """ last_gen = self.db.last_iteration if last_gen == -1: self.completed_generations = 0 return # Check for contiguous generations from 0 up to last_gen completed_up_to = 0 for i in range(last_gen + 1): if self.db.get_programs_by_generation(i): completed_up_to = i + 1 else: # Found a gap, so contiguous sequence is broken self.completed_generations = completed_up_to return self.completed_generations = completed_up_to def _submit_new_job(self): """Submit a new job to the queue.""" current_gen = self.next_generation_to_submit if current_gen >= self.evo_config.num_generations: return self.next_generation_to_submit += 1 exec_fname = ( f"{self.results_dir}/{FOLDER_PREFIX}_{current_gen}/main.{self.lang_ext}" ) results_dir = f"{self.results_dir}/{FOLDER_PREFIX}_{current_gen}/results" Path(results_dir).mkdir(parents=True, exist_ok=True) # Get current meta-recommendations for this job meta_recs, meta_summary, meta_scratch = self.meta_summarizer.get_current() # Sample parent and inspiration programs if current_gen == 0: parent_id = None archive_insp_ids = [] top_k_insp_ids = [] code_diff = None meta_patch_data = {} # Initial program already copied in setup_initial_program else: api_costs = 0 embed_cost = 0 novelty_cost = 0.0 novelty_checks_performed = 0 # Loop over novelty attempts for nov_attempt in range(self.evo_config.max_novelty_attempts): # Loop over patch resamples - including parents for resample in range(self.evo_config.max_patch_resamples): ( parent_program, archive_programs, top_k_programs, ) = self.db.sample( target_generation=current_gen, novelty_attempt=nov_attempt + 1, max_novelty_attempts=self.evo_config.max_novelty_attempts, resample_attempt=resample + 1, max_resample_attempts=self.evo_config.max_patch_resamples, ) archive_insp_ids = [p.id for p in archive_programs] top_k_insp_ids = [p.id for p in top_k_programs] parent_id = parent_program.id # Run patch (until success with max attempts) code_diff, meta_patch_data, num_applied_attempt = self.run_patch( parent_program, archive_programs, top_k_programs, current_gen, novelty_attempt=nov_attempt + 1, resample_attempt=resample + 1, ) api_costs += meta_patch_data["api_costs"] if ( meta_patch_data["error_attempt"] is None and num_applied_attempt > 0 ): meta_patch_data["api_costs"] = api_costs break # Get the code embedding for the evaluated code code_embedding, e_cost = self.get_code_embedding(exec_fname) embed_cost += e_cost if not code_embedding: self.novelty_judge.log_novelty_skip_message("no embedding") break # Use NoveltyJudge for novelty assessment with rejection sampling if self.novelty_judge.should_check_novelty( code_embedding, current_gen, parent_program, self.db ): should_accept, novelty_metadata = ( self.novelty_judge.assess_novelty_with_rejection_sampling( exec_fname, code_embedding, parent_program, self.db ) ) # Update costs and metadata from novelty assessment novelty_cost += novelty_metadata.get("novelty_total_cost", 0.0) novelty_checks_performed = novelty_metadata.get( "novelty_checks_performed", 0 ) novelty_explanation = novelty_metadata.get( "novelty_explanation", "" ) if should_accept: break # If not accepted, continue to next attempt (rejection sampling) else: if not self.db.island_manager or not hasattr( self.db.island_manager, "are_all_islands_initialized" ): self.novelty_judge.log_novelty_skip_message("no island manager") elif not self.db.island_manager.are_all_islands_initialized(): self.novelty_judge.log_novelty_skip_message( "not all islands initialized yet" ) break # Add meta-recommendations/summary/scratchpad to meta_patch_data if meta_recs is not None: meta_patch_data["meta_recommendations"] = meta_recs meta_patch_data["meta_summary"] = meta_summary meta_patch_data["meta_scratch_pad"] = meta_scratch # Add novelty check information to meta_patch_data if any checks were performed if current_gen > 0 and novelty_checks_performed > 0: meta_patch_data["novelty_checks_performed"] = novelty_checks_performed meta_patch_data["novelty_cost"] = novelty_cost meta_patch_data["novelty_explanation"] = novelty_explanation # Submit the job asynchronously use_eval_service = self.eval_service_url and self.evo_config.use_eval_service if use_eval_service: # Use eval service for evaluation job_id = self._submit_to_eval_service(exec_fname, results_dir, current_gen) else: # Use traditional scheduler job_id = self.scheduler.submit_async(exec_fname, results_dir) # Add to running jobs queue running_job = RunningJob( job_id=job_id, exec_fname=exec_fname, results_dir=results_dir, start_time=time.time(), generation=current_gen, parent_id=parent_id, archive_insp_ids=archive_insp_ids, top_k_insp_ids=top_k_insp_ids, code_diff=code_diff, meta_patch_data=meta_patch_data, code_embedding=code_embedding, embed_cost=embed_cost, novelty_cost=novelty_cost, use_eval_service=use_eval_service, ) self.running_jobs.append(running_job) if self.verbose: logger.info( f"Submitted job for generation {current_gen}, " f"queue size: {len(self.running_jobs)}" ) def _check_completed_jobs(self) -> List[RunningJob]: """Check for completed jobs and return them.""" completed = [] still_running = [] for job in self.running_jobs: if job.use_eval_service: # Check eval service status is_complete = self._check_eval_service_status(job.job_id) if is_complete: if self.verbose: logger.info(f"Eval service job {job.job_id} completed!") completed.append(job) else: still_running.append(job) else: # Check traditional scheduler status is_running = self.scheduler.check_job_status(job) if not is_running: if self.verbose: logger.info(f"Job {job.job_id} completed!") completed.append(job) else: still_running.append(job) self.running_jobs = still_running return completed def _process_completed_job(self, job: RunningJob): """Process a completed job and add results to database.""" end_time = time.time() rtime = end_time - job.start_time # Get job results if job.use_eval_service: results = self._get_eval_service_results(job.job_id, job.results_dir) else: results = self.scheduler.get_job_results(job.job_id, job.results_dir) # Read the evaluated code try: evaluated_code = Path(job.exec_fname).read_text(encoding="utf-8") except Exception as e: logger.warning(f"Could not read code for job {job.job_id}. Error: {e}") evaluated_code = "" # Use pre-computed embedding and novelty costs code_embedding = job.code_embedding e_cost = job.embed_cost n_cost = job.novelty_cost if self.verbose: logger.debug( f"=> Using pre-computed embedding for job {job.job_id}, " f"embed cost: {e_cost:.4f}, novelty cost: {n_cost:.4f}" ) correct_val = False metrics_val = {} stdout_log = "" stderr_log = "" if results: correct_val = results.get("correct", {}).get("correct", False) metrics_val = results.get("metrics", {}) stdout_log = results.get("stdout_log", "") stderr_log = results.get("stderr_log", "") combined_score = metrics_val.get("combined_score", 0.0) public_metrics = metrics_val.get("public", {}) private_metrics = metrics_val.get("private", {}) text_feedback = metrics_val.get("text_feedback", "") # Add the program to the database db_program = Program( id=str(uuid.uuid4()), code=evaluated_code, language=self.evo_config.language, parent_id=job.parent_id, generation=job.generation, archive_inspiration_ids=job.archive_insp_ids, top_k_inspiration_ids=job.top_k_insp_ids, code_diff=job.code_diff, embedding=code_embedding, correct=correct_val, combined_score=combined_score, public_metrics=public_metrics, private_metrics=private_metrics, text_feedback=text_feedback, metadata={ "compute_time": rtime, **(job.meta_patch_data or {}), "embed_cost": e_cost, "novelty_cost": n_cost, "stdout_log": stdout_log, "stderr_log": stderr_log, }, ) self.db.add(db_program, verbose=True) # If eval agent produced a candidate, add it to DB as a separate program agent_candidate = results.get("agent_candidate") if results else None if agent_candidate and isinstance(agent_candidate, dict): candidate_score = agent_candidate.get("combined_score", 0.0) candidate_code = agent_candidate.get("code", "") candidate_correct = agent_candidate.get("correct", False) if candidate_code and candidate_score > 0: candidate_program = Program( id=str(uuid.uuid4()), code=candidate_code, language=self.evo_config.language, parent_id=job.parent_id, generation=job.generation, correct=candidate_correct, combined_score=candidate_score, public_metrics=agent_candidate.get("public", {}), text_feedback=agent_candidate.get("text_feedback", ""), metadata={ "source": "agent_candidate", "original_score": combined_score, }, ) self.db.add(candidate_program, verbose=True) logger.info( f"🔬 Agent candidate added to DB: " f"score={candidate_score:.2f} (original={combined_score:.2f})" ) # Add the evaluated program to meta memory tracking self.meta_summarizer.add_evaluated_program(db_program) # Check if we should update meta memory after adding this program if self.meta_summarizer.should_update_meta(self.evo_config.meta_rec_interval): logger.info( f"Updating meta memory after processing " f"{len(self.meta_summarizer.evaluated_since_last_meta)} programs..." ) best_program = self.db.get_best_program() updated_recs, meta_cost = self.meta_summarizer.update_meta_memory( best_program ) if updated_recs: # Write meta output file using accumulated program count self.meta_summarizer.write_meta_output(str(self.results_dir)) # Store meta cost for tracking if meta_cost > 0: logger.info( f"Meta recommendation generation cost: ${meta_cost:.4f}" ) # Add meta cost to this program's metadata (the one that triggered the update) if db_program.metadata is None: db_program.metadata = {} db_program.metadata["meta_cost"] = meta_cost # Update the program in the database with the new metadata import json metadata_json = json.dumps(db_program.metadata) self.db.cursor.execute( "UPDATE programs SET metadata = ? WHERE id = ?", (metadata_json, db_program.id), ) self.db.conn.commit() if self.llm_selection is not None: if "model_name" not in db_program.metadata: logger.warning( "No model_name found in program metadata, " "unable to update model selection algorithm." ) else: parent = ( self.db.get(db_program.parent_id) if db_program.parent_id else None ) baseline = parent.combined_score if parent else None reward = db_program.combined_score if correct_val else None model_name = db_program.metadata["model_name"] result = self.llm_selection.update( arm=model_name, reward=reward, baseline=baseline, ) if result and self.verbose: normalized_score, baseline = result def fmt(x): return f"{x:.4f}" if isinstance(x, (float, int)) else "None" logger.debug( f"==> UPDATED LLM SELECTION: model: " f"{model_name.split('/')[-1][-25:]}..., " f"score: {fmt(normalized_score)}, " f"raw score: {fmt(reward)}, baseline: {fmt(baseline)}" ) self.llm_selection.print_summary() self.db.save() self._update_best_solution() # Note: Meta summarization check is now done after completed generations # are updated in the main loop to ensure correct timing # Save meta memory state after each job completion self._save_meta_memory() # Eval service notification is handled by _submit_to_eval_service # when use_eval_service is enabled; no separate notification needed. def _initialize_eval_service(self): """ Initialize eval service for this experiment. Sends POST /api/v1/initialize to reset service state and prepare for new experiment. """ import requests from pathlib import Path # Prepare absolute experiment root path experiment_root = str(Path(self.results_dir).resolve()) # Convert evaluator module path to file path # e.g., "examples.circle_packing.evaluate_ori" -> "examples/circle_packing/evaluate_ori.py" primary_evaluator_path = None if self.evo_config.evaluator_module: primary_evaluator_path = self.evo_config.evaluator_module.replace(".", "/") + ".py" payload = { "results_dir": experiment_root, "primary_evaluator": primary_evaluator_path, "experiment_name": Path(experiment_root).name, "problem_statement": getattr(self.evo_config, "task_sys_msg", ""), "evaluator_kwargs": self.evo_config.evaluator_kwargs, } if self.evo_config.eval_service_trigger_mode is not None: payload["trigger_mode"] = self.evo_config.eval_service_trigger_mode if self.evo_config.eval_service_trigger_interval is not None: payload["trigger_interval"] = self.evo_config.eval_service_trigger_interval logger.info("=" * 80) logger.info("🔧 Initializing Eval Service for new experiment") logger.info(f" Experiment root: {experiment_root}") logger.info(f" Service URL: {self.eval_service_url}") if "trigger_mode" in payload: logger.info(f" Trigger mode override: {payload['trigger_mode']}") if "trigger_interval" in payload: logger.info(f" Trigger interval override: {payload['trigger_interval']}") logger.info("=" * 80) try: response = requests.post( f"{self.eval_service_url}/api/v1/initialize", json=payload, timeout=30.0 # Allow more time for agent initialization ) if response.status_code != 200: logger.error(f"❌ Eval service initialization failed: {response.status_code}") logger.error(f" Response: {response.text}") raise RuntimeError(f"Eval service initialization failed: {response.status_code}") result = response.json() if result.get("status") != "ready": logger.error(f"❌ Eval service not ready: {result.get('message')}") raise RuntimeError(f"Eval service not ready: {result.get('message')}") logger.info("=" * 80) logger.info("✅ Eval Service Initialized Successfully") logger.info(f" Status: {result.get('status')}") logger.info(f" Results dir: {result.get('results_dir')}") logger.info(f" Agent initialized: {result.get('agent_initialized')}") logger.info(f" Init time: {result.get('processing_time_ms', 0):.1f}ms") logger.info("=" * 80) except requests.exceptions.RequestException as e: logger.error(f"❌ Failed to connect to eval service: {e}") logger.error(f" Make sure eval service is running at {self.eval_service_url}") raise RuntimeError(f"Cannot connect to eval service: {e}") except Exception as e: logger.error(f"❌ Eval service initialization error: {e}") raise def _submit_to_eval_service(self, code_path: str, results_dir: str, generation: int) -> str: """Submit evaluation to eval service (async mode). Returns generation as job_id.""" import requests from pathlib import Path # Convert to absolute paths abs_code_path = str(Path(code_path).resolve()) abs_results_dir = str(Path(results_dir).resolve()) payload = { "generation": generation, "code_path": abs_code_path, "results_dir": abs_results_dir, "evaluator_module": self.evo_config.evaluator_module, "evaluator_function": self.evo_config.evaluator_function, } if self.evo_config.evaluator_kwargs: payload["evaluator_kwargs"] = self.evo_config.evaluator_kwargs response = requests.post( f"{self.eval_service_url}/api/v1/generation/complete", json=payload, timeout=5.0 ) if response.status_code != 200: raise RuntimeError(f"Eval service error: {response.status_code}") result = response.json() if result.get("status") != "accepted": raise RuntimeError(f"Eval service rejected request: {result}") # Use generation as job_id (for tracking) job_id = str(generation) if self.verbose: logger.info(f"Submitted to eval service: generation {generation}") return job_id def _check_eval_service_status(self, job_id: str) -> bool: """Check if eval service job is completed. job_id is the generation number.""" import requests try: generation = int(job_id) # job_id is generation number response = requests.get( f"{self.eval_service_url}/api/v1/generation/{generation}/status", timeout=2.0 ) if response.status_code == 200: return response.json().get("status") in ["completed", "failed"] except Exception: pass return False def _get_eval_service_results(self, job_id: str, results_dir: str) -> Optional[Dict[str, Any]]: """Get evaluation results from eval service. job_id is the generation number.""" import requests try: generation = int(job_id) # job_id is generation number response = requests.get( f"{self.eval_service_url}/api/v1/generation/{generation}/status", timeout=2.0 ) if response.status_code == 200: result_data = response.json() # Check if evaluation is completed if result_data.get("status") != "completed": logger.warning(f"Generation {generation} evaluation not completed yet: {result_data.get('status')}") return None # Extract result from response eval_result = result_data.get("result", {}) if not eval_result: logger.error(f"No result in response for generation {generation}") return None # eval_result has structure: {"combined_score": X, "primary": {...}, "auxiliary": {...}, "correct": bool} # Extract correct field (should be at top level after our fix) correct_val = eval_result.get("correct", False) # Use primary result for metrics primary = eval_result.get("primary", eval_result) # Merge auxiliary metrics into public_metrics so LLM can see them auxiliary = eval_result.get("auxiliary", {}) auxiliary_descriptions = eval_result.get("auxiliary_descriptions", {}) if auxiliary and isinstance(primary, dict) and "public" in primary: # Create a copy of primary to avoid modifying the original primary = primary.copy() primary["public"] = primary["public"].copy() # Add auxiliary metrics to public with "aux_" prefix for key, value in auxiliary.items(): # Handle nested dicts (e.g., from evaluate_auxiliary_metrics) if isinstance(value, dict) and "error" not in value: for sub_key, sub_value in value.items(): if isinstance(sub_value, (int, float, bool, str)): primary["public"][f"aux_{sub_key}"] = sub_value elif isinstance(value, (int, float, bool, str)): primary["public"][f"aux_{key}"] = value logger.info(f"Merged {len(auxiliary)} auxiliary metrics into public_metrics") # Store auxiliary descriptions in text_feedback for LLM to see if auxiliary_descriptions: desc_text = "\n\n# Auxiliary Metrics Guide\n\n" for metric_name, description in auxiliary_descriptions.items(): desc_text += f"- **{metric_name}**: {description}\n" # Append to existing text_feedback or create new existing_feedback = primary.get("text_feedback", "") if existing_feedback: primary["text_feedback"] = existing_feedback + desc_text else: primary["text_feedback"] = desc_text logger.info(f"Added {len(auxiliary_descriptions)} metric descriptions to text_feedback") # Extract agent candidate if present agent_candidate = eval_result.get("agent_candidate") # Transform to scheduler format return { "correct": {"correct": correct_val}, "metrics": primary, # Now includes auxiliary metrics "stdout_log": "", "stderr_log": "", "agent_candidate": agent_candidate, } except Exception as e: logger.error(f"Error getting eval service results: {e}") return None def _update_best_solution(self): """Checks and updates the best program.""" best_programs = self.db.get_top_programs(n=1, correct_only=True) if not best_programs: if self.verbose: logger.debug( "No correct programs found yet, cannot determine best solution." ) return best_program = best_programs[0] if best_program.id == self.best_program_id: return # No change self.best_program_id = best_program.id source_dir = f"{self.results_dir}/{FOLDER_PREFIX}_{best_program.generation}" best_dir = Path(self.results_dir) / "best" if best_dir.exists(): shutil.rmtree(best_dir) shutil.copytree(source_dir, best_dir) if self.verbose: logger.info( f"New best program found: gen {best_program.generation}, " f"id {best_program.id[:6]}... " f"Copied to {best_dir}" ) def _get_generation_stats(self, generation: int) -> Dict[str, Any]: """ Get statistics for a specific generation. Args: generation: The generation number to get stats for Returns: Dictionary containing global and per-island statistics """ if not self.db.cursor: return {} stats = {} # Global statistics self.db.cursor.execute(""" SELECT COUNT(*) as total, COUNT(CASE WHEN correct = 1 THEN 1 END) as num_correct, MAX(CASE WHEN correct = 1 THEN combined_score ELSE NULL END) as best_score, AVG(CASE WHEN correct = 1 THEN combined_score ELSE NULL END) as avg_score FROM programs WHERE generation = ? """, (generation,)) row = self.db.cursor.fetchone() if row: stats['total_programs'] = row['total'] or 0 stats['num_correct'] = row['num_correct'] or 0 stats['best_score'] = row['best_score'] if row['best_score'] is not None else 0.0 stats['avg_score'] = row['avg_score'] if row['avg_score'] is not None else 0.0 # Per-island statistics stats['islands'] = {} if self.db_config.num_islands > 0: self.db.cursor.execute(""" SELECT island_idx, COUNT(*) as num_programs, COUNT(CASE WHEN correct = 1 THEN 1 END) as num_correct, MAX(CASE WHEN correct = 1 THEN combined_score ELSE NULL END) as best_score, AVG(CASE WHEN correct = 1 THEN combined_score ELSE NULL END) as avg_score FROM programs WHERE generation = ? AND island_idx IS NOT NULL GROUP BY island_idx """, (generation,)) for row in self.db.cursor.fetchall(): island_idx = row['island_idx'] if island_idx is not None: stats['islands'][island_idx] = { 'num_programs': row['num_programs'] or 0, 'num_correct': row['num_correct'] or 0, 'best_score': row['best_score'] if row['best_score'] is not None else 0.0, 'avg_score': row['avg_score'] if row['avg_score'] is not None else 0.0, } return stats def _log_generation_to_wandb(self, generation: int): """ Log generation statistics to WandB. Args: generation: The generation number to log """ if not self.wandb_enabled or self.wandb_run is None: return try: # Get stats for this generation stats = self._get_generation_stats(generation) if not stats: return # Get global best score so far (across all generations) best_program = self.db.get_best_program() global_best_score = best_program.combined_score if best_program else 0.0 # Prepare metrics to log metrics = { "generation": generation, "score": stats.get('best_score', 0.0), # Best score in this generation "best_score_so_far": global_best_score, # Best score across all generations "avg_score": stats.get('avg_score', 0.0), "num_correct": stats.get('num_correct', 0), "total_programs": stats.get('total_programs', 0), } # Add per-island metrics for island_idx, island_stats in stats.get('islands', {}).items(): island_best = island_stats['best_score'] # Update island's historical best if island_idx not in self.island_best_scores: self.island_best_scores[island_idx] = island_best else: self.island_best_scores[island_idx] = max( self.island_best_scores[island_idx], island_best ) metrics[f"island_{island_idx}/score"] = island_best metrics[f"island_{island_idx}/best_score"] = self.island_best_scores[island_idx] metrics[f"island_{island_idx}/avg_score"] = island_stats['avg_score'] metrics[f"island_{island_idx}/num_correct"] = island_stats['num_correct'] metrics[f"island_{island_idx}/num_programs"] = island_stats['num_programs'] # Log to wandb wandb.log(metrics, step=generation) if self.verbose: logger.debug( f"Logged to WandB - Gen {generation}: " f"score={stats.get('best_score', 0.0):.4f}, " f"best={global_best_score:.4f}, " f"correct={stats.get('num_correct', 0)}" ) except Exception as e: logger.warning(f"Failed to log generation {generation} to WandB: {e}") def _resolve_openhands_model_name(self, sampled_model_name: str) -> str: """Resolve a Shinka sampled model name into a litellm/OpenHands model name.""" if self.evo_config.openhands_model: return self.evo_config.openhands_model model_name = sampled_model_name.strip() if not model_name and self.evo_config.llm_models: model_name = self.evo_config.llm_models[0] if model_name.startswith("native-"): return f"vertex_ai/{model_name.replace('native-', '', 1)}" if model_name.startswith("gemini-"): return f"vertex_ai/{model_name}" if model_name.startswith("azure-"): return f"azure/{model_name.replace('azure-', '', 1)}" return model_name @staticmethod def _sanitize_jinja_prompt_text(text: str) -> str: """Strip Jinja directives so prompt templates can be used as plain text.""" sanitized = re.sub(r"{#.*?#}", "", text, flags=re.DOTALL) sanitized = re.sub(r"{%.*?%}", "", sanitized, flags=re.DOTALL) sanitized = re.sub(r"{{\s*[^}]+\s*}}", "", sanitized) lines = [line.rstrip() for line in sanitized.splitlines()] return "\n".join(lines).strip() def _read_optional_prompt_text(self, path_str: Optional[str]) -> Optional[str]: if not path_str: return None path = Path(path_str) if not path.is_absolute(): path = Path.cwd() / path if not path.exists(): logger.warning(f"Prompt file not found: {path}") return None try: return path.read_text(encoding="utf-8") except Exception as e: logger.warning(f"Failed to read prompt file {path}: {e}") return None def _build_openhands_system_prompt_suffix(self, patch_sys: str) -> str: fallback_template = ( "\n" "You are running one mutation step inside the Shinka evolution loop.\n" "The loop already chose the parent program and historical inspirations.\n" "Preserve evaluator compatibility while improving solution quality.\n\n" "Task objective and hard constraints:\n" "{{ shinka_task_policy }}\n" "\n\n" "\n" "{{ ev2_prompt_reference }}\n" "\n\n" "\n" "Edit the target file in-place and leave a correct improved program.\n" "In your final assistant response, include and tags.\n" "\n" ) template_text = self._read_optional_prompt_text( self.evo_config.openhands_system_prompt_suffix_path ) if not template_text: template_text = fallback_template ev2_text = self._read_optional_prompt_text(self.evo_config.openhands_ev2_prompt_path) ev2_text = self._sanitize_jinja_prompt_text(ev2_text or "") rendered = template_text rendered = rendered.replace("{{ shinka_task_policy }}", patch_sys or "") rendered = rendered.replace("{{shinka_task_policy}}", patch_sys or "") rendered = rendered.replace("{{ ev2_prompt_reference }}", ev2_text) rendered = rendered.replace("{{ev2_prompt_reference}}", ev2_text) return rendered.strip() @staticmethod def _flatten_openhands_message_content(content: Any) -> str: """Flatten OpenHands message content into plain text for metadata logging.""" if isinstance(content, str): return content if isinstance(content, dict): if isinstance(content.get("text"), str): return content["text"] if isinstance(content.get("content"), str): return content["content"] return str(content) if isinstance(content, list): chunks: List[str] = [] for part in content: if isinstance(part, str): chunks.append(part) continue if isinstance(part, dict): text_val = part.get("text") if isinstance(text_val, str): chunks.append(text_val) continue content_val = part.get("content") if isinstance(content_val, str): chunks.append(content_val) continue chunks.append(str(part)) return "\n".join([c for c in chunks if c]).strip() return str(content) if content is not None else "" @staticmethod def _extract_last_assistant_text(msg_history: List[Dict[str, Any]]) -> str: for msg in reversed(msg_history): if msg.get("role") == "assistant": content = msg.get("content") if isinstance(content, str) and content.strip(): return content.strip() return "" def _run_openhands_patch_attempt( self, *, parent_program: Program, patch_sys: str, patch_msg: str, llm_kwargs: Dict[str, Any], generation: int, novelty_attempt: int, resample_attempt: int, patch_attempt: int, images: Optional[List[str]], ) -> tuple[ Optional[QueryResult], Optional[str], Optional[str], Optional[str], Optional[str], ]: """ Run one OpenHands agentic edit attempt and return: - QueryResult-like response for existing metadata path - patch payload to apply_full_patch - optional patch name / description - optional error string """ try: from openhands.sdk import LLM, Agent, Conversation, Tool from openhands.sdk.context.agent_context import AgentContext from openhands.tools.file_editor import FileEditorTool from openhands.tools.task_tracker import TaskTrackerTool from openhands.tools.terminal import TerminalTool from openhands.sdk.event.base import LLMConvertibleEvent except Exception as e: return None, None, None, None, f"OpenHands import failed: {e}" attempt_workspace = ( Path(self.results_dir) / f"{FOLDER_PREFIX}_{generation}" / "agent_workspace" / f"n{novelty_attempt}_r{resample_attempt}_p{patch_attempt}" ).resolve() attempt_workspace.mkdir(parents=True, exist_ok=True) target_file = (attempt_workspace / f"main.{self.lang_ext}").resolve() target_file.write_text(parent_program.code, encoding="utf-8") task_file = attempt_workspace / "SHINKA_TASK.md" task_file.write_text( ( "# Shinka Mutation Brief\n\n" "This brief is prepared by the Shinka evolution loop for one mutation step.\n" "The parent program and historical inspirations are already selected.\n" "Your job is to produce a stronger variant while preserving evaluator compatibility.\n\n" "## Objective and Constraints\n" "This section defines task-level goals and hard constraints.\n\n" f"{patch_sys}\n\n" "## Parent Program, Prior Programs, and Metrics Context\n" "This section includes the selected parent program, historical inspirations,\n" "and metric feedback used for this mutation step.\n\n" f"{patch_msg}\n" ), encoding="utf-8", ) image_paths = [] if images: for img in images: try: image_paths.append(str(Path(img).resolve())) except Exception: image_paths.append(str(img)) image_note = "" if image_paths: image_note = ( "\n\n# Optional Visual Context\n" "If useful, inspect these files from the terminal:\n" + "\n".join(f"- {p}" for p in image_paths) ) task_message = ( "You are handling one Shinka mutation step.\n" "The evolution loop already selected the parent program and relevant inspirations.\n" "Use the full context below to create a better candidate.\n\n" f"Target file (absolute path): {target_file}\n" f"Workspace root: {attempt_workspace}\n\n" "## Parent Program, Prior Programs, and Metrics Context\n" "Use this section to understand what has been tried and how current code performs.\n\n" f"{patch_msg}\n" "\n## Execution Plan\n" "- Make edits directly to the target file using tools.\n" "- Keep code outside EVOLVE-BLOCK markers unchanged.\n" "- Run lightweight checks when feasible.\n" "- The primary requirement is to leave a correct, improved edited file on disk.\n" "- In your final assistant message, include and tags " "summarizing the edit.\n\n" "The same brief is also available at SHINKA_TASK.md in this workspace." f"{image_note}\n" ) sampled_model_name = str(llm_kwargs.get("model_name", "")) resolved_model = self._resolve_openhands_model_name(sampled_model_name) if not resolved_model: return ( None, None, None, None, "Could not resolve OpenHands model name from llm_kwargs.", ) llm_init_kwargs: Dict[str, Any] = { "model": resolved_model, "log_completions": self.evo_config.openhands_log_completions, "max_message_chars": self.evo_config.openhands_max_message_chars, } if self.evo_config.openhands_log_completions_dir: log_dir = Path(self.evo_config.openhands_log_completions_dir) if not log_dir.is_absolute(): log_dir = attempt_workspace / log_dir llm_init_kwargs["log_completions_folder"] = str(log_dir.resolve()) else: llm_init_kwargs["log_completions_folder"] = str( (attempt_workspace / "llm_completions").resolve() ) if "temperature" in llm_kwargs: llm_init_kwargs["temperature"] = llm_kwargs["temperature"] if "max_output_tokens" in llm_kwargs: llm_init_kwargs["max_output_tokens"] = llm_kwargs["max_output_tokens"] elif "max_tokens" in llm_kwargs: llm_init_kwargs["max_output_tokens"] = llm_kwargs["max_tokens"] reasoning_cfg = llm_kwargs.get("reasoning") if isinstance(reasoning_cfg, dict): effort = reasoning_cfg.get("effort") if effort in {"low", "medium", "high", "xhigh", "none"}: llm_init_kwargs["reasoning_effort"] = effort extra_body_cfg = llm_kwargs.get("extra_body") if isinstance(extra_body_cfg, dict): llm_init_kwargs["litellm_extra_body"] = extra_body_cfg api_key = os.getenv("LLM_API_KEY") if api_key: llm_init_kwargs["api_key"] = api_key base_url = os.getenv("LLM_BASE_URL") if base_url: llm_init_kwargs["base_url"] = base_url try: oh_llm = LLM(**llm_init_kwargs) start_cost = float(getattr(oh_llm.metrics, "accumulated_cost", 0.0) or 0.0) start_usage = getattr(oh_llm.metrics, "accumulated_token_usage", None) start_prompt = int(getattr(start_usage, "prompt_tokens", 0) or 0) start_completion = int(getattr(start_usage, "completion_tokens", 0) or 0) start_reasoning = int(getattr(start_usage, "reasoning_tokens", 0) or 0) system_prompt_path: Optional[str] = None if self.evo_config.openhands_system_prompt_path: candidate_path = Path(self.evo_config.openhands_system_prompt_path) if not candidate_path.is_absolute(): candidate_path = Path.cwd() / candidate_path if candidate_path.exists(): system_prompt_path = str(candidate_path.resolve()) else: logger.warning( "OpenHands system prompt template not found at " f"{candidate_path}; falling back to default." ) agent = Agent( llm=oh_llm, tools=[ Tool(name=TerminalTool.name), Tool(name=FileEditorTool.name), Tool(name=TaskTrackerTool.name), ], agent_context=AgentContext( system_message_suffix=self._build_openhands_system_prompt_suffix( patch_sys ) ), system_prompt_filename=( system_prompt_path if system_prompt_path else "system_prompt.j2" ), system_prompt_kwargs={ "shinka_task_policy": patch_sys, }, ) conversation = Conversation( agent=agent, workspace=str(attempt_workspace), max_iteration_per_run=self.evo_config.openhands_max_iterations_per_run, ) conversation.send_message(task_message) conversation.run() except Exception as e: return ( None, None, None, None, f"OpenHands run failed (model={resolved_model}): {e}", ) end_cost = float(getattr(oh_llm.metrics, "accumulated_cost", 0.0) or 0.0) end_usage = getattr(oh_llm.metrics, "accumulated_token_usage", None) end_prompt = int(getattr(end_usage, "prompt_tokens", 0) or 0) end_completion = int(getattr(end_usage, "completion_tokens", 0) or 0) end_reasoning = int(getattr(end_usage, "reasoning_tokens", 0) or 0) msg_history: List[Dict[str, Any]] = [] thought_chunks: List[str] = [] try: events = list(conversation.state.events) llm_events = [e for e in events if isinstance(e, LLMConvertibleEvent)] llm_messages = LLMConvertibleEvent.events_to_messages(llm_events) for msg in llm_messages: if hasattr(msg, "model_dump"): raw_msg = msg.model_dump() else: raw_msg = dict(msg) role = str(raw_msg.get("role", "assistant")) content = self._flatten_openhands_message_content(raw_msg.get("content")) entry: Dict[str, Any] = {"role": role, "content": content} thinking_blocks = raw_msg.get("thinking_blocks") if isinstance(thinking_blocks, list) and thinking_blocks: entry["thinking_blocks"] = thinking_blocks for blk in thinking_blocks: if isinstance(blk, dict): thought_val = blk.get("thinking") if isinstance(thought_val, str) and thought_val.strip(): thought_chunks.append(thought_val.strip()) msg_history.append(entry) except Exception as e: logger.debug(f"Failed to extract OpenHands LLM message history: {e}") if not msg_history: msg_history = [{"role": "user", "content": task_message}] assistant_text = self._extract_last_assistant_text(msg_history) if not assistant_text: assistant_text = "OpenHands completed without a textual summary." msg_history.append({"role": "assistant", "content": assistant_text}) try: edited_code = target_file.read_text(encoding="utf-8") except Exception as e: return ( None, None, None, None, f"Failed to read OpenHands-edited target file {target_file}: {e}", ) if edited_code == parent_program.code: response_no_change = QueryResult( content=assistant_text, msg=patch_msg, system_msg=patch_sys, new_msg_history=msg_history, model_name=resolved_model, kwargs={ **llm_kwargs, "edit_backend": "openhands_agent", "agent_workspace": str(attempt_workspace), "resolved_model_name": resolved_model, }, input_tokens=max(end_prompt - start_prompt, 0), output_tokens=max(end_completion - start_completion, 0), thoughts_tokens=max(end_reasoning - start_reasoning, 0), cost=max(end_cost - start_cost, 0.0), thought="\n\n".join(thought_chunks).strip(), ) return ( response_no_change, None, extract_between(assistant_text, "", "", False), extract_between(assistant_text, "", "", False), f"OpenHands agent produced no file changes for {target_file}.", ) patch_payload = f"```{self.evo_config.language}\n{edited_code}\n```" response = QueryResult( content=assistant_text, msg=patch_msg, system_msg=patch_sys, new_msg_history=msg_history, model_name=resolved_model, kwargs={ **llm_kwargs, "edit_backend": "openhands_agent", "agent_workspace": str(attempt_workspace), "resolved_model_name": resolved_model, "target_file": str(target_file), }, input_tokens=max(end_prompt - start_prompt, 0), output_tokens=max(end_completion - start_completion, 0), thoughts_tokens=max(end_reasoning - start_reasoning, 0), cost=max(end_cost - start_cost, 0.0), thought="\n\n".join(thought_chunks).strip(), ) patch_name = extract_between(assistant_text, "", "", False) patch_description = extract_between( assistant_text, "", "", False ) return response, patch_payload, patch_name, patch_description, None def run_patch( self, parent_program: Program, archive_programs: List[Program], top_k_programs: List[Program], generation: int, novelty_attempt: int = 1, resample_attempt: int = 1, ) -> tuple[Optional[str], dict, int]: """Run patch generation for a specific generation.""" max_patch_attempts = self.evo_config.max_patch_attempts if self.verbose: logger.info( f"Edit Cycle {generation} -> {generation + 1}, " f"Max Patch Attempts: {max_patch_attempts}" ) # Get current meta recommendations meta_recs, _, _ = self.meta_summarizer.get_current() # Fetch recent attempts for the structured history table recent_programs = [] best_program = None if self.evo_config.recent_attempts_k > 0: recent_programs = self.db.get_recent_programs( n=self.evo_config.recent_attempts_k ) best_program = self.db.get_best_program() # Construct edit / code change message patch_sys, patch_msg, patch_type, images = self.prompt_sampler.sample( parent=parent_program, archive_inspirations=archive_programs, top_k_inspirations=top_k_programs, meta_recommendations=meta_recs, recent_programs=recent_programs, best_program=best_program, ) base_patch_msg = patch_msg edit_backend = self.evo_config.edit_backend if edit_backend not in {"single_shot_patch", "openhands_agent"}: raise ValueError(f"Invalid edit_backend: {edit_backend}") use_openhands_agent = edit_backend == "openhands_agent" if use_openhands_agent: # Agent edits a real file in-place, then we re-apply as a full-file mutation # to preserve immutable EVOLVE-boundary behavior. apply_patch_fn = apply_full_patch else: if patch_type in ["full", "cross"]: apply_patch_fn = apply_full_patch elif patch_type == "diff": apply_patch_fn = apply_diff_patch elif patch_type == "paper": raise NotImplementedError("Paper edit not implemented.") # apply_patch = apply_paper_patch else: raise ValueError(f"Invalid patch type: {patch_type}") total_costs = 0 msg_history = [] llm_kwargs = self.llm.get_kwargs() if self.llm_selection is not None: model_name = llm_kwargs["model_name"] self.llm_selection.update_submitted(model_name) code_diff = None # Initialize code_diff num_applied_attempt = 0 # Initialize num_applied_attempt error_attempt = ( "Max attempts reached without successful patch." # Default error ) patch_name = None patch_description = None output_path_attempt = None patch_txt_attempt = None patch_path = None diff_summary = {} trajectory_files: List[str] = [] response: Optional[QueryResult] = None for patch_attempt in range(max_patch_attempts): pre_msg_history = copy.deepcopy(msg_history) current_patch_msg = patch_msg query_start = time.time() patch_payload: Optional[str] = None agent_error: Optional[str] = None agent_patch_name: Optional[str] = None agent_patch_description: Optional[str] = None if use_openhands_agent: ( response, patch_payload, agent_patch_name, agent_patch_description, agent_error, ) = self._run_openhands_patch_attempt( parent_program=parent_program, patch_sys=patch_sys, patch_msg=current_patch_msg, llm_kwargs=llm_kwargs, generation=generation, novelty_attempt=novelty_attempt, resample_attempt=resample_attempt, patch_attempt=patch_attempt + 1, images=images, ) else: response = self.llm.query( msg=current_patch_msg, system_msg=patch_sys, msg_history=msg_history, llm_kwargs=llm_kwargs, images=images, ) if response is not None: patch_payload = response.content latency_sec = time.time() - query_start if response is None or patch_payload is None: if self.verbose: logger.info( f" PATCH ATTEMPT {patch_attempt + 1}/{max_patch_attempts} FAILURE. " f"Error: {(agent_error or 'LLM response content was None.')}" ) # Prepare for next attempt or exit error_attempt = agent_error or "LLM response content was None." num_applied_attempt = 0 patch_txt_attempt = None trajectory_file = self._log_patch_trajectory( generation=generation, novelty_attempt=novelty_attempt, resample_attempt=resample_attempt, patch_attempt=patch_attempt + 1, patch_type=patch_type, parent_id=parent_program.id, system_msg=patch_sys, pre_msg_history=pre_msg_history, user_msg=current_patch_msg, response=response, llm_kwargs=llm_kwargs, latency_sec=latency_sec, apply_outcome={ "query_status": "agent_error" if use_openhands_agent else "empty_response", "apply_success": False, "num_applied": 0, "error_attempt": error_attempt, "output_path": None, }, ) if trajectory_file is not None: trajectory_files.append(trajectory_file) if patch_attempt < max_patch_attempts - 1: if use_openhands_agent: patch_msg = ( f"{base_patch_msg}\n\n" "# Retry Note\n" "The previous agentic edit attempt failed.\n" f"Error: {error_attempt}\n" "Try again and produce a concrete file edit." ) else: patch_msg = ( "The previous attempt to get an edit was not " "successful because the LLM response was empty. " "Try again." ) if response and not use_openhands_agent: msg_history = response.new_msg_history continue else: # Last attempt break total_costs += response.cost or 0.0 # Acc. cost if use_openhands_agent: if isinstance(agent_patch_name, str) and agent_patch_name.strip(): patch_name = agent_patch_name else: patch_name = "openhands_agent_edit" if ( isinstance(agent_patch_description, str) and agent_patch_description.strip() ): patch_description = agent_patch_description else: patch_description = ( "OpenHands multi-turn tool-assisted file edit." ) else: patch_name = extract_between( response.content, "", "", False, ) patch_description = extract_between( response.content, "", "", False, ) # Apply the code patch (diff/full rewrite) ( _, num_applied_attempt, output_path_attempt, error_attempt, patch_txt_attempt, patch_path, ) = apply_patch_fn( original_str=parent_program.code, patch_str=patch_payload, patch_dir=f"{self.results_dir}/{FOLDER_PREFIX}_{generation}", language=self.evo_config.language, verbose=False, ) if error_attempt is None and num_applied_attempt > 0: if patch_path: # Ensure patch_path is not None diff_summary = summarize_diff( str(patch_path) ) # Convert Path to str if self.verbose: logger.info( f" PATCH ATTEMPT {patch_attempt + 1}/{max_patch_attempts} SUCCESS. " f"Output: {output_path_attempt}, " f"Patches Applied: {num_applied_attempt}." ) trajectory_file = self._log_patch_trajectory( generation=generation, novelty_attempt=novelty_attempt, resample_attempt=resample_attempt, patch_attempt=patch_attempt + 1, patch_type=patch_type, parent_id=parent_program.id, system_msg=patch_sys, pre_msg_history=pre_msg_history, user_msg=current_patch_msg, response=response, llm_kwargs=llm_kwargs, latency_sec=latency_sec, apply_outcome={ "query_status": "ok", "apply_success": True, "num_applied": num_applied_attempt, "error_attempt": None, "output_path": str(output_path_attempt) if output_path_attempt else None, }, ) if trajectory_file is not None: trajectory_files.append(trajectory_file) code_diff = patch_txt_attempt break # Break from patch attempts else: error_str = ( str(error_attempt) if error_attempt else "No changes applied." ) patch_msg = ( "The previous edit was not successful." + " This was the error message: \n\n" + error_str + "\n\n Try again." ) if self.verbose: logger.info( f" PATCH ATTEMPT {patch_attempt + 1}/{max_patch_attempts} FAILURE. " f"Error: '{error_str}', " f"Patches Applied: {num_applied_attempt}." ) trajectory_file = self._log_patch_trajectory( generation=generation, novelty_attempt=novelty_attempt, resample_attempt=resample_attempt, patch_attempt=patch_attempt + 1, patch_type=patch_type, parent_id=parent_program.id, system_msg=patch_sys, pre_msg_history=pre_msg_history, user_msg=current_patch_msg, response=response, llm_kwargs=llm_kwargs, latency_sec=latency_sec, apply_outcome={ "query_status": "ok", "apply_success": False, "num_applied": num_applied_attempt, "error_attempt": error_str, "output_path": str(output_path_attempt) if output_path_attempt else None, }, ) if trajectory_file is not None: trajectory_files.append(trajectory_file) if not use_openhands_agent: msg_history = response.new_msg_history code_diff = None if patch_attempt == max_patch_attempts - 1: # Last attempt failed # error_attempt is already set from apply_patch or default pass # Only consider the diff summary for the original source file original_filename = f"original.{self.lang_ext}" if original_filename in diff_summary: diff_summary = diff_summary[original_filename] meta_edit_data = { "patch_type": patch_type, "api_costs": total_costs, "num_applied": num_applied_attempt, "patch_name": patch_name, "patch_description": patch_description, "error_attempt": error_attempt, "edit_backend": self.evo_config.edit_backend, "novelty_attempt": novelty_attempt, "resample_attempt": resample_attempt, "patch_attempt": patch_attempt + 1, **llm_kwargs, "llm_result": response.to_dict() if response else None, "trajectory_files": trajectory_files, "diff_summary": diff_summary, } if self.verbose and num_applied_attempt > 0: self._print_metadata_table(meta_edit_data, generation) # Delete generation from meta_edit_data return code_diff, meta_edit_data, num_applied_attempt def get_code_embedding(self, exec_fname: str) -> tuple[List[float], float]: """Get the embedding of the code.""" # Read the evaluated code try: evaluated_code = Path(exec_fname).read_text(encoding="utf-8") except Exception as e: logger.warning(f"Could not read code for job {exec_fname}. Error: {e}") evaluated_code = "" if evaluated_code != "": # Get the embedding of the initial program try: if self.embedding is not None: redacted_code = redact_immutable(evaluated_code, no_state=True) if self.verbose: logger.debug( "=> EMBED: Code length - " f"Original: {len(evaluated_code)} - " f"Redacted: {len(redacted_code)}" ) embedding_result, e_cost = self.embedding.get_embedding( redacted_code ) else: if self.verbose: logger.debug("=> EMBED: No embedding model configured.") embedding_result = [] e_cost = 0.0 code_embedding = cast(List[float], embedding_result) except Exception as e: logger.warning(f"Could not embed code for job {exec_fname}. Error: {e}") code_embedding = [] e_cost = 0.0 else: code_embedding = [] e_cost = 0.0 return code_embedding, e_cost def _print_metadata_table(self, meta_data: dict, generation: int): """Display metadata in a formatted rich table.""" # Create title with generation and attempt information title_parts = ["[bold magenta]Patch Metadata"] # Add generation if present if generation is not None: title_parts.append( f" - Gen {generation}/{self.evo_config.num_generations} - Novelty: {meta_data['novelty_attempt']}/{self.evo_config.max_novelty_attempts} - Resample: {meta_data['resample_attempt']}/{self.evo_config.max_patch_resamples} - Patch: {meta_data['patch_attempt']}/{self.evo_config.max_patch_attempts}" ) # Add attempt information if present if all( key in meta_data for key in [ "novelty_attempt", "resample_attempt", "patch_attempt", "generation", ] ): title_parts.append( f" (Novelty: {meta_data['novelty_attempt']}, " f"Resample: {meta_data['resample_attempt']}, " f"Patch: {meta_data['patch_attempt']})" ) title_parts.append("[/bold magenta]") table = Table( title="".join(title_parts), show_header=True, header_style="bold cyan", border_style="magenta", box=rich.box.ROUNDED, width=120, # Match display.py table width ) table.add_column("Field", style="cyan bold", no_wrap=True, width=25) table.add_column("Value", style="green", overflow="fold", width=90) # Define display order and formatting for specific fields display_order = [ "patch_type", "patch_name", "patch_description", "num_applied", "api_costs", "error_attempt", ] # Add ordered fields first for field_name in display_order: if field_name in meta_data: value = meta_data[field_name] if value is None: formatted_value = "[dim]None[/dim]" elif field_name == "api_costs": formatted_value = f"${value:.4f}" elif field_name == "error_attempt" and value is None: formatted_value = "[green]Success[/green]" elif field_name == "error_attempt": formatted_value = ( f"[red]{str(value)[:100]}...[/red]" if len(str(value)) > 100 else f"[red]{value}[/red]" ) else: formatted_value = str(value) table.add_row(field_name, formatted_value) # Add remaining fields (excluding llm_result, diff_summary, and header info) skip_fields = set( display_order + [ "llm_result", "diff_summary", "generation", "novelty_attempt", "resample_attempt", "patch_attempt", ] ) for field_key, field_value in meta_data.items(): if field_key not in skip_fields: if field_value is None: formatted_value = "[dim]None[/dim]" else: formatted_value = ( str(field_value)[:100] + "..." if len(str(field_value)) > 100 else str(field_value) ) table.add_row(field_key, formatted_value) # Add diff summary if available if "diff_summary" in meta_data and meta_data["diff_summary"]: diff_summary = meta_data["diff_summary"] if isinstance(diff_summary, dict): summary_text = "" for k, v in diff_summary.items(): summary_text += f"{k}: {v}; " table.add_row("diff_summary", summary_text.strip()) else: table.add_row("diff_summary", str(diff_summary)[:200]) self.console.print(table) def _save_meta_memory(self) -> None: """Save the meta memory state to disk.""" meta_memory_path = Path(self.results_dir) / "meta_memory.json" self.meta_summarizer.save_meta_state(str(meta_memory_path)) def _restore_meta_memory(self) -> None: """Restore the meta memory state from disk.""" meta_memory_path = Path(self.results_dir) / "meta_memory.json" if self.verbose: logger.info(f"Attempting to restore meta memory from: {meta_memory_path}") success = self.meta_summarizer.load_meta_state(str(meta_memory_path)) if success: logger.info("Successfully restored meta memory state") else: if meta_memory_path.exists(): logger.warning( f"Meta memory file exists but failed to load: {meta_memory_path}" ) else: logger.info("No previous meta memory state found - starting fresh")