forked from SWE-bench/SWE-smith
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbug_gen_modal.py
More file actions
2033 lines (1679 loc) · 73.5 KB
/
bug_gen_modal.py
File metadata and controls
2033 lines (1679 loc) · 73.5 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
"""
Modal Bug Generation & Validation Script
All logs are persisted to a Modal Volume.
Run with: modal run scripts/bug_gen.py [OPTIONS]
"""
import asyncio
import json
import logging
import shutil
import sys
from pathlib import Path
import modal
modal.enable_output()
# ============================================================================
# Asyncio Exception Logging (to diagnose 'socket.send() raised exception')
# ============================================================================
class DeduplicatingFilter(logging.Filter):
"""A logging filter that suppresses repeated log messages after a threshold."""
def __init__(self, max_repeats: int = 5):
super().__init__()
self.max_repeats = max_repeats
self._message_counts: dict[str, int] = {}
def filter(self, record: logging.LogRecord) -> bool:
# Create a key from the log message (truncate to avoid memory issues)
msg_key = f"{record.levelname}:{record.getMessage()[:100]}"
self._message_counts[msg_key] = self._message_counts.get(msg_key, 0) + 1
count = self._message_counts[msg_key]
if count <= self.max_repeats:
if count == self.max_repeats:
# Modify the message to indicate suppression
record.msg = f"{record.msg} (further repeats will be suppressed)"
return True
elif count % 1000 == 0:
# Log summary every 1000 occurrences
record.msg = f"[Repeated {count}x] {record.msg}"
return True
return False
def setup_asyncio_exception_logging():
"""
Configure asyncio to limit duplicate log messages and capture exception details.
The 'socket.send() raised exception' warning is logged by asyncio's
_SelectorSocketTransport.write() when an SSL/socket error occurs. This
adds a deduplication filter to prevent log spam.
"""
# Get the asyncio logger and clear any existing handlers to avoid duplicates
asyncio_logger = logging.getLogger("asyncio")
# Remove existing handlers to prevent duplicate output
asyncio_logger.handlers.clear()
# Add a deduplicating filter
dedup_filter = DeduplicatingFilter(max_repeats=5)
# Set up a detailed formatter with the dedup filter
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)d]"
)
)
handler.addFilter(dedup_filter)
asyncio_logger.addHandler(handler)
asyncio_logger.setLevel(logging.WARNING) # Only warnings and above
asyncio_logger.propagate = (
False # Don't propagate to root logger (prevents duplicates)
)
# Store exception counts to avoid log spam for unhandled exceptions
_exception_counts: dict[str, int] = {}
def custom_exception_handler(loop, context):
"""Custom exception handler that logs full exception details with deduplication."""
exception = context.get("exception")
message = context.get("message", "Unknown async error")
# Create a key for rate limiting
exc_type = type(exception).__name__ if exception else "Unknown"
exc_key = f"{exc_type}:{message[:50]}"
_exception_counts[exc_key] = _exception_counts.get(exc_key, 0) + 1
count = _exception_counts[exc_key]
# Only log full details for first 5 occurrences of each type
if count <= 5:
if exception:
logging.error(
f"Asyncio exception #{count}: {message}\n"
f" Exception type: {type(exception).__name__}\n"
f" Exception: {exception}\n"
f" Context: {context}"
)
if count == 5:
logging.warning(
f" (Further '{exc_key}' exceptions will be suppressed)"
)
else:
logging.error(f"Asyncio error #{count}: {message} | Context: {context}")
elif count % 1000 == 0:
# Log summary every 1000 occurrences
logging.warning(f"Asyncio '{exc_key}' exception count: {count}")
return custom_exception_handler
# ============================================================================
# Constants & Configuration
# ============================================================================
APP_NAME = "swesmith-bug-gen"
VOLUME_NAME = "swesmith-bug-gen"
MINUTES = 60
MODAL_TIMEOUT = 10 * MINUTES
SANDBOX_RATE_LIMIT = 4 # Modal limits to 5/s, use 4 to be safe
LANGUAGE_TO_BASE_CLASS = {
"python": "PythonProfile",
"javascript": "JavaScriptProfile",
"typescript": "TypeScriptProfile",
"golang": "GoProfile",
"go": "GoProfile",
"ruby": "RubyProfile",
"rust": "RustProfile",
"java": "JavaProfile",
"c": "CProfile",
"cpp": "CppProfile",
"csharp": "CSharpProfile",
"php": "PhpProfile",
}
TEST_OUTPUT_START = ">>>>> Start Test Output"
TEST_OUTPUT_END = ">>>>> End Test Output"
PREGOLD_TIMEOUT = 500 # seconds - skip post-gold if baseline exceeds this
MIN_PATCHES_FOR_VALIDATION = 50 # skip repos with fewer patches
REMOTE_VALIDATOR_SCRIPT = r"""
import sys
import json
import subprocess
import os
from pathlib import Path
# We need to make sure we can import these.
# The image sets PYTHONPATH=/root, and swesmith is at /root/swesmith
if "/root" not in sys.path:
sys.path.append("/root")
from swesmith.harness.grading import get_valid_report
from swesmith.constants import TEST_OUTPUT_START, TEST_OUTPUT_END
def main():
try:
config_path = sys.argv[1]
with open(config_path, 'r') as f:
config = json.load(f)
test_cmd = config['test_cmd']
output_path = Path(config['output_path'])
baseline_path = Path(config['baseline_path'])
report_path = Path(config['report_path'])
instance = config['instance']
# Ensure output directory exists (it's on a volume mount)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Run test command
print(f"Executing test: {test_cmd}")
full_cmd = f"set -uxo pipefail; : '{TEST_OUTPUT_START}'; {test_cmd} || true; : '{TEST_OUTPUT_END}'"
# execution
proc = subprocess.run(
full_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
executable="/bin/bash"
)
output_bytes = proc.stdout
exit_code = proc.returncode
# Decode
output_str = output_bytes.decode('utf-8', errors='replace')
# Write output to volume
output_path.write_text(output_str, encoding='utf-8')
print(f"Saved output to {output_path}")
result_summary = {
"instance_id": instance.get("instance_id"),
"valid": False,
"error": None,
"exit_code": exit_code
}
# Check baseline and validate
if baseline_path.exists():
print(f"Baseline found at {baseline_path}, validating...")
try:
report = get_valid_report(
val_pregold_path=str(baseline_path),
val_postgold_path=str(output_path),
instance=instance
)
report_path.write_text(json.dumps(report, indent=4))
print(f"Saved report to {report_path}")
if len(report.get("PASS_TO_FAIL", [])) > 0:
result_summary["valid"] = True
print("Validation SUCCESS: Found PASS_TO_FAIL")
else:
print("Validation result: No PASS_TO_FAIL")
except Exception as e:
print(f"Validation error: {e}")
result_summary["error"] = f"Grading error: {str(e)}"
else:
print(f"Baseline NOT found at {baseline_path}")
result_summary["error"] = "Baseline not found"
# Output result as JSON marked with special tags
print(f"\n<<RESULT_JSON>>{json.dumps(result_summary)}<<RESULT_JSON>>")
except Exception as e:
import traceback
traceback.print_exc()
# Fallback error result
res = {"valid": False, "error": str(e)}
print(f"\n<<RESULT_JSON>>{json.dumps(res)}<<RESULT_JSON>>")
if __name__ == "__main__":
main()
"""
# ============================================================================
# Profile & Repo Utilities
# ============================================================================
def get_repos_for_language(language: str) -> list[str]:
"""Get all registered repos for a given language."""
from swesmith.profiles import registry
base_class_name = LANGUAGE_TO_BASE_CLASS.get(language.lower())
if not base_class_name:
raise ValueError(
f"Unknown language: {language}. Supported: {list(LANGUAGE_TO_BASE_CLASS.keys())}"
)
return [
f"{profile.owner}/{profile.repo}"
for profile in registry.values()
if profile.__class__.__name__ != base_class_name
and base_class_name in [base.__name__ for base in profile.__class__.__mro__]
]
def resolve_profile(repo_name: str):
"""Resolve a profile from repo name using robust lookup."""
from swesmith.profiles import registry
try:
profile = registry.get(repo_name)
profile.arch = "x86_64"
return profile
except KeyError:
for key in registry.keys():
try:
p = registry.get(key)
if f"{p.owner}/{p.repo}" == repo_name:
p.arch = "x86_64"
return p
except Exception:
continue
raise RuntimeError(f"No profile found for repo: {repo_name}")
# ============================================================================
# Modal Setup & Images
# ============================================================================
generator_image = (
modal.Image.from_registry("ubuntu:22.04", add_python="3.11")
.apt_install("git")
.pip_install_from_pyproject("pyproject.toml", optional_dependencies=["generate"])
.env({"PYTHONPATH": "/root"})
.add_local_dir("swesmith", remote_path="/root/swesmith")
.add_local_file(".env", remote_path="/root/.env")
)
# Global cache for validator images - populated by prebuild_validator_images()
_validator_image_cache: dict[str, modal.Image] = {}
def _create_validator_image(image_name: str) -> modal.Image:
"""Create a validator image for the given Docker image name (internal helper)."""
return (
modal.Image.from_registry(image_name, add_python="3.11")
.pip_install_from_pyproject(
"pyproject.toml", optional_dependencies=["validate"]
)
.env({"PYTHONPATH": "/root"})
.add_local_dir("swesmith", remote_path="/root/swesmith")
)
def get_validator_image(image_name: str) -> modal.Image:
"""Get or create a validator image for the given Docker image name.
Uses the global cache if available (populated by prebuild_validator_images).
"""
if image_name in _validator_image_cache:
return _validator_image_cache[image_name]
print(
f"DEBUG: get_validator_image called for {image_name} (not cached, building...)"
)
image = _create_validator_image(image_name)
_validator_image_cache[image_name] = image
return image
async def prebuild_validator_images_async(
repos_with_patches: dict,
) -> dict[str, modal.Image]:
"""Pre-build and cache all validator images for the given repositories.
This builds all unique Docker images by running a simple warmup command
in each image before any validation runs. This forces Modal to build
and upload all images in parallel upfront.
Returns the cache dict of image_name -> modal.Image
"""
global _validator_image_cache
# Collect unique image names
unique_images = set()
for repo, info in repos_with_patches.items():
profile = info["profile"]
if hasattr(profile, "image_name") and profile.image_name:
unique_images.add(profile.image_name)
print(f"\n{'=' * 60}")
print(f"PRE-BUILDING VALIDATOR IMAGES ({len(unique_images)} unique images)")
print(f"{'=' * 60}\n")
# Filter out already-cached images
to_build = [img for img in unique_images if img not in _validator_image_cache]
if not to_build:
print("All images already cached!")
return _validator_image_cache
print(f"Building {len(to_build)} images in parallel...")
for i, img in enumerate(to_build, 1):
print(f" [{i}] {img}")
# Create all image objects and cache them using the helper
for img_name in to_build:
_validator_image_cache[img_name] = _create_validator_image(img_name)
# Now run warmup sandboxes to force Modal to build all images
async def warmup_all():
semaphore = asyncio.Semaphore(100) # Limit concurrent builds
async def warmup_image(img_name: str) -> tuple[str, bool, str]:
"""Run a simple command to force image build."""
async with semaphore:
try:
# Rate limit sandbox creation
await _sandbox_rate_limiter.acquire()
print(f" Building: {img_name}...")
image = _validator_image_cache[img_name]
sb = await modal.Sandbox.create.aio(
app=app, image=image, timeout=300
)
process = await sb.exec.aio("echo", "warmup_ok")
output = await process.stdout.read.aio()
await sb.terminate.aio()
print(f" ✓ Built: {img_name}")
return (img_name, True, "")
except Exception as e:
print(f" ✗ Failed: {img_name} - {e}")
return (img_name, False, str(e))
tasks = [warmup_image(img) for img in to_build]
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
print("\nWarming up images (this triggers the actual build/upload)...")
results = await warmup_all()
# Report results
success = sum(1 for r in results if isinstance(r, tuple) and r[1])
failed = len(results) - success
print(f"\nImage build complete: {success} succeeded, {failed} failed")
if failed > 0:
for r in results:
if isinstance(r, tuple) and not r[1]:
print(f" Failed: {r[0]} - {r[2]}")
print()
return _validator_image_cache
app = modal.App(APP_NAME)
# Use Volume v2 for better scalability (more files, concurrent writes, faster commits)
logs_volume = modal.Volume.from_name(VOLUME_NAME, create_if_missing=True, version=2)
LOGS_MOUNT_PATH = "/logs" # Where the volume is mounted in Modal containers
# ============================================================================
# Volume I/O Helpers
# ============================================================================
async def volume_write_text(path: str, content: str) -> None:
"""Write text content to a path on the Modal Volume."""
import io
def _write():
with logs_volume.batch_upload() as batch:
batch.put_file(io.BytesIO(content.encode("utf-8")), path)
await asyncio.to_thread(_write)
async def volume_write_bytes(path: str, content: bytes) -> None:
"""Write binary content to a path on the Modal Volume."""
import io
def _write():
with logs_volume.batch_upload() as batch:
batch.put_file(io.BytesIO(content), path)
await asyncio.to_thread(_write)
async def volume_read_text(path: str) -> str | None:
"""Read text content from the Modal Volume. Returns None if file doesn't exist."""
try:
chunks = []
async for chunk in logs_volume.read_file.aio(path):
chunks.append(chunk)
return b"".join(chunks).decode("utf-8")
except Exception:
return None
async def volume_file_exists(path: str) -> bool:
"""Check if a file exists on the Modal Volume."""
try:
# listdir is much faster than reading the file as it only fetches metadata
await logs_volume.listdir.aio(path)
return True
except Exception:
return False
async def volume_list_dir(path: str) -> list[str]:
"""List files/directories in a path on the Modal Volume."""
try:
entries = await logs_volume.listdir.aio(path)
return [e.path for e in entries]
except Exception:
return []
# ============================================================================
# Rate Limiter for Sandbox Creation
# ============================================================================
class AsyncRateLimiter:
"""Token bucket rate limiter for controlling sandbox creation rate."""
def __init__(self, rate: float):
"""Create rate limiter with given rate (operations per second)."""
self.rate = rate
self.interval = 1.0 / rate # Time between operations
self._lock = asyncio.Lock()
self._last_time = 0.0
async def acquire(self):
"""Wait until rate limit allows another operation."""
async with self._lock:
import time
now = time.monotonic()
wait_time = self._last_time + self.interval - now
if wait_time > 0:
await asyncio.sleep(wait_time)
now = time.monotonic()
self._last_time = now
# Global rate limiter for sandbox creation (Modal limit: 5/s)
_sandbox_rate_limiter = AsyncRateLimiter(SANDBOX_RATE_LIMIT)
# ============================================================================
# Remote Bug Generation
# ============================================================================
@app.function(
image=generator_image,
secrets=[modal.Secret.from_name("GITHUB_TOKEN")],
timeout=MODAL_TIMEOUT,
volumes={LOGS_MOUNT_PATH: logs_volume}, # Mount volume for direct writes
)
def generate_bugs_remote(
repo_name: str,
max_bugs: int,
interleave: bool,
max_entities: int,
max_candidates: int,
language: str,
timeout_buffer_seconds: int = 60,
) -> dict:
"""Generate bugs for a repository on a remote Modal worker.
Results are saved directly to the Modal Volume, reducing data transfer.
Returns only a lightweight summary.
"""
import sys
from io import StringIO
if "/root" not in sys.path:
sys.path.append("/root")
from swesmith.profiles import registry
from swesmith.bug_gen.procedural.generate import main as generate_main
from swesmith.bug_gen.collect_patches import main as collect_patches_main
# Setup output capture
log_buffer = StringIO()
original_stdout, original_stderr = sys.stdout, sys.stderr
class TeeWriter:
def __init__(self, buffer, original):
self.buffer, self.original = buffer, original
def write(self, data):
self.buffer.write(data)
self.original.write(data)
def flush(self):
self.buffer.flush()
self.original.flush()
sys.stdout = TeeWriter(log_buffer, original_stdout)
sys.stderr = TeeWriter(log_buffer, original_stderr)
# Resolve repo ID
def resolve_repo_id():
try:
return registry.get_from_inst(
{"repo": repo_name, "instance_id": "dummy"}
).repo_name
except Exception as e:
print(f"Direct profile lookup failed for {repo_name}: {e}")
target = repo_name.replace("/", "__")
candidates = [key for key in registry.keys() if target in key]
return candidates[0] if candidates else repo_name
repo_id = resolve_repo_id()
print(f"Resolved repo_id: {repo_id}")
logs_base = Path("logs/bug_gen")
# Volume paths for saving results
volume_base = Path(LOGS_MOUNT_PATH)
volume_bug_dir = volume_base / language / "bug_gen" / repo_id
def _safe_execute(func, error_msg, *args, **kwargs):
import traceback
try:
return func(*args, **kwargs)
except Exception as e:
print(f"{error_msg}: {e}")
traceback.print_exc()
return None
def save_results_to_volume() -> dict:
"""Collect results and save directly to Modal Volume. Returns summary."""
if not logs_base.exists():
print(f"LOGS BASE MISSING: {logs_base}")
return {"error": f"Logs directory {logs_base} does not exist."}
generated_dirs = [d for d in logs_base.iterdir() if d.is_dir()]
if not generated_dirs:
print(f"NO DATA IN LOGS BASE. Files: {list(logs_base.glob('**/*'))}")
return {"error": "No data generated"}
repo_id_actual = sorted(
generated_dirs, key=lambda x: x.stat().st_mtime, reverse=True
)[0].name
print(f"Detected repo_id_actual: {repo_id_actual}")
_safe_execute(
collect_patches_main,
"Error in collect_patches_main",
str(logs_base / repo_id_actual),
)
# Ensure volume directory exists
volume_bug_dir.mkdir(parents=True, exist_ok=True)
# Create and save zip
def _save_zip():
shutil.make_archive(
f"/tmp/{repo_id_actual}", "zip", str(logs_base / repo_id_actual)
)
zip_path = f"/tmp/{repo_id_actual}.zip"
dest_path = volume_bug_dir / "bugs.zip"
shutil.copy(zip_path, dest_path)
print(f"Saved bugs.zip to volume: {dest_path}")
_safe_execute(_save_zip, "Error saving zip to volume")
# Read and save patches
patches_file = logs_base / f"{repo_id_actual}_all_patches.json"
if patches_file.exists():
patches_json = patches_file.read_text()
patches = json.loads(patches_json)
# Save patches to volume
patches_dest = (
volume_base / language / "bug_gen" / f"{repo_id}_all_patches.json"
)
patches_dest.write_text(patches_json)
print(f"Saved {len(patches)} patches to volume: {patches_dest}")
if not patches:
# Mark as done with 0 bugs
(volume_bug_dir / "done.txt").write_text(
"Generation completed: 0 bugs generated"
)
return {"total_bugs": 0, "patches": []}
# Mark as done
(volume_bug_dir / "done.txt").write_text(
f"Generation completed: {len(patches)} bugs generated"
)
logs_volume.commit() # Force internal commit to persist done.txt immediately
return {"total_bugs": len(patches), "patches": patches}
else:
print(
f"Patches file not found. Available: {[p.name for p in logs_base.iterdir()]}"
)
(volume_bug_dir / "error.txt").write_text("No patches_json generated")
logs_volume.commit()
return {"error": "No patches_json generated"}
soft_timeout = MODAL_TIMEOUT - timeout_buffer_seconds
print(f"Soft timeout: {soft_timeout}s")
result = {"repo": repo_name, "repo_id": repo_id}
try:
generate_main(
repo=repo_id,
max_bugs=max_bugs,
seed=24,
interleave=interleave,
max_entities=max_entities,
max_candidates=max_candidates,
timeout_seconds=soft_timeout,
)
except Exception as e:
import traceback
print(f"Error in generate_main: {e}")
traceback.print_exc()
finally:
sys.stdout, sys.stderr = original_stdout, original_stderr
print("\nCollecting and saving results to volume...")
collection_result = _safe_execute(
save_results_to_volume, "Error saving results"
)
if collection_result:
result.update(collection_result)
else:
result["error"] = "Failed to collect results"
# Save log to volume
log_content = log_buffer.getvalue()
try:
volume_bug_dir.mkdir(parents=True, exist_ok=True)
(volume_bug_dir / "modal_output.log").write_text(log_content)
except Exception as e:
print(f"Failed to save log: {e}")
# If there was an error, write error file
if "error" in result:
try:
(volume_bug_dir / "error.txt").write_text(
f"Bug generation failed: {result['error']}"
)
except:
pass
# Commit volume changes
logs_volume.commit()
return result
# ============================================================================
# Validation Sandbox
# ============================================================================
async def run_validation_in_sandbox(
semaphore: asyncio.Semaphore,
app: modal.App,
image_name: str,
instance_id: str,
test_cmd: str,
workdir: str,
patch: str | None,
timeout: int,
postgold_config: dict | None = None,
) -> dict:
"""
Run validation in a Modal Sandbox with a specific Docker image.
If postgold_config is provided, runs the remote validator script and returns
summary metadata. Results are written directly to the volume.
If postgold_config is None, runs generic test cmd and returns output.
"""
async with semaphore:
# print(f"[{instance_id}] Getting validator image ({image_name})...")
validator_image = get_validator_image(image_name)
script_lines = [
"#!/bin/bash",
"exec 2>&1",
"set -uxo pipefail",
f"cd {workdir}",
"git checkout .",
]
if patch:
script_lines.extend(
[
f"cat > /tmp/{instance_id}.diff << 'PATCH_EOF'",
patch,
"PATCH_EOF",
f"git apply /tmp/{instance_id}.diff",
]
)
# Prepare Sandbox arguments
sandbox_kwargs = {
"app": app,
"image": validator_image,
"timeout": timeout,
}
if postgold_config:
# Mount logs volume for direct writing
sandbox_kwargs["volumes"] = {LOGS_MOUNT_PATH: logs_volume}
# Write config and validator script
config_json = json.dumps(postgold_config)
script_lines.extend(
[
"cat > /tmp/config.json << 'CONFIG_EOF'",
config_json,
"CONFIG_EOF",
"cat > /tmp/validator.py << 'SCRIPT_EOF'",
REMOTE_VALIDATOR_SCRIPT,
"SCRIPT_EOF",
"python3 /tmp/validator.py /tmp/config.json",
]
)
else:
# Legacy/Pregold mode: just run test
script_lines.extend(
[
f": '{TEST_OUTPUT_START}'",
f"{test_cmd} || true",
f": '{TEST_OUTPUT_END}'",
]
)
sb = None
sandbox_id = None # Track sandbox ID for debugging
current_step = "init" # Track current step for error reporting
# Debug logging helper
import time
debug_sandbox = True # Set to True to enable detailed sandbox logging
def _log(step: str, msg: str = ""):
nonlocal current_step
current_step = step
if debug_sandbox:
ts = time.strftime("%H:%M:%S")
extra = f" - {msg}" if msg else ""
print(f"[{ts}][{instance_id}] {step}{extra}")
try:
# Rate limit sandbox creation (Modal limit: 5/s)
_log("rate_limit", "acquiring...")
await _sandbox_rate_limiter.acquire()
_log("rate_limit", "acquired")
# Create sandbox
_log("create_sandbox", f"image={image_name}, timeout={timeout}s")
sb = await modal.Sandbox.create.aio(**sandbox_kwargs)
sandbox_id = getattr(sb, "object_id", None) or getattr(
sb, "_object_id", "unknown"
)
_log("create_sandbox", f"created (sandbox_id={sandbox_id})")
# Write script to file directly using sandbox.open() to avoid ARG_MAX limit
script_content = "\n".join(script_lines)
script_size = len(script_content)
# Write script file directly to sandbox filesystem (more robust than stdin)
_log("write_script", f"opening /tmp/run.sh ({script_size} bytes)")
f = await sb.open.aio("/tmp/run.sh", "w")
_log("write_script", "writing content")
await f.write.aio(script_content)
_log("write_script", "closing file")
await f.close.aio()
_log("write_script", "done")
# Execute the script
_log("exec_script", "starting bash /tmp/run.sh")
process = await sb.exec.aio("bash", "/tmp/run.sh")
_log("exec_script", "process started")
_log("read_stdout", "reading...")
output_raw = await process.stdout.read.aio()
output_size = len(output_raw) if output_raw else 0
_log("read_stdout", f"done ({output_size} bytes)")
_log("wait_exit", "waiting for exit code...")
exit_code = await process.wait.aio()
_log("wait_exit", f"exit_code={exit_code}")
output = (
output_raw.decode("utf-8", errors="replace")
if isinstance(output_raw, bytes)
else output_raw
)
# print(f'{output=}')
if postgold_config:
# Parse JSON result from output
if "<<RESULT_JSON>>" in output:
try:
json_str = output.split("<<RESULT_JSON>>")[1]
result = json.loads(json_str)
# Ensure error is propagated if script failed but printed JSON
if result.get("exit_code", 0) != 0 and not result.get("error"):
# This usually shouldn't happen with our script unless test failed (which is normal)
# But let's trust the 'valid' flag and 'error' field
pass
return result
except Exception as e:
return {
"instance_id": instance_id,
"error": f"Failed to parse remote result: {e}",
"raw_output": output,
"step": current_step,
"sandbox_id": sandbox_id,
}
else:
return {
"instance_id": instance_id,
"error": "No remote result found",
"raw_output": output,
"step": current_step,
"sandbox_id": sandbox_id,
}
else:
return {
"instance_id": instance_id,
"output": output,
"exit_code": exit_code,
}
except Exception as e:
err_str = str(e)
_log("exception", f"ERROR: {err_str[:200]}")
return {
"instance_id": instance_id,
"error": err_str[:2000],
"step": current_step,
"sandbox_id": sandbox_id,
}
finally:
# Always terminate sandbox to prevent zombie connections
if sb is not None:
try:
await sb.terminate.aio()
except Exception:
pass # Ignore errors during cleanup
# ============================================================================
# Generation Phase (using Modal .map() for true parallel processing)
# ============================================================================
async def run_generation_phase(repos: list[str], args, language: str) -> list[dict]:
"""Run bug generation for all repos in parallel using Modal .map().
Uses Modal's .map() for true parallel processing with autoscaling workers.
Each worker saves results directly to the Volume, reducing data transfer.
Returns lightweight summaries.
"""
print(f"{'#' * 60}")
print(f"# PHASE 1: BUG GENERATION ({len(repos)} repos)")
print(f"{'#' * 60}\n")
# Prepare inputs: resolve profiles and filter already-processed repos
repo_inputs = [] # List of (repo_name, repo_id) tuples for repos to process
skipped_done = 0
skipped_error = 0
failed_to_resolve = [] # Repos that failed profile resolution
# First, resolve all profiles (can be done in parallel too, but usually fast)
resolved_repos = [] # List of (repo, repo_id) tuples
for repo in repos:
try:
profile = resolve_profile(repo)
resolved_repos.append((repo, profile.repo_name))
except Exception as e:
failed_to_resolve.append(
{
"repo": repo,
"repo_id": None,
"error": f"Failed to resolve profile: {e}",
}
)
# Parallelize volume existence checks using asyncio
# Each repo needs 3 checks: done.txt, error.txt, patches.json
async def check_repo_status(repo_tuple: tuple[str, str]) -> tuple[str, str, str]:
"""Check if a repo is already processed. Returns (repo, repo_id, status)."""
repo, repo_id = repo_tuple
volume_bug_dir = f"{language}/bug_gen/{repo_id}"
if await volume_file_exists(f"{volume_bug_dir}/done.txt"):
return (repo, repo_id, "done")
elif await volume_file_exists(f"{volume_bug_dir}/error.txt"):
return (repo, repo_id, "error")
elif await volume_file_exists(f"{language}/bug_gen/{repo_id}_all_patches.json"):
return (repo, repo_id, "patches_exist")
else:
return (repo, repo_id, "pending")
print(f" Checking {len(resolved_repos)} repos for existing results (parallel)...")
semaphore = asyncio.Semaphore(100)
async def check_with_sem(repo_tuple):
async with semaphore:
return await check_repo_status(repo_tuple)
tasks = [check_with_sem(rt) for rt in resolved_repos]
if tasks:
results = await asyncio.gather(*tasks)
else:
results = []
for repo, repo_id, status in results:
if status == "done":
print(f" Skipping {repo}: already completed")
skipped_done += 1
elif status == "error":
print(f" Skipping {repo}: previously failed")
skipped_error += 1
elif status == "patches_exist":
print(f" Skipping {repo}: patches already exist")
skipped_done += 1