2026-11-11 00:36:30 +08:00
|
|
|
"""The operator file controls GPU admission, including already persisted jobs."""
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
import json
|
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
from llm_services.store import Store, Settings, initialize_store
|
|
|
|
|
from llm_services.scheduling import policy_status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def epoch(value):
|
|
|
|
|
return datetime.fromisoformat(value).timestamp()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_policy(path, enabled):
|
|
|
|
|
path.write_text(json.dumps({"schema_version": 1, "batch_window_enabled": enabled,
|
|
|
|
|
"workflow_max_shots": 120}), encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def submit(store, mode="batch"):
|
|
|
|
|
return store.submit("image.generate", {"prompt": "operator policy"}, {}, scheduling={
|
|
|
|
|
"execution_mode": mode, "principal_id": "owner", "policy_version": "night-v1"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_hot_config_releases_same_gpu_queue_id_then_blocks_next_phase(tmp_path):
|
|
|
|
|
path = tmp_path / "runtime-policy.json"
|
|
|
|
|
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
|
|
|
|
job = submit(store)
|
|
|
|
|
noon = epoch("2026-11-11T12:00:00+08:00")
|
|
|
|
|
assert store.claim_next(now=noon) is None
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
assert store.claim_next(now=noon)["id"] == job["id"]
|
|
|
|
|
assert store.admission(job["id"], now=noon)["eligible"]
|
|
|
|
|
write_policy(path, True)
|
|
|
|
|
assert not store.admission(job["id"], now=noon)["eligible"]
|
|
|
|
|
# Re-enabling does not cancel an already admitted runner.
|
|
|
|
|
store.finish(job["id"], "succeeded", result={"outputs": []})
|
|
|
|
|
next_job = submit(store)
|
|
|
|
|
assert store.claim_next(now=noon) is None
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
store.control(next_job["id"], "pause", command_id="manual-pause")
|
|
|
|
|
assert store.claim_next(now=noon) is None
|
|
|
|
|
store.control(next_job["id"], "run", command_id="manual-resume")
|
|
|
|
|
assert store.claim_next(now=noon)["id"] == next_job["id"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_disabled_policy_does_not_erase_clock_corruption(tmp_path):
|
|
|
|
|
path = tmp_path / "runtime-policy.json"
|
|
|
|
|
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
|
|
|
|
submit(store)
|
|
|
|
|
with store._connection() as connection:
|
|
|
|
|
store._set_state(connection, "clock_max_seen", "NaN")
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
noon = epoch("2026-11-11T12:00:00+08:00")
|
|
|
|
|
assert store.peek_next(now=noon)
|
|
|
|
|
with store._connection() as connection:
|
|
|
|
|
assert store._state(connection, "clock_max_seen") == "NaN"
|
|
|
|
|
write_policy(path, True)
|
|
|
|
|
assert store.peek_next(now=noon) is None
|
|
|
|
|
assert store.waiting_summary(now=noon)["reason"] == "clock_state_invalid"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("content", ["{corrupt", '{"schema_version":1,"batch_window_enabled":"false"}',
|
|
|
|
|
'{"schema_version":true,"batch_window_enabled":false}',
|
|
|
|
|
'{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":1001}'])
|
2026-11-26 21:06:27 +08:00
|
|
|
def test_invalid_policy_blocks_both_modes_even_at_night(tmp_path, content):
|
2026-11-11 00:36:30 +08:00
|
|
|
path = tmp_path / "runtime-policy.json"
|
|
|
|
|
path.write_text(content, encoding="utf-8")
|
|
|
|
|
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
|
|
|
|
submit(store)
|
|
|
|
|
now = epoch("2026-11-11T22:00:00+08:00")
|
|
|
|
|
assert store.peek_next(now=now) is None
|
|
|
|
|
interactive = submit(store, "interactive")
|
2026-11-26 21:06:27 +08:00
|
|
|
assert store.claim_next(now=now) is None
|
|
|
|
|
assert store.admission(interactive['id'], now=now)['reason'] == 'runtime_policy_invalid'
|
2026-11-11 00:36:30 +08:00
|
|
|
info = policy_status(now, policy_file=path)
|
|
|
|
|
assert not info["batch_open"] and info["configuration_error"] == "runtime_policy_invalid"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_settings_and_status_use_the_same_policy_path(tmp_path, monkeypatch):
|
|
|
|
|
path = tmp_path / "config.json"
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
monkeypatch.setenv("APP_ROOT", str(tmp_path / "app"))
|
|
|
|
|
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
|
|
|
|
|
monkeypatch.setenv("RUNTIME_POLICY_FILE", str(path))
|
|
|
|
|
settings = Settings.from_env()
|
|
|
|
|
assert settings.runtime_policy_file == path
|
|
|
|
|
store = initialize_store(settings)
|
|
|
|
|
noon = epoch("2026-11-11T12:00:00+08:00")
|
|
|
|
|
job = submit(store)
|
|
|
|
|
assert store.peek_next(now=noon)["id"] == job["id"]
|
|
|
|
|
info = policy_status(noon, policy_file=path)
|
|
|
|
|
assert info["batch_window_enabled"] is False and info["batch_open"]
|
|
|
|
|
assert info["next_batch_at"] is None and info["configuration_error"] is None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_api_reports_hot_policy_but_rejects_client_window_override(tmp_path):
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
from llm_services.api import create_app
|
|
|
|
|
settings = Settings(tmp_path / "app", tmp_path)
|
|
|
|
|
settings.key_file.parent.mkdir(parents=True)
|
|
|
|
|
settings.key_file.write_text("test-only-runtime-policy-key")
|
|
|
|
|
write_policy(settings.runtime_policy_file, False)
|
|
|
|
|
headers = {"Authorization": "Bearer test-only-runtime-policy-key"}
|
|
|
|
|
with TestClient(create_app(settings)) as client:
|
|
|
|
|
body = client.get("/capabilities", headers=headers).json()
|
|
|
|
|
assert body["execution_policy"]["batch_window_enabled"] is False
|
|
|
|
|
write_policy(settings.runtime_policy_file, True)
|
|
|
|
|
body = client.get("/capabilities", headers=headers).json()
|
|
|
|
|
assert body["execution_policy"]["batch_window_enabled"] is True
|
|
|
|
|
response = client.post("/jobs", headers=headers, json={"task_type": "image.generate",
|
|
|
|
|
"input": {"prompt": "cannot bypass"}, "scheduling": {
|
|
|
|
|
"execution_mode": "batch", "principal_id": "owner",
|
|
|
|
|
"batch_window_enabled": False}})
|
|
|
|
|
assert response.status_code == 422
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="Linux process/flock integration")
|
|
|
|
|
def test_running_worker_finishes_after_policy_reenabled_then_next_job_waits(tmp_path, monkeypatch):
|
|
|
|
|
from llm_services.worker import Worker
|
|
|
|
|
from llm_services import worker as worker_module
|
|
|
|
|
path = tmp_path / "runtime-policy.json"
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
settings = Settings(tmp_path / "app", tmp_path, runner_python=sys.executable,
|
|
|
|
|
poll_seconds=.01, runtime_policy_file=path)
|
|
|
|
|
store = initialize_store(settings)
|
|
|
|
|
first, second = submit(store), submit(store)
|
|
|
|
|
noon = epoch("2026-11-11T12:00:00+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 PolicyWorker(Worker):
|
|
|
|
|
def _command(self, request_path, result_path):
|
|
|
|
|
return [sys.executable, str(runner), str(request_path), str(result_path)]
|
|
|
|
|
|
|
|
|
|
real_popen = worker_module.subprocess.Popen
|
|
|
|
|
|
|
|
|
|
def launch_then_enable(*args, **kwargs):
|
|
|
|
|
process = real_popen(*args, **kwargs)
|
|
|
|
|
write_policy(path, True)
|
|
|
|
|
return process
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(worker_module.subprocess, "Popen", launch_then_enable)
|
|
|
|
|
with PolicyWorker(settings, gpu_policy=None, clock=lambda: noon) 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="Linux process/flock integration")
|
|
|
|
|
def test_final_launch_gate_hot_reads_policy_after_command_preparation(tmp_path, monkeypatch):
|
|
|
|
|
from llm_services.worker import Worker
|
|
|
|
|
from llm_services import worker as worker_module
|
|
|
|
|
path = tmp_path / "runtime-policy.json"
|
|
|
|
|
write_policy(path, False)
|
|
|
|
|
settings = Settings(tmp_path / "app", tmp_path, runner_python=sys.executable,
|
|
|
|
|
poll_seconds=.01, runtime_policy_file=path)
|
|
|
|
|
store = initialize_store(settings)
|
|
|
|
|
job = submit(store)
|
|
|
|
|
|
|
|
|
|
class DeferredWorker(Worker):
|
|
|
|
|
def _command(self, *args):
|
|
|
|
|
write_policy(path, True)
|
|
|
|
|
return [sys.executable, "-c", "raise SystemExit('must not launch')"]
|
|
|
|
|
|
|
|
|
|
def forbidden(*args, **kwargs):
|
|
|
|
|
raise AssertionError("A daytime batch spawned after production policy was enabled")
|
|
|
|
|
|
|
|
|
|
monkeypatch.setattr(worker_module.subprocess, "Popen", forbidden)
|
|
|
|
|
with DeferredWorker(settings, gpu_policy=None,
|
|
|
|
|
clock=lambda: epoch("2026-11-11T12:00:00+08:00")) as worker:
|
|
|
|
|
assert worker.run_once()
|
|
|
|
|
assert store.get(job["id"])["state"] == "queued"
|