-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalizer.py
More file actions
3361 lines (2617 loc) · 127 KB
/
Copy pathlocalizer.py
File metadata and controls
3361 lines (2617 loc) · 127 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
# issueexec/localizer.py
import os
import json
import ijson
import logging
from pathlib import Path
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple, Any, Optional, Union
from issueexec.utils.compress_file import get_skeleton
from issueexec.utils.postprocess_data import extract_code_blocks, extract_locs_for_files
from issueexec.utils.preprocess_data import (
correct_file_paths,
get_full_file_paths_and_classes_and_functions,
get_repo_files,
line_wrap_content,
show_project_structure,
)
import ast
import re
from rank_bm25 import BM25Okapi
from issueexec.prompts import *
MAX_CONTEXT_LENGTH = 60000 # < 65536
SUSPICIOUS_LOCATION_RETRY_PREFIXES = [
# Retry 1: light constraints
"""[RETRY NOTICE] Your previous response contained locations not found in the codebase.
Please select ONLY from:
1. Locations in "Code Locations Covered by Related Tests"
2. Locations visible in the traceback that exist in the project
""",
# Retry 2: stronger constraints with explicit candidate list
"""[STRICT MODE] WARNING: You previously output invalid code locations.
Here are ALL valid locations you can choose from:
{valid_candidate_list}
You MUST select ONLY from the above list. Do NOT invent location names.
""",
# Retry 3: strict copy-only mode
"""[FINAL ATTEMPT] CRITICAL: Your output contained invalid locations.
MANDATORY: You can ONLY output locations from this EXACT list:
{valid_candidate_list}
Copy location names CHARACTER-FOR-CHARACTER from the list above.
"""
]
def normalize_traceback_path(abs_path: str, project_file_paths: List[str]) -> Optional[str]:
"""
Map an absolute traceback path to a repository-relative path.
"""
# Normalize separators for cross-platform traceback strings.
abs_path = abs_path.replace('\\', '/')
for proj_path in project_file_paths:
# Suffix match: traceback path usually ends with project-relative path.
if abs_path.endswith('/' + proj_path) or abs_path == proj_path:
return proj_path
return None
def validate_location_in_project(
loc: str,
files: List[Tuple[str, Any]],
classes: List[Dict],
functions: List[Dict]
) -> Tuple[bool, Optional[str]]:
"""
Validate whether a location string points to a real entity in the project.
Args:
loc: location string, for example:
- file_path::function_name
- file_path::ClassName
- file_path::ClassName.method_name
- file_path::ClassName::method_name
files: project files
classes: parsed classes
functions: parsed top-level functions
Returns:
(is_valid, normalized_loc): validity flag and normalized location
"""
if '::' not in loc:
return False, None
# Parse location.
parts = loc.split('::', 1)
file_path = parts[0]
identifier = parts[1] if len(parts) > 1 else ''
# Check that file exists.
file_paths = [f[0] for f in files]
if file_path not in file_paths:
return False, None
# Parse identifier part (supports both `::` and `.` method separators).
class_name = None
method_name = None
if '::' in identifier:
# Format: file::ClassName::method_name
sub_parts = identifier.split('::', 1)
class_name = sub_parts[0]
method_name = sub_parts[1] if len(sub_parts) > 1 else None
elif '.' in identifier:
# Format: file::ClassName.method_name
sub_parts = identifier.split('.', 1)
class_name = sub_parts[0]
method_name = sub_parts[1] if len(sub_parts) > 1 else None
else:
# Format: file::identifier (function/class/method name)
identifier_name = identifier
# Try top-level function first.
for func in functions:
if func.get('file') == file_path and func.get('name') == identifier_name:
return True, loc
# Then try class name.
for cls in classes:
if cls.get('file') == file_path and cls.get('name') == identifier_name:
return True, loc
# Finally try method name only (common in traceback frames).
for cls in classes:
if cls.get('file') == file_path:
for method in cls.get('methods', []):
if method.get('name') == identifier_name:
# Return normalized full location.
normalized = f"{file_path}::{cls['name']}.{identifier_name}"
return True, normalized
return False, None
# Handle explicit class-method form.
if class_name and method_name:
for cls in classes:
if cls.get('file') == file_path and cls.get('name') == class_name:
for method in cls.get('methods', []):
if method.get('name') == method_name:
# Normalize to dot style.
normalized = f"{file_path}::{class_name}.{method_name}"
return True, normalized
return False, None
# Class-only case.
if class_name and not method_name:
for cls in classes:
if cls.get('file') == file_path and cls.get('name') == class_name:
return True, f"{file_path}::{class_name}"
return False, None
return False, None
def extract_and_validate_locations_from_traceback(
issue_desc: str,
files: List[Tuple[str, Any]],
classes: List[Dict],
functions: List[Dict],
logger=None
) -> List[str]:
"""
Extract traceback frames from issue text, map them to repository paths,
and return only validated locations.
Returns locations in format: ["file_path::entity_name", ...]
"""
import re
# Standard traceback frame: File "xxx.py", line N, in func_name
pattern = r'File\s+"([^"]+)",\s+line\s+\d+,\s+in\s+(\S+)'
matches = re.findall(pattern, issue_desc)
if not matches:
if logger:
logger.info("No traceback entries found in issue description")
return []
if logger:
logger.info(f"Found {len(matches)} traceback entries")
project_file_paths = [f[0] for f in files]
validated_locations = []
seen = set() # Deduplicate candidate locations.
for abs_path, func_name in matches:
# Skip stdlib frames.
if 'python' in abs_path.lower() and 'site-packages' not in abs_path.lower():
continue
# Map absolute frame path to project path.
proj_path = normalize_traceback_path(abs_path, project_file_paths)
if not proj_path:
if logger:
logger.debug(f"Could not map traceback path to project: {abs_path}")
continue
# Build candidate location.
candidate_loc = f"{proj_path}::{func_name}"
if candidate_loc in seen:
continue
seen.add(candidate_loc)
# Validate against parsed repository structure.
is_valid, normalized_loc = validate_location_in_project(
candidate_loc, files, classes, functions
)
if is_valid and normalized_loc:
validated_locations.append(normalized_loc)
if logger:
logger.debug(f"Validated traceback location: {normalized_loc}")
else:
if logger:
logger.debug(f"Could not validate traceback location: {candidate_loc}")
# Keep order while deduplicating.
unique_locations = list(dict.fromkeys(validated_locations))
if logger:
logger.info(f"Validated {len(unique_locations)} locations from traceback")
return unique_locations
def should_retry_suspicious_locations(
all_locations: List[str],
valid_locations: List[str]
) -> bool:
"""
Decide whether suspicious-location localization should retry.
Trigger when no valid location is found, or invalid ratio >= 50%.
"""
if len(all_locations) == 0:
return False
invalid_count = len(all_locations) - len(valid_locations)
if invalid_count == 0:
return False
# Retry when invalid count is at least half.
threshold = max(1, len(all_locations) // 2)
return invalid_count >= threshold
def extract_code_references_from_issue_description(
issue_desc: str,
files: List[Tuple[str, Any]],
classes: List[Dict],
functions: List[Dict],
logger=None
) -> List[str]:
"""
Extract direct code references from issue text (files/lines/functions).
Used as fallback when coverage-based localization fails.
Strategy:
1. Regex match for Python file paths.
2. Resolve line numbers to entities via AST.
3. Validate against repository structure.
Args:
issue_desc: issue description text
files: project files [(file_path, content), ...]
classes: parsed classes
functions: parsed functions
logger: logger instance
Returns:
Validated locations: ["file_path::entity_name", ...]
"""
import re
import ast
if logger:
logger.info("Starting Issue-Direct extraction fallback")
# Build project-path and content indexes.
project_file_paths = set(f[0] for f in files)
file_content_map = {f[0]: f[1] for f in files}
extracted_locations = []
seen = set()
# Pattern 1: file path + line number.
# Example: "...admin_modify.py ... line 102"
file_line_pattern = r'["\']?([\w/]+\.py)["\']?[^0-9]*(?:line\s*|:)(\d+)'
# Pattern 2: file path only.
file_only_pattern = r'["\']?([\w/]+\.py)["\']?'
# Pattern 3: quoted function names (weak signal, reserved for future use).
func_pattern = r'["\'](\w+)["\']'
# First try file+line matches.
file_line_matches = re.finditer(file_line_pattern, issue_desc, re.IGNORECASE)
for match in file_line_matches:
file_path_candidate = match.group(1)
line_number = int(match.group(2))
# Validate file path against project files.
matched_file_path = None
for proj_path in project_file_paths:
# Allow partial-path match from issue text.
if proj_path.endswith(file_path_candidate) or file_path_candidate.endswith(proj_path) or proj_path == file_path_candidate:
matched_file_path = proj_path
break
if not matched_file_path:
if logger:
logger.debug(f"File path not found in project: {file_path_candidate}")
continue
# Try to resolve entity by line number.
entity_name = _get_entity_at_line(
file_content_map.get(matched_file_path),
line_number,
logger
)
if entity_name:
location = f"{matched_file_path}::{entity_name}"
if location not in seen:
seen.add(location)
extracted_locations.append(location)
if logger:
logger.info(f"Issue-Direct extracted (file+line): {location}")
else:
# Fallback to file-level location.
location = matched_file_path
if location not in seen:
seen.add(location)
extracted_locations.append(location)
if logger:
logger.info(f"Issue-Direct extracted (file-level fallback): {location}")
# If file+line failed, try file-only matches.
if not extracted_locations:
file_only_matches = re.finditer(file_only_pattern, issue_desc)
for match in file_only_matches:
file_path_candidate = match.group(1)
# Validate file path.
matched_file_path = None
for proj_path in project_file_paths:
if proj_path.endswith(file_path_candidate) or file_path_candidate.endswith(proj_path) or proj_path == file_path_candidate:
matched_file_path = proj_path
break
if matched_file_path and matched_file_path not in seen:
seen.add(matched_file_path)
extracted_locations.append(matched_file_path)
if logger:
logger.info(f"Issue-Direct extracted (file-only): {matched_file_path}")
if logger:
logger.info(f"Issue-Direct extraction complete: {len(extracted_locations)} locations found")
return extracted_locations
def _get_entity_at_line(
file_content: Union[str, List[str], None],
line_number: int,
logger=None
) -> Optional[str]:
"""
Resolve a line number to the innermost containing class/function entity.
Args:
file_content: file content (string or line list)
line_number: target line number (1-based)
logger: logger instance
Returns:
Entity name, or None when not found
"""
import ast
if not file_content:
return None
try:
# Ensure content is string.
if isinstance(file_content, list):
content_str = '\n'.join(file_content)
else:
content_str = file_content
tree = ast.parse(content_str)
# Collect entities with line ranges.
entities = []
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
end_line = getattr(node, 'end_lineno', node.lineno + 1)
# Detect whether function is a class method.
parent_class = _find_parent_class(tree, node)
if parent_class:
entity_name = f"{parent_class}.{node.name}"
else:
entity_name = node.name
entities.append((node.lineno, end_line, entity_name))
elif isinstance(node, ast.ClassDef):
end_line = getattr(node, 'end_lineno', node.lineno + 1)
entities.append((node.lineno, end_line, node.name))
entities.sort(key=lambda x: x[0])
best_match = None
best_range = float('inf')
for start_line, end_line, name in entities:
if start_line <= line_number <= end_line:
range_size = end_line - start_line
if range_size < best_range:
best_range = range_size
best_match = name
if best_match and logger:
logger.debug(f"Line {line_number} maps to entity: {best_match}")
return best_match
except SyntaxError as e:
if logger:
logger.warning(f"Syntax error parsing file for line mapping: {e}")
return None
except Exception as e:
if logger:
logger.warning(f"Error mapping line to entity: {e}")
return None
def _find_parent_class(tree: ast.AST, target_node: ast.FunctionDef) -> Optional[str]:
import ast
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
for child in ast.iter_child_nodes(node):
if child is target_node:
return node.name
for child in ast.walk(node):
if child is target_node and child is not node:
return node.name
return None
# testEN(extract_key_words + filter_test_cases_by_token_match)
def extract_keywords(issue_desc):
import re
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in',
'on', 'at', 'to', 'for', 'of', 'with', 'by',
'is', 'are', 'was', 'were', 'be', 'been', 'being',
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
'should', 'could', 'can', 'may', 'might', 'must', 'this', 'that',
'these', 'those', 'when', 'where', 'why', 'how', 'if', 'then', 'get',
'got', 'some', 'each', 'while', 'even', 'though', 'def'
'import', 'from', 'return', 'class', 'elif', 'else', 'pass',
'break', 'continue', 'description', 'issue', 'example',
'test', 'tests', 'testing', 'pytest', 'unittest',
'py', 'pyc', 'pyx', 'pyd',
'init', 'main', 'setup',
'util', 'utils',
'common', 'base', 'core',
'lib', 'libs', 'src',
'dot', 'dotprint', 'dotnode',
}
def remove_common_suffixes(word):
"""
Remove common English suffixes and return a simple stem.
"""
suffixes = ['ing', 'ed', 'es', 's', 'er', 'ly', 'tion', 'ment']
original = word
for suffix in suffixes:
if len(word) > len(suffix) + 2:
if word.endswith(suffix):
stem = word[:-len(suffix)]
if len(stem) >= 3:
return stem, original
return original, None
def split_compound_word(word):
parts = word.split('_')
result = []
for part in parts:
camel_split = re.sub(r'([a-z])([A-Z])', r'\1 \2', part)
result.extend(camel_split.lower().split())
return result
clean_text = re.sub(r'[^a-zA-Z0-9_\s]', ' ', issue_desc)
words = clean_text.split()
all_keywords = []
for word in words:
if len(word) > 2:
sub_words = split_compound_word(word)
for sub_word in sub_words:
stem, original = remove_common_suffixes(sub_word)
all_keywords.append(stem)
if original and original != stem:
all_keywords.append(original)
keywords = [word for word in all_keywords
if len(word) > 2 and word.lower() not in stop_words]
result = []
for word in keywords:
result.append(word.lower())
return result
def filter_test_cases_by_token_match(
issue_desc: str,
test_cases: List,
min_tests: int = 10,
max_tests: int = 200,
random_backfill: bool = False,
strict_mode: bool = False
) -> List:
from rank_bm25 import BM25Okapi
import re
import random
if not test_cases:
return []
def tokenize(text):
return extract_keywords(text)
corpus = []
for test in test_cases:
test_text = test['name'] + " " + test['name'] + " " + (test['docstring'] or "")
corpus.append(tokenize(test_text))
bm25 = BM25Okapi(corpus)
query_tokens = tokenize(issue_desc)
scores = bm25.get_scores(query_tokens)
test_score_pairs = sorted(zip(test_cases, scores), key=lambda x: x[1], reverse=True)
threshold = 0.5 if strict_mode else 0.01
matched_tests = [test for test, score in test_score_pairs if score > threshold]
unmatched_tests = [test for test, score in test_score_pairs if score <= threshold]
if len(matched_tests) < min_tests and random_backfill and unmatched_tests:
needed = min(min_tests - len(matched_tests), len(unmatched_tests))
matched_tests.extend(random.sample(unmatched_tests, needed))
return matched_tests[:max_tests]
class BaseLocalizer(ABC):
def __init__(self, instance_id, structure, problem_statement, **kwargs):
self.structure = structure
self.instance_id = instance_id
self.problem_statement = problem_statement
# Fallback: discover from repository structure
self.files, self.classes, self.functions = get_full_file_paths_and_classes_and_functions(
self.structure
)
@abstractmethod
def localize(self, top_n=1, mock=False) -> tuple[list, list, list, any]:
pass
class RelatedTestRetriever(BaseLocalizer):
def __init__(
self,
instance_id,
structure,
problem_statement,
model_name,
backend,
logger,
coverage_graph_path: Optional[str] = None,
test_functions_path: Optional[str] = None,
expand_query: bool = True,
domain_knowledge_path: Optional[str] = None,
use_online_domain_knowledge: bool = False,
repo: Optional[str] = None,
base_commit: Optional[str] = None,
repo_path: Optional[str] = None,
**kwargs,
):
super().__init__(instance_id, structure, problem_statement)
self.max_tokens = 3000
self.model_name = model_name
self.backend = backend
self.logger = logger
self.coverage_graph_path = os.path.join(coverage_graph_path, instance_id + ".json") if coverage_graph_path else None
self.test_functions_path = test_functions_path
self.use_online_domain_knowledge = use_online_domain_knowledge
self.repo = repo
self.base_commit = base_commit
self.repo_path = repo_path
if use_online_domain_knowledge:
self.domain_knowledge_path = None
self.logger.info("Online domain knowledge mode enabled - will collect after BM25 filtering")
else:
self.domain_knowledge_path = os.path.join(domain_knowledge_path, instance_id + ".json") if domain_knowledge_path else None
self.obtain_relevant_tests_prompt = obtain_relevant_tests_prompt
self.logger.info(f"=== Initializing RelatedTestRetriever for {instance_id} ===")
self.logger.info(f"Coverage graph path: {self.coverage_graph_path}")
self.logger.info(f"Test functions path: {self.test_functions_path}")
self.logger.info(f"Total files in structure: {len(self.files)}")
# Load coverage data and test functions
self.coverage_data = self._load_coverage_data()
self.logger.info(f"Coverage data loaded: {len(self.coverage_data)} entries")
self.test_functions = self._load_test_functions()
self.logger.info(f"Test functions from file: {len(self.test_functions)} functions")
self.test_functions = self._discover_test_functions()
self.logger.info(f"Test functions after discovery: {len(self.test_functions)} functions")
# query expansion
if expand_query:
self.problem_statement = self.query_expansion(problem_statement)
# ENtoken_matchENtest_functions
before_filter = len(self.test_functions)
self.test_functions = filter_test_cases_by_token_match(issue_desc=self.problem_statement, test_cases=self.test_functions, min_tests=10, max_tests=200, random_backfill=True, strict_mode=False)
self.logger.info(f"Test functions after BM25 filtering: {len(self.test_functions)} (from {before_filter})")
# Load domain knowledge
if not self.use_online_domain_knowledge:
self.domain_knowledge = self._load_domain_knowledge()
self._merge_domain_knowledge()
if self.domain_knowledge:
self.logger.info(f"Domain knowledge loaded from file: {len(self.domain_knowledge)} entries")
else:
self.domain_knowledge = {}
self.logger.info("Starting online domain knowledge collection for BM25-filtered tests...")
if len(self.test_functions) > 0:
try:
from issueexec.utils.domain_knowledge_utils import OnlineDomainKnowledgeCollector
dk_log_dir = None
for handler in self.logger.handlers:
if isinstance(handler, logging.FileHandler):
log_path = Path(handler.baseFilename)
dk_log_dir = str(log_path.parent.parent / 'domain_knowledge_logs')
break
collector = OnlineDomainKnowledgeCollector(
instance_id=self.instance_id,
repo=self.repo,
base_commit=self.base_commit,
logger=self.logger,
existing_repo_path=self.repo_path,
dk_log_dir=dk_log_dir
)
test_names = [tf['name'] for tf in self.test_functions]
if getattr(self, '_use_lazy_loading', False):
coverage_for_dk = self._load_coverage_for_tests(test_names)
self.coverage_data.update(coverage_for_dk)
else:
coverage_for_dk = self.coverage_data
domain_knowledge_map = collector.collect_for_tests(
test_names,
coverage_for_dk
)
for test in self.test_functions:
test_name = test['name']
test['domain_tokens'] = domain_knowledge_map.get(test_name, [])
with_tokens = sum(1 for tf in self.test_functions if tf.get('domain_tokens'))
total_tokens = sum(len(tf.get('domain_tokens', [])) for tf in self.test_functions)
self.logger.info(f"Online domain knowledge collection complete:")
self.logger.info(f" - Tests with tokens: {with_tokens}/{len(self.test_functions)}")
self.logger.info(f" - Total tokens: {total_tokens}")
collector.cleanup()
except ImportError as e:
self.logger.error(f"Failed to import online collector: {e}")
for test in self.test_functions:
test['domain_tokens'] = []
except Exception as e:
self.logger.error(f"Online domain knowledge collection failed: {e}", exc_info=True)
for test in self.test_functions:
test['domain_tokens'] = []
else:
self.logger.warning("No test functions after BM25 filtering, skipping domain knowledge collection")
self.logger.info(f"=== RelatedTestRetriever initialization complete ===")
if len(self.test_functions) == 0 and len(self.coverage_data) > 0:
self.logger.warning("No test functions found but coverage data exists, running diagnosis...")
self._diagnose_coverage_mismatch()
def query_expansion(self, problem_statement: str) -> str:
"""
Expand the problem statement by extracting entities and their variations
to improve test retrieval accuracy.
Args:
problem_statement: Original issue description
Returns:
expanded_problem_statement: Original statement + expanded terms
"""
from issueexec.utils.api_requests import num_tokens_from_messages
from issueexec.utils.model import make_model
# Construct the prompt message
message = query_expansion_prompt.format(
problem_statement=problem_statement
).strip()
self.logger.info("Performing query expansion on problem statement")
# Check if message is too long
if num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH:
self.logger.warning("Query expansion prompt too long, using original problem statement")
return problem_statement
try:
# Create model and generate expansion
model = make_model(
model=self.model_name,
backend=self.backend,
logger=self.logger,
max_tokens=1000, # Limit expansion output
temperature=0,
batch_size=1,
)
traj = model.codegen(message, num_samples=1)[0]
raw_output = traj["response"]
self.logger.info(f"Query expansion raw output:\n{raw_output}")
# Extract the structured expansion content
expanded_content = self._parse_expansion_output(raw_output)
if not expanded_content:
self.logger.warning("No expanded content extracted, using original problem statement")
return problem_statement
# Simple concatenation
expanded_statement = f"{problem_statement}\n\n## Expanded Query Terms:\n{expanded_content}"
self.logger.info(f"Query expansion completed. Original length: {len(problem_statement)}, "
f"Expanded length: {len(expanded_statement)}")
return expanded_statement
except Exception as e:
self.logger.error(f"Error during query expansion: {e}")
self.logger.warning("Falling back to original problem statement")
return problem_statement
def _parse_expansion_output(self, raw_output: str) -> str:
"""
Extract the structured expansion content from code blocks.
Args:
raw_output: Raw model output
Returns:
Extracted expansion content (empty string if extraction fails)
"""
import re
# Extract content from code blocks
match = re.search(r'```\s*(.*?)\s*```', raw_output, re.DOTALL)
if match:
content = match.group(1).strip()
self.logger.debug(f"Extracted expansion content:\n{content}")
return content
else:
self.logger.warning("No code block found in expansion output")
return ""
def localize(self, top_n=5, mock=False) -> Tuple[List[str], Dict[str, Any], Dict[str, Any]]:
"""
Localize relevant test functions based on the issue description.
Returns:
found_tests: List of relevant test function names
metadata: Dictionary containing intermediate results
traj: Trajectory information for the LLM call
"""
from issueexec.utils.api_requests import num_tokens_from_messages
from issueexec.utils.model import make_model
# Get available test functions
if not self.test_functions:
self.logger.warning("No test functions found")
return [], {"raw_output_tests": "", "found_tests": []}, {}
# Format test functions for prompt
test_functions_text = self._format_test_functions_for_prompt(self.test_functions)
# Conditionally prepend Related Concepts note if any test has domain_tokens
has_domain_tokens = any(
test.get('domain_tokens')
for test in self.test_functions
)
if has_domain_tokens:
related_concepts_note = """Note: Some tests include "Related Concepts" derived from historical code changes and commit analysis. These concepts may indicate:
- Terminology expansions (e.g., abbreviations to full names)
- Frequently co-modified modules
- Hidden dependencies between components
Treat these as supplementary hints rather than definitive evidence.
"""
test_functions_text = related_concepts_note + test_functions_text
# Create prompt
message = self.obtain_relevant_tests_prompt.format(
problem_statement=self.problem_statement,
test_functions=test_functions_text,
max_tests=top_n
).strip()
# Create prompt
message = self.obtain_relevant_tests_prompt.format(
problem_statement=self.problem_statement,
test_functions=test_functions_text,
max_tests=top_n
).strip()
self.logger.info(f"Prompting with message:\n{message}")
self.logger.info("=" * 80)
if mock:
self.logger.info("Skipping querying model since mock=True")
traj = {
"prompt": message,
"usage": {
"prompt_tokens": num_tokens_from_messages(message, self.model_name),
},
}
return [], {"raw_output_tests": "", "found_tests": []}, traj
# Handle context length by batching if necessary
def message_too_long(message):
return num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH
# If message is too long, process in batches
if message_too_long(message):
self.logger.info("Message too long, processing in batches")
# ENtokenEN
def safe_token_count(msg):
count = num_tokens_from_messages(msg, self.model_name)
if "deepseek" in self.model_name.lower():
count = int(count * 1.3)
return count
SAFE_MAX_LENGTH = int(MAX_CONTEXT_LENGTH * 0.7)
COMPLETION_BUFFER = 1000
# ENbatchEN
estimated_batches = 8
batch_size = max(1, len(self.test_functions) // estimated_batches)
self.logger.info(f"Starting with batch size: {batch_size}, safe max length: {SAFE_MAX_LENGTH}")
found_tests = []
all_trajs = []
i = 0
while i < len(self.test_functions):
max_attempts = 5
current_batch_size = min(batch_size, len(self.test_functions) - i)
for attempt in range(max_attempts):
if current_batch_size <= 0:
break
batch = self.test_functions[i:i + current_batch_size]
batch_text = self._format_test_functions_for_prompt(batch)
batch_message = self.obtain_relevant_tests_prompt.format(
problem_statement=self.problem_statement,
test_functions=batch_text,
max_tests=top_n
).strip()
batch_tokens = safe_token_count(batch_message)
total_needed = batch_tokens + COMPLETION_BUFFER
self.logger.info(f"Batch attempt {attempt+1} (size={current_batch_size}): {batch_tokens} tokens, total needed: {total_needed}")
if total_needed <= SAFE_MAX_LENGTH:
break
else:
self.logger.warning(f"Batch too large ({total_needed} > {SAFE_MAX_LENGTH}), reducing size...")
current_batch_size = max(1, current_batch_size // 2)
if current_batch_size == 1 and total_needed > SAFE_MAX_LENGTH:
self.logger.error(f"Skipping oversized function: {batch[0].get('name', 'unknown')}")
i += 1
current_batch_size = 0
break
if current_batch_size > 0:
try:
model = make_model(
model=self.model_name,
backend=self.backend,
logger=self.logger,
max_tokens=self.max_tokens,
temperature=0,
batch_size=1,
)
batch_traj = model.codegen(batch_message, num_samples=1)[0]
batch_traj["prompt"] = batch_message
all_trajs.append(batch_traj)
batch_found_tests = self._parse_model_return_lines(batch_traj["response"])
found_tests.extend(batch_found_tests)
self.logger.info(f"Batch completed successfully, found {len(batch_found_tests)} tests")
i += current_batch_size
except Exception as e:
self.logger.error(f"Batch processing failed: {e}")
i += current_batch_size
# Merge trajectories
traj = {
"prompt": message,