From b7eb9184fad1ac3432d89c452578040087e24902 Mon Sep 17 00:00:00 2001 From: Cookie0103 <258013390+Cookie0103@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:53:39 +0900 Subject: [PATCH 1/4] feat: add durable AFlow trial evidence and bounded evaluation --- evoagentx/models/model_utils.py | 47 +++ evoagentx/optimizers/aflow/__init__.py | 7 + evoagentx/optimizers/aflow/budget.py | 112 ++++++ evoagentx/optimizers/aflow/evaluator.py | 171 ++++++++++ evoagentx/optimizers/aflow/evidence.py | 155 +++++++++ evoagentx/optimizers/aflow/store.py | 393 ++++++++++++++++++++++ evoagentx/optimizers/aflow/types.py | 320 ++++++++++++++++++ tests/src/optimizers/test_aflow_trials.py | 270 +++++++++++++++ 8 files changed, 1475 insertions(+) create mode 100644 evoagentx/optimizers/aflow/__init__.py create mode 100644 evoagentx/optimizers/aflow/budget.py create mode 100644 evoagentx/optimizers/aflow/evaluator.py create mode 100644 evoagentx/optimizers/aflow/evidence.py create mode 100644 evoagentx/optimizers/aflow/store.py create mode 100644 evoagentx/optimizers/aflow/types.py create mode 100644 tests/src/optimizers/test_aflow_trials.py diff --git a/evoagentx/models/model_utils.py b/evoagentx/models/model_utils.py index 065bc41d..e3f523d3 100644 --- a/evoagentx/models/model_utils.py +++ b/evoagentx/models/model_utils.py @@ -1,5 +1,9 @@ import threading +import math from collections import defaultdict +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass from typing import Optional import pandas as pd @@ -11,6 +15,19 @@ from .model_configs import LLMConfig from ..models.base_model import BaseLLM +_cost_observers = ContextVar('aflow_cost_observers', default=()) + + +@dataclass(frozen=True) +class CostEvent: + """Context-local accounting event; missing pricing is never a known zero.""" + + model: str + cost: Optional[float] + pricing: str + input_tokens: int + output_tokens: int + def get_openai_model_cost() -> dict: import json from importlib.resources import files @@ -51,6 +68,7 @@ def __init__( output_cost: Optional[float] = None, cost: Optional[float] = None ): + self.pricing_known = cost is not None or input_cost is not None or output_cost is not None self.input_tokens = input_tokens self.output_tokens = output_tokens # Keep input_cost/output_cost only as temporary constructor compatibility. @@ -96,6 +114,22 @@ def add_llm_cost(self, cost: Cost, model: str): self.cost_per_model[model] += cost.cost + @contextmanager + def observe(self, observer): + """Observe this context's updates while retaining all process totals. + + Async tasks and asyncio.to_thread inherit this context. Raw threads, + external processes and providers that bypass update_cost are unsupported + accounting paths. Observers must be fast and thread-safe. The innermost + scope for this manager replaces its parent observer. + """ + active = tuple(pair for pair in _cost_observers.get() if pair[0] is not self) + token = _cost_observers.set(active + ((self, observer),)) + try: + yield + finally: + _cost_observers.reset(token) + @atomic_method def update_cost(self, cost: Cost, model: str): self.add_llm_cost(cost, model) @@ -105,6 +139,19 @@ def update_cost(self, cost: Cost, model: str): current_llm_cost = cost.cost current_total_tokens = (cost.input_tokens or 0) + (cost.output_tokens or 0) + for manager, observer in _cost_observers.get(): + if manager is self: + known = getattr(cost, 'pricing_known', False) and math.isfinite(cost.cost) and cost.cost >= 0 + event = CostEvent(model, cost.cost if known else None, + 'known' if known else 'unknown', + cost.input_tokens or 0, cost.output_tokens or 0) + try: + observer(event) + except Exception: + # Accounting observers must not change provider behavior or + # prevent process-wide totals from being recorded. + logger.warning('Context-local cost observer failed') + if not suppress_cost_logs.get(): logger.info(f"Total LLM cost: ${total_llm_cost:.3f} | Total tokens: {total_tokens} | Current LLM cost: ${current_llm_cost:.3f} | Current tokens: {current_total_tokens}") diff --git a/evoagentx/optimizers/aflow/__init__.py b/evoagentx/optimizers/aflow/__init__.py new file mode 100644 index 00000000..cae17d19 --- /dev/null +++ b/evoagentx/optimizers/aflow/__init__.py @@ -0,0 +1,7 @@ +"""Optional reliable evidence protocol for AFlow only.""" +from .types import EvaluationPlan, Observation, ReliableTrialConfig, TrialSummary +from .store import TrialStore +from .budget import AdmissionBudget + +__all__ = ['EvaluationPlan', 'Observation', 'ReliableTrialConfig', 'TrialSummary', + 'TrialStore', 'AdmissionBudget'] diff --git a/evoagentx/optimizers/aflow/budget.py b/evoagentx/optimizers/aflow/budget.py new file mode 100644 index 00000000..63458743 --- /dev/null +++ b/evoagentx/optimizers/aflow/budget.py @@ -0,0 +1,112 @@ +"""Persistent admission counters and conservative whole-operation reservations.""" + +import time +from .types import SCHEMA_VERSION, finite_score +from .store import atomic_json, read_json + + +class AdmissionBudget: + """Bound only admissions controlled by the reliable AFlow owner. + + Nested provider retries/tokens are unobserved unless the caller's upper bound + covers them. Reservations survive crashes and ambiguous completion. An elapsed + deadline never establishes that noncooperative work has terminated. + """ + + def __init__(self, store, config): + self.store = store + self.config = config + self.state = store.read_state('budget', None) + if self.state is None: + self.state = {'schema_version': SCHEMA_VERSION, 'started_at': time.time(), + 'counts': {'example': 0, 'proposal': 0, 'trial': 0}, + 'known_spent': 0.0, 'uncertain': False, 'halted': False, 'reservations': {}} + self._save() + if self.state.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported budget schema') + # Wall time makes the admission deadline survive process restarts; a + # backwards clock is treated conservatively as an expired experiment. + elapsed = time.time() - self.state['started_at'] + self._deadline = time.monotonic() + max(0, config.deadline_seconds - elapsed) if config.deadline_seconds is not None else None + if elapsed < 0: + self._deadline = time.monotonic() + + def _save(self): + """Checkpoint counters before an admitted operation can start.""" + self.store.write_state('budget', self.state) + + def remaining_time(self): + """Return remaining admission time, not a shutdown wall-clock guarantee.""" + return None if self._deadline is None else max(0.0, self._deadline - time.monotonic()) + + def check_deadline(self): + """Stop further admission when the fixed experiment deadline elapses.""" + if self._deadline is not None and time.monotonic() >= self._deadline: + raise RuntimeError('experiment admission deadline exhausted') + + def admit(self, stage, operation_id): + """Persist one attempt and cost reservation before executing user code.""" + self.check_deadline() + self.store.assert_resolved() + if self.state['halted']: + raise RuntimeError('supported pre-call cost bound violated; admission halted') + limits = {'example': self.config.max_example_attempts, 'proposal': self.config.max_proposals, + 'trial': self.config.max_trials} + if stage not in limits: + raise ValueError('invalid admission stage') + import re + if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', operation_id): + raise ValueError('invalid admission ID') + admission_path = self.store.path / 'admissions' / f'{operation_id}.json' + if admission_path.exists() or operation_id in self.state['reservations']: + raise ValueError('operation admission ID already used') + if self.state['counts'][stage] >= limits[stage]: + raise RuntimeError(f'{stage} attempt admission budget exhausted') + bound = getattr(self.config, f'{stage}_cost_bound', None) or 0.0 + reserved = sum(value['reserved'] for value in self.state['reservations'].values()) + if self.config.max_known_cost is not None and self.state['known_spent'] + reserved + bound > self.config.max_known_cost + 1e-12: + raise RuntimeError('known cost admission budget exhausted') + reservation = {'stage': stage, 'reserved': bound, 'status': 'admitted'} + self.state['counts'][stage] += 1 + self.state['reservations'][operation_id] = reservation + self._save() + atomic_json(admission_path, reservation) + return dict(reservation) + + def finish(self, operation_id, known_cost, pricing_known, terminated=True): + """Release only a terminated reservation; retain conservative unknown cost.""" + known_cost = finite_score(known_cost) + if known_cost < 0: + raise ValueError('negative observed cost') + reservation = self.state['reservations'].get(operation_id) + if reservation is None: + raise ValueError('operation has no admission reservation') + if reservation['status'] != 'admitted': + raise ValueError('operation reservation already finalized') + bound = reservation['reserved'] + if self.config.max_known_cost is not None and known_cost > bound + 1e-12: + self.state['uncertain'] = True + self.state['halted'] = True + reservation['status'] = 'bound_violation' + self._save() + raise RuntimeError('supported pre-call cost bound violated; admission halted') + self.state['known_spent'] += known_cost + if not pricing_known: + self.state['uncertain'] = True + # A supplied upper bound remains reserved for unknown pricing, even if + # execution terminated; absent observer events never prove zero dollars. + reservation['reserved'] = 0.0 if terminated and pricing_known else max(0, bound - known_cost) + reservation['status'] = 'finished' if terminated else 'unknown' + atomic_json(self.store.path / 'admissions' / f'{operation_id}.json', reservation) + if reservation['reserved'] == 0 and terminated: + self.state['reservations'].pop(operation_id) + self._save() + + def report(self): + """Expose actual supported bounds and unobserved provider-internal usage.""" + return {'counts': dict(self.state['counts']), 'known_spent': self.state['known_spent'], + 'reserved': sum(r['reserved'] for r in self.state['reservations'].values()), + 'pricing_uncertain': self.state['uncertain'], + 'deadline_is_admission_only': True, 'provider_internal_attempts': 'unobserved', + 'hard_cost_bound': self.config.max_known_cost is not None, + 'tokens_hard_bounded': False} diff --git a/evoagentx/optimizers/aflow/evaluator.py b/evoagentx/optimizers/aflow/evaluator.py new file mode 100644 index 00000000..f803f738 --- /dev/null +++ b/evoagentx/optimizers/aflow/evaluator.py @@ -0,0 +1,171 @@ +"""Bounded detailed evaluation through the existing AFlow benchmark contract.""" + +import asyncio +import time + +from ...models.model_utils import cost_manager +from .evidence import CostLedger +from .types import Observation, TrialSummary, finite_score + + +async def join_owned(tasks): + """Drain owned async work despite repeated cancellation of its owner. + + This joins asyncio tasks only. Cancellation of a to_thread awaiter does not + prove that its thread or a remote operation stopped; that evidence stays unknown. + """ + waiter = asyncio.gather(*tasks, return_exceptions=True) + while not waiter.done(): + try: + await asyncio.shield(waiter) + except asyncio.CancelledError: + continue + return waiter.result() + + +async def owned_call(operation, timeout): + """Run one operation and distinguish completed errors from ambiguous timeout.""" + task = asyncio.create_task(operation()) + try: + done, _ = await asyncio.wait({task}, timeout=timeout) + if not done: + task.cancel() + await join_owned([task]) + return 'unknown', None + try: + return 'completed', task.result() + except asyncio.CancelledError: + return 'unknown', None + except Exception as exc: + return 'error', exc + except asyncio.CancelledError: + task.cancel() + await join_owned([task]) + raise + + +class DetailedEvaluator: + """Capture exact typed per-example evidence without changing Benchmark APIs.""" + + def __init__(self, llm): + self.llm = llm + + @staticmethod + def _timeout(plan, budget): + """Use the shorter cooperative attempt/deadline cancellation request.""" + values = [v for v in (plan.config.attempt_timeout, budget.remaining_time()) if v is not None] + return min(values) if values else None + + @staticmethod + def _retryable(error, config): + """Classify explicit configured exception types after the task has terminated.""" + names = {f'{cls.__module__}.{cls.__qualname__}' for cls in type(error).__mro__} + return bool(names.intersection(config.retryable_errors)) + + async def _attempt(self, benchmark, graph, example, identity, replicate, attempt, + plan, trial_id, store, budget): + """Own admission, intent checkpoint, call, cost snapshot and result commit.""" + obs_id = Observation.make(trial_id, identity, replicate, attempt, 'unknown').observation_id + budget.admit('example', obs_id) + store.start_attempt(trial_id, identity, replicate, attempt) + ledger = CostLedger() + started = time.monotonic() + try: + with cost_manager.observe(ledger.observe): + state, value = await owned_call(lambda: benchmark.async_evaluate(graph, example), self._timeout(plan, budget)) + except asyncio.CancelledError: + costs = ledger.close() + obs = Observation.make(trial_id, identity, replicate, attempt, 'cancelled', + duration=time.monotonic() - started, **costs) + store.record(obs) + store.mark_stopping() + budget.finish(obs_id, costs['known_cost'], costs['pricing'] == 'known', terminated=False) + raise + costs = ledger.close() + duration = time.monotonic() - started + if state == 'unknown': + obs = Observation.make(trial_id, identity, replicate, attempt, 'unknown', + error_type='AmbiguousTimeoutOrCancellation', duration=duration, **costs) + store.record(obs) + store.mark_stopping() + budget.finish(obs_id, costs['known_cost'], costs['pricing'] == 'known', terminated=False) + return obs + if state == 'error': + status = 'retryable' if self._retryable(value, plan.config) else 'inconclusive' + error_type = f'{type(value).__module__}.{type(value).__qualname__}' + obs = Observation.make(trial_id, identity, replicate, attempt, status, + error_type=error_type, duration=duration, **costs) + else: + try: + score = finite_score(value) + except ValueError: + obs = Observation.make(trial_id, identity, replicate, attempt, 'inconclusive', + error_type='InvalidMetric', duration=duration, **costs) + else: + obs = Observation.scored(trial_id, identity, replicate, attempt, score, + duration=duration, **costs) + store.record(obs) + budget.finish(obs_id, costs['known_cost'], costs['pricing'] == 'known') + return obs + + async def evaluate(self, benchmark, graph, data, plan, trial_id, store, budget): + """Resume completed coordinates and commit one complete or incomplete summary.""" + plan.verify_data(data) + existing = store.summary(trial_id) + if existing is not None: + return existing + store.assert_resolved() + configured = graph(name=benchmark.name, llm_config=self.llm.config if self.llm is not None else None, + benchmark=benchmark) + latest = {} + for obs in store.observations(trial_id): + key = (obs.example_key, obs.replicate) + if key not in latest or obs.attempt > latest[key].attempt: + latest[key] = obs + coordinates = iter((identity, replicate) for replicate in range(plan.config.replicates) + for identity in plan.examples) + stop_reason = [] + + async def worker(): + for identity, replicate in coordinates: + if stop_reason: + return + previous = latest.get((identity.key, replicate)) + if previous is not None: + if previous.status == 'scored' or previous.status == 'inconclusive': + continue + if previous.status in ('unknown', 'cancelled'): + resolution = store.operation(previous.observation_id) + if not resolution or resolution.get('resolution') != 'rerun': + continue + start = previous.attempt + 1 + else: + start = 1 + for attempt in range(start, plan.config.attempts_per_example + 1): + try: + observation = await self._attempt(benchmark, configured, data[identity.index], identity, + replicate, attempt, plan, trial_id, store, budget) + except RuntimeError as exc: + stop_reason.append(str(exc)) + return + if observation.status in ('unknown', 'cancelled'): + stop_reason.append('unknown external execution requires explicit resolution') + return + if observation.status != 'retryable': + break + + tasks = [asyncio.create_task(worker()) for _ in range(min(plan.config.concurrency, plan.requested))] + try: + await asyncio.gather(*tasks) + except BaseException: + for task in tasks: + task.cancel() + await join_owned(tasks) + raise + store.assert_resolved() + trial = store.trial(trial_id) + summary = TrialSummary.build(plan, trial_id, trial['round'], store.observations(trial_id)) + store.commit_summary(summary) + if stop_reason: + store.write_state('last_evaluation_stop', {'trial_id': trial_id, 'reason': stop_reason[0]}) + return summary diff --git a/evoagentx/optimizers/aflow/evidence.py b/evoagentx/optimizers/aflow/evidence.py new file mode 100644 index 00000000..0ac764fd --- /dev/null +++ b/evoagentx/optimizers/aflow/evidence.py @@ -0,0 +1,155 @@ +"""Shared consumers of committed AFlow summaries and context-local costs.""" + +import threading +from dataclasses import dataclass + +from .store import atomic_json + + +class CostLedger: + """Accumulate bounded context-local accounting, including supported threads.""" + + def __init__(self): + self._lock = threading.Lock() + self._cost = 0.0 + self._events = 0 + self._unknown = False + self._input = 0 + self._output = 0 + self._closed = False + self._late_events = 0 + + def observe(self, event): + """Accept provider events without performing disk writes from workers.""" + with self._lock: + if self._closed: + self._late_events += 1 + return + self._events += 1 + self._unknown |= event.pricing != 'known' + self._cost += event.cost or 0.0 + self._input += event.input_tokens + self._output += event.output_tokens + + def close(self): + """Freeze a snapshot; late accounting cannot mutate committed evidence.""" + with self._lock: + self._closed = True + return {'known_cost': self._cost, + 'pricing': 'unknown' if self._unknown else ('known' if self._events else 'unobserved'), + 'input_tokens': self._input, 'output_tokens': self._output} + + @property + def late_events(self): + """Expose ignored late events for diagnostics; global totals still include them.""" + with self._lock: + return self._late_events + + +@dataclass(frozen=True) +class EvolutionResult: + """Truthful terminal status, selected summary and controlled budget report.""" + + status: str + reason: str + best_trial_id: str | None + best_round: int | None + score: float | None + committed_trials: int + budget: dict + export_error: str | None = None + + +class EvidenceView: + """Use exactly one committed score for selection, feedback and convergence.""" + + def __init__(self, store): + self.store = store + self.config = store.plan.config + + def comparable(self): + """Select complete validation trials from the exact fixed experiment plan.""" + return [s for s in self.store.summaries() if s.eligible and s.split == 'validation' + and s.plan_id == self.store.plan.identity] + + def ranked(self): + """Rank eligible summaries stably, retaining earlier trials on ties.""" + reverse = self.config.direction == 'maximize' + return sorted(self.comparable(), key=lambda s: s.score, reverse=reverse) + + def best(self): + """Apply the explicit improvement margin in actual trial order.""" + parent = None + for summary in self.comparable(): + if parent is None or summary.improves(parent, self.config): + parent = summary + return parent + + def feedback(self): + """Distinguish task evidence from infrastructure without strategy prohibitions.""" + feedback = [] + for summary in self.store.summaries(): + trial = self.store.trial(summary.trial_id) + if trial['kind'] != 'candidate' or summary.split != 'validation': + continue + parent = self.store.summary(trial['parent_id']) + accepted = summary.improves(parent, self.config) if parent is not None else False + feedback.append({'trial_id': summary.trial_id, 'parent_id': trial['parent_id'], + 'modification': trial['modification'], + 'evidence': ('accepted' if accepted else 'rejected') if summary.eligible else 'inconclusive', + 'before': parent.score if parent is not None else None, + 'after': summary.score, 'requested': summary.requested, + 'scored': summary.scored, 'outcomes': summary.outcomes}) + return feedback + + def prompt_feedback(self, parent_id): + """Present measured task results separately from infrastructure diagnostics.""" + rows = [r for r in self.feedback() if r['parent_id'] == parent_id] + if not rows: + return 'No completed candidate evidence for this parent.' + lines = [] + for row in rows: + if row['evidence'] == 'inconclusive': + lines.append(f"Infrastructure/incomplete evidence for {row['trial_id']}; no task-strategy conclusion.") + else: + lines.append(f"{row['evidence'].capitalize()} task evidence: {row['modification']} (score {row['after']}).") + return '\n'.join(lines) + + def converged(self): + """Count only comparable committed trials since the last strict improvement.""" + parent = None + unchanged = 0 + for summary in self.comparable(): + if parent is None or summary.improves(parent, self.config): + parent = summary + unchanged = 0 + else: + unchanged += 1 + return unchanged >= self.config.convergence_patience + + def export(self, root_path): + """Repair legacy-shaped exports from authoritative evidence, idempotently. + + Export failure is diagnostic only: a committed summary remains committed. + Inconclusive candidates are excluded from legacy failure experience. + """ + from pathlib import Path + root = Path(root_path) + rows = [] + for summary in self.comparable(): + rows.append({'round': summary.round, 'score': summary.score, + 'avg_cost': summary.known_cost / summary.requested, + 'total_cost': summary.known_cost, 'time': '', + 'trial_id': summary.trial_id, 'split': summary.split, + 'pricing': summary.pricing, 'plan_id': summary.plan_id}) + atomic_json(root / 'results.json', rows) + for row in self.feedback(): + summary = self.store.summary(row['trial_id']) + atomic_json(root / f'round_{summary.round}' / 'trial_feedback.json', row) + if row['evidence'] != 'inconclusive': + parent = self.store.summary(row['parent_id']) + atomic_json(root / f'round_{summary.round}' / 'experience.json', + {'father node': parent.round, 'modification': row['modification'], + 'before': row['before'], 'after': row['after'], + 'succeed': row['evidence'] == 'accepted'}) + atomic_json(self.store.path / 'feedback.json', self.feedback()) diff --git a/evoagentx/optimizers/aflow/store.py b/evoagentx/optimizers/aflow/store.py new file mode 100644 index 00000000..febc0e13 --- /dev/null +++ b/evoagentx/optimizers/aflow/store.py @@ -0,0 +1,393 @@ +"""Single-writer local checkpoints with atomic, versioned evidence publication. + +The lock and rename protocol targets a local filesystem. It does not provide +multi-host/NFS coordination, a security sandbox, or exactly-once provider calls. +""" + +import contextlib +import json +import os +import re +import shutil +import socket +import tempfile +import time +import uuid +from pathlib import Path + +from .types import SCHEMA_VERSION, Observation, TrialSummary, canonical, digest + + +def atomic_json(path, value): + """Publish complete JSON and fsync the parent directory on local filesystems.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + content = canonical(value) + fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + sync_directory(path.parent) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(temporary) + + +def sync_directory(path): + """Persist a renamed directory entry where the platform supports it.""" + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def read_json(path): + """Read strict versioned JSON; corrupted checkpoints fail closed.""" + def reject_constant(value): + raise ValueError(f'nonfinite JSON constant: {value}') + with open(path, encoding='utf-8') as stream: + return json.load(stream, parse_constant=reject_constant) + + +class TrialStore: + """Own one reliable experiment and its immutable evidence files. + + Args: + path: Dedicated local reliable experiment directory. + plan: Exact immutable evaluation plan used for every validation trial. + """ + + def __init__(self, path, plan): + self.path = Path(path) + self.plan = plan + self._lock_file = None + self._owner_token = uuid.uuid4().hex + self._unclean = False + self._active_operations = set() + self._pending_operations = {} + + def __enter__(self): + """Acquire an OS-held writer lock before reading or mutating checkpoints.""" + try: + import fcntl + except ImportError as exc: + raise RuntimeError('reliable mode requires a supported local fcntl writer lock') from exc + self.path.mkdir(parents=True, exist_ok=True) + self._lock_file = open(self.path / 'writer.lock', 'a+', encoding='utf-8') + try: + try: + fcntl.flock(self._lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise RuntimeError('another writer owns this reliable experiment') from exc + owner_file = self.path / 'owner.json' + old_owner = read_json(owner_file) if owner_file.exists() else None + if old_owner and old_owner.get('status') in ('running', 'stopping'): + if not self.plan.config.recover_owner: + raise RuntimeError('unclean writer requires explicit recover_owner acknowledgement') + # Even after flock is released, a live previous process may own + # noncooperative thread/provider work. Never infer its termination. + if old_owner.get('host') != socket.gethostname() or self._pid_alive(old_owner.get('pid')): + raise RuntimeError('previous writer may still be running; explicit termination is required') + self._append_audit('recover_owner', previous=old_owner) + plan_file = self.path / 'plan.json' + if plan_file.exists(): + existing = read_json(plan_file) + if existing.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported plan schema') + if canonical(existing) != canonical(self.plan.to_dict()): + raise ValueError('experiment plan identity mismatch; use a new experiment directory') + else: + # A legacy result file supplies no coverage/split provenance. + if (self.path / 'results.json').exists(): + raise ValueError('legacy results cannot be imported as reliable evidence') + atomic_json(plan_file, self.plan.to_dict()) + atomic_json(owner_file, self._owner('running')) + for path in (self.path / 'attempts').glob('*.json'): + operation = read_json(path) + if operation['status'] in ('started', 'unknown', 'cancelled'): + self._pending_operations[operation['attempt_id']] = operation + return self + except BaseException: + self._release() + raise + + @staticmethod + def _pid_alive(pid): + """Conservatively reject recovery while a previous local process exists.""" + if not isinstance(pid, int) or pid < 1: + return True + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + return True + + def _owner(self, status): + """Build owner metadata without credentials or provider messages.""" + return {'schema_version': SCHEMA_VERSION, 'pid': os.getpid(), + 'host': socket.gethostname(), 'token': self._owner_token, + 'status': status, 'updated_at': time.time()} + + def _require_owner(self): + """Reject accidental writes outside the owning context.""" + if self._lock_file is None: + raise RuntimeError('writer context is not active') + + def mark_stopping(self): + """Retain an unclean owner when cancellation cannot prove termination.""" + self._require_owner() + self._unclean = True + atomic_json(self.path / 'owner.json', self._owner('stopping')) + + def __exit__(self, exc_type, exc, tb): + """Release the lock without erasing unknown external execution evidence.""" + try: + if self._lock_file is not None: + atomic_json(self.path / 'owner.json', self._owner('stopping' if self._unclean else 'closed')) + finally: + self._release() + + def _release(self): + """Close the OS lock descriptor, including on failed initialization.""" + if self._lock_file is not None: + self._lock_file.close() + self._lock_file = None + + def _trial_path(self, trial_id): + """Constrain all durable IDs to a single local path component.""" + if not isinstance(trial_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', trial_id): + raise ValueError('invalid trial ID') + return self.path / 'trials' / trial_id + + def create_trial(self, trial_id, round_number, kind, parent_id=None, modification=''): + """Create an idempotent stable trial record before staging or execution.""" + self._require_owner() + if kind not in ('baseline', 'candidate', 'test') or round_number < 0: + raise ValueError('invalid trial kind or round') + path = self._trial_path(trial_id) / 'trial.json' + value = {'schema_version': SCHEMA_VERSION, 'trial_id': trial_id, 'round': round_number, + 'kind': kind, 'parent_id': parent_id, 'modification': modification, + 'plan_id': self.plan.identity} + if path.exists(): + if canonical(read_json(path)) != canonical(value): + raise ValueError('trial identity conflict') + else: + atomic_json(path, value) + return value + + def trials(self): + """Read trials in actual monotonic round/creation order.""" + return sorted((read_json(p) for p in (self.path / 'trials').glob('*/trial.json')), + key=lambda t: (t['round'], t['trial_id'])) + + def trial(self, trial_id): + """Read one stable trial identity.""" + return read_json(self._trial_path(trial_id) / 'trial.json') + + def stage_artifacts(self, trial_id, graph, prompt): + """Publish graph and prompt together as one immutable artifact generation.""" + self._require_owner() + trial_path = self._trial_path(trial_id) + self.trial(trial_id) + artifact_digest = digest({'graph': graph, 'prompt': prompt}) + directory = trial_path / 'artifacts' + manifest = {'schema_version': SCHEMA_VERSION, 'digest': artifact_digest, + 'directory': str(directory.relative_to(self.path)), + 'graph_digest': digest(graph), 'prompt_digest': digest(prompt)} + if directory.exists(): + if read_json(directory / 'manifest.json') != manifest: + raise ValueError('artifact generation is immutable') + self.read_artifacts(trial_id) + return manifest + temporary = Path(tempfile.mkdtemp(prefix='.generation-', dir=trial_path)) + try: + for name, content in (('graph.py', graph), ('prompt.py', prompt)): + with open(temporary / name, 'w', encoding='utf-8') as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + atomic_json(temporary / 'manifest.json', manifest) + sync_directory(temporary) + os.rename(temporary, directory) + sync_directory(trial_path) + finally: + if temporary.exists(): + shutil.rmtree(temporary) + return manifest + + def read_artifacts(self, trial_id): + """Verify exact generation content before loading trusted user code.""" + directory = self._trial_path(trial_id) / 'artifacts' + manifest = read_json(directory / 'manifest.json') + if manifest.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported artifact schema') + graph = (directory / 'graph.py').read_text(encoding='utf-8') + prompt = (directory / 'prompt.py').read_text(encoding='utf-8') + if manifest['digest'] != digest({'graph': graph, 'prompt': prompt}): + raise ValueError('artifact digest mismatch') + return graph, prompt, manifest + + def start_attempt(self, trial_id, example, replicate, attempt): + """Checkpoint intent before a possibly effectful external example call.""" + observation_id = digest([trial_id, example.key, replicate, attempt]) + return self.begin_operation(observation_id, 'example', trial_id, + example_key=example.key, replicate=replicate, attempt=attempt) + + def begin_operation(self, attempt_id, stage, trial_id, **coordinates): + """Persist a proposal/example intent; missing completion means unknown.""" + self._require_owner() + self._trial_path(trial_id) + if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', attempt_id): + raise ValueError('invalid attempt ID') + value = {'schema_version': SCHEMA_VERSION, 'attempt_id': attempt_id, 'stage': stage, + 'trial_id': trial_id, 'status': 'started', **coordinates} + path = self.path / 'attempts' / f'{attempt_id}.json' + if path.exists(): + raise ValueError('attempt already exists; never replay an external call ID') + atomic_json(path, value) + self._pending_operations[attempt_id] = value + self._active_operations.add(attempt_id) + return value + + def finish_operation(self, attempt_id, status, **metadata): + """Record operation completion without overwriting immutable observations.""" + self._require_owner() + path = self.path / 'attempts' / f'{attempt_id}.json' + operation = read_json(path) + if operation['status'] != 'started': + if operation['status'] == status and all(operation.get(k) == v for k, v in metadata.items()): + return + raise ValueError('operation completion conflict') + operation.update(status=status, **metadata) + atomic_json(path, operation) + self._active_operations.discard(attempt_id) + if status in ('unknown', 'cancelled'): + self._pending_operations[attempt_id] = operation + else: + self._pending_operations.pop(attempt_id, None) + + def record(self, observation): + """Commit an immutable result before it can be consumed by selection.""" + self._require_owner() + self.trial(observation.trial_id) + allowed = {e.key: e for e in self.plan.examples} + example = allowed.get(observation.example_key) + if example is None or observation.replicate >= self.plan.config.replicates: + raise ValueError('observation outside fixed plan') + expected = digest([observation.trial_id, example.key, observation.replicate, observation.attempt]) + if observation.observation_id != expected or observation.example_id != example.original_id or observation.occurrence != example.occurrence: + raise ValueError('observation identity conflict') + path = self._trial_path(observation.trial_id) / 'observations' / f'{observation.observation_id}.json' + value = observation.to_dict() + if path.exists(): + if canonical(read_json(path)) != canonical(value): + raise ValueError('observation payload conflict') + return + if (self._trial_path(observation.trial_id) / 'summary.json').exists(): + raise ValueError('committed trial evidence is immutable') + atomic_json(path, value) + operation = self.path / 'attempts' / f'{observation.observation_id}.json' + if operation.exists(): + self.finish_operation(observation.observation_id, observation.status) + + def observations(self, trial_id): + """Read immutable outcomes in deterministic replicate/example order.""" + values = [Observation(**read_json(p)) for p in (self._trial_path(trial_id) / 'observations').glob('*.json')] + return sorted(values, key=lambda o: (o.replicate, o.example_key, o.attempt)) + + def unknown_attempts(self): + """Find ambiguous calls, including a crash between result and intent updates.""" + result = [] + for operation in self._pending_operations.values(): + if operation['attempt_id'] in self._active_operations: + continue + if operation['status'] not in ('started', 'unknown', 'cancelled'): + continue + observation_path = self._trial_path(operation['trial_id']) / 'observations' / f"{operation['attempt_id']}.json" + if observation_path.exists() and read_json(observation_path)['status'] not in ('unknown', 'cancelled'): + continue + result.append(operation) + return result + + def assert_resolved(self): + """Block admission whenever an earlier external call may still have effects.""" + if self.unknown_attempts(): + raise RuntimeError('unknown external attempts require explicit resolution; no automatic retry') + + def resolve_unknown(self, attempt_id, action, note): + """Audit an operator's confirmation of termination and replay decision. + + This API is an explicit operator assertion that the previous operation has + stopped. It cannot terminate remote requests or Python threads itself. + A rerun receives a new ID; completed scored results are never discarded. + """ + self._require_owner() + if action not in ('rerun', 'abandon') or not note or not note.strip(): + raise ValueError('resolution needs rerun/abandon and an operator note') + operations = {o['attempt_id']: o for o in self.unknown_attempts()} + if attempt_id not in operations: + raise ValueError('attempt is not unknown') + value = operations[attempt_id] + value.update(status='resolved', resolution=action) + self._append_audit('resolve_unknown', attempt_id=attempt_id, resolution=action, note=note) + atomic_json(self.path / 'attempts' / f'{attempt_id}.json', value) + self._pending_operations.pop(attempt_id, None) + + def operation(self, attempt_id): + """Read an attempt's explicit recovery decision.""" + path = self.path / 'attempts' / f'{attempt_id}.json' + return read_json(path) if path.exists() else None + + def commit_summary(self, summary): + """Atomically publish authoritative evidence after verifying durable coverage.""" + self._require_owner() + if summary.plan_id != self.plan.identity: + raise ValueError('summary plan identity mismatch') + actual = TrialSummary.build(self.plan, summary.trial_id, summary.round, + self.observations(summary.trial_id)) + if actual != summary: + raise ValueError('summary does not match durable observations') + path = self._trial_path(summary.trial_id) / 'summary.json' + if path.exists() and canonical(read_json(path)) != canonical(summary.to_dict()): + raise ValueError('summary conflict') + atomic_json(path, summary.to_dict()) + + def summary(self, trial_id): + """Read one published summary without using diagnostic export rows.""" + path = self._trial_path(trial_id) / 'summary.json' + return TrialSummary.from_dict(read_json(path)) if path.exists() else None + + def summaries(self): + """Return only committed summaries in actual trial order.""" + return [summary for trial in self.trials() if (summary := self.summary(trial['trial_id'])) is not None] + + def read_state(self, name, default=None): + """Read owner-maintained stage/budget state independently of exports.""" + if not re.fullmatch(r'[a-z_]+', name): + raise ValueError('invalid state name') + path = self.path / f'{name}.json' + return read_json(path) if path.exists() else default + + def write_state(self, name, value): + """Publish owner-maintained state with the same local atomic protocol.""" + self._require_owner() + if not re.fullmatch(r'[a-z_]+', name): + raise ValueError('invalid state name') + atomic_json(self.path / f'{name}.json', value) + + def _append_audit(self, action, **details): + """Append a rare recovery event atomically; normal observations are separate.""" + path = self.path / 'audit.json' + values = read_json(path) if path.exists() else [] + values.append({'action': action, 'at': time.time(), **details}) + atomic_json(path, values) + + def audit(self): + """Read explicit recovery history for operator inspection.""" + return self.read_state('audit', []) diff --git a/evoagentx/optimizers/aflow/types.py b/evoagentx/optimizers/aflow/types.py new file mode 100644 index 00000000..fd4713f9 --- /dev/null +++ b/evoagentx/optimizers/aflow/types.py @@ -0,0 +1,320 @@ +"""Immutable identities and evidence for opt-in AFlow experiments.""" + +import hashlib +import json +import math +import re +from collections import Counter +from dataclasses import asdict, dataclass, field +from typing import Any, Optional +from urllib.parse import urlsplit, urlunsplit + +SCHEMA_VERSION = 1 +_SECRET = re.compile(r'key|secret|password|token|authorization|credential', re.I) + + +def canonical(value: Any) -> str: + """Encode exact JSON data without accepting nonfinite or opaque values.""" + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False) + + +def digest(value: Any) -> str: + """Hash exact canonical content for identity, not semantic equivalence.""" + return hashlib.sha256(canonical(value).encode('utf-8')).hexdigest() + + +def public_model_config(value: Any) -> Any: + """Remove credentials and endpoint credentials before identity persistence.""" + if hasattr(value, 'model_dump'): + value = value.model_dump(mode='json') + if isinstance(value, dict): + result = {} + for key, item in value.items(): + # Generation limits are behavior, whereas authentication tokens are secrets. + if _SECRET.search(str(key)) and str(key) not in ('max_tokens', 'max_completion_tokens'): + continue + if str(key) in ('base_url', 'api_base', 'endpoint') and isinstance(item, str): + url = urlsplit(item) + item = urlunsplit((url.scheme, url.hostname or '', url.path, '', '')) + result[str(key)] = public_model_config(item) + return result + if isinstance(value, (list, tuple)): + return [public_model_config(item) for item in value] + canonical(value) + return value + + +def finite_score(value: Any) -> float: + """Require a numeric finite scalar rather than coercing error values.""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + # Numpy scalar metrics expose item(), but arrays are deliberately rejected. + if hasattr(value, 'shape') and value.shape == () and hasattr(value, 'item'): + value = value.item() + else: + raise ValueError('metric must be a finite numeric scalar') + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError('metric must be a finite numeric scalar') + return float(value) + + +@dataclass(frozen=True) +class ReliableTrialConfig: + """Fixed experiment policy; limits cover owned admissions, not provider internals. + + Cost bounds are a caller-supplied pre-call upper-bound contract covering the + entire graph/proposal operation, including any internal retries. Without that + contract max_known_cost is rejected. A deadline requests cancellation but + cannot establish termination of arbitrary code or threads. + """ + + experiment_id: str = 'aflow' + direction: str = 'maximize' + improvement_margin: float = 0.0 + replicates: int = 1 + concurrency: int = 20 + attempts_per_example: int = 2 + max_example_attempts: int = 1000000 + max_proposals: int = 60 + max_trials: int = 21 + duplicate_limit: int = 10 + deadline_seconds: Optional[float] = None + attempt_timeout: Optional[float] = None + proposal_timeout: Optional[float] = None + max_known_cost: Optional[float] = None + example_cost_bound: Optional[float] = None + proposal_cost_bound: Optional[float] = None + retryable_errors: tuple = ('builtins.TimeoutError', 'builtins.ConnectionError') + convergence_patience: int = 5 + metric_id: Optional[str] = None + recover_owner: bool = False + + def __post_init__(self): + """Reject ambiguous budgets before any external work can be admitted.""" + if not re.fullmatch(r'[A-Za-z0-9_-]{1,80}', self.experiment_id): + raise ValueError('experiment_id must be a local filename-safe identifier') + if self.direction not in ('maximize', 'minimize'): + raise ValueError('direction must be maximize or minimize') + if finite_score(self.improvement_margin) < 0: + raise ValueError('improvement_margin must be nonnegative') + for name in ('replicates', 'concurrency', 'attempts_per_example', 'max_example_attempts', + 'max_proposals', 'max_trials', 'duplicate_limit', 'convergence_patience'): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f'{name} must be a positive integer') + for name in ('deadline_seconds', 'attempt_timeout', 'proposal_timeout', 'max_known_cost', + 'example_cost_bound', 'proposal_cost_bound'): + value = getattr(self, name) + if value is not None and finite_score(value) <= 0: + raise ValueError(f'{name} must be finite and positive') + if self.max_known_cost is not None and (self.example_cost_bound is None or self.proposal_cost_bound is None): + raise ValueError('cost admission requires example and proposal pre-call upper bounds') + if not all(isinstance(name, str) and '.' in name for name in self.retryable_errors): + raise ValueError('retryable_errors must contain qualified exception names') + object.__setattr__(self, 'retryable_errors', tuple(self.retryable_errors)) + + def identity_dict(self) -> dict: + """Exclude operational owner recovery from the immutable execution plan.""" + value = asdict(self) + value.pop('recover_owner') + return value + + +@dataclass(frozen=True) +class ExampleIdentity: + """An ordered example occurrence, retaining its benchmark identifier.""" + + index: int + original_id: Any + occurrence: int + content_digest: str + + @property + def key(self) -> str: + """Return an unambiguous position key even for duplicate dataset IDs.""" + return f'{self.index}:{self.occurrence}:{self.content_digest}' + + +@dataclass(frozen=True) +class EvaluationPlan: + """Complete immutable split coverage and behavior identity.""" + + dataset: str + split: str + examples: tuple + model_config: dict + metric_id: str + config: ReliableTrialConfig + identity: str + schema_version: int = SCHEMA_VERSION + + @classmethod + def create(cls, dataset: str, data: list, model_config: Any, metric_id: str, + config: ReliableTrialConfig, split: str = 'validation'): + """Freeze exact data order and occurrence identity before evaluation.""" + if split not in ('validation', 'test'): + raise ValueError('split must be validation or test') + if not data: + raise ValueError('an evaluation plan requires nonempty data') + if not metric_id or not dataset: + raise ValueError('dataset and metric identity are required') + seen = Counter() + examples = [] + for index, example in enumerate(data): + original_id = example.get('_id', example.get('id', example.get('task_id', index))) if isinstance(example, dict) else index + key = canonical(original_id) + examples.append(ExampleIdentity(index, original_id, seen[key], digest(example))) + seen[key] += 1 + model = public_model_config(model_config) + identity = digest({'schema': SCHEMA_VERSION, 'dataset': dataset, 'split': split, + 'examples': [asdict(e) for e in examples], 'model': model, + 'metric': metric_id, 'policy': config.identity_dict()}) + return cls(dataset, split, tuple(examples), model, metric_id, config, identity) + + def to_dict(self) -> dict: + """Return the versioned durable plan without raw example contents.""" + value = asdict(self) + value['config'] = self.config.identity_dict() + return value + + def verify_data(self, data: list): + """Reject mutated/reordered examples before any new attempt is admitted.""" + if len(data) != len(self.examples) or any(digest(d) != e.content_digest for d, e in zip(data, self.examples)): + raise ValueError('evaluation data identity changed') + + @property + def requested(self) -> int: + """Return the exact fixed replicate/example denominator.""" + return len(self.examples) * self.config.replicates + + +@dataclass(frozen=True) +class Observation: + """Immutable outcome of one owned example attempt; never an inferred zero.""" + + observation_id: str + trial_id: str + example_key: str + example_id: Any + occurrence: int + replicate: int + attempt: int + status: str + score: Optional[float] = None + error_type: Optional[str] = None + known_cost: float = 0.0 + pricing: str = 'unobserved' + input_tokens: int = 0 + output_tokens: int = 0 + duration: float = 0.0 + schema_version: int = SCHEMA_VERSION + + def __post_init__(self): + """Validate durable evidence, including reloaded observations.""" + if self.status not in ('scored', 'retryable', 'inconclusive', 'unknown', 'cancelled'): + raise ValueError('invalid observation status') + if self.status == 'scored': + object.__setattr__(self, 'score', finite_score(self.score)) + elif self.score is not None: + raise ValueError('unscored observations cannot contain a task score') + if self.replicate < 0 or self.attempt < 1: + raise ValueError('invalid observation coordinates') + if finite_score(self.known_cost) < 0 or finite_score(self.duration) < 0: + raise ValueError('negative cost or duration') + if self.pricing not in ('known', 'unknown', 'unobserved'): + raise ValueError('invalid pricing status') + if self.schema_version != SCHEMA_VERSION: + raise ValueError('unsupported observation schema') + + @classmethod + def make(cls, trial_id, example, replicate, attempt, status, **kwargs): + """Build the deterministic idempotency key from attempt coordinates.""" + key = digest([trial_id, example.key, replicate, attempt]) + return cls(key, trial_id, example.key, example.original_id, example.occurrence, + replicate, attempt, status, **kwargs) + + @classmethod + def scored(cls, trial_id, example, replicate, attempt, score, **kwargs): + """Construct explicit task evidence, including valid zero scores.""" + return cls.make(trial_id, example, replicate, attempt, 'scored', score=score, **kwargs) + + def to_dict(self): + """Return the versioned observation payload.""" + return asdict(self) + + +@dataclass(frozen=True) +class TrialSummary: + """One authoritative score and diagnostic denominator for an entire trial.""" + + trial_id: str + round: int + plan_id: str + split: str + requested: int + scored: int + eligible: bool + score: Optional[float] + partial_score: Optional[float] + observation_ids: tuple + known_cost: float + pricing: str + outcomes: dict + schema_version: int = SCHEMA_VERSION + + @classmethod + def build(cls, plan, trial_id, round_number, observations): + """Require every requested coordinate and reject foreign/conflicting evidence.""" + expected = {(e.key, r) for e in plan.examples for r in range(plan.config.replicates)} + latest = {} + ids = set() + cost = 0.0 + pricing = 'known' + for obs in observations: + coordinate = (obs.example_key, obs.replicate) + if obs.trial_id != trial_id or coordinate not in expected: + raise ValueError('observation does not belong to trial plan') + if obs.observation_id in ids: + raise ValueError('duplicate observation in summary input') + ids.add(obs.observation_id) + cost += obs.known_cost + if obs.pricing != 'known': + pricing = 'unknown' + if coordinate not in latest or latest[coordinate].attempt < obs.attempt: + latest[coordinate] = obs + elif latest[coordinate].attempt == obs.attempt: + raise ValueError('conflicting attempt coordinates') + scored = [o.score for o in latest.values() if o.status == 'scored'] + complete = len(scored) == plan.requested + mean = math.fsum(scored) / len(scored) if scored else None + return cls(trial_id, round_number, plan.identity, plan.split, plan.requested, len(scored), + complete, mean if complete else None, mean, tuple(sorted(ids)), cost, + pricing, dict(Counter(o.status for o in latest.values()))) + + @classmethod + def from_dict(cls, value): + """Validate the schema and finite authoritative score when reading disk.""" + value = dict(value) + if value.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported summary schema') + value['observation_ids'] = tuple(value['observation_ids']) + result = cls(**value) + if result.eligible != (result.scored == result.requested and result.requested > 0): + raise ValueError('inconsistent summary coverage') + if result.eligible: + finite_score(result.score) + elif result.score is not None: + raise ValueError('incomplete summary has a ranking score') + return result + + def to_dict(self): + """Return the committed summary payload.""" + return asdict(self) + + def improves(self, parent, config): + """Compare only complete validation evidence under the exact same plan.""" + if not self.eligible or not parent.eligible or self.split != 'validation' or parent.split != 'validation': + return False + if self.plan_id != parent.plan_id: + raise ValueError('cannot compare different experiment plans') + difference = self.score - parent.score if config.direction == 'maximize' else parent.score - self.score + return difference > config.improvement_margin diff --git a/tests/src/optimizers/test_aflow_trials.py b/tests/src/optimizers/test_aflow_trials.py new file mode 100644 index 00000000..e769413b --- /dev/null +++ b/tests/src/optimizers/test_aflow_trials.py @@ -0,0 +1,270 @@ +"""Reliable evidence boundaries, using local disk and real cost contexts.""" +import asyncio +import json +from dataclasses import replace + +import pytest + + +def api(): + from evoagentx.optimizers.aflow import ( + EvaluationPlan, Observation, ReliableTrialConfig, TrialStore, + TrialSummary, AdmissionBudget, + ) + return EvaluationPlan, Observation, ReliableTrialConfig, TrialStore, TrialSummary, AdmissionBudget + + +def plan(data=None, **kwargs): + Plan, _, Config, *_ = api() + return Plan.create('Fixture', data or [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], + {'model': 'local', 'api_key': 'TOP_SECRET', 'temperature': 0}, + 'fixture.metric.v1', Config(**kwargs)) + + +def test_plan_preserves_duplicate_occurrences_order_and_omits_secrets(): + p = plan() + assert [e.original_id for e in p.examples] == ['same', 'same'] + assert [e.occurrence for e in p.examples] == [0, 1] + assert 'TOP_SECRET' not in json.dumps(p.to_dict()) + assert p.identity != plan([{'_id': 'same', 'answer': 'b'}, {'_id': 'same', 'answer': 'a'}]).identity + assert p.identity != plan(replicates=2).identity + + +def test_summary_requires_exact_finite_coverage(): + _, Obs, _, _, Summary, _ = api() + p = plan(replicates=2) + observations = [Obs.scored('trial', p.examples[0], 0, 1, 0.0)] + partial = Summary.build(p, 'trial', 0, observations) + assert not partial.eligible and partial.score is None + assert partial.scored == 1 and partial.requested == 4 and partial.partial_score == 0 + for replicate in range(2): + for example in p.examples: + if replicate or example.index: + observations.append(Obs.scored('trial', example, replicate, 1, 1.0)) + summary = Summary.build(p, 'trial', 0, observations) + assert summary.eligible and summary.score == .75 + with pytest.raises(ValueError): + Obs.scored('trial', p.examples[0], 0, 1, float('nan')) + + +def test_store_atomic_identity_observation_idempotence_and_owner_lock(tmp_path): + _, Obs, _, Store, Summary, _ = api() + p = plan() + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + obs = Obs.scored('trial', p.examples[0], 0, 1, 0) + store.record(obs) + store.record(obs) + assert len(store.observations('trial')) == 1 + with pytest.raises(ValueError, match='conflict'): + store.record(replace(obs, score=1)) + with pytest.raises(RuntimeError, match='writer'): + with Store(tmp_path, p): + pass + store.record(Obs.scored('trial', p.examples[1], 0, 1, 1)) + summary = Summary.build(p, 'trial', 0, store.observations('trial')) + store.commit_summary(summary) + assert store.summaries()[0].score == .5 + with pytest.raises(ValueError, match='identity'): + with Store(tmp_path, plan(replicates=2)): + pass + with Store(tmp_path, p) as store: + assert store.summaries()[0].score == .5 + + +def test_started_attempt_requires_explicit_resolution_before_rerun(tmp_path): + *_, Store, _, Budget = api() + p = plan() + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + store.start_attempt('trial', p.examples[0], 0, 1) + with Store(tmp_path, p) as store: + assert len(store.unknown_attempts()) == 1 + with pytest.raises(RuntimeError, match='unknown'): + store.assert_resolved() + attempt = store.unknown_attempts()[0] + store.resolve_unknown(attempt['attempt_id'], 'rerun', 'operator confirmed original call has terminated') + store.assert_resolved() + assert store.audit()[-1]['action'] == 'resolve_unknown' + + +def test_artifact_generation_is_immutable_and_digest_verified(tmp_path): + *_, Store, _, _ = api() + with Store(tmp_path, plan()) as store: + store.create_trial('trial', 0, 'baseline') + artifact = store.stage_artifacts('trial', 'class Workflow: pass\n', 'PROMPT = "x"\n') + assert store.read_artifacts('trial')[0] == 'class Workflow: pass\n' + with pytest.raises(ValueError, match='immutable'): + store.stage_artifacts('trial', 'different', '') + (store.path / artifact['directory'] / 'graph.py').write_text('tampered') + with pytest.raises(ValueError, match='digest'): + store.read_artifacts('trial') + + +def test_admissions_reserve_known_cost_and_do_not_reset_on_retry(tmp_path): + *_, Store, _, Budget = api() + p = plan(max_example_attempts=2, max_known_cost=.5, example_cost_bound=.3, proposal_cost_bound=.1) + with Store(tmp_path, p) as store: + budget = Budget(store, p.config) + first = budget.admit('example', 'a') + assert first['reserved'] == .3 + with pytest.raises(RuntimeError, match='cost'): + budget.admit('example', 'b') + budget.finish('a', .1, True) + budget.admit('example', 'b') + budget.finish('b', .1, True) + with pytest.raises(RuntimeError, match='attempt'): + budget.admit('example', 'c') + + +def test_context_cost_observation_isolates_siblings_and_propagates_to_thread(): + from evoagentx.models.model_utils import Cost, CostManager + manager = CostManager() + seen = [] + async def owned(): + with manager.observe(seen.append): + manager.update_cost(Cost(cost=.1), 'owned') + await asyncio.to_thread(manager.update_cost, Cost(cost=.2), 'thread') + manager.update_cost(Cost(), 'unknown') + async def unrelated(): + await asyncio.sleep(0) + manager.update_cost(Cost(cost=10), 'sibling') + async def run(): + await asyncio.gather(owned(), unrelated()) + asyncio.run(run()) + assert [event.model for event in seen] == ['owned', 'thread', 'unknown'] + assert sum(e.cost or 0 for e in seen) == pytest.approx(.3) + assert seen[-1].pricing == 'unknown' + assert manager.get_total_cost() == pytest.approx(10.3) + + +def test_finished_reservations_do_not_grow_admission_checkpoint(tmp_path): + *_, Store, _, Budget = api() + with Store(tmp_path, plan(max_example_attempts=150)) as store: + budget = Budget(store, store.plan.config) + for i in range(100): + budget.admit('example', str(i)) + budget.finish(str(i), 0, True) + assert (tmp_path / 'budget.json').stat().st_size < 1000 + with pytest.raises(ValueError, match='already'): + budget.admit('example', '0') + + +def test_bound_violation_halts_later_admission(tmp_path): + *_, Store, _, Budget = api() + with Store(tmp_path, plan(max_known_cost=1, example_cost_bound=.1, proposal_cost_bound=.1)) as store: + budget = Budget(store, store.plan.config) + budget.admit('example', 'a') + with pytest.raises(RuntimeError, match='violated'): + budget.finish('a', .2, True) + with pytest.raises(RuntimeError, match='violated'): + budget.admit('example', 'b') + + +def test_detailed_evaluator_preserves_zero_retries_and_exact_partial_resume(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + _, Obs, _, Store, _, Budget = api() + p = plan(replicates=2, concurrency=2) + data = [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}] + calls = [] + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + calls.append(example['answer']) + if example['answer'] == 'b' and calls.count('b') == 1: + raise TimeoutError('local provider boundary') + return 0 if example['answer'] == 'a' else 1 + class Graph: + def __init__(self, name, llm_config, benchmark): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + store.record(Obs.scored('trial', p.examples[0], 0, 1, 0)) + summary = asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, data, p, 'trial', store, Budget(store, p.config))) + assert summary.eligible and summary.score == .5 + assert calls.count('a') == 1 and calls.count('b') == 3 + assert len(store.observations('trial')) == 5 + assert store.summary('trial') == summary + + +def test_unknown_metric_error_is_inconclusive_and_not_retried(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan() + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + return float('inf') if example['answer'] == 'a' else 0 + class Graph: + def __init__(self, **kwargs): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + summary = asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + assert not summary.eligible and summary.score is None and summary.scored == 1 + assert summary.partial_score == 0 + assert summary.outcomes == {'inconclusive': 1, 'scored': 1} + assert len(store.observations('trial')) == 2 + + +def test_deadline_cancels_owned_work_and_never_promotes_late_completion(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan(attempt_timeout=.01, concurrency=1) + drained = [] + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + try: + await asyncio.sleep(10) + finally: + drained.append(example['answer']) + class Graph: + def __init__(self, **kwargs): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + with pytest.raises(RuntimeError, match='unknown'): + asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + assert drained == ['a'] + assert store.summary('trial') is None + assert store.observations('trial')[0].status == 'unknown' + assert len(store.unknown_attempts()) == 1 + with pytest.raises(RuntimeError, match='recover_owner'): + with Store(tmp_path, p): + pass + + +def test_outer_cancellation_joins_workers_and_records_unknown(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan(concurrency=1) + entered = asyncio.Event() + drained = [] + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + entered.set() + try: + await asyncio.sleep(10) + finally: + await asyncio.sleep(.01) + drained.append(1) + class Graph: + def __init__(self, **kwargs): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + async def run(): + task = asyncio.create_task(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + asyncio.run(run()) + assert drained == [1] + assert store.summary('trial') is None + assert store.unknown_attempts() From a59f911337fa4c2f4b3585f22770659b707a8b97 Mon Sep 17 00:00:00 2001 From: Cookie0103 <258013390+Cookie0103@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:12:30 +0900 Subject: [PATCH 2/4] feat: integrate resumable reliable trials with AFlow evolution --- docs/optimizers/aflow_reliable_trials.md | 138 +++++++ evoagentx/evaluators/aflow_evaluator.py | 29 +- evoagentx/models/aliyun_model.py | 1 + evoagentx/models/litellm_model.py | 2 +- evoagentx/models/model_utils.py | 20 +- evoagentx/models/novita_model.py | 1 + evoagentx/models/openrouter_model.py | 2 + evoagentx/models/siliconflow_model.py | 1 + evoagentx/optimizers/aflow/__init__.py | 14 +- evoagentx/optimizers/aflow/artifacts.py | 87 +++++ evoagentx/optimizers/aflow/budget.py | 4 +- evoagentx/optimizers/aflow/evaluator.py | 7 +- evoagentx/optimizers/aflow/reporting.py | 167 +++++++++ evoagentx/optimizers/aflow/runner.py | 343 ++++++++++++++++++ evoagentx/optimizers/aflow/store.py | 30 +- evoagentx/optimizers/aflow/types.py | 94 ++++- evoagentx/optimizers/aflow_optimizer.py | 78 +++- .../utils/aflow_utils/convergence_utils.py | 2 + evoagentx/utils/aflow_utils/data_utils.py | 4 +- .../utils/aflow_utils/evaluation_utils.py | 10 +- .../optimizers/test_aflow_native_trials.py | 220 +++++++++++ tests/src/optimizers/test_aflow_trials.py | 332 ++++++++++++++++- 22 files changed, 1510 insertions(+), 76 deletions(-) create mode 100644 docs/optimizers/aflow_reliable_trials.md create mode 100644 evoagentx/optimizers/aflow/artifacts.py create mode 100644 evoagentx/optimizers/aflow/reporting.py create mode 100644 evoagentx/optimizers/aflow/runner.py create mode 100644 tests/src/optimizers/test_aflow_native_trials.py diff --git a/docs/optimizers/aflow_reliable_trials.md b/docs/optimizers/aflow_reliable_trials.md new file mode 100644 index 00000000..e9b971f3 --- /dev/null +++ b/docs/optimizers/aflow_reliable_trials.md @@ -0,0 +1,138 @@ +# Reliable AFlow trials (opt in) + +`AFlowOptimizer` can checkpoint an evolution experiment as complete, comparable +validation evidence. This is a new local trial protocol, not a claim that a scalar +score proves better reasoning or statistical superiority. Existing optimizers and +legacy directories retain their existing mode unless configured explicitly. + +```python +from evoagentx.optimizers.aflow import ReliableTrialConfig +from evoagentx.optimizers.aflow_optimizer import AFlowOptimizer + +optimizer = AFlowOptimizer( + question_type="qa", + graph_path="seed_workflow", + optimized_path="experiment_workflows", + optimizer_llm=proposal_llm, + executor_llm=execution_llm, + max_rounds=10, + reliable_trials=ReliableTrialConfig( + experiment_id="hotpotqa_run_1", + replicates=3, + concurrency=8, + attempts_per_example=2, + max_example_attempts=20000, + max_proposals=30, + max_trials=11, # includes the baseline + duplicate_limit=5, + direction="maximize", + improvement_margin=0.0, + deadline_seconds=3600, + ), +) +result = optimizer.optimize(benchmark) +# In an existing event loop: result = await optimizer.optimize_async(benchmark) +print(result.status, result.reason, result.best_round, result.score) +``` + +In reliable mode `replicates` fixes validation and test replicate coverage; +`validation_rounds`/`eval_rounds` remain legacy options. `initial_round` must be 0: +resume uses the experiment's saved identity/stage instead of a round number. +Calling optimize again repairs exports and resumes incomplete stages without +repeating completed scored coordinates. A finished experiment returns its saved +terminal result; start a new experiment ID for a new plan or additional rounds. + +Every example occurrence retains its original ID and ordered occurrence index. +The plan fingerprints exact example contents/order, split, metric implementation, +public model configuration, seed sources and AFlow policy. Changed data, model, +metric or policy rejects resume. Authentication fields and endpoint credentials +are omitted. Custom benchmarks without inspectable source must supply a stable +`metric_id`, which the caller must change whenever scoring behavior changes. + +Only a finite numeric result counts as scored evidence. A valid incorrect answer +is scored zero. Explicit configured timeout/connection exception types may be +retried after their asyncio operation finishes; unknown exceptions and invalid +metrics are inconclusive. A summary is eligible only when every requested +replicate/example is scored. Diagnostic partial averages never rank or advance +convergence. Ties and improvements smaller than the configured margin retain the +parent. Proposal-only, failed and test trials do not advance convergence. + +## Checkpoints and reports + +The authoritative directory is +`experiment_workflows/reliable/hotpotqa_run_1/`. It contains `plan.json`, stable +trial identities, staged graph/prompt generations, immutable observation files, +operation intents, budget state and one committed `summary.json` per finished +trial. Graph source remains trusted code under AFlow's existing execution model. +Artifact hashes establish exact contents, not semantic equivalence or a sandbox. + +`reports/.json` includes every requested coordinate, the final status, +score or explicit missing result, typed infrastructure error, attempt history, +known cost, pricing uncertainty and original example ID. `reports/experiment.json` +includes parent selection, accepted/rejected/inconclusive feedback, pending calls, +controlled admission counts and recovery guidance. Raw provider error messages and +raw example contents are not copied into these reports. + +Legacy-shaped `results.json`, round artifacts and `experience.json` are repairable +exports of the same committed score. An export failure is reported in +`result.export_error` and `export_status.json`; it does not undo a committed +summary. Test evaluation uses a separate test plan/store and `test_results.json`. +Legacy result readers keep their old fields; reliable provenance is additive. +No old result file is accepted as reliable coverage evidence: imported graphs +must receive a fresh explicit baseline evaluation. + +## Unknown calls and recovery + +A crash after a provider call but before its outcome checkpoint is ambiguous. +There is no exactly-once provider guarantee. Reliable mode never silently repeats +that call. Cancellation/timeout of an awaiter cannot prove that a remote call or +`asyncio.to_thread` worker has stopped. Owned asyncio tasks are joined, late cost +events still update global accounting, and the experiment remains stopping/unknown +without promotion. Stop the previous process and confirm any remote/thread work +has terminated before recovery. A live previous owner is never overridden. + +```python +from evoagentx.optimizers.aflow import TrialStore +from evoagentx.optimizers.aflow.reporting import TrialReporter + +with TrialStore.open_existing(path, recover_owner=True) as store: + print(TrialReporter(store).recovery()) + for attempt in store.unknown_attempts(): + # Operator assertion: confirm termination externally before this call. + store.resolve_unknown( + attempt["attempt_id"], "abandon", # or explicit "rerun" + "Confirmed previous local and remote operation terminated", + ) +``` + +Explicit reruns receive new attempt IDs and consume remaining budgets. Abandoning +an unknown example leaves incomplete evidence. Known cost reservations remain +conservative where usage/pricing is unknown. Recovery decisions are audited. +Local `fcntl` locking enforces one owner, and parallel workers submit outcomes +through that owner. Unsupported lock platforms reject reliable mode. Multi-host +and NFS mutation are unsupported. + +## Supported limits and accounting + +Admission counters bound controlled trial/proposal/example attempts, and the +worker count bounds controlled example concurrency. Internal provider retries +are not separate trial attempts and are reported as unobserved. Token/request +counts inside arbitrary user graphs have no hard-cap claim. The elapsed deadline +stops new admission and requests cooperative cancellation; it does not guarantee +thread termination or shutdown within a wall-clock duration. + +`max_known_cost` requires both `example_cost_bound` and `proposal_cost_bound`. +Supplying these bounds is an explicit caller/provider contract that they cover +the entire admitted operation, including nested calls/retries. Without a supported +whole-operation pre-call upper bound, leave the cost limit unset and inspect +observed/unknown usage. Unknown pricing is never assumed free. Reservations are +persisted before work, retries do not reset them, and an observed bound violation +halts further admission. Trusted graph imports/constructor side effects and any +external unobserved accounting paths cannot acquire hard provider limits merely +by setting a number in this configuration. + +The optional `CostManager.observe` scope preserves existing process totals while +isolating sibling asyncio contexts. `asyncio.to_thread` propagates the observer; +raw threads, external processes and providers bypassing `CostManager.update_cost` +are unsupported accounting paths. Missing events/prices remain unobserved or +unknown rather than known zero. diff --git a/evoagentx/evaluators/aflow_evaluator.py b/evoagentx/evaluators/aflow_evaluator.py index f9ee585c..9864a47a 100644 --- a/evoagentx/evaluators/aflow_evaluator.py +++ b/evoagentx/evaluators/aflow_evaluator.py @@ -1,13 +1,15 @@ # Acknowledgement: Modified from AFlow (https://github.com/geekan/MetaGPT/blob/main/metagpt/ext/aflow/scripts/evaluator.py) under MIT License import asyncio +from typing import Callable, Optional, Tuple + from tqdm.asyncio import tqdm_asyncio -from typing import Tuple, Optional, Callable + from ..benchmark.benchmark import Benchmark -from ..models.base_model import BaseLLM from ..core.logging import logger +from ..models.base_model import BaseLLM from ..models.model_utils import cost_manager - +from ..optimizers.aflow.evidence import CostLedger # If you want to customize tasks, add task types here and provide evaluation functions, just like the ones given above @@ -57,7 +59,7 @@ async def graph_evaluate_async(self, benchmark: Benchmark, graph: Callable, is_t return (0.0, 0.0, 0.0, True) # get total cost before evaluation - cost_before = cost_manager.get_total_cost() + ledger = CostLedger() # Create a shared semaphore semaphore = asyncio.Semaphore(max_concurrent_tasks) @@ -74,18 +76,19 @@ async def evaluate_with_semaphore(example): tasks = [evaluate_with_semaphore(example) for example in data] # Wait for all tasks to complete - results = await tqdm_asyncio.gather( - *tasks, - desc=f"Evaluating {benchmark.name} problems", - total=len(data) - ) + with cost_manager.observe(ledger.observe): + results = await tqdm_asyncio.gather( + *tasks, + desc=f"Evaluating {benchmark.name} problems", + total=len(data) + ) # Replace failed evaluations (None results) with 0 valid_results = [0.0 if r is None else r for r in results] all_failed = all(r is None for r in results) # get total cost after evaluation - total_cost = cost_manager.get_total_cost() - cost_before + total_cost = ledger.close()['known_cost'] avg_cost = total_cost / len(data) if not valid_results: @@ -94,8 +97,4 @@ async def evaluate_with_semaphore(example): else: avg_metrics = sum(valid_results) / len(valid_results) - return avg_metrics, avg_cost, total_cost, all_failed - - - - \ No newline at end of file + return avg_metrics, avg_cost, total_cost, all_failed diff --git a/evoagentx/models/aliyun_model.py b/evoagentx/models/aliyun_model.py index 62c57fb8..62465ea4 100644 --- a/evoagentx/models/aliyun_model.py +++ b/evoagentx/models/aliyun_model.py @@ -79,6 +79,7 @@ def _compute_cost(self, usage: CompletionUsage) -> Cost: input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, cost=0.0, + pricing_known=False, ) usage_object = usage if isinstance(usage, Usage) else Usage(**usage.model_dump()) input_cost, output_cost = cost_per_token(model=self._litellm_model, usage_object=usage_object) diff --git a/evoagentx/models/litellm_model.py b/evoagentx/models/litellm_model.py index 9f4fb755..30f64c89 100644 --- a/evoagentx/models/litellm_model.py +++ b/evoagentx/models/litellm_model.py @@ -130,7 +130,7 @@ def _compute_cost(self, usage) -> Cost: f"[LiteLLM] Could not compute cost for model '{self.config.model}': {e}. " "Recording tokens with zero cost." ) - return Cost(input_tokens=input_tokens, output_tokens=output_tokens, input_cost=0.0, output_cost=0.0) + return Cost(input_tokens=input_tokens, output_tokens=output_tokens, input_cost=0.0, output_cost=0.0, pricing_known=False) @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(5)) def single_generate(self, messages: List[dict], **kwargs) -> str: diff --git a/evoagentx/models/model_utils.py b/evoagentx/models/model_utils.py index e3f523d3..93b10bd6 100644 --- a/evoagentx/models/model_utils.py +++ b/evoagentx/models/model_utils.py @@ -1,5 +1,5 @@ -import threading import math +import threading from collections import defaultdict from contextlib import contextmanager from contextvars import ContextVar @@ -8,12 +8,12 @@ import pandas as pd -from ..core.logging import logger -from ..core.decorators import atomic_method from ..core.callbacks import suppress_cost_logs +from ..core.decorators import atomic_method +from ..core.logging import logger from ..core.registry import MODEL_REGISTRY -from .model_configs import LLMConfig from ..models.base_model import BaseLLM +from .model_configs import LLMConfig _cost_observers = ContextVar('aflow_cost_observers', default=()) @@ -29,7 +29,7 @@ class CostEvent: output_tokens: int def get_openai_model_cost() -> dict: - import json + import json from importlib.resources import files # import importlib.resources # with importlib.resources.open_text('litellm', 'model_prices_and_context_window_backup.json') as f: @@ -66,14 +66,20 @@ def __init__( output_tokens: Optional[int] = None, input_cost: Optional[float] = None, output_cost: Optional[float] = None, - cost: Optional[float] = None + cost: Optional[float] = None, + pricing_known: Optional[bool] = None, ): - self.pricing_known = cost is not None or input_cost is not None or output_cost is not None + self._pricing_known = (cost is not None or input_cost is not None or output_cost is not None) if pricing_known is None else pricing_known self.input_tokens = input_tokens self.output_tokens = output_tokens # Keep input_cost/output_cost only as temporary constructor compatibility. self.cost = cost if cost is not None else (input_cost or 0.0) + (output_cost or 0.0) + @property + def pricing_known(self) -> bool: + """Return whether numeric cost has supported pricing rather than a fallback.""" + return self._pricing_known + @property def cost(self) -> float: return self._cost diff --git a/evoagentx/models/novita_model.py b/evoagentx/models/novita_model.py index aecb0208..a2fe4232 100644 --- a/evoagentx/models/novita_model.py +++ b/evoagentx/models/novita_model.py @@ -57,5 +57,6 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, cost=0.0, + pricing_known=False, ) cost_manager.update_cost(cost=cost, model=self.config.model) diff --git a/evoagentx/models/openrouter_model.py b/evoagentx/models/openrouter_model.py index e31e140d..151171b7 100644 --- a/evoagentx/models/openrouter_model.py +++ b/evoagentx/models/openrouter_model.py @@ -296,6 +296,7 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): logger.warning(f"[OpenRouterLLM] usage is None in response (id={response.id}); cost will not be recorded.") return cost_value = getattr(usage, "cost", None) + pricing_known = cost_value is not None if cost_value is None: logger.warning( f"[OpenRouterLLM] usage.cost not present in response (id={response.id}); " @@ -306,6 +307,7 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, cost=cost_value, + pricing_known=pricing_known, ) cost_manager.update_cost(cost, model=self.config.model) diff --git a/evoagentx/models/siliconflow_model.py b/evoagentx/models/siliconflow_model.py index 12ea71c4..b7080d9b 100644 --- a/evoagentx/models/siliconflow_model.py +++ b/evoagentx/models/siliconflow_model.py @@ -59,5 +59,6 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, cost=0.0, + pricing_known=False, ) cost_manager.update_cost(cost=cost, model=self.config.model) diff --git a/evoagentx/optimizers/aflow/__init__.py b/evoagentx/optimizers/aflow/__init__.py index cae17d19..1b65f904 100644 --- a/evoagentx/optimizers/aflow/__init__.py +++ b/evoagentx/optimizers/aflow/__init__.py @@ -1,7 +1,13 @@ """Optional reliable evidence protocol for AFlow only.""" -from .types import EvaluationPlan, Observation, ReliableTrialConfig, TrialSummary -from .store import TrialStore from .budget import AdmissionBudget +from .store import TrialStore +from .types import EvaluationPlan, Observation, ReliableTrialConfig, TrialSummary -__all__ = ['EvaluationPlan', 'Observation', 'ReliableTrialConfig', 'TrialSummary', - 'TrialStore', 'AdmissionBudget'] +__all__ = [ + 'AdmissionBudget', + 'EvaluationPlan', + 'Observation', + 'ReliableTrialConfig', + 'TrialStore', + 'TrialSummary', +] diff --git a/evoagentx/optimizers/aflow/artifacts.py b/evoagentx/optimizers/aflow/artifacts.py new file mode 100644 index 00000000..45017c8b --- /dev/null +++ b/evoagentx/optimizers/aflow/artifacts.py @@ -0,0 +1,87 @@ +"""Load exact staged trusted AFlow code without filesystem/import-name coupling.""" + +import importlib.util +import re +import sys +import types +from pathlib import Path + +from ...prompts.optimizers.aflow_optimizer import WORKFLOW_TEMPLATE +from .types import digest + + +def prepare_graph(graph, prompt, generated=False): + """Normalize the known prompt import before hashing and staging the source.""" + if not isinstance(graph, str) or not isinstance(prompt, str) or not graph.strip(): + raise ValueError('proposal must contain graph and prompt source strings') + source = WORKFLOW_TEMPLATE.format(graph=graph) if generated else graph + source = re.sub(r'^\s*import\s+[\w.]+\.prompt\s+as\s+prompt_custom\s*$', + 'from . import prompt as prompt_custom', source, flags=re.MULTILINE) + prompt = prompt.replace('prompt_custom.', '') if generated else prompt + compile(source, '', 'exec') + compile(prompt, '', 'exec') + return source, prompt + + +def load_staged_graph(store, trial_id): + """Import a verified immutable generation using a unique private package. + + Workflows remain trusted user code. This loader supplies the same public + Workflow constructor and does not claim execution isolation or sandboxing. + """ + _, _, manifest = store.read_artifacts(trial_id) + directory = store.path / manifest['directory'] + namespace = '_aflow_trial_' + digest([str(store.path.resolve()), trial_id, manifest['digest']]) + graph_name = namespace + '.graph' + if graph_name in sys.modules: + return sys.modules[graph_name].Workflow + package = types.ModuleType(namespace) + package.__path__ = [str(directory)] + package.__package__ = namespace + sys.modules[namespace] = package + loaded = [namespace] + try: + for name in ('prompt', 'graph'): + module_name = namespace + '.' + name + spec = importlib.util.spec_from_file_location(module_name, directory / f'{name}.py') + if spec is None or spec.loader is None: + raise ImportError('unable to load staged AFlow artifacts') + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + loaded.append(module_name) + spec.loader.exec_module(module) + setattr(package, name, module) + workflow = sys.modules[graph_name].Workflow + if not callable(workflow): + raise TypeError('staged graph has no callable Workflow') + return workflow + except BaseException: + for module_name in loaded: + sys.modules.pop(module_name, None) + raise + + +def publish_round(store, trial_id, root): + """Export one verified generation for existing round readers and test callers.""" + import os + import tempfile + + from .store import sync_directory + graph, prompt, _ = store.read_artifacts(trial_id) + trial = store.trial(trial_id) + directory = Path(root) / f"round_{trial['round']}" + directory.mkdir(parents=True, exist_ok=True) + # These files are compatibility exports. The immutable generation in the + # reliable store remains authoritative if publication is interrupted. + for name, content in (('graph.py', graph), ('prompt.py', prompt), ('__init__.py', '')): + fd, temporary = tempfile.mkstemp(prefix='.' + name, dir=directory) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, directory / name) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + sync_directory(directory) diff --git a/evoagentx/optimizers/aflow/budget.py b/evoagentx/optimizers/aflow/budget.py index 63458743..a82deb3c 100644 --- a/evoagentx/optimizers/aflow/budget.py +++ b/evoagentx/optimizers/aflow/budget.py @@ -1,8 +1,9 @@ """Persistent admission counters and conservative whole-operation reservations.""" import time + +from .store import atomic_json from .types import SCHEMA_VERSION, finite_score -from .store import atomic_json, read_json class AdmissionBudget: @@ -97,6 +98,7 @@ def finish(self, operation_id, known_cost, pricing_known, terminated=True): # execution terminated; absent observer events never prove zero dollars. reservation['reserved'] = 0.0 if terminated and pricing_known else max(0, bound - known_cost) reservation['status'] = 'finished' if terminated else 'unknown' + reservation.update(known_cost=known_cost, pricing_known=pricing_known, terminated=terminated) atomic_json(self.store.path / 'admissions' / f'{operation_id}.json', reservation) if reservation['reserved'] == 0 and terminated: self.state['reservations'].pop(operation_id) diff --git a/evoagentx/optimizers/aflow/evaluator.py b/evoagentx/optimizers/aflow/evaluator.py index f803f738..9d494cb7 100644 --- a/evoagentx/optimizers/aflow/evaluator.py +++ b/evoagentx/optimizers/aflow/evaluator.py @@ -36,7 +36,7 @@ async def owned_call(operation, timeout): return 'completed', task.result() except asyncio.CancelledError: return 'unknown', None - except Exception as exc: + except Exception as exc: # noqa: BLE001 - user/provider/export boundary is typed as evidence return 'error', exc except asyncio.CancelledError: task.cancel() @@ -111,6 +111,11 @@ async def _attempt(self, benchmark, graph, example, identity, replicate, attempt async def evaluate(self, benchmark, graph, data, plan, trial_id, store, budget): """Resume completed coordinates and commit one complete or incomplete summary.""" plan.verify_data(data) + # A durable completed outcome establishes completion even if the process + # died before releasing its conservative cost reservation. + for observation in store.observations(trial_id): + if observation.status not in ('unknown', 'cancelled') and observation.observation_id in budget.state['reservations']: + budget.finish(observation.observation_id, observation.known_cost, observation.pricing == 'known') existing = store.summary(trial_id) if existing is not None: return existing diff --git a/evoagentx/optimizers/aflow/reporting.py b/evoagentx/optimizers/aflow/reporting.py new file mode 100644 index 00000000..0290e4ae --- /dev/null +++ b/evoagentx/optimizers/aflow/reporting.py @@ -0,0 +1,167 @@ +"""Inspectable per-example evidence and recovery guidance for local trials.""" + +from collections import Counter, defaultdict + +from .evidence import EvidenceView +from .store import atomic_json, read_json +from .types import SCHEMA_VERSION, TrialSummary + + +class TrialReporter: + """Build reports from immutable outcomes, never infer missing task scores. + + Reports are repairable exports. Only each trial's summary.json authorizes + ranking; a partially written or absent report cannot change promotion. + """ + + def __init__(self, store): + self.store = store + self.plan = store.plan + + @classmethod + def inspect(cls, path, recover_owner=False): + """Take an owner-locked snapshot without executing any user graph/provider.""" + from .store import TrialStore + with TrialStore.open_existing(path, recover_owner=recover_owner) as store: + return cls(store).experiment() + + def _histories(self, trial_id): + """Group attempt evidence by the exact fixed replicate/example coordinate.""" + histories = defaultdict(list) + for observation in self.store.observations(trial_id): + histories[(observation.example_key, observation.replicate)].append(observation) + for values in histories.values(): + values.sort(key=lambda observation: observation.attempt) + return histories + + def _pending(self, trial_id): + """Index unresolved operations without exposing provider exception messages.""" + return [operation for operation in self.store.unknown_attempts() + if operation['trial_id'] == trial_id] + + def _example_row(self, example, replicate, observations, pending): + """Represent missing, scored and infrastructure evidence distinctly.""" + latest = observations[-1] if observations else None + unresolved = [operation['attempt_id'] for operation in pending + if operation.get('example_key') == example.key and operation.get('replicate') == replicate] + if latest is not None: + status = latest.status + else: + status = 'unknown' if unresolved else 'missing' + return {'example_index': example.index, 'example_id': example.original_id, + 'occurrence': example.occurrence, 'content_digest': example.content_digest, + 'replicate': replicate, 'status': status, + 'score': latest.score if latest is not None and latest.status == 'scored' else None, + 'latest_attempt': latest.attempt if latest is not None else None, + 'error_type': latest.error_type if latest is not None else None, + 'known_cost': sum(observation.known_cost for observation in observations), + 'pricing': 'known' if observations and all(o.pricing == 'known' for o in observations) else 'unknown', + 'input_tokens': sum(o.input_tokens for o in observations), + 'output_tokens': sum(o.output_tokens for o in observations), + 'unresolved_attempt_ids': unresolved, + 'attempts': [observation.to_dict() for observation in observations]} + + def trial(self, trial_id): + """Report every requested coordinate, including those never admitted.""" + trial = self.store.trial(trial_id) + summary = self.store.summary(trial_id) + observations = self.store.observations(trial_id) + diagnostic = TrialSummary.build(self.plan, trial_id, trial['round'], observations) + if summary is not None and summary != diagnostic: + raise ValueError('committed summary does not match immutable evidence') + histories = self._histories(trial_id) + pending = self._pending(trial_id) + examples = [] + for replicate in range(self.plan.config.replicates): + for example in self.plan.examples: + values = histories.get((example.key, replicate), []) + examples.append(self._example_row(example, replicate, values, pending)) + artifact = None + directory = self.store._trial_path(trial_id) / 'artifacts' + if directory.exists(): + _, _, artifact = self.store.read_artifacts(trial_id) + return {'schema_version': SCHEMA_VERSION, 'trial': trial, + 'plan_id': self.plan.identity, 'split': self.plan.split, + 'summary_committed': summary is not None, + 'summary': (summary or diagnostic).to_dict(), + 'artifact': artifact, 'examples': examples, + 'pending_operations': pending, + 'coverage': {'requested': self.plan.requested, + 'scored': diagnostic.scored, + 'missing_or_unscored': self.plan.requested - diagnostic.scored, + 'attempts_recorded': len(observations)}, + 'ranking_eligible': bool(summary and summary.eligible and summary.split == 'validation')} + + def _operation_totals(self): + """Expose controlled attempts by stage/status without provider-internal claims.""" + stages = defaultdict(Counter) + for path in (self.store.path / 'attempts').glob('*.json'): + operation = read_json(path) + stages[operation['stage']][operation['status']] += 1 + return {stage: dict(counts) for stage, counts in stages.items()} + + def recovery(self): + """Explain exactly which unknown calls block further automatic execution.""" + unknown = self.store.unknown_attempts() + owner = self.store.read_state('owner', {}) + return {'blocked': bool(unknown), 'owner_status': owner.get('status'), + 'unknown_attempts': unknown, + 'required_action': ('Confirm previous local/remote work terminated, then explicitly resolve each unknown ' + 'attempt as rerun or abandon with an operator note.' if unknown else None), + 'replay_policy': 'Completed observations are never repeated. Unknown calls are never automatically repeated.', + 'termination_limit': 'Cancelling an async awaiter does not terminate arbitrary threads or remote requests.'} + + def operation_accounting(self): + """Retain proposal/retry costs after the stage cursor has advanced.""" + rows = [] + for path in sorted((self.store.path / 'attempts').glob('*.json')): + operation = read_json(path) + admission = self.store.path / 'admissions' / path.name + costs = read_json(admission) if admission.exists() else {} + rows.append({'attempt_id': operation['attempt_id'], 'trial_id': operation['trial_id'], + 'stage': operation['stage'], 'status': operation['status'], + 'known_cost': costs.get('known_cost', 0.0), + 'pricing_known': costs.get('pricing_known', False), + 'reserved_upper_bound': costs.get('reserved', 0.0)}) + return rows + + def experiment(self): + """Take a stable owner-held inventory of summaries, outcomes and recovery.""" + view = EvidenceView(self.store) + best = view.best() + reports = [self.trial(trial['trial_id']) for trial in self.store.trials()] + summaries = self.store.summaries() + budget = self.store.read_state('budget', {}) + return {'schema_version': SCHEMA_VERSION, 'experiment_id': self.plan.config.experiment_id, + 'plan_id': self.plan.identity, 'split': self.plan.split, + 'direction': self.plan.config.direction, 'margin': self.plan.config.improvement_margin, + 'requested_per_trial': self.plan.requested, + 'best_trial_id': best.trial_id if best else None, + 'best_round': best.round if best else None, + 'best_score': best.score if best else None, + 'ranked_trials': [{'trial_id': s.trial_id, 'round': s.round, 'score': s.score} + for s in view.ranked()], + 'converged': view.converged(), + 'committed_trials': len(summaries), + 'incomplete_trials': [s.trial_id for s in summaries if not s.eligible], + 'evolution': self.store.read_state('evolution', None), + 'feedback': view.feedback(), 'operation_totals': self._operation_totals(), + 'operation_accounting': self.operation_accounting(), + 'cost': {'known_spent': budget.get('known_spent', 0), + 'uncertain': budget.get('uncertain', True), + 'reserved_upper_bounds': sum(r['reserved'] for r in budget.get('reservations', {}).values()), + 'proposal_cost_included': True, + 'provider_internal_requests': 'unobserved', + 'unsupported_accounting_paths': ['raw threads', 'external processes', 'providers bypassing CostManager']}, + 'deadline_semantics': 'Stops new admission and requests cooperative cancellation; shutdown may exceed deadline.', + 'recovery': self.recovery(), 'audit': self.store.audit(), + 'export': self.store.read_state('export_status', None), 'trials': reports} + + def export(self): + """Publish repairable per-example and experiment reports atomically.""" + report = self.experiment() + directory = self.store.path / 'reports' + for trial in report['trials']: + atomic_json(directory / f"{trial['trial']['trial_id']}.json", trial) + atomic_json(directory / 'experiment.json', report) + return report diff --git a/evoagentx/optimizers/aflow/runner.py b/evoagentx/optimizers/aflow/runner.py new file mode 100644 index 00000000..87169b20 --- /dev/null +++ b/evoagentx/optimizers/aflow/runner.py @@ -0,0 +1,343 @@ +"""AFlow-only staged evolution over committed, comparable trial evidence.""" + +import asyncio +import inspect +from dataclasses import replace +from pathlib import Path + +from ...models.model_utils import cost_manager +from .artifacts import load_staged_graph, prepare_graph, publish_round +from .budget import AdmissionBudget +from .evaluator import DetailedEvaluator, owned_call +from .evidence import CostLedger, EvidenceView, EvolutionResult +from .store import TrialStore, atomic_json +from .types import SCHEMA_VERSION, EvaluationPlan, digest + + +def metric_identity(benchmark): + """Fingerprint the native scorer and inherited benchmark implementation.""" + sources = [] + for cls in type(benchmark).__mro__: + if cls is object: + continue + try: + source = inspect.getsource(cls) + except (OSError, TypeError): + raise ValueError('custom benchmark requires an explicit stable metric_id') + sources.append((f'{cls.__module__}.{cls.__qualname__}', source)) + return digest(sources) + + +class ReliableAFlowRunner: + """Own one reliable experiment; provider/model APIs remain unchanged.""" + + def __init__(self, optimizer, benchmark): + self.optimizer = optimizer + self.benchmark = benchmark + self.config = optimizer.reliable_trials + self.root = Path(optimizer.root_path) + self.path = self.root / 'reliable' / self.config.experiment_id + self.data = list(benchmark.get_dev_data() or []) + self.plan = self._plan(self.data, self.config, 'validation') + self.export_error = None + + def _plan(self, data, config, split): + """Include model roles and AFlow behavior alongside exact dataset identity.""" + optimizer = self.optimizer + models = {'executor': optimizer.executor_llm.config, 'optimizer': optimizer.optimizer_llm.config} + models = {role: config.model_dump(mode='json') for role, config in models.items()} + models['aflow_policy'] = {'question_type': optimizer.question_type, 'operators': optimizer.operators, + 'sample': optimizer.sample, 'max_rounds': optimizer.max_rounds, + 'check_convergence': optimizer.check_convergence} + # Input seed changes must invalidate resume even after baseline completion. + seed_graph = (Path(optimizer.graph_path) / 'graph.py').read_text(encoding='utf-8') + seed_prompt = (Path(optimizer.graph_path) / 'prompt.py').read_text(encoding='utf-8') + models['seed_digest'] = digest({'graph': seed_graph, 'prompt': seed_prompt}) + return EvaluationPlan.create(self.benchmark.name, data, models, + config.metric_id or metric_identity(self.benchmark), config, split) + + def _save(self): + """Persist the stage cursor before further external work.""" + self.store.write_state('evolution', self.state) + + def _initial_state(self): + """Build a stable baseline/proposal cursor independent of retry count.""" + return {'schema_version': SCHEMA_VERSION, 'phase': 'baseline', 'round': 0, + 'candidate': None, 'parent': None, 'duplicates': 0, + 'modifications': [], 'artifact_digests': [], 'pending_proposal': None, + 'terminal_status': None, 'terminal_reason': None} + + def _result(self, status, reason): + """Report explicit terminal state using only a committed eligible parent.""" + best = self.view.best() + return EvolutionResult(status, reason, best.trial_id if best else None, + best.round if best else None, best.score if best else None, + len(self.store.summaries()), self.budget.report(), self.export_error) + + def _terminal(self, status, reason): + """Checkpoint terminal state so a repeated optimize call does no paid work.""" + self.state.update(phase='finished', terminal_status=status, terminal_reason=reason) + self._save() + self._export() + return self._result(status, reason) + + def _export(self): + """Repair compatibility files without undoing a committed summary on failure.""" + try: + for summary in self.store.summaries(): + if summary.eligible: + publish_round(self.store, summary.trial_id, self.root) + self.view.export(self.root) + from .reporting import TrialReporter + TrialReporter(self.store).export() + except Exception as exc: # noqa: BLE001 - user/provider/export boundary is typed as evidence + self.export_error = f'{type(exc).__module__}.{type(exc).__qualname__}' + self.store.write_state('export_status', {'status': 'failed', 'error_type': self.export_error}) + else: + self.export_error = None + self.store.write_state('export_status', {'status': 'complete'}) + + async def _baseline(self): + """Import seed artifacts but evaluate fresh coverage rather than old results.""" + trial_id = 'baseline' + if not any(t['trial_id'] == trial_id for t in self.store.trials()): + self.budget.admit('trial', 'trial_baseline') + self.store.create_trial(trial_id, 0, 'baseline') + self.budget.finish('trial_baseline', 0, True) + graph = (Path(self.optimizer.graph_path) / 'graph.py').read_text(encoding='utf-8') + prompt = (Path(self.optimizer.graph_path) / 'prompt.py').read_text(encoding='utf-8') + graph, prompt = prepare_graph(graph, prompt) + manifest = self.store.stage_artifacts(trial_id, graph, prompt) + if manifest['digest'] not in self.state['artifact_digests']: + self.state['artifact_digests'].append(manifest['digest']) + self._save() + summary = await self._evaluate(trial_id) + if not summary.eligible: + return self._terminal('incomplete', 'baseline does not cover the complete validation plan') + self.state.update(phase='proposal', parent=trial_id, round=1) + self._save() + self._export() + return None + + async def _evaluate(self, trial_id): + """Load exact staged code and use native detailed benchmark evaluation.""" + existing = self.store.summary(trial_id) + if existing is not None: + return existing + graph = load_staged_graph(self.store, trial_id) + return await DetailedEvaluator(self.optimizer.executor_llm).evaluate( + self.benchmark, graph, self.data, self.plan, trial_id, self.store, self.budget) + + def _proposal_prompt(self, parent): + """Reuse the existing AFlow proposal prompt with measured feedback.""" + graph, prompt, _ = self.store.read_artifacts(parent.trial_id) + extracted = self.optimizer.graph_utils.extract_solve_graph(graph) + if not extracted: + raise ValueError('parent graph must define class Workflow') + descriptions = self.optimizer.graph_utils.load_operators_description(self.optimizer.operators, + self.optimizer.optimizer_llm) + return self.optimizer.graph_utils.create_graph_optimize_prompt( + self.view.prompt_feedback(parent.trial_id), parent.score, extracted[0], prompt, + descriptions, self.optimizer.question_type, '') + + def _parse_proposal(self, content, parent): + """Preserve native XML parsing/fallback while requiring executable source.""" + from ..aflow_optimizer import GraphOptimizeOutput + graph, prompt, _ = self.store.read_artifacts(parent.trial_id) + extracted = self.optimizer.graph_utils.extract_solve_graph(graph) + try: + parsed = GraphOptimizeOutput.parse(content, parse_mode='xml').get_structured_data() + except Exception: # noqa: BLE001 - retain the existing XML parser fallback + parsed = self.optimizer._parse_optimizer_llm_output(content, extracted[0], prompt) + if not isinstance(parsed.get('modification'), str) or not parsed['modification'].strip(): + raise ValueError('proposal requires a modification description') + graph, prompt = prepare_graph(parsed['graph'], parsed['prompt'], generated=True) + return {'graph': graph, 'prompt': prompt, 'modification': parsed['modification']} + + async def _request_proposal(self, parent): + """Count proposal calls separately; an outage never restarts the baseline.""" + number = self.budget.state['counts']['proposal'] + 1 + operation_id = f'proposal_{number}' + prompt = self._proposal_prompt(parent) + self.budget.admit('proposal', operation_id) + self.store.begin_operation(operation_id, 'proposal', parent.trial_id) + ledger = CostLedger() + timeouts = [v for v in (self.config.proposal_timeout, self.budget.remaining_time()) if v is not None] + try: + with cost_manager.observe(ledger.observe): + state, value = await owned_call(lambda: self.optimizer.optimizer_llm.async_generate( + prompt=prompt, parse_mode='str'), min(timeouts) if timeouts else None) + except asyncio.CancelledError: + costs = ledger.close() + self.store.finish_operation(operation_id, 'cancelled') + self.store.mark_stopping() + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known', False) + raise + costs = ledger.close() + if state == 'unknown': + self.store.finish_operation(operation_id, 'unknown') + self.store.mark_stopping() + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known', False) + raise RuntimeError('unknown proposal completion requires explicit resolution') + if state == 'error': + retryable = DetailedEvaluator._retryable(value, self.config) + self.store.finish_operation(operation_id, 'retryable' if retryable else 'inconclusive', + error_type=f'{type(value).__module__}.{type(value).__qualname__}') + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known') + if retryable: + return None + raise ValueError('proposal infrastructure failure is inconclusive') + try: + response = self._parse_proposal(value.content, parent) + except (ValueError, SyntaxError, KeyError, TypeError) as exc: + self.store.finish_operation(operation_id, 'inconclusive', error_type=type(exc).__name__) + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known') + return None + # Durable parsed source proves response completion if a crash precedes + # operation/budget finalization. It is never reconstructed from old rows. + self.state['pending_proposal'] = {'operation_id': operation_id, 'response': response, + 'parent_id': parent.trial_id, 'costs': costs} + self._save() + self.store.finish_operation(operation_id, 'completed') + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known') + return response + + def _recover_pending_proposal(self): + """Finalize checkpointed provider output without repeating its external call.""" + pending = self.state['pending_proposal'] + if pending is None: + return None + operation_id = pending['operation_id'] + operation = self.store.operation(operation_id) + if operation is None: + raise ValueError('pending proposal has no durable attempt intent') + if operation['status'] == 'started': + self.store.finish_operation(operation_id, 'completed') + costs = pending['costs'] + if operation_id in self.budget.state['reservations']: + self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known') + return pending['response'] + + async def _proposal(self): + """Bound both paid requests and duplicate candidates under a stable parent.""" + parent = self.view.best() + if parent is None: + return self._terminal('incomplete', 'no eligible validation parent') + response = self._recover_pending_proposal() + self.store.assert_resolved() + if response is None: + response = await self._request_proposal(parent) + if response is None: + return None + normalized = ' '.join(response['modification'].casefold().split()) + artifact_digest = digest({'graph': response['graph'], 'prompt': response['prompt']}) + if normalized in self.state['modifications'] or artifact_digest in self.state['artifact_digests']: + self.state['duplicates'] += 1 + self.state['pending_proposal'] = None + self._save() + if self.state['duplicates'] >= self.config.duplicate_limit: + return self._terminal('exhausted', 'duplicate candidate budget exhausted') + return None + trial_id = f"candidate_{self.state['round']}" + # If a crash occurs after trial admission but before creating the trial, + # that reservation remains conservative; automatic duplicate admission + # is rejected rather than silently resetting an attempt budget. + if not any(t['trial_id'] == trial_id for t in self.store.trials()): + self.budget.admit('trial', f'trial_{trial_id}') + self.store.create_trial(trial_id, self.state['round'], 'candidate', parent.trial_id, + response['modification']) + self.budget.finish(f'trial_{trial_id}', 0, True) + self.store.stage_artifacts(trial_id, response['graph'], response['prompt']) + self.state['modifications'].append(normalized) + self.state['artifact_digests'].append(artifact_digest) + self.state.update(phase='evaluation', candidate=trial_id, parent=parent.trial_id, + pending_proposal=None, duplicates=0) + self._save() + return None + + async def run(self): + """Execute or resume stable stages and return a truthful terminal result.""" + with TrialStore(self.path, self.plan) as self.store: + self.budget = AdmissionBudget(self.store, self.config) + self.view = EvidenceView(self.store) + self.state = self.store.read_state('evolution', self._initial_state()) + if self.state.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported evolution state schema') + self._recover_pending_proposal() + self.store.assert_resolved() + if self.state['phase'] == 'finished': + self._export() + return self._result(self.state['terminal_status'], self.state['terminal_reason']) + try: + while True: + self.budget.check_deadline() + if self.state['phase'] == 'baseline': + result = await self._baseline() + if result is not None: + return result + elif self.state['phase'] == 'proposal': + if self.state['round'] > self.optimizer.max_rounds: + return self._terminal('completed', 'requested optimization rounds completed') + result = await self._proposal() + if result is not None: + return result + elif self.state['phase'] == 'evaluation': + summary = await self._evaluate(self.state['candidate']) + self._export() + if not summary.eligible: + return self._terminal('incomplete', 'candidate has incomplete validation evidence') + self.optimizer.round = summary.round + self.optimizer.avg_score = summary.score + self.state.update(phase='proposal', candidate=None, round=self.state['round'] + 1) + self._save() + if self.optimizer.check_convergence and self.view.converged(): + return self._terminal('completed', 'committed validation trials converged') + else: + raise ValueError('unknown evolution stage') + except RuntimeError as exc: + if self.store.unknown_attempts(): + # Preserve stage for explicit operator resolution. No late + # result callback is allowed to mutate this owner state. + return self._result('incomplete', 'unknown external execution requires explicit resolution') + return self._terminal('exhausted', str(exc)) + except (ValueError, ImportError, SyntaxError, AttributeError, TypeError) as exc: + return self._terminal('incomplete', f'workflow/proposal infrastructure: {type(exc).__name__}') + + async def test(self, rounds): + """Use a distinct split/store; test labels never enter evolutionary evidence.""" + validation_plan = self.plan + data = list(self.benchmark.get_test_data() or []) + test_config = replace(self.config, experiment_id=self.config.experiment_id + '_test') + plan = self._plan(data, test_config, 'test') + results = [] + with TrialStore(self.path, validation_plan) as validation: + validation.assert_resolved() + best = EvidenceView(validation).best() + if rounds is None: + if best is None: + raise ValueError('no committed validation trial to test') + rounds = [best.round] + selected = {trial['round']: trial['trial_id'] for trial in validation.trials() + if validation.summary(trial['trial_id']) is not None} + with TrialStore(self.root / 'reliable' / test_config.experiment_id, plan) as store: + budget = AdmissionBudget(store, test_config) + store.assert_resolved() + for round_number in rounds: + if round_number not in selected: + raise ValueError('test round has no reliable validation provenance') + source_id = selected[round_number] + graph, prompt, _ = validation.read_artifacts(source_id) + trial_id = f'test_{round_number}' + if not any(t['trial_id'] == trial_id for t in store.trials()): + budget.admit('trial', f'trial_{trial_id}') + store.create_trial(trial_id, round_number, 'test', source_id) + budget.finish(f'trial_{trial_id}', 0, True) + store.stage_artifacts(trial_id, graph, prompt) + summary = await DetailedEvaluator(self.optimizer.executor_llm).evaluate( + self.benchmark, load_staged_graph(store, trial_id), data, plan, trial_id, store, budget) + results.append(summary) + atomic_json(self.root / 'test_results.json', + [{'round': s.round, 'score': s.score, 'eligible': s.eligible, + 'trial_id': s.trial_id, 'split': 'test', 'requested': s.requested, + 'scored': s.scored, 'known_cost': s.known_cost} for s in results]) + return results diff --git a/evoagentx/optimizers/aflow/store.py b/evoagentx/optimizers/aflow/store.py index febc0e13..859d9760 100644 --- a/evoagentx/optimizers/aflow/store.py +++ b/evoagentx/optimizers/aflow/store.py @@ -13,9 +13,17 @@ import tempfile import time import uuid +from dataclasses import replace from pathlib import Path -from .types import SCHEMA_VERSION, Observation, TrialSummary, canonical, digest +from .types import ( + SCHEMA_VERSION, + EvaluationPlan, + Observation, + TrialSummary, + canonical, + digest, +) def atomic_json(path, value): @@ -69,6 +77,23 @@ def __init__(self, path, plan): self._unclean = False self._active_operations = set() self._pending_operations = {} + self._examples = {example.key: example for example in plan.examples} + + @classmethod + def open_existing(cls, path, recover_owner=False): + """Open an existing saved plan for explicit offline recovery/inspection. + + Args: + path: Reliable experiment directory containing plan.json. + recover_owner: Explicit acknowledgement of an unclean dead owner. + + This never automatically resolves unknown calls or admits paid work. + A previous running/stopping process must have terminated before recovery. + """ + plan = EvaluationPlan.from_dict(read_json(Path(path) / 'plan.json')) + if recover_owner: + plan = replace(plan, config=replace(plan.config, recover_owner=True)) + return cls(path, plan) def __enter__(self): """Acquire an OS-held writer lock before reading or mutating checkpoints.""" @@ -276,8 +301,7 @@ def record(self, observation): """Commit an immutable result before it can be consumed by selection.""" self._require_owner() self.trial(observation.trial_id) - allowed = {e.key: e for e in self.plan.examples} - example = allowed.get(observation.example_key) + example = self._examples.get(observation.example_key) if example is None or observation.replicate >= self.plan.config.replicates: raise ValueError('observation outside fixed plan') expected = digest([observation.trial_id, example.key, observation.replicate, observation.attempt]) diff --git a/evoagentx/optimizers/aflow/types.py b/evoagentx/optimizers/aflow/types.py index fd4713f9..0fc8419c 100644 --- a/evoagentx/optimizers/aflow/types.py +++ b/evoagentx/optimizers/aflow/types.py @@ -5,12 +5,12 @@ import math import re from collections import Counter -from dataclasses import asdict, dataclass, field -from typing import Any, Optional +from dataclasses import asdict, dataclass +from typing import Any from urllib.parse import urlsplit, urlunsplit SCHEMA_VERSION = 1 -_SECRET = re.compile(r'key|secret|password|token|authorization|credential', re.I) +_SECRET = re.compile(r'api_?key|secret|password|authorization|credential|(?:^|_)(?:key|token)$', re.IGNORECASE) def canonical(value: Any) -> str: @@ -31,11 +31,16 @@ def public_model_config(value: Any) -> Any: result = {} for key, item in value.items(): # Generation limits are behavior, whereas authentication tokens are secrets. - if _SECRET.search(str(key)) and str(key) not in ('max_tokens', 'max_completion_tokens'): + normalized_key = str(key).lower().replace('-', '_') + if _SECRET.search(normalized_key) and normalized_key not in ('max_tokens', 'max_completion_tokens'): continue - if str(key) in ('base_url', 'api_base', 'endpoint') and isinstance(item, str): + if normalized_key.endswith(('base_url', 'api_base', 'endpoint')) and isinstance(item, str): url = urlsplit(item) - item = urlunsplit((url.scheme, url.hostname or '', url.path, '', '')) + host = url.hostname or '' + if ':' in host: + host = f'[{host}]' + authority = f'{host}:{url.port}' if url.port is not None else host + item = urlunsplit((url.scheme, authority, url.path, '', '')) result[str(key)] = public_model_config(item) return result if isinstance(value, (list, tuple)): @@ -77,15 +82,15 @@ class ReliableTrialConfig: max_proposals: int = 60 max_trials: int = 21 duplicate_limit: int = 10 - deadline_seconds: Optional[float] = None - attempt_timeout: Optional[float] = None - proposal_timeout: Optional[float] = None - max_known_cost: Optional[float] = None - example_cost_bound: Optional[float] = None - proposal_cost_bound: Optional[float] = None + deadline_seconds: float | None = None + attempt_timeout: float | None = None + proposal_timeout: float | None = None + max_known_cost: float | None = None + example_cost_bound: float | None = None + proposal_cost_bound: float | None = None retryable_errors: tuple = ('builtins.TimeoutError', 'builtins.ConnectionError') convergence_patience: int = 5 - metric_id: Optional[str] = None + metric_id: str | None = None recover_owner: bool = False def __post_init__(self): @@ -176,6 +181,43 @@ def to_dict(self) -> dict: value['config'] = self.config.identity_dict() return value + @classmethod + def from_dict(cls, value): + """Reconstruct a versioned plan for offline inspection and explicit recovery. + + Resume still compares the live benchmark/model configuration with this + plan. Loading a saved plan alone never proves current data provenance. + """ + value = dict(value) + if value.get('schema_version') != SCHEMA_VERSION: + raise ValueError('unsupported plan schema') + config = ReliableTrialConfig(**value['config']) + examples = tuple(ExampleIdentity(**e) for e in value['examples']) + if not examples or [e.index for e in examples] != list(range(len(examples))): + raise ValueError('invalid ordered example coverage') + occurrences = Counter() + for example in examples: + key = canonical(example.original_id) + if example.occurrence != occurrences[key]: + raise ValueError('invalid example occurrence identity') + if not re.fullmatch(r'[0-9a-f]{64}', example.content_digest): + raise ValueError('invalid example content digest') + occurrences[key] += 1 + if value['split'] not in ('validation', 'test') or not value['dataset'] or not value['metric_id']: + raise ValueError('invalid dataset/split/metric identity') + model = public_model_config(value['model_config']) + if canonical(model) != canonical(value['model_config']): + raise ValueError('saved model configuration contains credentials') + identity = digest({'schema': SCHEMA_VERSION, 'dataset': value['dataset'], 'split': value['split'], + 'examples': [asdict(e) for e in examples], 'model': model, + 'metric': value['metric_id'], 'policy': config.identity_dict()}) + if value['identity'] != identity: + raise ValueError('saved plan identity mismatch') + result = cls(value['dataset'], value['split'], examples, model, value['metric_id'], config, identity) + if canonical(result.to_dict()) != canonical(value): + raise ValueError('unsupported or inconsistent plan fields') + return result + def verify_data(self, data: list): """Reject mutated/reordered examples before any new attempt is admitted.""" if len(data) != len(self.examples) or any(digest(d) != e.content_digest for d, e in zip(data, self.examples)): @@ -199,8 +241,8 @@ class Observation: replicate: int attempt: int status: str - score: Optional[float] = None - error_type: Optional[str] = None + score: float | None = None + error_type: str | None = None known_cost: float = 0.0 pricing: str = 'unobserved' input_tokens: int = 0 @@ -253,8 +295,8 @@ class TrialSummary: requested: int scored: int eligible: bool - score: Optional[float] - partial_score: Optional[float] + score: float | None + partial_score: float | None observation_ids: tuple known_cost: float pricing: str @@ -285,7 +327,7 @@ def build(cls, plan, trial_id, round_number, observations): raise ValueError('conflicting attempt coordinates') scored = [o.score for o in latest.values() if o.status == 'scored'] complete = len(scored) == plan.requested - mean = math.fsum(scored) / len(scored) if scored else None + mean = math.fsum(score / len(scored) for score in scored) if scored else None return cls(trial_id, round_number, plan.identity, plan.split, plan.requested, len(scored), complete, mean if complete else None, mean, tuple(sorted(ids)), cost, pricing, dict(Counter(o.status for o in latest.values()))) @@ -298,17 +340,31 @@ def from_dict(cls, value): raise ValueError('unsupported summary schema') value['observation_ids'] = tuple(value['observation_ids']) result = cls(**value) + if not isinstance(result.eligible, bool) or not isinstance(result.requested, int) or not isinstance(result.scored, int): + raise TypeError('invalid summary coverage types') + if result.round < 0 or result.scored < 0 or result.scored > result.requested: + raise ValueError('invalid summary coverage counts') if result.eligible != (result.scored == result.requested and result.requested > 0): raise ValueError('inconsistent summary coverage') if result.eligible: finite_score(result.score) elif result.score is not None: raise ValueError('incomplete summary has a ranking score') + if result.partial_score is not None: + finite_score(result.partial_score) + if result.eligible and result.partial_score != result.score: + raise ValueError('summary diagnostic score disagrees with committed score') + if result.pricing not in ('known', 'unknown', 'unobserved') or finite_score(result.known_cost) < 0: + raise ValueError('invalid summary accounting') + if tuple(sorted(set(result.observation_ids))) != result.observation_ids: + raise ValueError('duplicate or unordered summary observations') return result def to_dict(self): """Return the committed summary payload.""" - return asdict(self) + value = asdict(self) + value['observation_ids'] = list(self.observation_ids) + return value def improves(self, parent, config): """Compare only complete validation evidence under the exact same plan.""" diff --git a/evoagentx/optimizers/aflow_optimizer.py b/evoagentx/optimizers/aflow_optimizer.py index b9bcbe18..9f0ed8fd 100644 --- a/evoagentx/optimizers/aflow_optimizer.py +++ b/evoagentx/optimizers/aflow_optimizer.py @@ -6,7 +6,7 @@ import asyncio import numpy as np from tqdm import tqdm -from typing import List, Any +from typing import List, Any, Optional from pydantic import Field from ..core.logging import logger @@ -18,6 +18,7 @@ from ..utils.aflow_utils.evaluation_utils import EvaluationUtils from ..utils.aflow_utils.graph_utils import GraphUtils, OPERATOR_MAP from ..utils.aflow_utils.convergence_utils import ConvergenceUtils +from .aflow import ReliableTrialConfig class GraphOptimizeOutput(LLMOutputParser): @@ -63,6 +64,8 @@ class AFlowOptimizer(BaseModule): validation_rounds: int = Field(default=5, description="Run the workflow for `validation_rounds` times to evaluate the performance on the validation set.") eval_rounds: int = Field(default=3, description="Run the workflow for `eval_rounds` times to evaluate the performance on the test set.") check_convergence: bool = Field(default=True, description="Whether to check for convergence.") + reliable_trials: Optional[ReliableTrialConfig] = Field(default=None, description="Opt-in durable AFlow trial policy.") + max_proposal_attempts: int = Field(default=20, ge=1, description="Bound duplicate proposals in legacy mode.") def init_module(self, **kwargs): @@ -78,14 +81,17 @@ def init_module(self, **kwargs): self.graph = None self.round = self.initial_round - if self.round == 0: + self._baseline_complete = False + if self.reliable_trials is not None and self.initial_round != 0: + raise ValueError("Reliable trials resume by experiment identity, not initial_round") + if self.round == 0 and self.reliable_trials is None: round_zero_path = os.path.join(self.root_path, f"round_{self.round}") os.makedirs(round_zero_path, exist_ok=True) shutil.copy2(os.path.join(self.graph_path, "graph.py"), os.path.join(round_zero_path, "graph.py")) shutil.copy2(os.path.join(self.graph_path, "prompt.py"), os.path.join(round_zero_path, "prompt.py")) self.graph_utils.update_prompt_import(os.path.join(round_zero_path, "graph.py"), round_zero_path) - if not os.path.exists(os.path.join(self.root_path, f"round_{self.round}")): + if self.reliable_trials is None and not os.path.exists(os.path.join(self.root_path, f"round_{self.round}")): raise ValueError(f"Round {self.round} does not exist in {self.root_path}") if self.optimizer_llm is None: @@ -104,10 +110,18 @@ def optimize(self, benchmark: Benchmark): benchmark: The benchmark to evaluate the workflow against """ self.benchmark = benchmark + if self.reliable_trials is not None: + return asyncio.run(self.optimize_async(benchmark)) for _ in range(self.max_rounds): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - score = loop.run_until_complete(self._execute_with_retry(self._optimize_graph)) + try: + score = loop.run_until_complete(self._execute_with_retry(self._optimize_graph)) + finally: + loop.close() + if score is None: + logger.warning("Optimization round exhausted without completed evidence") + break self.round += 1 logger.info(f"Score for round {self.round}: {score}") if self._check_convergence(): @@ -116,6 +130,17 @@ def optimize(self, benchmark: Benchmark): logger.info(f"Max rounds reached: {self.max_rounds}, stopping optimization.") break + async def optimize_async(self, benchmark: Benchmark): + """Run or resume opt-in reliable evolution in the caller's event loop.""" + if self.reliable_trials is None: + raise ValueError("optimize_async requires reliable_trials configuration") + from .aflow.runner import ReliableAFlowRunner + self.benchmark = benchmark + self.trial_result = await ReliableAFlowRunner(self, benchmark).run() + if self.trial_result.best_round is not None: + self.round = self.trial_result.best_round + return self.trial_result + def test(self, benchmark: Benchmark, test_rounds: List[int] = None): """Run the test evaluation on optimized workflows. @@ -127,6 +152,8 @@ def test(self, benchmark: Benchmark, test_rounds: List[int] = None): test_rounds: Specific round numbers to test, or None to use the best round """ self.benchmark = benchmark + if self.reliable_trials is not None: + return asyncio.run(self.test_async(benchmark, test_rounds)) if test_rounds is None: best_round = self._load_best_round() logger.info(f"No test rounds provided, using best round: {best_round}") @@ -134,7 +161,18 @@ def test(self, benchmark: Benchmark, test_rounds: List[int] = None): for _ in tqdm(range(self.eval_rounds)): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - loop.run_until_complete(self._run_test(test_rounds)) + try: + loop.run_until_complete(self._run_test(test_rounds)) + finally: + loop.close() + + async def test_async(self, benchmark: Benchmark, test_rounds: List[int] = None): + """Evaluate a separate reliable test plan without changing parent evidence.""" + if self.reliable_trials is None: + raise ValueError("test_async requires reliable_trials configuration") + from .aflow.runner import ReliableAFlowRunner + self.benchmark = benchmark + return await ReliableAFlowRunner(self, benchmark).test(test_rounds) async def _execute_with_retry(self, func: callable, max_retries: int = 3) -> Any: @@ -171,8 +209,9 @@ async def _optimize_graph(self) -> float: graph_path = self.root_path data = self.data_utils.load_results(graph_path) - if self.round == 0: + if self.round == 0 and not self._baseline_complete: self.avg_score = await self._handle_initial_round(graph_path, validation_n, data) + self._baseline_complete = True return await self._handle_optimization_round(graph_path, validation_n, data) @@ -186,7 +225,7 @@ async def _handle_optimization_round(self, graph_path: str, validation_n: int, d directory = self.graph_utils.create_round_directory(graph_path, self.round + 1) - while True: + for _ in range(self.max_proposal_attempts): sample = self._get_optimization_sample() prompt, graph_load = self.graph_utils.read_graph_files(sample["round"], graph_path) graph = self.graph_utils.extract_solve_graph(graph_load) @@ -209,6 +248,8 @@ async def _handle_optimization_round(self, graph_path: str, validation_n: int, d if self.experience_utils.check_modification(processed_experience, response['modification'], sample["round"]): break + else: + raise RuntimeError("Duplicate proposal attempt budget exhausted") # Save and evaluate results avg_score = await self._evaluate_and_save_optimization_results(directory, response, sample, data, validation_n) @@ -269,6 +310,16 @@ async def _evaluate_and_save_optimization_results(self, directory: str, response def _load_best_round(self) -> int: """Load the best round""" + if self.reliable_trials is not None: + from .aflow.runner import ReliableAFlowRunner + from .aflow.store import TrialStore + from .aflow.evidence import EvidenceView + runner = ReliableAFlowRunner(self, self.benchmark) + with TrialStore(runner.path, runner.plan) as store: + best = EvidenceView(store).best() + if best is None: + raise ValueError("No eligible reliable validation trial") + return best.round ranked_scores = self.data_utils._load_scores() return ranked_scores[0]["round"] @@ -278,8 +329,14 @@ async def _run_test(self, test_rounds: List[int]): logger.info("Running test evaluation...") graph_path = self.root_path - data = self.data_utils.load_results(graph_path) - json_file_path = self.data_utils.get_results_file_path(graph_path) + json_file_path = os.path.join(graph_path, "test_results.json") + import json + data = [] + if os.path.exists(json_file_path): + with open(json_file_path, encoding="utf-8") as stream: + data = json.load(stream) + if not isinstance(data, list): + raise ValueError("Invalid test results") scores = [] # for round in tqdm(test_rounds, desc="Testing"): @@ -293,6 +350,7 @@ async def _run_test(self, test_rounds: List[int]): scores.append(score) new_data = self.data_utils.create_result_data(round, score, avg_cost, total_cost) + new_data['split'] = 'test' data.append(new_data) logger.info(f"Test round {round} score: {score}, avg_cost: {avg_cost}, total_cost: {total_cost}") @@ -300,4 +358,4 @@ async def _run_test(self, test_rounds: List[int]): self.data_utils.save_results(json_file_path, data) logger.info(f"Test round {round} avg_score: {np.mean(scores)}") - return np.mean(scores) \ No newline at end of file + return np.mean(scores) diff --git a/evoagentx/utils/aflow_utils/convergence_utils.py b/evoagentx/utils/aflow_utils/convergence_utils.py index ff29c272..3b72c6e1 100644 --- a/evoagentx/utils/aflow_utils/convergence_utils.py +++ b/evoagentx/utils/aflow_utils/convergence_utils.py @@ -41,6 +41,8 @@ def process_rounds(self): self.data = self.load_data(root_path=self.root_path) rounds = {} for entry in self.data: + if entry.get("split", "validation") != "validation": + continue round_number = entry["round"] score = entry["score"] if round_number not in rounds: diff --git a/evoagentx/utils/aflow_utils/data_utils.py b/evoagentx/utils/aflow_utils/data_utils.py index 43d513bd..cbb70b4d 100644 --- a/evoagentx/utils/aflow_utils/data_utils.py +++ b/evoagentx/utils/aflow_utils/data_utils.py @@ -192,6 +192,9 @@ def _load_scores(self, path=None, mode="Graph"): self.top_scores = [] data = load_json(result_file, type="json") + data = [row for row in data if row.get("split", "validation") == "validation"] + if not data: + return self.top_scores df = pd.DataFrame(data) scores_per_round = df.groupby("round")["score"].mean().to_dict() @@ -218,4 +221,3 @@ def test_check(): test_check() """ return tester_function - \ No newline at end of file diff --git a/evoagentx/utils/aflow_utils/evaluation_utils.py b/evoagentx/utils/aflow_utils/evaluation_utils.py index 1d2a08c3..3cd3de35 100644 --- a/evoagentx/utils/aflow_utils/evaluation_utils.py +++ b/evoagentx/utils/aflow_utils/evaluation_utils.py @@ -13,6 +13,9 @@ async def evaluate_graph_async(self, optimizer, validation_n, data, initial=Fals evaluator = AFlowEvaluator(llm=optimizer.executor_llm) sum_score = 0 + completed = 0 + if validation_n < 1: + raise ValueError("validation_n must be positive") for _ in range(validation_n): @@ -26,16 +29,19 @@ async def evaluate_graph_async(self, optimizer, validation_n, data, initial=Fals optimizer.data_utils.save_results(result_path, data) sum_score += score + completed += 1 if all_failed: logger.warning(f"All test cases failed in round {cur_round}. Stopping evaluation for this round.") break - return sum_score / validation_n + # Legacy selection averages persisted replicates; feedback must use the + # same denominator. Reliable mode separately requires complete coverage. + return sum_score / completed async def evaluate_graph_test_async(self, optimizer): evaluator = AFlowEvaluator(llm=optimizer.executor_llm) with suppress_logger_info(): score, avg_cost, total_cost, all_failed = await evaluator.graph_evaluate_async(optimizer.benchmark, optimizer.graph, is_test=True) - return score, avg_cost, total_cost \ No newline at end of file + return score, avg_cost, total_cost diff --git a/tests/src/optimizers/test_aflow_native_trials.py b/tests/src/optimizers/test_aflow_native_trials.py new file mode 100644 index 00000000..5ae65954 --- /dev/null +++ b/tests/src/optimizers/test_aflow_native_trials.py @@ -0,0 +1,220 @@ +"""Native AFlowOptimizer/HotPotQA regressions; only provider I/O is scripted.""" +import asyncio +import json +from pathlib import Path + +import pytest + +from evoagentx.benchmark.hotpotqa import AFlowHotPotQA +from evoagentx.core.registry import register_model +from evoagentx.models.base_model import BaseLLM +from evoagentx.models.model_configs import LLMConfig +from evoagentx.models.model_utils import Cost, cost_manager +from evoagentx.optimizers.aflow import ReliableTrialConfig +from evoagentx.optimizers.aflow_optimizer import AFlowOptimizer + +PROVIDER_STATE = {} + +GRAPH = '''class Workflow: + def __init__(self, name, llm_config, benchmark): + self.llm = create_llm_instance(llm_config) + async def __call__(self, problem): + response = await self.llm.async_generate(prompt=problem, parse_mode="str") + return response.content +''' + + +@register_model(LLMConfig) +class TrialFixtureProvider(BaseLLM): + def init_model(self): + self.state = PROVIDER_STATE + def formulate_messages(self, prompts, system_messages=None): + return [[{'role': 'user', 'content': p}] for p in prompts] + def single_generate(self, messages, **kwargs): + raise AssertionError('only async provider boundary is supported') + def batch_generate(self, batch_messages, **kwargs): + raise AssertionError('only async provider boundary is supported') + async def single_generate_async(self, messages, **kwargs): + await asyncio.sleep(0) + if 'You are building a Graph' in messages[-1]['content']: + self.state['proposal'] += 1 + cost_manager.update_cost(Cost(cost=.01), 'proposal-fixture') + if self.state['proposal'] <= self.state['outage']: + raise TimeoutError('scripted provider interruption') + self.state['mode'] = 'right' + graph = GRAPH + '\n# candidate generation\n' + return 'Use exact answer' + graph + '# no prompts' + self.state['execution'] += 1 + cost_manager.update_cost(Cost(cost=.01), 'execution-fixture') + if self.state['mode'] == 'executor_outage': + raise TimeoutError('scripted executor outage') + return 'Paris' if self.state['mode'] == 'right' else 'wrong' + + +def setup(tmp_path, monkeypatch, reliable=True, **kwargs): + if reliable: + assert 'reliable_trials' in AFlowOptimizer.model_fields, 'explicit reliable trial option missing' + monkeypatch.chdir(tmp_path) + monkeypatch.syspath_prepend(str(tmp_path)) + seed = tmp_path / 'seed' + seed.mkdir(exist_ok=True) + (seed / 'graph.py').write_text('from evoagentx.models.model_utils import create_llm_instance\n' + GRAPH) + (seed / 'prompt.py').write_text('# seed prompts\n') + for split in ('validate', 'test'): + (tmp_path / f'hotpotqa_{split}.jsonl').write_text(''.join(json.dumps({'_id': str(i), 'question': q, 'answer': 'Paris', 'context': []}) + '\n' for i, q in enumerate(['first', 'second']))) + benchmark = AFlowHotPotQA(path=str(tmp_path), mode='all') + PROVIDER_STATE.clear() + PROVIDER_STATE.update(mode='wrong', execution=0, proposal=0, outage=0) + llm = TrialFixtureProvider(LLMConfig(llm_type='TrialFixtureProvider', model='local-fixture')) + config = ReliableTrialConfig(replicates=2, max_proposals=4, duplicate_limit=2, **kwargs) if reliable else None + optimizer = AFlowOptimizer(question_type='qa', graph_path='seed', optimized_path='results', + optimizer_llm=llm, validation_rounds=2, eval_rounds=1, max_rounds=2, + check_convergence=False, reliable_trials=config) + return optimizer, benchmark, llm + + +def test_native_proposal_retry_never_repeats_completed_baseline_and_summary_is_shared(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + llm.state['outage'] = 1 + result = optimizer.optimize(benchmark) + assert result.status == 'exhausted' + assert result.score == 1 and result.best_round == 1 + assert llm.state['execution'] == 8 # 4 baseline, 4 candidate; duplicate candidates not evaluated + assert llm.state['proposal'] == 4 + rows = json.loads(Path('results/results.json').read_text()) + assert [(r['round'], r['score']) for r in rows] == [(0, 0), (1, 1)] + experience = json.loads(Path('results/round_1/experience.json').read_text()) + assert experience['before'] == 0 and experience['after'] == 1 and experience['succeed'] + assert optimizer._load_best_round() == 1 + summaries = list(Path('results/reliable/aflow/trials').glob('*/summary.json')) + assert len(summaries) == 2 + assert all(json.loads(path.read_text())['requested'] == 4 for path in summaries) + + +def test_native_resume_reuses_all_completed_evidence_and_test_is_isolated(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + first = optimizer.optimize(benchmark) + executions = llm.state['execution'] + before = Path('results/results.json').read_bytes() + llm.state['mode'] = 'wrong' + optimizer.test(benchmark, [1]) + assert Path('results/results.json').read_bytes() == before + assert json.loads(Path('results/test_results.json').read_text())[0]['score'] == 0 + second = optimizer.optimize(benchmark) + assert second.score == first.score and second.best_trial_id == first.best_trial_id + assert llm.state['execution'] == executions + 4 # separate reliable test plan has 2 replicates + assert optimizer._load_best_round() == 1 + + +def test_native_plan_rejects_model_change_without_external_call(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + optimizer.optimize(benchmark) + count = llm.state['execution'] + llm.config.temperature = .9 + with pytest.raises(ValueError, match='identity'): + optimizer.optimize(benchmark) + assert llm.state['execution'] == count + + +def test_legacy_test_results_do_not_change_validation_ranking(tmp_path, monkeypatch): + optimizer, benchmark, _llm = setup(tmp_path, monkeypatch, reliable=False) + optimizer.data_utils.save_results('results/results.json', [optimizer.data_utils.create_result_data(0, 1, 0, 0)]) + optimizer.test(benchmark, [0]) + assert optimizer.data_utils._load_scores() == [{'round': 0, 'score': 1}] + assert Path('results/test_results.json').exists() + + +def test_native_exports_repair_after_failure_without_repeating_evidence(tmp_path, monkeypatch): + from evoagentx.optimizers.aflow import evidence + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + original = evidence.atomic_json + def fail_results(path, value): + if str(path).endswith('/results.json'): + raise OSError('scripted export failure') + return original(path, value) + monkeypatch.setattr(evidence, 'atomic_json', fail_results) + first = optimizer.optimize(benchmark) + assert first.score == 1 and first.export_error == 'builtins.OSError' + calls = llm.state['execution'] + monkeypatch.setattr(evidence, 'atomic_json', original) + repaired = optimizer.optimize(benchmark) + assert repaired.score == 1 and repaired.export_error is None + assert llm.state['execution'] == calls + report = json.loads(Path('results/reliable/aflow/reports/candidate_1.json').read_text()) + assert [row['score'] for row in report['examples']] == [1, 1, 1, 1] + assert report['ranking_eligible'] + + +def test_legacy_tuple_cost_ignores_sibling_context(tmp_path, monkeypatch): + from evoagentx.evaluators.aflow_evaluator import AFlowEvaluator + optimizer, benchmark, llm = setup(tmp_path, monkeypatch, reliable=False) + graph = optimizer.graph_utils.load_graph(0, 'results') + async def run(): + async def sibling(): + await asyncio.sleep(0) + cost_manager.update_cost(Cost(cost=10), 'sibling') + result, _ = await asyncio.gather(AFlowEvaluator(llm).graph_evaluate_async(benchmark, graph), sibling()) + return result + score, avg_cost, total_cost, all_failed = asyncio.run(run()) + assert score == 0 and not all_failed + assert avg_cost == pytest.approx(.01) and total_cost == pytest.approx(.02) + + +def test_native_provider_outage_is_incomplete_evidence_without_failed_strategy(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + llm.state['mode'] = 'executor_outage' + result = optimizer.optimize(benchmark) + assert result.status == 'incomplete' and result.score is None + assert llm.state['proposal'] == 0 and llm.state['execution'] == 8 + assert not Path('results/round_1/experience.json').exists() + report = json.loads(Path('results/reliable/aflow/reports/baseline.json').read_text()) + assert not report['ranking_eligible'] + assert all(row['status'] == 'retryable' and row['score'] is None for row in report['examples']) + + +@pytest.mark.parametrize('kind', ['humaneval', 'mbpp', 'math']) +def test_native_task_failure_is_scored_zero_across_aflow_benchmarks(tmp_path, kind): + from evoagentx.benchmark.humaneval import AFlowHumanEval + from evoagentx.benchmark.math_benchmark import AFlowMATH + from evoagentx.benchmark.mbpp import AFlowMBPP + from evoagentx.optimizers.aflow import AdmissionBudget, EvaluationPlan, TrialStore + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + if kind == 'math': + data = [{'id': 'local', 'problem': 'What is 1+1?', 'solution': r'\boxed{2}'}] + benchmark_class = AFlowMATH + prediction = r'\boxed{3}' + else: + example = {'task_id': 'local', 'prompt': 'def add(a, b):\n', + 'canonical_solution': ' return a + b\n', 'code': 'def add(a, b):\n return a+b\n', + 'test': 'def check(candidate):\n assert candidate(1, 2) == 3\n', 'entry_point': 'add'} + data = [example] + benchmark_class = AFlowHumanEval if kind == 'humaneval' else AFlowMBPP + prediction = ' return 0\n' if kind == 'humaneval' else 'def add(a, b):\n return 0\n' + (tmp_path / f'{kind}_public_test.jsonl').write_text(json.dumps({'entry_point': 'add', 'test': example['test']}) + '\n') + (tmp_path / f'{kind}_validate.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in data)) + benchmark = benchmark_class(path=str(tmp_path), mode='dev') + class Graph: + def __init__(self, **kwargs): + pass + async def __call__(self, *args): + return prediction + config = ReliableTrialConfig(concurrency=1) + plan = EvaluationPlan.create(benchmark.name, data, {}, f'local.{kind}', config) + with TrialStore(tmp_path / 'evidence', plan) as store: + store.create_trial('baseline', 0, 'baseline') + summary = asyncio.run(DetailedEvaluator(None).evaluate(benchmark, Graph, data, plan, 'baseline', store, AdmissionBudget(store, config))) + assert summary.eligible and summary.score == 0 + assert store.observations('baseline')[0].status == 'scored' + + +def test_proposal_cost_evidence_survives_cleared_stage_cursor(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch) + llm.state['outage'] = 1 + optimizer.optimize(benchmark) + report = json.loads(Path('results/reliable/aflow/reports/experiment.json').read_text()) + operations = report['operation_accounting'] + proposals = [row for row in operations if row['stage'] == 'proposal'] + assert len(proposals) == 4 + assert sum(row['known_cost'] for row in proposals) == pytest.approx(.04) + assert sum(row['known_cost'] for row in operations) == pytest.approx(.12) + assert all(row['trial_id'] and row['pricing_known'] for row in proposals) diff --git a/tests/src/optimizers/test_aflow_trials.py b/tests/src/optimizers/test_aflow_trials.py index e769413b..df65fa2c 100644 --- a/tests/src/optimizers/test_aflow_trials.py +++ b/tests/src/optimizers/test_aflow_trials.py @@ -8,8 +8,12 @@ def api(): from evoagentx.optimizers.aflow import ( - EvaluationPlan, Observation, ReliableTrialConfig, TrialStore, - TrialSummary, AdmissionBudget, + AdmissionBudget, + EvaluationPlan, + Observation, + ReliableTrialConfig, + TrialStore, + TrialSummary, ) return EvaluationPlan, Observation, ReliableTrialConfig, TrialStore, TrialSummary, AdmissionBudget @@ -58,22 +62,20 @@ def test_store_atomic_identity_observation_idempotence_and_owner_lock(tmp_path): assert len(store.observations('trial')) == 1 with pytest.raises(ValueError, match='conflict'): store.record(replace(obs, score=1)) - with pytest.raises(RuntimeError, match='writer'): - with Store(tmp_path, p): - pass + with pytest.raises(RuntimeError, match='writer'), Store(tmp_path, p): + pass store.record(Obs.scored('trial', p.examples[1], 0, 1, 1)) summary = Summary.build(p, 'trial', 0, store.observations('trial')) store.commit_summary(summary) assert store.summaries()[0].score == .5 - with pytest.raises(ValueError, match='identity'): - with Store(tmp_path, plan(replicates=2)): - pass + with pytest.raises(ValueError, match='identity'), Store(tmp_path, plan(replicates=2)): + pass with Store(tmp_path, p) as store: assert store.summaries()[0].score == .5 def test_started_attempt_requires_explicit_resolution_before_rerun(tmp_path): - *_, Store, _, Budget = api() + *_, Store, _, _Budget = api() p = plan() with Store(tmp_path, p) as store: store.create_trial('trial', 0, 'baseline') @@ -232,9 +234,8 @@ def __init__(self, **kwargs): assert store.summary('trial') is None assert store.observations('trial')[0].status == 'unknown' assert len(store.unknown_attempts()) == 1 - with pytest.raises(RuntimeError, match='recover_owner'): - with Store(tmp_path, p): - pass + with pytest.raises(RuntimeError, match='recover_owner'), Store(tmp_path, p): + pass def test_outer_cancellation_joins_workers_and_records_unknown(tmp_path): @@ -268,3 +269,310 @@ async def run(): assert drained == [1] assert store.summary('trial') is None assert store.unknown_attempts() + + +def test_existing_store_can_be_opened_for_audited_offline_resolution(tmp_path): + *_, Store, _, _ = api() + p = plan() + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + store.start_attempt('trial', p.examples[0], 0, 1) + with Store.open_existing(tmp_path) as store: + assert store.plan.identity == p.identity + unknown = store.unknown_attempts()[0] + store.resolve_unknown(unknown['attempt_id'], 'abandon', 'confirmed terminated; do not repeat') + store.assert_resolved() + + +def test_versioned_plan_reload_rejects_modified_policy_and_schema(tmp_path): + Plan, *_ = api() + payload = plan().to_dict() + assert Plan.from_dict(payload).identity == plan().identity + payload['config']['replicates'] = 5 + with pytest.raises(ValueError, match='identity'): + Plan.from_dict(payload) + payload['schema_version'] = 77 + with pytest.raises(ValueError, match='schema'): + Plan.from_dict(payload) + + +def test_per_example_report_includes_missing_coordinates_without_inventing_scores(tmp_path): + from evoagentx.optimizers.aflow.reporting import TrialReporter + _, Obs, _, Store, Summary, _ = api() + p = plan(replicates=2) + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + store.record(Obs.scored('trial', p.examples[0], 0, 1, 0)) + summary = Summary.build(p, 'trial', 0, store.observations('trial')) + store.commit_summary(summary) + report = TrialReporter(store).trial('trial') + assert report['summary']['score'] is None + assert [row['status'] for row in report['examples']] == ['scored', 'missing', 'missing', 'missing'] + assert report['examples'][0]['score'] == 0 + assert report['examples'][1]['score'] is None + assert len(report['examples']) == 4 + TrialReporter(store).export() + assert json.loads((tmp_path / 'reports' / 'trial.json').read_text()) == report + + +def test_model_endpoint_identity_keeps_port_and_drops_credentials(): + Plan, _, Config, *_ = api() + def make(endpoint): + return Plan.create('fixture', [{'_id': 1}], {'base_url': endpoint}, 'm', Config()) + left = make('https://user:password@localhost:8000/v1?api_key=secret') + right = make('https://localhost:9000/v1') + assert left.identity != right.identity + assert left.model_config['base_url'] == 'https://localhost:8000/v1' + + +def test_summary_publication_failure_resumes_without_repeating_examples(tmp_path, monkeypatch): + import evoagentx.optimizers.aflow.store as storage + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan() + calls = [] + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + calls.append(1) + return 1 + class Graph: + def __init__(self, **kwargs): + pass + original = storage.atomic_json + def fail_summary(path, value): + if str(path).endswith('/summary.json'): + raise OSError('scripted summary storage failure') + return original(path, value) + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + monkeypatch.setattr(storage, 'atomic_json', fail_summary) + with pytest.raises(OSError): + asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + monkeypatch.setattr(storage, 'atomic_json', original) + with Store(tmp_path, p) as store: + summary = asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + assert summary.eligible and summary.score == 1 and len(calls) == 2 + + +def test_late_thread_cost_retains_unknown_and_never_changes_committed_outcome(tmp_path): + import threading + + from evoagentx.models.model_utils import Cost, cost_manager + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan(attempt_timeout=.01, concurrency=1) + release = threading.Event() + finished = threading.Event() + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + def blocking(): + release.wait(2) + cost_manager.update_cost(Cost(cost=.7), 'late-thread') + finished.set() + return 1 + return await asyncio.to_thread(blocking) + class Graph: + def __init__(self, **kwargs): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + before = cost_manager.get_total_cost() + async def run(): + try: + with pytest.raises(RuntimeError, match='unknown'): + await DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config)) + frozen = store.observations('trial')[0] + release.set() + await asyncio.to_thread(finished.wait, 2) + assert store.observations('trial')[0] == frozen + assert frozen.status == 'unknown' and frozen.score is None + assert frozen.known_cost == 0 + assert store.summary('trial') is None + finally: + release.set() + asyncio.run(run()) + assert finished.is_set() + assert cost_manager.get_total_cost() - before == pytest.approx(.7) + + +def test_finite_extreme_scores_keep_finite_aggregate_and_summary_reload_checks_diagnostics(): + _, Obs, _, _, Summary, _ = api() + p = plan() + summary = Summary.build(p, 'trial', 0, [Obs.scored('trial', e, 0, 1, 1e308) for e in p.examples]) + assert summary.score == 1e308 + payload = summary.to_dict() + payload['partial_score'] = float('nan') + with pytest.raises(ValueError): + Summary.from_dict(payload) + + +def test_completed_observation_recovers_pending_cost_reservation_without_reexecution(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + _, Obs, _, Store, Summary, Budget = api() + p = plan(max_known_cost=1, example_cost_bound=.2, proposal_cost_bound=.1) + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + budget = Budget(store, p.config) + for e in p.examples: + obs = Obs.scored('trial', e, 0, 1, 1, known_cost=.1, pricing='known') + budget.admit('example', obs.observation_id) + store.start_attempt('trial', e, 0, 1) + store.record(obs) # crash before budget.finish + store.commit_summary(Summary.build(p, 'trial', 0, store.observations('trial'))) + class NoCalls: + name = 'Fixture' + async def async_evaluate(self, *args): + raise AssertionError('completed external call must not repeat') + with Store(tmp_path, p) as store: + budget = Budget(store, p.config) + summary = asyncio.run(DetailedEvaluator(None).evaluate(NoCalls(), None, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, budget)) + assert summary.score == 1 + assert budget.report()['known_spent'] == pytest.approx(.2) + assert budget.report()['reserved'] == 0 + + +def test_total_admission_budget_and_concurrency_are_bounded(tmp_path): + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + Plan, _, Config, Store, _, Budget = api() + data = [{'_id': i} for i in range(10)] + p = Plan.create('fixture', data, {}, 'v1', Config(concurrency=2, max_example_attempts=3)) + active = 0 + peak = 0 + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + nonlocal active, peak + active += 1 + peak = max(peak, active) + await asyncio.sleep(.001) + active -= 1 + return 1 + class Graph: + def __init__(self, **kwargs): + pass + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + budget = Budget(store, p.config) + summary = asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, data, p, 'trial', store, budget)) + assert summary.score is None and summary.scored == 3 and summary.requested == 10 + assert budget.report()['counts']['example'] == 3 and peak == 2 + + +def test_interrupted_outcome_write_leaves_unknown_instead_of_paid_retry(tmp_path, monkeypatch): + from evoagentx.optimizers.aflow import store as storage + from evoagentx.optimizers.aflow.evaluator import DetailedEvaluator + *_, Store, _, Budget = api() + p = plan(concurrency=1) + class Benchmark: + name = 'Fixture' + async def async_evaluate(self, graph, example): + return 1 + class Graph: + def __init__(self, **kwargs): + pass + original = storage.atomic_json + def fail_outcome(path, value): + if '/observations/' in str(path): + raise OSError('scripted outcome publication failure') + return original(path, value) + with Store(tmp_path, p) as store: + store.create_trial('trial', 0, 'baseline') + monkeypatch.setattr(storage, 'atomic_json', fail_outcome) + with pytest.raises(OSError): + asyncio.run(DetailedEvaluator(None).evaluate(Benchmark(), Graph, + [{'_id': 'same', 'answer': 'a'}, {'_id': 'same', 'answer': 'b'}], p, 'trial', store, Budget(store, p.config))) + monkeypatch.setattr(storage, 'atomic_json', original) + with Store(tmp_path, p) as store: + assert len(store.unknown_attempts()) == 1 + assert store.observations('trial') == [] + with pytest.raises(RuntimeError, match='unknown'): + store.assert_resolved() + + +def test_artifact_publish_interruption_never_mixes_graph_prompt_generations(tmp_path, monkeypatch): + from evoagentx.optimizers.aflow import store as storage + *_, Store, _, _ = api() + with Store(tmp_path, plan()) as store: + store.create_trial('trial', 0, 'baseline') + original = storage.os.rename + def fail_rename(source, destination): + raise OSError('scripted generation publication failure') + monkeypatch.setattr(storage.os, 'rename', fail_rename) + with pytest.raises(OSError): + store.stage_artifacts('trial', 'graph', 'prompt') + assert not (tmp_path / 'trials' / 'trial' / 'artifacts').exists() + monkeypatch.setattr(storage.os, 'rename', original) + store.stage_artifacts('trial', 'new graph', 'new prompt') + assert store.read_artifacts('trial')[:2] == ('new graph', 'new prompt') + + +@pytest.mark.parametrize('provider', ['openrouter', 'novita', 'siliconflow', 'aliyun', 'litellm']) +def test_existing_unpriced_provider_fallbacks_emit_unknown_pricing(provider): + from types import SimpleNamespace + + from openai.types import CompletionUsage + + from evoagentx.models.model_utils import cost_manager + usage = CompletionUsage(prompt_tokens=2, completion_tokens=1, total_tokens=3) + seen = [] + with cost_manager.observe(seen.append): + if provider == 'aliyun': + from evoagentx.models.aliyun_model import AliyunLLM + cost = AliyunLLM._compute_cost(SimpleNamespace(_has_pricing=False), usage) + cost_manager.update_cost(cost, 'unpriced') + elif provider == 'litellm': + from evoagentx.models.litellm_model import LiteLLM + from evoagentx.models.model_configs import LiteLLMConfig + llm = object.__new__(LiteLLM) + llm.config = LiteLLMConfig(model='unpriced-fixture-no-such-model', is_local=False) + cost_manager.update_cost(llm._compute_cost(usage), 'unpriced') + else: + from evoagentx.models.novita_model import NovitaLLM + from evoagentx.models.openrouter_model import OpenRouterLLM + from evoagentx.models.siliconflow_model import SiliconFlowLLM + cls = {'openrouter': OpenRouterLLM, 'novita': NovitaLLM, 'siliconflow': SiliconFlowLLM}[provider] + cls._update_cost(SimpleNamespace(config=SimpleNamespace(model='unpriced')), + SimpleNamespace(id='local', usage=usage)) + assert len(seen) == 1 and seen[0].pricing == 'unknown' and seen[0].cost is None + assert seen[0].input_tokens == 2 and seen[0].output_tokens == 1 + + +def test_model_identity_retains_tokenizer_behavior_and_sanitizes_nested_headers_endpoints(): + Plan, _, Config, *_ = api() + model = {'model': 'local', 'tokenizer': 'first', 'max_tokens': 20, + 'azure_endpoint': 'https://user:secret@host:8000/v1?api_key=hidden', + 'default_headers': {'X-Api-Key': 'hidden-key', 'Authorization': 'Bearer hidden'}} + left = Plan.create('fixture', [{'_id': 1}], model, 'v1', Config()) + model['tokenizer'] = 'second' + right = Plan.create('fixture', [{'_id': 1}], model, 'v1', Config()) + assert left.identity != right.identity + assert left.model_config['azure_endpoint'] == 'https://host:8000/v1' + assert left.model_config['default_headers'] == {} + assert 'hidden' not in json.dumps(left.to_dict()) + + +def test_current_live_stopping_writer_cannot_be_overridden_and_dead_recovery_is_audited(tmp_path): + import os + from dataclasses import replace + + from evoagentx.optimizers.aflow.store import atomic_json + *_, Store, _, _ = api() + p = plan() + with Store(tmp_path, p): + pass + owner = json.loads((tmp_path / 'owner.json').read_text()) + owner.update(status='stopping', pid=os.getpid()) + atomic_json(tmp_path / 'owner.json', owner) + recovery = replace(p, config=replace(p.config, recover_owner=True)) + with pytest.raises(RuntimeError, match='still be running'), Store(tmp_path, recovery): + pass + owner['pid'] = 99999999 + atomic_json(tmp_path / 'owner.json', owner) + with Store(tmp_path, recovery) as store: + assert store.audit()[-1]['action'] == 'recover_owner' From 25c81530fa2277dd697debb2e768ec8f24591fba Mon Sep 17 00:00:00 2001 From: Cookie0103 <258013390+Cookie0103@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:24:50 +0900 Subject: [PATCH 3/4] feat: feed matched validation diagnostics into AFlow planning --- docs/optimizers/aflow_reliable_trials.md | 30 +++ evoagentx/optimizers/aflow/evidence.py | 21 +- evoagentx/optimizers/aflow/feedback.py | 203 ++++++++++++++++++ evoagentx/optimizers/aflow/reporting.py | 11 + evoagentx/optimizers/aflow/runner.py | 9 +- evoagentx/optimizers/aflow/types.py | 7 +- tests/src/optimizers/test_aflow_feedback.py | 167 ++++++++++++++ .../optimizers/test_aflow_native_trials.py | 61 ++++++ 8 files changed, 492 insertions(+), 17 deletions(-) create mode 100644 evoagentx/optimizers/aflow/feedback.py create mode 100644 tests/src/optimizers/test_aflow_feedback.py diff --git a/docs/optimizers/aflow_reliable_trials.md b/docs/optimizers/aflow_reliable_trials.md index e9b971f3..ac98b4cc 100644 --- a/docs/optimizers/aflow_reliable_trials.md +++ b/docs/optimizers/aflow_reliable_trials.md @@ -136,3 +136,33 @@ isolating sibling asyncio contexts. `asyncio.to_thread` propagates the observer; raw threads, external processes and providers bypassing `CostManager.update_cost` are unsupported accounting paths. Missing events/prices remain unobserved or unknown rather than known zero. + +## Diagnostic evidence in planning + +Reliable graph-proposal prompts include a bounded `validation_diagnostics` JSON +payload. It matches committed parent/candidate validation outcomes by original ID, +occurrence and replicate under the exact same plan. Equal means can therefore +retain distinct observed improvements/regressions/ties. Metric direction controls +these labels; score deltas retain their numeric sign. Missing and infrastructure +outcomes have separate coverage categories. An incomplete trial contributes +execution diagnostics and cannot support task-regression conclusions. Recovered +retry failures are counted as execution diagnostics, without blaming a strategy. + +`feedback_max_examples` defaults to 12 across the payload, and +`feedback_max_characters` defaults to 12000 including the JSON tags (minimum 512). +Selection uses recent candidate trials first, then fixed plan order. The payload +states omitted comparison/example counts; if detailed evidence cannot fit, it +explicitly reports unavailable detail and scalar-only summaries. Oversized IDs are +omitted as complete records rather than silently changing their identity. + +The payload contains IDs, observed scores, typed status categories and scoped +recorded-attempt cost deltas. It includes no raw labels or exception tracebacks. +Unknown pricing keeps the complete cost delta unknown; an observed known subtotal +is identified separately. Overflowing differences receive an explicit marker and +never produce nonfinite JSON. These are diagnostic associations, not causal or +agent-step attribution, and do not change the committed promotion score. + +The current bounded view is exported under `planner_feedback` in the experiment +report. Each proposal intent persists the exact payload sent to that provider; +`proposal_feedback` retains these historical snapshots even after later trials +change the current view. Test outcomes never enter either validation payload. diff --git a/evoagentx/optimizers/aflow/evidence.py b/evoagentx/optimizers/aflow/evidence.py index 0ac764fd..daf2d12f 100644 --- a/evoagentx/optimizers/aflow/evidence.py +++ b/evoagentx/optimizers/aflow/evidence.py @@ -102,18 +102,15 @@ def feedback(self): 'scored': summary.scored, 'outcomes': summary.outcomes}) return feedback - def prompt_feedback(self, parent_id): - """Present measured task results separately from infrastructure diagnostics.""" - rows = [r for r in self.feedback() if r['parent_id'] == parent_id] - if not rows: - return 'No completed candidate evidence for this parent.' - lines = [] - for row in rows: - if row['evidence'] == 'inconclusive': - lines.append(f"Infrastructure/incomplete evidence for {row['trial_id']}; no task-strategy conclusion.") - else: - lines.append(f"{row['evidence'].capitalize()} task evidence: {row['modification']} (score {row['after']}).") - return '\n'.join(lines) + def planner_feedback(self, parent_id): + """Return bounded matched diagnostics shared by planner and report consumers.""" + from .feedback import MatchedFeedback + return MatchedFeedback(self.store).payload(parent_id) + + def prompt_feedback(self, parent_id, payload=None): + """Render the exact persisted proposal evidence without task-cause claims.""" + from .feedback import MatchedFeedback + return MatchedFeedback.render(self.planner_feedback(parent_id) if payload is None else payload) def converged(self): """Count only comparable committed trials since the last strict improvement.""" diff --git a/evoagentx/optimizers/aflow/feedback.py b/evoagentx/optimizers/aflow/feedback.py new file mode 100644 index 00000000..3eb422a5 --- /dev/null +++ b/evoagentx/optimizers/aflow/feedback.py @@ -0,0 +1,203 @@ +"""Bounded matched validation diagnostics for AFlow's next graph proposal. + +Observed score changes identify examples worth inspecting. They do not establish +causes, step-level provenance, statistical superiority or a better agent policy. +""" + +import math +from collections import Counter, defaultdict + +from .types import SCHEMA_VERSION, canonical + +OPEN_TAG = '' +CLOSE_TAG = '' + + +def finite_difference(after, before): + """Represent unavailable or overflowing differences without nonfinite JSON.""" + if after is None or before is None: + return None, 'unavailable' + value = after - before + return (value, 'finite') if math.isfinite(value) else (None, 'overflow') + + +def finite_total(values): + """Sum observed nonnegative costs without emitting infinity on overflow.""" + try: + total = math.fsum(values) + except OverflowError: + return None + return total if math.isfinite(total) else None + + +class MatchedFeedback: + """Compare exact committed plans, then apply deterministic output budgets.""" + + def __init__(self, store): + self.store = store + self.plan = store.plan + self.config = self.plan.config + self._expected = { + (canonical(example.original_id), example.occurrence, replicate): example + for replicate in range(self.config.replicates) for example in self.plan.examples + } + + def _history(self, trial_id): + """Match IDs plus occurrence/replicate, validating exact plan membership.""" + histories = defaultdict(list) + for observation in self.store.observations(trial_id): + key = (canonical(observation.example_id), observation.occurrence, observation.replicate) + example = self._expected.get(key) + if example is None or observation.example_key != example.key: + raise ValueError('matched feedback observation identity mismatch') + histories[key].append(observation) + for values in histories.values(): + values.sort(key=lambda observation: observation.attempt) + return histories + + @staticmethod + def _cost_delta(parent, child): + """Separate known observed subtotals from a complete priced cost delta.""" + before = finite_total(observation.known_cost for observation in parent) + after = finite_total(observation.known_cost for observation in child) + delta, status = finite_difference(after, before) if before is not None and after is not None else (None, 'overflow') + known = bool(parent and child) and all(observation.pricing == 'known' for observation in parent + child) + return {'value': delta if known else None, + 'status': status if known else 'unknown', + 'known_subtotal_delta': delta, 'known_subtotal_delta_status': status, + 'parent_known_cost': before, 'candidate_known_cost': after, + 'scope': 'recorded_example_attempts'} + + def _change(self, before, after): + """Use ordering, avoiding overflowing subtraction when deciding direction.""" + if before == after: + return 'tied' + improved = after > before if self.config.direction == 'maximize' else after < before + return 'improved' if improved else 'regressed' + + def _comparison(self, parent, child, remaining_examples): + """Keep task conclusions separate from complete and incomplete execution data.""" + before = self._history(parent.trial_id) + after = self._history(child.trial_id) + task_conclusions = parent.eligible and child.eligible + matched = 0 + recovered = 0 + counts = {'improved': 0, 'regressed': 0, 'tied': 0, 'infrastructure': 0, 'missing': 0} + parent_statuses = Counter() + child_statuses = Counter() + examples = [] + for key, example in self._expected.items(): + parent_history = before.get(key, []) + child_history = after.get(key, []) + original = parent_history[-1] if parent_history else None + candidate = child_history[-1] if child_history else None + parent_status = original.status if original is not None else 'missing' + child_status = candidate.status if candidate is not None else 'missing' + parent_statuses[parent_status] += 1 + child_statuses[child_status] += 1 + paired = parent_status == child_status == 'scored' + matched += paired + for history in (parent_history, child_history): + if history and history[-1].status == 'scored': + recovered += sum(observation.status == 'retryable' for observation in history[:-1]) + if original is None or candidate is None: + change = 'missing' + elif not paired: + change = 'infrastructure' + elif task_conclusions: + change = self._change(original.score, candidate.score) + else: + change = 'unavailable' + if change in counts: + counts[change] += 1 + if len(examples) >= remaining_examples: + continue + score_delta, delta_status = finite_difference( + candidate.score if candidate is not None and task_conclusions else None, + original.score if original is not None and task_conclusions else None) + examples.append({'example_id': example.original_id, 'occurrence': example.occurrence, + 'replicate': key[2], 'parent_status': parent_status, + 'candidate_status': child_status, 'change': change, + 'parent_score': original.score if paired and task_conclusions else None, + 'candidate_score': candidate.score if paired and task_conclusions else None, + 'score_delta': score_delta, 'score_delta_status': delta_status, + 'cost_delta': self._cost_delta(parent_history, child_history)}) + delta, delta_status = finite_difference(child.score, parent.score) + all_before = [observation for values in before.values() for observation in values] + all_after = [observation for values in after.values() for observation in values] + cost_delta = self._cost_delta(all_before, all_after) + if matched != self.plan.requested: + # Missing/unscored coordinates cannot establish complete trial cost, + # even if every recorded event happened to have known pricing. + cost_delta['value'] = None + cost_delta['status'] = 'unknown' + return {'trial_id': child.trial_id, 'parent_id': parent.trial_id, + 'task_conclusions': task_conclusions, + 'evidence': ('accepted' if child.improves(parent, self.config) else 'rejected') if task_conclusions else 'inconclusive', + 'parent_score': parent.score, 'candidate_score': child.score, + 'score_delta': delta, 'score_delta_status': delta_status, + 'counts': counts, + 'coverage': {'requested': self.plan.requested, 'parent_scored': parent.scored, + 'candidate_scored': child.scored, 'matched_scored': matched, + 'parent_statuses': dict(parent_statuses), 'candidate_statuses': dict(child_statuses), + 'recovered_retry_attempts': recovered}, + 'cost_delta': cost_delta, 'examples': examples, + 'omitted_examples': self.plan.requested - len(examples)} + + def _envelope(self, parent_id, comparison_count): + """Reserve enough space for explicit coverage/omission and fallback metadata.""" + return {'schema_version': SCHEMA_VERSION, 'parent_id': parent_id, 'split': 'validation', + 'metric_direction': self.config.direction, + 'availability': 'unavailable', 'reason': 'No comparable committed validation candidates.', + 'interpretation': 'Observed validation associations only; no causal attribution.', + 'comparison_count': comparison_count, 'omitted_comparisons': comparison_count, + 'example_count': 0, 'omitted_examples': self.plan.requested * comparison_count, + 'comparisons': []} + + def _fits(self, payload): + """Bound actual tagged prompt characters, not only the inner JSON length.""" + return len(OPEN_TAG) + len(canonical(payload)) + len(CLOSE_TAG) <= self.config.feedback_max_characters + + def payload(self, parent_id): + """Select recent candidates then fixed plan order under shared hard budgets.""" + parent = self.store.summary(parent_id) + candidates = [] + if parent is not None and parent.plan_id == self.plan.identity and parent.split == self.plan.split == 'validation': + for trial in reversed(self.store.trials()): + if trial['kind'] != 'candidate' or trial['parent_id'] != parent_id: + continue + child = self.store.summary(trial['trial_id']) + if child is not None and child.plan_id == parent.plan_id and child.split == 'validation': + candidates.append(child) + payload = self._envelope(parent_id, len(candidates)) + if not candidates: + return payload + payload['reason'] = None + for child in candidates: + remaining = self.config.feedback_max_examples - payload['example_count'] + comparison = self._comparison(parent, child, remaining) + payload['comparisons'].append(comparison) + payload['omitted_comparisons'] -= 1 + payload['example_count'] += len(comparison['examples']) + payload['omitted_examples'] -= len(comparison['examples']) + payload['availability'] = 'available' + while comparison['examples'] and not self._fits(payload): + comparison['examples'].pop() + comparison['omitted_examples'] += 1 + payload['example_count'] -= 1 + payload['omitted_examples'] += 1 + if not self._fits(payload): + payload['comparisons'].pop() + payload['omitted_comparisons'] += 1 + break + if not payload['comparisons']: + payload['availability'] = 'unavailable' + payload['reason'] = 'Detail omitted by budget; scalar summaries only.' + if not self._fits(payload): + payload['interpretation'] = 'Observed only; no causal attribution.' + return payload + + @staticmethod + def render(payload): + """Render exactly the JSON payload persisted for this proposal operation.""" + return OPEN_TAG + canonical(payload) + CLOSE_TAG diff --git a/evoagentx/optimizers/aflow/reporting.py b/evoagentx/optimizers/aflow/reporting.py index 0290e4ae..e1165931 100644 --- a/evoagentx/optimizers/aflow/reporting.py +++ b/evoagentx/optimizers/aflow/reporting.py @@ -132,6 +132,15 @@ def experiment(self): reports = [self.trial(trial['trial_id']) for trial in self.store.trials()] summaries = self.store.summaries() budget = self.store.read_state('budget', {}) + parents = {trial['parent_id'] for trial in self.store.trials() + if trial['kind'] == 'candidate' and trial['parent_id'] is not None} + if best is not None: + parents.add(best.trial_id) + proposal_feedback = {} + for path in sorted((self.store.path / 'attempts').glob('*.json')): + operation = read_json(path) + if operation['stage'] == 'proposal' and 'planner_feedback' in operation: + proposal_feedback[operation['attempt_id']] = operation['planner_feedback'] return {'schema_version': SCHEMA_VERSION, 'experiment_id': self.plan.config.experiment_id, 'plan_id': self.plan.identity, 'split': self.plan.split, 'direction': self.plan.config.direction, 'margin': self.plan.config.improvement_margin, @@ -146,6 +155,8 @@ def experiment(self): 'incomplete_trials': [s.trial_id for s in summaries if not s.eligible], 'evolution': self.store.read_state('evolution', None), 'feedback': view.feedback(), 'operation_totals': self._operation_totals(), + 'planner_feedback': {parent: view.planner_feedback(parent) for parent in sorted(parents)}, + 'proposal_feedback': proposal_feedback, 'operation_accounting': self.operation_accounting(), 'cost': {'known_spent': budget.get('known_spent', 0), 'uncertain': budget.get('uncertain', True), diff --git a/evoagentx/optimizers/aflow/runner.py b/evoagentx/optimizers/aflow/runner.py index 87169b20..4e6d09d6 100644 --- a/evoagentx/optimizers/aflow/runner.py +++ b/evoagentx/optimizers/aflow/runner.py @@ -128,7 +128,7 @@ async def _evaluate(self, trial_id): return await DetailedEvaluator(self.optimizer.executor_llm).evaluate( self.benchmark, graph, self.data, self.plan, trial_id, self.store, self.budget) - def _proposal_prompt(self, parent): + def _proposal_prompt(self, parent, feedback=None): """Reuse the existing AFlow proposal prompt with measured feedback.""" graph, prompt, _ = self.store.read_artifacts(parent.trial_id) extracted = self.optimizer.graph_utils.extract_solve_graph(graph) @@ -137,7 +137,7 @@ def _proposal_prompt(self, parent): descriptions = self.optimizer.graph_utils.load_operators_description(self.optimizer.operators, self.optimizer.optimizer_llm) return self.optimizer.graph_utils.create_graph_optimize_prompt( - self.view.prompt_feedback(parent.trial_id), parent.score, extracted[0], prompt, + self.view.prompt_feedback(parent.trial_id, feedback), parent.score, extracted[0], prompt, descriptions, self.optimizer.question_type, '') def _parse_proposal(self, content, parent): @@ -158,9 +158,10 @@ async def _request_proposal(self, parent): """Count proposal calls separately; an outage never restarts the baseline.""" number = self.budget.state['counts']['proposal'] + 1 operation_id = f'proposal_{number}' - prompt = self._proposal_prompt(parent) + feedback = self.view.planner_feedback(parent.trial_id) + prompt = self._proposal_prompt(parent, feedback) self.budget.admit('proposal', operation_id) - self.store.begin_operation(operation_id, 'proposal', parent.trial_id) + self.store.begin_operation(operation_id, 'proposal', parent.trial_id, planner_feedback=feedback) ledger = CostLedger() timeouts = [v for v in (self.config.proposal_timeout, self.budget.remaining_time()) if v is not None] try: diff --git a/evoagentx/optimizers/aflow/types.py b/evoagentx/optimizers/aflow/types.py index 0fc8419c..53e641ba 100644 --- a/evoagentx/optimizers/aflow/types.py +++ b/evoagentx/optimizers/aflow/types.py @@ -92,6 +92,8 @@ class ReliableTrialConfig: convergence_patience: int = 5 metric_id: str | None = None recover_owner: bool = False + feedback_max_examples: int = 12 + feedback_max_characters: int = 12000 def __post_init__(self): """Reject ambiguous budgets before any external work can be admitted.""" @@ -102,10 +104,13 @@ def __post_init__(self): if finite_score(self.improvement_margin) < 0: raise ValueError('improvement_margin must be nonnegative') for name in ('replicates', 'concurrency', 'attempts_per_example', 'max_example_attempts', - 'max_proposals', 'max_trials', 'duplicate_limit', 'convergence_patience'): + 'max_proposals', 'max_trials', 'duplicate_limit', 'convergence_patience', + 'feedback_max_examples', 'feedback_max_characters'): value = getattr(self, name) if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f'{name} must be a positive integer') + if self.feedback_max_characters < 512: + raise ValueError('feedback_max_characters must be at least 512 for an explicit diagnostic fallback') for name in ('deadline_seconds', 'attempt_timeout', 'proposal_timeout', 'max_known_cost', 'example_cost_bound', 'proposal_cost_bound'): value = getattr(self, name) diff --git a/tests/src/optimizers/test_aflow_feedback.py b/tests/src/optimizers/test_aflow_feedback.py new file mode 100644 index 00000000..85d97d0f --- /dev/null +++ b/tests/src/optimizers/test_aflow_feedback.py @@ -0,0 +1,167 @@ +"""Planner evidence compares observed validation coordinates, not scalar averages.""" +import json +from dataclasses import replace + +import pytest + +from evoagentx.optimizers.aflow import ( + EvaluationPlan, + Observation, + ReliableTrialConfig, + TrialStore, + TrialSummary, +) +from evoagentx.optimizers.aflow.evidence import EvidenceView +from evoagentx.optimizers.aflow.reporting import TrialReporter +from evoagentx.optimizers.aflow.types import canonical + + +def fixture(tmp_path, **kwargs): + config = ReliableTrialConfig(replicates=2, **kwargs) + data = [{'_id': 'duplicate', 'value': 'first'}, {'_id': 'duplicate', 'value': 'second'}] + plan = EvaluationPlan.create('local', data, {}, 'metric.v1', config) + store = TrialStore(tmp_path, plan) + return store, plan + + +def commit(store, plan, trial_id, scores, parent=None, pricing='known', cost=.1): + number = len(store.trials()) + store.create_trial(trial_id, number, 'candidate' if parent else 'baseline', parent, 'local modification') + for replicate in range(plan.config.replicates): + for example in plan.examples: + score = scores[replicate * len(plan.examples) + example.index] + if score == 'missing': + continue + if score is None: + observation = Observation.make(trial_id, example, replicate, 1, 'inconclusive', error_type='TimeoutError', pricing=pricing, known_cost=cost) + else: + observation = Observation.scored(trial_id, example, replicate, 1, score, pricing=pricing, known_cost=cost) + store.record(observation) + summary = TrialSummary.build(plan, trial_id, number, store.observations(trial_id)) + store.commit_summary(summary) + return summary + + +def test_duplicate_ids_replicates_and_direction_keep_matched_tradeoffs(tmp_path): + store, plan = fixture(tmp_path, direction='minimize') + with store: + commit(store, plan, 'parent', [0, 1, 0, 1]) + commit(store, plan, 'child', [1, 0, 1, 0], 'parent', cost=.2) + payload = EvidenceView(store).planner_feedback('parent') + comparison = payload['comparisons'][0] + assert payload['metric_direction'] == 'minimize' + assert comparison['coverage']['matched_scored'] == 4 + assert comparison['counts'] == {'improved': 2, 'regressed': 2, 'tied': 0, 'infrastructure': 0, 'missing': 0} + assert comparison['score_delta'] == 0 + assert comparison['cost_delta']['value'] == pytest.approx(.4) + examples = comparison['examples'] + assert [(row['example_id'], row['occurrence'], row['replicate']) for row in examples] == [ + ('duplicate', 0, 0), ('duplicate', 1, 0), ('duplicate', 0, 1), ('duplicate', 1, 1)] + assert [row['change'] for row in examples] == ['regressed', 'improved', 'regressed', 'improved'] + assert all(row['score_delta'] in (-1, 1) for row in examples) + prompt = EvidenceView(store).prompt_feedback('parent') + assert canonical(payload) in prompt + assert TrialReporter(store).experiment()['planner_feedback']['parent'] == payload + + +def test_incomplete_and_test_evidence_never_become_task_regressions(tmp_path): + store, plan = fixture(tmp_path) + with store: + commit(store, plan, 'parent', [1, 1, 1, 1]) + commit(store, plan, 'incomplete', [0, None, 0, 'missing'], 'parent', pricing='unknown') + payload = EvidenceView(store).planner_feedback('parent') + row = payload['comparisons'][0] + assert not row['task_conclusions'] + assert row['counts']['regressed'] == 0 and row['counts']['improved'] == 0 + assert row['counts']['infrastructure'] == 1 and row['counts']['missing'] == 1 + assert row['coverage']['matched_scored'] == 2 + assert row['cost_delta']['status'] == 'unknown' and row['cost_delta']['value'] is None + assert all(example['change'] not in ('improved', 'regressed', 'tied') for example in row['examples']) + prompt = EvidenceView(store).prompt_feedback('parent') + assert 'TimeoutError' not in prompt # categories, never arbitrary exception payloads + test_plan = replace(plan, split='test') + with TrialStore(tmp_path / 'test', test_plan) as test_store: + commit(test_store, test_plan, 'parent', [1, 1, 1, 1]) + commit(test_store, test_plan, 'child', [0, 0, 0, 0], 'parent') + payload = EvidenceView(test_store).planner_feedback('parent') + assert payload['availability'] == 'unavailable' + assert payload['comparisons'] == [] + + +def test_feedback_is_deterministically_bounded_and_reports_omissions(tmp_path): + store, plan = fixture(tmp_path, feedback_max_examples=2, feedback_max_characters=1800) + with store: + commit(store, plan, 'parent', [1, 0, 1, 0]) + for index in range(4): + commit(store, plan, f'child_{index}', [0, 1, 0, 1], 'parent') + view = EvidenceView(store) + first = view.planner_feedback('parent') + assert first == view.planner_feedback('parent') + assert len(canonical(first)) <= 1800 + assert first['example_count'] <= 2 + assert first['omitted_examples'] >= 14 + assert first['omitted_comparisons'] > 0 + assert first['comparison_count'] == 4 + + +def test_extreme_finite_deltas_are_explicit_overflow_and_json_stays_finite(tmp_path): + store, plan = fixture(tmp_path) + with store: + commit(store, plan, 'parent', [-1e308, -1e308, -1e308, -1e308], cost=1e307) + commit(store, plan, 'child', [1e308, 1e308, 1e308, 1e308], 'parent', cost=2e307) + payload = EvidenceView(store).planner_feedback('parent') + comparison = payload['comparisons'][0] + assert comparison['score_delta'] is None and comparison['score_delta_status'] == 'overflow' + assert comparison['counts']['improved'] == 4 + assert all(row['score_delta_status'] == 'overflow' for row in comparison['examples']) + json.dumps(payload, allow_nan=False) + + +def test_minimum_character_budget_and_oversized_original_id_have_explicit_fallback(tmp_path): + config = ReliableTrialConfig(feedback_max_characters=512) + plan = EvaluationPlan.create('local', [{'_id': 'long' * 1000}], {}, 'metric.v1', config) + with TrialStore(tmp_path, plan) as store: + commit(store, plan, 'parent', [0]) + commit(store, plan, 'child', [1], 'parent') + payload = EvidenceView(store).planner_feedback('parent') + assert len(EvidenceView(store).prompt_feedback('parent')) <= 512 + assert payload['availability'] == 'unavailable' and payload['omitted_examples'] == 1 + assert payload['omitted_comparisons'] == 1 and payload['reason'] + + +def test_foreign_plan_is_excluded_and_source_labels_are_never_rendered(tmp_path): + from evoagentx.optimizers.aflow.store import atomic_json + store, plan = fixture(tmp_path) + with store: + commit(store, plan, 'parent', [1, 1, 1, 1]) + summary = commit(store, plan, 'foreign', [0, 0, 0, 0], 'parent') + payload = summary.to_dict() + payload['plan_id'] = 'different-experiment-plan' + atomic_json(tmp_path / 'trials' / 'foreign' / 'summary.json', payload) + feedback = EvidenceView(store).planner_feedback('parent') + assert feedback['comparison_count'] == 0 and feedback['comparisons'] == [] + assert 'first' not in canonical(feedback) and 'second' not in canonical(feedback) + + +def test_smallest_budget_still_holds_for_maximum_length_trial_id(tmp_path): + config = ReliableTrialConfig(feedback_max_characters=512) + plan = EvaluationPlan.create('local', [{'_id': 'x'}], {}, 'metric.v1', config) + parent = 'p' * 100 + with TrialStore(tmp_path, plan) as store: + commit(store, plan, parent, [0]) + commit(store, plan, 'child', [1], parent) + view = EvidenceView(store) + assert len(view.prompt_feedback(parent)) <= 512 + assert view.planner_feedback(parent)['reason'] + + +def test_observed_cost_sum_overflow_has_explicit_marker_not_unknown_free_cost(): + from evoagentx.optimizers.aflow.feedback import MatchedFeedback + plan = EvaluationPlan.create('local', [{'_id': 'x'}], {}, 'metric.v1', ReliableTrialConfig()) + example = plan.examples[0] + parent = [Observation.scored('parent', example, 0, 1, 0, known_cost=0, pricing='known')] + child = [Observation.scored('child', example, 0, attempt, 1, known_cost=1e308, pricing='known') for attempt in (1, 2)] + cost = MatchedFeedback._cost_delta(parent, child) + assert cost['value'] is None and cost['status'] == 'overflow' + assert cost['known_subtotal_delta_status'] == 'overflow' + json.dumps(cost, allow_nan=False) diff --git a/tests/src/optimizers/test_aflow_native_trials.py b/tests/src/optimizers/test_aflow_native_trials.py index 5ae65954..960afda7 100644 --- a/tests/src/optimizers/test_aflow_native_trials.py +++ b/tests/src/optimizers/test_aflow_native_trials.py @@ -218,3 +218,64 @@ def test_proposal_cost_evidence_survives_cleared_stage_cursor(tmp_path, monkeypa assert sum(row['known_cost'] for row in proposals) == pytest.approx(.04) assert sum(row['known_cost'] for row in operations) == pytest.approx(.12) assert all(row['trial_id'] and row['pricing_known'] for row in proposals) + + +FEEDBACK_STATE = {} + + +@register_model(LLMConfig) +class FeedbackFixtureProvider(TrialFixtureProvider): + def init_model(self): + self.state = FEEDBACK_STATE + async def single_generate_async(self, messages, **kwargs): + prompt = messages[-1]['content'] + cost_manager.update_cost(Cost(cost=.01), 'feedback-fixture') + if 'You are building a Graph' in prompt: + self.state['prompts'].append(prompt) + number = len(self.state['prompts']) + if number == 3: + # React to actual committed matched evidence, never test labels. + marker = '' + assert marker in prompt, 'native proposal still receives scalar-only feedback' + payload = json.loads(prompt.split(marker, 1)[1].split('', 1)[0]) + comparison = next(row for row in payload['comparisons'] if row['trial_id'] == 'candidate_2') + by_id = {row['example_id']: row['change'] for row in comparison['examples']} + assert by_id == {'0': 'regressed', '1': 'improved'} + assert comparison['coverage']['recovered_retry_attempts'] == int(self.state['transient']) + self.state['reacted'] = True + graph = GRAPH.replace('prompt=problem,', f'prompt="strategy_{number}:" + problem,') + return f'Strategy {number}{graph}# local' + self.state['execution'] += 1 + if prompt.startswith('strategy_2:') and 'first' in prompt and self.state['transient'] and not self.state.get('failed_once'): + self.state['failed_once'] = True + raise TimeoutError('recovered transient execution diagnostic') + if prompt.startswith('strategy_3:'): + return 'Paris' + if prompt.startswith('strategy_1:') and 'first' in prompt: + return 'Paris' + if prompt.startswith('strategy_2:') and 'second' in prompt: + return 'Paris' + return 'wrong' + + +@pytest.mark.parametrize('transient', [False, True]) +def test_native_next_proposal_reacts_to_equal_mean_validation_tradeoff(tmp_path, monkeypatch, transient): + optimizer, benchmark, _ = setup(tmp_path, monkeypatch) + FEEDBACK_STATE.clear() + FEEDBACK_STATE.update(prompts=[], execution=0, reacted=False, transient=transient) + llm = FeedbackFixtureProvider(LLMConfig(llm_type='FeedbackFixtureProvider', model='local-feedback-fixture')) + optimizer.optimizer_llm = llm + optimizer.executor_llm = llm + optimizer.max_rounds = 3 + result = optimizer.optimize(benchmark) + assert result.status == 'completed' and result.score == 1 and result.best_round == 3 + assert FEEDBACK_STATE['reacted'] and len(FEEDBACK_STATE['prompts']) == 3 + rows = json.loads(Path('results/results.json').read_text()) + assert [(row['round'], row['score']) for row in rows] == [(0, 0), (1, .5), (2, .5), (3, 1)] + marker = '' + prompt = FEEDBACK_STATE['prompts'][2] + payload = json.loads(prompt.split(marker, 1)[1].split('', 1)[0]) + report = json.loads(Path('results/reliable/aflow/reports/experiment.json').read_text()) + assert report['proposal_feedback']['proposal_3'] == payload + assert payload['comparisons'][0]['counts']['regressed'] == 2 + assert payload['comparisons'][0]['counts']['improved'] == 2 From a0fcb0690fa7d52ae8ee51d88bd45becde122a7f Mon Sep 17 00:00:00 2001 From: Cookie0103 <258013390+Cookie0103@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:43:45 +0900 Subject: [PATCH 4/4] fix: preserve unknown costs and resume durable AFlow attempts --- docs/optimizers/aflow_reliable_trials.md | 13 ++ evoagentx/models/litellm_model.py | 18 ++- evoagentx/models/model_utils.py | 26 +++- evoagentx/models/novita_model.py | 1 + evoagentx/models/openai_model.py | 18 ++- evoagentx/models/openrouter_model.py | 13 +- evoagentx/models/siliconflow_model.py | 1 + evoagentx/optimizers/aflow/budget.py | 13 +- evoagentx/optimizers/aflow/evaluator.py | 21 ++- evoagentx/optimizers/aflow/runner.py | 3 +- evoagentx/optimizers/aflow/store.py | 7 + .../optimizers/test_aflow_native_trials.py | 83 +++++++++++ .../test_aflow_review_regressions.py | 134 ++++++++++++++++++ 13 files changed, 332 insertions(+), 19 deletions(-) create mode 100644 tests/src/optimizers/test_aflow_review_regressions.py diff --git a/docs/optimizers/aflow_reliable_trials.md b/docs/optimizers/aflow_reliable_trials.md index ac98b4cc..18c83b97 100644 --- a/docs/optimizers/aflow_reliable_trials.md +++ b/docs/optimizers/aflow_reliable_trials.md @@ -166,3 +166,16 @@ The current bounded view is exported under `planner_feedback` in the experiment report. Each proposal intent persists the exact payload sent to that provider; `proposal_feedback` retains these historical snapshots even after later trials change the current view. Test outcomes never enter either validation payload. + +Native provider responses with missing usage, streams without usage, and failed +or cancelled generation attempts emit explicit unknown accounting evidence. +Consequently a different priced response in the same operation cannot make its +whole usage appear known. This completeness metadata does not add invented cost +or token counts to legacy process totals. Missing amounts retain the remaining +pre-call bound conservatively, including across replay of a completed trial. + +When an operator resolves an intent whose outcome was never published, rerun +uses the next unused attempt number and remaining attempt budget; abandon skips +that coordinate and keeps its evidence incomplete. The original unknown amount +remains reserved. Replaying already finalized unknown-price evidence returns its +cached result without spending or releasing that reservation again. diff --git a/evoagentx/models/litellm_model.py b/evoagentx/models/litellm_model.py index 30f64c89..7256dc22 100644 --- a/evoagentx/models/litellm_model.py +++ b/evoagentx/models/litellm_model.py @@ -1,17 +1,21 @@ +import asyncio import os +from typing import List + import litellm +from litellm import acompletion, completion from tenacity import ( retry, stop_after_attempt, wait_random_exponential, ) -from litellm import completion, acompletion -from typing import List + from ..core.logging import logger from ..core.registry import register_model from .model_configs import LiteLLMConfig +from .model_utils import Cost, cost_manager, infer_litellm_company_from_model from .openai_model import OpenAILLM -from .model_utils import infer_litellm_company_from_model, Cost + @register_model(config_cls=LiteLLMConfig, alias=["litellm"]) class LiteLLM(OpenAILLM): @@ -157,7 +161,11 @@ def single_generate(self, messages: List[dict], **kwargs) -> str: output = self.get_stream_output(response, output_response=output_response) else: output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate of LiteLLM: {str(e)}") return output @@ -187,7 +195,11 @@ async def single_generate_async(self, messages: List[dict], **kwargs) -> str: output = self.get_stream_output(response, output_response=output_response) else: output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate_async of LiteLLM: {str(e)}") return output diff --git a/evoagentx/models/model_utils.py b/evoagentx/models/model_utils.py index 93b10bd6..639bbd9f 100644 --- a/evoagentx/models/model_utils.py +++ b/evoagentx/models/model_utils.py @@ -145,12 +145,27 @@ def update_cost(self, cost: Cost, model: str): current_llm_cost = cost.cost current_total_tokens = (cost.input_tokens or 0) + (cost.output_tokens or 0) + known = getattr(cost, 'pricing_known', False) and math.isfinite(cost.cost) and cost.cost >= 0 + self._notify_observers(CostEvent(model, cost.cost if known else None, + 'known' if known else 'unknown', + cost.input_tokens or 0, cost.output_tokens or 0)) + + if not suppress_cost_logs.get(): + logger.info(f"Total LLM cost: ${total_llm_cost:.3f} | Total tokens: {total_tokens} | Current LLM cost: ${current_llm_cost:.3f} | Current tokens: {current_total_tokens}") + + def record_unknown_usage(self, model: str): + """Mark a native response/attempt whose accounting is incomplete. + + Missing usage provides no numeric cost or token count to add to legacy + process totals. Context observers still need an explicit unknown event so + a different priced response cannot make the whole operation look priced. + """ + self._notify_observers(CostEvent(model, None, 'unknown', 0, 0)) + + def _notify_observers(self, event): + """Deliver accounting completeness without changing provider behavior.""" for manager, observer in _cost_observers.get(): if manager is self: - known = getattr(cost, 'pricing_known', False) and math.isfinite(cost.cost) and cost.cost >= 0 - event = CostEvent(model, cost.cost if known else None, - 'known' if known else 'unknown', - cost.input_tokens or 0, cost.output_tokens or 0) try: observer(event) except Exception: @@ -158,9 +173,6 @@ def update_cost(self, cost: Cost, model: str): # prevent process-wide totals from being recorded. logger.warning('Context-local cost observer failed') - if not suppress_cost_logs.get(): - logger.info(f"Total LLM cost: ${total_llm_cost:.3f} | Total tokens: {total_tokens} | Current LLM cost: ${current_llm_cost:.3f} | Current tokens: {current_total_tokens}") - def display_cost(self): data = { diff --git a/evoagentx/models/novita_model.py b/evoagentx/models/novita_model.py index a2fe4232..16f07c67 100644 --- a/evoagentx/models/novita_model.py +++ b/evoagentx/models/novita_model.py @@ -48,6 +48,7 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): # counts and leave cost at 0 (see class docstring). usage = getattr(response, "usage", None) if usage is None: + cost_manager.record_unknown_usage(self.config.model) logger.warning( f"[NovitaLLM] usage is None in response (id={getattr(response, 'id', '?')}); " "tokens will not be recorded." diff --git a/evoagentx/models/openai_model.py b/evoagentx/models/openai_model.py index 75708ed2..dc50cd8b 100644 --- a/evoagentx/models/openai_model.py +++ b/evoagentx/models/openai_model.py @@ -1,6 +1,9 @@ +import asyncio import json from typing import Dict, List, Optional, Union +from litellm import cost_per_token +from litellm.types.utils import Usage from openai import AsyncOpenAI, OpenAI, Stream from openai.types.chat import ChatCompletion, ChatCompletionChunk from openai.types.completion_usage import CompletionUsage @@ -9,15 +12,13 @@ stop_after_attempt, wait_random_exponential, ) -from litellm import cost_per_token -from litellm.types.utils import Usage from ..core.logging import logger from ..core.registry import register_model from ..prompts.tool_calling import TOOL_CALL_FORMAT from ..utils.utils import format_tool_calls -from .model_configs import OpenAILLMConfig from .base_model import BaseLLM +from .model_configs import OpenAILLMConfig from .model_utils import Cost, cost_manager, get_openai_model_cost @@ -143,6 +144,7 @@ def get_stream_output(self, response: Stream, output_response: bool=True) -> str if usage_chunk is not None: self._update_cost(usage_chunk) else: + cost_manager.record_unknown_usage(self.config.model) logger.warning("[OpenAILLM] No usage data in stream response; cost will not be recorded. Set stream_options={'include_usage': True} to enable cost tracking.") return output @@ -184,6 +186,7 @@ async def get_stream_output_async(self, response, output_response: bool = False) if usage_chunk is not None: self._update_cost(usage_chunk) else: + cost_manager.record_unknown_usage(self.config.model) logger.warning("[OpenAILLM] No usage data in stream response; cost will not be recorded. Set stream_options={'include_usage': True} to enable cost tracking.") return output @@ -239,7 +242,11 @@ def single_generate(self, messages: List[dict], **kwargs) -> str: output = self.get_stream_output(response, output_response=output_response) else: output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate of OpenAILLM: {str(e)}") return output @@ -262,7 +269,11 @@ async def single_generate_async(self, messages: List[dict], **kwargs) -> str: # The network I/O is already awaited above; the response is fully in memory here, # so this synchronous parsing/cost call does not block the event loop. output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate_async of OpenAILLM: {str(e)}") return output @@ -283,6 +294,7 @@ def _compute_cost(self, usage: CompletionUsage) -> Cost: def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): usage = getattr(response, "usage", None) if usage is None: + cost_manager.record_unknown_usage(self.config.model) logger.warning(f"[OpenAILLM] usage is None in response (id={getattr(response, 'id', '?')}); cost will not be recorded.") return cost_manager.update_cost(cost=self._compute_cost(usage), model=self.config.model) diff --git a/evoagentx/models/openrouter_model.py b/evoagentx/models/openrouter_model.py index 151171b7..92791195 100644 --- a/evoagentx/models/openrouter_model.py +++ b/evoagentx/models/openrouter_model.py @@ -1,3 +1,4 @@ +import asyncio import json from copy import deepcopy from typing import Dict, List, Optional, Tuple, Union @@ -18,7 +19,6 @@ from .model_configs import OpenRouterConfig from .model_utils import Cost, cost_manager - # Models already warned about paid cache writes. Process-wide so the warning # fires at most once per model regardless of how many LLM instances are created. _PROMPT_CACHING_COST_WARNED: set = set() @@ -218,6 +218,7 @@ def get_stream_output(self, response: Stream, output_response: bool=True) -> str if usage_chunk is not None: self._update_cost(usage_chunk) else: + cost_manager.record_unknown_usage(self.config.model) logger.warning("[OpenRouterLLM] No usage data in stream response; cost will not be recorded.") return output @@ -249,6 +250,7 @@ async def get_stream_output_async(self, response, output_response: bool = False) if usage_chunk is not None: self._update_cost(usage_chunk) else: + cost_manager.record_unknown_usage(self.config.model) logger.warning("[OpenRouterLLM] No usage data in stream response; cost will not be recorded.") return output @@ -293,6 +295,7 @@ def _format_streamed_tool_calls(accum: Dict[int, dict]) -> List[dict]: def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): usage = response.usage if usage is None: + cost_manager.record_unknown_usage(self.config.model) logger.warning(f"[OpenRouterLLM] usage is None in response (id={response.id}); cost will not be recorded.") return cost_value = getattr(usage, "cost", None) @@ -325,7 +328,11 @@ def single_generate(self, messages: List[dict], **kwargs) -> str: output = self.get_stream_output(response, output_response=output_response) else: output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate of OpenRouterLLM: {str(e)}") return output @@ -351,7 +358,11 @@ async def single_generate_async(self, messages: List[dict], **kwargs) -> str: # so this synchronous parsing/cost call does not block the event loop. output: str = self.get_completion_output(response=response, output_response=output_response) + except asyncio.CancelledError: + cost_manager.record_unknown_usage(self.config.model) + raise except Exception as e: + cost_manager.record_unknown_usage(self.config.model) raise RuntimeError(f"Error during single_generate_async of OpenRouterLLM: {str(e)}") return output diff --git a/evoagentx/models/siliconflow_model.py b/evoagentx/models/siliconflow_model.py index b7080d9b..7562ce35 100644 --- a/evoagentx/models/siliconflow_model.py +++ b/evoagentx/models/siliconflow_model.py @@ -50,6 +50,7 @@ def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]): # counts and leave cost at 0 (see class docstring). usage = getattr(response, "usage", None) if usage is None: + cost_manager.record_unknown_usage(self.config.model) logger.warning( f"[SiliconFlowLLM] usage is None in response (id={getattr(response, 'id', '?')}); " "tokens will not be recorded." diff --git a/evoagentx/optimizers/aflow/budget.py b/evoagentx/optimizers/aflow/budget.py index a82deb3c..cadf5a13 100644 --- a/evoagentx/optimizers/aflow/budget.py +++ b/evoagentx/optimizers/aflow/budget.py @@ -92,7 +92,7 @@ def finish(self, operation_id, known_cost, pricing_known, terminated=True): self._save() raise RuntimeError('supported pre-call cost bound violated; admission halted') self.state['known_spent'] += known_cost - if not pricing_known: + if not pricing_known or not terminated: self.state['uncertain'] = True # A supplied upper bound remains reserved for unknown pricing, even if # execution terminated; absent observer events never prove zero dollars. @@ -104,6 +104,17 @@ def finish(self, operation_id, known_cost, pricing_known, terminated=True): self.state['reservations'].pop(operation_id) self._save() + def reconcile(self, operation_id, known_cost, pricing_known): + """Finalize a durable completion only while its reservation is admitted. + + A finished reservation can intentionally retain unknown priced usage. + Its presence does not mean finalization is pending, and replay must not + spend it again or release its remaining conservative bound. + """ + reservation = self.state['reservations'].get(operation_id) + if reservation is not None and reservation['status'] == 'admitted': + self.finish(operation_id, known_cost, pricing_known) + def report(self): """Expose actual supported bounds and unobserved provider-internal usage.""" return {'counts': dict(self.state['counts']), 'known_spent': self.state['known_spent'], diff --git a/evoagentx/optimizers/aflow/evaluator.py b/evoagentx/optimizers/aflow/evaluator.py index 9d494cb7..abfc76a1 100644 --- a/evoagentx/optimizers/aflow/evaluator.py +++ b/evoagentx/optimizers/aflow/evaluator.py @@ -114,8 +114,8 @@ async def evaluate(self, benchmark, graph, data, plan, trial_id, store, budget): # A durable completed outcome establishes completion even if the process # died before releasing its conservative cost reservation. for observation in store.observations(trial_id): - if observation.status not in ('unknown', 'cancelled') and observation.observation_id in budget.state['reservations']: - budget.finish(observation.observation_id, observation.known_cost, observation.pricing == 'known') + if observation.status not in ('unknown', 'cancelled'): + budget.reconcile(observation.observation_id, observation.known_cost, observation.pricing == 'known') existing = store.summary(trial_id) if existing is not None: return existing @@ -127,6 +127,15 @@ async def evaluate(self, benchmark, graph, data, plan, trial_id, store, budget): key = (obs.example_key, obs.replicate) if key not in latest or obs.attempt > latest[key].attempt: latest[key] = obs + intents = {} + for operation in store.example_attempts(trial_id): + key = (operation['example_key'], operation['replicate']) + if key not in intents or operation['attempt'] > intents[key]['attempt']: + intents[key] = operation + if operation.get('resolution') in ('rerun', 'abandon'): + # Resolution confirms termination, not actual usage. An outcome + # absent after a crash cannot manufacture a known zero price. + budget.reconcile(operation['attempt_id'], 0.0, False) coordinates = iter((identity, replicate) for replicate in range(plan.config.replicates) for identity in plan.examples) stop_reason = [] @@ -136,6 +145,12 @@ async def worker(): if stop_reason: return previous = latest.get((identity.key, replicate)) + intent = intents.get((identity.key, replicate)) + if intent is not None and (previous is None or intent['attempt'] >= previous.attempt): + if intent.get('resolution') == 'abandon': + continue + if (previous is None or intent['attempt'] > previous.attempt) and intent.get('resolution') != 'rerun': + raise RuntimeError('durable example intent has no completed outcome or explicit rerun') if previous is not None: if previous.status == 'scored' or previous.status == 'inconclusive': continue @@ -146,6 +161,8 @@ async def worker(): start = previous.attempt + 1 else: start = 1 + if intent is not None: + start = max(start, intent['attempt'] + 1) for attempt in range(start, plan.config.attempts_per_example + 1): try: observation = await self._attempt(benchmark, configured, data[identity.index], identity, diff --git a/evoagentx/optimizers/aflow/runner.py b/evoagentx/optimizers/aflow/runner.py index 4e6d09d6..3bf79e2d 100644 --- a/evoagentx/optimizers/aflow/runner.py +++ b/evoagentx/optimizers/aflow/runner.py @@ -215,8 +215,7 @@ def _recover_pending_proposal(self): if operation['status'] == 'started': self.store.finish_operation(operation_id, 'completed') costs = pending['costs'] - if operation_id in self.budget.state['reservations']: - self.budget.finish(operation_id, costs['known_cost'], costs['pricing'] == 'known') + self.budget.reconcile(operation_id, costs['known_cost'], costs['pricing'] == 'known') return pending['response'] async def _proposal(self): diff --git a/evoagentx/optimizers/aflow/store.py b/evoagentx/optimizers/aflow/store.py index 859d9760..d7400dfe 100644 --- a/evoagentx/optimizers/aflow/store.py +++ b/evoagentx/optimizers/aflow/store.py @@ -368,6 +368,13 @@ def operation(self, attempt_id): path = self.path / 'attempts' / f'{attempt_id}.json' return read_json(path) if path.exists() else None + def example_attempts(self, trial_id): + """Read durable example intents, including resolved calls without outcomes.""" + self.trial(trial_id) + operations = [read_json(path) for path in (self.path / 'attempts').glob('*.json')] + return [operation for operation in operations + if operation['trial_id'] == trial_id and operation['stage'] == 'example'] + def commit_summary(self, summary): """Atomically publish authoritative evidence after verifying durable coverage.""" self._require_owner() diff --git a/tests/src/optimizers/test_aflow_native_trials.py b/tests/src/optimizers/test_aflow_native_trials.py index 960afda7..7912aa43 100644 --- a/tests/src/optimizers/test_aflow_native_trials.py +++ b/tests/src/optimizers/test_aflow_native_trials.py @@ -279,3 +279,86 @@ def test_native_next_proposal_reacts_to_equal_mean_validation_tradeoff(tmp_path, assert report['proposal_feedback']['proposal_3'] == payload assert payload['comparisons'][0]['counts']['regressed'] == 2 assert payload['comparisons'][0]['counts']['improved'] == 2 + + +@pytest.mark.parametrize('resolution', ['rerun', 'abandon']) +def test_native_resolved_intent_without_outcome_drives_next_attempt(tmp_path, monkeypatch, resolution): + from evoagentx.optimizers.aflow import TrialStore + from evoagentx.optimizers.aflow import store as storage + optimizer, benchmark, llm = setup(tmp_path, monkeypatch, concurrency=1, + max_known_cost=10, example_cost_bound=.1, proposal_cost_bound=.1) + original = storage.atomic_json + def fail_result(path, value): + if '/observations/' in str(path): + raise OSError('review regression: outcome publication interrupted') + return original(path, value) + monkeypatch.setattr(storage, 'atomic_json', fail_result) + with pytest.raises(OSError): + optimizer.optimize(benchmark) + monkeypatch.setattr(storage, 'atomic_json', original) + path = Path('results/reliable/aflow') + with TrialStore.open_existing(path) as store: + unknown = store.unknown_attempts() + assert len(unknown) == 1 and store.observations('baseline') == [] + old = dict(unknown[0]) + store.resolve_unknown(old['attempt_id'], resolution, 'scripted native provider returned; termination confirmed') + before = llm.state['execution'] + result = optimizer.optimize(benchmark) + observations = [json.loads(p.read_text()) for p in (path / 'trials/baseline/observations').glob('*.json')] + matching = [o for o in observations if o['example_key'] == old['example_key'] and o['replicate'] == old['replicate']] + if resolution == 'rerun': + assert result.score == 1 and result.status == 'exhausted' + assert llm.state['execution'] - before == 8 + assert len(matching) == 1 and matching[0]['attempt'] == 2 + assert matching[0]['observation_id'] != old['attempt_id'] + else: + assert result.status == 'incomplete' and result.score is None + assert llm.state['execution'] - before == 3 and matching == [] + budget = json.loads((path / 'budget.json').read_text()) + retained = budget['reservations'][old['attempt_id']] + assert retained['reserved'] == pytest.approx(.1) + assert retained['status'] == 'finished' and not retained['pricing_known'] + assert budget['uncertain'] + + +def test_native_completed_test_replay_preserves_finalized_unknown_reservation(tmp_path, monkeypatch): + optimizer, benchmark, llm = setup(tmp_path, monkeypatch, concurrency=1, + max_known_cost=10, example_cost_bound=.1, proposal_cost_bound=.1) + original_cost = Cost + monkeypatch.setitem(globals(), 'Cost', lambda **kwargs: original_cost(**kwargs, pricing_known=False)) + optimizer.optimize(benchmark) + first = optimizer.test(benchmark, [1]) + path = Path('results/reliable/aflow_test/budget.json') + before = json.loads(path.read_text()) + calls = llm.state['execution'] + second = optimizer.test(benchmark, [1]) + assert second == first and second[0].eligible + assert llm.state['execution'] == calls + assert json.loads(path.read_text()) == before + assert before['known_spent'] == 0 + assert sum(r['reserved'] for r in before['reservations'].values()) == pytest.approx(.4) + + +def test_native_pending_proposal_recovery_keeps_finalized_unknown_cost(tmp_path, monkeypatch): + from evoagentx.optimizers.aflow import store as storage + optimizer, benchmark, llm = setup(tmp_path, monkeypatch, concurrency=1, + max_known_cost=10, example_cost_bound=.1, proposal_cost_bound=.1) + original_cost = Cost + monkeypatch.setitem(globals(), 'Cost', lambda **kwargs: original_cost(**kwargs, pricing_known=False)) + original_rename = storage.os.rename + def fail_candidate(source, destination): + if str(destination).endswith('/candidate_1/artifacts'): + raise OSError('review regression: candidate artifact publication interrupted') + return original_rename(source, destination) + monkeypatch.setattr(storage.os, 'rename', fail_candidate) + with pytest.raises(OSError): + optimizer.optimize(benchmark) + monkeypatch.setattr(storage.os, 'rename', original_rename) + assert llm.state['proposal'] == 1 and llm.state['execution'] == 4 + result = optimizer.optimize(benchmark) + assert result.score == 1 and result.status == 'exhausted' + assert llm.state['proposal'] == 3 and llm.state['execution'] == 8 + budget = json.loads(Path('results/reliable/aflow/budget.json').read_text()) + assert budget['known_spent'] == 0 + assert budget['reservations']['proposal_1']['reserved'] == pytest.approx(.1) + assert budget['reservations']['proposal_1']['status'] == 'finished' diff --git a/tests/src/optimizers/test_aflow_review_regressions.py b/tests/src/optimizers/test_aflow_review_regressions.py new file mode 100644 index 00000000..24c09d1a --- /dev/null +++ b/tests/src/optimizers/test_aflow_review_regressions.py @@ -0,0 +1,134 @@ +"""Independent review regressions for native accounting and durable recovery.""" +import asyncio +from types import SimpleNamespace + +import pytest + +from evoagentx.models.model_utils import cost_manager +from evoagentx.models.openrouter_model import OpenRouterLLM +from evoagentx.optimizers.aflow import ( + AdmissionBudget, + EvaluationPlan, + ReliableTrialConfig, + TrialStore, +) +from evoagentx.optimizers.aflow.evidence import CostLedger + + +def budget_store(tmp_path): + config = ReliableTrialConfig(max_known_cost=1, example_cost_bound=.8, proposal_cost_bound=.1) + return TrialStore(tmp_path, EvaluationPlan.create('local', [{'id': 'x'}], {}, 'v1', config)) + + +def priced_response(receiver): + OpenRouterLLM._update_cost(receiver, SimpleNamespace(id='priced', usage=SimpleNamespace( + prompt_tokens=1, completion_tokens=1, cost=.1))) + + +@pytest.mark.parametrize('provider', ['openrouter', 'openai', 'litellm', 'aliyun', 'novita', 'siliconflow']) +def test_mixed_native_missing_usage_retains_whole_operation_bound(tmp_path, provider): + from evoagentx.models.aliyun_model import AliyunLLM + from evoagentx.models.litellm_model import LiteLLM + from evoagentx.models.novita_model import NovitaLLM + from evoagentx.models.openai_model import OpenAILLM + from evoagentx.models.siliconflow_model import SiliconFlowLLM + cls = {'openrouter': OpenRouterLLM, 'openai': OpenAILLM, 'litellm': LiteLLM, + 'aliyun': AliyunLLM, 'novita': NovitaLLM, 'siliconflow': SiliconFlowLLM}[provider] + receiver = SimpleNamespace(config=SimpleNamespace(model='native-mixed-accounting')) + with budget_store(tmp_path) as store: + budget = AdmissionBudget(store, store.plan.config) + budget.admit('example', 'first') + ledger = CostLedger() + before = cost_manager.get_total_cost() + with cost_manager.observe(ledger.observe): + priced_response(receiver) + cls._update_cost(receiver, SimpleNamespace(id='missing', usage=None)) + snapshot = ledger.close() + assert snapshot['pricing'] == 'unknown' + assert snapshot['known_cost'] == pytest.approx(.1) + assert cost_manager.get_total_cost() - before == pytest.approx(.1) + budget.finish('first', snapshot['known_cost'], snapshot['pricing'] == 'known') + assert budget.report()['reserved'] == pytest.approx(.7) + assert budget.report()['pricing_uncertain'] + with pytest.raises(RuntimeError, match='cost'): + budget.admit('example', 'second') + + +@pytest.mark.parametrize('provider', ['openrouter', 'openai']) +@pytest.mark.parametrize('asynchronous', [False, True]) +def test_mixed_native_stream_without_usage_is_unknown(tmp_path, provider, asynchronous): + from evoagentx.models.openai_model import OpenAILLM + cls = OpenRouterLLM if provider == 'openrouter' else OpenAILLM + receiver = object.__new__(cls) + receiver.config = SimpleNamespace(model='native-stream-missing') + chunks = [SimpleNamespace(usage=None, choices=[SimpleNamespace(delta=SimpleNamespace(content='answer', tool_calls=None))])] + ledger = CostLedger() + async def stream(): + for chunk in chunks: + yield chunk + async def consume(): + return await receiver.get_stream_output_async(stream(), output_response=False) + with cost_manager.observe(ledger.observe): + priced_response(receiver) + if asynchronous: + assert asyncio.run(consume()) == 'answer' + else: + assert receiver.get_stream_output(iter(chunks), output_response=False) == 'answer' + assert ledger.close()['pricing'] == 'unknown' + + +@pytest.mark.parametrize('provider', ['openrouter', 'openai', 'litellm']) +@pytest.mark.parametrize('asynchronous', [False, True]) +def test_mixed_native_failed_call_keeps_prior_price_incomplete(provider, asynchronous, monkeypatch): + from evoagentx.models import litellm_model + from evoagentx.models.litellm_model import LiteLLM + from evoagentx.models.openai_model import OpenAILLM + cls = {'openrouter': OpenRouterLLM, 'openai': OpenAILLM, 'litellm': LiteLLM}[provider] + def failed(**kwargs): + raise ConnectionError('scripted provider boundary; completion usage unavailable') + async def failed_async(**kwargs): + raise ConnectionError('scripted provider boundary; completion usage unavailable') + client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=failed))) + async_client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=failed_async))) + receiver = SimpleNamespace(config=SimpleNamespace(model='native-failed-call', stream=False, output_response=False), + ensure_client=lambda: client, ensure_async_client=lambda: async_client, + get_completion_params=lambda **kwargs: {}, prepare_request=lambda messages, params: (messages, params), + _apply_provider_params=lambda params: params) + monkeypatch.setattr(litellm_model, 'completion', failed) + monkeypatch.setattr(litellm_model, 'acompletion', failed_async) + method = cls.single_generate_async if asynchronous else cls.single_generate + # Avoid transport retries/waits; this tests the native accounting boundary of + # one failed provider attempt, not Tenacity's implementation. + method = getattr(method, '__wrapped__', method) + ledger = CostLedger() + with cost_manager.observe(ledger.observe): + priced_response(receiver) + with pytest.raises(RuntimeError, match='scripted provider boundary'): + if asynchronous: + asyncio.run(method(receiver, [{'role': 'user', 'content': 'local'}])) + else: + method(receiver, [{'role': 'user', 'content': 'local'}]) + snapshot = ledger.close() + assert snapshot['known_cost'] == pytest.approx(.1) and snapshot['pricing'] == 'unknown' + + +@pytest.mark.parametrize('provider', ['openrouter', 'openai', 'litellm']) +def test_native_cancelled_call_marks_unknown_and_preserves_cancellation(provider, monkeypatch): + from evoagentx.models import litellm_model + from evoagentx.models.litellm_model import LiteLLM + from evoagentx.models.openai_model import OpenAILLM + cls = {'openrouter': OpenRouterLLM, 'openai': OpenAILLM, 'litellm': LiteLLM}[provider] + async def cancelled(**kwargs): + raise asyncio.CancelledError + client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=cancelled))) + receiver = SimpleNamespace(config=SimpleNamespace(model='native-cancelled', stream=False, output_response=False), + ensure_async_client=lambda: client, get_completion_params=lambda **kwargs: {}, + prepare_request=lambda messages, params: (messages, params), _apply_provider_params=lambda params: params) + monkeypatch.setattr(litellm_model, 'acompletion', cancelled) + method = getattr(cls.single_generate_async, '__wrapped__', cls.single_generate_async) + ledger = CostLedger() + with cost_manager.observe(ledger.observe): + priced_response(receiver) + with pytest.raises(asyncio.CancelledError): + asyncio.run(method(receiver, [{'role': 'user', 'content': 'local'}])) + assert ledger.close()['pricing'] == 'unknown'