mr-sarthakgupta
Initial dataset import
6d6b4b2
Raw History Blame Contribute Delete
6.05 kB
#!/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())