"""Declarative management of the Hugging Face Jobs that run this recipe. Scheduling lives on Hugging Face rather than in an external CI system: the data, the recipe revision, and the compute that produces them stay in one place, and a job is not bound by an external runner's disk or wall-clock limits. The scheduled job executes a UV script published in this same dataset repository, so the code that produced a revision is always recoverable from the revision itself. """ from __future__ import annotations from dataclasses import dataclass from typing import Any from .config import DEFAULT_HF_REPO, validate_user_agent # The whole corpus is about six hundred documents, none of them large. A cold # run is a few minutes of polite fetching; a warm one is seconds. UPDATE_FLAVOR = "cpu-basic" BACKFILL_FLAVOR = "cpu-basic" UPDATE_TIMEOUT = "2h" BACKFILL_TIMEOUT = "4h" # The Committee publishes at 14:00 Eastern -- 18:00 UTC in summer, 19:00 in # winter -- and the minutes three weeks later at the same hour. 19:45 UTC on # every weekday clears both, and catches the minutes on whichever Wednesday # they land on as well as the statement itself. # # The second schedule is not a retry. A statement is on the site within # seconds, but the implementation note, the projections and the press # conference page appear over the following hour, and the calendar gains its # `(Released ...)` stamp for the minutes later still. A run four hours later # finds all of that on the day it happened rather than the next morning. DEFAULT_SCHEDULE = "45 19 * * 1-5" LATE_SCHEDULE = "45 23 * * 1-5" JOB_SCRIPT = "jobs/run.py" UPDATE_JOB_NAME = "fomc-events-update" LATE_JOB_NAME = "fomc-events-sweep" BACKFILL_JOB_NAME = "fomc-events-backfill" def script_url( *, repo_id: str = DEFAULT_HF_REPO, script: str = JOB_SCRIPT, revision: str = "main" ) -> str: return f"https://huggingface.co/datasets/{repo_id}/resolve/{revision}/{script}" @dataclass(frozen=True, slots=True) class JobSpec: """Everything needed to launch or schedule one run, minus the credentials.""" script: str script_url: str flavor: str timeout: str script_args: tuple[str, ...] env: dict[str, str] name: str def as_kwargs(self, *, secrets: dict[str, str]) -> dict[str, Any]: """Build the huggingface_hub call arguments. The Jobs API takes no ``name`` parameter; a job's display name is the ``name`` label. Credentials go through ``secrets`` so they are encrypted server side instead of travelling as plain environment variables. """ return { "script": self.script_url, "script_args": list(self.script_args), "flavor": self.flavor, "timeout": self.timeout, "env": dict(self.env), "secrets": secrets, "labels": {"name": self.name, "project": "fomc-events"}, } def _spec( *, repo_id: str, revision: str, flavor: str, timeout: str, args: tuple[str, ...], name: str ) -> JobSpec: return JobSpec( script=JOB_SCRIPT, script_url=script_url(repo_id=repo_id, revision=revision), flavor=flavor, timeout=timeout, script_args=args, env={"HF_DATASET_REPO": repo_id}, name=name, ) def update_spec( *, repo_id: str = DEFAULT_HF_REPO, revision: str = "main", flavor: str = UPDATE_FLAVOR, timeout: str = UPDATE_TIMEOUT, ) -> JobSpec: return _spec( repo_id=repo_id, revision=revision, flavor=flavor, timeout=timeout, args=("--mode", "update"), name=UPDATE_JOB_NAME, ) def late_spec( *, repo_id: str = DEFAULT_HF_REPO, revision: str = "main" ) -> JobSpec: """The evening sweep, for the documents that trail the statement. The implementation note and the projections are posted within the hour, the press conference page later in the afternoon, and the calendar's minutes release stamp later still. Running again at the end of the day picks those up on the day they happened. """ return _spec( repo_id=repo_id, revision=revision, flavor=UPDATE_FLAVOR, timeout=UPDATE_TIMEOUT, args=("--mode", "update"), name=LATE_JOB_NAME, ) def backfill_spec( *, repo_id: str = DEFAULT_HF_REPO, revision: str = "main", flavor: str = BACKFILL_FLAVOR, timeout: str = BACKFILL_TIMEOUT, ) -> JobSpec: """A run that re-reads every document rather than trusting the cache.""" return _spec( repo_id=repo_id, revision=revision, flavor=flavor, timeout=timeout, args=("--mode", "update", "--rebuild"), name=BACKFILL_JOB_NAME, ) def job_secrets(*, hf_token: str, user_agent: str | None = None) -> dict[str, str]: """Validate credentials locally so a misconfigured job fails before it costs money.""" if not hf_token.strip(): raise ValueError("HF_TOKEN is required to create or run a Hugging Face Job") secrets = {"HF_TOKEN": hf_token.strip()} if user_agent: secrets["FOMC_USER_AGENT"] = validate_user_agent(user_agent) return secrets def _api(token: str | None) -> Any: try: from huggingface_hub import HfApi except ImportError as error: # pragma: no cover - exercised in the job environment raise RuntimeError("install the 'publish' extra to manage Hugging Face Jobs") from error return HfApi(token=token) def _require(api: Any, method: str) -> Any: """Fail with an actionable message when the installed hub predates a Jobs API.""" function = getattr(api, method, None) if function is None: raise RuntimeError( f"the installed huggingface_hub has no {method}(); " "upgrade with: pip install -U 'huggingface-hub>=1.19'" ) return function def create_schedule( spec: JobSpec, *, schedule: str = DEFAULT_SCHEDULE, secrets: dict[str, str], namespace: str | None = None, token: str | None = None, ) -> Any: api = _api(token) return _require(api, "create_scheduled_uv_job")( schedule=schedule, namespace=namespace, **spec.as_kwargs(secrets=secrets) ) def run_once( spec: JobSpec, *, secrets: dict[str, str], namespace: str | None = None, token: str | None = None, ) -> Any: api = _api(token) return _require(api, "run_uv_job")(namespace=namespace, **spec.as_kwargs(secrets=secrets)) def list_schedules(*, namespace: str | None = None, token: str | None = None) -> list[Any]: api = _api(token) return list(_require(api, "list_scheduled_jobs")(namespace=namespace)) def inspect_schedule( scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None ) -> Any: api = _api(token) return _require(api, "inspect_scheduled_job")( scheduled_job_id=scheduled_job_id, namespace=namespace ) def delete_schedule( scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None ) -> None: api = _api(token) _require(api, "delete_scheduled_job")(scheduled_job_id=scheduled_job_id, namespace=namespace) def suspend_schedule( scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None ) -> Any: api = _api(token) return _require(api, "suspend_scheduled_job")( scheduled_job_id=scheduled_job_id, namespace=namespace ) def resume_schedule( scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None ) -> Any: api = _api(token) return _require(api, "resume_scheduled_job")( scheduled_job_id=scheduled_job_id, namespace=namespace ) __all__ = [ "BACKFILL_FLAVOR", "BACKFILL_JOB_NAME", "BACKFILL_TIMEOUT", "DEFAULT_SCHEDULE", "JOB_SCRIPT", "LATE_JOB_NAME", "LATE_SCHEDULE", "UPDATE_FLAVOR", "UPDATE_JOB_NAME", "UPDATE_TIMEOUT", "JobSpec", "backfill_spec", "create_schedule", "delete_schedule", "inspect_schedule", "job_secrets", "late_spec", "list_schedules", "resume_schedule", "run_once", "script_url", "suspend_schedule", "update_spec", ]