cmvr-visual/backend/tests/test_environment_gpu_window.py

301 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""环境开关只能来自可信后端;两种队列共享阶段边界准入。"""
import asyncio
import copy
from datetime import datetime
import json
from types import SimpleNamespace
import pytest
from app.core.config import Settings
from app.core.runtime_policy import read_runtime_policy
from app.services.orchestration.resource_policy import admits, execution_policy
from test_jobs import submit
def configured(tmp_path, mode="test", **kwargs):
database_url = (
"mysql+aiomysql://u:p@localhost/db"
if mode == "production"
else "sqlite+aiosqlite:///:memory:"
)
return Settings(mode=mode, database_url=database_url, workspace_root=tmp_path, **kwargs)
@pytest.mark.parametrize(
"mode, expected", [("production", True), ("preview", False), ("test", False)]
)
def test_environment_default_overrides_legacy_file_but_keeps_shot_limit(tmp_path, mode, expected):
path = tmp_path / "policy.json"
path.write_text(
json.dumps(
{"schema_version": 1, "batch_window_enabled": not expected, "workflow_max_shots": 240}
)
)
settings = configured(tmp_path, mode, runtime_policy_file=path)
assert getattr(settings, "gpu_window_enabled", "missing") is expected
assert read_runtime_policy(settings) == {
"batch_window_enabled": expected,
"workflow_max_shots": 240,
"configuration_error": None,
}
@pytest.mark.parametrize("value", ["nope", "", "2", "null"])
def test_environment_rejects_invalid_window_boolean(tmp_path, monkeypatch, value):
monkeypatch.setenv("CMVR_MODE", "test")
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
monkeypatch.setenv("GPU_WINDOW_ENABLED", value)
with pytest.raises(ValueError, match="GPU_WINDOW_ENABLED"):
Settings.from_env()
@pytest.mark.parametrize(
"value, expected", [("true", True), ("FALSE", False), ("1", True), ("off", False)]
)
def test_environment_parses_explicit_window_boolean(tmp_path, monkeypatch, value, expected):
monkeypatch.setenv("CMVR_MODE", "test")
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
monkeypatch.setenv("GPU_WINDOW_ENABLED", value)
assert getattr(Settings.from_env(), "gpu_window_enabled", None) is expected
@pytest.mark.parametrize("mode", ["interactive", "batch"])
@pytest.mark.parametrize(
"stamp, expected",
[("20:59:59", False), ("21:00:00", True), ("07:59:59", True), ("08:00:00", False)],
)
def test_both_modes_obey_shanghai_window_and_settings(tmp_path, mode, stamp, expected):
settings = SimpleNamespace(runtime_policy_file=None, gpu_window_enabled=True)
job = SimpleNamespace(
execution_mode=mode, desired_state="run", cancel_requested=False, hold_reasons=[]
)
now = datetime.fromisoformat(f"2026-11-26T{stamp}+08:00")
assert admits(job, now, settings=settings) is expected
settings.gpu_window_enabled = False
assert admits(job, now, settings=settings) is True
assert execution_policy(now, settings=settings)["batch_open"] is True
def test_environment_override_retains_remote_and_file_configuration_errors(tmp_path):
path = tmp_path / "policy.json"
path.write_text('{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":1001}')
settings = SimpleNamespace(runtime_policy_file=path, gpu_window_enabled=False)
assert read_runtime_policy(settings)["configuration_error"] == "runtime_policy_invalid"
settings.inference_remote_files = True
settings._remote_policy_error = "runtime_policy_unavailable"
assert read_runtime_policy(settings)["configuration_error"] == "runtime_policy_unavailable"
async def capable(system, feature=True):
async def capabilities():
return {
"protocol_version": 2,
"admission_policy": True,
"features": {"project_gpu_window": feature},
}
system.provider.upstream_capabilities = capabilities
def set_open(monkeypatch, system, opened=True):
from app.services.orchestration import resource_policy
original = resource_policy.execution_policy
def fixed(now=None, *, settings=None):
result = original(datetime.fromisoformat("2026-11-26T22:00:00+08:00"), settings=settings)
result["batch_open"] = opened or not result["batch_window_enabled"]
return result
monkeypatch.setattr(resource_policy, "execution_policy", fixed)
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_same_upstream_receives_environment_snapshots(system, monkeypatch, mode):
await capable(system)
set_open(monkeypatch, system)
coordinator = system.app.state.coordinator
for enabled in (True, False):
system.settings.gpu_window_enabled = enabled
job = (await submit(system, execution_mode=mode))[0]
await coordinator.run_once(force=True)
if coordinator._preparing:
await asyncio.gather(*coordinator._preparing.values())
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
assert current.upstream_id
assert current.upstream_payload["scheduling"]["gpu_window_enabled"] is enabled
assert current.upstream_payload["scheduling"]["execution_mode"] == mode
@pytest.mark.parametrize("mode", ["interactive", "batch"])
@pytest.mark.parametrize("feature", [False, "true", 1, None])
async def test_enabled_environment_waits_for_strict_upstream_feature(
system, monkeypatch, mode, feature
):
system.settings.gpu_window_enabled = True
await capable(system, feature)
set_open(monkeypatch, system)
job = (await submit(system, execution_mode=mode))[0]
coordinator = system.app.state.coordinator
await coordinator.run_once(force=True)
if coordinator._preparing:
await asyncio.gather(*coordinator._preparing.values())
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
assert not system.provider.submitted_payloads
assert "升级" in (current.sync_warning or "")
assert current.state not in {"failed", "cancelled"}
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_disabled_environment_uses_legacy_upstream_envelope(system, monkeypatch, mode):
system.settings.gpu_window_enabled = False
await capable(system, False)
set_open(monkeypatch, system)
coordinator = system.app.state.coordinator
job = (await submit(system, execution_mode=mode))[0]
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
assert current.upstream_id
assert "gpu_window_enabled" not in current.upstream_payload["scheduling"]
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_enabled_environment_preserves_unsafe_frozen_payload_and_key(
system, monkeypatch, mode
):
await capable(system, False)
set_open(monkeypatch, system)
coordinator = system.app.state.coordinator
job = (await submit(system, execution_mode=mode))[0]
await coordinator._gpu(await coordinator._job(job["id"]), prepare_only=True)
current = await coordinator._job(job["id"])
original, key = copy.deepcopy(current.upstream_payload), current.upstream_key
assert "gpu_window_enabled" not in original["scheduling"]
system.settings.gpu_window_enabled = True
await capable(system)
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
assert current.upstream_payload == original and current.upstream_key == key
assert not system.provider.submitted_payloads
assert "历史参数包需重新执行" in (current.sync_warning or "")
assert current.state == "needs_attention"
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_unsafe_frozen_queue_does_not_starve_new_safe_job(system, monkeypatch, mode):
from app.models import Job
await capable(system)
system.settings.gpu_window_enabled = True
system.settings.max_creation_commands_per_minute = 100
set_open(monkeypatch, system)
old_jobs = []
for count in (4, 4, 4, 4, 4, 4, 1):
old_jobs.extend(await submit(system, execution_mode=mode, count=count))
async with system.app.state.db.session() as session:
for info in old_jobs:
row = await session.get(Job, info["id"])
row.upstream_payload = {
"task_type": row.task_type,
"input": row.input_json,
"parameters": row.parameters,
"timeout_seconds": 3600,
"scheduling": {"execution_mode": mode},
}
await session.commit()
new = (await submit(system, execution_mode=mode))[0]
coordinator = system.app.state.coordinator
for _ in range(3):
await coordinator.run_once(force=True)
if coordinator._preparing:
await asyncio.gather(*coordinator._preparing.values())
assert (await coordinator._job(new["id"])).upstream_id
assert len(system.provider.submitted_payloads) == 1
for info in old_jobs:
assert (await coordinator._job(info["id"])).state == "needs_attention"
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_cancel_of_unconfirmed_legacy_payload_stays_visible_without_resubmission(
system, monkeypatch, mode
):
await capable(system, False)
set_open(monkeypatch, system)
coordinator = system.app.state.coordinator
info = (await submit(system, execution_mode=mode))[0]
await coordinator._gpu(await coordinator._job(info["id"]), prepare_only=True)
original = await coordinator._job(info["id"])
system.settings.gpu_window_enabled = True
# 模拟旧POST后崩溃:原包已冻结但本地既没有ID也没有失败计数。
response = await system.client.post(f"/api/jobs/{info['id']}/cancel")
assert response.status_code == 200
await coordinator.run_once(force=True)
current = await coordinator._job(info["id"])
assert current.state == "needs_attention" and current.cancel_requested
assert "取消需确认" in (current.sync_warning or "")
assert current.upstream_payload == original.upstream_payload
assert current.upstream_key == original.upstream_key
assert not system.provider.submitted_payloads
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_closed_window_blocks_fresh_cpu_gpu_and_phase_callbacks(system, monkeypatch, mode):
from app.services.orchestration.coordinator import PhaseDeferred
system.settings.gpu_window_enabled = True
await capable(system)
set_open(monkeypatch, system, False)
cpu = (
await submit(system, task_type="math.solve", input={"prompt": "2+3"}, execution_mode=mode)
)[0]
gpu = (await submit(system, execution_mode=mode))[0]
coordinator = system.app.state.coordinator
await coordinator.run_once(force=True)
assert not coordinator._preparing and not coordinator._cpu
assert not system.provider.submitted_payloads and system.provider.cpu_runs == 0
for pool in ("cpu_media", "qwen_http", "new_gpu"):
with pytest.raises(PhaseDeferred):
await coordinator._enter_phase(cpu["id"], "later", pool, nonblocking=True)
assert not coordinator._pools[pool].locked()
assert (await coordinator._job(gpu["id"])).upstream_payload is None
@pytest.mark.parametrize("mode", ["interactive", "batch"])
async def test_existing_bound_gpu_is_observed_after_window_closes(system, monkeypatch, mode):
await capable(system, False)
coordinator = system.app.state.coordinator
job = (await submit(system, execution_mode=mode))[0]
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
original = copy.deepcopy(current.upstream_payload)
system.settings.gpu_window_enabled = True
set_open(monkeypatch, system, False)
system.provider.remote[current.upstream_id].update(state="running", attempt_count=1)
await coordinator.run_once(force=True)
current = await coordinator._job(job["id"])
assert current.state == "running" and current.upstream_payload == original
assert len(system.provider.submitted_payloads) == 1
@pytest.mark.parametrize(
"field, value, status",
[
("gpu_window_enabled", False, 422),
("scheduling", {"gpu_window_enabled": False}, 422),
("parameters", {"gpu_window_enabled": False}, 400),
("input", {"prompt": "cup", "gpu_window_enabled": False}, 422),
],
)
async def test_browser_cannot_select_trusted_window_snapshot(system, field, value, status):
response = await system.client.post(
"/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, field: value}
)
assert response.status_code == status
assert not system.provider.submitted_payloads