Files
leleka/scripts/smoke-cuda-memory.py
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

155 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""Isolated Linux CPU children and fake inventory; never queries a real GPU."""
import http.client
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import tempfile
import time
A = 'GPU-00000000-0000-0000-0000-000000000001'
B = 'GPU-00000000-0000-0000-0000-000000000002'
def main():
binary = str(Path(sys.argv[1]).resolve())
assert sys.platform == 'linux', 'Linux-only isolated admission fixture'
with tempfile.TemporaryDirectory(prefix='strata-cuda-memory-') as temp:
root = Path(temp)
probe = root / 'nvidia-smi'
probe.write_text('''#!/usr/bin/env python3
import os, pathlib, sys, time
r=pathlib.Path(os.environ['FIXTURE_ROOT'])
if sys.argv[1] == '--query-gpu=driver_version':
print((r/'driver-version').read_text() if (r/'driver-version').exists() else '580.65.06');sys.exit(0)
assert sys.argv[1:] == ['--query-gpu=uuid,memory.total,memory.free,mig.mode.current','--format=csv,noheader,nounits']
n=int((r/'queries').read_text())+1 if (r/'queries').exists() else 1
(r/'queries').write_text(str(n))
mode=(r/'mode').read_text()
if mode=='sleep':
(r/'probe-pid').write_text(str(os.getpid()));time.sleep(30)
if mode=='oversize': print('x'*8193);sys.exit(0)
if mode=='exit':sys.exit(3)
if mode=='malformed':print('not inventory');sys.exit(0)
f=r/('later' if n>1 and (r/'later').exists() else 'inventory')
print(f.read_text(),end='')
''')
probe.chmod(0o700)
engine = root / 'engine'
engine.write_text('''#!/usr/bin/env python3
import os, pathlib, sys
r=pathlib.Path(os.environ['FIXTURE_ROOT'])
with (r/'children').open('a') as f:f.write(os.environ.get('CUDA_VISIBLE_DEVICES','UNSET')+'\\n')
print('READY 256 stop',flush=True)
if (r/'crash').exists():sys.exit(3)
for line in sys.stdin:
if line.strip()=='QUIT':break
''')
engine.chmod(0o700)
env = {'PATH': str(root)+os.pathsep+os.environ['PATH'], 'FIXTURE_ROOT': str(root)}
with socket.socket() as s:
s.bind(('127.0.0.1', 0));port=s.getsockname()[1]
config = {'bind': f'127.0.0.1:{port}', 'model': 'fixture', 'gpu_requirement': 'cuda-13.0-linux',
'cuda_memory': {'required_mib': 7000, 'reserve_mib': 1000},
'engine': {'executable': str(engine), 'startup_timeout_s': 3, 'max_restarts': 1}}
path = root / 'config.json'
def reset(mode='ok', later=None, visible=None):
for name in ('queries', 'children', 'later', 'probe-pid', 'crash', 'driver-version'):
(root/name).unlink(missing_ok=True)
(root/'mode').write_text(mode)
(root/'inventory').write_text(f'{A},8192,8000,Disabled\n{B},16384,16000,[N/A]\n')
if later is not None:(root/'later').write_text(later)
env.pop('CUDA_VISIBLE_DEVICES',None)
if visible is not None:env['CUDA_VISIBLE_DEVICES']=visible
path.write_text(json.dumps(config))
def run(command, expected=0, *extra):
r=subprocess.run([binary,command,'--config',str(path),*extra],env=env,capture_output=True,timeout=9)
assert (r.returncode==0)==(expected==0),(r.returncode,r.stderr)
return r
def status():
c=http.client.HTTPConnection('127.0.0.1',port,timeout=2)
try:
c.request('GET','/status');r=c.getresponse();assert r.status==200
return json.loads(r.read())
finally:c.close()
def serve(expected, crash=False):
if crash:(root/'crash').touch()
with tempfile.TemporaryFile() as log:
p=subprocess.Popen([binary,'serve','--config',str(path)],env=env,stdout=log,stderr=log,start_new_session=True)
try:
end=time.monotonic()+8
while True:
try:
value=status()
worker=value['worker']
children=(root/'children').read_text().splitlines() if (root/'children').exists() else []
if expected is None and worker=='failed':assert not children;break
if expected is not None and children==expected and (worker=='failed' if crash else worker=='ready'):break
except (OSError,KeyError):pass
assert p.poll() is None and time.monotonic()<end, 'worker state/pin not reached'
time.sleep(.03)
finally:
os.killpg(p.pid,signal.SIGTERM)
p.wait(timeout=8)
log.seek(0);data=log.read().decode()
assert p.returncode==0,data
reset('exit')
assert json.loads(run('check-config').stdout)['cuda_memory_checked'] is False
assert not (root/'queries').exists()
for policy in [{'required_mib':0,'reserve_mib':1},{'required_mib':2**64-1,'reserve_mib':1}]:
invalid={**config,'cuda_memory':policy};path.write_text(json.dumps(invalid));run('check-config',1)
path.write_text(json.dumps({k:v for k,v in config.items() if k!='gpu_requirement'}));run('check-config',1)
for mode in ('exit','malformed','oversize','sleep'):
reset(mode);start=time.monotonic();run('provision',1)
assert time.monotonic()-start<7
assert not (root/'children').exists()
if mode=='sleep':
pid=int((root/'probe-pid').read_text())
try:os.kill(pid,0)
except ProcessLookupError:pass
else:raise AssertionError('timed-out probe was not reaped')
for visible in ('','0','-1','GPU-123',f'{A},{A}'):
reset(visible=visible);run('provision',1)
reset();(root/'inventory').write_text(f'{A},8192,7999,Disabled\n')
path.write_text(json.dumps({**config,'assets':[{'manifest':str(root/'absent-manifest'),'directory':str(root/'absent-output')}]}))
assert b'no visible non-MIG GPU' in run('provision',1).stderr
assert not (root/'absent-output').exists() # before acquisition or manifest loading
# Allocation-free switch preparation works while the old model occupies VRAM.
reset();(root/'inventory').write_text(f'{A},8192,0,Disabled\n')
prepared=json.loads(run('provision',0,'--defer-memory-check').stdout)
assert prepared['memory_admission']=='deferred_until_serve' and not prepared['worker_started']
assert not (root/'queries').exists() and not (root/'children').exists()
assert b'no visible non-MIG GPU' in run('provision',1).stderr
assert b'no visible non-MIG GPU' in run('serve',1).stderr
assert not (root/'children').exists()
path.write_text(json.dumps({**config,'assets':[{'manifest':str(root/'absent-manifest'),'directory':str(root/'absent-output')}]}))
run('provision',1,'--defer-memory-check')
assert not (root/'absent-output').exists()
reset();(root/'driver-version').write_text('570.1')
run('provision',1,'--defer-memory-check')
assert not (root/'queries').exists() and not (root/'children').exists()
reset();run('provision');assert not (root/'children').exists()
reset();serve([B])
reset(visible=A);serve([A])
# Early selection B cannot silently move to A after B loses memory/disappears.
reset(later=f'{A},8192,8000,Disabled\n{B},16384,7999,[N/A]\n');serve(None)
reset(later=f'{A},8192,8000,Disabled\n');serve(None)
reset();serve([B,B],crash=True)
# No policy preserves manual CPU/visibility behavior and performs no inventory.
reset('exit',visible='fixture-manual-value')
path.write_text(json.dumps({k:v for k,v in config.items() if k not in ('cuda_memory','gpu_requirement')}))
serve(['fixture-manual-value']);assert not (root/'queries').exists()
print('CUDA memory CPU fixture: budget/visibility/UUID pin/recheck/restart/timeout/strict input/CPU compatibility PASS; no GPU or model fit qualification')
if __name__=='__main__':main()