Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 19,344 Bytes
4fc6e96 1e1fe1f 4fc6e96 1e1fe1f 4fc6e96 60474c1 4fc6e96 60474c1 4fc6e96 1e1fe1f 60474c1 b05b6f5 1e1fe1f b05b6f5 1e1fe1f | 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | import logging
from types import SimpleNamespace
import pytest
from agent.core import hub_artifacts
from agent.core.hub_artifacts import (
ML_INTERN_TAG,
PROVENANCE_MARKER,
artifact_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_tool
from agent.tools.hf_repo_files_tool import HfRepoFilesTool
from agent.tools.hf_repo_git_tool import HfRepoGitTool
from agent.tools.jobs_tool import _wrap_command_with_artifact_bootstrap
def _session() -> SimpleNamespace:
return SimpleNamespace(
session_id="session-123",
session_start_time="2026-05-05T10:20:30",
)
def test_artifact_collection_title_uses_session_date_and_id():
assert (
artifact_collection_title(_session())
== "ml-intern-artifacts-2026-05-05-session-123"
)
def test_artifact_collection_title_uses_short_uuid_fragment():
session = SimpleNamespace(
session_id="fadcbc77-3439-4c2b-bc52-50d7f6353af3",
session_start_time="2026-05-05T10:20:30",
)
title = artifact_collection_title(session)
assert title == "ml-intern-artifacts-2026-05-05-fadcbc77"
assert len(title) < 60
def test_artifact_collection_title_still_truncates_long_non_uuid_ids():
session = SimpleNamespace(
session_id="custom-session-id-that-is-longer-than-the-hub-title-limit",
session_start_time="2026-05-05T10:20:30",
)
title = artifact_collection_title(session)
assert title.startswith("ml-intern-artifacts-2026-05-05-custom-session-id")
assert len(title) < 60
def test_model_card_merges_tags_and_appends_provenance_and_usage():
content = """---
license: apache-2.0
tags:
- text-generation
---
# Existing Model
Existing details stay here.
"""
updated = augment_repo_card_content(content, "alice/model", "model")
second_pass = augment_repo_card_content(updated, "alice/model", "model")
assert "license: apache-2.0" in updated
assert "- text-generation" in updated
assert f"- {ML_INTERN_TAG}" in updated
assert "# Existing Model" in updated
assert "Existing details stay here." in updated
assert PROVENANCE_MARKER in updated
assert "AutoModelForCausalLM" in updated
assert second_pass.count(PROVENANCE_MARKER) == 1
assert second_pass.count("AutoModelForCausalLM") == updated.count(
"AutoModelForCausalLM"
)
def test_dataset_card_adds_load_dataset_usage():
updated = augment_repo_card_content("", "alice/dataset", "dataset")
assert f"- {ML_INTERN_TAG}" in updated
assert "# alice/dataset" in updated
assert "from datasets import load_dataset" in updated
assert 'load_dataset("alice/dataset")' in updated
def test_existing_usage_section_is_preserved_without_duplicate_usage():
content = """# Existing Dataset
## Usage
Use the custom loader in this repository.
"""
updated = augment_repo_card_content(content, "alice/dataset", "dataset")
assert "Use the custom loader in this repository." in updated
assert "from datasets import load_dataset" not in updated
assert PROVENANCE_MARKER in updated
def test_space_card_gets_metadata_without_provenance_body():
updated = augment_repo_card_content("# Existing Space\n", "alice/space", "space")
assert f"- {ML_INTERN_TAG}" in updated
assert "# Existing Space" in updated
assert PROVENANCE_MARKER not in updated
def test_register_hub_artifact_creates_private_collection_and_adds_item_once(
monkeypatch,
):
session = _session()
class FakeApi:
token = "hf-token"
def __init__(self):
self.created_collections = []
self.collection_items = []
self.uploads = []
def create_collection(self, **kwargs):
self.created_collections.append(kwargs)
return SimpleNamespace(slug="alice/ml-intern-artifacts")
def add_collection_item(self, **kwargs):
self.collection_items.append(kwargs)
def upload_file(self, **kwargs):
self.uploads.append(kwargs)
api = FakeApi()
monkeypatch.setattr(hub_artifacts, "_read_remote_readme", lambda *_, **__: "")
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert is_known_hub_artifact(session, "alice/model", "model")
assert len(api.created_collections) == 1
assert api.created_collections[0]["title"] == artifact_collection_title(session)
assert api.created_collections[0]["private"] is True
assert len(api.collection_items) == 1
assert api.collection_items[0]["item_id"] == "alice/model"
assert api.collection_items[0]["item_type"] == "model"
assert api.collection_items[0]["exists_ok"] is True
assert len(api.uploads) == 1
assert b"ml-intern" in api.uploads[0]["path_or_fileobj"]
def test_register_hub_artifact_skips_sandbox_spaces(monkeypatch):
session = _session()
api = SimpleNamespace(token="hf-token")
calls = []
monkeypatch.setattr(
hub_artifacts,
"_update_repo_card",
lambda *args, **kwargs: calls.append(("card", args, kwargs)),
)
monkeypatch.setattr(
hub_artifacts,
"_add_to_collection",
lambda *args, **kwargs: calls.append(("collection", args, kwargs)),
)
assert is_sandbox_hub_repo("alice/sandbox-1234abcd", "space")
assert not is_sandbox_hub_repo("alice/sandbox-1234abcd", "model")
assert not is_sandbox_hub_repo("alice/demo-space", "space")
assert not register_hub_artifact(
api,
"alice/sandbox-1234abcd",
"space",
session=session,
)
assert not is_known_hub_artifact(session, "alice/sandbox-1234abcd", "space")
assert calls == []
def test_register_hub_artifact_retries_after_partial_failure(monkeypatch):
session = _session()
api = SimpleNamespace(token="hf-token")
card_attempts = 0
collection_attempts = 0
def flaky_update_repo_card(*args, **kwargs):
nonlocal card_attempts
card_attempts += 1
if card_attempts == 1:
raise RuntimeError("temporary card failure")
def add_to_collection(*args, **kwargs):
nonlocal collection_attempts
collection_attempts += 1
return True
monkeypatch.setattr(
hub_artifacts,
"_update_repo_card",
flaky_update_repo_card,
)
monkeypatch.setattr(hub_artifacts, "_add_to_collection", add_to_collection)
assert not register_hub_artifact(api, "alice/model", "model", session=session)
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert card_attempts == 2
assert collection_attempts == 2
def test_register_hub_artifact_retries_after_collection_failure(monkeypatch):
session = _session()
api = SimpleNamespace(token="hf-token")
card_attempts = 0
collection_attempts = 0
def update_repo_card(*args, **kwargs):
nonlocal card_attempts
card_attempts += 1
def flaky_add_to_collection(*args, **kwargs):
nonlocal collection_attempts
collection_attempts += 1
if collection_attempts == 1:
raise RuntimeError("temporary collection failure")
return True
monkeypatch.setattr(hub_artifacts, "_update_repo_card", update_repo_card)
monkeypatch.setattr(
hub_artifacts,
"_add_to_collection",
flaky_add_to_collection,
)
assert not register_hub_artifact(api, "alice/model", "model", session=session)
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert register_hub_artifact(api, "alice/model", "model", session=session)
assert card_attempts == 2
assert collection_attempts == 2
def test_session_artifact_set_falls_back_when_session_rejects_attrs(caplog):
class SlottedSession:
__slots__ = ("session_id", "session_start_time")
def __init__(self):
self.session_id = "session-123"
self.session_start_time = "2026-05-05T10:20:30"
session = SlottedSession()
with caplog.at_level(logging.WARNING):
remember_hub_artifact(session, "alice/model", "model")
assert is_known_hub_artifact(session, "alice/model", "model")
assert "using process-local fallback state" in caplog.text
@pytest.mark.asyncio
async def test_hf_repo_git_create_repo_registers_artifact(monkeypatch):
session = _session()
calls = []
class FakeApi:
token = "hf-token"
def create_repo(self, **kwargs):
self.create_kwargs = kwargs
return "https://huggingface.co/spaces/alice/demo"
def fake_register(api, repo_id, repo_type, **kwargs):
calls.append((api, repo_id, repo_type, kwargs))
return True
monkeypatch.setattr(
"agent.tools.hf_repo_git_tool.register_hub_artifact",
fake_register,
)
tool = HfRepoGitTool(hf_token="hf-token", session=session)
tool.api = FakeApi()
result = await tool._create_repo(
{
"repo_id": "alice/demo",
"repo_type": "space",
"space_sdk": "gradio",
"private": True,
}
)
assert result["totalResults"] == 1
assert calls == [
(
tool.api,
"alice/demo",
"space",
{"session": session, "extra_metadata": {"sdk": "gradio"}},
)
]
@pytest.mark.asyncio
async def test_hf_repo_files_upload_registers_known_artifact_with_force(monkeypatch):
session = _session()
calls = []
uploads = []
class FakeApi:
token = "hf-token"
def upload_file(self, **kwargs):
uploads.append(kwargs)
return SimpleNamespace()
def fake_register(api, repo_id, repo_type, **kwargs):
calls.append((api, repo_id, repo_type, kwargs))
return True
monkeypatch.setattr(
"agent.tools.hf_repo_files_tool.register_hub_artifact",
fake_register,
)
remember_hub_artifact(session, "alice/model", "model")
tool = HfRepoFilesTool(hf_token="hf-token", session=session)
tool.api = FakeApi()
result = await tool._upload(
{
"repo_id": "alice/model",
"repo_type": "model",
"path": "weights.bin",
"content": b"weights",
}
)
readme_result = await tool._upload(
{
"repo_id": "alice/model",
"repo_type": "model",
"path": "README.md",
"content": "# Model",
}
)
assert result["totalResults"] == 1
assert readme_result["totalResults"] == 1
assert [upload["path_in_repo"] for upload in uploads] == [
"weights.bin",
"README.md",
]
assert calls == [
(
tool.api,
"alice/model",
"model",
{"session": session, "force": False},
),
(
tool.api,
"alice/model",
"model",
{"session": session, "force": True},
),
]
def test_hf_jobs_artifact_bootstrap_wraps_command_without_changing_exec_target():
command = ["uv", "run", "train.py"]
wrapped = _wrap_command_with_artifact_bootstrap(command, _session())
assert wrapped[0:2] == ["/bin/sh", "-lc"]
assert "sitecustomize.py" in wrapped[2]
assert "PYTHONPATH" in wrapped[2]
assert "exec uv run train.py" in wrapped[2]
assert _wrap_command_with_artifact_bootstrap(command, None) == command
def test_shell_bootstrap_wraps_capybara_push_to_hub_pattern():
command = (
"pip install -q datasets huggingface_hub && python -c "
"\"subset.push_to_hub('lewtun/Capybara-100', private=False)\""
)
wrapped = wrap_shell_command_with_hub_artifact_bootstrap(command, _session())
assert "sitecustomize.py" in wrapped
assert "PYTHONPATH" in wrapped
assert command in wrapped
assert wrap_shell_command_with_hub_artifact_bootstrap(command, None) == command
assert (
wrap_shell_command_with_hub_artifact_bootstrap(
command,
SimpleNamespace(session_start_time="2026-05-05T10:20:30"),
)
== command
)
@pytest.mark.asyncio
async def test_sandbox_bash_wraps_command_for_session_artifact_hooks():
calls = []
class FakeSandbox:
def call_tool(self, name, args):
calls.append((name, args))
return SimpleNamespace(success=True, output="ok", error="")
session = _session()
session.sandbox = FakeSandbox()
handler = sandbox_tool._make_tool_handler("bash")
output, ok = await handler({"command": "python make_dataset.py"}, session=session)
assert ok is True
assert output == "ok"
assert calls[0][0] == "bash"
assert "sitecustomize.py" in calls[0][1]["command"]
assert "python make_dataset.py" in calls[0][1]["command"]
@pytest.mark.asyncio
async def test_local_bash_wraps_command_for_session_artifact_hooks(monkeypatch):
seen = {}
def fake_run(command, **kwargs):
seen["command"] = command
seen["kwargs"] = kwargs
return SimpleNamespace(stdout="ok", stderr="", returncode=0)
monkeypatch.setattr(local_tools.subprocess, "run", fake_run)
output, ok = await local_tools._bash_handler(
{"command": "python make_dataset.py"},
session=_session(),
)
assert ok is True
assert output == "ok"
assert "sitecustomize.py" in seen["command"]
assert "python make_dataset.py" in seen["command"]
def test_sitecustomize_bootstrap_is_valid_python():
code = build_hub_artifact_sitecustomize(_session())
compile(code, "sitecustomize.py", "exec")
assert "ml-intern-artifacts-2026-05-05-session-123" in code
def test_sitecustomize_bootstrap_reuses_existing_collection_slug():
session = _session()
setattr(
session,
hub_artifacts._COLLECTION_SLUG_ATTR,
"alice/ml-intern-artifacts-2026-05-05-session-123",
)
code = build_hub_artifact_sitecustomize(session)
compile(code, "sitecustomize.py", "exec")
assert (
"collection_slug = 'alice/ml-intern-artifacts-2026-05-05-session-123'" in code
)
def test_sitecustomize_caches_lazy_collection_slug_across_bootstraps(
monkeypatch,
tmp_path,
):
import huggingface_hub as hub
from huggingface_hub import HfApi
readme_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_file
install_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_slug
assert len(collection_creates) == 1
assert [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, tmp_path):
import huggingface_hub as hub
from huggingface_hub import HfApi
uploads = []
downloads = []
collection_creates = []
collection_items = []
for name in ("create_repo", "upload_folder", "create_commit"):
if hasattr(HfApi, name):
monkeypatch.setattr(HfApi, name, getattr(HfApi, name))
if hasattr(hub, name):
monkeypatch.setattr(hub, name, getattr(hub, name))
def fake_upload_file(self, **kwargs):
uploads.append(kwargs)
return SimpleNamespace()
def fake_hf_hub_download(*args, **kwargs):
downloads.append((args, kwargs))
raise RuntimeError("sandbox metadata update should be skipped")
def fake_create_collection(self, **kwargs):
collection_creates.append(kwargs)
return SimpleNamespace(slug="alice/ml-intern-artifacts")
def fake_add_collection_item(self, **kwargs):
collection_items.append(kwargs)
monkeypatch.setenv(
"ML_INTERN_ARTIFACT_COLLECTION_CACHE",
str(tmp_path / "collection-slug.txt"),
)
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, "upload_file", getattr(hub, "upload_file"))
monkeypatch.setattr(hub, "hf_hub_download", fake_hf_hub_download)
exec(build_hub_artifact_sitecustomize(_session()), {})
assert HfApi.upload_file is not fake_upload_file
HfApi(token="hf-token").upload_file(
path_or_fileobj=b"app",
path_in_repo="app.py",
repo_id="alice/normal-space",
repo_type="space",
token="hf-token",
)
assert downloads[0][1]["repo_id"] == "alice/normal-space"
assert len(collection_creates) == 1
assert collection_items[0]["item_id"] == "alice/normal-space"
uploads.clear()
downloads.clear()
collection_creates.clear()
collection_items.clear()
HfApi(token="hf-token").upload_file(
path_or_fileobj=b"app",
path_in_repo="app.py",
repo_id="alice/sandbox-1234abcd",
repo_type="space",
token="hf-token",
)
assert [upload["repo_id"] for upload in uploads] == ["alice/sandbox-1234abcd"]
assert downloads == []
assert collection_creates == []
assert collection_items == []
|