Bypass multipart 1024KB limit on /api/projects/index-precomputed via raw binary framing
Browse files- backend/app/api/projects.py +30 -8
- backend/tests/test_hf_hub_and_space.py +31 -0
- frontend/src/api/client.ts +12 -13
backend/app/api/projects.py
CHANGED
|
@@ -11,7 +11,7 @@ from datetime import datetime, timezone
|
|
| 11 |
from typing import Any
|
| 12 |
|
| 13 |
import numpy as np
|
| 14 |
-
from fastapi import APIRouter,
|
| 15 |
from fastapi.responses import StreamingResponse
|
| 16 |
|
| 17 |
from app.config import MAX_CONCURRENT_INDEX_JOBS
|
|
@@ -588,21 +588,43 @@ def _telemetry_from_precomputed(
|
|
| 588 |
|
| 589 |
|
| 590 |
@router.post("/index-precomputed")
|
| 591 |
-
async def index_precomputed_embeddings_stream(
|
| 592 |
-
metadata: str = Form(...),
|
| 593 |
-
embeddings: UploadFile = File(...),
|
| 594 |
-
):
|
| 595 |
"""
|
| 596 |
Finalize a run whose dense embeddings were computed on the user's device
|
| 597 |
(WebGPU Metal/GPU or Browser WASM CPU): builds BM25, corpus diagnostics, UMAP 2D,
|
| 598 |
and persists Parquet/Atlas cache without ever loading embedding weights on the Space server.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
try:
|
| 601 |
-
meta = IndexPrecomputedMetadata.model_validate_json(
|
| 602 |
except Exception as exc:
|
| 603 |
raise HTTPException(status_code=400, detail=f"Invalid metadata payload: {exc}") from exc
|
| 604 |
-
|
| 605 |
-
raw_bytes = await embeddings.read()
|
| 606 |
n_docs = len(meta.indexed_texts)
|
| 607 |
dim = int(meta.embedding_dim)
|
| 608 |
expected_bytes = n_docs * dim * 4
|
|
|
|
| 11 |
from typing import Any
|
| 12 |
|
| 13 |
import numpy as np
|
| 14 |
+
from fastapi import APIRouter, HTTPException, Request, Response
|
| 15 |
from fastapi.responses import StreamingResponse
|
| 16 |
|
| 17 |
from app.config import MAX_CONCURRENT_INDEX_JOBS
|
|
|
|
| 588 |
|
| 589 |
|
| 590 |
@router.post("/index-precomputed")
|
| 591 |
+
async def index_precomputed_embeddings_stream(request: Request):
|
|
|
|
|
|
|
|
|
|
| 592 |
"""
|
| 593 |
Finalize a run whose dense embeddings were computed on the user's device
|
| 594 |
(WebGPU Metal/GPU or Browser WASM CPU): builds BM25, corpus diagnostics, UMAP 2D,
|
| 595 |
and persists Parquet/Atlas cache without ever loading embedding weights on the Space server.
|
| 596 |
+
|
| 597 |
+
Supports both:
|
| 598 |
+
1. Raw binary `application/octet-stream` framed as:
|
| 599 |
+
[4-byte little-endian uint32 metadata_byte_len][UTF-8 metadata JSON][float32 embeddings]
|
| 600 |
+
(bypasses multipart parsers & part-size limits completely)
|
| 601 |
+
2. `multipart/form-data` (`metadata` file or string + `embeddings` file) with 1 GB part limit.
|
| 602 |
"""
|
| 603 |
+
content_type = (request.headers.get("content-type") or "").lower()
|
| 604 |
+
if content_type.startswith("application/octet-stream"):
|
| 605 |
+
body = await request.body()
|
| 606 |
+
if len(body) < 4:
|
| 607 |
+
raise HTTPException(status_code=400, detail="Truncated binary payload.")
|
| 608 |
+
meta_len = int.from_bytes(body[:4], "little")
|
| 609 |
+
if meta_len <= 0 or 4 + meta_len > len(body):
|
| 610 |
+
raise HTTPException(status_code=400, detail="Invalid binary metadata header length.")
|
| 611 |
+
meta_payload: bytes | str = body[4 : 4 + meta_len]
|
| 612 |
+
raw_bytes = body[4 + meta_len :]
|
| 613 |
+
else:
|
| 614 |
+
form = await request.form(max_part_size=1024 * 1024 * 1024)
|
| 615 |
+
raw_meta = form.get("metadata")
|
| 616 |
+
embeddings = form.get("embeddings")
|
| 617 |
+
if raw_meta is None:
|
| 618 |
+
raise HTTPException(status_code=400, detail="Missing 'metadata' part.")
|
| 619 |
+
if embeddings is None or not hasattr(embeddings, "read"):
|
| 620 |
+
raise HTTPException(status_code=400, detail="Missing 'embeddings' file part.")
|
| 621 |
+
meta_payload = await raw_meta.read() if hasattr(raw_meta, "read") else raw_meta
|
| 622 |
+
raw_bytes = await embeddings.read()
|
| 623 |
+
|
| 624 |
try:
|
| 625 |
+
meta = IndexPrecomputedMetadata.model_validate_json(meta_payload)
|
| 626 |
except Exception as exc:
|
| 627 |
raise HTTPException(status_code=400, detail=f"Invalid metadata payload: {exc}") from exc
|
|
|
|
|
|
|
| 628 |
n_docs = len(meta.indexed_texts)
|
| 629 |
dim = int(meta.embedding_dim)
|
| 630 |
expected_bytes = n_docs * dim * 4
|
backend/tests/test_hf_hub_and_space.py
CHANGED
|
@@ -253,3 +253,34 @@ def test_precomputed_webgpu_indexing_and_slice_prepare(tmp_path):
|
|
| 253 |
assert saved.device_label == "WebGPU · Apple Metal"
|
| 254 |
assert saved.health.embedding_dim == 16
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
assert saved.device_label == "WebGPU · Apple Metal"
|
| 254 |
assert saved.health.embedding_dim == 16
|
| 255 |
|
| 256 |
+
# 3. Large (>1024KB) metadata uploaded via raw binary framing (and multipart) succeeds
|
| 257 |
+
large_texts = [f"Doc {i}: " + ("embedding retrieval diagnostics " * 4000) for i in range(12)]
|
| 258 |
+
large_meta = {
|
| 259 |
+
**meta_payload,
|
| 260 |
+
"run_name": "large-webgpu-run",
|
| 261 |
+
"indexed_texts": large_texts,
|
| 262 |
+
"docs_by_field": {"text": large_texts},
|
| 263 |
+
"metadata_by_field": {},
|
| 264 |
+
"labels": None,
|
| 265 |
+
"all_meta_fields": [],
|
| 266 |
+
}
|
| 267 |
+
large_json = json.dumps(large_meta).encode("utf-8")
|
| 268 |
+
assert len(large_json) > 1024 * 1024 # strictly > 1024KB Starlette default
|
| 269 |
+
framed_body = len(large_json).to_bytes(4, "little") + large_json + vecs.tobytes()
|
| 270 |
+
bin_resp = client.post(
|
| 271 |
+
"/api/projects/index-precomputed",
|
| 272 |
+
content=framed_body,
|
| 273 |
+
headers={"Content-Type": "application/octet-stream"},
|
| 274 |
+
)
|
| 275 |
+
assert bin_resp.status_code == 200
|
| 276 |
+
assert "event: complete" in bin_resp.text
|
| 277 |
+
|
| 278 |
+
# Also verify legacy multipart >1024KB form string works without part-size rejection
|
| 279 |
+
mp_resp = client.post(
|
| 280 |
+
"/api/projects/index-precomputed",
|
| 281 |
+
data={"metadata": large_json.decode("utf-8")},
|
| 282 |
+
files={"embeddings": ("embeddings.f32", vecs.tobytes(), "application/octet-stream")},
|
| 283 |
+
)
|
| 284 |
+
assert mp_resp.status_code == 200
|
| 285 |
+
assert "event: complete" in mp_resp.text
|
| 286 |
+
|
frontend/src/api/client.ts
CHANGED
|
@@ -267,25 +267,24 @@ export async function streamIndexPrecomputedRun(
|
|
| 267 |
embeddings: Float32Array,
|
| 268 |
onProgress: (ev: IndexProgressEvent) => void
|
| 269 |
): Promise<RunManifest> {
|
| 270 |
-
|
| 271 |
-
form
|
| 272 |
-
const
|
|
|
|
| 273 |
embeddings.buffer,
|
| 274 |
embeddings.byteOffset,
|
| 275 |
embeddings.byteLength
|
| 276 |
-
);
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
new Blob([copy.buffer], { type: "application/octet-stream" }),
|
| 283 |
-
"embeddings.f32"
|
| 284 |
-
);
|
| 285 |
|
| 286 |
const res = await fetch(`${API_BASE}/api/projects/index-precomputed`, {
|
| 287 |
method: "POST",
|
| 288 |
-
|
|
|
|
| 289 |
});
|
| 290 |
|
| 291 |
if (!res.ok || !res.body) {
|
|
|
|
| 267 |
embeddings: Float32Array,
|
| 268 |
onProgress: (ev: IndexProgressEvent) => void
|
| 269 |
): Promise<RunManifest> {
|
| 270 |
+
// Pack as a single raw binary stream: [uint32_le metaLen][utf8 metaJSON][float32 embeddings].
|
| 271 |
+
// Completely bypasses multipart form parsers and Starlette's 1024KB part-size limits.
|
| 272 |
+
const metaBytes = new TextEncoder().encode(JSON.stringify(meta));
|
| 273 |
+
const embCopy = new Uint8Array(
|
| 274 |
embeddings.buffer,
|
| 275 |
embeddings.byteOffset,
|
| 276 |
embeddings.byteLength
|
| 277 |
+
).slice();
|
| 278 |
+
const header = new ArrayBuffer(4);
|
| 279 |
+
new DataView(header).setUint32(0, metaBytes.byteLength, true);
|
| 280 |
+
const payload = new Blob([header, metaBytes, embCopy], {
|
| 281 |
+
type: "application/octet-stream",
|
| 282 |
+
});
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
const res = await fetch(`${API_BASE}/api/projects/index-precomputed`, {
|
| 285 |
method: "POST",
|
| 286 |
+
headers: { "Content-Type": "application/octet-stream" },
|
| 287 |
+
body: payload,
|
| 288 |
});
|
| 289 |
|
| 290 |
if (!res.ok || !res.body) {
|