Create Hub artifact collections lazily (#245)
Browse files* Create Hub artifact collections lazily
Co-authored-by: OpenAI Codex <codex@openai.com>
* Cache lazy Hub collection slugs in child hooks
Co-authored-by: OpenAI Codex <codex@openai.com>
---------
Co-authored-by: OpenAI Codex <codex@openai.com>
Files changed (5)
26 unmodified lines272829303132331990 unmodified lines202420252026202720282029203026 unmodified linesfrom agent.messaging.gateway import NotificationGatewayfrom agent.core import telemetryfrom agent.core.doom_loop import check_for_doom_loopfrom agent.core.hub_artifacts import start_session_artifact_collection_taskfrom agent.core.llm_params import _resolve_llm_paramsfrom agent.core.prompt_caching import with_prompt_cachingfrom agent.core.session import DEFAULT_SESSION_LOG_DIR, Event, OpType, Session1990 unmodified lines)if session_holder is not None:session_holder[0] = sessionstart_session_artifact_collection_task(session, token=hf_token)logger.info("Agent loop started")# Retry any failed uploads from previous sessions (fire-and-forget).26 unmodified lines2728293031321990 unmodified lines20232024202520262027202826 unmodified linesfrom agent.messaging.gateway import NotificationGatewayfrom agent.core import telemetryfrom agent.core.doom_loop import check_for_doom_loopfrom agent.core.llm_params import _resolve_llm_paramsfrom agent.core.prompt_caching import with_prompt_cachingfrom agent.core.session import DEFAULT_SESSION_LOG_DIR, Event, OpType, Session1990 unmodified lines)if session_holder is not None:session_holder[0] = sessionlogger.info("Agent loop started")# Retry any failed uploads from previous sessions (fire-and-forget).
1234564 unmodified lines1112131415161711 unmodified lines29303132333435271 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753761 unmodified line3783793803813823833843853863875 unmodified lines39339439539639739837 unmodified lines43643743843944044144244346 unmodified lines490491492493494495106 unmodified lines6026036046056066075 unmodified lines61361461561661761818 unmodified lines6376386396406416429 unmodified lines6526536546556566576586598 unmodified lines668669670671672673674675676"""Best-effort Hub metadata for artifacts generated by ML Intern sessions."""import asyncioimport base64import loggingimport re4 unmodified linesfrom pathlib import Pathfrom typing import Anyfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.repocard import metadata_load, metadata_savefrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError11 unmodified lines_KNOWN_ARTIFACTS_ATTR = "_ml_intern_known_hub_artifacts"_REGISTERED_ARTIFACTS_ATTR = "_ml_intern_registered_hub_artifacts"_COLLECTION_SLUG_ATTR = "_ml_intern_artifact_collection_slug"_COLLECTION_TASK_ATTR = "_ml_intern_artifact_collection_task"_SESSION_ARTIFACT_SET_FALLBACK: dict[tuple[int, str], set[str]] = {}_USAGE_HEADING_RE = re.compile(r"^#{2,6}\s+(usage|how to use|using this (model|dataset)|use this (model|dataset))\b",271 unmodified linesreturn slugasync def ensure_session_artifact_collection(session: Any,*,token: str | bool | None = None,) -> str | None:"""Create/cache the per-session artifact collection without raising."""if session is None or not getattr(session, "session_id", None):return Nonetoken_value = token if token is not None else getattr(session, "hf_token", None)if not token_value:return Nonetry:api = HfApi(token=token_value)return await asyncio.to_thread(_ensure_collection_slug,api,session,token=token_value,)except Exception as e:logger.warning("ML Intern session collection creation failed for %s: %s",_safe_session_id(session),e,)return Nonedef start_session_artifact_collection_task(session: Any,*,token: str | bool | None = None,) -> asyncio.Task | None:"""Schedule best-effort collection creation for a newly started session."""if session is None or not getattr(session, "session_id", None):return Noneif getattr(session, _COLLECTION_SLUG_ATTR, None):return Nonetoken_value = token if token is not None else getattr(session, "hf_token", None)if not token_value:return Noneexisting = getattr(session, _COLLECTION_TASK_ATTR, None)if isinstance(existing, asyncio.Task) and not existing.done():return existingtry:loop = asyncio.get_running_loop()except RuntimeError:return Noneasync def _run() -> None:await ensure_session_artifact_collection(session, token=token_value)task = loop.create_task(_run())try:setattr(session, _COLLECTION_TASK_ATTR, task)except Exception:logger.debug("Could not attach ML Intern collection task to session")return taskdef _add_to_collection(api: Any,session: Any,1 unmodified linerepo_type: str,*,token: str | bool | None = None,) -> None:slug = _ensure_collection_slug(api, session, token=token)if not slug:returnapi.add_collection_item(collection_slug=slug,item_id=repo_id,5 unmodified linesexists_ok=True,token=token,)def register_hub_artifact(37 unmodified lineslogger.debug("ML Intern repo-card update failed for %s: %s", repo_id, e)try:_add_to_collection(api, session, repo_id, repo_type, token=token_value)collection_updated = Trueexcept Exception as e:logger.debug("ML Intern collection update failed for %s: %s", repo_id, e)46 unmodified linesre.IGNORECASE | re.MULTILINE,)front_matter_re = re.compile(r"\\A---\\s*\\n.*?\\n---\\s*\\n?", re.DOTALL)def _token(value=None, api=None):if isinstance(value, str) and value:106 unmodified linesnonlocal collection_slugif collection_slug:return collection_slugcollection = api.create_collection(title=collection_title,description=(5 unmodified linestoken=token_value,)collection_slug = getattr(collection, "slug", None)return collection_slugdef _register(18 unmodified linestry:token_value = _token(token_value)api = HfApi(token=token_value)try:current = _readme(api, repo_id, repo_type, token_value)updated = _augment(9 unmodified linestoken=token_value,commit_message="Update ML Intern artifact metadata",)except Exception:passtry:slug = _ensure_collection(api, token_value)if slug:8 unmodified linesexists_ok=True,token=token_value,)except Exception:passregistered.add(key)finally:registering = False123454 unmodified lines1011121314151611 unmodified lines282930313233271 unmodified lines3053063073083093101 unmodified line3123133143153163173183193203215 unmodified lines32732832933033133233337 unmodified lines37137237337437537637737837938038138238346 unmodified lines430431432433434435436437438439440441442106 unmodified lines5495505515525535545555565575585595605615625635 unmodified lines56957057157257357457557657757857958058118 unmodified lines6006016026036046056069 unmodified lines6166176186196206216226236246258 unmodified lines634635636637638639640641642643644"""Best-effort Hub metadata for artifacts generated by ML Intern sessions."""import base64import loggingimport re4 unmodified linesfrom pathlib import Pathfrom typing import Anyfrom huggingface_hub import hf_hub_downloadfrom huggingface_hub.repocard import metadata_load, metadata_savefrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError11 unmodified lines_KNOWN_ARTIFACTS_ATTR = "_ml_intern_known_hub_artifacts"_REGISTERED_ARTIFACTS_ATTR = "_ml_intern_registered_hub_artifacts"_COLLECTION_SLUG_ATTR = "_ml_intern_artifact_collection_slug"_SESSION_ARTIFACT_SET_FALLBACK: dict[tuple[int, str], set[str]] = {}_USAGE_HEADING_RE = re.compile(r"^#{2,6}\s+(usage|how to use|using this (model|dataset)|use this (model|dataset))\b",271 unmodified linesreturn slugdef _add_to_collection(api: Any,session: Any,1 unmodified linerepo_type: str,*,token: str | bool | None = None,) -> bool:slug = _ensure_collection_slug(api, session, token=token)if not slug:return Falseapi.add_collection_item(collection_slug=slug,item_id=repo_id,5 unmodified linesexists_ok=True,token=token,)return Truedef register_hub_artifact(37 unmodified lineslogger.debug("ML Intern repo-card update failed for %s: %s", repo_id, e)try:collection_updated = _add_to_collection(api,session,repo_id,repo_type,token=token_value,)except Exception as e:logger.debug("ML Intern collection update failed for %s: %s", repo_id, e)46 unmodified linesre.IGNORECASE | re.MULTILINE,)front_matter_re = re.compile(r"\\A---\\s*\\n.*?\\n---\\s*\\n?", re.DOTALL)collection_cache_path = (os.environ.get("ML_INTERN_ARTIFACT_COLLECTION_CACHE")or str(Path(tempfile.gettempdir())/ f"ml-intern-artifacts-{{session_id}}.collection"))def _token(value=None, api=None):if isinstance(value, str) and value:106 unmodified linesnonlocal collection_slugif collection_slug:return collection_slugtry:cached_slug = Path(collection_cache_path).read_text(encoding="utf-8").strip()if cached_slug:collection_slug = cached_slugreturn collection_slugexcept Exception:passcollection = api.create_collection(title=collection_title,description=(5 unmodified linestoken=token_value,)collection_slug = getattr(collection, "slug", None)if collection_slug:try:cache_path = Path(collection_cache_path)cache_path.parent.mkdir(parents=True, exist_ok=True)cache_path.write_text(collection_slug, encoding="utf-8")except Exception:passreturn collection_slugdef _register(18 unmodified linestry:token_value = _token(token_value)api = HfApi(token=token_value)card_updated = Falsetry:current = _readme(api, repo_id, repo_type, token_value)updated = _augment(9 unmodified linestoken=token_value,commit_message="Update ML Intern artifact metadata",)card_updated = Trueexcept Exception:passcollection_updated = Falsetry:slug = _ensure_collection(api, token_value)if slug:8 unmodified linesexists_ok=True,token=token_value,)collection_updated = Trueexcept Exception:passif card_updated and collection_updated:registered.add(key)finally:registering = False
11 unmodified lines12131415161718117 unmodified lines136137138139140141142270 unmodified lines413414415416417418419420421422423424425426427428429430431432433434435436437438439440150 unmodified lines59159259359459559659715 unmodified lines61361461561661761861980 unmodified lines70070170270370470570670770876 unmodified lines78578678778878979079111 unmodified linesfrom agent.config import load_configfrom agent.core.agent_loop import process_submissionfrom agent.core.hub_artifacts import start_session_artifact_collection_taskfrom agent.core.session import Event, OpType, Sessionfrom agent.core.session_persistence import get_session_storefrom agent.core.tools import ToolRouter117 unmodified linesself.sessions: dict[str, AgentSession] = {}self._lock = asyncio.Lock()self.persistence_store = Noneself.enable_hub_artifact_collections = Trueasync def start(self) -> None:"""Start shared background resources."""270 unmodified linessession.sandbox_preload_cancel_event = Noneself._start_cpu_sandbox_preload(agent_session)def _start_hub_artifact_collection(self, agent_session: AgentSession) -> None:"""Kick off best-effort Hub collection creation for the session."""if not getattr(self, "enable_hub_artifact_collections", False):returnsession = agent_session.sessionif not getattr(session, "session_id", None):try:session.session_id = agent_session.session_idexcept Exception:logger.debug("Could not attach session id for Hub artifact collection")token = agent_session.hf_token or getattr(session, "hf_token", None)if not token:returntry:start_session_artifact_collection_task(session, token=token)except Exception as e:logger.debug("Failed to schedule Hub artifact collection for %s: %s",agent_session.session_id,e,)async def _clear_persisted_sandbox_metadata(self, session_id: str) -> None:try:await self._store().update_session_fields(150 unmodified linesexisting,preload_sandbox=preload_sandbox,)self._start_hub_artifact_collection(existing)return existingreturn None15 unmodified linesexisting,preload_sandbox=preload_sandbox,)self._start_hub_artifact_collection(existing)return existingreturn None80 unmodified lineshf_token=hf_token,hf_username=hf_username,)self._start_hub_artifact_collection(started)return startedself._start_hub_artifact_collection(agent_session)if preload_sandbox:self._start_cpu_sandbox_preload(agent_session)logger.info("Restored session %s for user %s", session_id, owner or user_id)76 unmodified linesevent_queue=event_queue,tool_router=tool_router,)self._start_hub_artifact_collection(agent_session)await self.persist_session_snapshot(agent_session, runtime_state="idle")self._start_cpu_sandbox_preload(agent_session)11 unmodified lines121314151617117 unmodified lines135136137138139140270 unmodified lines411412413414415416150 unmodified lines56756856957057157215 unmodified lines58858959059159259380 unmodified lines67467567667767867968076 unmodified lines75775875976076176211 unmodified linesfrom agent.config import load_configfrom agent.core.agent_loop import process_submissionfrom agent.core.session import Event, OpType, Sessionfrom agent.core.session_persistence import get_session_storefrom agent.core.tools import ToolRouter117 unmodified linesself.sessions: dict[str, AgentSession] = {}self._lock = asyncio.Lock()self.persistence_store = Noneasync def start(self) -> None:"""Start shared background resources."""270 unmodified linessession.sandbox_preload_cancel_event = Noneself._start_cpu_sandbox_preload(agent_session)async def _clear_persisted_sandbox_metadata(self, session_id: str) -> None:try:await self._store().update_session_fields(150 unmodified linesexisting,preload_sandbox=preload_sandbox,)return existingreturn None15 unmodified linesexisting,preload_sandbox=preload_sandbox,)return existingreturn None80 unmodified lineshf_token=hf_token,hf_username=hf_username,)return startedif preload_sandbox:self._start_cpu_sandbox_preload(agent_session)logger.info("Restored session %s for user %s", session_id, owner or user_id)76 unmodified linesevent_queue=event_queue,tool_router=tool_router,)await self.persist_session_snapshot(agent_session, runtime_state="idle")self._start_cpu_sandbox_preload(agent_session)
12346 unmodified lines111213141516171819202122184 unmodified lines20720820921021121225 unmodified lines23823924024124224327 unmodified lines271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333201 unmodified lines535536537538539540import asyncioimport loggingfrom types import SimpleNamespace6 unmodified linesartifact_collection_title,augment_repo_card_content,build_hub_artifact_sitecustomize,ensure_session_artifact_collection,is_known_hub_artifact,is_sandbox_hub_repo,register_hub_artifact,remember_hub_artifact,start_session_artifact_collection_task,wrap_shell_command_with_hub_artifact_bootstrap,)from agent.tools import local_tools, sandbox_tool184 unmodified linesdef add_to_collection(*args, **kwargs):nonlocal collection_attemptscollection_attempts += 1monkeypatch.setattr(hub_artifacts,25 unmodified linescollection_attempts += 1if collection_attempts == 1:raise RuntimeError("temporary collection failure")monkeypatch.setattr(hub_artifacts, "_update_repo_card", update_repo_card)monkeypatch.setattr(27 unmodified linesassert "using process-local fallback state" in caplog.text@pytest.mark.asyncioasync def test_ensure_session_artifact_collection_uses_user_token(monkeypatch):session = _session()calls = []class FakeApi:def __init__(self, token):self.token = tokendef fake_ensure_collection_slug(api, seen_session, **kwargs):calls.append((api.token, seen_session, kwargs))return "alice/ml-intern-artifacts"monkeypatch.setattr(hub_artifacts, "HfApi", FakeApi)monkeypatch.setattr(hub_artifacts,"_ensure_collection_slug",fake_ensure_collection_slug,)slug = await ensure_session_artifact_collection(session, token="hf-token")assert slug == "alice/ml-intern-artifacts"assert calls == [("hf-token", session, {"token": "hf-token"}),]@pytest.mark.asyncioasync def test_start_session_artifact_collection_task_dedupes(monkeypatch):session = _session()calls = []async def fake_ensure_session_artifact_collection(seen_session, **kwargs):calls.append((seen_session, kwargs))await asyncio.sleep(0)return "alice/ml-intern-artifacts"monkeypatch.setattr(hub_artifacts,"ensure_session_artifact_collection",fake_ensure_session_artifact_collection,)task = start_session_artifact_collection_task(session, token="hf-token")second = start_session_artifact_collection_task(session, token="hf-token")assert task is not Noneassert second is taskawait taskassert calls == [(session, {"token": "hf-token"})]def test_start_session_artifact_collection_task_skips_without_token():assert start_session_artifact_collection_task(_session()) is None@pytest.mark.asyncioasync def test_hf_repo_git_create_repo_registers_artifact(monkeypatch):session = _session()201 unmodified lines)def test_sitecustomize_skips_sandbox_space_registration(monkeypatch):import huggingface_hub as hubfrom huggingface_hub import HfApi1236 unmodified lines10111213141516171819184 unmodified lines20420520620720820921025 unmodified lines23623723823924024124227 unmodified lines270271272273274275201 unmodified lines477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554import loggingfrom types import SimpleNamespace6 unmodified linesartifact_collection_title,augment_repo_card_content,build_hub_artifact_sitecustomize,is_known_hub_artifact,is_sandbox_hub_repo,register_hub_artifact,remember_hub_artifact,wrap_shell_command_with_hub_artifact_bootstrap,)from agent.tools import local_tools, sandbox_tool184 unmodified linesdef add_to_collection(*args, **kwargs):nonlocal collection_attemptscollection_attempts += 1return Truemonkeypatch.setattr(hub_artifacts,25 unmodified linescollection_attempts += 1if collection_attempts == 1:raise RuntimeError("temporary collection failure")return Truemonkeypatch.setattr(hub_artifacts, "_update_repo_card", update_repo_card)monkeypatch.setattr(27 unmodified linesassert "using process-local fallback state" in caplog.text@pytest.mark.asyncioasync def test_hf_repo_git_create_repo_registers_artifact(monkeypatch):session = _session()201 unmodified lines)def test_sitecustomize_caches_lazy_collection_slug_across_bootstraps(monkeypatch,tmp_path,):import huggingface_hub as hubfrom huggingface_hub import HfApireadme_path = tmp_path / "README.md"readme_path.write_text("# Existing Model\n", encoding="utf-8")cache_path = tmp_path / "collection-slug.txt"collection_slug = "alice/ml-intern-artifacts-2026-05-05-session-123"uploads = []downloads = []collection_creates = []collection_items = []def fake_upload_file(self, **kwargs):uploads.append(kwargs)return SimpleNamespace()def fake_hf_hub_download(*args, **kwargs):downloads.append((args, kwargs))return str(readme_path)def fake_create_collection(self, **kwargs):collection_creates.append(kwargs)return SimpleNamespace(slug=collection_slug)def fake_add_collection_item(self, **kwargs):collection_items.append(kwargs)monkeypatch.setenv("ML_INTERN_ARTIFACT_COLLECTION_CACHE", str(cache_path))code = build_hub_artifact_sitecustomize(_session())def install_fresh_bootstrap():monkeypatch.setattr(HfApi, "upload_file", fake_upload_file)monkeypatch.setattr(HfApi, "create_collection", fake_create_collection)monkeypatch.setattr(HfApi, "add_collection_item", fake_add_collection_item)monkeypatch.setattr(hub, "hf_hub_download", fake_hf_hub_download)exec(code, {})assert HfApi.upload_file is not fake_upload_fileinstall_fresh_bootstrap()HfApi(token="hf-token").upload_file(path_or_fileobj=b"weights",path_in_repo="model.safetensors",repo_id="alice/model-a",repo_type="model",token="hf-token",)install_fresh_bootstrap()HfApi(token="hf-token").upload_file(path_or_fileobj=b"weights",path_in_repo="model.safetensors",repo_id="alice/model-b",repo_type="model",token="hf-token",)assert cache_path.read_text(encoding="utf-8") == collection_slugassert len(collection_creates) == 1assert [item["item_id"] for item in collection_items] == ["alice/model-a","alice/model-b",]assert [download[1]["repo_id"] for download in downloads] == ["alice/model-a","alice/model-b",]def test_sitecustomize_skips_sandbox_space_registration(monkeypatch):import huggingface_hub as hubfrom huggingface_hub import HfApi
424 unmodified lines42542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545618 unmodified lines475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511424 unmodified linesassert scheduled == [session_id]assert session_id in manager.sessionsfinally:stop.set()await _cancel_runtime_tasks(manager)@pytest.mark.asyncioasync def test_create_session_starts_hub_artifact_collection(monkeypatch):manager = _manager_with_store(NoopSessionStore())manager.enable_hub_artifact_collections = Truestop = _install_fake_runtime(manager)started: list[tuple[str, str]] = []def fake_start_session_artifact_collection_task(session, **kwargs):started.append((session.session_id, kwargs["token"]))return Nonemonkeypatch.setattr("session_manager.start_session_artifact_collection_task",fake_start_session_artifact_collection_task,)manager._start_cpu_sandbox_preload = lambda _: None # type: ignore[method-assign]try:session_id = await manager.create_session(user_id="owner", hf_token="token")assert started == [(session_id, "token")]finally:stop.set()await _cancel_runtime_tasks(manager)18 unmodified linesassert restored is not Noneassert scheduled == ["persisted-session"]assert "persisted-session" in manager.sessionsfinally:stop.set()await _cancel_runtime_tasks(manager)@pytest.mark.asyncioasync def test_lazy_restore_starts_hub_artifact_collection(monkeypatch):manager = _manager_with_store(RestoreStore())manager.enable_hub_artifact_collections = Truestop = _install_fake_runtime(manager)started: list[tuple[str, str]] = []def fake_start_session_artifact_collection_task(session, **kwargs):started.append((session.session_id, kwargs["token"]))return Nonemonkeypatch.setattr("session_manager.start_session_artifact_collection_task",fake_start_session_artifact_collection_task,)manager._start_cpu_sandbox_preload = lambda _: None # type: ignore[method-assign]try:restored = await manager.ensure_session_loaded("persisted-session",user_id="owner",hf_token="token",)assert restored is not Noneassert started == [("persisted-session", "token")]finally:stop.set()await _cancel_runtime_tasks(manager)424 unmodified lines42542642742842943043143243318 unmodified lines452453454455456457458459424 unmodified linesassert scheduled == [session_id]assert session_id in manager.sessionsruntime_session = manager.sessions[session_id].sessionassert not hasattr(runtime_session, "_ml_intern_artifact_collection_task")assert not hasattr(runtime_session, "_ml_intern_artifact_collection_slug")finally:stop.set()await _cancel_runtime_tasks(manager)18 unmodified linesassert restored is not Noneassert scheduled == ["persisted-session"]assert "persisted-session" in manager.sessionsassert not hasattr(restored.session, "_ml_intern_artifact_collection_task")assert not hasattr(restored.session, "_ml_intern_artifact_collection_slug")finally:stop.set()await _cancel_runtime_tasks(manager)
agent/core/agent_loop.py-2
agent/core/hub_artifacts.py+40-72
backend/session_manager.py-29
tests/unit/test_hub_artifacts.py+74-60
tests/unit/test_session_manager_persistence.py+5-57