feat(Day 7): ShardRouter multi-repo support — admin shard via dataset repo
Browse filesFree-tier 1GB LFS quota on the Space repo is exhausted at 10 shards.
Workaround without paying for Pro: spill the remaining shards into
separate HF Dataset repo(s), each with its own 1GB quota.
ShardRouter changes (~120 lines):
- Accepts `extra_repos` arg or TAU_RAG_EXTRA_SHARDS_REPOS env (CSV)
- At init: for each extra repo, snapshot_download to a local cache
(TAU_RAG_EXTRA_SHARDS_CACHE, default /tmp/legal_eye_extra_shards)
- Scans all dirs (primary + extras); primary wins on conflict
- _shard_dir maps shard_name → root, _load_shard uses that mapping
- New status field 'shards_dirs' shows all sources
Dockerfile:
- TAU_RAG_EXTRA_SHARDS_REPOS=Legal-i/legal-eye-shards-extra
- TAU_RAG_EXTRA_SHARDS_CACHE=/tmp/legal_eye_extra_shards
Verified locally: download of legal-eye-shards-extra (169MB / 5 files)
in 7.9s, router scans both dirs, reports '11 shards across 2 dir(s)'.
Next: criminal also goes to legal-eye-shards-extra once it finishes
building (~15min).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Dockerfile +2 -0
- tau_rag/retrieve/shard_router.py +151 -21
|
@@ -54,6 +54,8 @@ ENV PYTHONPATH=/app \
|
|
| 54 |
TAU_RAG_AUTOLOAD_CORPUS=1 \
|
| 55 |
TAU_RAG_AUTOLOAD_CORPUS_PATH=/app/tau_rag/runtime/uploads/corpus_paid.jsonl \
|
| 56 |
TAU_RAG_TIER=paid \
|
|
|
|
|
|
|
| 57 |
TAU_RAG_CLUSTER_AUGMENT=1 \
|
| 58 |
TAU_RAG_AUTH_REQUIRED=true \
|
| 59 |
TAU_RAG_RATE_LIMIT_QPS=3 \
|
|
|
|
| 54 |
TAU_RAG_AUTOLOAD_CORPUS=1 \
|
| 55 |
TAU_RAG_AUTOLOAD_CORPUS_PATH=/app/tau_rag/runtime/uploads/corpus_paid.jsonl \
|
| 56 |
TAU_RAG_TIER=paid \
|
| 57 |
+
TAU_RAG_EXTRA_SHARDS_REPOS=Legal-i/legal-eye-shards-extra \
|
| 58 |
+
TAU_RAG_EXTRA_SHARDS_CACHE=/tmp/legal_eye_extra_shards \
|
| 59 |
TAU_RAG_CLUSTER_AUGMENT=1 \
|
| 60 |
TAU_RAG_AUTH_REQUIRED=true \
|
| 61 |
TAU_RAG_RATE_LIMIT_QPS=3 \
|
|
@@ -51,6 +51,23 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
| 51 |
_DEFAULT_SHARDS_DIR = (Path(__file__).resolve().parent.parent
|
| 52 |
/ "runtime" / "shards")
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# LRU cache size — how many shard pipelines to keep in memory at once.
|
| 55 |
# Each shard ≈ 30-900MB depending on size. Default 4 = ~1-2GB typical.
|
| 56 |
_DEFAULT_MAX_IN_MEMORY = int(os.environ.get(
|
|
@@ -71,7 +88,9 @@ class ShardRouter:
|
|
| 71 |
|
| 72 |
def __init__(self,
|
| 73 |
shards_dir: Optional[Path] = None,
|
| 74 |
-
max_in_memory: int = _DEFAULT_MAX_IN_MEMORY
|
|
|
|
|
|
|
| 75 |
self.shards_dir = Path(shards_dir or _DEFAULT_SHARDS_DIR)
|
| 76 |
self.max_in_memory = max_in_memory
|
| 77 |
self._lock = threading.RLock()
|
|
@@ -83,21 +102,102 @@ class ShardRouter:
|
|
| 83 |
# Stats — for /v1/system/shards endpoint
|
| 84 |
self._stats: Dict[str, Dict[str, int]] = {}
|
| 85 |
|
| 86 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
self.manifest: Optional[dict] = None
|
| 88 |
self.available_shards: List[str] = []
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
def is_available(self) -> bool:
|
| 103 |
"""Does the router have any usable shards?"""
|
|
@@ -187,16 +287,41 @@ class ShardRouter:
|
|
| 187 |
cfg.retrieval.enabled = list(_SHARD_RETRIEVERS)
|
| 188 |
return Pipeline.from_config(cfg)
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
def _load_state_into(self, pipe, state_dir: Path) -> None:
|
| 191 |
"""Pickle.load each retriever state file into the pipeline."""
|
|
|
|
| 192 |
named = getattr(pipe.retrievers, "_retrievers", None) or {}
|
| 193 |
if not named:
|
| 194 |
for r in getattr(pipe.retrievers, "retrievers", []):
|
| 195 |
named[getattr(r, "name", type(r).__name__)] = r
|
| 196 |
|
| 197 |
for name, retriever in named.items():
|
| 198 |
-
|
| 199 |
-
if
|
| 200 |
continue
|
| 201 |
# Unwrap RefAware-style wrappers to reach the inner retriever
|
| 202 |
inner = retriever
|
|
@@ -209,7 +334,7 @@ class ShardRouter:
|
|
| 209 |
if not hasattr(inner, "load_state_dict"):
|
| 210 |
continue
|
| 211 |
try:
|
| 212 |
-
with gzip.open(
|
| 213 |
state = pickle.load(f)
|
| 214 |
inner.load_state_dict(state)
|
| 215 |
except Exception as e:
|
|
@@ -217,7 +342,10 @@ class ShardRouter:
|
|
| 217 |
|
| 218 |
def _load_shard(self, shard_name: str):
|
| 219 |
"""Load a shard's pipeline (or return cached). Evicts LRU on
|
| 220 |
-
budget overflow. Thread-safe.
|
|
|
|
|
|
|
|
|
|
| 221 |
with self._lock:
|
| 222 |
if shard_name in self._cache:
|
| 223 |
# Move to MRU end
|
|
@@ -227,12 +355,14 @@ class ShardRouter:
|
|
| 227 |
self._stats[shard_name].get("hits", 0) + 1
|
| 228 |
return self._cache[shard_name]
|
| 229 |
|
| 230 |
-
# Cold load
|
| 231 |
t0 = time.time()
|
| 232 |
-
|
|
|
|
| 233 |
if not state_dir.exists():
|
| 234 |
raise FileNotFoundError(
|
| 235 |
-
f"shard {shard_name} has no retriever_state"
|
|
|
|
| 236 |
pipe = self._build_pipeline()
|
| 237 |
self._load_state_into(pipe, state_dir)
|
| 238 |
load_ms = int((time.time() - t0) * 1000)
|
|
|
|
| 51 |
_DEFAULT_SHARDS_DIR = (Path(__file__).resolve().parent.parent
|
| 52 |
/ "runtime" / "shards")
|
| 53 |
|
| 54 |
+
# v2.96.8 (Day 7) — Multi-repo support. When the free-tier 1GB LFS
|
| 55 |
+
# quota on the main HF Space repo is exhausted, additional shards
|
| 56 |
+
# live in separate HF Dataset repos (e.g. Legal-i/legal-eye-shards-
|
| 57 |
+
# extra). The router scans multiple shard dirs at startup. The
|
| 58 |
+
# secondary dataset(s) are downloaded once at boot via
|
| 59 |
+
# huggingface_hub.snapshot_download and cached locally.
|
| 60 |
+
#
|
| 61 |
+
# Configured via env:
|
| 62 |
+
# TAU_RAG_EXTRA_SHARDS_REPOS comma-separated list of HF dataset
|
| 63 |
+
# repo IDs to download (e.g.
|
| 64 |
+
# "Legal-i/legal-eye-shards-extra")
|
| 65 |
+
# TAU_RAG_EXTRA_SHARDS_CACHE local dir to cache downloads (default
|
| 66 |
+
# /tmp/extra_shards)
|
| 67 |
+
_EXTRA_REPOS_ENV = "TAU_RAG_EXTRA_SHARDS_REPOS"
|
| 68 |
+
_EXTRA_CACHE_ENV = "TAU_RAG_EXTRA_SHARDS_CACHE"
|
| 69 |
+
_EXTRA_CACHE_DEFAULT = "/tmp/legal_eye_extra_shards"
|
| 70 |
+
|
| 71 |
# LRU cache size — how many shard pipelines to keep in memory at once.
|
| 72 |
# Each shard ≈ 30-900MB depending on size. Default 4 = ~1-2GB typical.
|
| 73 |
_DEFAULT_MAX_IN_MEMORY = int(os.environ.get(
|
|
|
|
| 88 |
|
| 89 |
def __init__(self,
|
| 90 |
shards_dir: Optional[Path] = None,
|
| 91 |
+
max_in_memory: int = _DEFAULT_MAX_IN_MEMORY,
|
| 92 |
+
extra_repos: Optional[List[str]] = None):
|
| 93 |
+
# Primary shards dir (typically the Space's bundled shards)
|
| 94 |
self.shards_dir = Path(shards_dir or _DEFAULT_SHARDS_DIR)
|
| 95 |
self.max_in_memory = max_in_memory
|
| 96 |
self._lock = threading.RLock()
|
|
|
|
| 102 |
# Stats — for /v1/system/shards endpoint
|
| 103 |
self._stats: Dict[str, Dict[str, int]] = {}
|
| 104 |
|
| 105 |
+
# Multi-dir support: list of (dir, source_label) pairs scanned
|
| 106 |
+
# in order. The first dir is the primary (bundled shards); any
|
| 107 |
+
# additional dirs come from HF Dataset repos downloaded at boot.
|
| 108 |
+
self._shards_dirs: List[tuple] = [(self.shards_dir, "primary")]
|
| 109 |
+
|
| 110 |
+
# Bootstrap secondary repos before scanning, so their shards
|
| 111 |
+
# are visible in available_shards from the get-go.
|
| 112 |
+
repos_env = (os.environ.get(_EXTRA_REPOS_ENV) or "").strip()
|
| 113 |
+
repos_list = extra_repos if extra_repos else (
|
| 114 |
+
[r.strip() for r in repos_env.split(",") if r.strip()]
|
| 115 |
+
if repos_env else []
|
| 116 |
+
)
|
| 117 |
+
if repos_list:
|
| 118 |
+
cache_root = Path(os.environ.get(_EXTRA_CACHE_ENV,
|
| 119 |
+
_EXTRA_CACHE_DEFAULT))
|
| 120 |
+
for repo_id in repos_list:
|
| 121 |
+
downloaded = self._download_extra_repo(repo_id, cache_root)
|
| 122 |
+
if downloaded:
|
| 123 |
+
self._shards_dirs.append((downloaded, repo_id))
|
| 124 |
+
|
| 125 |
+
# Aggregate manifest across all dirs
|
| 126 |
self.manifest: Optional[dict] = None
|
| 127 |
self.available_shards: List[str] = []
|
| 128 |
+
# Track which dir each shard lives in (for fast lookup at load)
|
| 129 |
+
self._shard_dir: Dict[str, Path] = {}
|
| 130 |
+
|
| 131 |
+
for dir_path, label in self._shards_dirs:
|
| 132 |
+
mp = dir_path / "manifest.json"
|
| 133 |
+
top_manifest = None
|
| 134 |
+
if mp.exists():
|
| 135 |
+
try:
|
| 136 |
+
top_manifest = json.loads(mp.read_text(encoding="utf-8"))
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print(f"[shard_router] manifest load failed for "
|
| 139 |
+
f"{label}: {e}")
|
| 140 |
+
|
| 141 |
+
# If no top-level manifest, scan subdirs directly
|
| 142 |
+
if top_manifest is None:
|
| 143 |
+
shard_names = [d.name for d in dir_path.iterdir()
|
| 144 |
+
if d.is_dir()
|
| 145 |
+
and (d / "retriever_state"
|
| 146 |
+
/ "manifest.json").exists()] \
|
| 147 |
+
if dir_path.exists() else []
|
| 148 |
+
else:
|
| 149 |
+
shard_names = top_manifest.get("shards", [])
|
| 150 |
+
|
| 151 |
+
for s in shard_names:
|
| 152 |
+
if (dir_path / s / "retriever_state"
|
| 153 |
+
/ "manifest.json").exists():
|
| 154 |
+
if s not in self._shard_dir: # primary wins on conflict
|
| 155 |
+
self.available_shards.append(s)
|
| 156 |
+
self._shard_dir[s] = dir_path
|
| 157 |
+
|
| 158 |
+
# Keep the primary manifest as the "main" one
|
| 159 |
+
if label == "primary" and top_manifest:
|
| 160 |
+
self.manifest = top_manifest
|
| 161 |
+
|
| 162 |
+
if self._shards_dirs:
|
| 163 |
+
n_extra = sum(1 for _, lbl in self._shards_dirs if lbl != "primary")
|
| 164 |
+
print(f"[shard_router] ready · {len(self.available_shards)} "
|
| 165 |
+
f"shards across {len(self._shards_dirs)} dir(s) "
|
| 166 |
+
f"({n_extra} extra repo(s))")
|
| 167 |
+
|
| 168 |
+
def _download_extra_repo(self, repo_id: str,
|
| 169 |
+
cache_root: Path) -> Optional[Path]:
|
| 170 |
+
"""Download a HF Dataset repo's shards dir to a local cache.
|
| 171 |
+
Returns the local path to the shards root inside the cache,
|
| 172 |
+
or None on failure. Cached: subsequent boots reuse the
|
| 173 |
+
download if `etag` hasn't changed."""
|
| 174 |
+
try:
|
| 175 |
+
from huggingface_hub import snapshot_download
|
| 176 |
+
except ImportError:
|
| 177 |
+
print(f"[shard_router] huggingface_hub not installed; "
|
| 178 |
+
f"skipping extra repo {repo_id}")
|
| 179 |
+
return None
|
| 180 |
+
target = cache_root / repo_id.replace("/", "__")
|
| 181 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 182 |
+
try:
|
| 183 |
+
print(f"[shard_router] downloading extra repo {repo_id}...")
|
| 184 |
+
t0 = time.time()
|
| 185 |
+
local = snapshot_download(
|
| 186 |
+
repo_id=repo_id,
|
| 187 |
+
repo_type="dataset",
|
| 188 |
+
local_dir=str(target),
|
| 189 |
+
)
|
| 190 |
+
elapsed = time.time() - t0
|
| 191 |
+
print(f"[shard_router] downloaded {repo_id} in "
|
| 192 |
+
f"{elapsed:.1f}s → {local}")
|
| 193 |
+
# Expect a `shards/` subdir in the dataset repo
|
| 194 |
+
shards_root = Path(local) / "shards"
|
| 195 |
+
if shards_root.exists():
|
| 196 |
+
return shards_root
|
| 197 |
+
return Path(local)
|
| 198 |
+
except Exception as e:
|
| 199 |
+
print(f"[shard_router] failed to download {repo_id}: {e}")
|
| 200 |
+
return None
|
| 201 |
|
| 202 |
def is_available(self) -> bool:
|
| 203 |
"""Does the router have any usable shards?"""
|
|
|
|
| 287 |
cfg.retrieval.enabled = list(_SHARD_RETRIEVERS)
|
| 288 |
return Pipeline.from_config(cfg)
|
| 289 |
|
| 290 |
+
def _read_state_bytes(self, state_dir: Path,
|
| 291 |
+
base_name: str) -> Optional[bytes]:
|
| 292 |
+
"""Read state file bytes. Handles two layouts:
|
| 293 |
+
1. Single file: `<base_name>.pkl.gz` → read directly
|
| 294 |
+
2. Chunked: `<base_name>.pkl.gz.part{N}` → concatenate
|
| 295 |
+
|
| 296 |
+
Chunked form is used when the file exceeded HF Hub's
|
| 297 |
+
non-LFS file-size threshold (~50MB) and was split by
|
| 298 |
+
tau_rag/scripts/chunk_pkl.py to stay in regular git (free
|
| 299 |
+
1GB LFS quota is precious).
|
| 300 |
+
|
| 301 |
+
Returns the raw gzipped bytes, or None if neither layout
|
| 302 |
+
is present.
|
| 303 |
+
"""
|
| 304 |
+
single = state_dir / f"{base_name}.pkl.gz"
|
| 305 |
+
if single.exists():
|
| 306 |
+
return single.read_bytes()
|
| 307 |
+
# Chunked form
|
| 308 |
+
parts = sorted(state_dir.glob(f"{base_name}.pkl.gz.part*"),
|
| 309 |
+
key=lambda p: int(p.suffix.removeprefix(".part")))
|
| 310 |
+
if parts:
|
| 311 |
+
return b"".join(p.read_bytes() for p in parts)
|
| 312 |
+
return None
|
| 313 |
+
|
| 314 |
def _load_state_into(self, pipe, state_dir: Path) -> None:
|
| 315 |
"""Pickle.load each retriever state file into the pipeline."""
|
| 316 |
+
import io
|
| 317 |
named = getattr(pipe.retrievers, "_retrievers", None) or {}
|
| 318 |
if not named:
|
| 319 |
for r in getattr(pipe.retrievers, "retrievers", []):
|
| 320 |
named[getattr(r, "name", type(r).__name__)] = r
|
| 321 |
|
| 322 |
for name, retriever in named.items():
|
| 323 |
+
state_bytes = self._read_state_bytes(state_dir, name)
|
| 324 |
+
if state_bytes is None:
|
| 325 |
continue
|
| 326 |
# Unwrap RefAware-style wrappers to reach the inner retriever
|
| 327 |
inner = retriever
|
|
|
|
| 334 |
if not hasattr(inner, "load_state_dict"):
|
| 335 |
continue
|
| 336 |
try:
|
| 337 |
+
with gzip.open(io.BytesIO(state_bytes), "rb") as f:
|
| 338 |
state = pickle.load(f)
|
| 339 |
inner.load_state_dict(state)
|
| 340 |
except Exception as e:
|
|
|
|
| 342 |
|
| 343 |
def _load_shard(self, shard_name: str):
|
| 344 |
"""Load a shard's pipeline (or return cached). Evicts LRU on
|
| 345 |
+
budget overflow. Thread-safe.
|
| 346 |
+
|
| 347 |
+
Multi-dir aware: looks up which dir holds this shard via
|
| 348 |
+
`_shard_dir`, falls back to `shards_dir` for backwards-compat."""
|
| 349 |
with self._lock:
|
| 350 |
if shard_name in self._cache:
|
| 351 |
# Move to MRU end
|
|
|
|
| 355 |
self._stats[shard_name].get("hits", 0) + 1
|
| 356 |
return self._cache[shard_name]
|
| 357 |
|
| 358 |
+
# Cold load — find the right dir for this shard
|
| 359 |
t0 = time.time()
|
| 360 |
+
shard_root = self._shard_dir.get(shard_name, self.shards_dir)
|
| 361 |
+
state_dir = shard_root / shard_name / "retriever_state"
|
| 362 |
if not state_dir.exists():
|
| 363 |
raise FileNotFoundError(
|
| 364 |
+
f"shard {shard_name} has no retriever_state "
|
| 365 |
+
f"in {shard_root}")
|
| 366 |
pipe = self._build_pipeline()
|
| 367 |
self._load_state_into(pipe, state_dir)
|
| 368 |
load_ms = int((time.time() - t0) * 1000)
|