"""Census of community OpenEnv environments on the Hugging Face Hub, using only the model-free players. python scripts/hub_sweep.py --top 150 --random 150 --out runs/hub/sweep For each Space tagged `openenv`: its runtime state from the Hub API, a wake-up if it sleeps, the standard OpenEnv routes (/health, /schema), one reset, then a short do-nothing episode and two random ones. No model tokens are spent. Each Space ends in one class: broken build or runtime error reported by the Hub paused by owner the owner paused or stopped the Space asleep, didn't wake asleep, and no OpenEnv route answered within the wake timeout (may only be slow) no standard API running, but no /schema with an action schema on any of the routes tried refuses a session the WebSocket session is rejected crashes reset() or step() raises a server error suspicious floor doing nothing scores above zero and as well as random play: needs a model to confirm passes floor checks runs, and doing nothing doesn't already score well Polite to the Hub: at most a few Spaces at a time, with a pause between starts. """ from __future__ import annotations import argparse import json import random import sys import threading import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path import requests sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from openenv.core.generic_client import GenericEnvClient # noqa: E402 from openenv.core.utils import hf_space_subdomain # noqa: E402 from shortlist.policies import Null, Random, action_tool, random_supported # noqa: E402 from shortlist.rollout import run_episode # noqa: E402 PREFIXES = ["", "/env", "/api", "/openenv"] # some Spaces mount the app under a path UA = {"User-Agent": "shortlist-census (OpenEnv learnability checks)"} def list_spaces() -> list[dict]: import re url, out = "https://huggingface.co/api/spaces?filter=openenv&limit=1000&full=true", [] while url: r = requests.get(url, headers=UA, timeout=60) out += r.json() m = re.search(r'<([^>]+)>;\s*rel="next"', r.headers.get("Link", "")) url = m.group(1) if m else None return out def stage(space: str) -> str: try: return requests.get(f"https://huggingface.co/api/spaces/{space}/runtime", headers=UA, timeout=20).json().get("stage", "?") except Exception: # noqa: BLE001 return "?" def wake(base: str, limit: float) -> bool: """Visit the Space until it answers on /health or /schema (not every Space serves /health).""" deadline = time.time() + limit while time.time() < deadline: for route in ("/health", "/schema"): try: if requests.get(base + route, headers=UA, timeout=15).ok: return True except requests.RequestException: pass try: requests.get(base + "/", headers=UA, timeout=15) # visiting the Space wakes it except requests.RequestException: pass time.sleep(10) return False def find_api(base: str) -> tuple[str | None, dict | None, list[str]]: tried = [] for prefix in PREFIXES: url = base + prefix tried.append(prefix or "/") try: r = requests.get(url + "/schema", headers=UA, timeout=20) schema = r.json() if r.ok and r.headers.get("content-type", "").startswith("application/json") else None except (requests.RequestException, ValueError): schema = None if schema and isinstance(schema.get("action"), dict): return url, schema, tried return None, None, tried def check(space: dict, wake_limit: float) -> dict: sid = space["id"] rec = {"id": sid, "likes": space.get("likes", 0), "created": space.get("createdAt", "")[:10], "stage": stage(sid)} base = f"https://{hf_space_subdomain(sid)}.hf.space" rec["url"] = base if rec["stage"] in ("BUILD_ERROR", "RUNTIME_ERROR", "CONFIG_ERROR", "NO_APP_FILE"): return {**rec, "class": "broken", "why": rec["stage"]} if rec["stage"] in ("PAUSED", "STOPPED", "DELETING"): return {**rec, "class": "paused by owner", "why": rec["stage"]} if rec["stage"] != "RUNNING" and not wake(base, wake_limit): return {**rec, "class": "asleep, didn't wake", "why": f"was {rec['stage']}; no /health or /schema within {int(wake_limit)}s"} url, schema, tried = find_api(base) if not url: return {**rec, "class": "no standard API", "why": f"no /schema with an action schema at {', '.join(tried)}"} rec["api_url"] = url tool = action_tool(schema["action"]) rec["action_fields"] = list(tool["function"]["parameters"]["properties"]) try: with GenericEnvClient(base_url=url).sync() as env: first = env.reset().observation or {} except Exception as error: # noqa: BLE001 text = str(error) if "403" in text or "rejected WebSocket" in text: return {**rec, "class": "refuses a session", "why": text[:200]} return {**rec, "class": "crashes", "why": f"reset: {text[:200]}"} episodes = [run_episode(url, tool, Null(), {}, 10)] if random_supported(tool, first): episodes += [run_episode(url, tool, Random(s), {}, 10) for s in range(2)] rec["floor"] = [{"policy": e["policy"], "return": e["return"], "steps": e["n_steps"], "done": e["done"], "error": e["error"]} for e in episodes] errors = [e for e in episodes if e["error"]] if errors: return {**rec, "class": "crashes", "why": f"step: {errors[0]['error'][:200]}"} null_ret = episodes[0]["return"] others = [e["return"] for e in episodes[1:]] if null_ret > 0 and all(null_ret >= o for o in others): return {**rec, "class": "suspicious floor", "why": f"doing nothing scored {null_ret:.3g}" + (f", random {others}" if others else "")} return {**rec, "class": "passes floor checks", "why": ""} def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--top", type=int, default=150) ap.add_argument("--random", type=int, default=150) ap.add_argument("--workers", type=int, default=3) ap.add_argument("--wake", type=float, default=150) ap.add_argument("--out", default="runs/hub/sweep") ap.add_argument("--recheck", action="store_true", help="re-check the Spaces the first pass couldn't reach, with --wake seconds, into census2.jsonl") args = ap.parse_args() if args.recheck: recheck(Path(args.out), args.wake, args.workers) return out = Path(args.out) out.mkdir(parents=True, exist_ok=True) spaces = [s for s in list_spaces() if s.get("sdk") == "docker"] top = sorted(spaces, key=lambda s: -s.get("likes", 0))[: args.top] rest = [s for s in spaces if s not in top] sample = random.Random(20261030).sample(rest, min(args.random, len(rest))) chosen = [{**s, "_group": "top"} for s in top] + [{**s, "_group": "random"} for s in sample] (out / "chosen.json").write_text(json.dumps([{"id": s["id"], "group": s["_group"]} for s in chosen], indent=1)) path = out / "census.jsonl" done = {json.loads(l)["id"] for l in path.read_text().splitlines()} if path.exists() else set() lock = threading.Lock() print(f"{len(spaces)} docker Spaces tagged openenv; checking {len(chosen)} ({len(done)} already done)", flush=True) def work(s): if s["id"] in done: return time.sleep(random.uniform(1, 3)) # spread out the starts try: rec = check(s, args.wake) except Exception as error: # noqa: BLE001 rec = {"id": s["id"], "class": "crashes", "why": f"sweep error: {error}"[:200]} rec["group"] = s["_group"] with lock: with path.open("a") as f: f.write(json.dumps(rec, default=str) + "\n") print(f"{rec['class']:20s} {s['_group']:6s} {s['id']} {rec.get('why', '')[:90]}", flush=True) with ThreadPoolExecutor(max_workers=args.workers) as pool: list(pool.map(work, chosen)) def recheck(out: Path, wake_limit: float, workers: int) -> None: """Second pass over first-pass 'doesn't start' rows: reclassify paused/broken from the Hub's own state, and give sleeping Spaces a long wake. Rows already re-checked are skipped, so the pass can be resumed.""" first = [json.loads(l) for l in (out / "census.jsonl").read_text().splitlines()] path = out / "census2.jsonl" done = {json.loads(l)["id"] for l in path.read_text().splitlines()} if path.exists() else set() todo = [r for r in first if r["class"] == "doesn't start" and r["id"] not in done] lock = threading.Lock() print(f"re-checking {len(todo)} Spaces with a {int(wake_limit)}s wake ({len(done)} already done)", flush=True) def work(r): time.sleep(random.uniform(1, 4)) try: rec = check({"id": r["id"], "likes": r.get("likes", 0), "createdAt": r.get("created", "")}, wake_limit) except Exception as error: # noqa: BLE001 rec = {"id": r["id"], "class": "crashes", "why": f"sweep error: {error}"[:200]} rec["group"] = r.get("group") rec["first_pass"] = r.get("why") with lock: with path.open("a") as f: f.write(json.dumps(rec, default=str) + "\n") print(f"{rec['class']:20s} {r['id']} {rec.get('why', '')[:90]}", flush=True) with ThreadPoolExecutor(max_workers=workers) as pool: list(pool.map(work, todo)) def merged(out: Path) -> list[dict]: """The census with second-pass results replacing first-pass ones.""" rows = {r["id"]: r for r in (json.loads(l) for l in (out / "census.jsonl").read_text().splitlines())} if (out / "census2.jsonl").exists(): for line in (out / "census2.jsonl").read_text().splitlines(): r = json.loads(line) rows[r["id"]] = r return list(rows.values()) if __name__ == "__main__": main()