File size: 6,045 Bytes
6d6b4b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | #!/usr/bin/env python3
"""Publish an explicit analysis manifest into the Harbor submission directory."""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import shutil
import tempfile
from pathlib import Path, PurePosixPath
from typing import Any
def _inside(path: Path, root: Path) -> bool:
try:
path.relative_to(root)
return True
except ValueError:
return False
def _atomic_bytes(path: Path, content: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.parent.chmod(0o755)
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}-", dir=path.parent)
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.chmod(temporary, 0o644)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def create_submission(
*,
answer: str,
analysis_manifest: str | None,
workspace_root: Path = Path("/app"),
submit_dir: Path = Path("/app/submission"),
) -> dict[str, Any] | None:
"""Copy only manifest-declared artifacts, preserving nested relative paths."""
workspace_root = workspace_root.resolve()
submit_dir = submit_dir.resolve()
submit_dir.mkdir(parents=True, exist_ok=True)
submit_dir.chmod(0o755)
_atomic_bytes(submit_dir / "answer.md", answer.encode())
if not analysis_manifest:
return None
manifest_path = Path(analysis_manifest)
if not manifest_path.is_absolute():
manifest_path = workspace_root / manifest_path
manifest_path = manifest_path.resolve()
if (
not _inside(manifest_path, workspace_root)
or not manifest_path.is_file()
or manifest_path.is_symlink()
):
raise ValueError(
"analysis manifest must be a regular non-symlink file inside /app"
)
try:
manifest = json.loads(manifest_path.read_text(errors="replace"))
except json.JSONDecodeError as exc:
raise ValueError(f"analysis manifest is not valid JSON: {exc}") from exc
artifacts = manifest.get("artifacts")
if not isinstance(artifacts, list) or not artifacts:
raise ValueError("manifest must contain a non-empty artifacts array")
copied: list[dict[str, Any]] = []
reserved = {"answer.md", "analysis_manifest.json"}
for item in artifacts:
if (
not isinstance(item, dict)
or not isinstance(item.get("path"), str)
or not item["path"]
):
raise ValueError("each artifact must be an object with a path")
relative = PurePosixPath(item["path"])
if (
relative.is_absolute()
or ".." in relative.parts
or relative.as_posix() in {".", *reserved}
):
raise ValueError(f"invalid artifact path: {item['path']}")
source = (manifest_path.parent / Path(*relative.parts)).resolve()
if (
not _inside(source, workspace_root)
or not source.is_file()
or source.is_symlink()
):
raise ValueError(
f"artifact must be a regular non-symlink file inside /app: {item['path']}"
)
destination = submit_dir / Path(*relative.parts)
if source != destination.resolve():
destination.parent.mkdir(parents=True, exist_ok=True)
destination.parent.chmod(0o755)
descriptor, temporary = tempfile.mkstemp(
prefix=f".{destination.name}-", dir=destination.parent
)
os.close(descriptor)
try:
shutil.copy2(source, temporary)
os.chmod(temporary, 0o644)
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
else:
destination.chmod(0o644)
copied_item = dict(item)
copied_item["path"] = relative.as_posix()
copied_item["sha256"] = hashlib.sha256(destination.read_bytes()).hexdigest()
copied_item["bytes"] = destination.stat().st_size
copied.append(copied_item)
output = {**manifest, "artifacts": copied}
_atomic_bytes(
submit_dir / "analysis_manifest.json",
(json.dumps(output, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode(),
)
return output
def main() -> int:
parser = argparse.ArgumentParser(description="Submit the final BioEval answer.")
answer_group = parser.add_mutually_exclusive_group(required=True)
answer_group.add_argument("--answer-base64")
answer_group.add_argument("--answer-file")
parser.add_argument("--analysis-manifest")
parser.add_argument(
"--workspace-root",
default=os.getenv("BIOEVAL_WORKSPACE", "/app"),
)
parser.add_argument(
"--submit-dir",
default=os.getenv("BIOEVAL_SUBMIT_DIR", "/app/submission"),
)
args = parser.parse_args()
if args.answer_file:
answer_path = Path(args.answer_file).resolve()
workspace_root = Path(args.workspace_root).resolve()
if (
not _inside(answer_path, workspace_root)
or not answer_path.is_file()
or answer_path.is_symlink()
):
raise ValueError(
"answer file must be a regular non-symlink file inside /app"
)
answer = answer_path.read_text(encoding="utf-8", errors="strict")
else:
answer = base64.b64decode(args.answer_base64, validate=True).decode()
create_submission(
answer=answer,
analysis_manifest=args.analysis_manifest,
workspace_root=Path(args.workspace_root),
submit_dir=Path(args.submit_dir),
)
print(f"Submitted final answer to {Path(args.submit_dir) / 'answer.md'}.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|