submit: write pending row + upload zip on successful validation
Browse filesStep 6 (E) chunk 3. Cheap-sync validation (chunk 2) now also commits
to the Hub: on success the handler uploads submissions/<id>.zip and
appends a status=pending row to results.jsonl under a process-wide
threading.Lock. Eval still stubbed, the row stays pending forever
until chunk 4 lands the background worker.
Hub-write ordering (after validation passes):
1. Upload submissions/<id>.zip. Unique path per submission, no
lock needed (HfApi handles its own commit serialization).
2. Build the pending row: metadata fields + status="pending" +
failure_reason=null + submission_blob_url + null score fields,
matching the "Pending" regime in cadgenbench-submissions/schema.md.
3. Acquire _HUB_LOCK, download current results.jsonl (treat
EntryNotFoundError as empty), append one JSON line, re-upload.
Lock held only for the RMW cycle (~1-2s), not for eval time;
concurrent submitters serialise here, not in the worker.
If step 1 fails the submitter sees a clean "Hub upload failed"
rejection. If step 3 fails the zip is left orphaned in submissions/
and the submitter sees a clean "Hub write failed" rejection; an
orphan-zip sweep is a future-chunk concern (covered by the eventual
stuck-pending recovery in chunk 6 plus a manual sweep if needed).
leaderboard.py:
- Add `status` as the first leaderboard column so pending rows are
visually distinguishable from completed ones.
- Backfill `status` to "completed" in-memory for legacy rows
written before the schema bump (the three baseline seeds);
populated rows are completed by definition.
cadgenbench_version and cadgenbench_data_revision get pinned on the
pending row at submit time so the row is meaningful even if the
worker never runs and chunk 6 ends up flipping it to failed.
data_revision is the short sha from HfApi().dataset_info; cached
per-process and falls back to "unknown" on Hub flake (it's a
metadata field, not worth failing a submit over).
HF_DATA_REPO and HF_SUBMISSIONS_REPO are imported from leaderboard.py
for now; pulling them into a shared config module is a worthwhile
refactor once submit.py grows again in chunks 4+.
Files changed (2)
- leaderboard.py+8
- submit.py+200-10
22 unmodified lines23242526272851 unmodified lines80818283848522 unmodified linesLOCAL_RESULTS_PATH = Path(__file__).parent / "results.jsonl"LEADERBOARD_COLS = ["submission_name","submitter_name","aggregate_score",51 unmodified linesif not rows:return pd.DataFrame(columns=LEADERBOARD_COLS)df = pd.DataFrame(rows)cols = [c for c in LEADERBOARD_COLS if c in df.columns]df = (df[cols]22 unmodified lines2324252627282951 unmodified lines8182838485868788899091929322 unmodified linesLOCAL_RESULTS_PATH = Path(__file__).parent / "results.jsonl"LEADERBOARD_COLS = ["status","submission_name","submitter_name","aggregate_score",51 unmodified linesif not rows:return pd.DataFrame(columns=LEADERBOARD_COLS)df = pd.DataFrame(rows)# Backfill `status` for legacy rows written before the schema bump# (the three baseline seed rows). They all have populated score# fields, so "completed" is the correct retrofit.if "status" not in df.columns:df["status"] = "completed"else:df["status"] = df["status"].fillna("completed")cols = [c for c in LEADERBOARD_COLS if c in df.columns]df = (df[cols]
1234567891012 unmodified lines232425262728293031323334353637383940414 unmodified lines46474849505152535455565735 unmodified lines93949596979899100101102103104154 unmodified lines259260261"""Submit-tab handler for the CADGenBench leaderboard Space.Step 6 (E) chunk 2: the cheap-sync validation pipeline. The handlervalidates the upload and returns a placeholder message describing thesubmission it would have queued. No Hub writes, no eval kick-off, nobackground work. The async write + worker thread land in later chunksof Step 6 (E); see ``space-setup/step-6e-async.md``.Validation gates, in order:12 unmodified linesgeometry. Per-fixture validity (watertight, manifold, etc) is*not* checked here, that's the evaluator's job and contributes tothe per-fixture score; this gate only rejects "not actually STEP"."""from __future__ import annotationsimport jsonimport reimport tempfileimport zipfilefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Anyfrom cadgenbench.common.paths import data_inputs_dirfrom cadgenbench.common.validity import parse_stepNOTES_MAX_CHARS = 500REQUIRED_META_KEYS: tuple[str, ...] = (4 unmodified lines"agree_to_publish",)SUBMISSION_ID_SLUG_MAX = 40class _ValidationError(Exception):"""Internal sentinel that maps to a user-facing rejection message."""def handle_submit(zip_file,submission_name: str, # noqa: ARG001 - kept for UI compat; meta.json wins35 unmodified linessubmission_id = _mint_submission_id(meta["submitter_name"], meta["submission_name"])return (f"**Validation OK.** Would queue submission `{submission_id}` "f"(submitter: `{meta['submitter_name']}`, system: "f"`{meta['submission_name']}`, {len(fixture_names)} fixtures).\n\n"f"_Chunk 2 of Step 6 (E): validation only. Hub write + eval "f"kick-off land in the next chunk._")154 unmodified lines"""Filesystem-safe slug. Lowercase, ``[a-z0-9-]``, collapsed dashes."""cleaned = re.sub(r"[^A-Za-z0-9]+", "-", s).strip("-").lower()return cleaned[:SUBMISSION_ID_SLUG_MAX] or "unnamed"123456789101112 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162634 unmodified lines6869707172737475767778798081828384858687888990919293949596979835 unmodified lines134135136137138139140141142143144145146147148149150151152154 unmodified lines307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451"""Submit-tab handler for the CADGenBench leaderboard Space.Step 6 (E) chunks 2 + 3: cheap-sync validation pipeline + pending-rowwrite + zip upload. The handler validates the upload, uploads thezip to ``submissions/<id>.zip``, appends a ``status: pending`` row to``results.jsonl`` (under a process-wide lock), and returnsimmediately. No eval and no worker yet, the row stays pendingforever until later chunks add the background thread.Validation gates, in order:12 unmodified linesgeometry. Per-fixture validity (watertight, manifold, etc) is*not* checked here, that's the evaluator's job and contributes tothe per-fixture score; this gate only rejects "not actually STEP".Hub-write ordering (after validation passes):1. Upload ``submissions/<id>.zip``. Unique path per submission, nolock needed.2. Build pending row (metadata + null scores + ``submission_blob_url``).3. Acquire ``_HUB_LOCK``; download current ``results.jsonl`` (orstart empty); append the pending row; re-upload.If step 1 fails the user sees a clean rejection. If step 3 fails thezip is left orphaned in ``submissions/`` and the user sees a cleanrejection; an orphan-zip sweep is a future-chunk concern."""from __future__ import annotationsimport jsonimport loggingimport reimport tempfileimport threadingimport zipfilefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Anyimport cadgenbenchfrom cadgenbench.common.paths import data_inputs_dirfrom cadgenbench.common.validity import parse_stepfrom huggingface_hub import HfApifrom huggingface_hub.errors import EntryNotFoundErrorfrom leaderboard import HF_DATA_REPO, HF_SUBMISSIONS_REPOlogger = logging.getLogger(__name__)NOTES_MAX_CHARS = 500REQUIRED_META_KEYS: tuple[str, ...] = (4 unmodified lines"agree_to_publish",)SUBMISSION_ID_SLUG_MAX = 40RESULTS_FILENAME = "results.jsonl"SUBMISSIONS_DIR = "submissions"DATA_REV_SHORT_LEN = 12# One HfApi client per process. HF_TOKEN is picked up from the env at# construction time and reused for every call._HF_API = HfApi()# Process-wide lock guarding the read-modify-write of results.jsonl.# The Space is single-process so a threading.Lock is sufficient; held# only for the duration of the RMW cycle (~1-2s), not for eval time._HUB_LOCK = threading.Lock()# Lazily-resolved cadgenbench-data revision, cached per process._DATA_REVISION: str | None = Noneclass _ValidationError(Exception):"""Internal sentinel that maps to a user-facing rejection message."""class _HubWriteError(Exception):"""Raised when a Hub upload fails after validation succeeded."""def handle_submit(zip_file,submission_name: str, # noqa: ARG001 - kept for UI compat; meta.json wins35 unmodified linessubmission_id = _mint_submission_id(meta["submitter_name"], meta["submission_name"])try:blob_url = _upload_submission_zip(submission_id, zip_path)row = _build_pending_row(submission_id, meta, fixture_names, blob_url)_append_pending_row(row)except _HubWriteError as e:return f"**Submission rejected.** {e}"return (f"**Queued.** Submission `{submission_id}` has been accepted and a "f"`pending` row added to the leaderboard (submitter: "f"`{meta['submitter_name']}`, system: `{meta['submission_name']}`, "f"{len(fixture_names)} fixtures). Evaluation will populate the "f"score columns once the worker lands in a later chunk.")154 unmodified lines"""Filesystem-safe slug. Lowercase, ``[a-z0-9-]``, collapsed dashes."""cleaned = re.sub(r"[^A-Za-z0-9]+", "-", s).strip("-").lower()return cleaned[:SUBMISSION_ID_SLUG_MAX] or "unnamed"def _upload_submission_zip(submission_id: str, zip_path: Path) -> str:"""Upload the submission zip to ``submissions/<id>.zip``.Returns the canonical Hub blob URL on success. Raises:class:`_HubWriteError` with a short user-facing reason onfailure."""repo_path = f"{SUBMISSIONS_DIR}/{submission_id}.zip"try:_HF_API.upload_file(path_or_fileobj=str(zip_path),path_in_repo=repo_path,repo_id=HF_SUBMISSIONS_REPO,repo_type="dataset",commit_message=f"add submission zip for {submission_id}",)except Exception as e: # noqa: BLE001 - Hub API surface is broadlogger.exception("Failed to upload submission zip %s", submission_id)raise _HubWriteError(f"Server-side error uploading submission zip "f"({type(e).__name__}: {e}). Please try again later.") from ereturn (f"https://huggingface.co/datasets/{HF_SUBMISSIONS_REPO}"f"/resolve/main/{repo_path}")def _build_pending_row(submission_id: str,meta: dict[str, Any],fixture_names: set[str], # noqa: ARG001 - kept for future per-fixture pre-fillblob_url: str,) -> dict[str, Any]:"""Construct the JSON row written for a freshly-queued submission.Mirrors the pending regime in ``cadgenbench-submissions/schema.md``:metadata + ``status: pending`` + ``submission_blob_url``; everyscore-shaped field is ``null`` until the worker flips the row."""return {"submission_id": submission_id,"status": "pending","failure_reason": None,"submitter_name": meta["submitter_name"],"submission_name": meta["submission_name"],"agent_url": meta["agent_url"],"notes": meta["notes"],"submitted_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),"cadgenbench_version": cadgenbench.__version__,"cadgenbench_data_revision": _resolve_data_revision(),"validity_rate": None,"aggregate_score": None,"score_by_task_type": None,"per_task_scores": None,"per_fixture_scores": None,"per_fixture_breakdown": None,"submission_blob_url": blob_url,}def _append_pending_row(row: dict[str, Any]) -> None:"""Append a pending row to ``results.jsonl`` on the Hub under the lock.Read-modify-write: download the current file (or treat as empty ifit doesn't exist yet), append one line, re-upload. The lock isheld only for the duration of this cycle (~1-2s), not for anybackground eval; concurrent submitters serialise here, not on theeval pipeline."""with _HUB_LOCK:try:existing = _download_results_jsonl()except Exception as e: # noqa: BLE001 - Hub API surface is broadlogger.exception("Failed to download results.jsonl for append")raise _HubWriteError(f"Server-side error reading the submissions table "f"({type(e).__name__}: {e}). Please try again later.") from eline = json.dumps(row, ensure_ascii=False)new_body = existing + line + "\n" if existing else line + "\n"try:_HF_API.upload_file(path_or_fileobj=new_body.encode("utf-8"),path_in_repo=RESULTS_FILENAME,repo_id=HF_SUBMISSIONS_REPO,repo_type="dataset",commit_message=(f"add pending row for {row['submission_id']}"),)except Exception as e: # noqa: BLE001 - Hub API surface is broadlogger.exception("Failed to upload appended results.jsonl for %s",row["submission_id"],)raise _HubWriteError(f"Server-side error writing the submissions table "f"({type(e).__name__}: {e}). The submission zip was "f"uploaded but the row was not; please try again later.") from edef _download_results_jsonl() -> str:"""Fetch the current ``results.jsonl`` body as text, or ``""`` if absent."""from huggingface_hub import hf_hub_downloadtry:path = hf_hub_download(repo_id=HF_SUBMISSIONS_REPO,filename=RESULTS_FILENAME,repo_type="dataset",force_download=True,)except EntryNotFoundError:return ""return Path(path).read_text(encoding="utf-8")def _resolve_data_revision() -> str:"""Return a short sha for the cadgenbench-data dataset, cached per process.Falls back to ``"unknown"`` on Hub errors so a flaky network can'tblock a submission over a metadata field."""global _DATA_REVISIONif _DATA_REVISION is not None:return _DATA_REVISIONtry:info = _HF_API.dataset_info(HF_DATA_REPO)_DATA_REVISION = (info.sha or "unknown")[:DATA_REV_SHORT_LEN]except Exception as e: # noqa: BLE001 - metadata only, don't fail the submitlogger.warning("Failed to resolve cadgenbench-data revision (%s: %s)",type(e).__name__, e,)_DATA_REVISION = "unknown"return _DATA_REVISION