Spaces:
Running
Running
Upload 34 files
Browse filesFiles changed (6)
1844 unmodified lines1845184618471844 unmodified linesRedis AOF/RDB/managed-service persistence guarantees, backup retention, or disasterrecovery policy. Keep `CONTRIBUTION_REQUIRE_DURABLE` as a separate deploymentrequirement and verify the external Redis durability contract independently.1844 unmodified lines184518461847184818491850185118521844 unmodified linesRedis AOF/RDB/managed-service persistence guarantees, backup retention, or disasterrecovery policy. Keep `CONTRIBUTION_REQUIRE_DURABLE` as a separate deploymentrequirement and verify the external Redis durability contract independently.## Run 25 / B44 provider response boundariesStorage-provider control traffic is a small metadata plane, not a bulk-download plane. Its response ceiling defaults to **4 MiB** and is hard-clamped to **16 MiB**. GitHub/GitLab/Bitbucket mutations that need no response body do not consume one; metadata reads are stream-bounded before JSON parsing. Hugging Face Hub control calls run with a scoped bounded lower-level HTTP client and restore the prior SDK client factory immediately afterward. Intentional large offline dataset/model downloads remain separately scoped (`SEC-P2-49`).
395 unmodified lines396397398399400401468 unmodified lines870871872395 unmodified lines| `SHARE_REQUIRE_DURABLE` | `false` | When true, Global Share writes fail closed unless the active store reports durable lifecycle storage. || `SHARE_REQUIRE_SHARED` | `false` | When true, Global Share writes fail closed unless the active store is shared and authoritative. Use for horizontally scaled replicas. || `MAX_BODY_BYTES` | `10485760` | Maximum accepted chat request body size. Enforced while streaming and hard-clamped to 16 MiB. || `CHAT_RATE_LIMIT_PER_HOUR` | `30` | Chat requests per resolved client identity. Enforced by the selected local or Redis backend. || `SHARE_RATE_LIMIT_PER_HOUR` | `10` | Global Share creates/updates per resolved client identity. Enforced by the selected backend. || `FEEDBACK_RATE_LIMIT_PER_HOUR` | `30` | Feedback writes, including retractions, per resolved client identity. |468 unmodified lines- [HuggingFace Inference API](https://huggingface.co/docs/api-inference/)- [HuggingFace Datasets — `huggingface_hub`](https://huggingface.co/docs/huggingface_hub/guides/repository)- [ZeroGPU documentation](https://huggingface.co/docs/hub/spaces-zerogpu)395 unmodified lines396397398399400401402468 unmodified lines871872873874875876877878395 unmodified lines| `SHARE_REQUIRE_DURABLE` | `false` | When true, Global Share writes fail closed unless the active store reports durable lifecycle storage. || `SHARE_REQUIRE_SHARED` | `false` | When true, Global Share writes fail closed unless the active store is shared and authoritative. Use for horizontally scaled replicas. || `MAX_BODY_BYTES` | `10485760` | Maximum accepted chat request body size. Enforced while streaming and hard-clamped to 16 MiB. || `MAX_UPSTREAM_RESPONSE_BYTES` | `8388608` | Maximum decoded upstream response body accepted by the proxy. Enforced while streaming before whole-body buffering and hard-clamped to 32 MiB. Oversize or malformed declared lengths fail closed. || `CHAT_RATE_LIMIT_PER_HOUR` | `30` | Chat requests per resolved client identity. Enforced by the selected local or Redis backend. || `SHARE_RATE_LIMIT_PER_HOUR` | `10` | Global Share creates/updates per resolved client identity. Enforced by the selected backend. || `FEEDBACK_RATE_LIMIT_PER_HOUR` | `30` | Feedback writes, including retractions, per resolved client identity. |468 unmodified lines- [HuggingFace Inference API](https://huggingface.co/docs/api-inference/)- [HuggingFace Datasets — `huggingface_hub`](https://huggingface.co/docs/huggingface_hub/guides/repository)- [ZeroGPU documentation](https://huggingface.co/docs/hub/spaces-zerogpu)### Provider control-response boundary (Run 25 / B44)Record-storage provider control responses are bounded independently from intentional model/dataset downloads. The default ceiling is **4 MiB** and `AI_RECORD_STORAGE_CONTROL_RESPONSE_MAX_BYTES` is clamped to **16 MiB**. Provider mutations that do not require response content are streamed and closed without buffering a body; metadata JSON is byte-counted before parsing. Custom `api_base` is supported only for GitLab and must be HTTPS with a valid host and no userinfo, query, fragment, control characters, or traversal.
362 unmodified lines363364365366367368369362 unmodified linesconversation values with DOM ``textContent`` and never injects untrusted HTML."""read_path_json = json.dumps(str(read_path), ensure_ascii=False)template = r'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Shared AI conversation</title><style>:root{font-family:system-ui,sans-serif;color-scheme:light dark}body{margin:0;background:Canvas;color:CanvasText}.wrap{max-width:850px;margin:auto;padding:24px}.head{border-bottom:1px solid currentColor;padding-bottom:16px}.source{overflow-wrap:anywhere}.source a{color:inherit}.msg{margin:18px 0;padding:14px;border:1px solid currentColor;border-radius:12px}.msg.user{margin-left:10%}.msg.error{border-style:dashed}.role{font-weight:700;margin-bottom:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;margin:0}.error-note{border:1px dashed currentColor;padding:14px;border-radius:12px}</style></head><body><main id="app" class="wrap"><p>Loading shared conversation…</p></main><script>(()=>{'use strict';const app=document.getElementById('app');const fail=(m)=>{app.replaceChildren();const p=document.createElement('p');p.className='error-note';p.textContent=m;app.appendChild(p);};let raw=(location.hash||'').slice(1);if(raw.startsWith('share='))raw=raw.slice(6);try{raw=decodeURIComponent(raw)}catch(_e){}if(!/^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(raw)){fail('This Share link is invalid or incomplete.');return;}fetch(__READ_PATH__,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({shareId:raw}),cache:'no-store',credentials:'omit',redirect:'error',referrerPolicy:'no-referrer'}).then(async r=>{let data=null;try{data=await r.json()}catch(_e){}if(!r.ok){throw new Error(r.status===410?'This Share has expired.':r.status===404?'This Share is unavailable.':'Could not load this Share.');}return data||{};}).then(data=>{app.replaceChildren();if(data.format==='html'&&data.snapshot&&data.snapshot.session&&Array.isArray(data.snapshot.records)){const snap=data.snapshot;const h=document.createElement('header');h.className='head';const h1=document.createElement('h1');h1.textContent=(snap.session.assistant_name||'AI Assistant')+' — Shared conversation';h.appendChild(h1);if(snap.session.page_title){const p=document.createElement('p');p.textContent=snap.session.page_title;h.appendChild(p);}if(snap.session.page_url){const p=document.createElement('p');p.className='source';p.append('Source: ');const a=document.createElement('a');a.href=snap.session.page_url;a.rel='noopener noreferrer';a.referrerPolicy='no-referrer';a.textContent=snap.session.page_url;p.appendChild(a);h.appendChild(p);}app.appendChild(h);for(const row of snap.records){const article=document.createElement('article');article.className='msg '+(row.role==='user'?'user':row.role==='error'?'error':'assistant');const role=document.createElement('div');role.className='role';role.textContent=row.role==='user'?'You':row.role==='error'?'Error':(snap.session.assistant_name||'AI Assistant');const pre=document.createElement('pre');pre.textContent=String(row.text||'');article.append(role,pre);app.appendChild(article);}return;}const pre=document.createElement('pre');pre.textContent=String(data.content||'');app.appendChild(pre);}).catch(e=>fail(e&&e.message?e.message:'Could not load this Share.'));})();</script></body></html>'''return template.replace("__READ_PATH__", read_path_json)def generate_edit_token() -> str:362 unmodified lines363364365366367368369362 unmodified linesconversation values with DOM ``textContent`` and never injects untrusted HTML."""read_path_json = json.dumps(str(read_path), ensure_ascii=False)template = r'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Shared AI conversation</title><style>:root{font-family:system-ui,sans-serif;color-scheme:light dark}body{margin:0;background:Canvas;color:CanvasText}.wrap{max-width:850px;margin:auto;padding:24px}.head{border-bottom:1px solid currentColor;padding-bottom:16px}.source{overflow-wrap:anywhere}.source a{color:inherit}.msg{margin:18px 0;padding:14px;border:1px solid currentColor;border-radius:12px}.msg.user{margin-left:10%}.msg.error{border-style:dashed}.role{font-weight:700;margin-bottom:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;margin:0}.error-note{border:1px dashed currentColor;padding:14px;border-radius:12px}</style></head><body><main id="app" class="wrap"><p>Loading shared conversation…</p></main><script>(()=>{'use strict';const app=document.getElementById('app');const fail=(m)=>{app.replaceChildren();const p=document.createElement('p');p.className='error-note';p.textContent=m;app.appendChild(p);};let raw=(location.hash||'').slice(1);if(raw.startsWith('share='))raw=raw.slice(6);try{raw=decodeURIComponent(raw)}catch(_e){}if(!/^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.test(raw)){fail('This Share link is invalid or incomplete.');return;}const readJson=async(r)=>{const max=4*1024*1024;const h=r.headers&&r.headers.get?r.headers.get('content-length'):null;if(h!=null&&String(h).trim()!==''){if(!/^\d+$/.test(String(h).trim())||Number(h)>max)throw new Error('Share response is too large.');}if(!r.body||typeof r.body.getReader!=='function'||typeof TextDecoder!=='function')throw new Error('Bounded Share reader unavailable.');const rd=r.body.getReader(),dec=new TextDecoder(),parts=[];let n=0;try{for(;;){const x=await rd.read();if(x.done)break;const v=x.value||new Uint8Array(0);n+=Number(v.byteLength||v.length||0);if(n>max)throw new Error('Share response is too large.');parts.push(dec.decode(v,{stream:true}));}parts.push(dec.decode());}catch(e){try{await rd.cancel()}catch(_e){}throw e;}finally{try{rd.releaseLock()}catch(_e){}}return JSON.parse(parts.join(''));};fetch(__READ_PATH__,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({shareId:raw}),cache:'no-store',credentials:'omit',redirect:'error',referrerPolicy:'no-referrer'}).then(async r=>{if(!r.ok){throw new Error(r.status===410?'This Share has expired.':r.status===404?'This Share is unavailable.':'Could not load this Share.');}return await readJson(r);}).then(data=>{app.replaceChildren();if(data.format==='html'&&data.snapshot&&data.snapshot.session&&Array.isArray(data.snapshot.records)){const snap=data.snapshot;const h=document.createElement('header');h.className='head';const h1=document.createElement('h1');h1.textContent=(snap.session.assistant_name||'AI Assistant')+' — Shared conversation';h.appendChild(h1);if(snap.session.page_title){const p=document.createElement('p');p.textContent=snap.session.page_title;h.appendChild(p);}if(snap.session.page_url){const p=document.createElement('p');p.className='source';p.append('Source: ');const a=document.createElement('a');a.href=snap.session.page_url;a.rel='noopener noreferrer';a.referrerPolicy='no-referrer';a.textContent=snap.session.page_url;p.appendChild(a);h.appendChild(p);}app.appendChild(h);for(const row of snap.records){const article=document.createElement('article');article.className='msg '+(row.role==='user'?'user':row.role==='error'?'error':'assistant');const role=document.createElement('div');role.className='role';role.textContent=row.role==='user'?'You':row.role==='error'?'Error':(snap.session.assistant_name||'AI Assistant');const pre=document.createElement('pre');pre.textContent=String(row.text||'');article.append(role,pre);app.appendChild(article);}return;}const pre=document.createElement('pre');pre.textContent=String(data.content||'');app.appendChild(pre);}).catch(e=>fail(e&&e.message?e.message:'Could not load this Share.'));})();</script></body></html>'''return template.replace("__READ_PATH__", read_path_json)def generate_edit_token() -> str:
219 unmodified lines220221222223224225226219 unmodified lines# ─────────────────────────────────────────────────────────────────────────────#: Proxy release version — bump on every breaking change.PROXY_VERSION: str = "7.0.0"#: HuggingFace Inference Providers router base URL (no trailing slash).#: Only used for Path 3 (standard provider models) when ``BACKEND_URL`` is219 unmodified lines220221222223224225226219 unmodified lines# ─────────────────────────────────────────────────────────────────────────────#: Proxy release version — bump on every breaking change.PROXY_VERSION: str = "7.2.0"#: HuggingFace Inference Providers router base URL (no trailing slash).#: Only used for Path 3 (standard provider models) when ``BACKEND_URL`` is
14 unmodified lines151617181920212223249 unmodified lines343536373839128 unmodified lines168169170171172173174175176176 unmodified lines353354355356357358359360361362226 unmodified lines58959059159259359459559659759859960010 unmodified lines6116126136146156166176186196206216226236246256266276286296306316326331 unmodified line6356366376386396406416426436446456466476486492 unmodified lines65265365465565665765865966066166266366466566666766866967067120 unmodified lines69269369469569669769869970070170270312 unmodified lines7167177187197207217 unmodified lines7297307317327337347357367377387397407417427437447457467477487492 unmodified lines7527537547557567577587597607617627637647657667677687691 unmodified line77177277377477577677714 unmodified linesimport osimport reimport timefrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Any, Literalfrom urllib.parse import quote, urlencodeimport httpx9 unmodified lines_SEG_RE = re.compile(r"^[A-Za-z0-9._-]+$")_ALLOWED_PROVIDERS = {"huggingface", "github", "gitlab", "bitbucket"}_TRANSIENT_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}class StorageConfigError(ValueError):128 unmodified linespaths = raw.get("paths") if isinstance(raw.get("paths"), dict) else {}token_env = _safe_token_env(raw.get("token_env"))token_type = _normalize_token_type(raw.get("token_type") or os.environ.get(token_env + "_TYPE"))api_base = str(raw.get("api_base") or "").strip().rstrip("/")if provider == "gitlab" and not api_base:api_base = "https://gitlab.com/api/v4"return StorageTarget(id=target_id,label=label,176 unmodified linesauth_check = getattr(api, "auth_check", None)if auth_check and "write" in inspect.signature(auth_check).parameters:await asyncio.to_thread(auth_check,repo_id=target.repo,repo_type="dataset",write=True,)return "verified"except Exception as exc:226 unmodified linesapi = HfApi(token=target.token)await asyncio.to_thread(api.create_commit,repo_id=target.repo,repo_type="dataset",revision=target.branch,operations=[CommitOperationDelete(path_in_repo=path)],commit_message=message,)return "removed-current-view"except Exception as exc: # noqa: BLE00110 unmodified lines"Accept": "application/vnd.github+json","X-GitHub-Api-Version": "2022-11-28",}current = await self._client().get(url, headers=headers, params={"ref": target.branch}, timeout=15.0)if current.status_code == 404:return "already-absent"if current.status_code != 200:raise StorageWriteError("GITHUB_DELETE_LOOKUP", transient=current.status_code in _TRANSIENT_STATUS)sha = str((current.json() or {}).get("sha") or "")if not sha:raise StorageWriteError("GITHUB_DELETE_SHA")resp = await self._client().request("DELETE", url, headers=headers,json={"message": message, "sha": sha, "branch": target.branch}, timeout=20.0,)if resp.status_code in {200, 204}:return "removed-current-view"if resp.status_code == 404:return "already-absent"raise StorageWriteError("GITHUB_DELETE", transient=resp.status_code in _TRANSIENT_STATUS)async def _delete_gitlab(self, target: StorageTarget, path: str, message: str) -> str:base = target.api_base or "https://gitlab.com/api/v4"1 unmodified linefile_path = quote(path, safe="")url = f"{base}/projects/{project}/repository/files/{file_path}"headers = {"PRIVATE-TOKEN": target.token}resp = await self._client().request("DELETE", url, headers=headers,json={"branch": target.branch, "commit_message": message}, timeout=20.0,)if resp.status_code in {200, 204}:return "removed-current-view"if resp.status_code == 404:return "already-absent"raise StorageWriteError("GITLAB_DELETE", transient=resp.status_code in _TRANSIENT_STATUS)async def _delete_bitbucket(self, target: StorageTarget, path: str, message: str) -> str:workspace, repo = _repo_parts(target.repo)2 unmodified linesf"/src/{quote(target.branch, safe='')}/{quote(path, safe='/')}")headers = {"Authorization": f"Bearer {target.token}"}current = await self._client().get(read_url, headers=headers, timeout=15.0)if current.status_code == 404:return "already-absent"if current.status_code != 200:raise StorageWriteError("BITBUCKET_DELETE_LOOKUP", transient=current.status_code in _TRANSIENT_STATUS)url = f"https://api.bitbucket.org/2.0/repositories/{quote(workspace)}/{quote(repo)}/src"form = urlencode([("branch", target.branch), ("message", message), ("files", "/" + path)])delete_headers = {**headers, "Content-Type": "application/x-www-form-urlencoded"}resp = await self._client().post(url, headers=delete_headers, content=form.encode("utf-8"), timeout=25.0)if resp.status_code in {200, 201}:return "removed-current-view"raise StorageWriteError("BITBUCKET_DELETE", transient=resp.status_code in _TRANSIENT_STATUS)async def _dispatch(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:try:20 unmodified linesapi = HfApi(token=target.token)await asyncio.to_thread(api.create_commit,repo_id=target.repo,repo_type="dataset",revision=target.branch,operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=content)],commit_message=message,)except Exception as exc: # noqa: BLE001# Keep the exception private. HTTP permission/transient distinction is12 unmodified linesraise StorageWriteError("NO_HTTP_CLIENT", transient=True)return self.clientasync def _write_github(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:owner, repo = _repo_parts(target.repo)url = f"https://api.github.com/repos/{quote(owner)}/{quote(repo)}/contents/{quote(path, safe='/')}"7 unmodified lines"content": base64.b64encode(content).decode("ascii"),"branch": target.branch,}resp = await self._client().put(url, headers=headers, json=payload, timeout=20.0)if resp.status_code in {200, 201}:return# A retry may encounter an already-created idempotent path. Confirm# content equality before treating the conflict as success.if resp.status_code in {409, 422}:get = await self._client().get(url, headers=headers, params={"ref": target.branch}, timeout=15.0)if get.status_code == 200:try:existing = base64.b64decode((get.json().get("content") or "").replace("\n", ""))if existing == content:returnexcept Exception:passraise StorageWriteError("GITHUB_WRITE", transient=resp.status_code in _TRANSIENT_STATUS)async def _write_gitlab(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:base = target.api_base or "https://gitlab.com/api/v4"2 unmodified linesurl = f"{base}/projects/{project}/repository/files/{file_path}"headers = {"PRIVATE-TOKEN": target.token}payload = {"branch": target.branch, "commit_message": message, "content": content.decode("utf-8")}resp = await self._client().post(url, headers=headers, json=payload, timeout=20.0)if resp.status_code in {200, 201}:returnif resp.status_code == 400:get = await self._client().get(url, headers=headers, params={"ref": target.branch}, timeout=15.0)if get.status_code == 200:try:if get.json().get("content_sha256") == hashlib.sha256(content).hexdigest():returnexcept Exception:passraise StorageWriteError("GITLAB_WRITE", transient=resp.status_code in _TRANSIENT_STATUS)async def _write_bitbucket(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:workspace, repo = _repo_parts(target.repo)1 unmodified lineheaders = {"Authorization": f"Bearer {target.token}"}files = {"/" + path: (path.rsplit("/", 1)[-1], content, "application/x-ndjson")}data = {"branch": target.branch, "message": message}resp = await self._client().post(url, headers=headers, data=data, files=files, timeout=25.0)if resp.status_code in {200, 201}:returnraise StorageWriteError("BITBUCKET_WRITE", transient=resp.status_code in _TRANSIENT_STATUS)14 unmodified lines15161718192021222324259 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147128 unmodified lines276277278279280281282283284285286287288176 unmodified lines465466467468469470471472473474475476226 unmodified lines70370470570670770870971071171271371471571610 unmodified lines7277287297307317327337347357367377387397407417427437447457467477487497501 unmodified line7527537547557567577587597607617627637647657662 unmodified lines76977077177277377477577677777877978078178278378478578678778820 unmodified lines80981081181281381481581681781881982082182212 unmodified lines8358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738747 unmodified lines8828838848858868878888898908918928938948958968978988999009019029032 unmodified lines9069079089099109119129139149159169179189199209219229239241 unmodified line92692792892993093193214 unmodified linesimport osimport reimport timeimport threadingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Any, Literalfrom urllib.parse import quote, urlencode, urlsplitimport httpx9 unmodified lines_SEG_RE = re.compile(r"^[A-Za-z0-9._-]+$")_ALLOWED_PROVIDERS = {"huggingface", "github", "gitlab", "bitbucket"}_TRANSIENT_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}_CONTROL_RESPONSE_DEFAULT = 4 * 1024 * 1024_CONTROL_RESPONSE_HARD_MAX = 16 * 1024 * 1024_HF_FACTORY_LOCK = threading.RLock()class _ProviderResponseTooLarge(RuntimeError):passdef _control_response_limit() -> int:raw = os.environ.get("AI_RECORD_STORAGE_CONTROL_RESPONSE_MAX_BYTES", "").strip()try:value = int(raw) if raw else _CONTROL_RESPONSE_DEFAULTexcept ValueError:value = _CONTROL_RESPONSE_DEFAULTreturn max(1024, min(_CONTROL_RESPONSE_HARD_MAX, value))def _safe_gitlab_api_base(value: Any) -> str:raw = str(value or "").strip().rstrip("/")if not raw:return "https://gitlab.com/api/v4"if any(ord(ch) < 0x20 or ord(ch) == 0x7f for ch in raw):raise StorageConfigError("TARGET_API_BASE")try:parsed = urlsplit(raw)except Exception as exc:raise StorageConfigError("TARGET_API_BASE") from excif parsed.scheme.lower() != "https" or not parsed.hostname:raise StorageConfigError("TARGET_API_BASE")if parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment:raise StorageConfigError("TARGET_API_BASE")if ".." in [seg for seg in parsed.path.split("/") if seg]:raise StorageConfigError("TARGET_API_BASE")if "\\" in parsed.path:raise StorageConfigError("TARGET_API_BASE")try:_ = parsed.portexcept ValueError as exc:raise StorageConfigError("TARGET_API_BASE") from excreturn rawclass _BoundedSyncStream(httpx.SyncByteStream):def __init__(self, stream: httpx.SyncByteStream, limit: int) -> None:self._stream = streamself._limit = limitself._seen = 0def __iter__(self):for chunk in self._stream:self._seen += len(chunk)if self._seen > self._limit:raise _ProviderResponseTooLarge("provider control response exceeds configured limit")yield chunkdef close(self) -> None:self._stream.close()class _BoundedTransport(httpx.BaseTransport):def __init__(self, transport: httpx.BaseTransport, limit: int) -> None:self._transport = transportself._limit = limitdef handle_request(self, request: httpx.Request) -> httpx.Response:response = self._transport.handle_request(request)length = response.headers.get("content-length")if length and length.isdigit() and int(length) > self._limit:response.close()raise _ProviderResponseTooLarge("provider control response exceeds configured limit")response.stream = _BoundedSyncStream(response.stream, self._limit)return responsedef close(self) -> None:self._transport.close()def _with_bounded_hf_client(call):"""Run one huggingface_hub control-plane call with bounded HTTP bodies.Minimal test doubles and old SDK shims may not expose the factory module;production is pinned to a version that does. In that compatibility-onlycase there is no underlying SDK HTTP client to wrap, so execute directly."""try:from huggingface_hub.utils import _http as hf_http # noqa: PLC0415except (ImportError, ModuleNotFoundError):return call()with _HF_FACTORY_LOCK:previous = hf_http._GLOBAL_CLIENT_FACTORYdef factory():client = previous()transport = getattr(client, "_transport", None)if transport is None:client.close()raise RuntimeError("HF_CLIENT_TRANSPORT")client._transport = _BoundedTransport(transport, _control_response_limit())return clienthf_http.set_client_factory(factory)try:return call()finally:hf_http.set_client_factory(previous)class StorageConfigError(ValueError):128 unmodified linespaths = raw.get("paths") if isinstance(raw.get("paths"), dict) else {}token_env = _safe_token_env(raw.get("token_env"))token_type = _normalize_token_type(raw.get("token_type") or os.environ.get(token_env + "_TYPE"))raw_api_base = raw.get("api_base")if provider == "gitlab":api_base = _safe_gitlab_api_base(raw_api_base)else:if str(raw_api_base or "").strip():raise StorageConfigError("TARGET_API_BASE_UNSUPPORTED")api_base = ""return StorageTarget(id=target_id,label=label,176 unmodified linesauth_check = getattr(api, "auth_check", None)if auth_check and "write" in inspect.signature(auth_check).parameters:await asyncio.to_thread(_with_bounded_hf_client,lambda: auth_check(repo_id=target.repo,repo_type="dataset",write=True,),)return "verified"except Exception as exc:226 unmodified linesapi = HfApi(token=target.token)await asyncio.to_thread(_with_bounded_hf_client,lambda: api.create_commit(repo_id=target.repo,repo_type="dataset",revision=target.branch,operations=[CommitOperationDelete(path_in_repo=path)],commit_message=message,),)return "removed-current-view"except Exception as exc: # noqa: BLE00110 unmodified lines"Accept": "application/vnd.github+json","X-GitHub-Api-Version": "2022-11-28",}current_status, current_json = await self._request_bounded_json("GET", url, headers=headers, params={"ref": target.branch}, timeout=15.0)if current_status == 404:return "already-absent"if current_status != 200:raise StorageWriteError("GITHUB_DELETE_LOOKUP", transient=current_status in _TRANSIENT_STATUS)sha = str((current_json or {}).get("sha") or "")if not sha:raise StorageWriteError("GITHUB_DELETE_SHA")status = await self._request_no_body("DELETE", url, headers=headers,json={"message": message, "sha": sha, "branch": target.branch}, timeout=20.0,)if status in {200, 204}:return "removed-current-view"if status == 404:return "already-absent"raise StorageWriteError("GITHUB_DELETE", transient=status in _TRANSIENT_STATUS)async def _delete_gitlab(self, target: StorageTarget, path: str, message: str) -> str:base = target.api_base or "https://gitlab.com/api/v4"1 unmodified linefile_path = quote(path, safe="")url = f"{base}/projects/{project}/repository/files/{file_path}"headers = {"PRIVATE-TOKEN": target.token}status = await self._request_no_body("DELETE", url, headers=headers,json={"branch": target.branch, "commit_message": message}, timeout=20.0,)if status in {200, 204}:return "removed-current-view"if status == 404:return "already-absent"raise StorageWriteError("GITLAB_DELETE", transient=status in _TRANSIENT_STATUS)async def _delete_bitbucket(self, target: StorageTarget, path: str, message: str) -> str:workspace, repo = _repo_parts(target.repo)2 unmodified linesf"/src/{quote(target.branch, safe='')}/{quote(path, safe='/')}")headers = {"Authorization": f"Bearer {target.token}"}current_status = await self._request_no_body("GET", read_url, headers=headers, timeout=15.0)if current_status == 404:return "already-absent"if current_status != 200:raise StorageWriteError("BITBUCKET_DELETE_LOOKUP", transient=current_status in _TRANSIENT_STATUS)url = f"https://api.bitbucket.org/2.0/repositories/{quote(workspace)}/{quote(repo)}/src"form = urlencode([("branch", target.branch), ("message", message), ("files", "/" + path)])delete_headers = {**headers, "Content-Type": "application/x-www-form-urlencoded"}status = await self._request_no_body("POST", url, headers=delete_headers, content=form.encode("utf-8"), timeout=25.0)if status in {200, 201}:return "removed-current-view"raise StorageWriteError("BITBUCKET_DELETE", transient=status in _TRANSIENT_STATUS)async def _dispatch(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:try:20 unmodified linesapi = HfApi(token=target.token)await asyncio.to_thread(_with_bounded_hf_client,lambda: api.create_commit(repo_id=target.repo,repo_type="dataset",revision=target.branch,operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=content)],commit_message=message,),)except Exception as exc: # noqa: BLE001# Keep the exception private. HTTP permission/transient distinction is12 unmodified linesraise StorageWriteError("NO_HTTP_CLIENT", transient=True)return self.clientasync def _request_no_body(self, method: str, url: str, **kwargs: Any) -> int:client = self._client()request = client.build_request(method, url, **kwargs)response = await client.send(request, stream=True)try:return response.status_codefinally:await response.aclose()async def _request_bounded_json(self, method: str, url: str, **kwargs: Any) -> tuple[int, Any]:client = self._client()request = client.build_request(method, url, **kwargs)response = await client.send(request, stream=True)try:limit = _control_response_limit()declared = response.headers.get("content-length")if declared and declared.isdigit() and int(declared) > limit:raise StorageWriteError("PROVIDER_RESPONSE_TOO_LARGE")buf = bytearray()async for chunk in response.aiter_bytes():buf.extend(chunk)if len(buf) > limit:raise StorageWriteError("PROVIDER_RESPONSE_TOO_LARGE")if not buf:payload = {}else:try:payload = json.loads(bytes(buf))except Exception as exc:raise StorageWriteError("PROVIDER_RESPONSE_JSON") from excreturn response.status_code, payloadfinally:await response.aclose()async def _write_github(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:owner, repo = _repo_parts(target.repo)url = f"https://api.github.com/repos/{quote(owner)}/{quote(repo)}/contents/{quote(path, safe='/')}"7 unmodified lines"content": base64.b64encode(content).decode("ascii"),"branch": target.branch,}status = await self._request_no_body("PUT", url, headers=headers, json=payload, timeout=20.0)if status in {200, 201}:return# A retry may encounter an already-created idempotent path. Confirm# content equality before treating the conflict as success.if status in {409, 422}:get_status, get_json = await self._request_bounded_json("GET", url, headers=headers, params={"ref": target.branch}, timeout=15.0)if get_status == 200:try:existing = base64.b64decode((get_json.get("content") or "").replace("\n", ""))if existing == content:returnexcept Exception:passraise StorageWriteError("GITHUB_WRITE", transient=status in _TRANSIENT_STATUS)async def _write_gitlab(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:base = target.api_base or "https://gitlab.com/api/v4"2 unmodified linesurl = f"{base}/projects/{project}/repository/files/{file_path}"headers = {"PRIVATE-TOKEN": target.token}payload = {"branch": target.branch, "commit_message": message, "content": content.decode("utf-8")}status = await self._request_no_body("POST", url, headers=headers, json=payload, timeout=20.0)if status in {200, 201}:returnif status == 400:get_status, get_json = await self._request_bounded_json("GET", url, headers=headers, params={"ref": target.branch}, timeout=15.0)if get_status == 200:try:if get_json.get("content_sha256") == hashlib.sha256(content).hexdigest():returnexcept Exception:passraise StorageWriteError("GITLAB_WRITE", transient=status in _TRANSIENT_STATUS)async def _write_bitbucket(self, target: StorageTarget, path: str, content: bytes, message: str) -> None:workspace, repo = _repo_parts(target.repo)1 unmodified lineheaders = {"Authorization": f"Bearer {target.token}"}files = {"/" + path: (path.rsplit("/", 1)[-1], content, "application/x-ndjson")}data = {"branch": target.branch, "message": message}status = await self._request_no_body("POST", url, headers=headers, data=data, files=files, timeout=25.0)if status in {200, 201}:returnraise StorageWriteError("BITBUCKET_WRITE", transient=status in _TRANSIENT_STATUS)
4 unmodified lines56789101181 unmodified lines939495969798360 unmodified lines459460461462463464271 unmodified lines7367377387397407411103 unmodified lines18451846184718481849185018511852185343 unmodified lines1897189818991900190119021903190419051906190775 unmodified lines1983198419851986198719881989199019911992199319944 unmodified lines1999200020012002200320041 unmodified line200620072008200920102011201265 unmodified lines2078207920802081208220832084208520862087270 unmodified lines235823592360236123622363100 unmodified lines2464246524662467246824694 unmodified lines# Authors: The scikit-plots developers# SPDX-License-Identifier: BSD-3-Clause## scikit-plots/ai · _hf_spaces_proxy/app.py v7.0.0## Server-authoritative chat proxy for sphinx-ai-assistant.#81 unmodified lines# prefix AI_RECORD_STORAGE_TOKEN_. When absent, legacy# TRAINING_DATASET_REPO + HF_* token settings are used.# MAX_BODY_BYTES Maximum accepted body size. Default: 10485760.# SHARE_MAX_BODY_BYTES Global Share request/canonical snapshot limit. Default: 512000.# SHARE_MAX_ENTRIES Maximum live in-memory Global Share entries. Default: 256.# SHARE_MAX_TOTAL_BYTES Aggregate live Global Share byte budget. Default: 16777216.360 unmodified linesreturn Falseasync def _read_limited_body(request: Request, max_bytes: int, label: str = "Request") -> bytes:"""Read an ASGI request incrementally and stop once *max_bytes* is crossed."""raw_cl = request.headers.get("content-length")271 unmodified lines16 * 1024 * 1024,))#: Maximum JSON request size accepted by Global Share. Kept independent from#: chat bodies so a public share service cannot consume 10 MiB per request.SHARE_MAX_BODY_BYTES: int = max(16_384, min(1103 unmodified linesreturn json.dumps(clone, ensure_ascii=False, separators=(",", ":")).encode()async def _post_buffered(request_body: bytes) -> Response:try:upstream = await _http_client.post(url, content=request_body, headers=headers, timeout=req_timeout)except httpx.ReadTimeout:logger.warning(43 unmodified lines"upstream_request_error","Failed to reach the upstream service.",)return Response(content=upstream.content,status_code=upstream.status_code,media_type=upstream.headers.get("content-type", "application/json"),)if not stream_requested:75 unmodified linesif upstream.status_code != 200: # noqa: PLR2004status = upstream.status_codetry:await upstream.aread()except httpx.HTTPError:passfinally:await upstream.aclose()logger.warning("AI proxy [UPSTREAM_STATUS]: upstream rejected streaming request status=%d",status,4 unmodified linesf"The upstream service returned HTTP {status}.",)content_type = (upstream.headers.get("content-type") or "").lower()if "text/event-stream" not in content_type:# The custom ai-model Space currently returns an ordinary OpenAI JSON1 unmodified line# instead of falsely labelling raw JSON bytes as SSE (which the browser# would correctly ignore, producing an empty answer).try:content = await upstream.aread()except httpx.ReadTimeout:await upstream.aclose()logger.warning(65 unmodified linesemitted = Falsesaw_data_field = Falseprobe_tail = b""try:async for chunk in upstream.aiter_bytes():if not chunk:continueemitted = Trueprobe = probe_tail + chunk.lower()if b"data:" in probe:270 unmodified lines"required_shared": RATE_LIMIT_REQUIRE_SHARED,"scope": "single_redis_consistency_domain" if RATE_LIMIT_BACKEND == "redis" else "process_local",},"cors": _cors_public_status(),},headers={"Cache-Control": "no-store"},100 unmodified lines"ready": (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED),"required_shared": RATE_LIMIT_REQUIRE_SHARED,},"cors": _cors_public_status(),},headers={"Cache-Control": "no-store"},4 unmodified lines56789101181 unmodified lines93949596979899360 unmodified lines460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508271 unmodified lines7807817827837847857867877887897907917927931103 unmodified lines18971898189919001901190219031904190519061907190819091910191119121913191419151916191743 unmodified lines1961196219631964196519661967196819691970197119721973197475 unmodified lines20502051205220532054205520564 unmodified lines206120622063206420652066206720682069207020712072207320742075207620771 unmodified line20792080208120822083208420852086208720882089209020912092209365 unmodified lines21592160216121622163216421652166216721682169217021712172217321742175217621772178270 unmodified lines2449245024512452245324542455100 unmodified lines25562557255825592560256125624 unmodified lines# Authors: The scikit-plots developers# SPDX-License-Identifier: BSD-3-Clause## scikit-plots/ai · _hf_spaces_proxy/app.py v7.2.0## Server-authoritative chat proxy for sphinx-ai-assistant.#81 unmodified lines# prefix AI_RECORD_STORAGE_TOKEN_. When absent, legacy# TRAINING_DATASET_REPO + HF_* token settings are used.# MAX_BODY_BYTES Maximum accepted body size. Default: 10485760.# MAX_UPSTREAM_RESPONSE_BYTES Maximum decoded upstream response bytes. Default: 8388608.# SHARE_MAX_BODY_BYTES Global Share request/canonical snapshot limit. Default: 512000.# SHARE_MAX_ENTRIES Maximum live in-memory Global Share entries. Default: 256.# SHARE_MAX_TOTAL_BYTES Aggregate live Global Share byte budget. Default: 16777216.360 unmodified linesreturn Falseclass _UpstreamResponseTooLarge(RuntimeError):"""Raised when decoded upstream response bytes exceed the hard application cap."""def _upstream_declared_length(response: httpx.Response) -> int | None:raw = (response.headers.get("content-length") or "").strip()if not raw:return Noneif not raw.isdigit():raise _UpstreamResponseTooLarge("invalid upstream content-length")value = int(raw)if value < 0:raise _UpstreamResponseTooLarge("invalid upstream content-length")return valuedef _check_upstream_declared_length(response: httpx.Response, max_bytes: int | None = None) -> None:limit = MAX_UPSTREAM_RESPONSE_BYTES if max_bytes is None else int(max_bytes)declared = _upstream_declared_length(response)if declared is not None and declared > limit:raise _UpstreamResponseTooLarge("declared upstream response too large")async def _read_upstream_limited(response: httpx.Response, max_bytes: int | None = None) -> bytes:"""Read a streamed upstream response with a decoded-byte hard ceiling."""limit = MAX_UPSTREAM_RESPONSE_BYTES if max_bytes is None else int(max_bytes)_check_upstream_declared_length(response, limit)out = bytearray()total = 0async for chunk in response.aiter_bytes():if not chunk:continuetotal += len(chunk)if total > limit:raise _UpstreamResponseTooLarge("upstream response too large")out.extend(chunk)return bytes(out)async def _read_limited_body(request: Request, max_bytes: int, label: str = "Request") -> bytes:"""Read an ASGI request incrementally and stop once *max_bytes* is crossed."""raw_cl = request.headers.get("content-length")271 unmodified lines16 * 1024 * 1024,))#: Maximum decoded upstream response bytes accepted before the proxy aborts the#: provider stream. This is independent from request-body limits because a#: malicious/misconfigured upstream controls response size.MAX_UPSTREAM_RESPONSE_BYTES: int = max(64 * 1024, min(_safe_int(os.environ.get("MAX_UPSTREAM_RESPONSE_BYTES"), 8 * 1024 * 1024),32 * 1024 * 1024,))#: Maximum JSON request size accepted by Global Share. Kept independent from#: chat bodies so a public share service cannot consume 10 MiB per request.SHARE_MAX_BODY_BYTES: int = max(16_384, min(1103 unmodified linesreturn json.dumps(clone, ensure_ascii=False, separators=(",", ":")).encode()async def _post_buffered(request_body: bytes) -> Response:upstream: httpx.Response | None = Nonetry:request = _http_client.build_request("POST", url, content=request_body, headers=headers, timeout=req_timeout)upstream = await _http_client.send(request, stream=True)status = upstream.status_codemedia_type = upstream.headers.get("content-type", "application/json")content = await _read_upstream_limited(upstream)except _UpstreamResponseTooLarge:logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: upstream response exceeded the application byte ceiling")return _error_response(502,"upstream_response_too_large","The upstream response exceeded the proxy safety limit.",)except httpx.ReadTimeout:logger.warning(43 unmodified lines"upstream_request_error","Failed to reach the upstream service.",)finally:if upstream is not None and not upstream.is_closed:await upstream.aclose()return Response(content=content,status_code=status,media_type=media_type,)if not stream_requested:75 unmodified linesif upstream.status_code != 200: # noqa: PLR2004status = upstream.status_codeawait upstream.aclose()logger.warning("AI proxy [UPSTREAM_STATUS]: upstream rejected streaming request status=%d",status,4 unmodified linesf"The upstream service returned HTTP {status}.",)try:_check_upstream_declared_length(upstream)except _UpstreamResponseTooLarge:await upstream.aclose()logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: declared upstream response exceeded the application byte ceiling")return _error_response(502,"upstream_response_too_large","The upstream response exceeded the proxy safety limit.",)content_type = (upstream.headers.get("content-type") or "").lower()if "text/event-stream" not in content_type:# The custom ai-model Space currently returns an ordinary OpenAI JSON1 unmodified line# instead of falsely labelling raw JSON bytes as SSE (which the browser# would correctly ignore, producing an empty answer).try:content = await _read_upstream_limited(upstream)except _UpstreamResponseTooLarge:await upstream.aclose()logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: buffered JSON fallback exceeded the application byte ceiling")return _error_response(502,"upstream_response_too_large","The upstream response exceeded the proxy safety limit.",)except httpx.ReadTimeout:await upstream.aclose()logger.warning(65 unmodified linesemitted = Falsesaw_data_field = Falseprobe_tail = b""total_bytes = 0try:async for chunk in upstream.aiter_bytes():if not chunk:continuetotal_bytes += len(chunk)if total_bytes > MAX_UPSTREAM_RESPONSE_BYTES:logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: SSE response exceeded the application byte ceiling")yield _sse_error_frame(502,"upstream_response_too_large","The upstream response exceeded the proxy safety limit.",)returnemitted = Trueprobe = probe_tail + chunk.lower()if b"data:" in probe:270 unmodified lines"required_shared": RATE_LIMIT_REQUIRE_SHARED,"scope": "single_redis_consistency_domain" if RATE_LIMIT_BACKEND == "redis" else "process_local",},"limits": {"max_upstream_response_bytes": MAX_UPSTREAM_RESPONSE_BYTES},"cors": _cors_public_status(),},headers={"Cache-Control": "no-store"},100 unmodified lines"ready": (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED),"required_shared": RATE_LIMIT_REQUIRE_SHARED,},"limits": {"max_upstream_response_bytes": MAX_UPSTREAM_RESPONSE_BYTES},"cors": _cors_public_status(),},headers={"Cache-Control": "no-store"},
DATASET_COLLECTION_GUIDANCE.md+5
README.md+6
_utils/_share_contract.py+1-1
_utils/_shared_logic.py+1-1
_utils/_storage.py+213-58
app.py+106-13