Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions openevolve/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import logging
import os
import re
import sys
from typing import Any, Dict, List, Optional

Expand Down Expand Up @@ -201,15 +202,16 @@ async def main_async() -> int:
checkpoint_dir = os.path.join(openevolve.output_dir, "checkpoints")
latest_checkpoint = None
if os.path.exists(checkpoint_dir):
# Only checkpoint_<iteration> folders are checkpoints. Anything else a
# user keeps here must not fail a finished run with a ValueError.
checkpoints = [
os.path.join(checkpoint_dir, d)
(int(match.group(1)), os.path.join(checkpoint_dir, d))
for d in os.listdir(checkpoint_dir)
if os.path.isdir(os.path.join(checkpoint_dir, d))
if (match := re.fullmatch(r"checkpoint_(\d+)", d))
and os.path.isdir(os.path.join(checkpoint_dir, d))
]
if checkpoints:
latest_checkpoint = sorted(
checkpoints, key=lambda x: int(x.split("_")[-1]) if "_" in x else 0
)[-1]
latest_checkpoint = max(checkpoints)[1]

print(f"\nEvolution complete!")
print(f"Best program metrics:")
Expand Down
62 changes: 62 additions & 0 deletions tests/test_cli_latest_checkpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""The end-of-run summary must not fail a finished run over the checkpoints folder."""

import asyncio
import contextlib
import io
import os
import tempfile
import unittest
from unittest.mock import AsyncMock, MagicMock, patch

from openevolve import cli


class TestCliLatestCheckpoint(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
# The default output folder name, "openevolve_output", has an underscore
self.output_dir = os.path.join(temp.name, "openevolve_output")
self.checkpoint_dir = os.path.join(self.output_dir, "checkpoints")
for name in ("checkpoint_9", "checkpoint_10"):
os.makedirs(os.path.join(self.checkpoint_dir, name))
self.program = os.path.join(temp.name, "program.py")
self.evaluator = os.path.join(temp.name, "evaluator.py")
for path in (self.program, self.evaluator):
open(path, "w").close()

def _run_cli(self):
engine = MagicMock()
engine.output_dir = self.output_dir
engine.run = AsyncMock(return_value=MagicMock(metrics={"combined_score": 1.0}))
argv = ["openevolve-run", self.program, self.evaluator]
output = io.StringIO()
with patch("sys.argv", argv), patch.object(cli, "OpenEvolve", return_value=engine):
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
exit_code = asyncio.run(cli.main_async())
return exit_code, output.getvalue()

def test_reports_highest_numbered_checkpoint(self):
exit_code, output = self._run_cli()
self.assertEqual(exit_code, 0, output)
self.assertIn(f"--checkpoint {os.path.join(self.checkpoint_dir, 'checkpoint_10')}", output)

def test_ignores_other_directories(self):
# e.g. a checkpoint the user kept under another name, or a notes folder
for name in ("checkpoint_10_backup", "notes"):
os.makedirs(os.path.join(self.checkpoint_dir, name))
exit_code, output = self._run_cli()
self.assertEqual(exit_code, 0, output)
self.assertIn(f"--checkpoint {os.path.join(self.checkpoint_dir, 'checkpoint_10')}", output)

def test_no_numbered_checkpoints(self):
for name in ("checkpoint_9", "checkpoint_10"):
os.rmdir(os.path.join(self.checkpoint_dir, name))
os.makedirs(os.path.join(self.checkpoint_dir, "notes"))
exit_code, output = self._run_cli()
self.assertEqual(exit_code, 0, output)
self.assertNotIn("--checkpoint", output)


if __name__ == "__main__":
unittest.main()
Loading