File size: 26,886 Bytes
dbf7313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse

from slop_farmer.config import PrSearchRefreshOptions
from slop_farmer.data.ghreplica_api import GhReplicaProbeUnavailableError, GhrProbeClient
from slop_farmer.data.snapshot_materialize import materialize_hf_dataset_snapshot
from slop_farmer.data.snapshot_paths import (
    CURRENT_ANALYSIS_MANIFEST_PATH,
    default_hf_materialize_dir,
)
from slop_farmer.reports.analysis_service import (
    get_analysis_best,
    get_analysis_meta_bug,
    get_analysis_status,
    get_pr_analysis,
    list_analysis_duplicate_prs,
    list_analysis_meta_bugs,
)
from slop_farmer.reports.pr_search_service import (
    get_pr_search_cluster,
    get_pr_search_clusters,
    get_pr_search_contributor_pulls,
    get_pr_search_pull_contributor,
    get_pr_search_similar_lookup,
    get_pr_search_status,
    list_pr_search_clusters,
    run_pr_search_refresh,
)
from slop_farmer.reports.read_views import (
    check_issue_cluster_membership,
    get_contributor,
    get_contributor_risk,
    get_contributor_status,
    get_issue_best,
    get_issue_cluster,
    get_issue_cluster_status,
    get_issue_clusters_for_pr,
    get_snapshot_surfaces,
    list_contributors,
    list_issue_clusters,
    list_issue_duplicate_prs,
)


@dataclass(slots=True)
class PrSearchApiSettings:
    default_repo: str | None
    index_path: Path
    output_dir: Path
    snapshot_dir: Path | None = None
    hf_repo_id: str | None = None
    hf_revision: str | None = None
    hf_materialize_dir: Path | None = None
    ghr_base_url: str | None = None
    http_timeout: int = 180
    http_max_retries: int = 5
    refresh_if_missing: bool = False
    rebuild_on_start: bool = False
    include_drafts: bool = False
    include_closed: bool = False
    similar_limit_default: int = 10
    similar_limit_max: int = 50
    candidate_limit_default: int = 5
    candidate_limit_max: int = 20
    cluster_list_limit_default: int = 50
    cluster_list_limit_max: int = 200
    issue_list_limit_default: int = 50
    issue_list_limit_max: int = 200
    contributor_list_limit_default: int = 50
    contributor_list_limit_max: int = 200
    probe_limit_default: int = 10
    probe_limit_max: int = 25

    @classmethod
    def from_env(cls) -> PrSearchApiSettings:
        output_dir = Path(os.environ.get("OUTPUT_DIR", "data")).resolve()
        index_path = Path(
            os.environ.get("INDEX_PATH", str(output_dir / "state" / "pr-search.duckdb"))
        ).resolve()
        snapshot_dir = _env_path("SNAPSHOT_DIR")
        hf_materialize_dir = _env_path("HF_MATERIALIZE_DIR")
        return cls(
            default_repo=os.environ.get("DEFAULT_REPO"),
            index_path=index_path,
            output_dir=output_dir,
            snapshot_dir=snapshot_dir,
            hf_repo_id=os.environ.get("HF_REPO_ID"),
            hf_revision=os.environ.get("HF_REVISION"),
            hf_materialize_dir=hf_materialize_dir,
            ghr_base_url=os.environ.get("GHR_BASE_URL"),
            http_timeout=_env_int("HTTP_TIMEOUT", 180),
            http_max_retries=_env_int("HTTP_MAX_RETRIES", 5),
            refresh_if_missing=_env_bool("REFRESH_IF_MISSING", False),
            rebuild_on_start=_env_bool("REBUILD_ON_START", False),
            include_drafts=_env_bool("INCLUDE_DRAFTS", False),
            include_closed=_env_bool("INCLUDE_CLOSED", False),
            similar_limit_default=_env_int("SIMILAR_LIMIT_DEFAULT", 10),
            similar_limit_max=_env_int("SIMILAR_LIMIT_MAX", 50),
            candidate_limit_default=_env_int("CANDIDATE_LIMIT_DEFAULT", 5),
            candidate_limit_max=_env_int("CANDIDATE_LIMIT_MAX", 20),
            cluster_list_limit_default=_env_int("CLUSTER_LIST_LIMIT_DEFAULT", 50),
            cluster_list_limit_max=_env_int("CLUSTER_LIST_LIMIT_MAX", 200),
            issue_list_limit_default=_env_int("ISSUE_LIST_LIMIT_DEFAULT", 50),
            issue_list_limit_max=_env_int("ISSUE_LIST_LIMIT_MAX", 200),
            contributor_list_limit_default=_env_int("CONTRIBUTOR_LIST_LIMIT_DEFAULT", 50),
            contributor_list_limit_max=_env_int("CONTRIBUTOR_LIST_LIMIT_MAX", 200),
            probe_limit_default=_env_int("PROBE_LIMIT_DEFAULT", 10),
            probe_limit_max=_env_int("PROBE_LIMIT_MAX", 25),
        )


def create_app(settings: PrSearchApiSettings | None = None) -> FastAPI:
    api_settings = settings or PrSearchApiSettings.from_env()

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.settings = api_settings
        app.state.ready = False
        app.state.startup_error = None
        try:
            _bootstrap_snapshot_assets(api_settings)
            _bootstrap_index(api_settings)
            app.state.ready = _is_ready(api_settings)
        except Exception as exc:
            app.state.startup_error = str(exc)
        yield

    app = FastAPI(title="slop PR search API", version="0.1.1", lifespan=lifespan)

    @app.exception_handler(ValueError)
    async def handle_value_error(_request: Request, exc: ValueError) -> JSONResponse:
        status_code = 404 if _looks_not_found(exc) else 400
        return JSONResponse({"detail": str(exc)}, status_code=status_code)

    @app.exception_handler(GhReplicaProbeUnavailableError)
    async def handle_probe_unavailable(
        _request: Request, exc: GhReplicaProbeUnavailableError
    ) -> JSONResponse:
        return JSONResponse({"detail": str(exc)}, status_code=exc.status_code)

    @app.get("/healthz")
    async def healthz() -> dict[str, bool]:
        return {"ok": True}

    @app.get("/readyz")
    async def readyz(request: Request) -> JSONResponse:
        settings = request.app.state.settings
        error = request.app.state.startup_error
        ready = request.app.state.ready and _is_ready(settings)
        if ready:
            return JSONResponse({"ok": True})
        detail = error or _readiness_detail(settings)
        return JSONResponse({"ok": False, "detail": detail}, status_code=503)

    @app.get("/v1/repos/{owner}/{repo}/status")
    async def repo_status(owner: str, repo: str, request: Request) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        status = get_pr_search_status(settings.index_path, repo=repo_slug)
        issue_snapshot_dir = _surface_snapshot_dir(settings, repo_slug, surface="issues")
        contributor_snapshot_dir = _surface_snapshot_dir(
            settings, repo_slug, surface="contributors"
        )
        return {
            **status,
            "surfaces": {
                "issues": get_snapshot_surfaces(issue_snapshot_dir)["issues"],
                "contributors": get_snapshot_surfaces(contributor_snapshot_dir)["contributors"],
            },
        }

    @app.get("/v1/repos/{owner}/{repo}/pulls/{number}/similar")
    async def pr_similar(
        owner: str,
        repo: str,
        number: int,
        request: Request,
        limit: int | None = None,
        mode: Literal["auto", "indexed", "live"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_search_similar_lookup(
            settings.index_path,
            repo=repo_slug,
            pr_number=number,
            limit=_limit(
                limit, default=settings.similar_limit_default, maximum=settings.similar_limit_max
            ),
            mode=mode,
            client=_probe_client(settings),
        )

    @app.get("/v1/repos/{owner}/{repo}/pulls/{number}/clusters")
    async def pr_clusters(
        owner: str,
        repo: str,
        number: int,
        request: Request,
        limit: int | None = None,
        mode: Literal["auto", "indexed", "live"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_search_clusters(
            settings.index_path,
            repo=repo_slug,
            pr_number=number,
            limit=_limit(
                limit,
                default=settings.candidate_limit_default,
                maximum=settings.candidate_limit_max,
            ),
            mode=mode,
            client=_probe_client(settings),
        )

    @app.get("/v1/repos/{owner}/{repo}/clusters/{cluster_id}")
    async def cluster_view(
        owner: str,
        repo: str,
        cluster_id: str,
        request: Request,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_search_cluster(settings.index_path, repo=repo_slug, cluster_id=cluster_id)

    @app.get("/v1/repos/{owner}/{repo}/clusters")
    async def cluster_list(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_pr_search_clusters(
            settings.index_path,
            repo=repo_slug,
            limit=_limit(
                limit,
                default=settings.cluster_list_limit_default,
                maximum=settings.cluster_list_limit_max,
            ),
        )

    @app.get("/v1/repos/{owner}/{repo}/contributors/{login}/pulls")
    async def contributor_pulls(
        owner: str,
        repo: str,
        login: str,
        request: Request,
        limit: int | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_search_contributor_pulls(
            settings.index_path,
            repo=repo_slug,
            author_login=login,
            limit=_limit(
                limit, default=settings.similar_limit_default, maximum=settings.similar_limit_max
            ),
        )

    @app.get("/v1/repos/{owner}/{repo}/pulls/{number}/contributor")
    async def pull_contributor(
        owner: str,
        repo: str,
        number: int,
        request: Request,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_search_pull_contributor(settings.index_path, repo=repo_slug, pr_number=number)

    @app.get("/v1/repos/{owner}/{repo}/analysis/status")
    async def analysis_status(
        owner: str,
        repo: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_analysis_status(
            settings.index_path,
            repo=repo_slug,
            variant=variant,
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/pulls/{number}/analysis")
    async def pr_analysis(
        owner: str,
        repo: str,
        number: int,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_pr_analysis(
            settings.index_path,
            repo=repo_slug,
            pr_number=number,
            variant=variant,
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/analysis/meta-bugs")
    async def analysis_meta_bugs(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_analysis_meta_bugs(
            settings.index_path,
            repo=repo_slug,
            variant=variant,
            limit=_limit(
                limit,
                default=settings.cluster_list_limit_default,
                maximum=settings.cluster_list_limit_max,
            ),
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/analysis/meta-bugs/{cluster_id}")
    async def analysis_meta_bug(
        owner: str,
        repo: str,
        cluster_id: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_analysis_meta_bug(
            settings.index_path,
            repo=repo_slug,
            cluster_id=cluster_id,
            variant=variant,
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/analysis/duplicate-prs")
    async def analysis_duplicate_prs(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_analysis_duplicate_prs(
            settings.index_path,
            repo=repo_slug,
            variant=variant,
            limit=_limit(
                limit,
                default=settings.cluster_list_limit_default,
                maximum=settings.cluster_list_limit_max,
            ),
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/analysis/best")
    async def analysis_best(
        owner: str,
        repo: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
        snapshot_id: str | None = None,
        analysis_id: str | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_analysis_best(
            settings.index_path,
            repo=repo_slug,
            variant=variant,
            snapshot_id=snapshot_id,
            analysis_id=analysis_id,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/status")
    async def issue_status(
        owner: str,
        repo: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_issue_cluster_status(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/clusters")
    async def issue_clusters(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_issue_clusters(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            limit=_limit(
                limit,
                default=settings.issue_list_limit_default,
                maximum=settings.issue_list_limit_max,
            ),
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/clusters/{cluster_id}")
    async def issue_cluster(
        owner: str,
        repo: str,
        cluster_id: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_issue_cluster(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            cluster_id=cluster_id,
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/pulls/{number}")
    async def issue_clusters_for_pr(
        owner: str,
        repo: str,
        number: int,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_issue_clusters_for_pr(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            pr_number=number,
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/pulls/{number}/membership")
    async def issue_membership_for_pr(
        owner: str,
        repo: str,
        number: int,
        request: Request,
        cluster_id: str | None = None,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return check_issue_cluster_membership(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            pr_number=number,
            cluster_id=cluster_id,
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/duplicate-prs")
    async def issue_duplicate_prs(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_issue_duplicate_prs(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            limit=_limit(
                limit,
                default=settings.issue_list_limit_default,
                maximum=settings.issue_list_limit_max,
            ),
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/issues/best")
    async def issue_best(
        owner: str,
        repo: str,
        request: Request,
        variant: Literal["auto", "hybrid", "deterministic"] = "auto",
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_issue_best(
            _surface_snapshot_dir(settings, repo_slug, surface="issues"),
            variant=variant,
        )

    @app.get("/v1/repos/{owner}/{repo}/contributors/status")
    async def contributor_status(
        owner: str,
        repo: str,
        request: Request,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_contributor_status(
            _surface_snapshot_dir(settings, repo_slug, surface="contributors")
        )

    @app.get("/v1/repos/{owner}/{repo}/contributors")
    async def contributors(
        owner: str,
        repo: str,
        request: Request,
        limit: int | None = None,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return list_contributors(
            _surface_snapshot_dir(settings, repo_slug, surface="contributors"),
            limit=_limit(
                limit,
                default=settings.contributor_list_limit_default,
                maximum=settings.contributor_list_limit_max,
            ),
        )

    @app.get("/v1/repos/{owner}/{repo}/contributors/{login}")
    async def contributor(
        owner: str,
        repo: str,
        login: str,
        request: Request,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_contributor(
            _surface_snapshot_dir(settings, repo_slug, surface="contributors"),
            author_login=login,
        )

    @app.get("/v1/repos/{owner}/{repo}/contributors/{login}/risk")
    async def contributor_risk(
        owner: str,
        repo: str,
        login: str,
        request: Request,
    ) -> dict[str, Any]:
        settings = request.app.state.settings
        repo_slug = _repo_slug(settings, owner, repo)
        return get_contributor_risk(
            _surface_snapshot_dir(settings, repo_slug, surface="contributors"),
            author_login=login,
        )

    return app


def _bootstrap_index(settings: PrSearchApiSettings) -> None:
    settings.output_dir.mkdir(parents=True, exist_ok=True)
    settings.index_path.parent.mkdir(parents=True, exist_ok=True)
    if not _needs_refresh(settings):
        return
    if settings.snapshot_dir is None and settings.hf_repo_id is None:
        return
    run_pr_search_refresh(
        PrSearchRefreshOptions(
            snapshot_dir=settings.snapshot_dir,
            output_dir=settings.output_dir,
            db=settings.index_path,
            hf_repo_id=settings.hf_repo_id,
            hf_revision=settings.hf_revision,
            hf_materialize_dir=settings.hf_materialize_dir,
            include_drafts=settings.include_drafts,
            include_closed=settings.include_closed,
        )
    )


def _bootstrap_snapshot_assets(settings: PrSearchApiSettings) -> None:
    if settings.snapshot_dir is not None or settings.hf_repo_id is None:
        return
    materialize_dir = settings.hf_materialize_dir or default_hf_materialize_dir(
        settings.output_dir,
        settings.hf_repo_id,
        settings.hf_revision,
    )
    materialize_hf_dataset_snapshot(
        repo_id=settings.hf_repo_id,
        local_dir=materialize_dir,
        revision=settings.hf_revision,
    )


def _needs_refresh(settings: PrSearchApiSettings) -> bool:
    if settings.rebuild_on_start:
        return True
    if not settings.refresh_if_missing:
        return False
    return not _is_ready(settings)


def _is_ready(settings: PrSearchApiSettings) -> bool:
    if not settings.index_path.exists():
        return False
    try:
        get_pr_search_status(settings.index_path, repo=settings.default_repo)
    except Exception:
        return False
    return True


def _readiness_detail(settings: PrSearchApiSettings) -> str:
    if not settings.index_path.exists():
        return f"index not found at {settings.index_path}"
    try:
        get_pr_search_status(settings.index_path, repo=settings.default_repo)
    except Exception as exc:
        return str(exc)
    return "ready"


def _repo_slug(settings: PrSearchApiSettings, owner: str, repo: str) -> str:
    repo_slug = f"{owner}/{repo}"
    if settings.default_repo and repo_slug != settings.default_repo:
        raise HTTPException(
            status_code=400,
            detail=f"repo {settings.default_repo} is the only configured repo for this deployment",
        )
    return repo_slug


def _active_snapshot_dir(settings: PrSearchApiSettings, repo_slug: str) -> Path:
    return _status_snapshot_dir(get_pr_search_status(settings.index_path, repo=repo_slug))


def _surface_snapshot_dir(
    settings: PrSearchApiSettings,
    repo_slug: str,
    *,
    surface: Literal["issues", "contributors"],
) -> Path:
    active_snapshot_dir = _active_snapshot_dir(settings, repo_slug)
    if _surface_available(active_snapshot_dir, surface=surface):
        return active_snapshot_dir
    materialized_snapshot_dir = _materialized_snapshot_dir(settings)
    if materialized_snapshot_dir is not None and _surface_available(
        materialized_snapshot_dir, surface=surface
    ):
        return materialized_snapshot_dir
    return active_snapshot_dir


def _status_snapshot_dir(status: dict[str, Any]) -> Path:
    snapshot_dir = status.get("snapshot_dir")
    if not snapshot_dir:
        raise HTTPException(status_code=503, detail="active snapshot directory is unavailable")
    return Path(str(snapshot_dir))


def _materialized_snapshot_dir(settings: PrSearchApiSettings) -> Path | None:
    if settings.hf_repo_id is None:
        return None
    return settings.hf_materialize_dir or default_hf_materialize_dir(
        settings.output_dir,
        settings.hf_repo_id,
        settings.hf_revision,
    )


def _surface_available(snapshot_dir: Path, *, surface: Literal["issues", "contributors"]) -> bool:
    if not snapshot_dir.exists():
        return False
    if surface == "issues":
        return (snapshot_dir / CURRENT_ANALYSIS_MANIFEST_PATH).exists() or any(
            snapshot_dir.glob("analysis-report*.json")
        )
    return (snapshot_dir / "new-contributors-report.json").exists()


def _limit(value: int | None, *, default: int, maximum: int) -> int:
    limit = default if value is None else value
    if limit < 1:
        raise HTTPException(status_code=400, detail="limit must be at least 1")
    if limit > maximum:
        raise HTTPException(status_code=400, detail=f"limit must be at most {maximum}")
    return limit


def _probe_client(settings: PrSearchApiSettings) -> Any:
    if not settings.ghr_base_url:
        return None
    return GhrProbeClient(
        base_url=settings.ghr_base_url,
        timeout=settings.http_timeout,
        max_retries=settings.http_max_retries,
    )


def _looks_not_found(exc: ValueError) -> bool:
    message = str(exc).lower()
    return (
        "not found" in message
        or "analysis report was not found" in message
        or "no analysis report was found" in message
        or "published analysis" in message
        or "materialized snapshot" in message
        or "no active pr search run" in message
        or "was not found in the active indexed universe" in message
    )


def _env_bool(name: str, default: bool) -> bool:
    raw = os.environ.get(name)
    if raw is None:
        return default
    return raw.strip().lower() in {"1", "true", "yes", "on"}


def _env_int(name: str, default: int) -> int:
    raw = os.environ.get(name)
    return default if raw is None else int(raw)


def _env_path(name: str) -> Path | None:
    raw = os.environ.get(name)
    return None if raw is None else Path(raw).resolve()


app = create_app()