174 lines
9.7 KiB
Python
174 lines
9.7 KiB
Python
from datetime import datetime
|
|
import pytest
|
|
|
|
from llm_services.store import Store, IdempotencyConflict
|
|
from llm_services.scheduling import eligibility
|
|
import sys
|
|
|
|
|
|
def epoch(value):
|
|
return datetime.fromisoformat(value).timestamp()
|
|
|
|
|
|
def policy(mode):
|
|
return {"execution_mode": mode, "principal_id": "owner-1", "policy_version": "night-v1"}
|
|
|
|
|
|
def test_window_is_half_open_and_current_execution_is_not_a_deadline():
|
|
assert not eligibility("batch", epoch("2026-11-10T20:59:59+08:00"))["eligible"]
|
|
assert eligibility("batch", epoch("2026-11-10T21:00:00+08:00"))["eligible"]
|
|
assert eligibility("batch", epoch("2026-11-11T07:59:59+08:00"))["eligible"]
|
|
result = eligibility("batch", epoch("2026-11-11T08:00:00+08:00"))
|
|
assert not result["eligible"] and result["reason"] == "waiting_batch_window"
|
|
assert result["next_eligible_at"] == epoch("2026-11-11T21:00:00+08:00")
|
|
assert eligibility("interactive", epoch("2026-11-11T08:00:00+08:00"))["eligible"]
|
|
|
|
|
|
def test_daytime_batch_head_does_not_block_interactive_and_queue_survives_restart(tmp_path):
|
|
store = Store(tmp_path / "jobs.sqlite3")
|
|
batch = store.submit("image.generate", {"prompt": "batch"}, {}, scheduling=policy("batch"))
|
|
interactive = store.submit("image.generate", {"prompt": "interactive"}, {}, scheduling=policy("interactive"))
|
|
daytime = epoch("2026-11-11T08:00:00+08:00")
|
|
assert store.peek_next(now=daytime)["id"] == interactive["id"]
|
|
claimed = store.claim_next(now=daytime)
|
|
assert claimed["id"] == interactive["id"]
|
|
store.finish(claimed["id"], "succeeded", result={"outputs": []})
|
|
assert store.claim_next(now=daytime) is None
|
|
reopened = Store(store.path)
|
|
assert reopened.get(batch["id"])["state"] == "queued"
|
|
assert reopened.get(batch["id"])["attempt_count"] == 0
|
|
assert reopened.claim_next(now=epoch("2026-11-11T21:00:00+08:00"))["id"] == batch["id"]
|
|
|
|
|
|
def test_legacy_hash_replays_and_mode_is_in_new_immutable_hash(tmp_path):
|
|
store = Store(tmp_path / "jobs.sqlite3")
|
|
old = store.submit("image.generate", {"prompt": "x"}, {}, idempotency_key="legacy")
|
|
assert Store(store.path).submit("image.generate", {"prompt": "x"}, {}, idempotency_key="legacy")["id"] == old["id"]
|
|
new = store.submit("image.generate", {"prompt": "x"}, {}, idempotency_key="v2", scheduling=policy("batch"))
|
|
assert store.submit("image.generate", {"prompt": "x"}, {}, idempotency_key="v2", scheduling=policy("batch"))["id"] == new["id"]
|
|
with pytest.raises(IdempotencyConflict):
|
|
store.submit("image.generate", {"prompt": "x"}, {}, idempotency_key="v2", scheduling=policy("interactive"))
|
|
|
|
|
|
def test_manual_pause_drains_running_and_control_command_is_idempotent(tmp_path):
|
|
store = Store(tmp_path / "jobs.sqlite3")
|
|
job = store.submit("image.generate", {"prompt": "x"}, {}, scheduling=policy("batch"))
|
|
store.claim_next(now=epoch("2026-11-11T07:59:59+08:00"))
|
|
paused = store.control(job["id"], "pause", command_id="pause-1")
|
|
assert paused["state"] == "running" and paused["admission_paused"]
|
|
store.finish(job["id"], "succeeded", result={"outputs": []})
|
|
assert store.get(job["id"])["state"] == "succeeded"
|
|
queued = store.submit("image.generate", {"prompt": "next"}, {}, scheduling=policy("batch"))
|
|
store.control(queued["id"], "pause", command_id="p")
|
|
assert store.claim_next(now=epoch("2026-11-11T21:00:00+08:00")) is None
|
|
store.control(queued["id"], "run", command_id="r")
|
|
store.control(queued["id"], "pause", command_id="p") # Old retry cannot undo a newer resume.
|
|
assert store.claim_next(now=epoch("2026-11-11T21:00:00+08:00"))["id"] == queued["id"]
|
|
|
|
|
|
def test_crossing_window_before_spawn_defers_without_failure_or_preemption(tmp_path):
|
|
store = Store(tmp_path / "jobs.sqlite3")
|
|
job = store.submit("image.generate", {"prompt": "x"}, {}, scheduling=policy("batch"))
|
|
claim = store.claim_next(now=epoch("2026-11-11T07:59:59+08:00"))
|
|
deferred = store.defer_unlaunched(job["id"], claim["attempt_count"], "waiting_batch_window")
|
|
assert deferred["state"] == "queued" and deferred["preemptions"] == 0
|
|
assert store.claim_next(now=epoch("2026-11-11T08:00:00+08:00")) is None
|
|
|
|
|
|
def test_clock_rollback_cannot_reopen_closed_window_after_restart(tmp_path):
|
|
store = Store(tmp_path / "jobs.sqlite3")
|
|
job = store.submit("image.generate", {"prompt": "batch"}, {}, scheduling=policy("batch"))
|
|
assert store.peek_next(now=epoch("2026-11-11T08:00:01+08:00")) is None
|
|
store = Store(store.path)
|
|
assert store.claim_next(now=epoch("2026-11-11T07:55:00+08:00")) is None
|
|
assert store.get(job['id'])['attempt_count'] == 0
|
|
assert store.waiting_summary(now=epoch("2026-11-11T07:55:00+08:00"))['reason'] == 'clock_rollback'
|
|
assert store.claim_next(now=epoch("2026-11-11T21:00:00+08:00"))['id'] == job['id']
|
|
|
|
|
|
def test_global_fifo_replaces_mode_and_batch_round_robin(tmp_path):
|
|
store = Store(tmp_path / 'jobs.sqlite3')
|
|
now=epoch('2026-11-11T01:00:00+08:00')
|
|
for index in range(8):
|
|
store.submit('image.generate', {'prompt':str(index)}, {}, scheduling=policy('interactive'))
|
|
a=store.submit('image.generate', {'prompt':'a1'}, {}, scheduling={**policy('batch'),'batch_id':'a'})
|
|
a2=store.submit('image.generate', {'prompt':'a2'}, {}, scheduling={**policy('batch'),'batch_id':'a'})
|
|
b=store.submit('image.generate', {'prompt':'b1'}, {}, scheduling={**policy('batch'),'batch_id':'b'})
|
|
selected=[]
|
|
for _ in range(10):
|
|
store=Store(store.path)
|
|
current=store.claim_next(now=now)
|
|
if current['execution_mode']=='batch':selected.append(current['id'])
|
|
store.finish(current['id'],'succeeded',result={})
|
|
assert selected==[a['id'],a2['id']]
|
|
|
|
|
|
@pytest.mark.parametrize('key,value',[('clock_max_seen','NaN'),('clock_max_seen','not-a-clock'),('closed_window_through','broken')])
|
|
def test_bad_clock_state_holds_batch_without_blocking_interactive(tmp_path,key,value):
|
|
store=Store(tmp_path/'jobs.sqlite3')
|
|
batch=store.submit('image.generate',{'prompt':'batch'},{},scheduling=policy('batch'))
|
|
interactive=store.submit('image.generate',{'prompt':'interactive'},{},scheduling=policy('interactive'))
|
|
with store._connection() as connection:store._set_state(connection,key,value)
|
|
now=epoch('2026-11-11T21:00:00+08:00')
|
|
assert store.claim_next(now=now)['id']==interactive['id']
|
|
assert store.waiting_summary(now=now)['reason']=='clock_state_invalid'
|
|
assert store.get(batch['id'])['attempt_count']==0
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process/flock integration')
|
|
def test_running_batch_finishes_after_close_and_next_batch_waits(tmp_path, monkeypatch):
|
|
from llm_services.store import Settings, initialize_store
|
|
from llm_services.worker import Worker
|
|
settings = Settings(tmp_path / 'app', tmp_path, runner_python=sys.executable, poll_seconds=.01)
|
|
store = initialize_store(settings)
|
|
first = store.submit('image.generate', {'prompt':'current'}, {}, scheduling=policy('batch'))
|
|
second = store.submit('image.generate', {'prompt':'next'}, {}, scheduling=policy('batch'))
|
|
clock = [epoch('2026-11-11T07:59:59+08:00')]
|
|
runner = tmp_path / 'fake.py'
|
|
runner.write_text('import json,pathlib,sys,time\nr=json.loads(pathlib.Path(sys.argv[1]).read_text());time.sleep(.05)\np=pathlib.Path(r["output_dir"])/"result.txt";p.write_text("finished")\npathlib.Path(sys.argv[2]).write_text(json.dumps({"outputs":[str(p)]}))')
|
|
|
|
class ClosingWorker(Worker):
|
|
def _command(self, request_path, result_path):
|
|
return [sys.executable, str(runner), str(request_path), str(result_path)]
|
|
|
|
from llm_services import worker as worker_module
|
|
real_popen = worker_module.subprocess.Popen
|
|
def start_then_close(*args, **kwargs):
|
|
process = real_popen(*args, **kwargs)
|
|
# The process actually exists before the window closes.
|
|
clock[0] = max(clock[0], epoch('2026-11-11T08:01:00+08:00'))
|
|
return process
|
|
monkeypatch.setattr(worker_module.subprocess, 'Popen', start_then_close)
|
|
|
|
with ClosingWorker(settings, gpu_policy=None, clock=lambda: clock[0]) as worker:
|
|
assert worker.run_once()
|
|
assert store.get(first['id'])['state'] == 'succeeded'
|
|
assert not worker.run_once()
|
|
assert store.get(second['id'])['state'] == 'queued'
|
|
assert store.get(second['id'])['attempt_count'] == 0
|
|
clock[0] = epoch('2026-11-11T21:00:00+08:00')
|
|
assert worker.run_once()
|
|
assert store.get(second['id'])['state'] == 'succeeded'
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process/flock integration')
|
|
@pytest.mark.parametrize('close_kind', ['window','pause'])
|
|
def test_last_launch_gate_observes_command_preparation_changes(tmp_path, monkeypatch, close_kind):
|
|
from llm_services.store import Settings, initialize_store
|
|
from llm_services.worker import Worker
|
|
from llm_services import worker as worker_module
|
|
settings=Settings(tmp_path/'app',tmp_path,runner_python=sys.executable,poll_seconds=.01)
|
|
store=initialize_store(settings)
|
|
job=store.submit('image.generate',{'prompt':'do not start'},{},scheduling=policy('batch'))
|
|
clock=[epoch('2026-11-11T07:59:59+08:00')]
|
|
class DeferredWorker(Worker):
|
|
def _command(self,*args):
|
|
if close_kind=='window':clock[0]=epoch('2026-11-11T08:00:00+08:00')
|
|
else:store.control(job['id'],'pause',command_id='pause-during-command')
|
|
return [sys.executable,'-c','raise SystemExit("must not launch")']
|
|
def forbidden(*args,**kwargs):raise AssertionError('A deferred job spawned a process')
|
|
monkeypatch.setattr(worker_module.subprocess,'Popen',forbidden)
|
|
with DeferredWorker(settings,gpu_policy=None,clock=lambda:clock[0]) as worker:
|
|
assert worker.run_once()
|
|
assert store.get(job['id'])['state']=='queued'
|