"""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 # The work is downloading the sibling datasets and four hundred settlement # archives, then a few minutes of grouping. Memory is modest; bandwidth is not. UPDATE_FLAVOR = "cpu-upgrade" BACKFILL_FLAVOR = "cpu-upgrade" UPDATE_TIMEOUT = "3h" BACKFILL_TIMEOUT = "4h" # Monday 08:10 UTC, an hour after the fundamentals rebuild: this dataset is # derived entirely from that one, and reading last week's revision would # publish corporate actions that lag their own source. DEFAULT_SCHEDULE = "10 8 * * 1" # One self-contained UV script serves both modes: a Job downloads a single file. JOB_SCRIPT = "jobs/run.py" UPDATE_JOB_NAME = "corporate-actions-update" BACKFILL_JOB_NAME = "corporate-actions-rebuild" 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": "insider-trading"}, } def update_spec( *, repo_id: str = DEFAULT_HF_REPO, revision: str = "main", flavor: str = UPDATE_FLAVOR, timeout: str = UPDATE_TIMEOUT, ) -> JobSpec: return JobSpec( script=JOB_SCRIPT, script_url=script_url(repo_id=repo_id, revision=revision), flavor=flavor, timeout=timeout, script_args=("--mode", "update"), env={"HF_DATASET_REPO": repo_id}, name=UPDATE_JOB_NAME, ) def backfill_spec( *, repo_id: str = DEFAULT_HF_REPO, revision: str = "main", start: str | None = None, end: str | None = None, flavor: str = BACKFILL_FLAVOR, timeout: str = BACKFILL_TIMEOUT, ) -> JobSpec: args = ["--mode", "build"] _ = (start, end) return JobSpec( script=JOB_SCRIPT, script_url=script_url(repo_id=repo_id, revision=revision), flavor=flavor, timeout=timeout, script_args=tuple(args), env={"HF_DATASET_REPO": repo_id}, name=BACKFILL_JOB_NAME, ) def job_secrets(*, hf_token: str) -> dict[str, str]: """Credentials the Job needs, and only those. No SEC User-Agent here: this dataset fetches nothing from SEC. It is derived entirely from a sibling dataset on the Hub, so the only secret it can use is the token that reads and writes it. """ if not hf_token: raise ValueError("an HF token is required to run or schedule a Job") return {"HF_TOKEN": hf_token} 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_TIMEOUT", "DEFAULT_SCHEDULE", "JOB_SCRIPT", "UPDATE_FLAVOR", "UPDATE_TIMEOUT", "JobSpec", "backfill_spec", "create_schedule", "delete_schedule", "inspect_schedule", "job_secrets", "list_schedules", "resume_schedule", "run_once", "script_url", "suspend_schedule", "update_spec", ]