280 lines
14 KiB
Python
280 lines
14 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import datetime
|
|
import json
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
import pytest
|
|
from llm_services.store import Store, Settings
|
|
|
|
|
|
def test_distinct_gpu_claims_fifo_and_case_insensitive_lease(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
jobs = [store.submit('image.generate', {}, {}) for _ in range(4)]
|
|
claims = [store.claim_next(gpu_uuid=f'GPU-{n}') for n in range(3)]
|
|
assert [j['id'] for j in claims] == [j['id'] for j in jobs[:3]]
|
|
assert store.claim_next(gpu_uuid='gpu-0') is None
|
|
assert store.get(jobs[3]['id'])['state'] == 'queued'
|
|
|
|
|
|
def test_concurrent_claims_unique_gpu_and_job(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
for _ in range(20): store.submit('image.generate', {}, {})
|
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
|
claims = list(pool.map(lambda n: store.claim_next(gpu_uuid=f'GPU-{n % 3}'), range(24)))
|
|
claims = [j for j in claims if j]
|
|
assert len(claims) == 3
|
|
assert len({j['id'] for j in claims}) == 3
|
|
assert len({j['gpu_uuid'].lower() for j in claims}) == 3
|
|
|
|
|
|
def test_eligible_global_fifo_across_modes_and_owners(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
jobs = [store.submit('image.generate', {}, {}, scheduling={'execution_mode': mode,
|
|
'principal_id': owner, 'policy_version': 'night-v1'}) for mode, owner in
|
|
[('batch','z'), ('interactive','z'), ('interactive','a')]]
|
|
now = datetime.fromisoformat('2026-11-11T22:00:00+08:00').timestamp()
|
|
assert [store.claim_next(gpu_uuid=f'GPU-{n}', now=now)['id'] for n in range(3)] == [j['id'] for j in jobs]
|
|
|
|
|
|
def test_stale_attempt_cannot_finalize_requeue_or_set_runner(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
j = store.submit('image.generate', {}, {})
|
|
store.claim_next(gpu_uuid='GPU-0')
|
|
store.requeue_preempted(j['id'], 'external', attempt_count=1)
|
|
store.claim_next(gpu_uuid='GPU-1')
|
|
for write in [lambda: store.finish(j['id'], 'failed', attempt_count=1),
|
|
lambda: store.requeue_preempted(j['id'], 'late', attempt_count=1),
|
|
lambda: store.set_runner(j['id'], 9, '1', 9, attempt_count=1)]:
|
|
with pytest.raises(RuntimeError): write()
|
|
assert store.get(j['id'])['state'] == 'running'
|
|
assert store.get(j['id'])['gpu_uuid'] == 'GPU-1'
|
|
|
|
|
|
def test_migration_keeps_jobs_and_blocks_old_singleton_ddl(tmp_path):
|
|
store = Store(tmp_path / 'jobs.db')
|
|
job = store.submit('image.generate', {}, {})
|
|
Store(store.path)
|
|
assert store.get(job['id'])['state'] == 'queued'
|
|
with sqlite3.connect(store.path) as db:
|
|
with pytest.raises(sqlite3.OperationalError):
|
|
db.execute("CREATE UNIQUE INDEX IF NOT EXISTS one_running_job ON jobs(state) WHERE state='running'")
|
|
|
|
|
|
def test_memory_working_set_reservations_and_shm(tmp_path):
|
|
from llm_services.resources import MemoryAdmission
|
|
cg = tmp_path / 'cg'; cg.mkdir()
|
|
(cg / 'memory.max').write_text(str(384 * 1024**3))
|
|
(cg / 'memory.current').write_text(str(250 * 1024**3))
|
|
(cg / 'memory.stat').write_text(f'inactive_file {180 * 1024**3}\n')
|
|
admission = MemoryAdmission(Settings(tmp_path/'app', tmp_path), cgroup=cg,
|
|
shm_usage=lambda: (0, 64 * 1024**3))
|
|
assert admission.check('image.generate', [88, 88]) is None
|
|
assert admission.check('image.generate', [88, 88, 88]) is not None
|
|
admission.shm_usage = lambda: (64 * 1024**3, 64 * 1024**3)
|
|
assert admission.check('audio.transcribe', []) is not None
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
|
|
def test_three_runners_overlap_fourth_waits_and_cancel_is_local(tmp_path):
|
|
from llm_services.worker import Worker
|
|
class Policy:
|
|
def describe(self): return {'eligible_gpus':[{'uuid':f'GPU-{n}', 'index':n} for n in range(3)]}
|
|
def should_yield(self, lease): return None
|
|
def environment(self, lease): return {'CUDA_VISIBLE_DEVICES':lease['uuid']}
|
|
class TestWorker(Worker):
|
|
def _command(self, request, result):
|
|
return [sys.executable, '-c', 'import time; time.sleep(30)']
|
|
settings = Settings(tmp_path/'app', tmp_path, poll_seconds=.02, terminate_grace_seconds=.1)
|
|
w = TestWorker(settings, gpu_policy=Policy())
|
|
w.memory_admission = type('Memory', (), {'check':lambda *args: None})()
|
|
jobs = [w.store.submit('image.generate', {}, {}) for _ in range(4)]
|
|
with w:
|
|
try:
|
|
w.dispatch_once()
|
|
assert [j['id'] for j in w.store.running()] == [j['id'] for j in jobs[:3]]
|
|
assert w.store.get(jobs[3]['id'])['state'] == 'queued'
|
|
w.store.cancel(jobs[1]['id'])
|
|
deadline = time.monotonic() + 5
|
|
while w.store.get(jobs[1]['id'])['state'] == 'running' and time.monotonic() < deadline:
|
|
time.sleep(.02)
|
|
w.dispatch_once()
|
|
assert {j['id'] for j in w.store.running()} == {jobs[n]['id'] for n in (0,2,3)}
|
|
status = json.loads((settings.state_dir/'gpu-scheduler.json').read_text())
|
|
assert status['schema_version'] == 2 and status['running_count'] == 3
|
|
finally:
|
|
w.shutdown()
|
|
assert not w.store.running()
|
|
assert not list(settings.runner_markers.glob('*.json'))
|
|
|
|
def test_memory_shortage_keeps_fifo_head_and_no_attempt(tmp_path):
|
|
from llm_services.worker import Worker
|
|
class Policy:
|
|
def describe(self): return {'eligible_gpus':[{'uuid':'GPU-0', 'index':0}]}
|
|
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=Policy())
|
|
w._lock_fd = -1
|
|
w.memory_admission = type('Memory', (), {'check':lambda *args: 'memory shortage'})()
|
|
jobs = [w.store.submit(kind, {}, {}) for kind in ('image.generate','audio.transcribe')]
|
|
w.dispatch_once()
|
|
assert all(w.store.get(j['id'])['attempt_count'] == 0 for j in jobs)
|
|
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
|
|
assert status['state'] == 'waiting' and status['reason'] == 'memory shortage'
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
|
|
def test_per_attempt_markers_prevent_unsafe_recovery(tmp_path):
|
|
from llm_services.worker import Worker, UnsafeRecovery
|
|
settings = Settings(tmp_path/'app', tmp_path)
|
|
w = Worker(settings, gpu_policy=None)
|
|
(settings.runner_markers/'first-1.json').write_text('{}')
|
|
(settings.runner_markers/'second-2.json').write_text('{}')
|
|
with pytest.raises(UnsafeRecovery):
|
|
with w: pass
|
|
assert len(settings.active_markers()) == 2
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
|
|
def test_external_user_preempts_only_leased_gpu(tmp_path):
|
|
from llm_services.worker import Worker
|
|
class Policy:
|
|
external = set()
|
|
def describe(self): return {'eligible_gpus':[{'uuid':f'GPU-{n}', 'index':n}
|
|
for n in range(3) if f'GPU-{n}' not in self.external]}
|
|
def should_yield(self, lease): return 'external user' if lease['uuid'] in self.external else None
|
|
def environment(self, lease): return {}
|
|
class TestWorker(Worker):
|
|
def _command(self, request, result):
|
|
return [sys.executable, '-c', 'import time; time.sleep(30)']
|
|
policy = Policy()
|
|
settings = Settings(tmp_path/'app', tmp_path, poll_seconds=.02, terminate_grace_seconds=.1)
|
|
w = TestWorker(settings, gpu_policy=policy)
|
|
w.memory_admission = type('Memory', (), {'check':lambda *args: None})()
|
|
jobs = [w.store.submit('image.generate', {}, {}) for _ in range(3)]
|
|
with w:
|
|
w.dispatch_once()
|
|
peers = {j['id']:j['runner_pid'] for j in w.store.running() if j['gpu_uuid'] != 'GPU-1'}
|
|
policy.external.add('GPU-1')
|
|
deadline = time.monotonic()+5
|
|
while w.store.get(jobs[1]['id'])['state'] == 'running' and time.monotonic()<deadline:
|
|
time.sleep(.02)
|
|
assert w.store.get(jobs[1]['id'])['state'] == 'queued'
|
|
assert w.store.get(jobs[1]['id'])['preemptions'] == 1
|
|
assert {j['id']:j['runner_pid'] for j in w.store.running()} == peers
|
|
w.dispatch_once()
|
|
assert w.store.get(jobs[1]['id'])['attempt_count'] == 1
|
|
assert not w.store.running()
|
|
|
|
|
|
def test_scheduler_heartbeat_refreshes_unchanged_state(tmp_path, monkeypatch):
|
|
from llm_services.worker import Worker
|
|
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
|
|
w._publish_scheduler('idle')
|
|
status_path = w.settings.state_dir/'gpu-scheduler.json'
|
|
first = json.loads(status_path.read_text())['updated_at']
|
|
w._scheduler_written_at -= 2
|
|
w._publish_scheduler('idle')
|
|
assert json.loads(status_path.read_text())['updated_at'] > first
|
|
|
|
|
|
@pytest.mark.parametrize('values', [{'max_gpu_jobs':5}, {'max_gpu_jobs':True},
|
|
{'cpu_threads_per_job':0}, {'memory_headroom_gib':float('nan')}, {'memory_estimates_gib':{}}])
|
|
def test_settings_reject_unsafe_limits(tmp_path, values):
|
|
with pytest.raises(ValueError): Settings(tmp_path/'app', tmp_path, **values)
|
|
|
|
def test_unfenced_legacy_write_cannot_touch_a_retried_execution(tmp_path):
|
|
store = Store(tmp_path/'jobs.db')
|
|
job = store.submit('image.generate', {}, {})
|
|
store.claim_next(gpu_uuid='GPU-0')
|
|
store.requeue_preempted(job['id'], 'external', attempt_count=1)
|
|
store.claim_next(gpu_uuid='GPU-0')
|
|
for operation in (lambda: store.set_runner(job['id'], 1, '1', 1),
|
|
lambda: store.requeue_preempted(job['id'], 'unfenced'),
|
|
lambda: store.finish(job['id'], 'failed')):
|
|
with pytest.raises(RuntimeError): operation()
|
|
assert store.get(job['id'])['state'] == 'running'
|
|
|
|
def test_old_monitor_status_cannot_overwrite_reclaimed_attempt(tmp_path, monkeypatch):
|
|
from llm_services.worker import Worker
|
|
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
|
|
w._lock_fd = -1
|
|
w.store.submit('image.generate', {}, {})
|
|
job = w.store.claim_next(gpu_uuid='GPU-0')
|
|
monkeypatch.setattr(w, '_yield_reason', lambda lease: 'external')
|
|
original = w.store.requeue_preempted
|
|
def reclaim(*args, **kwargs):
|
|
result = original(*args, **kwargs)
|
|
next_job = w.store.claim_next(gpu_uuid='GPU-1')
|
|
w._publish_scheduler('running', job=next_job, lease={'uuid':'GPU-1','index':1})
|
|
return result
|
|
monkeypatch.setattr(w.store, 'requeue_preempted', reclaim)
|
|
w._execute(job, {'uuid':'GPU-0','index':0})
|
|
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
|
|
assert len(status['active_jobs']) == 1
|
|
assert status['active_jobs'][0]['attempt_count'] == 2
|
|
assert status['active_jobs'][0]['gpu_index'] == 1
|
|
|
|
def test_memory_diagnostics_include_cgroup_events_and_shm(tmp_path):
|
|
from llm_services.resources import MemoryAdmission
|
|
for name, value in {'memory.current':str(10*1024**3), 'memory.max':str(384*1024**3),
|
|
'memory.stat':'inactive_file 0\n', 'memory.events':'oom 2\noom_kill 1\n'}.items():
|
|
(tmp_path/name).write_text(value)
|
|
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
|
|
shm_usage=lambda:(123,1024**3))
|
|
assert memory.check('image.generate',[]) is None
|
|
assert memory.last_sample['memory_events']['oom_kill'] == 1
|
|
assert memory.last_sample['shm_used_bytes'] == 123
|
|
assert memory.last_sample['memory_max_bytes'] == 384*1024**3
|
|
|
|
def test_memory_rechecks_growth_outside_runner_reservations(tmp_path):
|
|
from llm_services.resources import MemoryAdmission
|
|
gib = 1024**3
|
|
(tmp_path/'memory.max').write_text(str(384*gib))
|
|
(tmp_path/'memory.current').write_text(str(20*gib))
|
|
(tmp_path/'memory.stat').write_text('inactive_file 0\n')
|
|
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
|
|
shm_usage=lambda:(0,64*gib))
|
|
assert memory.check('image.generate', []) is None
|
|
# Two models currently use only 20 GiB each, while an unrelated local
|
|
# workload grows to 220 GiB. Their remaining reserved allocations still
|
|
# need capacity: the cgroup's observed 260 GiB cannot stand in for them.
|
|
(tmp_path/'memory.current').write_text(str(260*gib))
|
|
assert memory.check('image.generate', [88,88]) is not None
|
|
|
|
|
|
def test_conservative_memory_still_admits_three_expected_wan_jobs(tmp_path):
|
|
from llm_services.resources import MemoryAdmission
|
|
gib = 1024**3
|
|
(tmp_path/'memory.max').write_text(str(384*gib))
|
|
(tmp_path/'memory.stat').write_text('inactive_file 0\n')
|
|
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
|
|
shm_usage=lambda:(0,64*gib))
|
|
for running in range(3):
|
|
(tmp_path/'memory.current').write_text(str((1+37*running)*gib))
|
|
assert memory.check('video.generate', [64]*running) is None
|
|
|
|
def test_scheduler_preserves_blocked_card_alongside_running_peer(tmp_path):
|
|
from llm_services.worker import Worker
|
|
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
|
|
for _ in range(2): w.store.submit('image.generate', {}, {})
|
|
blocked = w.store.claim_next(gpu_uuid='GPU-0')
|
|
peer = w.store.claim_next(gpu_uuid='GPU-1')
|
|
peer['stage'] = 'executing'
|
|
w._publish_scheduler('running', job=peer, lease={'uuid':'GPU-1','index':1})
|
|
w._publish_scheduler('blocked', job=blocked, lease={'uuid':'GPU-0','index':0},
|
|
reason='Cannot prove complete runner exit; operator recovery required')
|
|
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
|
|
entries = {entry['gpu_index']:entry for entry in status['active_jobs']}
|
|
assert status['state'] == 'blocked'
|
|
assert entries[0]['state'] == 'blocked'
|
|
assert 'operator recovery' in entries[0]['reason']
|
|
assert entries[1]['state'] == 'running'
|
|
|
|
|
|
def test_scheduler_marks_unspawned_claim_launching(tmp_path):
|
|
from llm_services.worker import Worker
|
|
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
|
|
w.store.submit('image.generate', {}, {})
|
|
job = w.store.claim_next(gpu_uuid='GPU-0')
|
|
w._publish_scheduler('running', job=job, lease={'uuid':'GPU-0','index':0})
|
|
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
|
|
assert status['active_jobs'][0]['state'] == 'launching'
|