appvoid commited on
Commit
bebe819
·
verified ·
1 Parent(s): 53cafbc

Bound browser candidate hangs with a phase-aware watchdog

Browse files

Separate startup failures from candidate wall-time failures; preserve parsed syntax and completed observations; kill worker process groups; allow Chromium thread headroom. 350-task dataset unchanged. Browser runtime integration remains unverified locally.

README.md CHANGED
@@ -62,7 +62,7 @@ python validate.py
62
 
63
  The image supplies CPython, Node.js, GCC/G++ (C11/C++17), Lua 5.4, Mono C#, Rust (edition 2021), and Playwright Chromium. Candidate functions use basic C# features supported by Mono. The base Playwright image and Python browser dependencies are pinned. OS compiler packages are resolved at build time; preserve/export the built image for exact runtime reproduction. Every evaluation records the immutable local image ID and available registry digests. Rebuilding later may produce a different image.
64
 
65
- Containers run as UID 1000 with network disabled, a read-only root, no Linux capabilities, no privilege escalation, 2 GB memory/swap ceiling, one CPU, 128 processes, bounded temporary filesystems, CPU/wall timeouts, and bounded output. Compilation has a separate 30-second limit; each program test has a three-second CPU limit plus a one-second wall allowance. Browser operations have three-second timeouts and a container supervisor limit. Candidates have access only to their code, fixture, and input values; expected answers remain in the host scorer. No host home, Docker socket, credentials, or full dataset is mounted. There is no host-execution fallback. Containers are the required isolation boundary; use a dedicated worker for adversarial submissions.
66
 
67
  The sandbox uses the documented [Docker resource and isolation options](https://docs.docker.com/reference/cli/docker/container/run/) and the [Playwright Python container image](https://playwright.dev/python/docs/docker). Evaluation requires no network after model/tokenizer weights and the image have been cached. To enforce offline Hugging Face loading, set `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1`.
68
 
@@ -126,3 +126,12 @@ The default split and both local/Modal evaluators now use the same fixed 350 IDs
126
  The language budgets (before a 32-token moderate-task allowance, capped at 256) are Python 128, JavaScript 192, HTML 160, CSS 96, C++ 224, C 256, Lua 160, C# 256, Rust 256. They depend only on language/difficulty, never reference solutions. `--max-new-tokens N` overrides these budgets for a separately recorded experiment; `--batch-size N` overrides the default 64. A response that hits its cap is scored as generated; incorrect or incomplete code still fails the normal execution tests. Generation statistics include token-limit completions, OOM retries, final batch size, elapsed generation time and measured token throughput.
127
 
128
  Example: `python evaluate.py --model HuggingFaceTB/SmolLM2-135M --batch-size 64 --output results-v030.json`. Generated batches are checkpointed before execution, and resume skips their inference. Numerical batching differences can change greedy outputs for near-tied logits. This release reduces the task count from 1,000 to 350 and retains the fast decoding budgets introduced in 0.2.0. Its scores must not be merged with earlier editions. Template IDs are `smolscript-0.3.0` and `cognirank2-v3`; use a new output path. No GPU throughput speedup is claimed without a measured run.
 
 
 
 
 
 
 
 
 
 
62
 
63
  The image supplies CPython, Node.js, GCC/G++ (C11/C++17), Lua 5.4, Mono C#, Rust (edition 2021), and Playwright Chromium. Candidate functions use basic C# features supported by Mono. The base Playwright image and Python browser dependencies are pinned. OS compiler packages are resolved at build time; preserve/export the built image for exact runtime reproduction. Every evaluation records the immutable local image ID and available registry digests. Rebuilding later may produce a different image.
64
 
65
+ Containers run as UID 1000 with network disabled, a read-only root, no Linux capabilities, no privilege escalation, 2 GB memory/swap ceiling, one CPU, 512 processes, bounded temporary filesystems, CPU/wall timeouts, and bounded output. Compilation has a separate 30-second limit; each program test has a three-second CPU limit plus a one-second wall allowance. Browser operations have three-second timeouts and a container supervisor limit. Candidates have access only to their code, fixture, and input values; expected answers remain in the host scorer. No host home, Docker socket, credentials, or full dataset is mounted. There is no host-execution fallback. Containers are the required isolation boundary; use a dedicated worker for adversarial submissions.
66
 
67
  The sandbox uses the documented [Docker resource and isolation options](https://docs.docker.com/reference/cli/docker/container/run/) and the [Playwright Python container image](https://playwright.dev/python/docs/docker). Evaluation requires no network after model/tokenizer weights and the image have been cached. To enforce offline Hugging Face loading, set `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1`.
68
 
 
126
  The language budgets (before a 32-token moderate-task allowance, capped at 256) are Python 128, JavaScript 192, HTML 160, CSS 96, C++ 224, C 256, Lua 160, C# 256, Rust 256. They depend only on language/difficulty, never reference solutions. `--max-new-tokens N` overrides these budgets for a separately recorded experiment; `--batch-size N` overrides the default 64. A response that hits its cap is scored as generated; incorrect or incomplete code still fails the normal execution tests. Generation statistics include token-limit completions, OOM retries, final batch size, elapsed generation time and measured token throughput.
127
 
128
  Example: `python evaluate.py --model HuggingFaceTB/SmolLM2-135M --batch-size 64 --output results-v030.json`. Generated batches are checkpointed before execution, and resume skips their inference. Numerical batching differences can change greedy outputs for near-tied logits. This release reduces the task count from 1,000 to 350 and retains the fast decoding budgets introduced in 0.2.0. Its scores must not be merged with earlier editions. Template IDs are `smolscript-0.3.0` and `cognirank2-v3`; use a new output path. No GPU throughput speedup is claimed without a measured run.
129
+
130
+
131
+ ## Browser timeout handling
132
+
133
+ The `phase-watchdog-v1` evaluator supervises the browser worker in a separate process group. Chromium launch has a 20-second limit; trusted setup/cleanup phases have a 45-second watchdog. Generated browser code and its assertions have a per-scenario wall limit of `max(6, 3*timeout_seconds)` (nine seconds for current tasks), in addition to three-second Playwright operation timeouts. This also bounds `page.evaluate`, script injection, and stuck page teardown, which do not all obey Playwright's default timeout.
134
+
135
+ A candidate-phase timeout preserves successful syntax parsing and completed observations, fails the unfinished assertions, and lets later tasks continue. Setup failures remain infrastructure errors and do not receive an invented score. The supervisor kills the worker process group during cleanup. Docker/Modal outer deadlines provide additional containment; an outer infrastructure timeout remains a failed evaluation. Modal evaluators run without credentials, and worker environments are explicitly filtered.
136
+
137
+ Rebuild the Docker image after updating these files. The Modal launcher automatically submits the updated supervisor and worker image. Full browser runtime validation remains unverified in the local authoring environment; watchdog regression tests use trusted synthetic worker fixtures.
SHA256SUMS CHANGED
@@ -1,6 +1,6 @@
1
  ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
2
  8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE
3
- e64097e32ceb9ec31376a534a35230f830e173cac543051b9eb339344a655e4e README.md
4
  2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac archive/v0.1.0/hidden.jsonl
5
  1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 archive/v0.1.0/smolscript.jsonl
6
  7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 archive/v0.1.0/smolscript.parquet
@@ -11,8 +11,8 @@ e64097e32ceb9ec31376a534a35230f830e173cac543051b9eb339344a655e4e README.md
11
  34c7244ea9160ba090e7c3bc1802ca68cc882f8ee9c29736ea8529d499977677 archive/v0.2.0/solutions.jsonl
12
  9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonl
13
  ad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet
14
- e2fb32b17e0cb933d08ee8cb87a19f5fa23861a5c37821946a45d9130b04305e evaluate.py
15
- 87a8231fe09d311dfee0a9872234ca13072d401412e0a35bdf8da9b477a54b37 examples/local-test-report.json
16
  713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json
17
  b0871e1f323ac493a0e413d1ac085b1cda3c94e496a1bfecac11aa58773d3144 generation_settings.py
18
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py
@@ -28,7 +28,7 @@ d45aab2646a9bfa15ab1636ce3af71b7ce9dffb49037bfd565e51cea967ceae5 pyproject.toml
28
  d736311f2645f4bdc7bac3316d858788118af4d551290d3924299f96935bd886 references/solutions.jsonl
29
  5a3cb2a82cf3784c41fc9f9046fe6806d5bbe7ce8ae415a9ed1c373abcfe7826 runners/__init__.py
30
  965bc9e3dabfc3fba4b745994b43118c456be477edcc34a3ba929ebf39e19ce9 runners/c_runner.py
31
- 47eaf32ac4ce76fcfbd01d515f6befccfcd2bf6c277447a73e8b7b58fa7e96f8 runners/common.py
32
  17c846633f3730669790ee2f11fc93661648eedc950c96d47996d0db4514672b runners/cpp_runner.py
33
  e87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp_runner.py
34
  96e542ceb76e18759aa8f19fd87beef3612e535f7b9f04944a6bdf1e2fddffec runners/css_runner.py
@@ -40,10 +40,12 @@ e87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp
40
  217be73aeb9055bfcf897d4cc72eb7b06092b9da96202ac2eab95a26d9302b56 runners/protocol.py
41
  efabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python_runner.py
42
  63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.py
43
- 824119581e0bf1c913059fdf506c26494c9aa2f65f718f08630ff5fe74779ff3 runners/sandbox.py
44
- 4fb1552346d86503372e6762f3ddcb0fc7e7e0be2cc1209f419b7c5e37aeccdc sandbox/Dockerfile
45
- 331503e3e4ef8dfce8c82caee8face396275c272b43c7cd61bcca1f535db76ad sandbox/worker.py
 
46
  c155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py
 
47
  ffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py
48
  845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json
49
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 validators/__init__.py
 
1
  ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
2
  8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE
3
+ 79bde23371c74e742d81b9eedcb41c3bbc1f6a22a89a7d4fe29578e43f662353 README.md
4
  2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac archive/v0.1.0/hidden.jsonl
5
  1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 archive/v0.1.0/smolscript.jsonl
6
  7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 archive/v0.1.0/smolscript.parquet
 
11
  34c7244ea9160ba090e7c3bc1802ca68cc882f8ee9c29736ea8529d499977677 archive/v0.2.0/solutions.jsonl
12
  9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonl
13
  ad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet
14
+ 96bc6e69d752e9fee97389dd15d921173f603c9ce972b1defa49549e977032b1 evaluate.py
15
+ 3999b70595e7a873bb2b3de2877de69da280043a91351d33e26872aaa9dcb416 examples/local-test-report.json
16
  713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json
17
  b0871e1f323ac493a0e413d1ac085b1cda3c94e496a1bfecac11aa58773d3144 generation_settings.py
18
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py
 
28
  d736311f2645f4bdc7bac3316d858788118af4d551290d3924299f96935bd886 references/solutions.jsonl
29
  5a3cb2a82cf3784c41fc9f9046fe6806d5bbe7ce8ae415a9ed1c373abcfe7826 runners/__init__.py
30
  965bc9e3dabfc3fba4b745994b43118c456be477edcc34a3ba929ebf39e19ce9 runners/c_runner.py
31
+ 2cd2ee3e805abfca108f19363a828ee38a46afb9d91773f68bdc08231449b68c runners/common.py
32
  17c846633f3730669790ee2f11fc93661648eedc950c96d47996d0db4514672b runners/cpp_runner.py
33
  e87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp_runner.py
34
  96e542ceb76e18759aa8f19fd87beef3612e535f7b9f04944a6bdf1e2fddffec runners/css_runner.py
 
40
  217be73aeb9055bfcf897d4cc72eb7b06092b9da96202ac2eab95a26d9302b56 runners/protocol.py
41
  efabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python_runner.py
42
  63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.py
43
+ d9ebf5141e3c1928879865050bf3ad7773613084fe62a0ff7eac8d1ea69f8cc4 runners/sandbox.py
44
+ 53098a63b7d2053a4d8494c340e63d924646255c297d31e78c0025ef552c6cd6 sandbox/Dockerfile
45
+ 64e26d439e80819fac084f21b3831543d7b3b9ef7cd7afdaa5d9767a033777e1 sandbox/supervisor.py
46
+ 13628f680958644d71c5ba74216bbb06f3fe8928f8b727e02d99944ccfe2f904 sandbox/worker.py
47
  c155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py
48
+ 5a408508d1548d7530bd20af0c3c14fa06b43dbf7e8582868b417265d207e906 tests/test_watchdog.py
49
  ffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py
50
  845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json
51
  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 validators/__init__.py
evaluate.py CHANGED
@@ -34,7 +34,7 @@ def main():
34
  sandbox=Sandbox(a.image,a.engine)
35
  rows=[r for r in load(ROOT/'data/smolscript.jsonl') if (not a.language or r['language'] in a.language) and (not a.difficulty or r['difficulty'] in a.difficulty)]
36
  hidden={r['id']:r for r in load(ROOT/'private_tests/hidden.jsonl')}
37
- files=['data/smolscript.jsonl','private_tests/hidden.jsonl','evaluate.py','metrics.py','generation_settings.py']+[str(p.relative_to(ROOT)) for p in sorted((ROOT/'runners').glob('*.py'))]+['sandbox/worker.py']
38
  fingerprint={f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in files}
39
  settings={'model':a.model,'requested_revision':a.revision,'language':a.language,'difficulty':a.difficulty,
40
  'max_new_tokens':a.max_new_tokens,'batch_size':a.batch_size,'decode_protocol':PROTOCOL,'prompt_version':PROMPT_VERSION,'dataset':fingerprint,'sandbox':sandbox.identity,
 
34
  sandbox=Sandbox(a.image,a.engine)
35
  rows=[r for r in load(ROOT/'data/smolscript.jsonl') if (not a.language or r['language'] in a.language) and (not a.difficulty or r['difficulty'] in a.difficulty)]
36
  hidden={r['id']:r for r in load(ROOT/'private_tests/hidden.jsonl')}
37
+ files=['data/smolscript.jsonl','private_tests/hidden.jsonl','evaluate.py','metrics.py','generation_settings.py']+[str(p.relative_to(ROOT)) for p in sorted((ROOT/'runners').glob('*.py'))]+['sandbox/worker.py','sandbox/supervisor.py']
38
  fingerprint={f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in files}
39
  settings={'model':a.model,'requested_revision':a.revision,'language':a.language,'difficulty':a.difficulty,
40
  'max_new_tokens':a.max_new_tokens,'batch_size':a.batch_size,'decode_protocol':PROTOCOL,'prompt_version':PROMPT_VERSION,'dataset':fingerprint,'sandbox':sandbox.identity,
examples/local-test-report.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "unit_tests": {
3
- "passed": 10,
4
  "command": "python -m unittest discover -s tests -q"
5
  },
6
  "python_reference_ast_parse": 44,
@@ -22,5 +22,7 @@
22
  },
23
  "blocked_reason": "Docker/Podman unavailable; full isolated reference and negative-control execution remains unverified.",
24
  "model_baselines": "not run",
25
- "gpu_throughput_benchmark": "not run"
 
 
26
  }
 
1
  {
2
  "unit_tests": {
3
+ "passed": 17,
4
  "command": "python -m unittest discover -s tests -q"
5
  },
6
  "python_reference_ast_parse": 44,
 
22
  },
23
  "blocked_reason": "Docker/Podman unavailable; full isolated reference and negative-control execution remains unverified.",
24
  "model_baselines": "not run",
25
+ "gpu_throughput_benchmark": "not run",
26
+ "watchdog_policy": "phase-watchdog-v1",
27
+ "watchdog_test_execution": "trusted synthetic workers; candidate generations not executed on host"
28
  }
runners/common.py CHANGED
@@ -49,7 +49,7 @@ class BrowserRunner:
49
  expected.append(checks)
50
  response=sandbox.run({'language':row['language'],'kind':row['metadata']['family'],'code':code,
51
  'fixture':row['metadata'].get('fixture',''),'base_css':row['metadata'].get('base_css',''),
52
- 'scenarios':scenarios,'timeout_seconds':row['timeout_seconds']},timeout=30+len(scenarios)*20)
53
  results=[]
54
  for i,checks in enumerate(expected):
55
  actual=response['observations'][i] if i<len(response['observations']) else None
@@ -58,4 +58,4 @@ class BrowserRunner:
58
  target=actual['baseline'][j] if actual and c['kind']=='unchanged' else c.get('value',True)
59
  passed=bool(actual and not actual['error'] and j<len(actual['actual']) and observed==target)
60
  results.append({'scenario':i,'test':j,'passed':passed,'actual':observed,'error':actual['error'] if actual else 'syntax failure'})
61
- return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(r['passed'] for r in results),'tests':results}
 
49
  expected.append(checks)
50
  response=sandbox.run({'language':row['language'],'kind':row['metadata']['family'],'code':code,
51
  'fixture':row['metadata'].get('fixture',''),'base_css':row['metadata'].get('base_css',''),
52
+ 'scenarios':scenarios,'timeout_seconds':row['timeout_seconds']},timeout=270)
53
  results=[]
54
  for i,checks in enumerate(expected):
55
  actual=response['observations'][i] if i<len(response['observations']) else None
 
58
  target=actual['baseline'][j] if actual and c['kind']=='unchanged' else c.get('value',True)
59
  passed=bool(actual and not actual['error'] and j<len(actual['actual']) and observed==target)
60
  results.append({'scenario':i,'test':j,'passed':passed,'actual':observed,'error':actual['error'] if actual else 'syntax failure'})
61
+ return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(r['passed'] for r in results),'tests':results,'candidate_timeout':response.get('candidate_timeout',False)}
runners/sandbox.py CHANGED
@@ -28,12 +28,12 @@ class Sandbox:
28
  path.write_text(json.dumps(payload));path.chmod(0o444);os.chmod(directory,0o755)
29
  command=[self.engine,'run','--rm','--name',name,'--network','none','--read-only',
30
  '--cap-drop','ALL','--security-opt','no-new-privileges','--user','1000:1000',
31
- '--memory','2g','--memory-swap','2g','--cpus','1','--pids-limit','128',
32
  '--ulimit','nofile=256:256','--ulimit','core=0:0',
33
  '--tmpfs','/work:rw,exec,nosuid,size=256m,uid=1000,gid=1000',
34
  '--tmpfs','/tmp:rw,nosuid,size=128m,uid=1000,gid=1000','--shm-size','128m',
35
  '--mount',f'type=bind,src={directory},dst=/input,readonly',
36
- self.image,'python3','/opt/smolscript/worker.py','/input/request.json']
37
  try:
38
  result=subprocess.run(command,capture_output=True,text=True,timeout=timeout)
39
  if result.returncode:raise RuntimeError('Sandbox infrastructure failed: '+result.stderr[-2000:])
 
28
  path.write_text(json.dumps(payload));path.chmod(0o444);os.chmod(directory,0o755)
29
  command=[self.engine,'run','--rm','--name',name,'--network','none','--read-only',
30
  '--cap-drop','ALL','--security-opt','no-new-privileges','--user','1000:1000',
31
+ '--memory','2g','--memory-swap','2g','--cpus','1','--pids-limit','512',
32
  '--ulimit','nofile=256:256','--ulimit','core=0:0',
33
  '--tmpfs','/work:rw,exec,nosuid,size=256m,uid=1000,gid=1000',
34
  '--tmpfs','/tmp:rw,nosuid,size=128m,uid=1000,gid=1000','--shm-size','128m',
35
  '--mount',f'type=bind,src={directory},dst=/input,readonly',
36
+ self.image,'python3','/opt/smolscript/supervisor.py','/input/request.json']
37
  try:
38
  result=subprocess.run(command,capture_output=True,text=True,timeout=timeout)
39
  if result.returncode:raise RuntimeError('Sandbox infrastructure failed: '+result.stderr[-2000:])
sandbox/Dockerfile CHANGED
@@ -6,6 +6,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
6
  rm -rf /var/lib/apt/lists/*
7
  RUN python3 -m pip install --no-cache-dir playwright==1.56.0 html5lib==1.1 tinycss2==1.4.0
8
  RUN ln -sf /usr/bin/lua5.4 /usr/local/bin/lua && ln -sf /usr/bin/luac5.4 /usr/local/bin/luac
 
9
  COPY sandbox/worker.py /opt/smolscript/worker.py
10
  COPY runners/protocol.py /opt/smolscript/protocol.py
11
  RUN useradd --uid 1000 --create-home --non-unique benchmark 2>/dev/null || true
 
6
  rm -rf /var/lib/apt/lists/*
7
  RUN python3 -m pip install --no-cache-dir playwright==1.56.0 html5lib==1.1 tinycss2==1.4.0
8
  RUN ln -sf /usr/bin/lua5.4 /usr/local/bin/lua && ln -sf /usr/bin/luac5.4 /usr/local/bin/luac
9
+ COPY sandbox/supervisor.py /opt/smolscript/supervisor.py
10
  COPY sandbox/worker.py /opt/smolscript/worker.py
11
  COPY runners/protocol.py /opt/smolscript/protocol.py
12
  RUN useradd --uid 1000 --create-home --non-unique benchmark 2>/dev/null || true
sandbox/supervisor.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted worker watchdog; distinguish startup failures from candidate hangs."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+
11
+
12
+ def supervise(request, worker='/opt/smolscript/worker.py', demote=None,
13
+ startup_seconds=45, candidate_seconds=None, total_seconds=240):
14
+ payload=json.loads(Path(request).read_text())
15
+ if candidate_seconds is None:candidate_seconds=max(6,3*payload.get('timeout_seconds',3))
16
+ with tempfile.TemporaryDirectory(dir=Path(request).parent,prefix='watchdog-') as directory:
17
+ os.chmod(directory,0o777)
18
+ state_path=Path(directory)/'state.json'
19
+ env={k:v for k,v in os.environ.items() if k in ('PATH','HOME','LANG','LC_ALL','TZ','PYTHONHASHSEED','PYTHONPATH','PLAYWRIGHT_BROWSERS_PATH')}
20
+ env['SMOLSCRIPT_WORKER_STATE']=str(state_path)
21
+ with tempfile.TemporaryFile() as stdout,tempfile.TemporaryFile() as stderr:
22
+ process=subprocess.Popen([sys.executable,str(worker),str(request)],cwd=Path(request).parent,
23
+ stdout=stdout,stderr=stderr,env=env,start_new_session=True,preexec_fn=demote)
24
+ started=time.monotonic();phase_started=started;previous=None;state={}
25
+ try:
26
+ while process.poll() is None:
27
+ try:state=json.loads(state_path.read_text())
28
+ except (FileNotFoundError,json.JSONDecodeError):pass
29
+ phase=(state.get('phase'),state.get('scenario'))
30
+ if phase!=previous:previous=phase;phase_started=time.monotonic()
31
+ now=time.monotonic()
32
+ candidate=state.get('phase')=='candidate'
33
+ browser=payload.get('kind') in ('html','css','dom')
34
+ limit=(candidate_seconds if candidate else startup_seconds) if browser else total_seconds
35
+ if now-phase_started>limit or now-started>total_seconds:
36
+ if candidate and state.get('syntax_success') is True:
37
+ observations=list(state.get('observations',[]))
38
+ for _ in range(len(payload.get('scenarios',[]))-len(observations)):
39
+ observations.append({'actual':[],'baseline':[],
40
+ 'error':'CandidateTimeout: browser execution exceeded its wall-time limit'})
41
+ return {'syntax_success':True,'observations':observations,'candidate_timeout':True}
42
+ raise RuntimeError('SmolScript worker timed out during browser/runtime setup; evaluation incomplete')
43
+ try:process.wait(timeout=.1)
44
+ except subprocess.TimeoutExpired:pass
45
+ stdout.seek(0);stderr.seek(0)
46
+ if process.returncode:
47
+ raise RuntimeError('SmolScript sandbox worker failed: '+stderr.read(2000).decode('utf8','replace'))
48
+ response=json.loads(stdout.read(8*1024*1024))
49
+ if response.get('infrastructure_error'):raise RuntimeError(response['infrastructure_error'])
50
+ return response
51
+ finally:
52
+ # Kill descendants even if the worker exited but left children alive.
53
+ try:os.killpg(process.pid,signal.SIGKILL)
54
+ except ProcessLookupError:pass
55
+ process.wait(timeout=5)
56
+
57
+ if __name__=='__main__':
58
+ try:response=supervise(sys.argv[1])
59
+ except Exception as exc:response={'infrastructure_error':type(exc).__name__+': '+str(exc)[:2000]}
60
+ print(json.dumps(response,allow_nan=False))
sandbox/worker.py CHANGED
@@ -10,6 +10,15 @@ import tempfile
10
  from protocol import COMMANDS,wrap_source
11
 
12
 
 
 
 
 
 
 
 
 
 
13
  def limits(seconds,file_limit):
14
  os.setsid()
15
  resource.setrlimit(resource.RLIMIT_CPU,(seconds,seconds+1))
@@ -52,6 +61,7 @@ def observe(page,check):
52
  loc=page.locator(check['selector']);kind=check['kind']
53
  if kind=='count':return loc.count()
54
  if kind in ('layout_column','layout_row'):
 
55
  return loc.evaluate('''(e,kind) => { const a=e.querySelectorAll('span'); if(a.length!==2) return false;
56
  const x=a[0].getBoundingClientRect(), y=a[1].getBoundingClientRect();
57
  return kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)
@@ -89,12 +99,14 @@ def browser(request):
89
  syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0
90
  if not syntax:return {'syntax_success':False,'observations':[]}
91
  observations=[]
 
92
  with sync_playwright() as p:
93
  # Container namespace, seccomp, uid, cgroups and disabled networking are
94
  # the mandatory boundary; no browser flag substitutes for that boundary.
95
- b=p.chromium.launch(headless=True,args=['--disable-dev-shm-usage'])
96
  try:
97
- for scenario in request['scenarios']:
 
98
  page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')
99
  page.set_default_timeout(request['timeout_seconds']*1000)
100
  page.route('**/*',lambda route:route.abort())
@@ -103,6 +115,7 @@ def browser(request):
103
  page.set_content(request['fixture'],wait_until='domcontentloaded')
104
  if request.get('base_css'):page.add_style_tag(content=request['base_css'])
105
  baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]
 
106
  if kind=='html':page.set_content(code,wait_until='domcontentloaded')
107
  elif kind=='css':page.add_style_tag(content=code)
108
  else:
@@ -119,7 +132,10 @@ def browser(request):
119
  except Exception as e:error=type(e).__name__+': '+str(e)[:500]
120
  observations.append({'actual':actual,'baseline':baseline,'error':error})
121
  page.close()
122
- finally:b.close()
 
 
 
123
  return {'syntax_success':True,'observations':observations}
124
 
125
 
 
10
  from protocol import COMMANDS,wrap_source
11
 
12
 
13
+ def publish_state(phase,observations=None,scenario=None):
14
+ path=os.environ.get('SMOLSCRIPT_WORKER_STATE')
15
+ if not path:return
16
+ target=Path(path);tmp=target.with_suffix('.tmp')
17
+ tmp.write_text(json.dumps({'phase':phase,'syntax_success':True,
18
+ 'scenario':scenario,'observations':observations or []}))
19
+ tmp.replace(target)
20
+
21
+
22
  def limits(seconds,file_limit):
23
  os.setsid()
24
  resource.setrlimit(resource.RLIMIT_CPU,(seconds,seconds+1))
 
61
  loc=page.locator(check['selector']);kind=check['kind']
62
  if kind=='count':return loc.count()
63
  if kind in ('layout_column','layout_row'):
64
+ if loc.count()!=1:return {'error':'missing or ambiguous layout target'}
65
  return loc.evaluate('''(e,kind) => { const a=e.querySelectorAll('span'); if(a.length!==2) return false;
66
  const x=a[0].getBoundingClientRect(), y=a[1].getBoundingClientRect();
67
  return kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)
 
99
  syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0
100
  if not syntax:return {'syntax_success':False,'observations':[]}
101
  observations=[]
102
+ publish_state('browser_startup')
103
  with sync_playwright() as p:
104
  # Container namespace, seccomp, uid, cgroups and disabled networking are
105
  # the mandatory boundary; no browser flag substitutes for that boundary.
106
+ b=p.chromium.launch(headless=True,timeout=20000,args=['--disable-dev-shm-usage'])
107
  try:
108
+ for index,scenario in enumerate(request['scenarios']):
109
+ publish_state('fixture_setup',observations,index)
110
  page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')
111
  page.set_default_timeout(request['timeout_seconds']*1000)
112
  page.route('**/*',lambda route:route.abort())
 
115
  page.set_content(request['fixture'],wait_until='domcontentloaded')
116
  if request.get('base_css'):page.add_style_tag(content=request['base_css'])
117
  baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]
118
+ publish_state('candidate',observations,index)
119
  if kind=='html':page.set_content(code,wait_until='domcontentloaded')
120
  elif kind=='css':page.add_style_tag(content=code)
121
  else:
 
132
  except Exception as e:error=type(e).__name__+': '+str(e)[:500]
133
  observations.append({'actual':actual,'baseline':baseline,'error':error})
134
  page.close()
135
+ publish_state('fixture_setup',observations,index)
136
+ finally:
137
+ publish_state('browser_cleanup',observations)
138
+ b.close()
139
  return {'syntax_success':True,'observations':observations}
140
 
141
 
tests/test_watchdog.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run only trusted watchdog fixtures on host; no candidate generations."""
2
+ import importlib.util
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import sys
7
+ import tempfile
8
+ import unittest
9
+ ROOT=Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0,str(ROOT))
11
+ spec=importlib.util.spec_from_file_location('smolscript_watchdog',ROOT/'sandbox/supervisor.py')
12
+ watchdog=importlib.util.module_from_spec(spec);spec.loader.exec_module(watchdog)
13
+
14
+ class WatchdogTests(unittest.TestCase):
15
+ def fixture(self,d,source):
16
+ request=Path(d)/'request.json';request.write_text(json.dumps({'kind':'dom','scenarios':[{},{}]}))
17
+ worker=Path(d)/'fixture.py';worker.write_text(source)
18
+ return request,worker
19
+ def test_candidate_timeout_preserves_syntax_and_completed_scenarios(self):
20
+ with tempfile.TemporaryDirectory() as d:
21
+ request,worker=self.fixture(d,'''import json,os,time
22
+ from pathlib import Path
23
+ Path(os.environ['SMOLSCRIPT_WORKER_STATE']).write_text(json.dumps({'phase':'candidate','scenario':1,'syntax_success':True,'observations':[{'actual':['ok'],'baseline':[None],'error':None}]}))
24
+ while True: time.sleep(1)
25
+ ''')
26
+ result=watchdog.supervise(request,worker,startup_seconds=2,candidate_seconds=.1,total_seconds=3)
27
+ self.assertTrue(result['syntax_success']);self.assertTrue(result['candidate_timeout'])
28
+ self.assertEqual(result['observations'][0]['actual'],['ok'])
29
+ self.assertIn('CandidateTimeout',result['observations'][1]['error'])
30
+ def test_startup_hang_is_infrastructure_failure(self):
31
+ with tempfile.TemporaryDirectory() as d:
32
+ request,worker=self.fixture(d,'import time\ntime.sleep(60)\n')
33
+ with self.assertRaisesRegex(RuntimeError,'setup; evaluation incomplete'):
34
+ watchdog.supervise(request,worker,startup_seconds=.1,total_seconds=2)
35
+ def test_normal_return_and_infrastructure_error(self):
36
+ with tempfile.TemporaryDirectory() as d:
37
+ request,worker=self.fixture(d,'print(\'{"syntax_success":false,"observations":[]}\')')
38
+ self.assertFalse(watchdog.supervise(request,worker)['syntax_success'])
39
+ worker.write_text('print(\'{"infrastructure_error":"Chromium missing"}\')')
40
+ with self.assertRaisesRegex(RuntimeError,'Chromium missing'):watchdog.supervise(request,worker)
41
+ def test_program_does_not_use_browser_startup_deadline(self):
42
+ with tempfile.TemporaryDirectory() as d:
43
+ request,worker=self.fixture(d,'import time\ntime.sleep(.25)\nprint(\'{"syntax_success":true,"observations":[]}\')')
44
+ request.write_text('{"kind":"scalar"}')
45
+ result=watchdog.supervise(request,worker,startup_seconds=.05,total_seconds=2)
46
+ self.assertTrue(result['syntax_success'])
47
+ def test_browser_runner_records_timeout_as_failed_task(self):
48
+ from runners.common import BrowserRunner
49
+ class Sandbox:
50
+ def run(self,payload,timeout):
51
+ return {'syntax_success':True,'candidate_timeout':True,'observations':[
52
+ {'actual':[],'baseline':[],'error':'CandidateTimeout: execution exceeded wall time'}]}
53
+ row={'language':'javascript','timeout_seconds':3,'metadata':{'family':'dom','fixture':'<p id="x">0</p>'}}
54
+ result=BrowserRunner().evaluate(row,'function setup() {}',
55
+ {'tests':[{'checks':[{'kind':'text','selector':'#x','value':'1'}]}]},Sandbox())
56
+ self.assertTrue(result['syntax_success']);self.assertFalse(result['passed'])
57
+ self.assertTrue(result['candidate_timeout']);self.assertIn('CandidateTimeout',result['tests'][0]['error'])
58
+
59
+ def test_worker_environment_excludes_credentials(self):
60
+ with tempfile.TemporaryDirectory() as d:
61
+ request,worker=self.fixture(d,'import json,os\nprint(json.dumps({"secret":os.environ.get("SMOLSCRIPT_TEST_SECRET")}))')
62
+ from unittest.mock import patch
63
+ with patch.dict(os.environ,SMOLSCRIPT_TEST_SECRET='never-pass-to-worker'):
64
+ self.assertIsNone(watchdog.supervise(request,worker)['secret'])
65
+ def test_missing_layout_target_does_not_wait_on_locator_evaluate(self):
66
+ sys.path.insert(0,str(ROOT/'runners'))
67
+ spec=importlib.util.spec_from_file_location('worker_layout_test',ROOT/'sandbox/worker.py')
68
+ worker=importlib.util.module_from_spec(spec);spec.loader.exec_module(worker)
69
+ class Locator:
70
+ def count(self):return 0
71
+ def evaluate(self,*args):raise AssertionError('should not wait')
72
+ class Page:
73
+ def locator(self,*args):return Locator()
74
+ self.assertIn('error',worker.observe(Page(),{'selector':'#absent','kind':'layout_row'}))
75
+
76
+ if __name__=='__main__':unittest.main()