File size: 21,644 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
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import duckdb

TABLE_COLUMNS: dict[str, tuple[str, ...]] = {
    "pr_search_runs": (
        "id",
        "repo",
        "snapshot_id",
        "snapshot_dir",
        "source_type",
        "hf_repo_id",
        "hf_revision",
        "started_at",
        "finished_at",
        "status",
        "settings_json",
        "notes",
    ),
    "pr_search_active_run": (
        "repo",
        "run_id",
        "activated_at",
    ),
    "pr_search_documents": (
        "run_id",
        "repo",
        "pr_number",
        "github_id",
        "author_login",
        "state",
        "draft",
        "merged",
        "title",
        "base_ref",
        "created_at",
        "updated_at",
        "merged_at",
        "additions",
        "deletions",
        "changed_files",
        "comments_count",
        "review_comments_count",
        "html_url",
    ),
    "pr_search_contributors": (
        "run_id",
        "repo",
        "snapshot_id",
        "report_generated_at",
        "window_days",
        "author_login",
        "name",
        "profile_url",
        "repo_pull_requests_url",
        "repo_issues_url",
        "repo_first_seen_at",
        "repo_last_seen_at",
        "repo_primary_artifact_count",
        "repo_artifact_count",
        "snapshot_issue_count",
        "snapshot_pr_count",
        "snapshot_comment_count",
        "snapshot_review_count",
        "snapshot_review_comment_count",
        "repo_association",
        "new_to_repo",
        "first_seen_in_snapshot",
        "report_reason",
        "account_age_days",
        "young_account",
        "follow_through_score",
        "breadth_score",
        "automation_risk_signal",
        "heuristic_note",
        "public_orgs_json",
        "visible_authored_pr_count",
        "merged_pr_count",
        "closed_unmerged_pr_count",
        "open_pr_count",
        "merged_pr_rate",
        "closed_unmerged_pr_rate",
        "still_open_pr_rate",
        "distinct_repos_with_authored_prs",
        "distinct_repos_with_open_prs",
        "fetch_error",
    ),
    "pr_scope_features": (
        "run_id",
        "repo",
        "pr_number",
        "feature_version",
        "total_changed_lines",
        "file_count",
        "directory_count",
        "dominant_dir_share",
        "filenames_json",
        "directories_json",
        "vector_json",
        "computed_at",
    ),
    "pr_scope_run_artifacts": (
        "run_id",
        "repo",
        "feature_version",
        "idf_json",
        "computed_at",
    ),
    "pr_scope_neighbors": (
        "run_id",
        "repo",
        "left_pr_number",
        "right_pr_number",
        "rank_from_left",
        "rank_from_right",
        "similarity",
        "content_similarity",
        "size_similarity",
        "breadth_similarity",
        "concentration_similarity",
        "shared_filenames_json",
        "shared_directories_json",
        "created_at",
    ),
    "pr_scope_clusters": (
        "run_id",
        "repo",
        "cluster_id",
        "representative_pr_number",
        "cluster_size",
        "average_similarity",
        "summary",
        "shared_filenames_json",
        "shared_directories_json",
        "created_at",
    ),
    "pr_scope_cluster_members": (
        "run_id",
        "repo",
        "cluster_id",
        "pr_number",
        "member_role",
    ),
    "pr_scope_cluster_candidates": (
        "run_id",
        "repo",
        "pr_number",
        "cluster_id",
        "candidate_rank",
        "candidate_score",
        "matched_member_count",
        "best_member_pr_number",
        "max_member_similarity",
        "avg_top_member_similarity",
        "evidence_json",
        "assigned",
    ),
}


SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS pr_search_runs (
    id VARCHAR,
    repo VARCHAR,
    snapshot_id VARCHAR,
    snapshot_dir VARCHAR,
    source_type VARCHAR,
    hf_repo_id VARCHAR,
    hf_revision VARCHAR,
    started_at VARCHAR,
    finished_at VARCHAR,
    status VARCHAR,
    settings_json VARCHAR,
    notes VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_search_active_run (
    repo VARCHAR,
    run_id VARCHAR,
    activated_at VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_search_documents (
    run_id VARCHAR,
    repo VARCHAR,
    pr_number BIGINT,
    github_id BIGINT,
    author_login VARCHAR,
    state VARCHAR,
    draft BOOLEAN,
    merged BOOLEAN,
    title VARCHAR,
    base_ref VARCHAR,
    created_at VARCHAR,
    updated_at VARCHAR,
    merged_at VARCHAR,
    additions BIGINT,
    deletions BIGINT,
    changed_files BIGINT,
    comments_count BIGINT,
    review_comments_count BIGINT,
    html_url VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_search_contributors (
    run_id VARCHAR,
    repo VARCHAR,
    snapshot_id VARCHAR,
    report_generated_at VARCHAR,
    window_days BIGINT,
    author_login VARCHAR,
    name VARCHAR,
    profile_url VARCHAR,
    repo_pull_requests_url VARCHAR,
    repo_issues_url VARCHAR,
    repo_first_seen_at VARCHAR,
    repo_last_seen_at VARCHAR,
    repo_primary_artifact_count BIGINT,
    repo_artifact_count BIGINT,
    snapshot_issue_count BIGINT,
    snapshot_pr_count BIGINT,
    snapshot_comment_count BIGINT,
    snapshot_review_count BIGINT,
    snapshot_review_comment_count BIGINT,
    repo_association VARCHAR,
    new_to_repo BOOLEAN,
    first_seen_in_snapshot BOOLEAN,
    report_reason VARCHAR,
    account_age_days BIGINT,
    young_account BOOLEAN,
    follow_through_score VARCHAR,
    breadth_score VARCHAR,
    automation_risk_signal VARCHAR,
    heuristic_note VARCHAR,
    public_orgs_json VARCHAR,
    visible_authored_pr_count BIGINT,
    merged_pr_count BIGINT,
    closed_unmerged_pr_count BIGINT,
    open_pr_count BIGINT,
    merged_pr_rate DOUBLE,
    closed_unmerged_pr_rate DOUBLE,
    still_open_pr_rate DOUBLE,
    distinct_repos_with_authored_prs BIGINT,
    distinct_repos_with_open_prs BIGINT,
    fetch_error VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_features (
    run_id VARCHAR,
    repo VARCHAR,
    pr_number BIGINT,
    feature_version VARCHAR,
    total_changed_lines BIGINT,
    file_count BIGINT,
    directory_count BIGINT,
    dominant_dir_share DOUBLE,
    filenames_json VARCHAR,
    directories_json VARCHAR,
    vector_json VARCHAR,
    computed_at VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_run_artifacts (
    run_id VARCHAR,
    repo VARCHAR,
    feature_version VARCHAR,
    idf_json VARCHAR,
    computed_at VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_neighbors (
    run_id VARCHAR,
    repo VARCHAR,
    left_pr_number BIGINT,
    right_pr_number BIGINT,
    rank_from_left BIGINT,
    rank_from_right BIGINT,
    similarity DOUBLE,
    content_similarity DOUBLE,
    size_similarity DOUBLE,
    breadth_similarity DOUBLE,
    concentration_similarity DOUBLE,
    shared_filenames_json VARCHAR,
    shared_directories_json VARCHAR,
    created_at VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_clusters (
    run_id VARCHAR,
    repo VARCHAR,
    cluster_id VARCHAR,
    representative_pr_number BIGINT,
    cluster_size BIGINT,
    average_similarity DOUBLE,
    summary VARCHAR,
    shared_filenames_json VARCHAR,
    shared_directories_json VARCHAR,
    created_at VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_cluster_members (
    run_id VARCHAR,
    repo VARCHAR,
    cluster_id VARCHAR,
    pr_number BIGINT,
    member_role VARCHAR
);
CREATE TABLE IF NOT EXISTS pr_scope_cluster_candidates (
    run_id VARCHAR,
    repo VARCHAR,
    pr_number BIGINT,
    cluster_id VARCHAR,
    candidate_rank BIGINT,
    candidate_score DOUBLE,
    matched_member_count BIGINT,
    best_member_pr_number BIGINT,
    max_member_similarity DOUBLE,
    avg_top_member_similarity DOUBLE,
    evidence_json VARCHAR,
    assigned BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_pr_search_active_run_repo ON pr_search_active_run (repo);
CREATE INDEX IF NOT EXISTS idx_pr_search_runs_repo_status ON pr_search_runs (repo, status);
CREATE INDEX IF NOT EXISTS idx_pr_search_documents_run_pr ON pr_search_documents (run_id, pr_number);
CREATE INDEX IF NOT EXISTS idx_pr_search_documents_run_author ON pr_search_documents (run_id, author_login);
CREATE INDEX IF NOT EXISTS idx_pr_search_contributors_run_author ON pr_search_contributors (run_id, author_login);
CREATE INDEX IF NOT EXISTS idx_pr_scope_features_run_pr ON pr_scope_features (run_id, pr_number);
CREATE INDEX IF NOT EXISTS idx_pr_scope_run_artifacts_run ON pr_scope_run_artifacts (run_id);
CREATE INDEX IF NOT EXISTS idx_pr_scope_neighbors_run_left ON pr_scope_neighbors (run_id, left_pr_number);
CREATE INDEX IF NOT EXISTS idx_pr_scope_neighbors_run_right ON pr_scope_neighbors (run_id, right_pr_number);
CREATE INDEX IF NOT EXISTS idx_pr_scope_clusters_run_cluster ON pr_scope_clusters (run_id, cluster_id);
CREATE INDEX IF NOT EXISTS idx_pr_scope_cluster_members_run_pr ON pr_scope_cluster_members (run_id, pr_number);
CREATE INDEX IF NOT EXISTS idx_pr_scope_cluster_candidates_run_pr ON pr_scope_cluster_candidates (run_id, pr_number);
"""


def connect_pr_search_db(path: Path, *, read_only: bool = False) -> duckdb.DuckDBPyConnection:
    resolved = path.resolve()
    if read_only and not resolved.exists():
        raise FileNotFoundError(f"PR search database does not exist: {resolved}")
    if not read_only:
        resolved.parent.mkdir(parents=True, exist_ok=True)
    connection = duckdb.connect(str(resolved), read_only=read_only)
    if not read_only:
        ensure_pr_search_schema(connection)
    return connection


def ensure_pr_search_schema(connection: duckdb.DuckDBPyConnection) -> None:
    connection.execute(SCHEMA_SQL)
    connection.execute(
        "ALTER TABLE pr_search_documents ADD COLUMN IF NOT EXISTS author_login VARCHAR"
    )


def insert_rows(
    connection: duckdb.DuckDBPyConnection,
    table_name: str,
    rows: list[dict[str, Any]],
) -> None:
    if not rows:
        return
    columns = TABLE_COLUMNS[table_name]
    placeholders = ", ".join("?" for _ in columns)
    column_sql = ", ".join(columns)
    values = [tuple(_db_value(row.get(column)) for column in columns) for row in rows]
    connection.executemany(
        f"INSERT INTO {table_name} ({column_sql}) VALUES ({placeholders})",
        values,
    )


def update_run_status(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    status: str,
    finished_at: str | None = None,
    notes: str | None = None,
) -> None:
    connection.execute(
        """
        UPDATE pr_search_runs
        SET status = ?, finished_at = COALESCE(?, finished_at), notes = COALESCE(?, notes)
        WHERE id = ?
        """,
        [status, finished_at, notes, run_id],
    )


def replace_active_run(
    connection: duckdb.DuckDBPyConnection,
    *,
    repo: str,
    run_id: str,
    activated_at: str,
) -> str | None:
    previous = fetch_one(
        connection,
        "SELECT run_id FROM pr_search_active_run WHERE repo = ?",
        [repo],
    )
    connection.execute("DELETE FROM pr_search_active_run WHERE repo = ?", [repo])
    connection.execute(
        "INSERT INTO pr_search_active_run (repo, run_id, activated_at) VALUES (?, ?, ?)",
        [repo, run_id, activated_at],
    )
    previous_run_id = None if previous is None else str(previous["run_id"])
    if previous_run_id is not None and previous_run_id != run_id:
        connection.execute(
            "UPDATE pr_search_runs SET status = 'superseded' WHERE id = ? AND status = 'succeeded'",
            [previous_run_id],
        )
    return previous_run_id


def resolve_active_run(
    connection: duckdb.DuckDBPyConnection,
    *,
    repo: str | None = None,
) -> dict[str, Any]:
    if repo is None:
        active_repos = fetch_rows(
            connection,
            "SELECT repo FROM pr_search_active_run ORDER BY repo",
        )
        if not active_repos:
            raise ValueError("No active PR search run found.")
        if len(active_repos) > 1:
            raise ValueError("Multiple active repos found; pass --repo.")
        repo = str(active_repos[0]["repo"])
    row = fetch_one(
        connection,
        """
        SELECT r.*
        FROM pr_search_runs AS r
        JOIN pr_search_active_run AS a
          ON a.run_id = r.id AND a.repo = r.repo
        WHERE a.repo = ?
        """,
        [repo],
    )
    if row is None:
        raise ValueError(f"No active PR search run found for repo {repo!r}.")
    return row


def get_run_counts(connection: duckdb.DuckDBPyConnection, *, run_id: str) -> dict[str, int]:
    return {
        "documents": _count(connection, "pr_search_documents", run_id),
        "contributors": _count(connection, "pr_search_contributors", run_id),
        "features": _count(connection, "pr_scope_features", run_id),
        "run_artifacts": _count(connection, "pr_scope_run_artifacts", run_id),
        "neighbors": _count(connection, "pr_scope_neighbors", run_id),
        "clusters": _count(connection, "pr_scope_clusters", run_id),
        "cluster_members": _count(connection, "pr_scope_cluster_members", run_id),
        "cluster_candidates": _count(connection, "pr_scope_cluster_candidates", run_id),
    }


def get_document(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    pr_number: int,
) -> dict[str, Any] | None:
    return fetch_one(
        connection,
        "SELECT * FROM pr_search_documents WHERE run_id = ? AND pr_number = ?",
        [run_id, pr_number],
    )


def get_contributor(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    author_login: str,
) -> dict[str, Any] | None:
    return fetch_one(
        connection,
        """
        SELECT *
        FROM pr_search_contributors
        WHERE run_id = ? AND lower(author_login) = lower(?)
        """,
        [run_id, author_login],
    )


def get_contributor_pulls(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    author_login: str,
    limit: int,
) -> list[dict[str, Any]]:
    return fetch_rows(
        connection,
        """
        SELECT
            pr_number,
            github_id,
            author_login,
            state,
            draft,
            merged,
            title,
            base_ref,
            created_at,
            updated_at,
            merged_at,
            additions,
            deletions,
            changed_files,
            comments_count,
            review_comments_count,
            html_url
        FROM pr_search_documents
        WHERE run_id = ? AND lower(author_login) = lower(?)
        ORDER BY updated_at DESC NULLS LAST, pr_number DESC
        LIMIT ?
        """,
        [run_id, author_login, limit],
    )


def get_feature(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    pr_number: int,
) -> dict[str, Any] | None:
    return fetch_one(
        connection,
        "SELECT * FROM pr_scope_features WHERE run_id = ? AND pr_number = ?",
        [run_id, pr_number],
    )


def get_scope_run_artifact(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
) -> dict[str, Any] | None:
    try:
        return fetch_one(
            connection,
            """
            SELECT *
            FROM pr_scope_run_artifacts
            WHERE run_id = ?
            """,
            [run_id],
        )
    except duckdb.Error:
        return None


def get_similar_pr_rows(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    pr_number: int,
    limit: int,
) -> list[dict[str, Any]]:
    return fetch_rows(
        connection,
        """
        SELECT
            CASE WHEN left_pr_number = ? THEN right_pr_number ELSE left_pr_number END AS neighbor_pr_number,
            CASE WHEN left_pr_number = ? THEN rank_from_left ELSE rank_from_right END AS neighbor_rank,
            similarity,
            content_similarity,
            size_similarity,
            breadth_similarity,
            concentration_similarity,
            shared_filenames_json,
            shared_directories_json
        FROM pr_scope_neighbors
        WHERE run_id = ? AND (? = left_pr_number OR ? = right_pr_number)
        ORDER BY neighbor_rank IS NULL, neighbor_rank, similarity DESC, neighbor_pr_number
        LIMIT ?
        """,
        [pr_number, pr_number, run_id, pr_number, pr_number, limit],
    )


def get_candidate_cluster_rows(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    pr_number: int,
    limit: int,
) -> list[dict[str, Any]]:
    return fetch_rows(
        connection,
        """
        SELECT
            c.cluster_id,
            c.candidate_rank,
            c.candidate_score,
            c.matched_member_count,
            c.best_member_pr_number,
            c.max_member_similarity,
            c.avg_top_member_similarity,
            c.evidence_json,
            c.assigned,
            cl.representative_pr_number,
            cl.cluster_size,
            cl.average_similarity,
            cl.summary,
            cl.shared_filenames_json,
            cl.shared_directories_json,
            d.title AS representative_title
        FROM pr_scope_cluster_candidates AS c
        JOIN pr_scope_clusters AS cl
          ON cl.run_id = c.run_id AND cl.cluster_id = c.cluster_id
        LEFT JOIN pr_search_documents AS d
          ON d.run_id = cl.run_id AND d.pr_number = cl.representative_pr_number
        WHERE c.run_id = ? AND c.pr_number = ?
        ORDER BY c.candidate_rank, c.candidate_score DESC, c.cluster_id
        LIMIT ?
        """,
        [run_id, pr_number, limit],
    )


def get_cluster(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    cluster_id: str,
) -> dict[str, Any] | None:
    return fetch_one(
        connection,
        "SELECT * FROM pr_scope_clusters WHERE run_id = ? AND cluster_id = ?",
        [run_id, cluster_id],
    )


def get_cluster_members(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    cluster_id: str,
) -> list[dict[str, Any]]:
    return fetch_rows(
        connection,
        """
        SELECT
            m.pr_number,
            m.member_role,
            d.title,
            d.html_url,
            d.state,
            d.draft
        FROM pr_scope_cluster_members AS m
        LEFT JOIN pr_search_documents AS d
          ON d.run_id = m.run_id AND d.pr_number = m.pr_number
        WHERE m.run_id = ? AND m.cluster_id = ?
        ORDER BY m.member_role != 'representative', m.pr_number
        """,
        [run_id, cluster_id],
    )


def get_cluster_ids_for_prs(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    pr_numbers: list[int],
) -> dict[int, list[str]]:
    if not pr_numbers:
        return {}
    placeholders = ", ".join("?" for _ in pr_numbers)
    rows = fetch_rows(
        connection,
        f"""
        SELECT pr_number, cluster_id
        FROM pr_scope_cluster_members
        WHERE run_id = ? AND pr_number IN ({placeholders})
        ORDER BY pr_number, cluster_id
        """,
        [run_id, *pr_numbers],
    )
    result: dict[int, list[str]] = {}
    for row in rows:
        result.setdefault(int(row["pr_number"]), []).append(str(row["cluster_id"]))
    return result


def get_shared_cluster_ids(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    left_pr_number: int,
    right_pr_number: int,
) -> list[str]:
    rows = fetch_rows(
        connection,
        """
        SELECT left_members.cluster_id
        FROM pr_scope_cluster_members AS left_members
        JOIN pr_scope_cluster_members AS right_members
          ON right_members.run_id = left_members.run_id
         AND right_members.cluster_id = left_members.cluster_id
        WHERE left_members.run_id = ?
          AND left_members.pr_number = ?
          AND right_members.pr_number = ?
        ORDER BY left_members.cluster_id
        """,
        [run_id, left_pr_number, right_pr_number],
    )
    return [str(row["cluster_id"]) for row in rows]


def get_pair_neighbor_row(
    connection: duckdb.DuckDBPyConnection,
    *,
    run_id: str,
    left_pr_number: int,
    right_pr_number: int,
) -> dict[str, Any] | None:
    canonical_left = min(left_pr_number, right_pr_number)
    canonical_right = max(left_pr_number, right_pr_number)
    return fetch_one(
        connection,
        """
        SELECT *
        FROM pr_scope_neighbors
        WHERE run_id = ? AND left_pr_number = ? AND right_pr_number = ?
        """,
        [run_id, canonical_left, canonical_right],
    )


def fetch_rows(
    connection: duckdb.DuckDBPyConnection,
    sql: str,
    parameters: list[Any] | tuple[Any, ...] | None = None,
) -> list[dict[str, Any]]:
    cursor = connection.execute(sql, parameters or [])
    columns = [column[0] for column in cursor.description]
    return [dict(zip(columns, row, strict=False)) for row in cursor.fetchall()]


def fetch_one(
    connection: duckdb.DuckDBPyConnection,
    sql: str,
    parameters: list[Any] | tuple[Any, ...] | None = None,
) -> dict[str, Any] | None:
    rows = fetch_rows(connection, sql, parameters)
    return rows[0] if rows else None


def _count(connection: duckdb.DuckDBPyConnection, table_name: str, run_id: str) -> int:
    row = fetch_one(
        connection,
        f"SELECT COUNT(*) AS row_count FROM {table_name} WHERE run_id = ?",
        [run_id],
    )
    return 0 if row is None else int(row["row_count"])


def _db_value(value: Any) -> Any:
    if isinstance(value, (dict, list)):
        return json.dumps(value, sort_keys=True)
    return value