File size: 29,921 Bytes
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
b1bc2dc
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1bc2dc
46d70d9
 
 
 
b1bc2dc
 
 
 
 
 
46d70d9
b1bc2dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46d70d9
b1bc2dc
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
from __future__ import annotations

import asyncio
import json
import queue
import threading
import time
import uuid
from collections import Counter
from datetime import datetime, timezone
from typing import Any

import numpy as np
from fastapi import APIRouter, HTTPException, Request, Response
from fastapi.responses import StreamingResponse

from app.config import MAX_CONCURRENT_INDEX_JOBS
from app.engine.bm25 import MultiFieldBM25Index, tokenize_with_spans
from app.engine.diagnostics import cluster_embeddings_2d, compute_corpus_diagnostics
from app.engine.embedder import TokenTelemetry, embedder_cache
from app.engine.facets import compute_crossfilter_facets
from app.engine.hardware import detect_hardware
from app.engine.ingest import load_hf_slice
from app.schemas import (
    DocumentDetail,
    FacetQueryRequest,
    FacetQueryResponse,
    IndexPrecomputedMetadata,
    IndexRunRequest,
    LassoRequest,
    LassoResponse,
    PrepareSliceRequest,
    PrepareSliceResponse,
    ReclusterRequest,
    RunManifest,
)
from app.storage.project_store import project_store

router = APIRouter(prefix="/api/projects", tags=["projects"])

_INDEX_SEMAPHORE = threading.Semaphore(max(1, MAX_CONCURRENT_INDEX_JOBS))


def _point_in_polygon(pts: np.ndarray, poly: list[list[float]]) -> np.ndarray:
    """Vectorized ray-casting point-in-polygon check for lasso selection."""
    n_pts = len(pts)
    inside = np.zeros(n_pts, dtype=bool)
    m = len(poly)
    if m < 3:
        return inside
    x = pts[:, 0].astype(np.float64, copy=False)
    y = pts[:, 1].astype(np.float64, copy=False)
    j = m - 1
    for i in range(m):
        xi, yi = float(poly[i][0]), float(poly[i][1])
        xj, yj = float(poly[j][0]), float(poly[j][1])
        crosses = (yi > y) != (yj > y)
        if np.any(crosses):
            dy = yj - yi
            x_intersect = (xj - xi) * (y[crosses] - yi) / dy + xi
            inside[crosses] ^= x[crosses] < x_intersect
        j = i
    return inside


@router.get("", response_model=list[RunManifest])
def list_projects():
    return project_store.list_runs()


@router.get("/{run_id}", response_model=RunManifest)
def get_project(run_id: str):
    try:
        return project_store.load_run(run_id).manifest
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@router.delete("/{run_id}")
def delete_project(run_id: str):
    project_store.delete_run(run_id)
    return {"deleted": run_id}


@router.get("/{run_id}/atlas-binary")
def get_atlas_binary(run_id: str):
    try:
        run = project_store.load_run(run_id)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return Response(
        content=run.atlas_binary,
        media_type="application/octet-stream",
        headers={
            "X-Ostra-Doc-Count": str(run.manifest.doc_count),
            "X-Ostra-Stride-Floats": "8",
            "Cache-Control": "public, max-age=3600",
        },
    )


@router.get("/{run_id}/docs/{doc_id}", response_model=DocumentDetail)
def get_document_detail(run_id: str, doc_id: int):
    try:
        run = project_store.load_run(run_id)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    n = len(run.indexed_texts)
    if doc_id < 0 or doc_id >= n:
        raise HTTPException(status_code=404, detail=f"doc_id {doc_id} out of range [0, {n - 1}]")

    cid = int(run.cluster_ids[doc_id])
    neighbors = []
    for k_idx in range(min(8, run.nn_indices.shape[1])):
        nid = int(run.nn_indices[doc_id, k_idx])
        neighbors.append(
            {
                "doc_id": nid,
                "cosine": round(float(run.nn_cosines[doc_id, k_idx]), 4),
                "title_preview": run.doc_title_preview(nid),
                "label": run.labels[nid] if run.labels is not None else None,
            }
        )

    return DocumentDetail(
        doc_id=doc_id,
        indexed_text=run.indexed_texts[doc_id],
        fields={f: vals[doc_id] for f, vals in run.docs_by_field.items()},
        metadata={mf: vals[doc_id] for mf, vals in run.metadata_by_field.items()},
        label=run.labels[doc_id] if run.labels is not None else None,
        cluster_id=cid,
        cluster_label=run.cluster_label_map.get(cid, "Unclustered"),
        x=round(float(run.coords_2d[doc_id, 0]), 5),
        y=round(float(run.coords_2d[doc_id, 1]), 5),
        token_count=int(run.token_counts[doc_id]),
        max_seq_len=run.manifest.health.max_seq_len,
        is_truncated=bool(run.is_truncated[doc_id]),
        truncation_ratio=round(float(run.truncation_ratio[doc_id]), 4),
        truncated_char_offset=run.truncated_char_offsets[doc_id],
        subword_fertility=round(float(run.subword_fertility[doc_id]), 3),
        hubness_nk=int(run.hubness_nk[doc_id]),
        purity=round(float(run.purity[doc_id]), 4),
        is_near_dup=bool(run.is_near_dup[doc_id]),
        neighbors=neighbors,
    )


@router.post("/{run_id}/lasso", response_model=LassoResponse)
def inspect_lasso(run_id: str, req: LassoRequest):
    try:
        run = project_store.load_run(run_id)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc

    mask = _point_in_polygon(run.coords_2d, req.polygon)
    doc_ids = np.flatnonzero(mask).tolist()
    if not doc_ids:
        return LassoResponse(
            count=0,
            doc_ids=[],
            top_terms=[],
            truncation_rate=0.0,
            avg_hubness=0.0,
            label_distribution={},
            sample_docs=[],
        )

    term_counts: Counter[str] = Counter()
    for did in doc_ids[:400]:
        for raw, _, _, _ in tokenize_with_spans(run.indexed_texts[did]):
            if len(raw) >= 3 and not raw.isdigit():
                term_counts[raw.lower()] += 1
    top_terms = [t for t, _ in term_counts.most_common(8)]

    trunc_rate = float(run.is_truncated[doc_ids].mean())
    avg_hub = float(run.hubness_nk[doc_ids].mean())
    lbl_dist: dict[str, int] = {}
    if run.labels is not None:
        c_lbl = Counter(run.labels[did] for did in doc_ids)
        lbl_dist = dict(c_lbl.most_common(10))

    sample_docs = [
        {
            "doc_id": did,
            "title_preview": run.doc_title_preview(did),
            "label": run.labels[did] if run.labels is not None else None,
            "hubness_nk": int(run.hubness_nk[did]),
            "is_truncated": bool(run.is_truncated[did]),
        }
        for did in doc_ids[:25]
    ]

    return LassoResponse(
        count=len(doc_ids),
        doc_ids=doc_ids,
        top_terms=top_terms,
        truncation_rate=round(trunc_rate, 4),
        avg_hubness=round(avg_hub, 2),
        label_distribution=lbl_dist,
        sample_docs=sample_docs,
    )


@router.post("/{run_id}/facets", response_model=FacetQueryResponse)
def query_facets(run_id: str, req: FacetQueryRequest):
    try:
        run = project_store.load_run(run_id)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return compute_crossfilter_facets(run, req)


@router.post("/{run_id}/recluster", response_model=RunManifest)
def recluster_project(run_id: str, req: ReclusterRequest):
    """Live sub-50ms re-clustering at Coarse / Balanced / Fine / Pinpoint granularity or drill-down split."""
    try:
        run = project_store.load_run(run_id)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc

    cluster_ids, clusters = cluster_embeddings_2d(
        coords_2d=run.coords_2d,
        texts=run.indexed_texts,
        embeddings=run.embeddings,
        granularity=req.granularity,
        existing_cluster_ids=run.cluster_ids if req.focus_cluster_id is not None else None,
        focus_cluster_id=req.focus_cluster_id,
        sub_clusters=req.sub_clusters,
    )
    return project_store.update_run_clusters(run_id, cluster_ids, clusters)


@router.post("/index")
async def index_hf_dataset_stream(req: IndexRunRequest):
    """Stream real-time SSE indexing progress: HF ingest -> Tokenize/Embed -> BM25 -> Diagnostics."""
    q: queue.Queue[dict[str, Any] | None] = queue.Queue()

    def emit(event: str, payload: dict[str, Any]) -> None:
        q.put({"event": event, "data": payload})

    def worker() -> None:
        acquired = False
        try:
            hw = detect_hardware()
            effective_max_rows = min(req.max_rows, hw.max_rows_limit)
            effective_batch_size = min(req.batch_size, hw.default_batch_size) if (hw.is_hf_space and not hw.cuda_available) else req.batch_size

            if not _INDEX_SEMAPHORE.acquire(blocking=False):
                emit(
                    "progress",
                    {
                        "stage": "queue",
                        "message": "Another indexing job is running on this Space — waiting for slot…",
                        "percent": 2.0,
                    },
                )
                _INDEX_SEMAPHORE.acquire()
            acquired = True

            t_start = time.perf_counter()
            emit(
                "progress",
                {
                    "stage": "ingest",
                    "message": f"Streaming up to {effective_max_rows:,} rows from {req.dataset_id}…",
                    "percent": 5.0,
                },
            )
            sliced = load_hf_slice(
                dataset_id=req.dataset_id.strip(),
                config=req.config,
                split=req.split,
                max_rows=effective_max_rows,
                dense_fields=req.dense_fields,
                dense_template=req.dense_template,
                bm25_fields=req.bm25_fields,
                metadata_fields=req.metadata_fields,
                label_field=req.label_field,
            )
            indexed_texts: list[str] = sliced["indexed_texts"]
            n_docs = len(indexed_texts)
            if n_docs < 5:
                raise ValueError(
                    f"Only {n_docs} non-empty documents found with template '{req.dense_template}'."
                )

            emit(
                "progress",
                {
                    "stage": "model_load",
                    "message": f"Loading embedding model {req.model_id}…",
                    "percent": 14.0,
                    "doc_count": n_docs,
                },
            )
            embedder = embedder_cache.get(
                model_id=req.model_id.strip(),
                preferred_device=req.preferred_device,
                max_seq_len_override=req.max_seq_len,
            )

            emit(
                "progress",
                {
                    "stage": "tokenize",
                    "message": f"Auditing tokenization & silent truncation on {n_docs:,} docs…",
                    "percent": 20.0,
                    "device": embedder.device_label,
                    "backend": embedder.backend_name,
                },
            )
            telemetry = embedder.inspect_truncation_and_fertility(
                indexed_texts, prefix=req.doc_prefix
            )
            trunc_so_far = int(telemetry.is_truncated.sum())

            emit(
                "progress",
                {
                    "stage": "embed",
                    "message": f"Embedding {n_docs:,} docs on {embedder.device_label}…",
                    "percent": 25.0,
                    "done": 0,
                    "total": n_docs,
                    "truncated_count": trunc_so_far,
                    "device": embedder.device_label,
                    "backend": embedder.backend_name,
                },
            )

            t_embed0 = time.perf_counter()

            def on_embed_progress(done: int, total: int, rate: float) -> None:
                pct = 25.0 + 43.0 * (done / max(total, 1))
                emit(
                    "progress",
                    {
                        "stage": "embed",
                        "message": f"Embedded {done:,}/{total:,} docs ({rate:.0f} docs/s)",
                        "percent": round(pct, 1),
                        "done": done,
                        "total": total,
                        "docs_per_sec": round(rate, 1),
                        "truncated_count": trunc_so_far,
                        "device": embedder.device_label,
                        "backend": embedder.backend_name,
                    },
                )

            embeddings = embedder.encode_corpus(
                indexed_texts,
                prefix=req.doc_prefix,
                batch_size=effective_batch_size,
                progress_cb=on_embed_progress,
            )
            embed_seconds = max(time.perf_counter() - t_embed0, 1e-4)
            docs_per_sec = n_docs / embed_seconds

            emit(
                "progress",
                {
                    "stage": "bm25",
                    "message": f"Building multi-field sparse BM25 index ({', '.join(req.bm25_fields)})…",
                    "percent": 72.0,
                    "truncated_count": trunc_so_far,
                    "device": embedder.device_label,
                },
            )
            bm25 = MultiFieldBM25Index.build(
                docs_by_field=sliced["docs_by_field"],
                fields=req.bm25_fields,
            )

            def on_diag_progress(msg: str, frac: float) -> None:
                emit(
                    "progress",
                    {
                        "stage": "diagnostics",
                        "message": msg,
                        "percent": round(75.0 + 20.0 * frac, 1),
                        "truncated_count": trunc_so_far,
                        "device": embedder.device_label,
                    },
                )

            diag = compute_corpus_diagnostics(
                embeddings=embeddings,
                texts=indexed_texts,
                telemetry=telemetry,
                labels=sliced["labels"],
                use_umap=True,
                progress_cb=on_diag_progress,
            )

            run_id = f"run_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            short_ds = req.dataset_id.split("/")[-1]
            short_mod = req.model_id.split("/")[-1]
            run_name = req.run_name.strip() if req.run_name and req.run_name.strip() else f"{short_ds} · {short_mod}"

            initial_weights = {
                f: float(req.bm25_initial_weights.get(f, 1.0))
                for f in req.bm25_fields
            }

            manifest = RunManifest(
                run_id=run_id,
                run_name=run_name,
                created_at=datetime.now(timezone.utc).isoformat(),
                dataset_id=req.dataset_id.strip(),
                config=req.config,
                split=req.split,
                max_rows=effective_max_rows,
                doc_count=n_docs,
                dense_fields=req.dense_fields,
                dense_template=req.dense_template,
                bm25_fields=req.bm25_fields,
                bm25_initial_weights=initial_weights,
                metadata_fields=sliced["all_meta_fields"],
                label_field=req.label_field,
                model_id=req.model_id.strip(),
                doc_prefix=req.doc_prefix,
                query_prefix=req.query_prefix,
                backend_used=embedder.backend_name,
                device_label=embedder.device_label,
                embed_seconds=round(embed_seconds, 2),
                docs_per_sec=round(docs_per_sec, 1),
                health=diag.health,
                clusters=diag.clusters,
                contours=diag.contours,
                coord_bounds=diag.coord_bounds,
            )

            emit(
                "progress",
                {
                    "stage": "save",
                    "message": "Persisting Parquet + binary Atlas cache to .ostra/…",
                    "percent": 97.0,
                },
            )
            loaded = project_store.save_run(
                manifest=manifest,
                embeddings=embeddings,
                diag=diag,
                telemetry=telemetry,
                bm25=bm25,
                indexed_texts=indexed_texts,
                docs_by_field=sliced["docs_by_field"],
                metadata_by_field=sliced["metadata_by_field"],
                labels=sliced["labels"],
            )

            emit(
                "complete",
                {
                    "run_id": loaded.manifest.run_id,
                    "elapsed_seconds": round(time.perf_counter() - t_start, 2),
                    "manifest": loaded.manifest.model_dump(),
                },
            )
        except Exception as exc:
            emit("error", {"message": str(exc)})
        finally:
            if acquired:
                _INDEX_SEMAPHORE.release()
            q.put(None)

    threading.Thread(target=worker, daemon=True).start()

    def _next_event() -> dict[str, Any] | None | str:
        try:
            return q.get(timeout=10.0)
        except queue.Empty:
            return "__keepalive__"

    async def event_generator():
        while True:
            item = await asyncio.to_thread(_next_event)
            if item == "__keepalive__":
                # Prevent HF Spaces reverse proxy idle timeouts during model download / UMAP
                yield ": keepalive\n\n"
                continue
            if item is None:
                break
            yield f"event: {item['event']}\ndata: {json.dumps(item['data'])}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )


@router.post("/prepare-slice", response_model=PrepareSliceResponse)
def prepare_hf_slice_for_client(req: PrepareSliceRequest):
    """
    Stream & format an HF dataset slice so the browser can compute dense embeddings
    locally on the user's GPU (WebGPU/Metal) or CPU (WASM) with zero server GPU/CPU load.
    """
    hw = detect_hardware()
    # Browser WebGPU/WASM handles heavier slices cleanly even on CPU Basic HF Spaces
    client_row_cap = 5000 if hw.is_hf_space else max(hw.max_rows_limit, 5000)
    effective_max_rows = min(req.max_rows, client_row_cap)
    try:
        sliced = load_hf_slice(
            dataset_id=req.dataset_id.strip(),
            config=req.config,
            split=req.split,
            max_rows=effective_max_rows,
            dense_fields=req.dense_fields,
            dense_template=req.dense_template,
            bm25_fields=req.bm25_fields,
            metadata_fields=req.metadata_fields,
            label_field=req.label_field,
        )
    except Exception as exc:
        raise HTTPException(
            status_code=400,
            detail=f"Failed to stream Hugging Face dataset '{req.dataset_id}': {exc}",
        ) from exc

    n_docs = len(sliced["indexed_texts"])
    if n_docs < 5:
        raise HTTPException(
            status_code=400,
            detail=f"Only {n_docs} non-empty documents found with template '{req.dense_template}'.",
        )
    return PrepareSliceResponse(
        doc_count=n_docs,
        indexed_texts=sliced["indexed_texts"],
        docs_by_field=sliced["docs_by_field"],
        metadata_by_field=sliced["metadata_by_field"],
        labels=sliced["labels"],
        all_text_fields=sliced["all_text_fields"],
        all_meta_fields=sliced["all_meta_fields"],
    )


def _telemetry_from_precomputed(
    meta: IndexPrecomputedMetadata,
    indexed_texts: list[str],
) -> TokenTelemetry:
    n_docs = len(indexed_texts)
    t = meta.telemetry
    if (
        t is not None
        and len(t.token_counts) == n_docs
        and len(t.is_truncated) == n_docs
        and len(t.truncation_ratio) == n_docs
        and len(t.truncated_char_offsets) == n_docs
        and len(t.subword_fertility) == n_docs
    ):
        return TokenTelemetry(
            token_counts=np.asarray(t.token_counts, dtype=np.int32),
            is_truncated=np.asarray(t.is_truncated, dtype=bool),
            truncation_ratio=np.asarray(t.truncation_ratio, dtype=np.float32),
            truncated_char_offsets=list(t.truncated_char_offsets),
            subword_fertility=np.asarray(t.subword_fertility, dtype=np.float32),
            max_seq_len=max(int(t.max_seq_len), 32),
        )

    # Lightweight fallback if client omitted token telemetry
    max_seq = 512
    token_counts = np.empty(n_docs, dtype=np.int32)
    is_truncated = np.zeros(n_docs, dtype=bool)
    truncation_ratio = np.zeros(n_docs, dtype=np.float32)
    truncated_offsets: list[int | None] = [None] * n_docs
    subword_fertility = np.ones(n_docs, dtype=np.float32)
    for i, text in enumerate(indexed_texts):
        est = max(1, int(round(len(text.split()) * 1.3)) + 2)
        token_counts[i] = est
        if est > max_seq:
            is_truncated[i] = True
            truncation_ratio[i] = float((est - max_seq) / est)
            truncated_offsets[i] = int(len(text) * (max_seq / est))
    return TokenTelemetry(
        token_counts=token_counts,
        is_truncated=is_truncated,
        truncation_ratio=truncation_ratio,
        truncated_char_offsets=truncated_offsets,
        subword_fertility=subword_fertility,
        max_seq_len=max_seq,
    )


@router.post("/index-precomputed")
async def index_precomputed_embeddings_stream(request: Request):
    """
    Finalize a run whose dense embeddings were computed on the user's device
    (WebGPU Metal/GPU or Browser WASM CPU): builds BM25, corpus diagnostics, UMAP 2D,
    and persists Parquet/Atlas cache without ever loading embedding weights on the Space server.

    Supports both:
      1. Raw binary `application/octet-stream` framed as:
         [4-byte little-endian uint32 metadata_byte_len][UTF-8 metadata JSON][float32 embeddings]
         (bypasses multipart parsers & part-size limits completely)
      2. `multipart/form-data` (`metadata` file or string + `embeddings` file) with 1 GB part limit.
    """
    content_type = (request.headers.get("content-type") or "").lower()
    if content_type.startswith("application/octet-stream"):
        body = await request.body()
        if len(body) < 4:
            raise HTTPException(status_code=400, detail="Truncated binary payload.")
        meta_len = int.from_bytes(body[:4], "little")
        if meta_len <= 0 or 4 + meta_len > len(body):
            raise HTTPException(status_code=400, detail="Invalid binary metadata header length.")
        meta_payload: bytes | str = body[4 : 4 + meta_len]
        raw_bytes = body[4 + meta_len :]
    else:
        form = await request.form(max_part_size=1024 * 1024 * 1024)
        raw_meta = form.get("metadata")
        embeddings = form.get("embeddings")
        if raw_meta is None:
            raise HTTPException(status_code=400, detail="Missing 'metadata' part.")
        if embeddings is None or not hasattr(embeddings, "read"):
            raise HTTPException(status_code=400, detail="Missing 'embeddings' file part.")
        meta_payload = await raw_meta.read() if hasattr(raw_meta, "read") else raw_meta
        raw_bytes = await embeddings.read()

    try:
        meta = IndexPrecomputedMetadata.model_validate_json(meta_payload)
    except Exception as exc:
        raise HTTPException(status_code=400, detail=f"Invalid metadata payload: {exc}") from exc
    n_docs = len(meta.indexed_texts)
    dim = int(meta.embedding_dim)
    expected_bytes = n_docs * dim * 4
    if n_docs < 5:
        raise HTTPException(status_code=400, detail="At least 5 documents are required.")
    if len(raw_bytes) != expected_bytes:
        raise HTTPException(
            status_code=400,
            detail=f"Embedding buffer size mismatch: got {len(raw_bytes)} bytes, expected {expected_bytes} ({n_docs}x{dim} float32).",
        )

    vecs = np.frombuffer(raw_bytes, dtype=np.float32).reshape(n_docs, dim).copy()
    if not np.all(np.isfinite(vecs)):
        raise HTTPException(status_code=400, detail="Embeddings contain NaN or Inf values.")
    norms = np.linalg.norm(vecs, axis=1, keepdims=True)
    vecs = (vecs / np.maximum(norms, 1e-12)).astype(np.float32)

    q: queue.Queue[dict[str, Any] | None] = queue.Queue()

    def emit(event: str, payload: dict[str, Any]) -> None:
        q.put({"event": event, "data": payload})

    def worker() -> None:
        try:
            t_start = time.perf_counter()
            telemetry = _telemetry_from_precomputed(meta, meta.indexed_texts)
            trunc_so_far = int(telemetry.is_truncated.sum())

            emit(
                "progress",
                {
                    "stage": "bm25",
                    "message": f"Building multi-field sparse BM25 index ({', '.join(meta.bm25_fields)})…",
                    "percent": 74.0,
                    "truncated_count": trunc_so_far,
                    "device": meta.device_label,
                },
            )
            bm25 = MultiFieldBM25Index.build(
                docs_by_field=meta.docs_by_field,
                fields=meta.bm25_fields,
            )

            def on_diag_progress(msg: str, frac: float) -> None:
                emit(
                    "progress",
                    {
                        "stage": "diagnostics",
                        "message": msg,
                        "percent": round(77.0 + 18.0 * frac, 1),
                        "truncated_count": trunc_so_far,
                        "device": meta.device_label,
                    },
                )

            diag = compute_corpus_diagnostics(
                embeddings=vecs,
                texts=meta.indexed_texts,
                telemetry=telemetry,
                labels=meta.labels,
                use_umap=True,
                progress_cb=on_diag_progress,
            )

            run_id = f"run_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
            short_ds = meta.dataset_id.split("/")[-1]
            short_mod = meta.model_id.split("/")[-1]
            run_name = (
                meta.run_name.strip()
                if meta.run_name and meta.run_name.strip()
                else f"{short_ds} · {short_mod}"
            )

            initial_weights = {
                f: float(meta.bm25_initial_weights.get(f, 1.0))
                for f in meta.bm25_fields
            }
            all_meta_fields = meta.all_meta_fields or list(meta.metadata_by_field.keys())

            manifest = RunManifest(
                run_id=run_id,
                run_name=run_name,
                created_at=datetime.now(timezone.utc).isoformat(),
                dataset_id=meta.dataset_id.strip(),
                config=meta.config,
                split=meta.split,
                max_rows=meta.max_rows,
                doc_count=n_docs,
                dense_fields=meta.dense_fields,
                dense_template=meta.dense_template,
                bm25_fields=meta.bm25_fields,
                bm25_initial_weights=initial_weights,
                metadata_fields=all_meta_fields,
                label_field=meta.label_field,
                model_id=meta.model_id.strip(),
                doc_prefix=meta.doc_prefix,
                query_prefix=meta.query_prefix,
                backend_used=meta.backend_used,
                device_label=meta.device_label,
                embed_seconds=round(max(meta.embed_seconds, 0.01), 2),
                docs_per_sec=round(meta.docs_per_sec, 1),
                health=diag.health,
                clusters=diag.clusters,
                contours=diag.contours,
                coord_bounds=diag.coord_bounds,
            )

            emit(
                "progress",
                {
                    "stage": "save",
                    "message": "Persisting Parquet + binary Atlas cache…",
                    "percent": 97.0,
                    "device": meta.device_label,
                },
            )
            loaded = project_store.save_run(
                manifest=manifest,
                embeddings=vecs,
                diag=diag,
                telemetry=telemetry,
                bm25=bm25,
                indexed_texts=meta.indexed_texts,
                docs_by_field=meta.docs_by_field,
                metadata_by_field=meta.metadata_by_field,
                labels=meta.labels,
            )

            emit(
                "complete",
                {
                    "run_id": loaded.manifest.run_id,
                    "elapsed_seconds": round(time.perf_counter() - t_start, 2),
                    "manifest": loaded.manifest.model_dump(),
                },
            )
        except Exception as exc:
            emit("error", {"message": str(exc)})
        finally:
            q.put(None)

    threading.Thread(target=worker, daemon=True).start()

    def _next_event() -> dict[str, Any] | None | str:
        try:
            return q.get(timeout=10.0)
        except queue.Empty:
            return "__keepalive__"

    async def event_generator():
        while True:
            item = await asyncio.to_thread(_next_event)
            if item == "__keepalive__":
                yield ": keepalive\n\n"
                continue
            if item is None:
                break
            yield f"event: {item['event']}\ndata: {json.dumps(item['data'])}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )