Skip to content

Commit f0a7628

Browse files
committed
Show live run status and log tail while saving progress to disk
1 parent 43da195 commit f0a7628

3 files changed

Lines changed: 210 additions & 24 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -269,10 +269,14 @@ This experiment file describes **which tests to run**. A model profile such as
269269
across suites.
270270

271271
Terminal progress identifies the experiment number, image build, warmup, and
272-
measured attempts/retries. Builds and model phases print elapsed time every
273-
15 seconds; model phases also show current and peak cgroup memory when samples
274-
are available. Full console output stays in the printed log paths. These are
275-
status updates, not an estimated completion percentage.
272+
measured attempts/retries. During builds and model phases, an interactive terminal
273+
shows live elapsed time, current and peak cgroup memory (when available), and a
274+
panel with the last 12 lines of the run log. Ctrl-C cancels the command. Full
275+
console output stays in the printed log paths; elapsed time and memory status
276+
are saved every 15 seconds in a sibling `console.progress.log` (or
277+
`build.progress.log` for builds). Redirected output and non-interactive terminals
278+
only print start and finish summaries. These are status updates, not an estimated
279+
completion percentage.
276280

277281
## Run controls
278282

‎src/abench/progress.py‎

Lines changed: 114 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
11
"""Host-side progress for long commands without changing measured model work."""
22

3+
import asyncio
34
import csv
5+
import os
46
import subprocess
7+
import sys
58
import time
69

10+
from prompt_toolkit.application import Application
11+
from prompt_toolkit.data_structures import Point
12+
from prompt_toolkit.key_binding import KeyBindings
13+
from prompt_toolkit.layout import HSplit, Layout, Window
14+
from prompt_toolkit.layout.controls import FormattedTextControl
15+
from prompt_toolkit.widgets import Frame
16+
17+
from .failures import tail
18+
719

820
def memory_status(path):
921
"""Read only the last complete sample; tolerate partial writes and startup."""
@@ -24,24 +36,105 @@ def memory_status(path):
2436
return ""
2537

2638

39+
def interactive_terminal():
40+
return (
41+
sys.stdin.isatty() and sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
42+
)
43+
44+
45+
def log_tail(path, lines=12):
46+
"""Bound reads and remove terminal controls from untrusted subprocess output."""
47+
text = tail(path, limit=16384)
48+
return (
49+
"\n".join(
50+
"".join(char if char.isprintable() or char == "\t" else "" for char in line)
51+
for line in text.splitlines()[-lines:]
52+
)
53+
or "Waiting for log output…"
54+
)
55+
56+
57+
def live_view(status, log):
58+
bindings = KeyBindings()
59+
60+
@bindings.add("c-c")
61+
@bindings.add("c-d")
62+
def cancel(event):
63+
event.app.exit(exception=KeyboardInterrupt())
64+
65+
return Application(
66+
layout=Layout(
67+
HSplit(
68+
[
69+
Window(FormattedTextControl(status), height=2, wrap_lines=True),
70+
Frame(
71+
Window(
72+
FormattedTextControl(
73+
lambda: log_tail(log),
74+
show_cursor=False,
75+
get_cursor_position=lambda: Point(
76+
x=0, y=len(log_tail(log).splitlines()) - 1
77+
),
78+
),
79+
height=12,
80+
wrap_lines=False,
81+
),
82+
title=f"Log tail: {log.name}",
83+
),
84+
]
85+
)
86+
),
87+
key_bindings=bindings,
88+
full_screen=False,
89+
erase_when_done=True,
90+
refresh_interval=0.25,
91+
)
92+
93+
2794
def run_logged(args, log, interval=15):
28-
"""Keep full logs on disk and print periodic stage status, including failures."""
95+
"""Retain progress on disk and show a live status/log panel on terminals."""
96+
if interval <= 0:
97+
raise ValueError("progress interval must be positive")
2998
label = "Image build" if log.name == "build.log" else log.parent.name
99+
progress_log = log.with_name(f"{log.stem}.progress.log")
30100
started = time.monotonic()
31-
print(f"{label}: started; log: {log}", flush=True)
32-
with log.open("w") as stream:
101+
102+
def status():
103+
return f"{label}: {time.monotonic() - started:.0f}s elapsed" + memory_status(
104+
log.parent / "memory.csv"
105+
)
106+
107+
initial = f"{label}: started; log: {log}; progress: {progress_log}"
108+
print(initial, flush=True)
109+
with log.open("w") as stream, progress_log.open("w", buffering=1) as progress:
110+
progress.write(initial + "\n")
33111
process = subprocess.Popen(args, stdout=stream, stderr=subprocess.STDOUT)
34112
try:
35-
while True:
36-
try:
37-
code = process.wait(timeout=interval)
38-
break
39-
except subprocess.TimeoutExpired:
40-
detail = memory_status(log.parent / "memory.csv")
41-
print(
42-
f"{label}: {time.monotonic() - started:.0f}s elapsed{detail}",
43-
flush=True,
44-
)
113+
if interactive_terminal():
114+
app = live_view(status, log)
115+
116+
async def monitor():
117+
try:
118+
next_sample = started + interval
119+
while process.poll() is None:
120+
now = time.monotonic()
121+
if now >= next_sample:
122+
progress.write(status() + "\n")
123+
next_sample = now + interval
124+
await asyncio.sleep(min(0.25, interval))
125+
except Exception as error:
126+
app.exit(exception=error)
127+
else:
128+
app.exit(result=process.returncode)
129+
130+
code = app.run(pre_run=lambda: app.create_background_task(monitor()))
131+
else:
132+
while True:
133+
try:
134+
code = process.wait(timeout=interval)
135+
break
136+
except subprocess.TimeoutExpired:
137+
progress.write(status() + "\n")
45138
except BaseException:
46139
# Let container_phase's finally block remove a cancelled container.
47140
# Reap the host Docker client so cancellation never leaves it running.
@@ -51,12 +144,14 @@ def run_logged(args, log, interval=15):
51144
except subprocess.TimeoutExpired:
52145
process.kill()
53146
process.wait()
147+
progress.write(f"{status()}; interrupted\n")
54148
raise
55-
status = "completed" if code == 0 else f"failed (exit {code})"
56-
print(
57-
f"{label}: {status} after {time.monotonic() - started:.0f}s"
58-
+ memory_status(log.parent / "memory.csv"),
59-
flush=True,
60-
)
149+
outcome = "completed" if code == 0 else f"failed (exit {code})"
150+
final = (
151+
f"{label}: {outcome} after {time.monotonic() - started:.0f}s"
152+
+ memory_status(log.parent / "memory.csv")
153+
)
154+
progress.write(final + "\n")
155+
print(final, flush=True)
61156
if code:
62157
raise subprocess.CalledProcessError(code, args)

‎tests/test_progress.py‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,97 @@ def test_logged_command_progress_and_exit(tmp_path, capsys):
2525
interval=0.03,
2626
)
2727
output = capsys.readouterr().out
28-
assert "elapsed" in output and "completed" in output
28+
assert "elapsed" not in output and "completed" in output
29+
assert "elapsed" in log.with_name("build.progress.log").read_text()
2930
assert "build output" not in output
3031
assert "build output" in log.read_text()
3132
with pytest.raises(subprocess.CalledProcessError) as error:
3233
run_logged([sys.executable, "-c", "raise SystemExit(7)"], log)
3334
assert error.value.returncode == 7
3435
assert "failed (exit 7)" in capsys.readouterr().out
36+
37+
38+
@pytest.mark.parametrize("exit_code", [0, 7])
39+
def test_live_progress(tmp_path, monkeypatch, exit_code):
40+
from prompt_toolkit.application import create_app_session
41+
from prompt_toolkit.input import create_pipe_input
42+
from prompt_toolkit.output import DummyOutput
43+
44+
from abench import progress
45+
46+
log = tmp_path / "console.log"
47+
(tmp_path / "memory.csv").write_text(
48+
"elapsed_seconds,current_bytes,peak_bytes\n1,1073741824,2147483648\n"
49+
)
50+
monkeypatch.setattr(progress, "interactive_terminal", lambda: True)
51+
frames = []
52+
original = progress.live_view
53+
54+
def view(status, path):
55+
app = original(status, path)
56+
app.before_render += lambda _: frames.append(
57+
(status(), progress.log_tail(path))
58+
)
59+
return app
60+
61+
monkeypatch.setattr(progress, "live_view", view)
62+
with (
63+
create_pipe_input() as pipe,
64+
create_app_session(input=pipe, output=DummyOutput()),
65+
):
66+
args = [
67+
sys.executable,
68+
"-u",
69+
"-c",
70+
f"import time; print('model output'); time.sleep(.6); exit({exit_code})",
71+
]
72+
if exit_code:
73+
with pytest.raises(subprocess.CalledProcessError) as error:
74+
run_logged(args, log, interval=0.03)
75+
assert error.value.returncode == exit_code
76+
else:
77+
run_logged(args, log, interval=0.03)
78+
assert any("model output" in text for _, text in frames)
79+
assert any("memory 1.00 GiB (peak 2.00 GiB)" in status for status, _ in frames)
80+
assert "elapsed" in log.with_name("console.progress.log").read_text()
81+
82+
83+
def test_live_cancellation_reaps_process(tmp_path, monkeypatch):
84+
from prompt_toolkit.application import create_app_session
85+
from prompt_toolkit.input import create_pipe_input
86+
from prompt_toolkit.output import DummyOutput
87+
88+
from abench import progress
89+
90+
monkeypatch.setattr(progress, "interactive_terminal", lambda: True)
91+
processes = []
92+
original = subprocess.Popen
93+
94+
def popen(*args, **kwargs):
95+
process = original(*args, **kwargs)
96+
processes.append(process)
97+
return process
98+
99+
monkeypatch.setattr(progress.subprocess, "Popen", popen)
100+
with (
101+
create_pipe_input() as pipe,
102+
create_app_session(input=pipe, output=DummyOutput()),
103+
):
104+
pipe.send_text("\x03")
105+
with pytest.raises(KeyboardInterrupt):
106+
run_logged(
107+
[sys.executable, "-c", "import time; time.sleep(30)"],
108+
tmp_path / "console.log",
109+
)
110+
assert processes[0].poll() is not None
111+
assert "interrupted" in (tmp_path / "console.progress.log").read_text()
112+
113+
114+
def test_tail_is_bounded_and_plain(tmp_path):
115+
from abench.progress import log_tail
116+
117+
log = tmp_path / "console.log"
118+
assert log_tail(log) == "Waiting for log output…"
119+
log.write_text("old\n" * 10000 + "new\x1b[2J\x00\nlast\n")
120+
result = log_tail(log, lines=2)
121+
assert result == "new[2J\nlast"

0 commit comments

Comments
 (0)