|
| 1 | +""" |
| 2 | +Mirror trial artifacts to sauron's AWS S3 bucket. |
| 3 | +
|
| 4 | +When ODDISH_SAURON_S3_BUCKET is set, trial results are uploaded to |
| 5 | +sauron's bucket so sauron can render oddish experiments using its |
| 6 | +existing UI components. |
| 7 | +
|
| 8 | +Layout: |
| 9 | + PR-triggered: |
| 10 | + {owner}/{repo}/pr-{n}/run-{experiment_id}/ |
| 11 | + run-meta.json |
| 12 | + agent-{name}:{model}/{task_name}/attempt_{n}/... |
| 13 | +
|
| 14 | + CLI-triggered: |
| 15 | + {org_slug}/runs/{experiment_id}/run-{experiment_id}/ |
| 16 | + run-meta.json |
| 17 | + agent-{name}:{model}/{task_name}/attempt_{n}/... |
| 18 | +
|
| 19 | +The CLI path uses the experiment_id literally as the grouping segment |
| 20 | +(not a synthetic pr-N) so sauron's existing 4-segment route renders it |
| 21 | +without modification. `run-meta.json` carries identity/metadata at the |
| 22 | +run root so sauron can render run headers without parsing the path or |
| 23 | +hitting GitHub. |
| 24 | +""" |
| 25 | + |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +import asyncio |
| 29 | +import json |
| 30 | +import logging |
| 31 | +import os |
| 32 | +from pathlib import Path |
| 33 | +from typing import Any |
| 34 | + |
| 35 | +import aioboto3 |
| 36 | +from botocore.config import Config |
| 37 | + |
| 38 | +from oddish.config import settings |
| 39 | +from oddish.integrations.github.client import GitHubMeta |
| 40 | + |
| 41 | +logger = logging.getLogger(__name__) |
| 42 | + |
| 43 | +MANIFEST_SCHEMA_VERSION = 1 |
| 44 | + |
| 45 | + |
| 46 | +class SauronS3Uploader: |
| 47 | + """Best-effort mirror of trial artifacts to sauron's AWS S3 bucket.""" |
| 48 | + |
| 49 | + def __init__(self) -> None: |
| 50 | + self._client = None |
| 51 | + self._session = None |
| 52 | + |
| 53 | + def is_enabled(self) -> bool: |
| 54 | + return bool( |
| 55 | + settings.sauron_s3_bucket |
| 56 | + and os.environ.get("AWS_ACCESS_KEY_ID") |
| 57 | + and os.environ.get("AWS_SECRET_ACCESS_KEY") |
| 58 | + ) |
| 59 | + |
| 60 | + async def _ensure_client(self) -> None: |
| 61 | + if self._client is not None: |
| 62 | + return |
| 63 | + self._session = aioboto3.Session() |
| 64 | + self._client = await self._session.client( |
| 65 | + "s3", |
| 66 | + aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"], |
| 67 | + aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"], |
| 68 | + region_name=os.environ.get("AWS_REGION", "us-west-2"), |
| 69 | + config=Config(signature_version="s3v4"), |
| 70 | + ).__aenter__() |
| 71 | + |
| 72 | + async def upload_trial( |
| 73 | + self, |
| 74 | + *, |
| 75 | + harbor_job_dir: Path, |
| 76 | + task_name: str, |
| 77 | + agent: str, |
| 78 | + model: str | None, |
| 79 | + experiment_id: str, |
| 80 | + experiment_name: str | None, |
| 81 | + attempt_number: int, |
| 82 | + github_meta: GitHubMeta | None, |
| 83 | + task_tags: dict | None = None, |
| 84 | + ) -> str | None: |
| 85 | + """Upload trial artifacts. Returns the trial S3 prefix or None on failure.""" |
| 86 | + if not self.is_enabled(): |
| 87 | + return None |
| 88 | + |
| 89 | + run_prefix = self._build_run_prefix(github_meta=github_meta, experiment_id=experiment_id) |
| 90 | + attempt_prefix = ( |
| 91 | + f"{run_prefix}agent-{agent}:{(model or 'default').replace('/', '-')}/" |
| 92 | + f"{task_name}/attempt_{attempt_number}/" |
| 93 | + ) |
| 94 | + |
| 95 | + # Harbor's job_dir contains a task-{name}__{hash}/ subdirectory with |
| 96 | + # the actual trial output. Sauron expects these at the attempt root. |
| 97 | + source = self._find_trial_subdir(harbor_job_dir) or harbor_job_dir |
| 98 | + |
| 99 | + try: |
| 100 | + await self._upload_directory(source, attempt_prefix) |
| 101 | + await self._write_manifest( |
| 102 | + run_prefix=run_prefix, |
| 103 | + experiment_id=experiment_id, |
| 104 | + experiment_name=experiment_name, |
| 105 | + github_meta=github_meta, |
| 106 | + task_tags=task_tags, |
| 107 | + ) |
| 108 | + return attempt_prefix |
| 109 | + except Exception as e: |
| 110 | + logger.warning("Sauron mirror failed for %s: %s", attempt_prefix, e) |
| 111 | + return None |
| 112 | + |
| 113 | + # -- Path construction --------------------------------------------------- |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def _build_run_prefix(*, github_meta: GitHubMeta | None, experiment_id: str) -> str: |
| 117 | + if github_meta: |
| 118 | + return ( |
| 119 | + f"{github_meta.owner}/{github_meta.repo}/" |
| 120 | + f"pr-{github_meta.pr_number}/run-{experiment_id}/" |
| 121 | + ) |
| 122 | + org = settings.sauron_s3_org or "oddish" |
| 123 | + # 4-segment path so sauron's existing [org]/[repo]/[pr]/[run] route |
| 124 | + # renders without modification. The experiment_id appears twice: |
| 125 | + # once as the grouping ("pr") segment, once as the run identifier. |
| 126 | + return f"{org}/runs/{experiment_id}/run-{experiment_id}/" |
| 127 | + |
| 128 | + # -- Manifest ------------------------------------------------------------ |
| 129 | + |
| 130 | + async def _write_manifest( |
| 131 | + self, |
| 132 | + *, |
| 133 | + run_prefix: str, |
| 134 | + experiment_id: str, |
| 135 | + experiment_name: str | None, |
| 136 | + github_meta: GitHubMeta | None, |
| 137 | + task_tags: dict | None, |
| 138 | + ) -> None: |
| 139 | + """Write run-meta.json at run root. Last-writer-wins for stable fields.""" |
| 140 | + manifest: dict[str, Any] = { |
| 141 | + "schema_version": MANIFEST_SCHEMA_VERSION, |
| 142 | + "kind": "pr" if github_meta else "experiment", |
| 143 | + "experiment_id": experiment_id, |
| 144 | + "experiment_name": experiment_name, |
| 145 | + "github": ( |
| 146 | + { |
| 147 | + "owner": github_meta.owner, |
| 148 | + "repo": github_meta.repo, |
| 149 | + "pr_number": github_meta.pr_number, |
| 150 | + } |
| 151 | + if github_meta |
| 152 | + else None |
| 153 | + ), |
| 154 | + "tags": {k: v for k, v in (task_tags or {}).items() if k != "github_meta"}, |
| 155 | + } |
| 156 | + body = json.dumps(manifest, indent=2, sort_keys=True).encode("utf-8") |
| 157 | + |
| 158 | + await self._ensure_client() |
| 159 | + await self._client.put_object( |
| 160 | + Bucket=settings.sauron_s3_bucket, |
| 161 | + Key=f"{run_prefix}run-meta.json", |
| 162 | + Body=body, |
| 163 | + ContentType="application/json", |
| 164 | + ) |
| 165 | + |
| 166 | + # -- Harbor directory unwrapping ----------------------------------------- |
| 167 | + |
| 168 | + @staticmethod |
| 169 | + def _find_trial_subdir(harbor_job_dir: Path) -> Path | None: |
| 170 | + """Find the trial subdirectory (task-name__hash/) inside job_dir.""" |
| 171 | + if not harbor_job_dir.exists(): |
| 172 | + return None |
| 173 | + subdirs = [d for d in harbor_job_dir.iterdir() if d.is_dir()] |
| 174 | + trial_dirs = [d for d in subdirs if "__" in d.name] |
| 175 | + if len(trial_dirs) == 1: |
| 176 | + return trial_dirs[0] |
| 177 | + if len(subdirs) == 1: |
| 178 | + return subdirs[0] |
| 179 | + return None |
| 180 | + |
| 181 | + # -- S3 upload ----------------------------------------------------------- |
| 182 | + |
| 183 | + async def _upload_directory(self, local_dir: Path, s3_prefix: str) -> None: |
| 184 | + files = [p for p in local_dir.rglob("*") if p.is_file()] |
| 185 | + if not files: |
| 186 | + return |
| 187 | + |
| 188 | + sem = asyncio.Semaphore(16) |
| 189 | + |
| 190 | + async def upload_one(f: Path) -> None: |
| 191 | + key = f"{s3_prefix}{f.relative_to(local_dir).as_posix()}" |
| 192 | + async with sem: |
| 193 | + await self._ensure_client() |
| 194 | + await self._client.upload_file(str(f), settings.sauron_s3_bucket, key) |
| 195 | + |
| 196 | + await asyncio.gather(*(upload_one(f) for f in files), return_exceptions=True) |
| 197 | + |
| 198 | + |
| 199 | +# -- Singleton --------------------------------------------------------------- |
| 200 | + |
| 201 | +_uploader: SauronS3Uploader | None = None |
| 202 | + |
| 203 | + |
| 204 | +def get_sauron_uploader() -> SauronS3Uploader: |
| 205 | + global _uploader |
| 206 | + if _uploader is None: |
| 207 | + _uploader = SauronS3Uploader() |
| 208 | + return _uploader |
0 commit comments