240 lines
10 KiB
Python
240 lines
10 KiB
Python
import json
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
import pytest
|
|
|
|
pytestmark = pytest.mark.usefixtures('all_day_gpu_policy')
|
|
|
|
from llm_services.store import Store, Settings
|
|
from llm_services.gpu_policy import GpuPolicy
|
|
from llm_services.gpu_reservation import GpuReservation
|
|
from llm_services.worker import Worker, UnsafeRecovery, group_members
|
|
|
|
|
|
def queued(store):
|
|
return store.submit('image.generate', {}, {})
|
|
|
|
|
|
def test_overlapping_claims_are_atomic(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
for _ in range(3):
|
|
queued(store)
|
|
stores = [Store(store.path), Store(store.path)]
|
|
with ThreadPoolExecutor(2) as pool:
|
|
claims = list(pool.map(lambda pair: pair[0].claim_next(gpu_uuids=pair[1]),
|
|
zip(stores, [('GPU-A','GPU-B'), ('gpu-b','GPU-C')])))
|
|
winner, = [j for j in claims if j]
|
|
assert store.running()[0]['gpu_uuids'] == winner['gpu_uuids']
|
|
assert store.claim_next(gpu_uuid='GPU-B') is None
|
|
store.requeue_preempted(winner['id'], 'external', attempt_count=1)
|
|
store.claim_next(gpu_uuids=['GPU-A', 'GPU-B'])
|
|
with pytest.raises(RuntimeError):
|
|
store.finish(winner['id'], 'failed', attempt_count=1)
|
|
assert store.active_gpu_uuids() == {'GPU-A','GPU-B'}
|
|
|
|
|
|
def test_second_member_failure_rolls_back_claim(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
job = queued(store)
|
|
with sqlite3.connect(store.path) as db:
|
|
db.execute("""CREATE TRIGGER reject_second BEFORE INSERT ON gpu_lease_members
|
|
WHEN NEW.rank=1 BEGIN SELECT RAISE(ABORT,'injected'); END""")
|
|
with pytest.raises(sqlite3.IntegrityError):
|
|
store.claim_next(gpu_uuids=['GPU-A','GPU-B'])
|
|
assert not store.active_gpu_uuids()
|
|
assert store.get(job['id'])['attempt_count'] == 0
|
|
|
|
|
|
def test_old_running_single_is_migrated(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
job = queued(store)
|
|
store.claim_next(gpu_uuid='GPU-A')
|
|
with sqlite3.connect(store.path) as db:
|
|
db.execute('drop table gpu_lease_members')
|
|
db.execute('pragma user_version=2')
|
|
migrated = Store(store.path)
|
|
assert migrated.get(job['id'])['gpu_uuids'] == ['GPU-A']
|
|
queued(migrated)
|
|
assert migrated.claim_next(gpu_uuids=['GPU-B','gpu-a']) is None
|
|
|
|
|
|
def test_group_environment(tmp_path):
|
|
policy = GpuPolicy(tmp_path / 'status')
|
|
members = [{'uuid':'GPU-00000000-0000-0000-0000-00000000000'+str(i),'index':i} for i in (1,2)]
|
|
env = policy.environment(dict(members[0],members=members))
|
|
assert env['CUDA_VISIBLE_DEVICES'] == ','.join(m['uuid'] for m in members)
|
|
assert json.loads(env['LLM_GPU_LEASE_MEMBERS']) == members
|
|
|
|
|
|
@pytest.mark.parametrize('members',[[], ['GPU-A','gpu-a'], [1], ['a','b','c'], 'GPU-A'])
|
|
def test_invalid_members(tmp_path,members):
|
|
store = Store(tmp_path/'queue')
|
|
with pytest.raises(ValueError):
|
|
store.claim_next(gpu_uuids=members)
|
|
|
|
|
|
def test_group_rank1_reservation(tmp_path):
|
|
store = Store(tmp_path/'queue')
|
|
queued(store)
|
|
store.claim_next(gpu_uuids=['GPU-A','GPU-B'])
|
|
reservation = GpuReservation(tmp_path/'hold','GPU-B')
|
|
reservation.path.write_text(json.dumps(dict(schema_version=1,gpu_uuid='GPU-B',hold=True,token='0'*32,queue_seq_cutoff=0)))
|
|
assert not reservation.acknowledgement(store,0)['quiesced']
|
|
|
|
|
|
TP2 = 'minimax-h3-fl2va-bf16-tp2-v1'
|
|
UUIDS = [f'GPU-00000000-0000-0000-0000-{rank:012d}' for rank in range(2)]
|
|
|
|
|
|
class FakeGroupPolicy(GpuPolicy):
|
|
def __init__(self, path, card_count=2):
|
|
super().__init__(path)
|
|
self.card_count = card_count
|
|
self.external = set()
|
|
|
|
def _read(self):
|
|
gpus = [dict(uuid=uuid, index=index, external_pids=([1] if uuid in self.external else []))
|
|
for index, uuid in enumerate(UUIDS[:self.card_count])]
|
|
return {'gpus': gpus}, None, 0
|
|
|
|
def describe(self):
|
|
return {'eligible_gpus': [dict(uuid=uuid, index=index)
|
|
for index, uuid in enumerate(UUIDS[:self.card_count]) if uuid not in self.external]}
|
|
|
|
|
|
def test_rank1_external_yields_whole_lease(tmp_path):
|
|
policy = FakeGroupPolicy(tmp_path/'guard')
|
|
members = policy.describe()['eligible_gpus']
|
|
lease = dict(members[0], members=members)
|
|
assert policy.should_yield(lease) is None
|
|
policy.external.add(UUIDS[1])
|
|
assert 'External' in policy.should_yield(lease)
|
|
|
|
|
|
def test_one_card_leaves_fifo_head_unclaimed(tmp_path, monkeypatch):
|
|
settings = Settings(tmp_path/'app', tmp_path, video_generation_tp2_poc_enabled=True)
|
|
worker = Worker(settings, gpu_policy=FakeGroupPolicy(tmp_path/'guard', 1))
|
|
monkeypatch.setattr(worker, '_reference_admission_reason', lambda job: None)
|
|
worker._lock_fd = -1
|
|
head = worker.store.submit('video.generate', {}, {'profile': TP2})
|
|
tail = queued(worker.store)
|
|
assert not worker.dispatch_once()
|
|
assert not worker.run_once()
|
|
assert not worker.store.active_gpu_uuids()
|
|
assert all(worker.store.get(job['id'])['attempt_count'] == 0 for job in (head,tail))
|
|
assert settings.memory_estimates_gib['video.generate'] >= 288
|
|
|
|
|
|
@pytest.mark.skipif(sys.platform != 'linux', reason='requires Linux flock and /proc')
|
|
@pytest.mark.parametrize('action', ['cancel','preempt','pressure','uncertain_cleanup'])
|
|
def test_both_cpu_ranks_exit_before_release(tmp_path, monkeypatch, action):
|
|
policy = FakeGroupPolicy(tmp_path/'guard')
|
|
settings = Settings(tmp_path/'app', tmp_path, video_generation_tp2_poc_enabled=True,
|
|
video_generation_tp2_python=sys.executable, poll_seconds=.02)
|
|
worker = Worker(settings, gpu_policy=policy)
|
|
monkeypatch.setattr(worker, '_reference_admission_reason', lambda job: None)
|
|
monkeypatch.setattr(worker.memory_admission, 'check', lambda *args, **kwargs: None)
|
|
monkeypatch.setattr('llm_services.worker.validate_request', lambda kind, inputs, params, root: (inputs, params))
|
|
monkeypatch.setattr(worker.memory_admission, 'running_pressure', lambda: None)
|
|
ready = tmp_path/'ranks-ready'
|
|
code = (
|
|
"import os,sys,time,subprocess,pathlib,json;"
|
|
"children=[subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)']) for _ in range(2)];"
|
|
f"pathlib.Path({str(ready)!r}).write_text(json.dumps([os.getpgid(c.pid) for c in children]));"
|
|
"time.sleep(60)"
|
|
)
|
|
monkeypatch.setattr(worker, '_command', lambda *args: [sys.executable,'-c',code])
|
|
job = worker.store.submit('video.generate', {}, {'profile': TP2})
|
|
with worker:
|
|
assert worker.dispatch_once()
|
|
deadline = time.monotonic() + 8
|
|
while not ready.exists() and time.monotonic() < deadline:
|
|
time.sleep(.02)
|
|
pgid = worker.store.get(job['id'])['runner_pgid']
|
|
assert json.loads(ready.read_text()) == [pgid,pgid]
|
|
assert worker.store.active_gpu_uuids() == set(UUIDS)
|
|
if action == 'cancel':
|
|
worker.store.cancel(job['id'])
|
|
elif action == 'preempt':
|
|
policy.external.add(UUIDS[1])
|
|
else:
|
|
terminate = worker._terminate_group
|
|
def verify_ownership(*args, **kwargs):
|
|
assert worker.store.active_gpu_uuids() == set(UUIDS)
|
|
terminate(*args, **kwargs)
|
|
if action == 'uncertain_cleanup':
|
|
raise UnsafeRecovery("Injected cleanup uncertainty")
|
|
monkeypatch.setattr(worker, '_terminate_group', verify_ownership)
|
|
monkeypatch.setattr(worker.memory_admission, 'running_pressure', lambda: 'memory pressure')
|
|
if action == 'uncertain_cleanup':
|
|
deadline = time.monotonic() + 8
|
|
while not worker._errors and time.monotonic() < deadline:
|
|
time.sleep(.02)
|
|
assert worker._errors
|
|
assert worker.store.get(job['id'])['state'] == 'running'
|
|
assert worker.store.active_gpu_uuids() == set(UUIDS)
|
|
return
|
|
deadline = time.monotonic() + 8
|
|
while worker.store.running() and time.monotonic() < deadline:
|
|
time.sleep(.02)
|
|
assert not group_members(pgid)
|
|
assert not worker.store.active_gpu_uuids()
|
|
assert worker.store.get(job['id'])['state'] == ('cancelled' if action=='cancel' else 'queued')
|
|
|
|
|
|
@pytest.mark.skipif(sys.platform != 'linux', reason='requires Linux flock and /proc')
|
|
def test_orphan_member_blocks_startup(tmp_path):
|
|
worker = Worker(Settings(tmp_path/'app',tmp_path),gpu_policy=None)
|
|
with sqlite3.connect(worker.store.path) as db:
|
|
db.execute("insert into gpu_lease_members values ('GPU-A','orphan',1,1)")
|
|
with pytest.raises(UnsafeRecovery):
|
|
with worker:
|
|
pass
|
|
assert worker.store.active_gpu_uuids() == {'GPU-A'}
|
|
|
|
@pytest.mark.parametrize("blocked", [True,False])
|
|
def test_run_once_dispatch_limits(tmp_path,monkeypatch,blocked):
|
|
worker = Worker(Settings(tmp_path/'app',tmp_path,max_gpu_jobs=1),gpu_policy=None)
|
|
worker._lock_fd = -1
|
|
queued(worker.store)
|
|
worker.store.claim_next(gpu_uuid=UUIDS[0])
|
|
job = queued(worker.store)
|
|
monkeypatch.setattr(worker, '_execute', lambda *args: True)
|
|
if blocked:
|
|
worker._errors.append(UnsafeRecovery("rank unresolved"))
|
|
with pytest.raises(UnsafeRecovery):
|
|
worker.run_once()
|
|
else:
|
|
assert not worker.run_once()
|
|
assert worker.store.get(job['id'])['attempt_count']==0
|
|
|
|
|
|
def test_scheduler_publishes_rank1(tmp_path):
|
|
from llm_services.remote_bridge import _scheduler
|
|
worker = Worker(Settings(tmp_path/'app',tmp_path),gpu_policy=None)
|
|
queued(worker.store)
|
|
job = worker.store.claim_next(gpu_uuids=UUIDS)
|
|
members = [dict(uuid=u,index=i) for i,u in enumerate(UUIDS)]
|
|
worker._publish_scheduler('running',job=job,lease=dict(members[0],members=members))
|
|
assert _scheduler(worker.settings)['active_jobs'][0]['members']==members
|
|
|
|
|
|
@pytest.mark.parametrize("maximum,current,inactive,expected", [
|
|
(32<<30,17<<30,1<<30,None), (32<<30,(17<<30)+1,1<<30,"pressure"),
|
|
("max",0,0,"unavailable"), (0,0,0,"unavailable"), (32<<30,-1,0,"unavailable"),
|
|
(32<<30,1,2,"unavailable"), (32<<30,0,None,"unavailable"),
|
|
])
|
|
def test_running_pressure(tmp_path,maximum,current,inactive,expected):
|
|
from llm_services.resources import MemoryAdmission
|
|
from types import SimpleNamespace
|
|
for name, value in [('memory.max',maximum),('memory.current',current)]:
|
|
(tmp_path/name).write_text(str(value))
|
|
if inactive is not None:
|
|
(tmp_path/'memory.stat').write_text(f'inactive_file {inactive}')
|
|
monitor = MemoryAdmission(SimpleNamespace(memory_headroom_gib=8),cgroup=tmp_path)
|
|
result = monitor.running_pressure()
|
|
assert (result is None) if expected is None else expected in result
|