rbx.cp 0.13.5__py3-none-any.whl → 0.13.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rbx/box/header.py CHANGED
@@ -49,7 +49,7 @@ def _get_string_var_block() -> str:
49
49
  return _get_var_block(_get_vars_of_type(str, _string_repr))
50
50
 
51
51
 
52
- def _check_int_bounds(x: int) -> None:
52
+ def check_int_bounds(x: int) -> None:
53
53
  if x >= 2**64:
54
54
  raise ValueError(
55
55
  f'Some variable you defined (value: {x}) is too large to fit in a C++ 64-bit integer (signed or unsigned)'
@@ -63,11 +63,19 @@ def _check_int_bounds(x: int) -> None:
63
63
  def _get_int_var_block() -> str:
64
64
  def _transform(x: Primitive) -> str:
65
65
  if isinstance(x, bool):
66
- return str(int(x))
67
- _check_int_bounds(int(x))
66
+ return f'static_cast<int64_t>({int(x)})'
67
+ check_int_bounds(int(x))
68
68
  return f'static_cast<int64_t>({x})'
69
69
 
70
- return _get_var_block(_get_vars_of_type(int, _transform))
70
+ # Get both int and bool variables for the int block
71
+ pkg = package.find_problem_package_or_die()
72
+ vars = pkg.expanded_vars
73
+ int_vars = {
74
+ name: _transform(value)
75
+ for name, value in vars.items()
76
+ if isinstance(value, (int, bool))
77
+ }
78
+ return _get_var_block(int_vars)
71
79
 
72
80
 
73
81
  def _get_float_var_block() -> str:
@@ -81,11 +89,9 @@ def _get_bool_var_block() -> str:
81
89
  def _get_vars_of_type(t: Type, transform: Callable[[Primitive], str]) -> Dict[str, str]:
82
90
  pkg = package.find_problem_package_or_die()
83
91
  vars = pkg.expanded_vars
84
-
85
- def is_valid(value: Primitive) -> bool:
86
- return isinstance(value, t)
87
-
88
- return {name: transform(value) for name, value in vars.items() if is_valid(value)}
92
+ return {
93
+ name: transform(value) for name, value in vars.items() if isinstance(value, t)
94
+ }
89
95
 
90
96
 
91
97
  def _get_var_block(mappings: Dict[str, str]) -> str:
@@ -3,9 +3,10 @@ from dataclasses import dataclass
3
3
  from typing import Dict, List, Optional
4
4
 
5
5
  from rbx import console, utils
6
- from rbx.box import presets
6
+ from rbx.box import package, presets
7
7
  from rbx.box.fields import Primitive
8
8
  from rbx.box.schema import (
9
+ CheckerTest,
9
10
  CodeItem,
10
11
  ExpectedOutcome,
11
12
  Generator,
@@ -14,6 +15,8 @@ from rbx.box.schema import (
14
15
  Solution,
15
16
  TaskType,
16
17
  TestcaseGroup,
18
+ ValidatorOutcome,
19
+ ValidatorTest,
17
20
  )
18
21
  from rbx.box.testing.testing_preset import TestingPreset
19
22
  from rbx.box.testing.testing_shared import PathOrStr, TestingShared
@@ -79,6 +82,9 @@ class TestingPackage(TestingShared):
79
82
 
80
83
  def save(self):
81
84
  self.yml_path.write_text(utils.model_to_yaml(self.yml))
85
+ # Clear internal cache and package cache to ensure the updated package is loaded fresh
86
+ self._yml = None
87
+ package.clear_package_cache()
82
88
 
83
89
  def set_type(self, type: TaskType):
84
90
  self.yml.type = type
@@ -244,3 +250,59 @@ class TestingPackage(TestingShared):
244
250
  if interactor_pipes_path.exists():
245
251
  contents.interactor_pipes = interactor_pipes_path.read_text()
246
252
  return contents
253
+
254
+ def add_validator_unit_test(
255
+ self,
256
+ glob: str,
257
+ outcome: ValidatorOutcome = ValidatorOutcome.VALID,
258
+ validator: Optional[PathOrStr] = None,
259
+ files: Optional[Dict[str, str]] = None,
260
+ ):
261
+ """Add a unit test for the validator.
262
+
263
+ Args:
264
+ glob: Glob pattern for input files
265
+ outcome: Expected validation outcome
266
+ validator: Optional validator to use (if not main validator)
267
+ files: Optional dict of {filename: content} to create test files
268
+ """
269
+ if files:
270
+ for filename, content in files.items():
271
+ self.add_file(filename).write_text(content)
272
+
273
+ validator_test = ValidatorTest(
274
+ glob=glob,
275
+ outcome=outcome,
276
+ validator=CodeItem(path=pathlib.Path(validator)) if validator else None,
277
+ )
278
+
279
+ # Explicitly set the unitTests field to mark it as dirty
280
+ unit_tests = self.yml.unitTests
281
+ unit_tests.validator = unit_tests.validator + [validator_test]
282
+ self.yml.unitTests = unit_tests
283
+ self.save()
284
+
285
+ def add_checker_unit_test(
286
+ self,
287
+ glob: str,
288
+ outcome: ExpectedOutcome = ExpectedOutcome.ACCEPTED,
289
+ files: Optional[Dict[str, str]] = None,
290
+ ):
291
+ """Add a unit test for the checker.
292
+
293
+ Args:
294
+ glob: Glob pattern for test files
295
+ outcome: Expected checker outcome
296
+ files: Optional dict of {filename: content} to create test files
297
+ """
298
+ if files:
299
+ for filename, content in files.items():
300
+ self.add_file(filename).write_text(content)
301
+
302
+ checker_test = CheckerTest(glob=glob, outcome=outcome)
303
+
304
+ # Explicitly set the unitTests field to mark it as dirty
305
+ unit_tests = self.yml.unitTests
306
+ unit_tests.checker = unit_tests.checker + [checker_test]
307
+ self.yml.unitTests = unit_tests
308
+ self.save()
rbx/box/unit.py CHANGED
@@ -41,7 +41,7 @@ class CheckerTestEntry(BaseModel):
41
41
  return ', '.join(res)
42
42
 
43
43
 
44
- def _extract_validator_test_entries(
44
+ def extract_validator_test_entries(
45
45
  tests: List[ValidatorTest],
46
46
  ) -> List[ValidatorTestEntry]:
47
47
  res: List[ValidatorTestEntry] = []
@@ -57,7 +57,7 @@ def _extract_validator_test_entries(
57
57
  return sorted(res, key=lambda x: x.input.name)
58
58
 
59
59
 
60
- def _extract_checker_test_entries(tests: List[CheckerTest]) -> List[CheckerTestEntry]:
60
+ def extract_checker_test_entries(tests: List[CheckerTest]) -> List[CheckerTestEntry]:
61
61
  res: List[CheckerTestEntry] = []
62
62
  seen: Set[pathlib.Path] = set()
63
63
  for test in tests:
@@ -94,7 +94,7 @@ def _get_validator_for_test(test: ValidatorTestEntry) -> Optional[CodeItem]:
94
94
  async def run_validator_unit_tests(progress: StatusProgress):
95
95
  pkg = package.find_problem_package_or_die()
96
96
 
97
- entries = _extract_validator_test_entries(pkg.unitTests.validator)
97
+ entries = extract_validator_test_entries(pkg.unitTests.validator)
98
98
 
99
99
  vals: List[CodeItem] = []
100
100
  for test in entries:
@@ -158,7 +158,7 @@ async def run_checker_unit_tests(progress: StatusProgress):
158
158
 
159
159
  console.console.rule('Checker tests', style='info')
160
160
 
161
- entries = _extract_checker_test_entries(pkg.unitTests.checker)
161
+ entries = extract_checker_test_entries(pkg.unitTests.checker)
162
162
  if not entries:
163
163
  console.console.print('No checker unit tests found.')
164
164
  return
rbx/grading/caching.py CHANGED
@@ -371,7 +371,7 @@ class DependencyCache:
371
371
  self.transient_db = SqliteDict(str(tmp_dir / '.cache_db'), autocommit=True)
372
372
  atexit.register(lambda: self.db.close())
373
373
  atexit.register(lambda: self.transient_db.close())
374
- atexit.register(lambda: shutil.rmtree(tmp_dir))
374
+ atexit.register(lambda: shutil.rmtree(tmp_dir, ignore_errors=True))
375
375
 
376
376
  def _cache_name(self) -> str:
377
377
  return str(self.root / '.cache_db')
@@ -73,7 +73,9 @@ class FileCacher:
73
73
  self.file_dir = pathlib.Path(tempfile.mkdtemp())
74
74
  # Delete this directory on exit since it has a random name and
75
75
  # won't be used again.
76
- atexit.register(lambda: shutil.rmtree(str(self.file_dir)))
76
+ atexit.register(
77
+ lambda: shutil.rmtree(str(self.file_dir), ignore_errors=True)
78
+ )
77
79
  else:
78
80
  assert folder is not None
79
81
  self.file_dir = folder / 'fs-cache-shared'
@@ -84,7 +86,7 @@ class FileCacher:
84
86
  self.temp_dir = pathlib.Path(
85
87
  tempfile.mkdtemp(dir=self.file_dir, prefix='_temp')
86
88
  )
87
- atexit.register(lambda: shutil.rmtree(str(self.temp_dir)))
89
+ atexit.register(lambda: shutil.rmtree(str(self.temp_dir), ignore_errors=True))
88
90
  # Just to make sure it was created.
89
91
 
90
92
  def is_shared(self) -> bool:
@@ -526,7 +528,7 @@ class FileCacher:
526
528
  """
527
529
  if self.is_shared():
528
530
  raise Exception('You may not destroy a shared cache.')
529
- shutil.rmtree(str(self.file_dir))
531
+ shutil.rmtree(str(self.file_dir), ignore_errors=True)
530
532
 
531
533
  def list(self) -> List[storage.FileWithMetadata]:
532
534
  """List the files available in the storage.
@@ -94,12 +94,40 @@ def get_preexec_fn(params: ProgramParams):
94
94
 
95
95
 
96
96
  def get_memory_usage(ru: resource.struct_rusage) -> int:
97
+ """Get memory usage in bytes from resource usage statistics.
98
+
99
+ Returns the total memory usage (RSS + shared memory segments) in bytes.
100
+
101
+ Platform differences in ru.ru_maxrss:
102
+ - macOS/Darwin: ru.ru_maxrss is in bytes
103
+ - Linux: ru.ru_maxrss is in kilobytes
104
+
105
+ This function normalizes the result to always return bytes.
106
+
107
+ Args:
108
+ ru: Resource usage statistics from os.wait4() or similar
109
+
110
+ Returns:
111
+ int: Total memory usage in bytes
112
+ """
97
113
  if sys.platform == 'darwin':
98
- return ru.ru_maxrss // 1024 + ru.ru_ixrss
99
- return ru.ru_maxrss + ru.ru_ixrss + ru.ru_idrss + ru.ru_isrss
114
+ # On macOS, ru.ru_maxrss is already in bytes
115
+ return ru.ru_maxrss + ru.ru_ixrss * 1024
116
+ # On Linux, ru.ru_maxrss is in kilobytes, so convert to bytes
117
+ return (ru.ru_maxrss + ru.ru_ixrss + ru.ru_idrss + ru.ru_isrss) * 1024
100
118
 
101
119
 
102
120
  def get_cpu_time(ru: resource.struct_rusage) -> float:
121
+ """Get CPU time in seconds from resource usage statistics.
122
+
123
+ Returns the total CPU time (user + system) in seconds.
124
+
125
+ Args:
126
+ ru: Resource usage statistics from os.wait4() or similar
127
+
128
+ Returns:
129
+ float: Total CPU time in seconds
130
+ """
103
131
  return ru.ru_utime + ru.ru_stime
104
132
 
105
133
 
@@ -239,6 +267,10 @@ class Program:
239
267
  ):
240
268
  program_codes.append(ProgramCode.WT)
241
269
  program_codes.append(ProgramCode.TO)
270
+ # Memory limit checking: Two ways a process can exceed memory limits:
271
+ # 1. Runtime monitoring (_handle_alarm) kills the process during execution
272
+ # 2. Post-execution check using ru.ru_maxrss detects peak memory usage exceeded limit
273
+ # Both memory_used (from ru.ru_maxrss) and memory_limit (converted to bytes) are in bytes
242
274
  if (
243
275
  self.params.memory_limit is not None
244
276
  and memory_used > self.params.memory_limit * 1024 * 1024
@@ -1,6 +1,5 @@
1
1
  import abc
2
2
  import asyncio
3
- import collections
4
3
  import dataclasses
5
4
  import io
6
5
  import json
@@ -146,12 +145,6 @@ class SandboxParams(pydantic.BaseModel):
146
145
  reverse_io: bool = False
147
146
  pgid: Optional[int] = None
148
147
 
149
- # For timeit
150
- timeit_dups: Dict[str, List[pathlib.Path]] = dataclasses.field(
151
- default_factory=lambda: collections.defaultdict(list)
152
- )
153
- timeit_prefix: Optional[str] = None
154
-
155
148
  def get_cacheable_params(self) -> Dict[str, Any]:
156
149
  return self.model_dump(mode='json', exclude_unset=True, exclude_none=True)
157
150
 
@@ -5,6 +5,7 @@ import logging
5
5
  import os
6
6
  import pathlib
7
7
  import shutil
8
+ import signal
8
9
  import subprocess
9
10
  import sys
10
11
  import tempfile
@@ -313,7 +314,9 @@ class StupidSandbox(SandboxBase):
313
314
  if should_tee:
314
315
  assert interactor_tee.pipes.output is not None
315
316
  interactor_tee.pipes.output.close()
316
- # TODO: kill in case of WA
317
+
318
+ if idx == 0 and program_result.exitcode != 0:
319
+ os.killpg(group_id, signal.SIGKILL)
317
320
  elif pid == program.pid:
318
321
  program_result = program.process_exit(status, ru)
319
322
  results[0] = self._get_sandbox_log(program_result, params)
@@ -277,8 +277,14 @@ class FilesystemStorage(Storage):
277
277
  return None
278
278
 
279
279
  # Create a temporary file in the same directory
280
+ # Use only the basename for the suffix to avoid issues with subdirectories
281
+ filename_basename = pathlib.Path(filename).name
280
282
  temp_file = tempfile.NamedTemporaryFile(
281
- 'wb', delete=False, prefix='.tmp.', suffix=filename, dir=self.path
283
+ 'wb',
284
+ delete=False,
285
+ prefix='.tmp.',
286
+ suffix=f'.{filename_basename}',
287
+ dir=self.path,
282
288
  )
283
289
  metadata: Dict[str, Optional[BaseModel]] = {'compression': None}
284
290
  if self.compress or grading_context.should_compress():
rbx/grading/steps.py CHANGED
@@ -595,7 +595,7 @@ def _maybe_complain_about_sanitization(command: str) -> None:
595
595
  raise typer.Exit(1)
596
596
 
597
597
 
598
- def _check_for_sanitizer_warnings_in_line(line: str) -> bool:
598
+ def check_for_sanitizer_warnings_in_line(line: str) -> bool:
599
599
  line = line.lower()
600
600
  return 'runtime error:' in line or '==error' in line
601
601
 
@@ -608,7 +608,7 @@ def _check_for_sanitizer_warnings(
608
608
  if not sandbox.file_exists(stderr_file):
609
609
  return False
610
610
  with sandbox.get_file(stderr_file) as f:
611
- return any(_check_for_sanitizer_warnings_in_line(line.decode()) for line in f)
611
+ return any(check_for_sanitizer_warnings_in_line(line.decode()) for line in f)
612
612
 
613
613
 
614
614
  _WARNING_RE = re.compile(r'([^:]+):\d+:\d+:[ ]+warning:.*')
rbx/utils.py CHANGED
@@ -103,14 +103,62 @@ def uploaded_schema_path(model: Type[BaseModel]) -> str:
103
103
  return f'https://rsalesc.github.io/rbx/schemas/{model.__name__}.json'
104
104
 
105
105
 
106
- def model_to_yaml(model: BaseModel) -> str:
106
+ def model_to_yaml(model: BaseModel, **kwargs) -> str:
107
+ """Convert model to YAML string with proper boolean handling.
108
+
109
+ This function works around Pydantic's issue where Union[str, int, float, bool]
110
+ fields convert booleans to floats when using mode='json'.
111
+ """
112
+ # Use regular dump to preserve boolean types
113
+ data = model.model_dump(exclude_unset=True, exclude_none=True)
114
+
115
+ # Ensure the result is JSON-serializable by converting any non-JSON types
116
+ json_safe_data = _ensure_json_serializable(data)
117
+
118
+ # Add schema path comment and convert to YAML
107
119
  path = uploaded_schema_path(model.__class__)
108
- return f'# yaml-language-server: $schema={path}\n\n' + yaml.dump(
109
- model.model_dump(mode='json', exclude_unset=True, exclude_none=True),
110
- sort_keys=False,
111
- allow_unicode=True,
120
+ schema_comment = f'# yaml-language-server: $schema={path}\n\n'
121
+
122
+ yaml_content = yaml.safe_dump(
123
+ json_safe_data, sort_keys=False, allow_unicode=True, **kwargs
112
124
  )
113
125
 
126
+ return schema_comment + yaml_content
127
+
128
+
129
+ def _ensure_json_serializable(obj):
130
+ """Recursively ensure an object is JSON-serializable while preserving booleans."""
131
+ from datetime import date, datetime
132
+ from enum import Enum
133
+ from pathlib import Path
134
+ from uuid import UUID
135
+
136
+ from rbx.autoenum import AutoEnum
137
+
138
+ if isinstance(obj, dict):
139
+ return {k: _ensure_json_serializable(v) for k, v in obj.items()}
140
+ elif isinstance(obj, list):
141
+ return [_ensure_json_serializable(item) for item in obj]
142
+ elif isinstance(obj, tuple):
143
+ return [_ensure_json_serializable(item) for item in obj]
144
+ elif isinstance(obj, set):
145
+ return [_ensure_json_serializable(item) for item in obj]
146
+ elif isinstance(obj, AutoEnum):
147
+ return str(obj)
148
+ elif isinstance(obj, Enum):
149
+ return obj.value
150
+ elif isinstance(obj, (str, int, float, bool)) or obj is None:
151
+ return obj
152
+ elif isinstance(obj, (datetime, date)):
153
+ return obj.isoformat()
154
+ elif isinstance(obj, UUID):
155
+ return str(obj)
156
+ elif isinstance(obj, Path):
157
+ return str(obj)
158
+ else:
159
+ # For any other type, try to convert to string
160
+ return str(obj)
161
+
114
162
 
115
163
  def model_from_yaml(model: Type[T], s: str) -> T:
116
164
  return model(**yaml.safe_load(s))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: rbx.cp
3
- Version: 0.13.5
3
+ Version: 0.13.6
4
4
  Summary:
5
5
  Author: Roberto Sales
6
6
  Requires-Python: >=3.9.1,<4.0.0
@@ -26,7 +26,7 @@ rbx/box/formatting.py,sha256=i3vXHpo_L_VpVPxOe4wHlai1WhlDJlfxUexS9DC0Szg,1249
26
26
  rbx/box/generators.py,sha256=Q7xZ0BQVrh4eTwiYgxdpaHJqqZT4_X_YPl-uReZz5tw,16880
27
27
  rbx/box/git_utils.py,sha256=VlUgzuHOCnrjjiJQnDB32qDHbHw_zkwgA7wm4bloibc,750
28
28
  rbx/box/global_package.py,sha256=YfFGw2vxFspF2v3phBEeBCrLe1sfbANrctGqii3I2X4,2106
29
- rbx/box/header.py,sha256=68Sd7cnooULXVb2KCWc4Wrt8YrAP4hpOfZbry4A-fp0,2828
29
+ rbx/box/header.py,sha256=OZJD2J0fdIiYyiEAwQ3x3M8TwM1v1J9nhIjnPVz4Zy8,3029
30
30
  rbx/box/lang.py,sha256=CSD-yxFUC3LWdGpv4IVFOLdgONc_JbsI45BEN3bjaFw,888
31
31
  rbx/box/lazy_importing_main.py,sha256=6Z8As7qVFFT619xHH9Xt8VCH57NjC4aDxfAgkWiUwT8,116
32
32
  rbx/box/linting.py,sha256=wRE0hKCduTBHZYBFmmis_d9AMTsDu0Q-AjByCeTnkrY,3187
@@ -79,7 +79,7 @@ rbx/box/testcase_utils.py,sha256=HoDr_RxWpfviLd2oTj_m2wg1e4XaY9LD-QBqx_QjDI0,689
79
79
  rbx/box/testcases/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
80
80
  rbx/box/testcases/main.py,sha256=_I7h_obRcpNLRQ6dDJDIE5NAvTyn5nBOhdsBhRA_PvU,5442
81
81
  rbx/box/testing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
- rbx/box/testing/testing_package.py,sha256=kEQn22CwyYK_KbeY6eEG_FeVdQ_Is61Xb1QNdqNYmjY,7947
82
+ rbx/box/testing/testing_package.py,sha256=kzvSbL_4fkjD2l3hfYapyOezLHhhySi9sp4u92MoycY,10121
83
83
  rbx/box/testing/testing_preset.py,sha256=7TxfL4fT9JetRMRkQ3Iko99N5gzfKz8_lPM0rkkQx_k,1135
84
84
  rbx/box/testing/testing_shared.py,sha256=rX7w5VrCzf4l9zYhq3eFW1iHaWDLU-Xkn5oCjnAavhA,2558
85
85
  rbx/box/tooling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -113,29 +113,26 @@ rbx/box/ui/widgets/interaction_box.py,sha256=mJoQjHegxkIL00OgiCULmV0_w-2ZcwsQEa-
113
113
  rbx/box/ui/widgets/rich_log_box.py,sha256=mF565c_Y3RYUZ_GJEFj5Eb86SFjsib31wE5qu1K0UBM,91
114
114
  rbx/box/ui/widgets/test_output_box.py,sha256=ws7Oa2E8ZABM6Q4ZtL2UQiq59sJzKYPe-STrqhZJI8M,3871
115
115
  rbx/box/ui/widgets/two_sided_test_output_box.py,sha256=L-ORiDwd6CP5DFpavrKGBaX0ZHkSoQqbJrGZ4BdFUWc,2289
116
- rbx/box/unit.py,sha256=oIXbQDidrt-DlDjhM1C-WW2jBr7xjsZrRBO6YXP3sJo,7891
116
+ rbx/box/unit.py,sha256=B1GOt537hOh-E0KAhB7AAgTpcu9UbA8n3JLNlX-2tRg,7887
117
117
  rbx/box/validators.py,sha256=z34cUMkuSlCPWnaCqaHqegCxuvmfhAvWlsqSeaduL6s,10580
118
118
  rbx/config.py,sha256=Tj0NHSf13fXxbNpif5C4qnaL1k3S-G87OnzuykEAcNQ,8463
119
119
  rbx/console.py,sha256=X8EJy68OROgh6ao3ZcUjZm5Y56VFMzen58ywAuQ7pAU,990
120
120
  rbx/grading/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
121
- rbx/grading/caching.py,sha256=p9ZTz9Y1ZdkcPTIjPH8hEK_LHFtLMWY5z5YIVCkhi3k,16931
121
+ rbx/grading/caching.py,sha256=hasSs10PV4J_3e6b3xc7BDCnUNzT9uwrDZcZ_h_hL1I,16951
122
122
  rbx/grading/debug_context.py,sha256=kuAXEI8yRG8xfhS9WKKIRh9X0e5JUD8zvl_cpczJTC8,699
123
123
  rbx/grading/grading_context.py,sha256=TaRyLwPkkxvspQIFUFk8Ok0T8EST2pHMMNoVDx9lbFU,3416
124
124
  rbx/grading/judge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
125
- rbx/grading/judge/cacher.py,sha256=wtRnVE_Es9xcqIgrhn6WzUoB90aihUuKaFyuVsusngg,20323
125
+ rbx/grading/judge/cacher.py,sha256=QiVa74gFUuN4pyw_0hT3qg4oMF0frc1Iu56svpRUa9k,20413
126
126
  rbx/grading/judge/digester.py,sha256=gtOIe_iL4PEWA7OKelW1gjSI-nBvbOpDPJGV8VQyjSg,912
127
- rbx/grading/judge/program.py,sha256=ejjmnAN2evN9FiPsmEUrsDeOvM4uccB_0oyJVaUzWQw,8465
128
- rbx/grading/judge/sandbox.py,sha256=STsDJH-PEhSJ9hGvwxApHDX7jCAa797FV7hZQBmFOSo,21537
127
+ rbx/grading/judge/program.py,sha256=ttT7X_uLls4ARIbid0MnSteo8Eti1fRw73FL_Ej6S_o,9683
128
+ rbx/grading/judge/sandbox.py,sha256=mcqJscMPhMfjKhxKFkwIP-I4bnQHHMWeBcXiWHGVS-k,21324
129
129
  rbx/grading/judge/sandboxes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
130
- rbx/grading/judge/sandboxes/stupid_sandbox.py,sha256=Q3UyFiwMpJ36tlU_oesNJ3lTzL4iNVmcWlazA0Yq4r4,11368
130
+ rbx/grading/judge/sandboxes/stupid_sandbox.py,sha256=-fSYt0WNf04rrakhxdrunYlmwO2uM2Pf1HmUX8qfxrI,11458
131
131
  rbx/grading/judge/sandboxes/tee.py,sha256=fLulB8fV7k5cO-ikRgURpsETrvr6LoUSjGxFM3GZs5U,672
132
- rbx/grading/judge/sandboxes/timeit.py,sha256=V4Nu7YAU85jJp2_MtUbh4g8Fx5Wf3hax-4_UTNCorEs,11355
133
- rbx/grading/judge/storage.py,sha256=T1r3g8NKzF6IpW2K2gCJSBz81NBAQ_j_0cwq58gqZFA,14373
134
- rbx/grading/judge/test.py,sha256=ll0Iw7zyOpGdKPD_PGH7dvUkb4stQLu-ikbQnqJvuAc,944
132
+ rbx/grading/judge/storage.py,sha256=A88O81-vzv8vMBGrO9gtFk8iB5fTD7ObpO8mvNH4OmA,14576
135
133
  rbx/grading/limits.py,sha256=ev312UTOo8S4-3AAVibQdXZclWCxS96CdbZxqW4y1kE,770
136
- rbx/grading/processing_context.py,sha256=Jg9kNnkH3hi2hiE6Gh23QwS89r9Zj230NMl1CUEHSfo,1866
137
134
  rbx/grading/profiling.py,sha256=OEdtoAzjYjLfi-QI5Ke7tLZzJeqvGpMB2utQBNuH3E4,3369
138
- rbx/grading/steps.py,sha256=PLnuORN-11W9ARSLOrZ0Di30Pl9oSKVfRUGLQoCfeow,26606
135
+ rbx/grading/steps.py,sha256=MkeWH3VfTcwBkKW8Jn5q32ttdJKw0m0_4Cl5rZiL5WI,26604
139
136
  rbx/grading/steps_with_caching.py,sha256=RWHtmlEfszKnKM9ADrfbCUZbxZSTD-BiHV3XSiGW8WY,4797
140
137
  rbx/providers/__init__.py,sha256=gHXg1BTiXJ_0Z_HoVTZrqhi5IIZ57Dhy0pt7K2ETbA4,1378
141
138
  rbx/providers/codeforces.py,sha256=HWQN3Zb9UfXgCfwcNMEk6m1HoXQ-UE2odVfZoPukyCg,2294
@@ -221,9 +218,9 @@ rbx/submitors/__init__.py,sha256=sVcRNnuKMZatmpGkQURaEVHK-MfU2U0nH4nOatuqywE,620
221
218
  rbx/submitors/codeforces.py,sha256=s8c7sXfm5k76SKMC8g0Y93-RRf8wY2uWbBtA8ODD5eM,4030
222
219
  rbx/submitors/submitor.py,sha256=8q-Hbdahxt30ciT_R9j_xF6lEPUh9IcfAUnzjQjbvHU,457
223
220
  rbx/testing_utils.py,sha256=965vlkQpUW8cEqjB6S2g_C_avL5fn503mJPbqjY_zt4,2317
224
- rbx/utils.py,sha256=8f53t5AdonCi20Xxm3hjBZ8fdg9hNpt0-xUhSTfE7u4,6929
225
- rbx_cp-0.13.5.dist-info/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
226
- rbx_cp-0.13.5.dist-info/METADATA,sha256=lKzIg6at_3DbPTYFqMgkGU2FOsrnRTzojlgvS6x6aXk,4659
227
- rbx_cp-0.13.5.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
228
- rbx_cp-0.13.5.dist-info/entry_points.txt,sha256=qBTLBOeifT1F00LWaEewRRE_jQPgvH7BUdJfZ-dYsFU,57
229
- rbx_cp-0.13.5.dist-info/RECORD,,
221
+ rbx/utils.py,sha256=xDqmry5rpqRGPFrx3ipNGBt2WxWDAD5LwU7jvgibXkk,8630
222
+ rbx_cp-0.13.6.dist-info/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
223
+ rbx_cp-0.13.6.dist-info/METADATA,sha256=YRfhn0e29x1tf9DRjJbTE2kL19oQN3gx7Cz1evofaUg,4659
224
+ rbx_cp-0.13.6.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
225
+ rbx_cp-0.13.6.dist-info/entry_points.txt,sha256=qBTLBOeifT1F00LWaEewRRE_jQPgvH7BUdJfZ-dYsFU,57
226
+ rbx_cp-0.13.6.dist-info/RECORD,,
@@ -1,358 +0,0 @@
1
- import dataclasses
2
- import os
3
- import pathlib
4
- import resource
5
- import signal
6
- import stat
7
- import sys
8
- import threading
9
- from time import monotonic
10
- from typing import Any, Dict, List, Optional, Set, Union
11
-
12
-
13
- @dataclasses.dataclass
14
- class Options:
15
- output_file: str
16
- argv: List[str]
17
- chdir: Optional[str] = None
18
- stdin_file: Optional[str] = None
19
- stdout_file: Optional[str] = None
20
- stderr_file: Optional[str] = None
21
- time_limit: Optional[float] = None
22
- wall_time_limit: Optional[float] = None # seconds
23
- memory_limit: Optional[int] = None # kb, but passed in args as mb
24
- fs_limit: Optional[int] = None # kb
25
- files_to_open: List[int] = dataclasses.field(default_factory=list)
26
- file_duplicates: Dict[int, List[str]] = dataclasses.field(default_factory=dict)
27
- prefixed: Set[str] = dataclasses.field(default_factory=set)
28
- prefix: str = ''
29
- process_group: Optional[int] = None
30
-
31
-
32
- def exit_with(code: int):
33
- sys.exit(code)
34
-
35
-
36
- def get_tee_command(files: List[str]) -> str:
37
- path = (
38
- os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tee.py')
39
- + ' '
40
- + ' '.join(files)
41
- )
42
- return sys.executable + ' ' + path
43
-
44
-
45
- valid_modes = ['a', 'w']
46
-
47
-
48
- @dataclasses.dataclass
49
- class Tee:
50
- file: Any
51
- prefix: Union[str, bytes] = ''
52
-
53
-
54
- def create_tee(files, mode, buffer_size=4096, prefix=''):
55
- """Get a file object that will mirror writes across multiple files objs
56
-
57
- Options:
58
- files A list of files and/or file objects. All strings will be
59
- treated as file paths and opened for writing. Everything
60
- else is assumed to be a file-like object that implements
61
- both the write() and flush() methods.
62
-
63
- mode Which mode to use when opening new files. Valid values
64
- are 'a' (append) and 'w' (overwrite).
65
-
66
- buffer_size
67
- Control the size of the buffer between writes to the
68
- resulting file object and the list of files.
69
- """
70
- if mode not in valid_modes:
71
- raise IOError(
72
- 'Only valid modes to create_tee() are: %s' % ', '.join(valid_modes)
73
- )
74
-
75
- tee_list = []
76
- for file in files:
77
- if isinstance(file, Tee):
78
- tee_list.append(file)
79
- else:
80
- tee_list.append(Tee(file))
81
- for tee in tee_list:
82
- if isinstance(tee.file, str):
83
- tee.file = open(tee.file, f'{mode}b')
84
- if isinstance(tee.prefix, str):
85
- tee.prefix = tee.prefix.encode()
86
-
87
- pipe_read, pipe_write = os.pipe()
88
- pid = os.fork()
89
- if pid == 0:
90
- # Child -- Read bytes from the pipe and write them to the specified
91
- # files.
92
- try:
93
- # Close parent's end of the pipe
94
- os.close(pipe_write)
95
-
96
- new = True
97
- while bytes := os.read(pipe_read, 1):
98
- for tee in tee_list:
99
- if tee.prefix and new:
100
- tee.file.write(tee.prefix)
101
- tee.file.write(bytes)
102
- tee.file.flush()
103
- # TODO maybe add in fsync() here if the fileno() method
104
- # exists on file
105
- new = bytes == b'\n'
106
- except Exception:
107
- pass
108
- finally:
109
- os._exit(255)
110
- else:
111
- # Parent -- Return a file object wrapper around the pipe to the
112
- # child.
113
- # Preserve line buffering (buffering=1).
114
- return os.fdopen(pipe_write, 'w', buffering=1, closefd=False)
115
-
116
-
117
- def parse_opts() -> Options:
118
- options = Options(output_file=sys.argv[1], argv=[])
119
- options.files_to_open = []
120
- num_opts = 0
121
- while num_opts + 2 < len(sys.argv) and sys.argv[num_opts + 2].startswith('-'):
122
- # Process option
123
- opt = sys.argv[num_opts + 2]
124
- if opt.startswith('-t'):
125
- options.time_limit = float(opt[2:])
126
- elif opt.startswith('-w'):
127
- options.wall_time_limit = float(opt[2:])
128
- elif opt.startswith('-m'):
129
- options.memory_limit = int(opt[2:]) * 1024
130
- elif opt.startswith('-i'):
131
- options.stdin_file = opt[2:]
132
- options.files_to_open.append(0)
133
- elif opt.startswith('-o'):
134
- options.stdout_file = opt[2:]
135
- options.files_to_open.append(1)
136
- elif opt.startswith('-e'):
137
- options.stderr_file = opt[2:]
138
- options.files_to_open.append(2)
139
- elif opt.startswith('-d') or opt.startswith('-D'):
140
- is_prefixed = opt.startswith('-D')
141
- possibilities = [None, 'o', 'e']
142
- index = possibilities.index(opt[2])
143
- if index not in options.file_duplicates:
144
- options.file_duplicates[index] = []
145
- options.file_duplicates[index].append(opt[3:])
146
- if is_prefixed:
147
- options.prefixed.add(opt[3:])
148
- elif opt.startswith('-c'):
149
- options.chdir = opt[2:]
150
- elif opt.startswith('-f'):
151
- options.fs_limit = int(opt[2:])
152
- elif opt.startswith('-P'):
153
- options.prefix = opt[2:]
154
- elif opt.startswith('-g'):
155
- options.process_group = int(opt[2:])
156
- else:
157
- raise Exception(f'Invalid option {opt}')
158
- num_opts += 1
159
- options.argv = sys.argv[num_opts + 2 :]
160
- return options
161
-
162
-
163
- def get_memory_usage(ru: resource.struct_rusage) -> int:
164
- if sys.platform == 'darwin':
165
- return ru.ru_maxrss // 1024 + ru.ru_ixrss
166
- return ru.ru_maxrss + ru.ru_ixrss + ru.ru_idrss + ru.ru_isrss
167
-
168
-
169
- def get_cpu_time(ru: resource.struct_rusage) -> float:
170
- return ru.ru_utime + ru.ru_stime
171
-
172
-
173
- def _get_file_size(filename: Optional[str]) -> int:
174
- if filename is None:
175
- return 0
176
- path = pathlib.Path(filename)
177
- if not path.is_file():
178
- return 0
179
- return path.stat().st_size
180
-
181
-
182
- def get_file_sizes(options: Options):
183
- return _get_file_size(options.stdout_file) + _get_file_size(options.stderr_file)
184
-
185
-
186
- def set_rlimits(options: Options):
187
- if options.time_limit is not None:
188
- time_limit_in_ms = int(options.time_limit * 1000)
189
- rlimit_cpu = int((time_limit_in_ms + 999) // 1000)
190
- resource.setrlimit(resource.RLIMIT_CPU, (rlimit_cpu, rlimit_cpu + 1))
191
- if options.fs_limit is not None:
192
- fs_limit = options.fs_limit * 1024 # in bytes
193
- resource.setrlimit(resource.RLIMIT_FSIZE, (fs_limit + 1, fs_limit * 2))
194
-
195
-
196
- def redirect_fds(options: Options):
197
- files = [options.stdin_file, options.stdout_file, options.stderr_file]
198
-
199
- for i in options.files_to_open:
200
- file = files[i]
201
- if file is None:
202
- continue
203
- open_args = [
204
- os.O_WRONLY | os.O_TRUNC | os.O_CREAT,
205
- stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR,
206
- ]
207
- if i == 0:
208
- # stdin
209
- open_args = [os.O_RDONLY]
210
- if i in options.file_duplicates:
211
- dups = [
212
- Tee(f, prefix=options.prefix if f in options.prefixed else '')
213
- for f in options.file_duplicates[i]
214
- ]
215
- tee = create_tee(dups + [file], 'a', prefix=options.prefix)
216
- fd = tee.fileno()
217
- else:
218
- fd = os.open(
219
- file,
220
- *open_args,
221
- )
222
- os.dup2(fd, i)
223
- os.close(fd)
224
-
225
-
226
- def wait_and_finish(
227
- pid: int,
228
- options: Options,
229
- start_time: float,
230
- status_holder: Set[str],
231
- alarm_msg: Optional[List[Optional[str]]] = None,
232
- ):
233
- _, exitstatus, ru = os.wait4(pid, 0)
234
- wall_time = monotonic() - start_time
235
- cpu_time = get_cpu_time(ru)
236
- memory_used = get_memory_usage(ru)
237
- file_sizes = get_file_sizes(options)
238
-
239
- entries = []
240
- exitcode = os.waitstatus_to_exitcode(exitstatus)
241
- entries.append(f'exit-code: {exitcode}')
242
- if exitcode < 0:
243
- entries.append(f'exit-sig: {-exitcode}')
244
-
245
- status = status_holder
246
- if exitcode > 0:
247
- status.add('RE')
248
- if exitcode < 0:
249
- status.add('SG')
250
- if options.time_limit is not None and (
251
- cpu_time > options.time_limit or -exitcode == 24
252
- ):
253
- status.add('TO')
254
- cpu_time = max(cpu_time, options.time_limit)
255
- if options.wall_time_limit is not None and wall_time > options.wall_time_limit:
256
- status.add('WT')
257
- status.add('TO')
258
- if options.memory_limit is not None and memory_used > options.memory_limit:
259
- status.add('ML')
260
- if options.fs_limit is not None and file_sizes > options.fs_limit * 1024:
261
- status.add('OL')
262
-
263
- if status:
264
- status_str = ','.join(status)
265
- entries.append(f'status: {status_str}')
266
-
267
- if alarm_msg:
268
- alarm_str = ','.join(msg for msg in alarm_msg if msg is not None)
269
- if alarm_str:
270
- entries.append(f'alarm-msg: {alarm_str}')
271
-
272
- entries.append(f'time: {cpu_time:.3f}')
273
- entries.append(f'time-wall: {wall_time:.3f}')
274
- entries.append(f'mem: {memory_used}')
275
- entries.append(f'file: {file_sizes}')
276
- entries.append(f'pid: {pid}')
277
-
278
- output_file = pathlib.Path(sys.argv[1])
279
- output_file.parent.mkdir(parents=True, exist_ok=True)
280
- output_file.write_text('\n'.join(entries) + '\n')
281
-
282
-
283
- def main():
284
- options = parse_opts()
285
-
286
- if options.process_group is not None:
287
- os.setpgid(0, options.process_group)
288
-
289
- start_time = monotonic()
290
- sub_pid = os.fork()
291
- if sub_pid == 0:
292
- if options.chdir is not None:
293
- os.chdir(options.chdir)
294
- set_rlimits(options)
295
- redirect_fds(options)
296
- signal.signal(signal.SIGPIPE, signal.SIG_DFL)
297
- os.execvp(options.argv[0], options.argv)
298
-
299
- alarm_msg: List[Optional[str]] = [None]
300
- status_holder: Set[str] = set()
301
-
302
- stop_wall_handler = threading.Event()
303
- stop_alarm_handler = threading.Event()
304
-
305
- def handle_wall():
306
- if stop_wall_handler.wait(options.wall_time_limit):
307
- return
308
- stop_alarm_handler.set()
309
- nonlocal alarm_msg
310
- alarm_msg[0] = 'wall timelimit'
311
- os.kill(sub_pid, 9)
312
-
313
- def handle_alarm():
314
- if stop_alarm_handler.wait(0.3):
315
- return
316
- nonlocal alarm_msg
317
- ru = resource.getrusage(resource.RUSAGE_CHILDREN)
318
- if options.time_limit is not None:
319
- cpu_time = get_cpu_time(ru)
320
- if cpu_time > options.time_limit:
321
- alarm_msg[0] = 'timelimit'
322
- os.kill(sub_pid, 9)
323
- return
324
- if options.memory_limit is not None:
325
- memory_used = get_memory_usage(ru)
326
- if memory_used > options.memory_limit:
327
- alarm_msg[0] = 'memorylimit'
328
- os.kill(sub_pid, 9)
329
- return
330
-
331
- stop_alarm_handler.clear()
332
- handle_alarm()
333
-
334
- alarm_handler = threading.Thread(target=handle_alarm, daemon=True)
335
- wall_handler = threading.Thread(target=handle_wall, daemon=True)
336
- alarm_handler.start()
337
- wall_handler.start()
338
-
339
- def handle_sub_term(*args, **kwargs):
340
- nonlocal status_holder
341
- status_holder.add('TE')
342
- os.kill(sub_pid, 9)
343
-
344
- signal.signal(signal.SIGTERM, handle_sub_term)
345
-
346
- wait_and_finish(sub_pid, options, start_time, status_holder, alarm_msg=alarm_msg)
347
-
348
- # Process finished, stop the handlers.
349
- stop_wall_handler.set()
350
- stop_alarm_handler.set()
351
-
352
- # Exit gracefully.
353
- sys.exit(0)
354
-
355
-
356
- if __name__ == '__main__':
357
- main()
358
- # type: ignore
rbx/grading/judge/test.py DELETED
@@ -1,38 +0,0 @@
1
- import atexit
2
- import pathlib
3
-
4
- from rich.console import Console
5
-
6
- from rbx.grading.judge import cacher, storage
7
- from rbx.grading.judge.sandboxes import stupid_sandbox
8
-
9
- console = Console()
10
-
11
-
12
- def main():
13
- fs = storage.FilesystemStorage(pathlib.PosixPath('/tmp/rbx-storage'))
14
- cache = cacher.FileCacher(fs)
15
-
16
- python_file = cache.put_file_text("print('hello')")
17
-
18
- sandbox = stupid_sandbox.StupidSandbox(cache)
19
- atexit.register(sandbox.cleanup)
20
- sandbox.create_file_from_storage(pathlib.PosixPath('run.py'), python_file)
21
-
22
- sandbox.params.stdout_file = pathlib.PosixPath('run.out')
23
-
24
- sandbox.execute_without_std(['ls'])
25
- try:
26
- sandbox.hydrate_logs()
27
- except Exception:
28
- console.print_exception()
29
-
30
- print(sandbox.get_human_exit_description())
31
- print(sandbox.get_stats())
32
- print(sandbox.log)
33
-
34
- print(sandbox.get_file_to_string(pathlib.PosixPath('run.out')))
35
-
36
-
37
- if __name__ == '__main__':
38
- main()
@@ -1,71 +0,0 @@
1
- import contextlib
2
- import os
3
- import signal
4
- import subprocess
5
- from typing import List, Optional
6
-
7
- from rbx.grading.judge.sandbox import SandboxBase
8
-
9
-
10
- @contextlib.contextmanager
11
- def new_process_group():
12
- p = subprocess.Popen(['/bin/bash', '-c', 'exec sleep infinity'])
13
- try:
14
- yield p.pid
15
- finally:
16
- p.terminate()
17
- p.wait()
18
-
19
-
20
- def should_use_group(sandboxes: List[SandboxBase]) -> bool:
21
- if not sandboxes:
22
- return False
23
- uses_pgid = all(sandbox.use_pgid() for sandbox in sandboxes)
24
- all_pgids = set(
25
- sandbox.params.pgid for sandbox in sandboxes if sandbox.params.pgid is not None
26
- )
27
- return uses_pgid and len(all_pgids) == 1
28
-
29
-
30
- async def _fetch_pids(sandboxes: List[SandboxBase]) -> List[int]:
31
- return [await sandbox.get_pid() for sandbox in sandboxes]
32
-
33
-
34
- def _find_sandbox_idx(pids: List[int], pid: int) -> Optional[int]:
35
- try:
36
- return pids.index(pid)
37
- except ValueError:
38
- return None
39
-
40
-
41
- async def _wait_for_group(sandboxes: List[SandboxBase]) -> List[int]:
42
- pgid = [
43
- sandbox.params.pgid for sandbox in sandboxes if sandbox.params.pgid is not None
44
- ][0]
45
- assert pgid is not None
46
-
47
- sandbox_pids = await _fetch_pids(sandboxes)
48
-
49
- finished = []
50
- while len(finished) < len(sandboxes):
51
- try:
52
- pid, status = os.waitpid(-pgid, 0)
53
- except ChildProcessError:
54
- break
55
-
56
- if os.waitstatus_to_exitcode(status) != 0:
57
- os.kill(pgid, signal.SIGKILL)
58
-
59
- sandbox_idx = _find_sandbox_idx(sandbox_pids, pid)
60
- if sandbox_idx is not None:
61
- finished.append(sandbox_idx)
62
- continue
63
-
64
- return finished
65
-
66
-
67
- async def wait_all(sandboxes: List[SandboxBase]):
68
- if not should_use_group(sandboxes):
69
- raise RuntimeError('Sandboxes are not using a process group')
70
-
71
- await _wait_for_group(sandboxes)