j-chim commited on
Commit
2f2b4d7
Β·
verified Β·
1 Parent(s): 1ac9e85

Deploy eval-entity-registry service

Browse files
src/eval_entity_registry/services/hub_stats.py CHANGED
@@ -21,44 +21,36 @@ import threading
21
  from datetime import datetime, date
22
  from typing import Optional
23
 
24
- # Live-lookup source for the deployed Space's `HubStatsClient` ONLY. This is
25
- # the HF parquet-converter endpoint, which answers 400 for several minutes after
26
- # ANY commit to the upstream dataset (daily, ~13:18–13:36 UTC) while the
27
- # dataset-viewer rebuilds `refs/convert/parquet`. The bulk scripts (refresh /
28
- # index / freeze) therefore do NOT read it: they download a pinned snapshot of
29
- # `main/models.parquet` via `services/hub_stats_snapshot.py` (same bytes; see
30
- # specs/hub-stats-snapshot-fetch.md). The client tolerates the window because a
31
- # lookup failure degrades to "no enrichment".
32
- PARQUET_URL = (
33
- "https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet"
34
- )
35
 
36
  # Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats
37
- # parquet, every
38
- # hub-stats query (bulk refresh + live HubStatsClient lookup) reads that file
39
- # instead of streaming the live URL. CI / the deployed Space leave the env unset
40
- # and keep the live path. The env var is read at call time (not import time) so
41
  # tests can set/unset it per-test without reimporting the module.
42
  HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"
43
 
44
 
45
- def resolve_parquet_source(parquet_url: str = PARQUET_URL) -> str:
46
- """Return the parquet source DuckDB should `read_parquet()` from.
47
-
48
- Prefers the local file at `$HUB_STATS_LOCAL_PARQUET` when that env var is
49
- set and the file exists (offline mode); otherwise the passed-in live URL.
50
- A set-but-missing path falls through to the live URL so a stale env var
51
- never silently breaks the live path."""
52
  local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)
53
  if local and os.path.exists(local):
54
  return local
55
- return parquet_url
56
 
57
 
58
  def is_local_parquet() -> bool:
59
  """True when the offline local-parquet read path is active."""
60
- local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)
61
- return bool(local and os.path.exists(local))
62
 
63
  # Columns the queries fetch. Centralized so the bulk and lookup paths
64
  # parse the same row shape.
@@ -405,28 +397,35 @@ def extract_base_models(base_models) -> list[dict]:
405
  class HubStatsClient:
406
  """Single-id lookup against the hub-stats parquet via DuckDB.
407
 
408
- Materializes the remote parquet into a local DuckDB table on first
409
- use, then serves all subsequent lookups against the local copy.
410
- Trade-off: one bulk fetch (large but a single HTTP transaction)
411
- instead of N per-id range-fetch queries (small but rate-limit-prone
412
- when N is in the thousands β€” `huggingface.co` 429s aggressively on
413
- the parquet API even with auth, and DuckDB's range-fetch pattern
414
- counts as multiple HTTP HEAD/GET requests per logical query).
415
-
416
- On bulk-fetch failure, falls back to per-id remote queries (older
417
- behaviour) so the client degrades gracefully rather than going
418
- silent. Per-id fallback retains the same in-process cache.
419
-
420
- Failure mode: any DuckDB error (network down, parquet schema drift,
421
- etc.) returns None from `lookup()` and is logged. Callers must
 
 
 
 
 
 
 
 
 
422
  handle None as "no enrichment data available" β€” never raise."""
423
 
424
- def __init__(self, parquet_url: str = PARQUET_URL) -> None:
425
- # Resolve the offline local-parquet path here (at construction) AND
426
- # again at query time β€” the env-aware `resolve_parquet_source` makes the
427
- # offline switch transparent to all the `read_parquet('{self.parquet_url}')`
428
- # call sites below without touching their SQL.
429
- self.parquet_url = resolve_parquet_source(parquet_url)
430
  self._con = None
431
  self._local_table_ready: bool = False
432
  self._local_table_failed: bool = False
@@ -440,25 +439,29 @@ class HubStatsClient:
440
  # the duckdb import cost.
441
  import os
442
  import duckdb
 
 
 
 
 
 
 
 
 
 
443
  con = duckdb.connect()
444
  # Reading a LOCAL parquet needs no httpfs / HF auth β€” skip the network
445
  # extension install so the offline path works with no connectivity.
446
- if is_local_parquet():
447
  self._con = con
448
  return con
449
  con.execute("INSTALL httpfs; LOAD httpfs;")
450
- # Authenticate parquet fetches when HF_TOKEN is in the environment
451
- # (typical on the deployed Space). Unauth limit is 500 req/5min;
452
- # one DuckDB read_parquet against the remote file streams via
453
- # several range requests and a sync that auto-creates many drafts
454
- # can brush that ceiling. With auth the ceiling is ~30k/5min.
455
- hf_token = os.environ.get("HF_TOKEN")
456
  if hf_token:
457
  escaped = hf_token.replace("'", "''")
458
- con.execute(
459
- f"CREATE SECRET hf_auth (TYPE HTTP, BEARER_TOKEN '{escaped}', "
460
- f"SCOPE 'https://huggingface.co');"
461
- )
462
  self._con = con
463
  return con
464
 
 
21
  from datetime import datetime, date
22
  from typing import Optional
23
 
24
+ # Where hub-stats bytes come from β€” NEVER the HF parquet-converter endpoint
25
+ # (the `/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet` URL), which
26
+ # answers 400 for several minutes after ANY commit to the upstream dataset
27
+ # (daily, ~13:18–13:36 UTC) while the dataset-viewer rebuilds
28
+ # `refs/convert/parquet`. Every reader pins a commit sha of `main/models.parquet`
29
+ # (same bytes) via `services/hub_stats_snapshot.py`: the bulk scripts download
30
+ # it; the live `HubStatsClient` below range-reads the pinned `hf://` path. See
31
+ # specs/hub-stats-snapshot-fetch.md.
 
 
 
32
 
33
  # Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats
34
+ # parquet, every hub-stats query (bulk refresh + live HubStatsClient lookup)
35
+ # reads that file instead of the pinned remote snapshot. CI / the deployed Space
36
+ # leave the env unset. The env var is read at call time (not import time) so
 
37
  # tests can set/unset it per-test without reimporting the module.
38
  HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"
39
 
40
 
41
+ def local_parquet_path() -> Optional[str]:
42
+ """The offline local parquet path when `$HUB_STATS_LOCAL_PARQUET` is set
43
+ AND the file exists; else None. A set-but-missing path is ignored so a
44
+ stale env var never silently breaks the live path."""
 
 
 
45
  local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)
46
  if local and os.path.exists(local):
47
  return local
48
+ return None
49
 
50
 
51
  def is_local_parquet() -> bool:
52
  """True when the offline local-parquet read path is active."""
53
+ return local_parquet_path() is not None
 
54
 
55
  # Columns the queries fetch. Centralized so the bulk and lookup paths
56
  # parse the same row shape.
 
397
  class HubStatsClient:
398
  """Single-id lookup against the hub-stats parquet via DuckDB.
399
 
400
+ Used only by draft enrichment (`_auto_create_entity`), i.e. in WRITE
401
+ mode β€” a `sync` run. The deployed read-only Space never instantiates it
402
+ (read-only resolves confirm HF ids against the published
403
+ `hub_stats_index` table instead).
404
+
405
+ Source: a PINNED commit of `cfahlgren1/hub-stats` `main/models.parquet`,
406
+ resolved on first use (`hf://datasets/<repo>@<sha>/models.parquet`), or
407
+ the local file at `$HUB_STATS_LOCAL_PARQUET`. Never the HF
408
+ parquet-converter endpoint (400s after every upstream commit β€” see the
409
+ module comment). Pinning means a mid-sync upstream commit cannot swap
410
+ the file under the bulk load.
411
+
412
+ Materializes the parquet into a local DuckDB table on first use, then
413
+ serves all subsequent lookups against the local copy. Trade-off: one
414
+ bulk fetch instead of N per-id range-fetch queries (rate-limit-prone when
415
+ N is in the thousands; the Hub's `ratelimit-policy` header gives the
416
+ per-bucket limits). On bulk-fetch failure, falls back to per-id remote
417
+ queries against the same pinned source so the client degrades gracefully
418
+ rather than going silent. Per-id fallback retains the same in-process
419
+ cache.
420
+
421
+ Failure mode: any DuckDB / network error (incl. failing to resolve the
422
+ snapshot) returns None from `lookup()` and is logged. Callers must
423
  handle None as "no enrichment data available" β€” never raise."""
424
 
425
+ def __init__(self, parquet_url: Optional[str] = None) -> None:
426
+ # Explicit source > offline local file > (lazily, on first use) the
427
+ # pinned remote snapshot. Construction never touches the network.
428
+ self.parquet_url: Optional[str] = parquet_url or local_parquet_path()
 
 
429
  self._con = None
430
  self._local_table_ready: bool = False
431
  self._local_table_failed: bool = False
 
439
  # the duckdb import cost.
440
  import os
441
  import duckdb
442
+ from eval_entity_registry.services.hub_stats_snapshot import (
443
+ hf_source,
444
+ is_remote_source,
445
+ resolve_snapshot,
446
+ )
447
+
448
+ hf_token = os.environ.get("HF_TOKEN")
449
+ if self.parquet_url is None:
450
+ # One resolver-bucket HEAD; pins the sha for this client's lifetime.
451
+ self.parquet_url = hf_source(resolve_snapshot(token=hf_token))
452
  con = duckdb.connect()
453
  # Reading a LOCAL parquet needs no httpfs / HF auth β€” skip the network
454
  # extension install so the offline path works with no connectivity.
455
+ if not is_remote_source(self.parquet_url):
456
  self._con = con
457
  return con
458
  con.execute("INSTALL httpfs; LOAD httpfs;")
459
+ # Authenticate the `hf://` reads when HF_TOKEN is in the environment
460
+ # (typical on a sync host): DuckDB's HUGGINGFACE secret type sends the
461
+ # bearer to the resolve endpoint and not to the CDN redirect target.
 
 
 
462
  if hf_token:
463
  escaped = hf_token.replace("'", "''")
464
+ con.execute(f"CREATE SECRET hf_auth (TYPE HUGGINGFACE, TOKEN '{escaped}');")
 
 
 
465
  self._con = con
466
  return con
467
 
src/eval_entity_registry/services/hub_stats_snapshot.py CHANGED
@@ -1,19 +1,20 @@
1
  """Pinned, local snapshot of `cfahlgren1/hub-stats` for the bulk scripts.
2
 
3
  Why this exists (see specs/hub-stats-snapshot-fetch.md): the HF parquet-converter
4
- endpoint (`/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet`, the
5
- `PARQUET_URL` the live `HubStatsClient` still uses) answers 400 for several
6
- minutes after *any* commit to the upstream dataset β€” the dataset-viewer deletes
7
- and rebuilds the whole `refs/convert/parquet` branch. Upstream commits six files
8
- every day around 13:18–13:36 UTC, and the crons regularly fired inside that
9
- window. The raw `main/models.parquet` is byte-identical to the converted file
10
- and lives on a path the viewer never touches.
11
-
12
- The scripts therefore (1) resolve the dataset's current commit sha + the file's
13
  content hash in ONE resolver-bucket request, (2) short-circuit on an unchanged
14
  hash, else (3) `hf_hub_download` the file at that pinned sha (one resumable,
15
- hash-verified stream) and query it locally. Nothing here is used by the
16
- deployed Space.
 
17
  """
18
  from __future__ import annotations
19
 
 
1
  """Pinned, local snapshot of `cfahlgren1/hub-stats` for the bulk scripts.
2
 
3
  Why this exists (see specs/hub-stats-snapshot-fetch.md): the HF parquet-converter
4
+ endpoint (`/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet`) answers
5
+ 400 for several minutes after *any* commit to the upstream dataset β€” the
6
+ dataset-viewer deletes and rebuilds the whole `refs/convert/parquet` branch.
7
+ Upstream commits six files every day around 13:18–13:36 UTC, and the crons
8
+ regularly fired inside that window. The raw `main/models.parquet` is
9
+ byte-identical to the converted file and lives on a path the viewer never
10
+ touches.
11
+
12
+ The bulk scripts (1) resolve the dataset's current commit sha + the file's
13
  content hash in ONE resolver-bucket request, (2) short-circuit on an unchanged
14
  hash, else (3) `hf_hub_download` the file at that pinned sha (one resumable,
15
+ hash-verified stream) and query it locally. The write-mode live
16
+ `HubStatsClient` (draft enrichment during `sync`) resolves the same pinned sha
17
+ and range-reads `hf_source(snap)` instead of downloading.
18
  """
19
  from __future__ import annotations
20