verifiers 0.3.1.dev60__py3-none-any.whl → 0.3.1.dev62__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,8 @@
2
2
 
3
3
  import contextlib
4
4
  import time
5
+ from collections import deque
6
+ from pathlib import Path
5
7
  from typing import TYPE_CHECKING
6
8
 
7
9
  from pydantic import BaseModel
@@ -13,7 +15,7 @@ from rich.table import Table
13
15
  from rich.text import Text
14
16
 
15
17
  from verifiers.v1.cli.dashboard.base import live_view
16
- from verifiers.v1.cli.output import output_path
18
+ from verifiers.v1.cli.output import attempt_log_file, output_path
17
19
  from verifiers.v1.configs.cli.eval import EvalConfig
18
20
  from verifiers.v1.env import RunSlot
19
21
  from verifiers.v1.trace import Trace
@@ -499,10 +501,11 @@ def _stage(trace: Trace) -> str:
499
501
 
500
502
  def _started(slot: RunSlot) -> float:
501
503
  # Sort key: when a rollout began (its first trace's boot start; setup for
502
- # pre-boot-span traces on resume). A still-pending rollout has no trace yet, so it
503
- # sorts last (+inf) — behind everything already in flight, in task order.
504
+ # pre-boot-span traces on resume; the slot's own dispatch stamp on a served run).
505
+ # A still-pending rollout has neither, so it sorts last (+inf) — behind everything
506
+ # already in flight, in task order.
504
507
  if not slot.traces:
505
- return float("inf")
508
+ return slot.started if slot.started is not None else float("inf")
506
509
  return min(t.timing.boot.start or t.timing.setup.start for t in slot.traces)
507
510
 
508
511
 
@@ -549,6 +552,13 @@ def Rows(groups: list[list[RunSlot]], now: float, runtime_type: str) -> Table:
549
552
  "",
550
553
  )
551
554
  )
555
+ elif slot.started is not None:
556
+ # Dispatched to an env server: running, but with no live trace to
557
+ # read stages/turns from — detail lands when the episode completes.
558
+ elapsed = format_time(now - slot.started)
559
+ group_rows.append(
560
+ ("running", [f"task {base}", *[""] * 7], "", elapsed)
561
+ )
552
562
  else: # queued behind the concurrency cap — only its task is known yet
553
563
  group_rows.append(("pending", [f"task {base}", *[""] * 7], "", ""))
554
564
  continue
@@ -687,6 +697,55 @@ class Pager:
687
697
  return self.page
688
698
 
689
699
 
700
+ _TAIL_BYTES = 256 * 1024
701
+ """How far back into a pre-existing log file the tail's first read reaches."""
702
+
703
+
704
+ class LogTail:
705
+ """Incremental tail of the run's log file for `--rich.show-logs`: read only what
706
+ was appended since the last frame, keep a bounded window of whole lines."""
707
+
708
+ def __init__(self, path: Path, max_lines: int = 1000) -> None:
709
+ self.path = path
710
+ self.lines: deque[str] = deque(maxlen=max_lines)
711
+ self._pos: int | None = None
712
+ self._partial = ""
713
+
714
+ def _poll(self) -> None:
715
+ try:
716
+ size = self.path.stat().st_size
717
+ except OSError: # not written yet — the first record creates it
718
+ return
719
+ if (
720
+ self._pos is not None and size < self._pos
721
+ ): # truncated/replaced — start over
722
+ self._pos, self._partial = None, ""
723
+ if size == self._pos:
724
+ return
725
+ # The first read starts at most _TAIL_BYTES from the end: a pre-existing file
726
+ # (a reused run dir) must not be read whole on the render path.
727
+ first = self._pos is None
728
+ start = max(0, size - _TAIL_BYTES) if first else self._pos
729
+ with self.path.open("rb") as file:
730
+ file.seek(start)
731
+ data = file.read()
732
+ self._pos = file.tell()
733
+ chunk = data.decode("utf-8", errors="replace")
734
+ *complete, self._partial = (self._partial + chunk).split("\n")
735
+ if first and start: # landed mid-line — drop the cut first line
736
+ complete = complete[1:]
737
+ self.lines.extend(complete)
738
+
739
+ def view(self, height: int) -> Group:
740
+ """The newest lines that fit, one Text per line (no markup parsing — log
741
+ content stays literal), each cropped to the terminal width."""
742
+ self._poll()
743
+ window = list(self.lines)[-height:]
744
+ return Group(
745
+ *(Text(line, no_wrap=True, overflow="ellipsis") for line in window)
746
+ )
747
+
748
+
690
749
  def _rows_of(group: list[RunSlot]) -> int:
691
750
  """How many display rows a task's slots take: one per trace, one for a slot with
692
751
  none yet (pending) or none at all (the env's hook failed before any trace)."""
@@ -727,6 +786,7 @@ def _render(
727
786
  start: float,
728
787
  pager: Pager,
729
788
  push: "PushState | None" = None,
789
+ tail: LogTail | None = None,
730
790
  ) -> Group:
731
791
  now = time.time()
732
792
  warning = _warning(config)
@@ -741,6 +801,16 @@ def _render(
741
801
  if footer is not None:
742
802
  reserved += len(_CONSOLE.render_lines(footer))
743
803
  rows_per_page = max(1, _CONSOLE.size.height - reserved - 1)
804
+ if tail is not None: # --show-logs: the run's log stream in place of rollout rows
805
+ parts = [
806
+ header,
807
+ Progress(slots, start),
808
+ Rule(style="dim"),
809
+ tail.view(rows_per_page),
810
+ ]
811
+ if footer is not None:
812
+ parts.append(footer)
813
+ return Group(*parts)
744
814
  page_groups, index, count = _paginate(_groups(slots), rows_per_page, pager, now)
745
815
  progress = Progress(
746
816
  slots,
@@ -776,8 +846,13 @@ async def dashboard(
776
846
  push: "PushState | None" = None,
777
847
  ):
778
848
  pager = Pager()
849
+ tail = (
850
+ LogTail(attempt_log_file(output_path(config)))
851
+ if config.rich is not None and config.rich.show_logs
852
+ else None
853
+ )
779
854
  async with live_view(
780
- lambda: _render(slots, config, start, pager, push),
855
+ lambda: _render(slots, config, start, pager, push, tail),
781
856
  on_key=pager.on_key,
782
857
  ):
783
858
  yield
@@ -8,11 +8,11 @@ import sys
8
8
 
9
9
  from pydantic_config import cli
10
10
 
11
- import verifiers.v1 as vf
12
11
  from verifiers.v1.cli.eval.runner import run_eval
13
12
  from verifiers.v1.cli.output import (
14
13
  TRACES_FILE,
15
14
  config_digest,
15
+ create_attempt_log_dir,
16
16
  output_path,
17
17
  saved_config_path,
18
18
  write_config,
@@ -116,18 +116,12 @@ def main(argv: list[str] | None = None) -> None:
116
116
  setup_logging("DEBUG" if config.verbose else "INFO")
117
117
  logger.info("wrote config to %s", write_config(config, output_path(config)))
118
118
  return
119
- # Execution path: in-process by default; `--server` opts into the env-server worker pool
120
- # (the path prime-rl trains through). The `--rich` dashboard reads live in-process run
121
- # slots, so it's in-process only (`server + rich` is rejected at config validation).
122
- # Always tee the run's logs to a file under the output dir (in-process and server mode).
123
- log_file = str(output_path(config) / "logs" / "eval.log")
119
+ # Always tee this attempt's logs to `logs/attempt_<n>/eval.log` (`logs/latest`
120
+ # points there) — in server mode (the default) the workers write there too, and
121
+ # `--rich.show-logs` tails it live.
122
+ log_file = str(create_attempt_log_dir(output_path(config)) / "eval.log")
124
123
  level = "DEBUG" if config.verbose else "INFO"
125
- if config.rich:
126
- setup_logging(level, log_file=log_file, console=False)
127
- # drop stray stdlib records that bypass loguru (else they print over the UI)
128
- logging.lastResort = None
129
- else:
130
- setup_logging(level, log_file=log_file, console=True)
124
+ setup_logging(level, log_file=log_file, console=config.rich is None)
131
125
  # First Ctrl-C / SIGTERM warns and raises KeyboardInterrupt so a killed/timed-out eval still
132
126
  # runs each rollout's `finally` (tears down containers/sandboxes) and any worker pool it
133
127
  # spawned; further signals during that cleanup are swallowed so an impatient second Ctrl-C
@@ -135,22 +129,19 @@ def main(argv: list[str] | None = None) -> None:
135
129
  install_interrupt()
136
130
 
137
131
  try:
138
- if config.server: # opt-in: drive rollouts through the env-server worker pool
139
- from verifiers.v1.cli.eval.runner import run_eval_server
140
-
141
- episodes = asyncio.run(run_eval_server(config))
142
- else: # in-process (default), with or without the live dashboard
143
- env = vf.load_environment(config.env)
144
- episodes = asyncio.run(run_eval(env, config))
132
+ # Through the env-server worker pool by default; in-process with --no-serve.
133
+ episodes = asyncio.run(run_eval(config))
145
134
  except KeyboardInterrupt:
146
135
  # Graceful cleanup has already run (each rollout's `finally`); partial results are on
147
136
  # disk. Exit on the conventional Ctrl-C code without a traceback.
148
137
  raise SystemExit(130)
149
- if config.push and not config.rich:
138
+ if config.push and config.rich is None:
150
139
  from verifiers.v1.utils.platform import push_traces
151
140
 
152
141
  push_traces(episodes, config)
153
- if not config.rich: # --rich is the whole output; otherwise dump each trace as JSON
142
+ if (
143
+ config.rich is None
144
+ ): # --rich is the whole output; otherwise dump each trace as JSON
154
145
  for episode in episodes:
155
146
  for trace in episode.traces:
156
147
  print(trace.model_dump_json(indent=2, exclude_none=True))
@@ -1,30 +1,150 @@
1
- """The eval runner: fan episodes out with bounded concurrency."""
1
+ """The eval runner: fan episodes out with bounded concurrency.
2
+
3
+ Rollouts run through the env-server worker pool by default (`[serve]` sizes it;
4
+ elastic — one worker, scaling on demand), the same path prime-rl trains through.
5
+ `--no-serve` runs them in-process instead. Both paths share this runner — task
6
+ selection, resume, persistence, the dashboard — and differ only in how one slot
7
+ becomes one episode: `env.run_slot` in-process, a `run` request to the pool
8
+ otherwise. The dashboard watches the same `RunSlot`s either way; a served slot
9
+ has no live traces, so its per-turn detail lands when the episode completes.
10
+ """
2
11
 
3
12
  import asyncio
4
13
  import contextlib
5
14
  import logging
6
15
  import time
16
+ from collections.abc import AsyncIterator, Awaitable, Callable
7
17
  from typing import cast
8
18
 
9
19
  from verifiers.v1.cli.dashboard import dashboard
10
20
  from verifiers.v1.cli.eval import resume
11
21
  from verifiers.v1.cli.output import (
12
22
  append_episode,
23
+ attempt_log_file,
13
24
  output_path,
14
25
  save_config,
15
26
  )
16
27
  from verifiers.v1.cli.resume import distribute
17
28
  from verifiers.v1.clients import ModelContext
18
29
  from verifiers.v1.configs.cli.eval import EvalConfig
30
+ from verifiers.v1.configs.serve import ServeConfig
19
31
  from verifiers.v1.env import Env, RunSlot
20
32
  from verifiers.v1.episode import Episode, EvalRunInfo
21
33
 
22
34
  logger = logging.getLogger(__name__)
23
35
 
36
+ RunSlotFn = Callable[[RunSlot], Awaitable[Episode]]
37
+ OnComplete = Callable[[Episode], Awaitable[None]]
38
+
39
+
40
+ @contextlib.asynccontextmanager
41
+ async def _in_process(
42
+ env: Env,
43
+ config: EvalConfig,
44
+ semaphore: asyncio.Semaphore | None,
45
+ on_complete: OnComplete,
46
+ ) -> AsyncIterator[RunSlotFn]:
47
+ """Run slots in-process: serving resources (shared tool servers, interception)
48
+ come up once for the run; the env's agents borrow them."""
49
+ ctx = ModelContext(
50
+ client=config.client, model=config.model, sampling=config.sampling
51
+ )
52
+
53
+ async def run(slot: RunSlot) -> Episode:
54
+ return await env.run_slot(slot, ctx, semaphore, on_complete)
55
+
56
+ async with env.serving():
57
+ yield run
58
+
59
+
60
+ @contextlib.asynccontextmanager
61
+ async def _server(
62
+ config: EvalConfig,
63
+ serve: ServeConfig,
64
+ semaphore: asyncio.Semaphore | None,
65
+ on_complete: OnComplete,
66
+ ) -> AsyncIterator[RunSlotFn]:
67
+ """Run slots through a spawned env-server worker pool: each rollout is its own
68
+ `run` request, dispatched least-busy across workers. The workers own the env
69
+ (and its serving resources); this process owns the taskset and the results."""
70
+ import multiprocessing as mp
71
+ from functools import partial
72
+
73
+ from verifiers.v1.configs.serve import pool_serve_kwargs
74
+ from verifiers.v1.serve import EnvClient, env_config_data, serve_env
75
+ from verifiers.v1.utils.logging import setup_logging
76
+
77
+ # Spawned processes inherit no logging — hand them the main process's setup so
78
+ # their rollout logs land in the output dir. They share its stderr, so console
79
+ # output follows the main process's choice: off under the dashboard (worker log
80
+ # lines would print over the Live view and shift it), on otherwise.
81
+ level = "DEBUG" if config.verbose else "INFO"
82
+ log_file = str(attempt_log_file(output_path(config)))
83
+ console = config.rich is None
84
+ mpctx = mp.get_context("spawn")
85
+ address_queue: mp.Queue = mpctx.Queue()
86
+ # Death pipe: serve_env self-terminates if this process dies abruptly — we keep
87
+ # parent_conn, whose close (even on our SIGKILL) signals the child's watch.
88
+ parent_conn, child_conn = mpctx.Pipe()
89
+ proc = mpctx.Process(
90
+ target=serve_env,
91
+ kwargs=dict(
92
+ **pool_serve_kwargs(serve.pool),
93
+ address="tcp://127.0.0.1:0",
94
+ address_queue=address_queue,
95
+ death_pipe=child_conn,
96
+ log_setup=partial(setup_logging, level, log_file, console),
97
+ config_data=env_config_data(config.env), # picklable across the spawn
98
+ # `-c` seeds each worker's episode bound unless `[serve]` pins one — so a
99
+ # pool carries `workers * bound` episodes, as `multiplex` implies.
100
+ max_concurrent=serve.max_concurrent
101
+ if serve.max_concurrent is not None
102
+ else config.max_concurrent,
103
+ ),
104
+ daemon=False,
105
+ )
106
+ proc.start()
107
+ child_conn.close() # the child holds its end; we keep parent_conn so our exit closes it
108
+ try:
109
+ address = await asyncio.to_thread(address_queue.get, timeout=600)
110
+ client = EnvClient(address=address)
111
+ try:
112
+ await client.wait_for_server_startup(timeout=600)
113
+
114
+ async def run(slot: RunSlot) -> Episode:
115
+ async with semaphore or contextlib.nullcontext():
116
+ slot.started = time.time()
117
+ episode = await client.run(
118
+ client=config.client,
119
+ model=config.model,
120
+ sampling=config.sampling,
121
+ task_data=slot.task.data.model_dump(mode="json"),
122
+ )
123
+ slot.traces = list(episode.traces)
124
+ slot.episode = cast(Episode, episode)
125
+ slot.done = True
126
+ await on_complete(cast(Episode, episode))
127
+ return cast(Episode, episode)
128
+
129
+ yield run
130
+ finally:
131
+ await client.close()
132
+ finally:
133
+ proc.terminate()
134
+ with contextlib.suppress(Exception):
135
+ await asyncio.to_thread(proc.join, 10)
136
+ with contextlib.suppress(Exception):
137
+ parent_conn.close()
138
+
139
+
140
+ async def run_eval(config: EvalConfig) -> list[Episode]:
141
+ from verifiers.v1.utils.loaders import load_environment, load_taskset
24
142
 
25
- async def run_eval(env: Env, config: EvalConfig) -> list[Episode]:
26
143
  logger.info("eval config:\n%s", config.model_dump_json(indent=2))
27
- taskset = env.taskset
144
+ # The env comes up in this process only for an in-process run; a served run's
145
+ # workers each load their own, and this process owns just the taskset.
146
+ env = None if config.serve is not None else load_environment(config.env)
147
+ taskset = env.taskset if env is not None else load_taskset(config.env.taskset)
28
148
  if config.num_tasks is None and taskset.INFINITE:
29
149
  raise ValueError(
30
150
  f"{type(taskset).__name__} is infinite - bound the run with -n"
@@ -33,12 +153,6 @@ async def run_eval(env: Env, config: EvalConfig) -> list[Episode]:
33
153
  if config.num_tasks is not None:
34
154
  selected = selected.head(config.num_tasks)
35
155
  tasks = list(selected)
36
- ctx = ModelContext(
37
- client=config.client, model=config.model, sampling=config.sampling
38
- )
39
- semaphore = (
40
- asyncio.Semaphore(config.max_concurrent) if config.max_concurrent else None
41
- )
42
156
  out = output_path(config)
43
157
  # One (task, rollouts-to-run) pair per selected task; resume shrinks the counts.
44
158
  plan = [(task, config.num_rollouts) for task in tasks]
@@ -46,12 +160,14 @@ async def run_eval(env: Env, config: EvalConfig) -> list[Episode]:
46
160
  finished: list[Episode] = []
47
161
  if config.resume:
48
162
  keys = [task.hash for task in tasks]
49
- loaded, owed = resume.load(
50
- out,
51
- keys,
52
- config.num_rollouts,
53
- lambda episode: env.complete(cast(Episode, episode)),
163
+ # In-process, the env's own keep-verdict decides what resumes; a served run
164
+ # can't ask the worker-side env, so it keeps the default `episode.ok`.
165
+ complete = (
166
+ (lambda episode: env.complete(cast(Episode, episode)))
167
+ if env is not None
168
+ else None
54
169
  )
170
+ loaded, owed = resume.load(out, keys, config.num_rollouts, complete)
55
171
  finished = [cast(Episode, episode) for episode in loaded]
56
172
  if not owed: # already complete - report it and exit successfully
57
173
  print(resume.nothing_to_resume_msg(out, len(tasks), config.num_rollouts))
@@ -66,40 +182,60 @@ async def run_eval(env: Env, config: EvalConfig) -> list[Episode]:
66
182
  )
67
183
  else:
68
184
  save_config(config, out)
185
+ via = (
186
+ f" via the env-server {config.serve.pool.type} pool"
187
+ if config.serve is not None
188
+ else ""
189
+ )
69
190
  logger.info(
70
- "running %dx%d rollouts on %s",
71
- len(tasks),
191
+ "running %dx%d rollouts on %s%s",
192
+ len(plan),
72
193
  config.num_rollouts,
73
194
  config.model,
195
+ via,
74
196
  )
75
197
  start = time.time()
76
198
  logger.info("results: %s", out)
77
199
 
200
+ semaphore = (
201
+ asyncio.Semaphore(config.max_concurrent) if config.max_concurrent else None
202
+ )
78
203
  write_lock = asyncio.Lock()
79
204
 
80
205
  async def on_complete(episode: Episode) -> None:
81
206
  episode.record_run(EvalRunInfo(id=config.run.id, name=config.run.name))
82
207
  await append_episode(out, episode, write_lock)
83
208
 
84
- # Serving resources (shared tool servers, interception) come up once for the
85
- # run; plan slots inside so the env's agents borrow them.
86
- async with env.serving():
87
- planned = [slot for task, n in plan for slot in env.slots(task, n=n)]
209
+ backend = (
210
+ _in_process(env, config, semaphore, on_complete)
211
+ if env is not None
212
+ else _server(config, config.serve, semaphore, on_complete)
213
+ )
214
+ async with backend as run_slot:
215
+ # The display slots: in-process ones are the env's own (it fills their live
216
+ # traces); a served rollout's is a client-side stand-in its worker never sees.
217
+ planned = [
218
+ slot
219
+ for task, n in plan
220
+ for slot in (
221
+ env.slots(task, n)
222
+ if env is not None
223
+ else [RunSlot(task) for _ in range(n)]
224
+ )
225
+ ]
88
226
  slots = [RunSlot.finished(episode) for episode in finished] + planned
89
227
  push_state = None
90
- if config.push and config.rich:
228
+ if config.push and config.rich is not None:
91
229
  from verifiers.v1.utils.platform import PushState
92
230
 
93
231
  push_state = PushState()
94
232
  display = (
95
233
  dashboard(slots, config, start, push=push_state)
96
- if config.rich
234
+ if config.rich is not None
97
235
  else contextlib.nullcontext()
98
236
  )
99
237
  async with display:
100
- results = await asyncio.gather(
101
- *(env.run_slot(slot, ctx, semaphore, on_complete) for slot in planned)
102
- )
238
+ results = await asyncio.gather(*(run_slot(slot) for slot in planned))
103
239
  episodes = finished + list(results)
104
240
  if (
105
241
  push_state is not None
@@ -109,120 +245,3 @@ async def run_eval(env: Env, config: EvalConfig) -> list[Episode]:
109
245
  push_state.started = True
110
246
  await asyncio.to_thread(push_traces, episodes, config, push_state)
111
247
  return episodes
112
-
113
-
114
- async def run_eval_server(config: EvalConfig) -> list[Episode]:
115
- """Run evaluation through the env-server worker pool."""
116
- import multiprocessing as mp
117
- from functools import partial
118
-
119
- from verifiers.v1.configs.serve import pool_serve_kwargs
120
- from verifiers.v1.serve import EnvClient, env_config_data, serve_env
121
- from verifiers.v1.utils.loaders import load_taskset
122
- from verifiers.v1.utils.logging import setup_logging
123
-
124
- server_kwargs = {
125
- "config_data": env_config_data(config.env), # picklable across the spawn
126
- # `-c` seeds each worker's episode bound unless `[serve]` pins one — so a
127
- # pool carries `workers * bound` episodes, as `multiplex` implies.
128
- "max_concurrent": config.worker_max_concurrent,
129
- }
130
- # The client owns the taskset: load it here, once — the server (and its pool
131
- # workers) never load data, they rebuild each dispatched task from its request.
132
- taskset = load_taskset(config.env.taskset)
133
- if config.num_tasks is None and taskset.INFINITE:
134
- raise ValueError(
135
- f"{type(taskset).__name__} is infinite - bound the run with -n"
136
- )
137
- selected = taskset.shuffle() if config.shuffle else taskset
138
- if config.num_tasks is not None:
139
- selected = selected.head(config.num_tasks)
140
- tasks = list(selected)
141
- # Spawned processes inherit no logging — hand them the main process's setup so
142
- # their rollout logs land in the output dir.
143
- level = "DEBUG" if config.verbose else "INFO"
144
- log_file = str(output_path(config) / "logs" / "eval.log")
145
- mpctx = mp.get_context("spawn")
146
- address_queue: mp.Queue = mpctx.Queue()
147
- # Death pipe: serve_env self-terminates if this process dies abruptly — we keep
148
- # parent_conn, whose close (even on our SIGKILL) signals the child's watch.
149
- parent_conn, child_conn = mpctx.Pipe()
150
- proc = mpctx.Process(
151
- target=serve_env,
152
- kwargs=dict(
153
- **pool_serve_kwargs(config.serve.pool),
154
- address="tcp://127.0.0.1:0",
155
- address_queue=address_queue,
156
- death_pipe=child_conn,
157
- log_setup=partial(setup_logging, level, log_file),
158
- **server_kwargs,
159
- ),
160
- daemon=False,
161
- )
162
- proc.start()
163
- child_conn.close() # the child holds its end; we keep parent_conn so our exit closes it
164
- try:
165
- address = await asyncio.to_thread(address_queue.get, timeout=600)
166
- client = EnvClient(address=address)
167
- await client.wait_for_server_startup(timeout=600)
168
- # A run dispatches — and resumes — tasks by content: the client owns them,
169
- # and `task.hash` is their identity.
170
- plan = [
171
- ({"task_data": task.data.model_dump(mode="json")}, config.num_rollouts)
172
- for task in tasks
173
- ]
174
- out = output_path(config)
175
- finished: list[Episode] = []
176
- if config.resume:
177
- keys = [task.hash for task in tasks]
178
- loaded, owed = resume.load(out, keys, config.num_rollouts)
179
- finished = [cast(Episode, episode) for episode in loaded]
180
- counts = distribute(keys, owed, config.num_rollouts)
181
- if not owed: # already complete - report it and exit successfully
182
- print(resume.nothing_to_resume_msg(out, len(plan), config.num_rollouts))
183
- raise SystemExit(0)
184
- plan = [(payload, n) for (payload, _), n in zip(plan, counts) if n]
185
- logger.info(
186
- "resuming %s: %d task(s), %d rollout(s) owed",
187
- out,
188
- len(plan),
189
- sum(owed.values()),
190
- )
191
- else:
192
- save_config(config, out)
193
- logger.info(
194
- "running %dx%d rollouts via the env-server %s pool on %s",
195
- len(plan),
196
- config.num_rollouts,
197
- config.serve.pool.type,
198
- config.model,
199
- )
200
- logger.info("results: %s", out)
201
- semaphore = (
202
- asyncio.Semaphore(config.max_concurrent) if config.max_concurrent else None
203
- )
204
- write_lock = asyncio.Lock()
205
-
206
- async def run_unit(payload: dict) -> list[Episode]:
207
- async with semaphore or contextlib.nullcontext():
208
- episode = await client.run(
209
- client=config.client,
210
- model=config.model,
211
- sampling=config.sampling,
212
- **payload,
213
- )
214
- episode.record_run(EvalRunInfo(id=config.run.id, name=config.run.name))
215
- await append_episode(out, episode, write_lock)
216
- return [cast(Episode, episode)]
217
-
218
- # Each rollout is its own `run` request, dispatched least-busy across workers.
219
- units = [run_unit(payload) for payload, n in plan for _ in range(n)]
220
- results = await asyncio.gather(*units)
221
- await client.close()
222
- return finished + [record for unit in results for record in unit]
223
- finally:
224
- proc.terminate()
225
- with contextlib.suppress(Exception):
226
- await asyncio.to_thread(proc.join, 10)
227
- with contextlib.suppress(Exception):
228
- parent_conn.close()
@@ -12,6 +12,7 @@ by this surface contain episodes only.
12
12
  import asyncio
13
13
  import hashlib
14
14
  import json
15
+ import os
15
16
  from functools import cache
16
17
  from pathlib import Path
17
18
 
@@ -33,6 +34,40 @@ via `@ <run-dir>/configs/<cli>.json`). Resolved configs are JSON, not TOML: JSON
33
34
  nulls, so explicit None settings round-trip exactly on re-parse."""
34
35
 
35
36
 
37
+ def create_attempt_log_dir(run_dir: Path) -> Path:
38
+ """Create `logs/attempt_<n>` for this launch attempt and atomically repoint the
39
+ relative `logs/latest` symlink at it (prime-rl's log layout). Every launch —
40
+ fresh or `--resume` — gets its own numbered log directory, so a resume never
41
+ appends to an earlier attempt's logs."""
42
+ logs_dir = run_dir / "logs"
43
+ logs_dir.mkdir(parents=True, exist_ok=True)
44
+ attempts = (
45
+ int(p.name.removeprefix("attempt_"))
46
+ for p in logs_dir.glob("attempt_*")
47
+ if p.name.removeprefix("attempt_").isdigit()
48
+ )
49
+ attempt_dir = logs_dir / f"attempt_{1 + max(attempts, default=0)}"
50
+ attempt_dir.mkdir()
51
+ # Atomically repoint the relative `latest` symlink: create a temp link, then rename.
52
+ tmp_link = logs_dir / f".{attempt_dir.name}"
53
+ if tmp_link.is_symlink() or tmp_link.exists():
54
+ tmp_link.unlink()
55
+ os.symlink(attempt_dir.name, tmp_link)
56
+ os.replace(tmp_link, logs_dir / "latest")
57
+ return attempt_dir
58
+
59
+
60
+ def attempt_log_file(run_dir: Path) -> Path:
61
+ """The current attempt's `eval.log`. The CLI creates the attempt dir once at
62
+ startup; everyone after it — the runner's worker spawn, the dashboard's log
63
+ tail — resolves through `logs/latest`, so the whole invocation shares one file.
64
+ A direct `run_eval` call (no CLI) creates the first attempt itself."""
65
+ latest = run_dir / "logs" / "latest"
66
+ if not latest.exists():
67
+ create_attempt_log_dir(run_dir)
68
+ return latest / "eval.log"
69
+
70
+
36
71
  def config_digest(config: BaseModel) -> str:
37
72
  """Canonical hash of a resolved config's full model dump (nulls included)."""
38
73
  dump = config.model_dump(mode="json")
@@ -229,11 +229,7 @@ def main(argv: list[str] | None = None) -> None:
229
229
  return
230
230
 
231
231
  log_file = str(out / "logs" / "replay.log")
232
- if config.rich:
233
- setup_logging(level, log_file=log_file, console=False)
234
- logging.lastResort = None
235
- else:
236
- setup_logging(level, log_file=log_file, console=True)
232
+ setup_logging(level, log_file=log_file, console=not config.rich)
237
233
  # Graceful shutdown: first Ctrl-C/SIGTERM unwinds the scoring teardown `finally`;
238
234
  # a second is swallowed so it can't orphan resources mid-cleanup.
239
235
  install_interrupt()
@@ -503,8 +503,6 @@ def main(argv: list[str] | None = None) -> None:
503
503
  log_file=str(out / LOG_FILE),
504
504
  console=not config.rich,
505
505
  )
506
- if config.rich:
507
- logging.lastResort = None # drop stdlib records that bypass loguru
508
506
  # Graceful shutdown: first Ctrl-C/SIGTERM unwinds each task's teardown `finally`
509
507
  # (containers/sandboxes); a second is swallowed so it can't orphan them mid-cleanup.
510
508
  install_interrupt()
@@ -32,6 +32,14 @@ def default_run_name(env: EnvConfig, model: str) -> str:
32
32
  return slug.lower()
33
33
 
34
34
 
35
+ class RichConfig(BaseConfig):
36
+ """The live dashboard."""
37
+
38
+ show_logs: bool = False
39
+ """Replace the dashboard's per-rollout rows with a live tail of the attempt's log
40
+ file (`logs/latest/eval.log`) — the env's own log lines included."""
41
+
42
+
35
43
  class RunConfig(BaseConfig):
36
44
  name: str | None = None
37
45
  """Run name. Auto-generated as `<env>--<model>--<harness>--<short-id>` when unset."""
@@ -52,9 +60,10 @@ class EvalConfig(BaseConfig):
52
60
  env: SerializeAsAny[EnvConfig] = SingleAgentEnvConfig()
53
61
  """The environment — which env, its seed taskset, each agent, its knobs. Narrowed to
54
62
  the selected env's config class by the env id, else the taskset id."""
55
- serve: ServeConfig = ServeConfig()
56
- """How the env is hosted under `--server`: the worker pool, each worker's episode
57
- bound. Ignored by an in-process run."""
63
+ serve: ServeConfig | None = Field(default_factory=ServeConfig)
64
+ """How the env is hosted: the env-server worker pool (elastic by default) and each
65
+ worker's episode bound — the path prime-rl trains through. `--no-serve` runs the
66
+ rollouts in-process instead."""
58
67
  run: RunConfig = Field(default_factory=RunConfig)
59
68
  """Run identity: `run.name` names the run directory under `output_dir`, `run.id` is
60
69
  stamped on traces."""
@@ -85,7 +94,7 @@ class EvalConfig(BaseConfig):
85
94
  )
86
95
  """Episodes in flight at once, `None` for no limit. An episode plays its agents one
87
96
  at a time, so this is the live agent runs too — until `--env.max-concurrent-agents`
88
- says otherwise. Under `--server` it seeds each worker's bound, unless
97
+ says otherwise. Under `[serve]` it also seeds each worker's bound, unless
89
98
  `--serve.max-concurrent` pins one."""
90
99
  verbose: bool = Field(False, validation_alias=AliasChoices("verbose", "v"))
91
100
  """Log at debug level instead of the default info."""
@@ -95,12 +104,10 @@ class EvalConfig(BaseConfig):
95
104
  clean: bool = Field(False, exclude=True)
96
105
  """Delete the run directory (`output_dir / run.dir`) before running, overwriting a
97
106
  previous run's results. Excluded from the saved config."""
98
- rich: bool = True
99
- """Show a live dashboard instead of per-rollout logs (in-process only; an unset
100
- `rich` defaults off under `--server`)."""
101
- server: bool = False
102
- """Drive rollouts through the env-server worker pool (sized by `[serve]`) instead of
103
- in-process — the path prime-rl trains through. Incompatible with `--rich`."""
107
+ rich: RichConfig | None = Field(default_factory=RichConfig)
108
+ """The live dashboard (on by default; `--no-rich` streams logs to the console
109
+ instead). A served run has no live per-turn view, so its rollout rows fill in as
110
+ each episode completes; `--rich.show-logs` swaps the rows for the run's logs."""
104
111
  push: bool = True
105
112
  """Upload the finished run to the Prime Intellect platform (the private Evaluations
106
113
  tab) at the end of the eval. On by default; disable with `--no-push`. Needs
@@ -116,34 +123,10 @@ class EvalConfig(BaseConfig):
116
123
  run's own config — e.g. `uv run eval @ <run-dir>/config.toml --resume`. Excluded
117
124
  from the saved config."""
118
125
 
119
- @model_validator(mode="after")
120
- def reject_rich_with_server(self):
121
- """The dashboard reads live in-process run slots, so it can't ride the
122
- worker pool: an unset `rich` defaults off under `--server`; an explicit
123
- `--rich --server` is refused."""
124
- if self.server and self.rich:
125
- if "rich" not in self.model_fields_set:
126
- self.rich = False
127
- return self
128
- raise ValueError(
129
- "`--rich` (the live dashboard) runs in-process and can't be combined with "
130
- "`--server`; drop `--rich`."
131
- )
132
- return self
133
-
134
126
  @property
135
127
  def env_id(self) -> str:
136
128
  return self.env.env_id or ""
137
129
 
138
- @property
139
- def worker_max_concurrent(self) -> int | None:
140
- """A served worker's episode bound: its own pin, else the run's `--max-concurrent`."""
141
- return (
142
- self.serve.max_concurrent
143
- if self.serve.max_concurrent is not None
144
- else self.max_concurrent
145
- )
146
-
147
130
  @model_validator(mode="before")
148
131
  @classmethod
149
132
  def _resolve_env(cls, data):
verifiers/v1/env.py CHANGED
@@ -50,12 +50,15 @@ def _as_error(e: Exception) -> Error:
50
50
  @dataclass
51
51
  class RunSlot:
52
52
  """One planned episode, observable while it happens: `traces` collects the
53
- current attempt (a retry restarts the list), `episode`/`done` land when final."""
53
+ current attempt (a retry restarts the list), `episode`/`done` land when final.
54
+ A runner that can't watch live traces (the env-server path) stamps `started`
55
+ at dispatch so the slot still reads as running."""
54
56
 
55
57
  task: Task
56
58
  traces: list[Trace] = field(default_factory=list)
57
59
  episode: Episode | None = None
58
60
  done: bool = False
61
+ started: float | None = None
59
62
 
60
63
  @classmethod
61
64
  def finished(cls, episode: Episode) -> "RunSlot":
@@ -68,7 +68,10 @@ def narrow_plugin_field(
68
68
 
69
69
 
70
70
  def _import_plugin(plugin_id: str, kind: str, group: str) -> ModuleType:
71
- module = plugin_id.replace("-", "_").lower()
71
+ # Hub ids are `owner/name[@version]` (installed as just `name`); strip both
72
+ # before normalizing so a hub id imports the same module a bare id would.
73
+ name = plugin_id.rsplit("/", 1)[-1].split("@", 1)[0]
74
+ module = name.replace("-", "_").lower()
72
75
  namespaced = f"{group}.{module}"
73
76
  target = namespaced if importlib.util.find_spec(namespaced) else module
74
77
  try:
@@ -46,6 +46,10 @@ def setup_logging(
46
46
  logger.remove()
47
47
  if console:
48
48
  logger.add(sys.stderr, level=lvl, format=FORMAT)
49
+ else:
50
+ # The terminal is off-limits: stray stdlib records that bypass the intercept
51
+ # below must not fall through to stderr either (they'd print over the UI).
52
+ logging.lastResort = None
49
53
  if log_file is not None:
50
54
  Path(log_file).parent.mkdir(parents=True, exist_ok=True)
51
55
  logger.add(log_file, level=lvl, format=FORMAT)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.3.1.dev60
3
+ Version: 0.3.1.dev62
4
4
  Summary: Verifiers: Environments for LLM Reinforcement Learning
5
5
  Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
6
6
  Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
@@ -170,7 +170,7 @@ verifiers/legacy/utils/usage_utils.py,sha256=P1KioJnOwijznTJu6Yb2KuFv4aWGf4jxUjE
170
170
  verifiers/legacy/utils/version_utils.py,sha256=aGPdNge6a3PU5RbIzWqApvT9oJZ5DIaDi4sFAbvr5-Y,2663
171
171
  verifiers/v1/__init__.py,sha256=L3zG1p7dw4CfKS2DZ6PSzcwqFgD-negD8TfdRgclpp0,8066
172
172
  verifiers/v1/agent.py,sha256=cMRVKzg9Vs6DCLJ5vXj8xc3-PJ2S6fhoJctS7zHinKM,31393
173
- verifiers/v1/env.py,sha256=GQmSk4LYLY4RnlFHzywWdCt1ZynUq72IDpIsT5C-wSw,18068
173
+ verifiers/v1/env.py,sha256=CEhzjojhg5jqbOYruUnc5U7TtgDHDSx8NiiFA0qfbt8,18234
174
174
  verifiers/v1/episode.py,sha256=uStvI4WqgJT50hmHIB55m5B-ASqqLz-fZ-ynBz9uzEY,5474
175
175
  verifiers/v1/errors.py,sha256=kQeEPX06TwAIuiz7MlWFYirrpKbx5STi6A5b_dtQQoA,6885
176
176
  verifiers/v1/graph.py,sha256=JxhP34q-lH70C7i04WHLoqWX1OHBc0dp2Qkqtj9deaA,30330
@@ -189,20 +189,20 @@ verifiers/v1/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,
189
189
  verifiers/v1/cli/debug.py,sha256=gi9FBlM0c44enIbig4nA4yprOtanyoISmPnqrnOA_ac,11587
190
190
  verifiers/v1/cli/gepa.py,sha256=7YpppEMeuY2m1X5szGkybzTHztnIs83CvnSizhiEC-w,4210
191
191
  verifiers/v1/cli/init.py,sha256=_WBM_Ub8adMWWoJRDb4jqNaE2T7BgwlXfjVw2--3Pk0,8056
192
- verifiers/v1/cli/output.py,sha256=E6Z1kjTqI5-Nleq0svHwduBL3Owqt6St37Tgo3ZFwFQ,5815
193
- verifiers/v1/cli/replay.py,sha256=yW42yr-r3GtDRtlWOuwSMKWjJxSUc5R5uChNsaXokE8,10360
192
+ verifiers/v1/cli/output.py,sha256=jHH7yid6G7BDyiuUzBXALcRAai3zZRwaJzRFiTgS9gk,7351
193
+ verifiers/v1/cli/replay.py,sha256=JhhI_O8PLhtHbgLie5dG03RrTynvZtsEPX-MLY3KQy4,10240
194
194
  verifiers/v1/cli/resolve.py,sha256=OsNw4C3r9xOVFa-mminJFcex_bAsJ6EQ8K7A_H8u2kQ,4370
195
195
  verifiers/v1/cli/resume.py,sha256=hqV5AxxqeIInJeEZQerQznuijhMNijFEFcHZIltfLdE,470
196
- verifiers/v1/cli/validate.py,sha256=Z--avU6O4aAZqCRStiS6hMC0HxvaNYXoodxOPmRNLWE,18506
196
+ verifiers/v1/cli/validate.py,sha256=jUQZVwdzY9A5TcULBaxvsh_TvkYGQfO0zXEbnlYk_n4,18410
197
197
  verifiers/v1/cli/dashboard/__init__.py,sha256=v-baMxQuWxOCsbU7-p_jj2Q9BUnTN-TWi1q2hK6rU2s,198
198
198
  verifiers/v1/cli/dashboard/base.py,sha256=kUP93zJSIVLptSbnWX6MOy8kGg63fpeAzPqakCpPyDc,3547
199
- verifiers/v1/cli/dashboard/eval.py,sha256=VlTMx95B7o1c_7knuw_XllNU8rjLQ-ByBo4jSn1hunU,33605
199
+ verifiers/v1/cli/dashboard/eval.py,sha256=yfrhs4w1sqwwHieIegTbqPvyrdxcY14JZFawAf_0_mk,36662
200
200
  verifiers/v1/cli/dashboard/replay.py,sha256=CvRVaf0dUum5v0IzPQbFPPikBQmTrkMeaunGfVMTWHc,2755
201
201
  verifiers/v1/cli/dashboard/validate.py,sha256=rLsQ_31DjTIZpC_VO7zSG41ncUEBxqCx8mL9nTnGiMc,3650
202
202
  verifiers/v1/cli/eval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
203
- verifiers/v1/cli/eval/main.py,sha256=bmtVIQ3JeNNXOA4hGDlC2mAJcSlAWWigEfbdyLQPf1A,6804
203
+ verifiers/v1/cli/eval/main.py,sha256=tPLHAdCc8o2lxu4BEd-61UsF1Dfltmm9jV6K-HwCg3I,6222
204
204
  verifiers/v1/cli/eval/resume.py,sha256=WbWXmH7HLk2wkR-vyBtQIRT-P9IQpK9tOEMYPWfQaUs,3904
205
- verifiers/v1/cli/eval/runner.py,sha256=q4tOCTj9-EXpA0bfTekz0UP4tSN-9LZ9LNcED3o3HwI,9309
205
+ verifiers/v1/cli/eval/runner.py,sha256=NeV4NuxuQDgWi4QvZ_Qm4sP0GxREz1jS3LYxobfOxxY,9992
206
206
  verifiers/v1/clients/__init__.py,sha256=Ysig0tE_0E4Jsfgfes1XHN-fK1s_RCXdqZD6E7lK4PU,507
207
207
  verifiers/v1/clients/base.py,sha256=PoDw4GMqrfuPTFVK6n2jDmlD0_lJ5zTrYcNio5yq6K8,1691
208
208
  verifiers/v1/clients/client.py,sha256=zqC_AkiD9pl0kxxIbupNiehbS-YnVdp3EMZ0LOHTd8U,3125
@@ -222,7 +222,7 @@ verifiers/v1/configs/taskset.py,sha256=N5sFYjzjcmnUEiNiHH69vaOfl8fsVwmqXmWmPixqO
222
222
  verifiers/v1/configs/cli/__init__.py,sha256=TJaWQQHrcyXoeqS7P9S25ztd78YJ30_9_Ug0czRH7Tw,374
223
223
  verifiers/v1/configs/cli/debug.py,sha256=xrb56B_CyxncgW30_hwjZYgTM1ViEBCEI-IQjKkxbDY,2847
224
224
  verifiers/v1/configs/cli/env.py,sha256=YdIo0RW7VBhq_uCoa7RfnkkzGU5PW4kTa6Bn20lnd5c,2592
225
- verifiers/v1/configs/cli/eval.py,sha256=J5zEUeyH8_TJtqLB3DKOejGVMPioFRaVKFGoKkLtOJg,6984
225
+ verifiers/v1/configs/cli/eval.py,sha256=PA8j1KIKVh6m4IM-YIeL_BDwjplqed83F7Bp1__z3Ec,6370
226
226
  verifiers/v1/configs/cli/init.py,sha256=Vmuamb53F79UjGfS6lv-HBhndaM-YuVcjPCU0JbvUWI,899
227
227
  verifiers/v1/configs/cli/replay.py,sha256=xvMDZzIkvjgYl-a3ragjXI65DsD6FYl6gEFM5qpdIuA,2913
228
228
  verifiers/v1/configs/cli/validate.py,sha256=0LXGjqc9JxbCGTpMBX5OPsHCWxZw64uE1ky3ukQBULs,3654
@@ -339,8 +339,8 @@ verifiers/v1/utils/generic.py,sha256=2VIN9RapMO9pVkFHB1UKUHck1vlTJ1pjfad2NzxuuXA
339
339
  verifiers/v1/utils/git.py,sha256=MTRinOvG4EddfjdahHkFZUihHmhJ37n5ROtgjzjE1NA,8366
340
340
  verifiers/v1/utils/image.py,sha256=OFw_wdwVtbdwa8uJ3X3vYfhpUAi0CTH5HMBupjVsRRQ,282
341
341
  verifiers/v1/utils/interrupt.py,sha256=F-KKhc5ndPJJfhd3SuMqyqhXhA32FhCRy5KWFJpEoM4,1179
342
- verifiers/v1/utils/loaders.py,sha256=TbHwoz852MV938xIIC7uJOMGtljjwKJ3n4FfeAXX4gs,12089
343
- verifiers/v1/utils/logging.py,sha256=OcMHA6NsYux3oIzjPuI95rDWmFBHNcHDjZeNIhXTX-Y,2084
342
+ verifiers/v1/utils/loaders.py,sha256=2TrgZK3MzKub1GnfaTVIQhlwF6q4qATXZCjicH6nT9c,12299
343
+ verifiers/v1/utils/logging.py,sha256=-zgaM-HZsgxumZ4wYNlRMZepp6JanCSjeL2wSVulwJM,2296
344
344
  verifiers/v1/utils/memory.py,sha256=ZkIvGk6uITAH5sKon65LifKPbvZr8mJ__PVc23FZpOQ,1835
345
345
  verifiers/v1/utils/paths.py,sha256=it_4JWf_8bPZe4TRcyvL7_KJ4fsbEsxhhIY_xA8Ikus,308
346
346
  verifiers/v1/utils/platform.py,sha256=3P4ryQTHIA8r3hdi-cTGOzKJSsaJEZqsQ8HPK9Rtjxg,12269
@@ -348,8 +348,8 @@ verifiers/v1/utils/prime.py,sha256=UTYRjp9cbjNb6CVmBHda-1wWZAIIfxNOmTyNuT7_wL4,9
348
348
  verifiers/v1/utils/retries.py,sha256=Y2ZgrAjn-qNkRKZP_RVNL_7EK0iaRcZeCa404lpGYi4,5417
349
349
  verifiers/v1/utils/score.py,sha256=-R5Cog14r_tJ6Q_oOfGr5VPAm2CCUhofYZB6B9lm4wM,5787
350
350
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
351
- verifiers-0.3.1.dev60.dist-info/METADATA,sha256=0M3F7eW9Zr6ZUq1Kv7kmVWgNc8NAfux7MMLO63ntxkM,4653
352
- verifiers-0.3.1.dev60.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
353
- verifiers-0.3.1.dev60.dist-info/entry_points.txt,sha256=hZ5wDc1T8y-EvOziw7kQqatBJ6PbdSu2ygP5rjANl7c,564
354
- verifiers-0.3.1.dev60.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
355
- verifiers-0.3.1.dev60.dist-info/RECORD,,
351
+ verifiers-0.3.1.dev62.dist-info/METADATA,sha256=ynj_RJthR0NxAj0xLQxoMdEWOlihvNvlfccwVNxL7Ow,4653
352
+ verifiers-0.3.1.dev62.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
353
+ verifiers-0.3.1.dev62.dist-info/entry_points.txt,sha256=hZ5wDc1T8y-EvOziw7kQqatBJ6PbdSu2ygP5rjANl7c,564
354
+ verifiers-0.3.1.dev62.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
355
+ verifiers-0.3.1.dev62.dist-info/RECORD,,