-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_patch.py
More file actions
2258 lines (2042 loc) · 92.6 KB
/
Copy pathrun_patch.py
File metadata and controls
2258 lines (2042 loc) · 92.6 KB
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
GraphManager Patch Runner
End-to-end pipeline: retrieval → patch generation → (optional) SWE-bench evaluation.
Usage:
# Generate patches from a manifest, save to disk (no Docker needed):
./.venv/bin/python run_patch.py \
--manifest patch_manifests/swebench_verified_30.yaml \
--results-dir results/patch_runs
# Generate patches AND run SWE-bench harness evaluation (requires Docker):
./.venv/bin/python run_patch.py \
--manifest patch_manifests/swebench_verified_30.yaml \
--evaluate \
--results-dir results/patch_runs
Manifest format (YAML):
dataset_name: SWE-bench/SWE-bench_Verified
split: test
instance_ids:
- pallets__flask-4045
- psf__requests-1713
retrieval_method: gm_progressive # gm_deterministic | rag_progressive | raw_rag_function | raw_rag_fixed | bm25 | oracle | none | agentic_cold_start | repomap_like | agentless_like_localization
manager_max_turns: 4
retrieval_max_files_for_patch: 6 # post-retrieval cap before patching (set null to disable)
patch_max_turns: 3
patch_max_output_tokens: 4096
patch_max_file_chars: 8000
"""
import argparse
import concurrent.futures
import hashlib
import httpx
import json
import os
import platform
import random
import shutil
import subprocess
import sys
import time
from pathlib import Path
import yaml
from dotenv import load_dotenv
DEFAULT_MANAGER_MODEL = "gemini-3-flash-preview"
DEFAULT_PATCH_MODEL = "gemini-3-flash-preview"
def _capture_provenance(manifest_path: str) -> dict:
"""Capture reproducibility metadata: git SHA, manifest hash, python/dep versions."""
provenance: dict = {
"python_version": platform.python_version(),
"platform": platform.platform(),
"timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
# Git SHA of the repo running the pipeline (NOT the target repo)
try:
result = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True, timeout=5,
cwd=str(Path(__file__).parent),
)
provenance["pipeline_git_sha"] = result.stdout.strip() if result.returncode == 0 else "unknown"
except Exception:
provenance["pipeline_git_sha"] = "unknown"
# Check for uncommitted changes
try:
result = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True, text=True, timeout=5,
cwd=str(Path(__file__).parent),
)
provenance["pipeline_dirty"] = bool(result.stdout.strip()) if result.returncode == 0 else None
except Exception:
provenance["pipeline_dirty"] = None
# Manifest content hash
try:
manifest_bytes = Path(manifest_path).read_bytes()
provenance["manifest_sha256"] = hashlib.sha256(manifest_bytes).hexdigest()
except Exception:
provenance["manifest_sha256"] = "unknown"
# Key dependency versions
dep_versions = {}
for pkg in ("swebench", "google-genai", "rank_bm25", "tree_sitter", "networkx", "faiss"):
try:
import importlib.metadata
dep_versions[pkg] = importlib.metadata.version(pkg.replace("_", "-").replace("_", "-"))
except Exception:
dep_versions[pkg] = "unknown"
provenance["dependency_versions"] = dep_versions
return provenance
def _checkout_issue_commit(
*,
repo_git,
snapshot_commit: str | None,
issue: dict,
current_commit: str | None,
issue_id: str | None = None,
) -> str | None:
"""Checkout the commit for this issue when needed and return current commit."""
target_commit = snapshot_commit or issue.get("base_commit")
if target_commit and target_commit != current_commit:
if issue_id:
print(f" Checking out {target_commit[:12]} for {issue_id}...")
else:
print(f" Checking out {target_commit[:12]}...")
try:
repo_git.git.checkout(target_commit, force=True)
except Exception as exc:
# Some local SWE-bench repo clones do not yet contain the issue's base commit.
# Attempt a targeted fetch, then retry checkout once.
if "reference is not a tree" not in str(exc).lower():
raise
print(f" Missing commit locally; fetching {target_commit[:12]}...")
fetch_error = None
for fetch_args in (("origin", target_commit), ("--all", "--tags", "--prune")):
try:
repo_git.git.fetch(*fetch_args)
fetch_error = None
break
except Exception as fetch_exc:
fetch_error = fetch_exc
if fetch_error is not None:
raise fetch_error from exc
repo_git.git.checkout(target_commit, force=True)
return target_commit
return current_commit
def _check_docker() -> bool:
"""Return True if Docker daemon is reachable."""
import subprocess
result = subprocess.run(
["docker", "ps"],
capture_output=True,
timeout=5,
)
return result.returncode == 0
def _resolve_model_config(manifest: dict) -> tuple[str, str]:
"""Resolve retrieval and patch model names from manifest defaults/overrides."""
manager_model = str(manifest.get("manager_model") or DEFAULT_MANAGER_MODEL)
patch_model = str(manifest.get("patch_model") or DEFAULT_PATCH_MODEL)
return manager_model, patch_model
def _slugify_identifier(value: str) -> str:
"""Return a filesystem-safe lowercase identifier fragment."""
lowered = (value or "").strip().lower()
chars = [ch if ch.isalnum() else "-" for ch in lowered]
slug = "".join(chars).strip("-")
while "--" in slug:
slug = slug.replace("--", "-")
return slug or "unknown"
def _build_harness_run_id(
*,
run_id: str,
retrieval_method: str,
results_path: Path,
existing_harness_run_id: str | None = None,
) -> str:
"""Build a collision-resistant harness run ID for concurrent runs."""
if existing_harness_run_id:
return str(existing_harness_run_id)
method_slug = _slugify_identifier(retrieval_method)
path_hash = hashlib.sha1(str(results_path.resolve()).encode("utf-8")).hexdigest()[:8]
return f"graphmanager_{run_id}_{method_slug}_{path_hash}"
def _allocate_run_output_dir(results_dir: str) -> tuple[str, Path]:
"""Allocate a unique run directory under <results_dir>/patch_runs."""
patch_runs_root = Path(results_dir) / "patch_runs"
patch_runs_root.mkdir(parents=True, exist_ok=True)
base_run_id = time.strftime("%Y%m%d_%H%M%S")
suffix = 0
while True:
run_id = base_run_id if suffix == 0 else f"{base_run_id}_{suffix:02d}"
candidate = patch_runs_root / run_id
try:
candidate.mkdir(parents=False, exist_ok=False)
return run_id, candidate
except FileExistsError:
# Handle concurrent allocators racing on the same timestamp/suffix.
suffix += 1
suffix += 1
def _is_transient_api_error(exc: Exception) -> bool:
"""Return True when an API exception looks retryable."""
msg = str(exc).upper()
return any(
token in msg
for token in (
"429",
"RESOURCE_EXHAUSTED",
"RATE_LIMIT",
"503",
"UNAVAILABLE",
"DEADLINE_EXCEEDED",
"TIMEOUT",
)
)
def _run_with_rate_limit_backoff(
callable_fn,
*,
label: str,
max_retries: int = 6,
initial_delay_s: float = 6.0,
backoff_multiplier: float = 2.0,
max_delay_s: float = 120.0,
jitter_s: float = 1.0,
deadline_monotonic: float | None = None,
):
"""
Run callable with retries on transient API limits/failures.
max_retries counts retry attempts after the initial call.
"""
delay_s = max(initial_delay_s, 0.0)
for attempt in range(max_retries + 1):
if deadline_monotonic is not None and time.monotonic() >= deadline_monotonic:
raise TimeoutError(f"{label} timed out due to instance wall-clock budget")
try:
if deadline_monotonic is None:
return callable_fn()
remaining_s = deadline_monotonic - time.monotonic()
if remaining_s <= 0:
raise TimeoutError(f"{label} timed out due to instance wall-clock budget")
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
future = executor.submit(callable_fn)
try:
return future.result(timeout=remaining_s)
except concurrent.futures.TimeoutError as timeout_exc:
future.cancel()
raise TimeoutError(f"{label} timed out due to instance wall-clock budget") from timeout_exc
finally:
executor.shutdown(wait=False, cancel_futures=True)
except Exception as exc:
should_retry = _is_transient_api_error(exc) and attempt < max_retries
if not should_retry:
raise
sleep_s = min(delay_s, max_delay_s) + max(0.0, random.uniform(0.0, max(0.0, jitter_s)))
if deadline_monotonic is not None and (time.monotonic() + sleep_s) >= deadline_monotonic:
raise TimeoutError(f"{label} timed out due to instance wall-clock budget") from exc
print(
f" {label} transient API error "
f"(attempt {attempt + 1}/{max_retries + 1}): {type(exc).__name__}; "
f"retrying in {sleep_s:.1f}s"
)
time.sleep(sleep_s)
delay_s = min(max_delay_s, max(delay_s * max(backoff_multiplier, 1.0), delay_s + 1.0))
def _run_retrieval(
issue: dict,
*,
graph,
graph_index,
rag_index,
bm25_index=None,
rag_metadata_index=None,
client,
method: str,
manager_model: str,
manager_max_turns: int,
deterministic_config: dict,
redact_paths: bool = True,
retry_feedback: str | None = None,
rag_symmetric_tools: bool = False,
repo_dir: str | None = None,
include_prefixes: tuple[str, ...] | None = None,
valid_file_paths: set[str] | None = None,
patch_max_file_chars: int = 200_000,
repomap_config: dict | None = None,
agentless_like_config: dict | None = None,
) -> tuple[list[str], dict]:
"""Run one retrieval method for one issue."""
from src.evaluation import normalize_file_paths, prepare_issue_text
from src.path_resolution import canonicalize_file_paths
if method == "none":
return [], {
"prompt_tokens": 0,
"candidate_tokens": 0,
"total_tokens": 0,
"tool_calls": 0,
"stop_reason": "no_retrieval",
}
files: list[str]
tokens: dict
if method == "oracle":
from src.datasets.adapters import extract_gold_files_from_patch
oracle_files = extract_gold_files_from_patch(issue.get("patch", ""))
if not oracle_files:
oracle_files = issue.get("gold_files", [])
files = normalize_file_paths(oracle_files)
tokens = {
"prompt_tokens": 0,
"candidate_tokens": 0,
"total_tokens": 0,
"tool_calls": 0,
"stop_reason": "oracle",
}
else:
query = prepare_issue_text(
issue.get("problem_statement", ""),
redact_paths=redact_paths,
)
if retry_feedback:
query = f"{query}\n\n## Retrieval Retry Feedback\n{retry_feedback}"
if method == "gm_progressive":
from src.manager_agent import ManagerAgent
agent = ManagerAgent(
graph,
graph_index,
client,
model=manager_model,
retrieval_mode="progressive",
)
files, tokens = agent.find_relevant_files(query, max_turns=manager_max_turns)
elif method == "gm_deterministic":
from src.deterministic_retrieval import DeterministicGraphRetriever
agent = DeterministicGraphRetriever(
graph, graph_index,
**deterministic_config,
)
files, tokens = agent.find_relevant_files(query)
elif method == "rag_progressive":
from src.rag_baseline import RAGAgent
agent = RAGAgent(
rag_index,
client,
model=manager_model,
retrieval_mode="progressive",
repo_dir=repo_dir,
symmetric_tools=rag_symmetric_tools,
max_file_chars=patch_max_file_chars,
)
files, tokens = agent.find_relevant_files(query, max_turns=manager_max_turns)
elif method in {"rag_baseline", "raw_rag_function", "raw_rag_fixed"}:
if rag_index is None:
raise ValueError(f"rag_index must be provided when method='{method}'")
if method == "rag_baseline":
from src.rag_baseline import RAGAgent
agent = RAGAgent(
rag_index,
client,
model=manager_model,
retrieval_mode="baseline",
repo_dir=repo_dir,
symmetric_tools=False,
max_file_chars=patch_max_file_chars,
)
files, tokens = agent.find_relevant_files(query, max_turns=manager_max_turns)
else:
from src.rag_baseline import RawRAG
agent = RawRAG(rag_index)
files, tokens = agent.find_relevant_files(query, top_k=20)
elif method == "agentic_cold_start":
from src.agentic_cold_start import AgenticColdStartAgent
if not repo_dir:
raise ValueError("repo_dir must be provided when method='agentic_cold_start'")
agent = AgenticColdStartAgent(
repo_dir=repo_dir,
client=client,
model=manager_model,
include_prefixes=include_prefixes,
max_file_chars=patch_max_file_chars,
)
files, tokens = agent.find_relevant_files(query, max_turns=manager_max_turns)
elif method == "bm25":
if bm25_index is None:
raise ValueError("bm25_index must be provided when method='bm25'")
files, tokens = bm25_index.find_relevant_files(query)
elif method == "rag_metadata":
if rag_metadata_index is None:
raise ValueError("rag_metadata_index must be provided when method='rag_metadata'")
from src.rag_baseline import RawRAG
agent = RawRAG(rag_metadata_index)
files, tokens = agent.find_relevant_files(query)
elif method == "repomap_like":
if graph is None:
raise ValueError("graph must be provided when method='repomap_like'")
from src.repomap_like import RepoMapLikeRetriever
cfg = dict(repomap_config or {})
agent = RepoMapLikeRetriever(
graph=graph,
client=client if bool(cfg.get("use_llm_selector", False)) else None,
model=manager_model,
top_k_files=int(cfg.get("top_k_files", 10) or 10),
map_tokens=int(cfg.get("map_tokens", 1000) or 1000),
use_llm_selector=bool(cfg.get("use_llm_selector", False)),
refresh_mode=str(cfg.get("refresh_mode", "static_per_issue") or "static_per_issue"),
edge_weights=dict(cfg.get("edge_weights", {}) or {}),
enable_same_module_edge=bool(cfg.get("enable_same_module_edge", False)),
personalization_enabled=bool(cfg.get("personalization_enabled", True)),
)
files, tokens = agent.find_relevant_files(query)
elif method == "agentless_like_localization":
if rag_index is None:
raise ValueError("rag_index must be provided when method='agentless_like_localization'")
if graph is None:
raise ValueError("graph must be provided when method='agentless_like_localization'")
from src.agentless_like_localization import AgentlessLikeLocalizer
cfg = dict(agentless_like_config or {})
agent = AgentlessLikeLocalizer(
rag_index=rag_index,
graph=graph,
client=client,
model=manager_model,
stage2_enabled=bool(cfg.get("stage2_enabled", True)),
stage3_enabled=bool(cfg.get("stage3_enabled", True)),
edit_location_samples=int(cfg.get("edit_location_samples", 4) or 4),
file_branch_top_n=int(cfg.get("file_branch_top_n", 3) or 3),
embed_branch_top_k=int(cfg.get("embed_branch_top_k", 20) or 20),
merge_top_k=int(cfg.get("merge_top_k", 12) or 12),
stage3_context_window_lines=int(cfg.get("stage3_context_window_lines", 10) or 10),
stage3_max_tokens_per_file=int(cfg.get("stage3_max_tokens_per_file", 1200) or 1200),
constrained_candidates_max=int(cfg.get("constrained_candidates_max", 200) or 200),
reject_out_of_candidate_paths=bool(cfg.get("reject_out_of_candidate_paths", True)),
)
files, tokens = agent.find_relevant_files(query, max_turns=manager_max_turns)
else:
raise ValueError(f"Unsupported retrieval method: {method}")
resolved_valid_paths: set[str] = set(valid_file_paths or set())
if not resolved_valid_paths:
if graph is not None:
resolved_valid_paths = {
str(node_id)
for node_id, node_data in graph.nodes(data=True)
if node_data.get("type") == "file" and str(node_id).endswith(".py")
}
elif rag_index is not None:
resolved_valid_paths = {
str(chunk.get("file", ""))
for chunk in getattr(rag_index, "chunks", [])
if str(chunk.get("file", "")).endswith(".py")
}
elif bm25_index is not None:
resolved_valid_paths = {
str(path)
for path in getattr(bm25_index, "_file_paths", [])
if str(path).endswith(".py")
}
normalized = normalize_file_paths(files)
canonical = canonicalize_file_paths(normalized, resolved_valid_paths) if resolved_valid_paths else normalized
return canonical, tokens
def _cap_retrieved_files(
files: list[str],
*,
max_files: int | None,
) -> tuple[list[str], int, int]:
"""Apply a global post-retrieval file cap for patch-context fairness."""
normalized = list(files or [])
pre_count = len(normalized)
if max_files is None:
return normalized, pre_count, pre_count
capped = normalized[: max(max_files, 1)]
return capped, pre_count, len(capped)
def _tokenish_number(value):
return isinstance(value, (int, float)) and not isinstance(value, bool)
def _merge_token_usages(usages: list[dict]) -> dict:
"""Merge token usage maps by summing numeric fields."""
if not usages:
return {}
merged: dict = {}
for usage in usages:
if not isinstance(usage, dict):
continue
for key, value in usage.items():
if isinstance(value, dict):
existing = merged.get(key, {})
if isinstance(existing, dict):
nested = dict(existing)
else:
nested = {}
for sub_key, sub_val in value.items():
if _tokenish_number(sub_val):
nested[sub_key] = nested.get(sub_key, 0) + sub_val
else:
nested[sub_key] = sub_val
merged[key] = nested
elif _tokenish_number(value):
merged[key] = merged.get(key, 0) + value
else:
merged[key] = value
last = usages[-1]
if isinstance(last, dict) and "stop_reason" in last:
merged["stop_reason"] = last["stop_reason"]
return merged
def _compute_patch_robustness_metrics(per_instance_results: list[dict]) -> dict:
"""Compute run-level patch applicability metrics."""
n_apply_ok = sum(1 for r in per_instance_results if r.get("patch_status") == "patched")
n_apply_failed = sum(1 for r in per_instance_results if r.get("patch_status") == "apply_failed")
denominator = max(1, n_apply_ok + n_apply_failed)
return {
"n_apply_ok": n_apply_ok,
"n_apply_failed": n_apply_failed,
"apply_success_rate": n_apply_ok / denominator,
}
def _build_method_scoped_commit_context(
*,
retrieval_method: str,
repo_dir: str,
prefixes: tuple[str, ...] | None,
client,
graph_builder_cls,
graph_index_cls,
rag_index_cls,
validate_commit_context_fn,
) -> dict:
"""Build only the index family needed by the retrieval method."""
context = {
"graph": None,
"graph_index": None,
"rag_index": None,
"bm25_index": None,
"graph_file_paths": set(),
"retrieval_setup_tokens": 0,
"setup_tokens_graph_built": 0,
"setup_tokens_rag_built": 0,
"setup_tokens_method_accounted": 0,
}
gm_family = {"gm_progressive", "gm_deterministic", "gm_baseline"}
rag_family = {"rag_progressive", "rag_baseline", "raw_rag_function", "raw_rag_fixed"}
repomap_family = {"repomap_like"}
agentless_family = {"agentless_like_localization"}
rag_metadata_family = {"rag_metadata"}
if retrieval_method in gm_family:
print(" Building graph index...")
builder = graph_builder_cls(repo_dir, include_prefixes=prefixes)
graph = builder.build()
print(
f" Graph: {graph.number_of_nodes()} nodes, "
f"{graph.number_of_edges()} edges"
)
graph_index = graph_index_cls(graph, client)
graph_index.build()
graph_tokens = int(getattr(graph_index, "embedding_tokens_estimate", 0) or 0)
setup_costs = {
"gm_progressive": {"embedding_tokens": graph_tokens},
"gm_deterministic": {"embedding_tokens": graph_tokens},
"gm_baseline": {"embedding_tokens": graph_tokens},
}
graph_file_paths = {
str(node_id)
for node_id, node_data in graph.nodes(data=True)
if node_data.get("type") == "file"
}
validate_commit_context_fn(
{"graph_file_paths": graph_file_paths, "setup_costs": setup_costs},
required_methods=(retrieval_method,),
)
context.update(
{
"graph": graph,
"graph_index": graph_index,
"graph_file_paths": graph_file_paths,
"retrieval_setup_tokens": graph_tokens,
"setup_tokens_graph_built": graph_tokens,
"setup_tokens_method_accounted": graph_tokens,
}
)
return context
if retrieval_method in repomap_family:
print(" Building graph (repomap_like)...")
builder = graph_builder_cls(repo_dir, include_prefixes=prefixes)
graph = builder.build()
file_paths = {
str(node_id)
for node_id, node_data in graph.nodes(data=True)
if node_data.get("type") == "file"
}
if not file_paths:
raise ValueError(
"repomap_like graph is empty (no Python files in scope). "
"Check source_prefixes against repository layout."
)
context.update(
{
"graph": graph,
"graph_file_paths": file_paths,
"retrieval_setup_tokens": 0,
"setup_tokens_graph_built": 0,
"setup_tokens_method_accounted": 0,
}
)
return context
if retrieval_method in rag_family:
print(" Building RAG index...")
rag_chunk_strategy = "fixed" if retrieval_method == "raw_rag_fixed" else "function"
rag_index = rag_index_cls(
repo_dir,
client,
chunk_strategy=rag_chunk_strategy,
include_prefixes=prefixes,
)
rag_index.build()
rag_tokens = int(getattr(rag_index, "embedding_tokens_estimate", 0) or 0)
setup_costs = {
"rag_progressive": {"embedding_tokens": rag_tokens},
"rag_baseline": {"embedding_tokens": rag_tokens},
"raw_rag_function": {"embedding_tokens": rag_tokens},
"raw_rag_fixed": {"embedding_tokens": rag_tokens},
}
validate_commit_context_fn(
{"graph_file_paths": set(), "setup_costs": setup_costs},
required_methods=(retrieval_method,),
)
context.update(
{
"rag_index": rag_index,
"graph_file_paths": {
str(chunk.get("file", ""))
for chunk in getattr(rag_index, "chunks", [])
if str(chunk.get("file", ""))
},
"retrieval_setup_tokens": rag_tokens,
"setup_tokens_rag_built": rag_tokens,
"setup_tokens_method_accounted": rag_tokens,
}
)
return context
if retrieval_method in agentless_family:
print(" Building graph (agentless_like_localization)...")
builder = graph_builder_cls(repo_dir, include_prefixes=prefixes)
graph = builder.build()
graph_file_paths = {
str(node_id)
for node_id, node_data in graph.nodes(data=True)
if node_data.get("type") == "file"
}
if not graph_file_paths:
raise ValueError(
"agentless_like_localization graph is empty (no Python files in scope). "
"Check source_prefixes against repository layout."
)
print(" Building RAG index (agentless_like_localization)...")
rag_index = rag_index_cls(
repo_dir,
client,
chunk_strategy="function",
include_prefixes=prefixes,
)
rag_index.build()
rag_tokens = int(getattr(rag_index, "embedding_tokens_estimate", 0) or 0)
validate_commit_context_fn(
{"graph_file_paths": set(), "setup_costs": {"rag_progressive": {"embedding_tokens": rag_tokens}}},
required_methods=("rag_progressive",),
)
context.update(
{
"graph": graph,
"rag_index": rag_index,
"graph_file_paths": {
str(chunk.get("file", ""))
for chunk in getattr(rag_index, "chunks", [])
if str(chunk.get("file", ""))
} | graph_file_paths,
"retrieval_setup_tokens": rag_tokens,
"setup_tokens_graph_built": 0,
"setup_tokens_rag_built": rag_tokens,
"setup_tokens_method_accounted": rag_tokens,
}
)
return context
if retrieval_method in rag_metadata_family:
print(" Building graph (rag_metadata)...")
builder = graph_builder_cls(repo_dir, include_prefixes=prefixes)
graph = builder.build()
graph_file_paths = {
str(node_id)
for node_id, node_data in graph.nodes(data=True)
if node_data.get("type") == "file"
}
if not graph_file_paths:
raise ValueError(
"rag_metadata graph is empty (no Python files in scope). "
"Check source_prefixes against repository layout."
)
print(" Building RAGMetadataIndex (rag_metadata)...")
from src.rag_baseline import RAGMetadataIndex
rag_metadata_idx = RAGMetadataIndex(graph, client)
rag_metadata_idx.build()
meta_tokens = int(getattr(rag_metadata_idx, "embedding_tokens_estimate", 0) or 0)
setup_costs = {"rag_metadata": {"embedding_tokens": meta_tokens}}
validate_commit_context_fn(
{"graph_file_paths": graph_file_paths, "setup_costs": setup_costs},
required_methods=(retrieval_method,),
)
context.update(
{
"graph": graph,
"rag_metadata_index": rag_metadata_idx,
"graph_file_paths": graph_file_paths,
"retrieval_setup_tokens": meta_tokens,
"setup_tokens_graph_built": meta_tokens,
"setup_tokens_method_accounted": meta_tokens,
}
)
return context
if retrieval_method == "bm25":
print(" Building BM25 index...")
from src.bm25_baseline import BM25Index
bm25_index = BM25Index(repo_dir, include_prefixes=prefixes)
bm25_index.build()
bm25_file_paths = set(bm25_index._file_paths)
print(f" BM25: {len(bm25_file_paths)} files indexed")
context.update(
{
"bm25_index": bm25_index,
"graph_file_paths": bm25_file_paths, # used for patch context file set
"retrieval_setup_tokens": 0, # BM25 has no embedding cost
"setup_tokens_method_accounted": 0,
}
)
return context
# none/oracle/agentic_cold_start do not build retrieval indices, but still
# expose valid repo file paths for canonicalization and path safety.
repo_paths = set()
for py_file in sorted(Path(repo_dir).rglob("*.py")):
rel = py_file.relative_to(repo_dir).as_posix()
if any(part.startswith(".") for part in py_file.parts):
continue
if prefixes:
if not any(rel == prefix or rel.startswith(prefix + "/") for prefix in prefixes):
continue
repo_paths.add(rel)
context["graph_file_paths"] = repo_paths
return context
def _compute_cost_summary_fields(
*,
per_instance_results: list[dict],
retrieval_setup_tokens: int,
harness_results: dict | None,
setup_tokens_graph_built: int = 0,
setup_tokens_rag_built: int = 0,
setup_tokens_method_accounted: int | None = None,
) -> dict:
retrieval_runtime_tokens = sum(
int((result.get("retrieval_tokens") or {}).get("total_tokens", 0) or 0)
for result in per_instance_results
)
patch_runtime_tokens = sum(
int((result.get("patch_tokens") or {}).get("total_tokens", 0) or 0)
for result in per_instance_results
)
total_cost_tokens = int(retrieval_setup_tokens or 0) + retrieval_runtime_tokens + patch_runtime_tokens
resolved_instances = []
n_resolved = None
if isinstance(harness_results, dict):
raw_instances = harness_results.get("resolved_instances", [])
if isinstance(raw_instances, list):
resolved_instances = sorted(str(i) for i in raw_instances)
if _tokenish_number(harness_results.get("n_resolved")):
n_resolved = int(harness_results.get("n_resolved", 0))
elif resolved_instances:
n_resolved = len(resolved_instances)
cost_per_resolved_issue = None
if isinstance(n_resolved, int) and n_resolved > 0:
cost_per_resolved_issue = total_cost_tokens / n_resolved
if setup_tokens_method_accounted is None:
setup_tokens_method_accounted = int(retrieval_setup_tokens or 0)
return {
"retrieval_setup_tokens": int(retrieval_setup_tokens or 0),
"setup_tokens_graph_built": int(setup_tokens_graph_built or 0),
"setup_tokens_rag_built": int(setup_tokens_rag_built or 0),
"setup_tokens_method_accounted": int(setup_tokens_method_accounted or 0),
"retrieval_runtime_tokens": retrieval_runtime_tokens,
"patch_runtime_tokens": patch_runtime_tokens,
"total_cost_tokens": total_cost_tokens,
"n_resolved": n_resolved,
"resolved_instances": resolved_instances,
"cost_per_resolved_issue": cost_per_resolved_issue,
}
def _git_apply_check(repo_dir: str, patch_text: str) -> tuple[bool, str]:
"""Validate a patch against a checked-out repo context."""
result = subprocess.run(
["git", "apply", "--check", "--verbose", "-"],
cwd=repo_dir,
input=patch_text,
text=True,
capture_output=True,
)
if result.returncode == 0:
return True, ""
details = "\n".join(
part.strip()
for part in (result.stderr or "", result.stdout or "")
if part and part.strip()
).strip()
return False, details
def _is_cannot_patch(patch_text: str | None, patch_tokens: dict | None) -> bool:
if patch_text:
return False
tokens = patch_tokens or {}
if bool(tokens.get("cannot_patch")):
return True
stop_reason = str(tokens.get("stop_reason", "")).lower()
error_text = str(tokens.get("error", "")).lower()
return "cannot_patch" in stop_reason or "cannot_patch" in error_text
def _build_apply_failure_correction_context(apply_stderr: str) -> str:
return (
"Your previous diff failed to apply with git apply --check.\n"
f"Error:\n{apply_stderr}\n\n"
"Common causes: wrong hunk context, wrong file path, or malformed unified diff.\n"
"Regenerate a complete, valid unified diff."
)
def _make_swebench_prediction(
*,
instance_id: str,
retrieval_method: str,
patch_text: str | None,
patch_status: str,
) -> dict:
"""Build a single SWE-bench prediction entry.
The harness is the ground truth evaluator. Submit the generated patch
regardless of whether our local git-apply check passed (B7 fix). Our local
check is only a diagnostic used in the repair-retry loop; submitting an
empty string for apply_failed patches silently zeros out resolved_rate.
"""
return {
"instance_id": instance_id,
"model_name_or_path": f"graphmanager-{retrieval_method}",
"model_patch": patch_text or "",
}
def _build_retrieval_retry_feedback(previous_files: list[str], failure_hint: str) -> str:
file_lines = "\n".join(f"- {path}" for path in previous_files) if previous_files else "- (none)"
return (
"The previous retrieval context was insufficient to produce an applicable patch.\n"
f"Tried files:\n{file_lines}\n\n"
f"Failure hint:\n{failure_hint}\n\n"
"Search for additional or alternative files needed to fix the issue."
)
def _generate_patch_with_retries(
*,
issue_text: str,
initial_retrieved_files: list[str],
patch_generate_fn,
apply_check_fn,
retrieval_retry_fn,
max_repair_retries: int = 2,
max_retrieval_retries: int = 1,
) -> dict:
"""
Generate patch with bounded apply-repair and retrieval-retry loops.
patch_generate_fn signature:
fn(retrieved_files=[...], correction_context=str|None) -> (patch_text|None, patch_tokens:dict)
apply_check_fn signature:
fn(patch_text:str) -> (ok:bool, stderr:str)
retrieval_retry_fn signature:
fn(previous_files=[...], failure_hint:str) -> (retrieved_files:[...], retrieval_tokens:dict)
"""
retrieved_files = list(initial_retrieved_files)
patch_tokens_history: list[dict] = []
retrieval_retry_history: list[dict] = []
repair_retries_used = 0
retrieval_retries_used = 0
apply_failures = 0
final_patch_text = None
final_status = "no_patch"
failure_hint = ""
while True:
correction_context = None
current_cannot_patch = False
for repair_idx in range(max_repair_retries + 1):
patch_text, patch_tokens = patch_generate_fn(
retrieved_files=list(retrieved_files),
correction_context=correction_context,
)
patch_tokens = patch_tokens or {}
patch_tokens_history.append(patch_tokens)
current_cannot_patch = _is_cannot_patch(patch_text, patch_tokens)
if not patch_text:
final_patch_text = None
final_status = "no_patch"
if current_cannot_patch:
failure_hint = "Patch agent returned CANNOT_PATCH."
else:
failure_hint = "Patch agent did not return a valid diff."
break
apply_ok, apply_stderr = apply_check_fn(patch_text)
if apply_ok:
final_patch_text = patch_text
final_status = "patched"
failure_hint = ""
break
final_patch_text = patch_text
final_status = "apply_failed"
apply_failures += 1
failure_hint = apply_stderr or "git apply --check failed."
if repair_idx >= max_repair_retries:
break
repair_retries_used += 1
correction_context = _build_apply_failure_correction_context(failure_hint)
if final_status == "patched":
break
should_retry_retrieval = retrieval_retries_used < max_retrieval_retries and (
current_cannot_patch or final_status == "apply_failed"
)
if not should_retry_retrieval:
break
retrieval_feedback = _build_retrieval_retry_feedback(retrieved_files, failure_hint)
new_files, retry_tokens = retrieval_retry_fn(
previous_files=list(retrieved_files),
failure_hint=retrieval_feedback,
)
retrieved_files = list(new_files)
retrieval_retries_used += 1
retrieval_retry_history.append({
"retrieved_files": list(retrieved_files),