Skip to content

Commit e84c09c

Browse files
committed
Add persistent publication launcher and readable status
1 parent 204f5a3 commit e84c09c

4 files changed

Lines changed: 392 additions & 33 deletions

File tree

‎README.md‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,12 @@ abench examples/sandag-pr.yaml --set pr=1110 --publish-dry-run
309309
# Inspect or publish retained results without rerunning benchmarks:
310310
abench publish /path/to/suite-output --dry-run
311311
abench publish /path/to/suite-output
312+
# Read local status, or verify the comment still exists on GitHub:
313+
abench publish /path/to/suite-output --status
314+
abench publish /path/to/suite-output --verify
315+
# The permanent launcher works from any working directory:
316+
/path/to/suite-output/publication/publish.sh
317+
/path/to/suite-output/publication/publish.sh --dry-run
312318
```
313319

314320
Publication requires GitHub CLI 2.99 or newer with `gh pr comment --attach`, an
@@ -329,8 +335,28 @@ PR head/base commits are recorded at startup, and a head change during execution
329335
is noted when posting. These are observations, not statistical significance tests.
330336

331337
The `publication/` directory retains `comment.md`, `memory.svg`, `runtimes.svg`,
332-
and `state.json` with the comment ID/URL and publication status. The exact upload
333-
body is retained as `upload.md`. A retry searches for the suite's unique comment
338+
and `state.json` with the comment ID/URL and publication status. `STATUS.md` shows
339+
whether publication is pending, failed, uncertain, or published, with attempt time,
340+
errors, a retry command, and the comment link. It reflects local knowledge;
341+
`--verify` checks GitHub without uploading or editing anything. Verification
342+
failures preserve the previous publication record. A missing previously published
343+
comment is flagged and is not automatically recreated.
344+
345+
The executable `publish.sh` is permanent: it is safe to call repeatedly and passes
346+
through `--dry-run`, `--status`, or `--verify`. It prefers `abench` on PATH, then
347+
uses `uvx --refresh --from <recorded-checkout>` when a development checkout was
348+
available when the bundle was prepared. It reports an actionable error if neither
349+
is available and never stores credentials. Output paths with spaces are supported.
350+
Existing suites can create these helpers with `abench publish OUTPUT --status`
351+
without reading measurement data or contacting GitHub.
352+
353+
The final console message explicitly says whether results were published, gives
354+
the comment URL on success, or gives the launcher command when action is needed.
355+
A connection failure after posting begins is marked as an uncertain outcome;
356+
retrying reconciles the comment marker before attempting another post.
357+
358+
The exact upload body is retained as `upload.md`. A retry searches for the suite's
359+
unique comment
334360
marker before posting; a recorded successful publication is a no-op. Independent
335361
suite executions get separate comments. Simultaneous publication of the same
336362
output directory is blocked. Partial uploads can leave unused GitHub attachments,

‎src/abench/cli.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,13 +244,29 @@ def main(argv=None):
244244

245245
publish_parser = argparse.ArgumentParser(prog="abench publish")
246246
publish_parser.add_argument("output_directory", type=Path)
247-
publish_parser.add_argument(
247+
publish_mode = publish_parser.add_mutually_exclusive_group()
248+
publish_mode.add_argument(
248249
"--dry-run",
249250
action="store_true",
250251
help="generate the local bundle without GitHub access",
251252
)
253+
publish_mode.add_argument(
254+
"--status",
255+
action="store_true",
256+
help="show recorded publication status without contacting GitHub",
257+
)
258+
publish_mode.add_argument(
259+
"--verify",
260+
action="store_true",
261+
help="check publication status on GitHub without posting",
262+
)
252263
options = publish_parser.parse_args(argv[1:])
253-
publish(options.output_directory, dry_run=options.dry_run)
264+
publish(
265+
options.output_directory,
266+
dry_run=options.dry_run,
267+
status_only=options.status,
268+
verify=options.verify,
269+
)
254270
return 0
255271
# A file invocation stays separate from model profiles and ordinary flags.
256272
candidate = argv[1:] if argv and argv[0] in ("run", "validate", "prepare") else argv

‎src/abench/publishing.py‎

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
import fcntl
44
import json
55
import re
6+
import shlex
67
import subprocess
78
import uuid
9+
from datetime import datetime, timezone
10+
from importlib.metadata import PackageNotFoundError, distribution
811
from pathlib import Path
12+
from urllib.parse import unquote, urlparse
913
from xml.etree import ElementTree as ET
1014

1115
from . import __version__
@@ -142,8 +146,170 @@ def standalone(svg):
142146
)
143147

144148

145-
def build_bundle(root):
146-
"""Rebuild shareable artifacts from retained results, without GitHub access."""
149+
def now():
150+
return datetime.now(timezone.utc).isoformat()
151+
152+
153+
def local_checkout():
154+
"""Find a development checkout, including when running in a uvx environment."""
155+
candidates = [Path(__file__).resolve().parents[2]]
156+
try:
157+
direct = json.loads(distribution("abench").read_text("direct_url.json") or "{}")
158+
url = urlparse(direct.get("url", ""))
159+
if url.scheme == "file" and url.netloc in ("", "localhost"):
160+
candidates.append(Path(unquote(url.path)))
161+
except (ValueError, OSError, PackageNotFoundError):
162+
pass
163+
return next(
164+
(
165+
str(p)
166+
for p in candidates
167+
if (p / "pyproject.toml").is_file() and (p / "src/abench").is_dir()
168+
),
169+
None,
170+
)
171+
172+
173+
def write_launcher(bundle, checkout):
174+
launcher = bundle / "publish.sh"
175+
fallback = ""
176+
if checkout:
177+
quoted = shlex.quote(checkout)
178+
fallback = f"""if command -v uvx >/dev/null 2>&1 && [ -f {quoted}/pyproject.toml ]; then
179+
exec uvx --refresh --from {quoted} abench publish "$suite_dir" "$@"
180+
fi
181+
"""
182+
launcher.write_text(
183+
"""#!/bin/sh
184+
# Permanent, safe-to-repeat abench publication launcher. No credentials stored.
185+
set -eu
186+
publication_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
187+
suite_dir=$(dirname -- "$publication_dir")
188+
if command -v abench >/dev/null 2>&1; then
189+
exec abench publish "$suite_dir" "$@"
190+
fi
191+
"""
192+
+ fallback
193+
+ """echo 'Cannot find abench. Install a version with PR publishing support, or restore the recorded checkout and install uv.' >&2
194+
exit 127
195+
"""
196+
)
197+
launcher.chmod(0o755)
198+
199+
200+
STATUS_LABELS = {
201+
"prepared": "Not published",
202+
"failed": "Publication failed",
203+
"posting": "Publication outcome uncertain",
204+
"uncertain": "Publication outcome uncertain",
205+
"published": "Published",
206+
"missing": "Previously published comment not found",
207+
}
208+
209+
210+
def save_status(bundle, state):
211+
"""JSON is authoritative; the Markdown file is a readable projection."""
212+
write_json(bundle / "state.json", state)
213+
label = STATUS_LABELS.get(state["status"], state["status"])
214+
target = state["target"]
215+
lines = [
216+
"# Publication status",
217+
"",
218+
f"**{label}**",
219+
"",
220+
f"Target: https://github.com/{target['repository']}/pull/{target['pr']}",
221+
f"Last publication attempt: {state.get('last_attempt_at', 'Never recorded')}",
222+
]
223+
if state.get("comment_url"):
224+
lines += ["", f"[Open the recorded GitHub comment]({state['comment_url']})"]
225+
if state.get("last_verified_at"):
226+
lines += [f"Last GitHub check: {state['last_verified_at']}"]
227+
if state.get("error"):
228+
lines += ["", f"Last error: {cell(state['error'])}"]
229+
if state.get("verification_error"):
230+
lines += [
231+
"",
232+
f"GitHub verification failed: {cell(state['verification_error'])}",
233+
]
234+
if state["status"] in ("posting", "uncertain"):
235+
lines += [
236+
"",
237+
"GitHub may have accepted the comment. Retry checks for the existing comment before posting again.",
238+
]
239+
command = shlex.quote(str(bundle / "publish.sh"))
240+
lines += [
241+
"",
242+
"Publish or retry (safe to repeat):",
243+
"",
244+
"```sh",
245+
command,
246+
"```",
247+
"",
248+
"Preview with `--dry-run`; inspect local status with `--status`; check GitHub with `--verify`.",
249+
"",
250+
"This file records local knowledge; use --verify to check whether the comment still exists.",
251+
]
252+
(bundle / "STATUS.md").write_text("\n".join(lines) + "\n")
253+
254+
255+
def completion(bundle, state):
256+
if state["status"] == "published":
257+
print(f"Results published: {state['comment_url']}")
258+
elif state["status"] in ("posting", "uncertain"):
259+
print("Results saved; publication outcome uncertain.")
260+
else:
261+
print("Results saved but not published.")
262+
print(f"Publication status: {bundle / 'STATUS.md'}")
263+
if state["status"] != "published":
264+
print(f"Publish / retry: {shlex.quote(str(bundle / 'publish.sh'))}")
265+
266+
267+
def find_comment(state):
268+
target = state["target"]
269+
pages = json.loads(
270+
gh(
271+
"api",
272+
f"repos/{target['repository']}/issues/{target['pr']}/comments",
273+
"--hostname",
274+
"github.com",
275+
"--paginate",
276+
"--slurp",
277+
)
278+
)
279+
marker = f"<!-- abench:{state['id']} -->"
280+
return next(
281+
(
282+
c
283+
for page in pages
284+
for c in page
285+
if marker in (c.get("body") or "") or c["id"] == state.get("comment_id")
286+
),
287+
None,
288+
)
289+
290+
291+
def verify_publication(bundle, state):
292+
"""Read GitHub only; never recreate or edit a comment during verification."""
293+
try:
294+
found = find_comment(state)
295+
except (ValueError, OSError) as error:
296+
state["verification_error"] = str(error)
297+
save_status(bundle, state)
298+
raise
299+
state["last_verified_at"] = now()
300+
state.pop("verification_error", None)
301+
if found:
302+
state.update(
303+
status="published", comment_id=found["id"], comment_url=found["html_url"]
304+
)
305+
state.pop("error", None)
306+
elif state.get("comment_url"):
307+
state["status"] = "missing"
308+
save_status(bundle, state)
309+
310+
311+
def prepare_publication(root):
312+
"""Create local publication controls without reading benchmark measurements."""
147313
plan = read_json(root / "suite.json")
148314
if not plan:
149315
raise ValueError(f"No suite.json in {root}")
@@ -160,7 +326,20 @@ def build_bundle(root):
160326
raise ValueError("Publication target differs from the saved publication state")
161327
if not state:
162328
state = {"target": config, "id": str(uuid.uuid4()), "status": "prepared"}
329+
state["checkout"] = local_checkout()
163330
write_json(state_path, state)
331+
if "checkout" not in state:
332+
state["checkout"] = local_checkout()
333+
save_status(bundle, state)
334+
write_launcher(bundle, state.get("checkout"))
335+
return bundle, state
336+
337+
338+
def build_bundle(root):
339+
"""Rebuild shareable artifacts from retained results, without GitHub access."""
340+
bundle, state = prepare_publication(root)
341+
plan = read_json(root / "suite.json")
342+
config = state["target"]
164343
marker = f"<!-- abench:{state['id']} -->"
165344
runs = []
166345
names = []
@@ -240,8 +419,6 @@ def elapsed(run):
240419
"![Component runtimes](./runtimes.svg)",
241420
"",
242421
"Valid runs only. Mean ± population standard deviation across worker executions, not confidence intervals. Parallel component times must not be summed as wall time.",
243-
"",
244-
"The interactive HTML report and JSON remain in the experiment output directory.",
245422
]
246423
(bundle / "comment.md").write_text("\n".join(lines) + "\n")
247424
xmax = (
@@ -280,7 +457,7 @@ def elapsed(run):
280457
return bundle, state
281458

282459

283-
def publish(root, *, dry_run=False):
460+
def publish(root, *, dry_run=False, status_only=False, verify=False):
284461
"""Publish once per suite; recover a successful comment after a lost response."""
285462
root = Path(root).expanduser().resolve()
286463
if not (root / "suite.json").is_file():
@@ -290,30 +467,30 @@ def publish(root, *, dry_run=False):
290467
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
291468
except BlockingIOError as error:
292469
raise ValueError("Publication is already running for this suite") from error
470+
if status_only or verify:
471+
bundle, state = prepare_publication(root)
472+
if verify:
473+
verify_publication(bundle, state)
474+
print((bundle / "STATUS.md").read_text())
475+
return state.get("comment_url")
293476
bundle, state = build_bundle(root)
294477
if dry_run:
295478
print(f"Publication preview: {bundle / 'comment.md'}")
479+
completion(bundle, state)
296480
return None
481+
if state.get("status") == "missing":
482+
raise ValueError(
483+
"The previously published comment was not found on GitHub; not reposting automatically. See publication/STATUS.md."
484+
)
297485
if state.get("comment_url"):
298-
print(f"Already published: {state['comment_url']}")
486+
completion(bundle, state)
299487
return state["comment_url"]
300488
try:
489+
state["last_attempt_at"] = now()
490+
save_status(bundle, state)
301491
config = state["target"]
302492
current = preflight(config)
303-
marker = f"<!-- abench:{state['id']} -->"
304-
comments = json.loads(
305-
gh(
306-
"api",
307-
f"repos/{config['repository']}/issues/{config['pr']}/comments",
308-
"--hostname",
309-
"github.com",
310-
"--paginate",
311-
"--slurp",
312-
)
313-
)
314-
found = next(
315-
(c for page in comments for c in page if marker in c["body"]), None
316-
)
493+
found = find_comment(state)
317494
if not found:
318495
snapshot = read_json(root / "suite.json").get("publication_pr", {})
319496
body = (bundle / "comment.md").read_text()
@@ -332,8 +509,8 @@ def publish(root, *, dry_run=False):
332509
# Resolve relative image references from the bundle, including
333510
# output directories containing spaces or Markdown punctuation.
334511
(bundle / "upload.md").write_text(body)
335-
state["status"] = "posting"
336-
write_json(bundle / "state.json", state)
512+
state.update(status="posting", last_attempt_at=now())
513+
save_status(bundle, state)
337514
url = gh(
338515
"pr",
339516
"comment",
@@ -356,16 +533,26 @@ def publish(root, *, dry_run=False):
356533
found = {"id": int(match[1]), "html_url": match[0]}
357534
state.update(
358535
status="published",
536+
published_at=state.get("published_at") or now(),
359537
comment_id=found["id"],
360538
comment_url=found["html_url"],
361539
)
362540
state.pop("error", None)
363-
write_json(bundle / "state.json", state)
364-
except (ValueError, OSError) as error:
365-
state.update(status="failed", error=str(error))
366-
write_json(bundle / "state.json", state)
541+
save_status(bundle, state)
542+
except (ValueError, OSError, KeyboardInterrupt) as error:
543+
state.update(
544+
status="uncertain"
545+
if state["status"] in ("posting", "uncertain")
546+
else "failed",
547+
error=str(error) or "Publication interrupted",
548+
last_attempt_at=state.get("last_attempt_at") or now(),
549+
)
550+
save_status(bundle, state)
551+
completion(bundle, state)
552+
if isinstance(error, KeyboardInterrupt):
553+
raise
367554
raise ValueError(
368-
f"{error}\nResults retained. Retry: abench publish {root}"
555+
f"{error}\nResults retained. Retry: {shlex.quote(str(bundle / 'publish.sh'))}"
369556
) from error
370-
print(f"Published: {state['comment_url']}")
557+
completion(bundle, state)
371558
return state["comment_url"]

0 commit comments

Comments
 (0)