forked from openai/human-eval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrust_execution.py
More file actions
1285 lines (1115 loc) · 43.7 KB
/
rust_execution.py
File metadata and controls
1285 lines (1115 loc) · 43.7 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
"""
Rust-specific execution module for HumanEval evaluation.
Handles compilation and test execution of Rust code completions with sandboxing support.
Copyright (c) 2025 Dave Tofflemire, SigilDERG Project
Version: 3.0.0
"""
import multiprocessing
import os
import re
import shutil
import subprocess
import time
import unicodedata
# Use relative import to avoid circular dependency with execution.py
from .execution import create_tempdir, reliability_guard
# Try to import sandbox module (optional)
try:
from .sandbox import SandboxError, run_binary_sandboxed, run_rustc_sandboxed
SANDBOX_AVAILABLE = True
except ImportError:
SANDBOX_AVAILABLE = False
SandboxError = Exception
# Define stub functions to satisfy type checker
# These will never be called because SANDBOX_AVAILABLE is False
def run_rustc_sandboxed(
source_file: str,
output_binary: str,
command_args: list[str],
timeout: float = 30.0,
capture_output: bool = True,
sandbox_mode: str | None = None,
) -> subprocess.CompletedProcess[str]:
raise RuntimeError("Sandbox not available")
def run_binary_sandboxed(
binary_path: str,
timeout: float = 30.0,
capture_output: bool = True,
sandbox_mode: str | None = None,
) -> subprocess.CompletedProcess[str]:
raise RuntimeError("Sandbox not available")
DISALLOWED_COMPLETION_PATTERNS = [
# Filesystem operations
"std::fs",
"std::path",
"std::io::write",
"std::io::read",
"std::io::copy",
"std::io::create",
"std::io::remove",
"std::io::rename",
"std::io::metadata",
"std::io::symlink",
"std::io::hard_link",
"std::io::canonicalize",
"std::io::read_dir",
"std::io::read_to_string",
"std::io::read_to_end",
"std::io::read_exact",
"std::io::write_all",
"std::io::write_fmt",
"std::io::flush",
"std::io::seek",
"std::io::set_permissions",
"std::io::remove_file",
"std::io::remove_dir",
"std::io::remove_dir_all",
"std::io::create_dir",
"std::io::create_dir_all",
"std::io::rename",
"std::io::copy",
"std::io::hard_link",
"std::io::symlink_metadata",
"std::io::read_link",
"std::io::canonicalize",
"std::io::File::create",
"std::io::File::open",
"std::io::File::create_new",
"std::io::File::read",
"std::io::File::write",
# Process and system operations
"std::process",
"std::process::Command",
"std::process::Command::new",
"std::process::Command::spawn",
"std::process::Command::output",
"std::process::Command::status",
"std::process::exit",
"std::process::abort",
"std::process::id",
"std::process::parent_id",
"command::new",
"command::spawn",
"command::output",
# Network operations
"std::net",
"std::net::TcpStream",
"std::net::TcpListener",
"std::net::UdpSocket",
"std::net::UnixStream",
"std::net::UnixListener",
"std::net::SocketAddr",
"std::net::IpAddr",
"std::net::Ipv4Addr",
"std::net::Ipv6Addr",
"std::net::ToSocketAddrs",
"std::net::lookup_host",
"reqwest",
"ureq",
"hyper",
"tokio::net",
"tokio::net::TcpStream",
"tokio::net::TcpListener",
"tokio::net::UdpSocket",
"tokio::net::UnixStream",
"tokio::net::UnixListener",
# Threading and concurrency
"std::thread",
"std::thread::spawn",
"std::thread::Builder",
"std::thread::Thread",
"std::thread::park",
"std::thread::yield_now",
"std::thread::sleep",
"std::thread::available_parallelism",
"std::sync::mpsc",
"std::sync::mpsc::channel",
"std::sync::mpsc::sync_channel",
"std::sync::Arc",
"std::sync::Mutex",
"std::sync::RwLock",
"std::sync::Condvar",
"std::sync::Barrier",
"std::sync::Once",
"std::sync::atomic",
"tokio::spawn",
"tokio::task",
"tokio::runtime",
# Unsafe code
"unsafe",
"unsafe fn",
"unsafe trait",
"unsafe impl",
"unsafe block",
"unsafe {}",
# Memory operations
"std::alloc",
"std::alloc::alloc",
"std::alloc::dealloc",
"std::alloc::realloc",
"std::alloc::Layout",
"std::ptr",
"std::ptr::null",
"std::ptr::null_mut",
"std::ptr::read",
"std::ptr::write",
"std::ptr::copy",
"std::ptr::copy_nonoverlapping",
"std::ptr::swap",
"std::ptr::replace",
"std::ptr::drop_in_place",
"std::mem",
"std::mem::forget",
"std::mem::transmute",
"std::mem::zeroed",
"std::mem::uninitialized",
"std::mem::replace",
"std::mem::swap",
"std::mem::take",
"std::mem::size_of",
"std::mem::align_of",
"std::mem::size_of_val",
"std::mem::align_of_val",
"std::mem::needs_drop",
"std::mem::drop",
"std::mem::forget",
"std::mem::transmute",
"std::mem::zeroed",
"std::mem::uninitialized",
"std::mem::MaybeUninit",
# Environment and system
"std::env",
"std::env::var",
"std::env::vars",
"std::env::set_var",
"std::env::remove_var",
"std::env::current_dir",
"std::env::set_current_dir",
"std::env::args",
"std::env::args_os",
"std::env::consts",
"std::env::home_dir",
"std::env::temp_dir",
# Time and system calls
"std::time::SystemTime",
"std::time::UNIX_EPOCH",
"std::time::Duration",
# Note: std::time::Instant is allowed for benchmarking
# External process execution
"std::os",
"std::os::unix",
"std::os::windows",
"std::os::linux",
"std::os::macos",
# FFI (Foreign Function Interface)
"extern",
'extern "C"',
'extern "system"',
"libc",
"winapi",
# Dynamic loading
"std::ffi",
"std::ffi::CString",
"std::ffi::CStr",
"std::ffi::OsString",
"std::ffi::OsStr",
"std::ffi::NulError",
# Signal handling
"std::signal",
"libc::signal",
# Other dangerous patterns
"std::panic",
"std::panic::panic",
"std::panic::panic_any",
"std::panic::set_hook",
"std::panic::take_hook",
"std::panic::catch_unwind",
"std::panic::resume_unwind",
"std::panic::AssertUnwindSafe",
# Compile-time code execution
"include!",
"include_str!",
"include_bytes!",
"env!",
"option_env!",
"concat!",
"file!",
"line!",
"column!",
"module_path!",
# Assembly
"asm!",
"global_asm!",
# FFI/Linking
"#[link",
"#[no_mangle]",
"#[export_name",
"build.rs",
# Proc macros
"proc_macro",
# Note: #[derive( is checked separately to allow safe derives
# Additional dangerous patterns
"std::intrinsics",
"core::intrinsics",
]
# Safe derive macros that are allowed
SAFE_DERIVE_MACROS = {
"Debug", "Clone", "Copy", "PartialEq", "Eq", "PartialOrd", "Ord",
"Hash", "Default", "Display"
}
def _strip_comments_and_strings(code: str) -> str:
"""Strip comments and string literals from Rust code for security checking.
This prevents false positives from doc comments and string literals
that contain keywords.
Args:
code: Rust source code
Returns:
Code with comments and strings replaced with whitespace
"""
import re
# Strip line comments (// ...)
code = re.sub(r"//[^\n]*", "", code)
# Strip block comments (/* ... */)
code = re.sub(r"/\*.*?\*/", "", code, flags=re.DOTALL)
# Strip string literals (both "..." and r"..." raw strings)
# This is simplified - handles most common cases
code = re.sub(r'r#*"(?:[^"\\]|\\.)*"#*', '""', code)
code = re.sub(r'"(?:[^"\\]|\\.)*"', '""', code)
# Strip char literals
code = re.sub(r"'(?:[^'\\]|\\.)*'", "''", code)
return code
# Homoglyph mapping for characters that NFKD doesn't normalize to ASCII
# These are visually similar to ASCII letters but aren't decomposed by Unicode normalization
HOMOGLYPH_MAP: dict[str, str] = {
# Latin small capitals (Phonetic Extensions block)
"\u1d00": "a", # ᴀ LATIN LETTER SMALL CAPITAL A
"\u0299": "b", # ʙ LATIN LETTER SMALL CAPITAL B
"\u1d04": "c", # ᴄ LATIN LETTER SMALL CAPITAL C
"\u1d05": "d", # ᴅ LATIN LETTER SMALL CAPITAL D
"\u1d07": "e", # ᴇ LATIN LETTER SMALL CAPITAL E
"\ua730": "f", # ꜰ LATIN LETTER SMALL CAPITAL F
"\u0262": "g", # ɢ LATIN LETTER SMALL CAPITAL G
"\u029c": "h", # ʜ LATIN LETTER SMALL CAPITAL H
"\u026a": "i", # ɪ LATIN LETTER SMALL CAPITAL I
"\u1d0a": "j", # ᴊ LATIN LETTER SMALL CAPITAL J
"\u1d0b": "k", # ᴋ LATIN LETTER SMALL CAPITAL K
"\u029f": "l", # ʟ LATIN LETTER SMALL CAPITAL L
"\u1d0d": "m", # ᴍ LATIN LETTER SMALL CAPITAL M
"\u0274": "n", # ɴ LATIN LETTER SMALL CAPITAL N
"\u1d0f": "o", # ᴏ LATIN LETTER SMALL CAPITAL O
"\u1d18": "p", # ᴘ LATIN LETTER SMALL CAPITAL P
# No small capital Q in standard Unicode
"\u0280": "r", # ʀ LATIN LETTER SMALL CAPITAL R
"\ua731": "s", # ꜱ LATIN LETTER SMALL CAPITAL S
"\u1d1b": "t", # ᴛ LATIN LETTER SMALL CAPITAL T
"\u1d1c": "u", # ᴜ LATIN LETTER SMALL CAPITAL U
"\u1d20": "v", # ᴠ LATIN LETTER SMALL CAPITAL V
"\u1d21": "w", # ᴡ LATIN LETTER SMALL CAPITAL W
# No small capital X in standard Unicode
"\u028f": "y", # ʏ LATIN LETTER SMALL CAPITAL Y
"\u1d22": "z", # ᴢ LATIN LETTER SMALL CAPITAL Z
# Other common homoglyphs
"\u0430": "a", # а CYRILLIC SMALL LETTER A
"\u0435": "e", # е CYRILLIC SMALL LETTER IE
"\u043e": "o", # о CYRILLIC SMALL LETTER O
"\u0440": "p", # р CYRILLIC SMALL LETTER ER
"\u0441": "c", # с CYRILLIC SMALL LETTER ES
"\u0445": "x", # х CYRILLIC SMALL LETTER HA
"\u0443": "y", # у CYRILLIC SMALL LETTER U
"\u0410": "A", # А CYRILLIC CAPITAL LETTER A
"\u0412": "B", # В CYRILLIC CAPITAL LETTER VE
"\u0415": "E", # Е CYRILLIC CAPITAL LETTER IE
"\u041a": "K", # К CYRILLIC CAPITAL LETTER KA
"\u041c": "M", # М CYRILLIC CAPITAL LETTER EM
"\u041d": "H", # Н CYRILLIC CAPITAL LETTER EN
"\u041e": "O", # О CYRILLIC CAPITAL LETTER O
"\u0420": "P", # Р CYRILLIC CAPITAL LETTER ER
"\u0421": "C", # С CYRILLIC CAPITAL LETTER ES
"\u0422": "T", # Т CYRILLIC CAPITAL LETTER TE
"\u0425": "X", # Х CYRILLIC CAPITAL LETTER HA
"\u0427": "Y", # Ч looks like Y in some fonts
}
def _normalize_unicode(text: str) -> str:
"""Normalize Unicode to ASCII to prevent homoglyph attacks.
Uses both NFKD normalization and explicit homoglyph mapping for characters
that don't decompose to ASCII equivalents.
"""
# First apply explicit homoglyph mapping
mapped = "".join(HOMOGLYPH_MAP.get(c, c) for c in text)
# Then apply NFKD and strip remaining non-ASCII
return unicodedata.normalize("NFKD", mapped).encode("ascii", "ignore").decode("ascii")
def _sanitize_rust_completion(completion: str) -> str | None:
"""Check for disallowed patterns with Unicode normalization.
Strips comments and string literals before checking to avoid false positives
from documentation and example code.
"""
# First normalize Unicode to prevent homoglyph attacks
normalized = _normalize_unicode(completion.lower())
# Strip comments and strings from the normalized version for pattern checking
# This prevents false positives from doc comments like "/// Example using std::fs"
stripped = _strip_comments_and_strings(normalized)
# Check for disallowed patterns in the stripped code
for pattern in DISALLOWED_COMPLETION_PATTERNS:
if pattern.lower() in stripped:
return f"disallowed usage of {pattern}"
# Special check for #[derive( - only block if it contains unsafe traits
# Allow safe derives like #[derive(Debug, Clone)]
derive_pattern = r"#\[derive\s*\(([^)]+)\)"
for match in re.finditer(derive_pattern, stripped, re.IGNORECASE):
derives = match.group(1)
# Parse the comma-separated list of derives
derive_list = [d.strip() for d in derives.split(',')]
# Check if any derive is not in the safe list
for derive in derive_list:
# Remove any paths (e.g., serde::Deserialize -> Deserialize)
derive_name = derive.split('::')[-1].strip()
if derive_name and derive_name not in SAFE_DERIVE_MACROS:
# Check if it looks dangerous (contains keywords like unsafe, arbitrary)
dangerous_keywords = ['unsafe', 'arbitrary', 'deserialize', 'serialize']
if any(kw in derive_name.lower() for kw in dangerous_keywords):
return f"disallowed derive macro: {derive_name}"
# Check for dangerous patterns in raw strings (still check original, not stripped)
if re.search(
r"r#*\".*?(unsafe|std::fs|std::process).*?\"#*",
completion,
re.IGNORECASE | re.DOTALL,
):
return "disallowed pattern in raw string"
return None
MAX_COMPLETION_LENGTH = 100_000
MAX_COMPLETION_LINES = 5_000
def _validate_completion(completion: str) -> str | None:
"""Validate completion content. Returns error message or None."""
if not completion:
return "empty completion"
if len(completion) > MAX_COMPLETION_LENGTH:
return f"completion too long ({len(completion)} > {MAX_COMPLETION_LENGTH})"
if completion.count("\n") > MAX_COMPLETION_LINES:
return f"too many lines (> {MAX_COMPLETION_LINES})"
if "\x00" in completion:
return "null byte in completion"
try:
completion.encode("utf-8")
except UnicodeEncodeError:
return "invalid UTF-8 encoding"
return None
def _strip_markdown_code_blocks(completion: str) -> str:
"""Remove markdown code blocks from completion."""
if "```rust" in completion:
rust_match = re.search(r"```rust\s*(.*?)\s*```", completion, re.DOTALL)
if rust_match:
return rust_match.group(1)
elif "```" in completion:
code_match = re.search(r"```[^\n]*\s*(.*?)\s*```", completion, re.DOTALL)
if code_match:
return code_match.group(1)
return completion
def _strip_leading_attributes(completion: str) -> str:
"""Remove leading attribute lines (starting with #[) from completion."""
stripped_lines = []
for line in completion.split('\n'):
stripped_line = line.strip()
if stripped_line.startswith('#[') and not stripped_line.startswith('#!['):
continue
stripped_lines.append(line)
return '\n'.join(stripped_lines)
def _find_matching_brace(text: str, start_pos: int) -> int | None:
"""Find the position after the matching closing brace starting from start_pos.
Returns the position after the closing brace, or None if not found.
"""
brace_count = 0
for i in range(start_pos, len(text)):
if text[i] == "{":
brace_count += 1
elif text[i] == "}":
brace_count -= 1
if brace_count == 0:
return i + 1
return None
def _extract_target_function_body(text: str, entry_point: str) -> str | None:
"""Try to extract the body of a specific function by name.
Returns the function body if found, None otherwise.
"""
escaped_entry = re.escape(entry_point)
# Try with DOTALL to handle multiline signatures
fn_pattern = (
rf"fn\s+{escaped_entry}\s*<[^>]*>?\s*\([^)]*\)\s*"
rf"(?:->\s*[^{{}}where]+)?\s*(?:where\s+[^{{}}]+)?\s*\{{"
)
fn_match = re.search(fn_pattern, text, re.MULTILINE | re.DOTALL)
if not fn_match:
# Fallback to simpler pattern without where clause handling
not_brace_pattern = r"[^{]"
fn_pattern = rf"fn\s+{escaped_entry}\s*\([^)]*\)\s*(?:->{not_brace_pattern}*)?\s*\{{"
fn_match = re.search(fn_pattern, text, re.MULTILINE | re.DOTALL)
if fn_match:
start_pos = fn_match.end() - 1 # Position of opening brace
end_pos = _find_matching_brace(text, start_pos)
if end_pos is not None:
return text[start_pos + 1 : end_pos - 1].strip()
return None
def _extract_body_from_braces(text: str) -> str | None:
"""Extract content from text that starts with a brace block.
Returns the content between braces if found, None otherwise.
"""
stripped = text.strip()
if not stripped.startswith("{"):
return None
brace_count = 0
start_pos = 0
for i, char in enumerate(stripped):
if char == "{":
if brace_count == 0:
start_pos = i + 1
brace_count += 1
elif char == "}":
brace_count -= 1
if brace_count == 0:
return stripped[start_pos:i].strip()
# If we didn't find a matching brace, return everything after the first {
if brace_count > 0:
return stripped[start_pos:].strip()
return None
def _remove_main_functions(text: str) -> str:
"""Remove standalone main() functions from code."""
lines = text.split("\n")
cleaned_lines = []
in_main = False
brace_count = 0
i = 0
while i < len(lines):
line = lines[i]
stripped = line.strip()
if re.match(r"^fn\s+main\s*\([^)]*\)\s*(?:->[^{]*)?\s*\{", stripped):
in_main = True
brace_count = 1
i += 1
while i < len(lines) and brace_count > 0:
line = lines[i]
brace_count += line.count("{") - line.count("}")
i += 1
continue
if in_main:
brace_count += line.count("{") - line.count("}")
if brace_count <= 0:
in_main = False
i += 1
continue
cleaned_lines.append(line)
i += 1
return "\n".join(cleaned_lines).strip()
def _clean_extra_patterns(text: str) -> str:
"""Remove common extra patterns like example usage blocks."""
result = re.sub(
r"(?i)(//\s*)?(example\s+usage|usage\s+example):.*", "", text, flags=re.DOTALL
)
result = re.sub(
r"^use\s+std::collections::Vec;?\s*$", "", result, flags=re.MULTILINE
)
return result.strip()
def _extract_function_body(completion: str, entry_point: str) -> str:
"""
Extract the function body from a completion, removing extra code like main() functions.
Args:
completion: Raw completion text from the model
entry_point: Name of the function we're looking for (e.g., "has_close_elements")
Returns:
Cleaned completion with only the target function body
"""
# Step 1: Remove markdown code blocks
completion = _strip_markdown_code_blocks(completion).strip()
# Step 2: Strip leading attributes
current_completion = _strip_leading_attributes(completion)
# Step 3: Try to find the target function
body = _extract_target_function_body(current_completion, entry_point)
if body is not None:
return body
# Step 4: Check if completion is just a brace-enclosed body
body = _extract_body_from_braces(current_completion)
if body is not None:
return body
# Step 5: Remove main() functions and clean up
result = _remove_main_functions(current_completion)
result = _clean_extra_patterns(result)
return result
def _check_rustc_available(sandbox_mode: str | None = None) -> tuple[bool, str | None]:
"""
Preflight check for rustc availability.
Returns (available, error_message).
"""
try:
# Check local rustc (for firejail, none, or any mode - firejail uses host rustc)
result = subprocess.run(
["rustc", "--version"],
capture_output=True,
text=True,
timeout=5.0,
)
if result.returncode == 0:
return True, None
return False, "rustc --version failed"
except FileNotFoundError:
return False, "rustc not found in PATH"
except subprocess.TimeoutExpired:
return False, "rustc version check timed out"
except Exception as e:
return False, f"rustc check error: {e}"
def check_main_free(completion: str) -> bool:
"""Check if completion contains fn main outside of comments and strings."""
import re
# Strip line comments (// ...)
code = re.sub(r"//[^\n]*", "", completion)
# Strip block comments (/* ... */)
code = re.sub(r"/\*.*?\*/", "", code, flags=re.DOTALL)
# Strip string literals (both "..." and r"..." raw strings)
# This is a simplified approach - handles most common cases
code = re.sub(r'r?"(?:[^"\\]|\\.)*"', '""', code)
# Strip char literals
code = re.sub(r"'(?:[^'\\]|\\.)*'", "''", code)
# Check for fn main() patterns in the cleaned code
main_pattern = r"fn\s+main\s*\("
return not bool(re.search(main_pattern, code, re.IGNORECASE))
def _run_clippy_check(source_path: str, timeout: float) -> tuple[bool, str]:
"""Run clippy on compiled code and return (passed, warnings).
Creates a minimal Cargo.toml if one doesn't exist to enable clippy checking
in temporary directories.
"""
source_dir = os.path.dirname(source_path)
cargo_toml_path = os.path.join(source_dir, "Cargo.toml")
# Check if Cargo.toml exists, create minimal one if not
created_cargo_toml = False
if not os.path.exists(cargo_toml_path):
# Create minimal Cargo.toml for clippy checking
source_filename = os.path.basename(source_path)
binary_name = os.path.splitext(source_filename)[0]
minimal_cargo_toml = f'''[package]
name = "temp_eval"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "{binary_name}"
path = "{source_filename}"
'''
try:
with open(cargo_toml_path, "w", encoding="utf-8") as f:
f.write(minimal_cargo_toml)
created_cargo_toml = True
except OSError as e:
return False, f"infra: failed to create Cargo.toml: {e}"
try:
result = subprocess.run(
["cargo", "clippy", "--", "-D", "warnings"],
capture_output=True,
text=True,
timeout=timeout,
cwd=source_dir,
)
return result.returncode == 0, result.stderr
finally:
# Clean up created Cargo.toml
if created_cargo_toml and os.path.exists(cargo_toml_path):
try:
os.remove(cargo_toml_path)
except OSError:
pass # Best effort cleanup
class ReliabilityContext:
"""Context manager that provides isolated reliability guards.
IMPORTANT: This must save and restore ALL functions that reliability_guard()
modifies, otherwise the os module will be corrupted for subsequent code
(including pytest teardown), causing TypeError: 'NoneType' object is not callable.
"""
# Sentinel for "module not present in sys.modules"
_NOT_PRESENT = object()
def __init__(self, maximum_memory_bytes: int | None = None):
self.maximum_memory_bytes = maximum_memory_bytes
self._original_os: dict[str, object] = {}
self._original_shutil: dict[str, object] = {}
self._original_subprocess: dict[str, object] = {}
self._original_builtins: dict[str, object] = {}
self._original_sys_modules: dict[str, object] = {}
self._faulthandler_was_enabled: bool = False
self._original_help: object = None
def __enter__(self):
import builtins
import faulthandler
import sys
# Store faulthandler state - reliability_guard calls faulthandler.disable()
self._faulthandler_was_enabled = faulthandler.is_enabled()
# Store __builtins__["help"] - reliability_guard sets it to None
# Note: __builtins__ can be a dict or module depending on context
if isinstance(__builtins__, dict):
self._original_help = __builtins__.get("help")
else:
self._original_help = getattr(__builtins__, "help", None)
# Store ALL os module functions that reliability_guard() sets to None
self._original_os = {
"kill": getattr(os, "kill", None),
"system": getattr(os, "system", None),
"putenv": getattr(os, "putenv", None),
"remove": getattr(os, "remove", None),
"removedirs": getattr(os, "removedirs", None),
"rmdir": getattr(os, "rmdir", None),
"fchdir": getattr(os, "fchdir", None),
"setuid": getattr(os, "setuid", None),
"fork": getattr(os, "fork", None),
"forkpty": getattr(os, "forkpty", None),
"killpg": getattr(os, "killpg", None),
"rename": getattr(os, "rename", None),
"renames": getattr(os, "renames", None),
"truncate": getattr(os, "truncate", None),
"replace": getattr(os, "replace", None),
"unlink": getattr(os, "unlink", None),
"fchmod": getattr(os, "fchmod", None),
"fchown": getattr(os, "fchown", None),
"chmod": getattr(os, "chmod", None),
"chown": getattr(os, "chown", None),
"chroot": getattr(os, "chroot", None),
"lchflags": getattr(os, "lchflags", None),
"lchmod": getattr(os, "lchmod", None),
"lchown": getattr(os, "lchown", None),
"getcwd": getattr(os, "getcwd", None),
"chdir": getattr(os, "chdir", None),
}
# Store shutil functions
self._original_shutil = {
"rmtree": getattr(shutil, "rmtree", None),
"move": getattr(shutil, "move", None),
"chown": getattr(shutil, "chown", None),
}
# Store subprocess functions
self._original_subprocess = {
"Popen": getattr(subprocess, "Popen", None),
}
# Store builtins
self._original_builtins = {
"exit": getattr(builtins, "exit", None),
"quit": getattr(builtins, "quit", None),
}
# Store sys.modules entries that reliability_guard sets to None
for mod_name in ("ipdb", "joblib", "resource", "psutil", "tkinter"):
self._original_sys_modules[mod_name] = sys.modules.get(
mod_name, self._NOT_PRESENT
)
reliability_guard(self.maximum_memory_bytes)
return self
def __exit__(self, *args):
import builtins
import faulthandler
import sys
# Restore faulthandler state
if self._faulthandler_was_enabled:
faulthandler.enable()
# Restore __builtins__["help"]
if self._original_help is not None:
if isinstance(__builtins__, dict):
__builtins__["help"] = self._original_help
else:
setattr(__builtins__, "help", self._original_help)
# Restore ALL os module functions
for name, func in self._original_os.items():
if func is not None:
setattr(os, name, func)
# Restore shutil functions
for name, func in self._original_shutil.items():
if func is not None:
setattr(shutil, name, func)
# Restore subprocess functions
for name, func in self._original_subprocess.items():
if func is not None:
setattr(subprocess, name, func)
# Restore builtins
for name, func in self._original_builtins.items():
if func is not None:
setattr(builtins, name, func)
# Restore sys.modules entries
for mod_name, original in self._original_sys_modules.items():
if original is self._NOT_PRESENT:
# Module wasn't present before, remove if reliability_guard added None
sys.modules.pop(mod_name, None)
else:
# Restore original value (could be None or actual module)
sys.modules[mod_name] = original # type: ignore[assignment]
DETERMINISTIC_RUSTC_FLAGS = [
"--edition=2021",
"--test",
"-C",
"opt-level=0",
"-C",
"debuginfo=0",
"-C",
"incremental=false",
]
def _compile_rust_code(
source_path: str,
test_binary: str,
compile_args: list[str],
compile_timeout: float,
use_sandbox: bool,
sandbox_mode: str | None,
) -> tuple[subprocess.CompletedProcess, float]:
"""Compile Rust code with or without sandbox.
Returns:
Tuple of (compile_result, compile_time_seconds)
"""
start_time = time.perf_counter()
if use_sandbox:
compile_result = run_rustc_sandboxed(
source_path,
test_binary,
compile_args,
timeout=compile_timeout,
capture_output=True,
sandbox_mode=sandbox_mode,
)
else:
compile_result = subprocess.run(
["rustc"] + compile_args + [source_path, "-o", test_binary],
capture_output=True,
text=True,
timeout=compile_timeout,
)
compile_time = time.perf_counter() - start_time
return compile_result, compile_time
def _run_clippy_phase(
source_path: str,
clippy_timeout: float,
clippy_required: bool,
result_dict: dict,
) -> bool:
"""Run clippy check and update result_dict.
Returns:
True if should continue execution, False if should return early
"""
if not shutil.which("cargo"):
if clippy_required:
result_dict["clippy_ok"] = False
result_dict["error_type"] = "infra_missing_linter"
result_dict["stderr"] = "cargo not found (required for clippy)"
result_dict["result"] = "failed: cargo not available"
return False
return True
try:
clippy_ok, clippy_stderr = _run_clippy_check(source_path, clippy_timeout)
result_dict["clippy_ok"] = clippy_ok
# Check if clippy stderr indicates infrastructure problem
is_infra_error = clippy_stderr and "infra:" in clippy_stderr
if not clippy_ok and clippy_required:
if is_infra_error:
result_dict["error_type"] = "infra_missing_linter"
result_dict["stderr"] = clippy_stderr
result_dict["result"] = f"failed: {clippy_stderr}"
else:
result_dict["error_type"] = "lint_failure"
result_dict["stderr"] = clippy_stderr
result_dict["result"] = "failed: clippy check failed"
return False
elif not clippy_ok and not is_infra_error:
# Advisory mode: record but don't fail
result_dict["stderr"] = clippy_stderr
except subprocess.TimeoutExpired:
result_dict["clippy_ok"] = False
if clippy_required:
result_dict["error_type"] = "clippy_timeout"
result_dict["stderr"] = "clippy check timed out"
result_dict["result"] = "failed: clippy timeout"
return False
else:
result_dict["stderr"] = "clippy check timed out (advisory)"
except Exception as exc: # noqa: BLE001
result_dict["clippy_ok"] = False
if clippy_required:
result_dict["error_type"] = "infra_missing_linter"
result_dict["stderr"] = str(exc)
result_dict["result"] = f"failed: clippy error: {exc}"
return False
else:
result_dict["stderr"] = str(exc)
return True
def _run_test_binary(
test_binary: str,
run_timeout: float,
use_sandbox: bool,
sandbox_mode: str | None,
) -> subprocess.CompletedProcess:
"""Execute the test binary with or without sandbox."""
if use_sandbox:
return run_binary_sandboxed(
test_binary,
timeout=run_timeout,
capture_output=True,
sandbox_mode=sandbox_mode,
)
else:
return subprocess.run(
[test_binary],
capture_output=True,
text=True,
timeout=run_timeout,
)
def _rust_unsafe_execute(
problem: dict,
completion: str,
timeout: float,
result,
sandbox_mode: str | None = None,
enforce_policy: bool = True,
compile_timeout: float | None = None,
run_timeout: float | None = None,
clippy_timeout: float | None = None,
clippy_required: bool = False,
):
"""
Execute Rust code and return enhanced result schema.