Fix CSS injection with disabled page scripting and browser workspace setup
Browse filesUse synchronous style DOM insertion; add runtime computed-style preflight; report exact setup stage; use writable private HOME/XDG/temp paths and subprocess UID/GID rather than Python preexec hooks. Separate read-only requests from writable Docker workspaces. Fixed 350-task dataset unchanged. Live Modal verification remains outstanding.
- README.md +7 -0
- SHA256SUMS +5 -5
- examples/local-test-report.json +3 -2
- sandbox/supervisor.py +22 -11
- sandbox/worker.py +36 -13
- tests/test_watchdog.py +46 -0
README.md
CHANGED
|
@@ -135,3 +135,10 @@ The `phase-watchdog-v1` evaluator supervises the browser worker in a separate pr
|
|
| 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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
### CSS fixture setup correction
|
| 141 |
+
|
| 142 |
+
CSS styles are inserted synchronously with a DOM style element; the evaluator does not use Playwright 1.56 `add_style_tag`, whose inline-style path waits for a `load` callback. This avoids waiting for that callback on the HTML/CSS pages with scripting disabled. Trusted fixture and baseline errors remain infrastructure failures, separate from candidate execution. Timeout diagnostics now name the precise phase, operation, scenario and language and include bounded worker stderr.
|
| 143 |
+
|
| 144 |
+
The Modal path first checks runtime availability and a trusted CSS computed-style/distractor probe, before model generation. Worker processes use explicit subprocess UID/GID settings and private writable HOME/XDG/TMP directories; no Python pre-exec callback is used in the threaded launcher. These changes preserve the fixed 350-example dataset and scoring definition. End-to-end Modal browser verification is still required; local tests cover the injection protocol, diagnostic fields, preflight failure and watchdog behavior.
|
SHA256SUMS
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
|
| 2 |
8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE
|
| 3 |
-
|
| 4 |
2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac archive/v0.1.0/hidden.jsonl
|
| 5 |
1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 archive/v0.1.0/smolscript.jsonl
|
| 6 |
7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 archive/v0.1.0/smolscript.parquet
|
|
@@ -12,7 +12,7 @@ ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
|
|
| 12 |
9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonl
|
| 13 |
ad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet
|
| 14 |
96bc6e69d752e9fee97389dd15d921173f603c9ce972b1defa49549e977032b1 evaluate.py
|
| 15 |
-
|
| 16 |
713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json
|
| 17 |
b0871e1f323ac493a0e413d1ac085b1cda3c94e496a1bfecac11aa58773d3144 generation_settings.py
|
| 18 |
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py
|
|
@@ -42,10 +42,10 @@ efabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python
|
|
| 42 |
63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.py
|
| 43 |
d9ebf5141e3c1928879865050bf3ad7773613084fe62a0ff7eac8d1ea69f8cc4 runners/sandbox.py
|
| 44 |
53098a63b7d2053a4d8494c340e63d924646255c297d31e78c0025ef552c6cd6 sandbox/Dockerfile
|
| 45 |
-
|
| 46 |
-
|
| 47 |
c155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py
|
| 48 |
-
|
| 49 |
ffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py
|
| 50 |
845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json
|
| 51 |
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 validators/__init__.py
|
|
|
|
| 1 |
ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
|
| 2 |
8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE
|
| 3 |
+
f1025bcd6a338e93766ddeacb39f2aaf9edb743b9f418968f46bcd13aa14b862 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
|
|
|
|
| 12 |
9f9798909d3ab3631a457de1bc7e573c546ed3f3b0f78e6bcb82780e280b37b3 data/smolscript.jsonl
|
| 13 |
ad56c7186df28d84a23912a7fa2ec28b6762240a33b7b2a49412ce5b47319862 data/smolscript.parquet
|
| 14 |
96bc6e69d752e9fee97389dd15d921173f603c9ce972b1defa49549e977032b1 evaluate.py
|
| 15 |
+
9395164c1296d2d71c6c61a9ed367564c6a06d5933f0aeb2ed62d652561c857d examples/local-test-report.json
|
| 16 |
713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json
|
| 17 |
b0871e1f323ac493a0e413d1ac085b1cda3c94e496a1bfecac11aa58773d3144 generation_settings.py
|
| 18 |
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py
|
|
|
|
| 42 |
63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.py
|
| 43 |
d9ebf5141e3c1928879865050bf3ad7773613084fe62a0ff7eac8d1ea69f8cc4 runners/sandbox.py
|
| 44 |
53098a63b7d2053a4d8494c340e63d924646255c297d31e78c0025ef552c6cd6 sandbox/Dockerfile
|
| 45 |
+
013cc442aa61d4b85f1986b111ea9adea5f9749bf0cef5176faa67963c900e7c sandbox/supervisor.py
|
| 46 |
+
538b3c7176b678e6a2b2a55a52aaa2e4a03accc20b2d7d850ee67695f5ecdc9f sandbox/worker.py
|
| 47 |
c155b14ce8fa94dd4a179c22e6ab13accadffcf3571f384d27985ba916cbf864 tests/test_core.py
|
| 48 |
+
14f40a4b954c81dcf6cb8a2bdf361023e8cea36b54b31e40657f92f39433c124 tests/test_watchdog.py
|
| 49 |
ffba2ed9eabec6186a7568ff0535c9733841b661f7c1e420770dbeb47d87dbae validate.py
|
| 50 |
845d1ef1d45133e04908e1ff187281b9af9f4e48c2bec1994f91b1b191d5d563 validation_report.json
|
| 51 |
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 validators/__init__.py
|
examples/local-test-report.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
"unit_tests": {
|
| 3 |
-
"passed":
|
| 4 |
"command": "python -m unittest discover -s tests -q"
|
| 5 |
},
|
| 6 |
"python_reference_ast_parse": 44,
|
|
@@ -24,5 +24,6 @@
|
|
| 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 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"unit_tests": {
|
| 3 |
+
"passed": 21,
|
| 4 |
"command": "python -m unittest discover -s tests -q"
|
| 5 |
},
|
| 6 |
"python_reference_ast_parse": 44,
|
|
|
|
| 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 |
+
"browser_setup_patch": "synchronous-css-private-home-v1"
|
| 29 |
}
|
sandbox/supervisor.py
CHANGED
|
@@ -9,28 +9,35 @@ import tempfile
|
|
| 9 |
import time
|
| 10 |
|
| 11 |
|
| 12 |
-
def supervise(request, worker='/opt/smolscript/worker.py',
|
| 13 |
-
startup_seconds=45, candidate_seconds=None, total_seconds=240):
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
if candidate_seconds is None:candidate_seconds=max(6,3*payload.get('timeout_seconds',3))
|
| 16 |
-
with tempfile.TemporaryDirectory(dir=
|
| 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=
|
| 23 |
-
stdout=stdout,stderr=stderr,env=env,start_new_session=True,
|
| 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:
|
|
@@ -39,7 +46,11 @@ def supervise(request, worker='/opt/smolscript/worker.py', demote=None,
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
try:process.wait(timeout=.1)
|
| 44 |
except subprocess.TimeoutExpired:pass
|
| 45 |
stdout.seek(0);stderr.seek(0)
|
|
@@ -55,6 +66,6 @@ def supervise(request, worker='/opt/smolscript/worker.py', demote=None,
|
|
| 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))
|
|
|
|
| 9 |
import time
|
| 10 |
|
| 11 |
|
| 12 |
+
def supervise(request, worker='/opt/smolscript/worker.py', worker_uid=None, worker_gid=None,
|
| 13 |
+
startup_seconds=45, candidate_seconds=None, total_seconds=240, workspace=None):
|
| 14 |
+
request=Path(request).resolve()
|
| 15 |
+
workspace=Path(workspace).resolve() if workspace is not None else request.parent
|
| 16 |
+
payload=json.loads(request.read_text())
|
| 17 |
if candidate_seconds is None:candidate_seconds=max(6,3*payload.get('timeout_seconds',3))
|
| 18 |
+
with tempfile.TemporaryDirectory(dir=workspace,prefix='watchdog-') as directory:
|
| 19 |
os.chmod(directory,0o777)
|
| 20 |
state_path=Path(directory)/'state.json'
|
| 21 |
env={k:v for k,v in os.environ.items() if k in ('PATH','HOME','LANG','LC_ALL','TZ','PYTHONHASHSEED','PYTHONPATH','PLAYWRIGHT_BROWSERS_PATH')}
|
| 22 |
env['SMOLSCRIPT_WORKER_STATE']=str(state_path)
|
| 23 |
+
env['HOME']=str(workspace)
|
| 24 |
+
for key,name in (('XDG_CACHE_HOME','cache'),('XDG_CONFIG_HOME','config'),('TMPDIR','tmp')):
|
| 25 |
+
target=Path(directory)/name;target.mkdir(mode=0o777);target.chmod(0o777);env[key]=str(target)
|
| 26 |
+
credentials={}
|
| 27 |
+
if worker_uid is not None:credentials.update(user=worker_uid,group=worker_gid,extra_groups=[])
|
| 28 |
with tempfile.TemporaryFile() as stdout,tempfile.TemporaryFile() as stderr:
|
| 29 |
+
process=subprocess.Popen([sys.executable,str(worker),str(request)],cwd=workspace,
|
| 30 |
+
stdout=stdout,stderr=stderr,env=env,start_new_session=True,**credentials)
|
| 31 |
started=time.monotonic();phase_started=started;previous=None;state={}
|
| 32 |
try:
|
| 33 |
while process.poll() is None:
|
| 34 |
try:state=json.loads(state_path.read_text())
|
| 35 |
except (FileNotFoundError,json.JSONDecodeError):pass
|
| 36 |
+
phase=(state.get('phase'),state.get('scenario'),state.get('operation'))
|
| 37 |
if phase!=previous:previous=phase;phase_started=time.monotonic()
|
| 38 |
now=time.monotonic()
|
| 39 |
+
candidate=state.get('phase')=='candidate' and not payload.get('diagnostic')
|
| 40 |
+
browser=payload.get('diagnostic') or payload.get('kind') in ('html','css','dom')
|
| 41 |
limit=(candidate_seconds if candidate else startup_seconds) if browser else total_seconds
|
| 42 |
if now-phase_started>limit or now-started>total_seconds:
|
| 43 |
if candidate and state.get('syntax_success') is True:
|
|
|
|
| 46 |
observations.append({'actual':[],'baseline':[],
|
| 47 |
'error':'CandidateTimeout: browser execution exceeded its wall-time limit'})
|
| 48 |
return {'syntax_success':True,'observations':observations,'candidate_timeout':True}
|
| 49 |
+
stderr.seek(0)
|
| 50 |
+
detail=stderr.read(2000).decode('utf8','replace')
|
| 51 |
+
raise RuntimeError('SmolScript worker timed out during browser/runtime setup; evaluation incomplete; '
|
| 52 |
+
f"phase={state.get('phase','worker_start')} operation={state.get('operation')} "
|
| 53 |
+
f"scenario={state.get('scenario')} language={payload.get('language',payload.get('kind'))}; stderr={detail}")
|
| 54 |
try:process.wait(timeout=.1)
|
| 55 |
except subprocess.TimeoutExpired:pass
|
| 56 |
stdout.seek(0);stderr.seek(0)
|
|
|
|
| 66 |
process.wait(timeout=5)
|
| 67 |
|
| 68 |
if __name__=='__main__':
|
| 69 |
+
try:response=supervise(sys.argv[1],workspace=Path.cwd())
|
| 70 |
except Exception as exc:response={'infrastructure_error':type(exc).__name__+': '+str(exc)[:2000]}
|
| 71 |
print(json.dumps(response,allow_nan=False))
|
sandbox/worker.py
CHANGED
|
@@ -10,12 +10,12 @@ import tempfile
|
|
| 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 |
|
|
@@ -75,6 +75,16 @@ def observe(page,check):
|
|
| 75 |
raise ValueError(kind)
|
| 76 |
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def browser(request):
|
| 79 |
from playwright.sync_api import sync_playwright,TimeoutError as BrowserTimeout
|
| 80 |
kind=request['kind'];code=request['code']
|
|
@@ -99,25 +109,30 @@ def browser(request):
|
|
| 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())
|
| 113 |
actual=[];baseline=[];error=None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
try:
|
| 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':
|
| 121 |
else:
|
| 122 |
page.add_script_tag(content=code)
|
| 123 |
page.evaluate('() => setup()')
|
|
@@ -131,6 +146,7 @@ def browser(request):
|
|
| 131 |
actual=[observe(page,c) for c in scenario['checks']]
|
| 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:
|
|
@@ -146,11 +162,18 @@ def main():
|
|
| 146 |
for lang,(_,cmd,run) in COMMANDS.items():
|
| 147 |
import shutil
|
| 148 |
result[lang]=bool(shutil.which(cmd[0]) and (run[0].startswith('./') or shutil.which(run[0])))
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
result.update(html=True,css=True)
|
| 153 |
-
return {'runtimes':result}
|
| 154 |
return browser(r) if r['kind'] in ('html','css','dom') else program(r)
|
| 155 |
|
| 156 |
if __name__=='__main__':
|
|
|
|
| 10 |
from protocol import COMMANDS,wrap_source
|
| 11 |
|
| 12 |
|
| 13 |
+
def publish_state(phase,observations=None,scenario=None,operation=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,'operation':operation,'observations':observations or []}))
|
| 19 |
tmp.replace(target)
|
| 20 |
|
| 21 |
|
|
|
|
| 75 |
raise ValueError(kind)
|
| 76 |
|
| 77 |
|
| 78 |
+
def inject_css(page,css):
|
| 79 |
+
# Playwright 1.56 add_style_tag awaits a stylesheet load callback, which can
|
| 80 |
+
# stall with page scripting disabled. CSSOM insertion needs no event callback.
|
| 81 |
+
page.evaluate("""css => {
|
| 82 |
+
const style=document.createElement('style');
|
| 83 |
+
style.textContent=css;
|
| 84 |
+
document.head.appendChild(style);
|
| 85 |
+
}""",css)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
def browser(request):
|
| 89 |
from playwright.sync_api import sync_playwright,TimeoutError as BrowserTimeout
|
| 90 |
kind=request['kind'];code=request['code']
|
|
|
|
| 109 |
syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0
|
| 110 |
if not syntax:return {'syntax_success':False,'observations':[]}
|
| 111 |
observations=[]
|
| 112 |
+
publish_state('browser_startup',operation='playwright_driver')
|
| 113 |
with sync_playwright() as p:
|
| 114 |
# Container namespace, seccomp, uid, cgroups and disabled networking are
|
| 115 |
# the mandatory boundary; no browser flag substitutes for that boundary.
|
| 116 |
+
publish_state('browser_startup',operation='chromium_launch')
|
| 117 |
b=p.chromium.launch(headless=True,timeout=20000,args=['--disable-dev-shm-usage'])
|
| 118 |
try:
|
| 119 |
for index,scenario in enumerate(request['scenarios']):
|
| 120 |
+
publish_state('fixture_setup',observations,index,'new_page')
|
| 121 |
page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')
|
| 122 |
page.set_default_timeout(request['timeout_seconds']*1000)
|
| 123 |
page.route('**/*',lambda route:route.abort())
|
| 124 |
actual=[];baseline=[];error=None
|
| 125 |
+
publish_state('fixture_setup',observations,index,'fixture_document')
|
| 126 |
+
page.set_content(request['fixture'],wait_until='domcontentloaded')
|
| 127 |
+
if request.get('base_css'):
|
| 128 |
+
publish_state('fixture_setup',observations,index,'base_css')
|
| 129 |
+
inject_css(page,request['base_css'])
|
| 130 |
+
publish_state('fixture_setup',observations,index,'baseline_observations')
|
| 131 |
+
baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]
|
| 132 |
+
publish_state('candidate',observations,index,'candidate_execution')
|
| 133 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
if kind=='html':page.set_content(code,wait_until='domcontentloaded')
|
| 135 |
+
elif kind=='css':inject_css(page,code)
|
| 136 |
else:
|
| 137 |
page.add_script_tag(content=code)
|
| 138 |
page.evaluate('() => setup()')
|
|
|
|
| 146 |
actual=[observe(page,c) for c in scenario['checks']]
|
| 147 |
except Exception as e:error=type(e).__name__+': '+str(e)[:500]
|
| 148 |
observations.append({'actual':actual,'baseline':baseline,'error':error})
|
| 149 |
+
publish_state('candidate',observations[:-1],index,'page_close')
|
| 150 |
page.close()
|
| 151 |
publish_state('fixture_setup',observations,index)
|
| 152 |
finally:
|
|
|
|
| 162 |
for lang,(_,cmd,run) in COMMANDS.items():
|
| 163 |
import shutil
|
| 164 |
result[lang]=bool(shutil.which(cmd[0]) and (run[0].startswith('./') or shutil.which(run[0])))
|
| 165 |
+
probe=browser({'kind':'css','code':'#probe { color: rgb(10, 20, 30); }',
|
| 166 |
+
'fixture':'<p id="probe">Probe</p><p id="other">Other</p>',
|
| 167 |
+
'base_css':'p { color: rgb(0, 0, 0); }','timeout_seconds':3,
|
| 168 |
+
'scenarios':[{'checks':[{'kind':'style','selector':'#probe','property':'color'},
|
| 169 |
+
{'kind':'unchanged','selector':'#other','property':'color'}]}]})
|
| 170 |
+
if not probe['syntax_success'] or len(probe['observations'])!=1:
|
| 171 |
+
raise RuntimeError('CSS preflight produced incomplete observations')
|
| 172 |
+
observed=probe['observations'][0]
|
| 173 |
+
if observed['error'] or observed['actual']!=['rgb(10, 20, 30)','rgb(0, 0, 0)']:
|
| 174 |
+
raise RuntimeError('CSS preflight failed computed-style checks: '+json.dumps(observed))
|
| 175 |
result.update(html=True,css=True)
|
| 176 |
+
return {'runtimes':result,'browser_preflight':'passed'}
|
| 177 |
return browser(r) if r['kind'] in ('html','css','dom') else program(r)
|
| 178 |
|
| 179 |
if __name__=='__main__':
|
tests/test_watchdog.py
CHANGED
|
@@ -62,6 +62,52 @@ while True: time.sleep(1)
|
|
| 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')
|
|
|
|
| 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_css_injection_is_synchronous_and_does_not_wait_for_load(self):
|
| 66 |
+
from unittest.mock import Mock
|
| 67 |
+
sys.path.insert(0,str(ROOT/'runners'))
|
| 68 |
+
spec=importlib.util.spec_from_file_location('worker_injection_test',ROOT/'sandbox/worker.py')
|
| 69 |
+
worker=importlib.util.module_from_spec(spec);spec.loader.exec_module(worker)
|
| 70 |
+
page=Mock()
|
| 71 |
+
worker.inject_css(page,'p { color: red; }')
|
| 72 |
+
page.add_style_tag.assert_not_called()
|
| 73 |
+
source,css=page.evaluate.call_args.args
|
| 74 |
+
self.assertEqual(css,'p { color: red; }')
|
| 75 |
+
self.assertIn('style.textContent=css',source)
|
| 76 |
+
self.assertNotIn('Promise',source);self.assertNotIn('onload',source)
|
| 77 |
+
def test_setup_timeout_identifies_exact_operation(self):
|
| 78 |
+
with tempfile.TemporaryDirectory() as d:
|
| 79 |
+
request,worker=self.fixture(d,'''import json,os,time
|
| 80 |
+
from pathlib import Path
|
| 81 |
+
Path(os.environ['SMOLSCRIPT_WORKER_STATE']).write_text(json.dumps({'phase':'fixture_setup','scenario':0,'operation':'base_css'}))
|
| 82 |
+
time.sleep(60)
|
| 83 |
+
''')
|
| 84 |
+
with self.assertRaisesRegex(RuntimeError,'operation=base_css'):
|
| 85 |
+
watchdog.supervise(request,worker,startup_seconds=.15,total_seconds=3)
|
| 86 |
+
def test_worker_has_writable_private_home_and_xdg_paths(self):
|
| 87 |
+
with tempfile.TemporaryDirectory() as d:
|
| 88 |
+
request,worker=self.fixture(d,'''import json,os
|
| 89 |
+
from pathlib import Path
|
| 90 |
+
for key in ('HOME','XDG_CACHE_HOME','XDG_CONFIG_HOME','TMPDIR'):
|
| 91 |
+
(Path(os.environ[key])/('probe-'+key)).write_text('ok')
|
| 92 |
+
print(json.dumps({'home':os.environ['HOME']}))
|
| 93 |
+
''')
|
| 94 |
+
self.assertEqual(watchdog.supervise(request,worker)['home'],str(Path(d).resolve()))
|
| 95 |
+
|
| 96 |
+
def test_readonly_request_is_separate_from_writable_workspace(self):
|
| 97 |
+
with tempfile.TemporaryDirectory() as d:
|
| 98 |
+
inputs=Path(d)/'input';inputs.mkdir()
|
| 99 |
+
work=Path(d)/'work';work.mkdir()
|
| 100 |
+
request,worker=self.fixture(inputs,'''import json,os
|
| 101 |
+
from pathlib import Path
|
| 102 |
+
Path('artifact').write_text('ok')
|
| 103 |
+
print(json.dumps({'cwd':os.getcwd(),'home':os.environ['HOME']}))
|
| 104 |
+
''')
|
| 105 |
+
request.chmod(0o444);inputs.chmod(0o555)
|
| 106 |
+
try:result=watchdog.supervise(request,worker,workspace=work)
|
| 107 |
+
finally:inputs.chmod(0o755)
|
| 108 |
+
self.assertEqual(result['cwd'],str(work.resolve()));self.assertEqual(result['home'],str(work.resolve()))
|
| 109 |
+
self.assertTrue((work/'artifact').exists());self.assertFalse((inputs/'artifact').exists())
|
| 110 |
+
|
| 111 |
def test_missing_layout_target_does_not_wait_on_locator_evaluate(self):
|
| 112 |
sys.path.insert(0,str(ROOT/'runners'))
|
| 113 |
spec=importlib.util.spec_from_file_location('worker_layout_test',ROOT/'sandbox/worker.py')
|