"""Per-request environment snapshots share one queue without changing legacy hashes.""" from datetime import datetime from concurrent.futures import ThreadPoolExecutor import json import sys import threading import pytest from llm_services.scheduling import normalize_scheduling from llm_services.store import IdempotencyConflict, Settings, Store, initialize_store def epoch(value): return datetime.fromisoformat(value).timestamp() def scheduling(mode, enabled): return {'execution_mode': mode, 'principal_id': 'owner', 'gpu_window_enabled': enabled} def write_policy(path, enabled): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({'schema_version': 1, 'batch_window_enabled': enabled, 'workflow_max_shots': 120}), encoding='utf-8') def submit(store, mode, enabled): return store.submit('image.generate', {'prompt': 'test'}, {}, scheduling=scheduling(mode, enabled)) @pytest.mark.parametrize('enabled', [True, False]) def test_normalization_accepts_only_boolean_environment_snapshot(enabled): assert normalize_scheduling(scheduling('interactive', enabled)) == { 'execution_mode': 'interactive', 'principal_id': 'owner', 'policy_version': 'night-v1', 'gpu_window_enabled': enabled} @pytest.mark.parametrize('value', [None, 0, 1, 'false', 'true', [], {}]) def test_normalization_rejects_non_boolean_environment_snapshot(value): with pytest.raises(ValueError): normalize_scheduling(scheduling('batch', value)) @pytest.mark.parametrize('field', ['execution_mode', 'principal_id', 'batch_id', 'run_id', 'step_key', 'policy_version']) @pytest.mark.parametrize('value', [True, 1, [], {}]) def test_environment_snapshot_does_not_relax_identity_validation(field, value): with pytest.raises(ValueError): normalize_scheduling({**scheduling('batch', True), field: value}) def test_missing_snapshot_preserves_normalized_package_and_known_v2_hash(tmp_path): legacy = {'execution_mode': 'batch', 'principal_id': 'owner-1', 'policy_version': 'night-v1'} assert normalize_scheduling(None) is None assert normalize_scheduling(legacy) == legacy store = Store(tmp_path / 'jobs.db') job = store.submit('image.generate', {'prompt': 'x'}, {}, idempotency_key='v2', scheduling=legacy) with store._connection() as connection: row = connection.execute('SELECT request_hash,scheduling_json FROM jobs WHERE id=?', (job['id'],)).fetchone() assert row['request_hash'] == '8c3d9a18a867ac57072de4bcb152567f3fce4222b0ff1e75805180b415110fa7' assert 'gpu_window_enabled' not in json.loads(row['scheduling_json']) assert Store(store.path).submit('image.generate', {'prompt': 'x'}, {}, idempotency_key='v2', scheduling=legacy)['id'] == job['id'] with pytest.raises(IdempotencyConflict): store.submit('image.generate', {'prompt': 'x'}, {}, idempotency_key='v2', scheduling={**legacy, 'gpu_window_enabled': False}) def test_snapshot_is_immutable_idempotent_identity(tmp_path): store = Store(tmp_path / 'jobs.db') original = store.submit('image.generate', {}, {}, idempotency_key='new', scheduling=scheduling('batch', True)) assert store.submit('image.generate', {}, {}, idempotency_key='new', scheduling=scheduling('batch', True))['id'] == original['id'] with pytest.raises(IdempotencyConflict): store.submit('image.generate', {}, {}, idempotency_key='new', scheduling=scheduling('batch', False)) @pytest.mark.parametrize('mode', ['interactive', 'batch']) @pytest.mark.parametrize('legacy_enabled', [True, False]) def test_true_snapshot_controls_selection_claim_and_final_admission(tmp_path, mode, legacy_enabled): path = tmp_path / 'policy.json' write_policy(path, legacy_enabled) store = Store(tmp_path / 'jobs.db', policy_file=path) job = submit(store, mode, True) before = epoch('2026-11-11T07:59:59+08:00') close = epoch('2026-11-11T08:00:00+08:00') assert store.peek_next(now=before)['id'] == job['id'] assert store.claim_next(now=before, gpu_uuids=['GPU-A', 'GPU-B'])['id'] == job['id'] assert store.admission(job['id'], now=before)['eligible'] assert store.admission(job['id'], now=close)['reason'] == 'waiting_batch_window' assert store.waiting_summary(now=close)['queued'] == 0 store.defer_unlaunched(job['id'], 1, 'waiting_batch_window') assert not store.active_gpu_uuids() assert store.peek_next(now=close) is None assert store.claim_next(now=close) is None assert store.waiting_summary(now=close)['reason'] == 'waiting_batch_window' assert store.get(job['id'])['attempt_count'] == 1 assert store.get(job['id'])['preemptions'] == 0 assert store.claim_next(now=epoch('2026-11-11T21:00:00+08:00'))['id'] == job['id'] @pytest.mark.parametrize('production_mode', ['interactive', 'batch']) @pytest.mark.parametrize('development_mode', ['interactive', 'batch']) def test_daytime_shared_queue_skips_production_but_preserves_development_fifo_and_controls( tmp_path, production_mode, development_mode): store = Store(tmp_path / 'jobs.db') production = submit(store, production_mode, True) paused = submit(store, development_mode, False) cancelled = submit(store, development_mode, False) development = [submit(store, development_mode, False) for _ in range(2)] store.control(paused['id'], 'pause', command_id='pause') store.control(cancelled['id'], 'cancel', command_id='cancel') noon = epoch('2026-11-11T12:00:00+08:00') for job in development: assert store.peek_next(now=noon)['id'] == job['id'] claim = store.claim_next(now=noon, gpu_uuids=['GPU-A', 'GPU-B']) assert claim['id'] == job['id'] assert store.admission(job['id'], now=noon)['eligible'] store.finish(job['id'], 'succeeded', result={}, attempt_count=1) assert not store.active_gpu_uuids() assert store.claim_next(now=noon) is None assert store.admission(paused['id'], now=noon)['reason'] == 'manual_pause' assert store.admission(cancelled['id'], now=noon)['reason'] == 'cancelled' assert store.get(production['id'])['attempt_count'] == 0 store.control(paused['id'], 'run', command_id='resume') assert store.claim_next(now=noon)['id'] == paused['id'] @pytest.mark.parametrize('mode', ['interactive', 'batch']) @pytest.mark.parametrize('bad_clock', ['NaN', 'not-a-clock', '0']) def test_false_snapshot_bypasses_clock_without_mutating_watermarks(tmp_path, mode, bad_clock): store = Store(tmp_path / 'jobs.db') job = submit(store, mode, False) with store._connection() as connection: store._set_state(connection, 'clock_max_seen', bad_clock) store._set_state(connection, 'closed_window_through', 'broken') noon = epoch('2026-11-11T12:00:00+08:00') assert store.peek_next(now=noon)['id'] == job['id'] assert store.admission(job['id'], now=noon)['eligible'] assert store.claim_next(now=noon)['id'] == job['id'] with store._connection() as connection: assert store._state(connection, 'clock_max_seen') == bad_clock assert store._state(connection, 'closed_window_through') == 'broken' @pytest.mark.parametrize('mode', ['interactive', 'batch']) def test_unrestricted_job_and_empty_queue_status_do_not_create_clock_evidence(tmp_path, mode): store = Store(tmp_path / 'jobs.db') job = submit(store, mode, False) noon = epoch('2026-11-11T12:00:00+08:00') assert store.peek_next(now=noon)['id'] == job['id'] assert store.waiting_summary(now=noon)['eligible'] assert store.claim_next(now=noon)['id'] == job['id'] assert store.waiting_summary(now=noon)['queued'] == 0 assert store.admission(job['id'], now=noon)['eligible'] store.finish(job['id'], 'succeeded', result={}) assert store.waiting_summary(now=noon)['queued'] == 0 with store._connection() as connection: assert store._state(connection, 'clock_max_seen') == '' assert store._state(connection, 'closed_window_through') == '' @pytest.mark.parametrize('entry', ['peek_next', 'waiting_summary']) def test_clock_admission_serializes_concurrent_queue_writes(tmp_path, monkeypatch, entry): store = Store(tmp_path / 'jobs.db') first = submit(store, 'interactive', True) submit(store, 'batch', True) # Keep the selection cursor active after its first row. writer = Store(store.path) started, finished = threading.Event(), threading.Event() original = store._job_eligibility pending = [] def enqueue(): started.set() try: return submit(writer, 'batch', False) finally: finished.set() with ThreadPoolExecutor(max_workers=1) as pool: def check_with_concurrent_enqueue(connection, row, now): if not pending: pending.append(pool.submit(enqueue)) assert started.wait(2) # An unprotected reader lets this commit invalidate its WAL # snapshot; a writer transaction correctly holds it until return. finished.wait(.2) return original(connection, row, now) monkeypatch.setattr(store, '_job_eligibility', check_with_concurrent_enqueue) now = epoch('2026-11-11T01:00:00+08:00') result = getattr(store, entry)(now=now) if entry == 'peek_next': assert result['id'] == first['id'] else: assert result['queued'] == 2 and result['eligible'] added = pending[0].result(timeout=5) assert store.get(added['id'])['state'] == 'queued' assert store.get(first['id'])['attempt_count'] == 0 with store._connection() as connection: assert store._state(connection, 'clock_max_seen') == str(now) @pytest.mark.parametrize('mode', ['interactive', 'batch']) def test_true_snapshot_retains_clock_guard_when_host_file_is_disabled(tmp_path, mode): path = tmp_path / 'policy.json' write_policy(path, False) store = Store(tmp_path / 'jobs.db', policy_file=path) job = submit(store, mode, True) assert store.peek_next(now=epoch('2026-11-11T08:00:01+08:00')) is None store = Store(store.path, policy_file=path) rollback = epoch('2026-11-11T07:55:00+08:00') assert store.claim_next(now=rollback) is None assert store.admission(job['id'], now=rollback)['reason'] == 'clock_rollback' with store._connection() as connection: store._set_state(connection, 'clock_max_seen', 'NaN') assert store.admission(job['id'], now=rollback)['reason'] == 'clock_state_invalid' @pytest.mark.parametrize('mode', ['interactive', 'batch']) @pytest.mark.parametrize('enabled', [True, False]) def test_invalid_host_file_remains_closed_for_each_environment(tmp_path, mode, enabled): path = tmp_path / 'policy.json' path.write_text('{corrupt', encoding='utf-8') store = Store(tmp_path / 'jobs.db', policy_file=path) job = submit(store, mode, enabled) now = epoch('2026-11-11T22:00:00+08:00') assert store.peek_next(now=now) is None assert store.claim_next(now=now) is None assert store.admission(job['id'], now=now)['reason'] == 'runtime_policy_invalid' assert store.get(job['id'])['attempt_count'] == 0 assert not store.active_gpu_uuids() @pytest.mark.parametrize('mode', ['interactive', 'batch']) def test_legacy_job_without_snapshot_follows_hot_file_for_both_modes(tmp_path, mode): path = tmp_path / 'policy.json' store = Store(tmp_path / 'jobs.db', policy_file=path) job = store.submit('image.generate', {}, {}, scheduling={'execution_mode': mode}) noon = epoch('2026-11-11T12:00:00+08:00') assert store.peek_next(now=noon) is None assert store.admission(job['id'], now=noon)['reason'] == 'waiting_batch_window' 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 store.admission(job['id'], now=noon)['reason'] == 'waiting_batch_window' def test_authenticated_api_advertises_and_accepts_strict_project_snapshot(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-project-gpu-window-key') headers = {'Authorization': 'Bearer test-only-project-gpu-window-key'} with TestClient(create_app(settings)) as client: assert client.get('/capabilities', headers=headers).json()['features']['project_gpu_window'] is True for enabled in [True, False]: response = client.post('/jobs', headers=headers, json={'task_type': 'image.generate', 'input': {'prompt': 'snapshot'}, 'scheduling': scheduling('interactive', enabled)}) assert response.status_code == 202, response.text assert response.json()['scheduling']['gpu_window_enabled'] is enabled for value in [None, 0, 1, 'false']: response = client.post('/jobs', headers=headers, json={'task_type': 'image.generate', 'scheduling': scheduling('batch', value)}) assert response.status_code == 422, response.text @pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process/flock integration') @pytest.mark.parametrize('mode', ['interactive', 'batch']) def test_shared_worker_runs_development_in_daytime_then_production_at_night(tmp_path, mode): from llm_services.worker import Worker settings = Settings(tmp_path / 'app', tmp_path, runner_python=sys.executable, poll_seconds=.01) write_policy(settings.runtime_policy_file, False) store = initialize_store(settings) production = submit(store, mode, True) development = submit(store, mode, False) clock = [epoch('2026-11-11T12:00:00+08:00')] runner = tmp_path / 'fake.py' runner.write_text('import json,pathlib,sys\nr=json.loads(pathlib.Path(sys.argv[1]).read_text())\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 SharedWorker(Worker): def _command(self, request_path, result_path): return [sys.executable, str(runner), str(request_path), str(result_path)] with SharedWorker(settings, gpu_policy=None, clock=lambda: clock[0]) as worker: assert worker.run_once() assert store.get(development['id'])['state'] == 'succeeded' assert store.get(production['id'])['state'] == 'queued' assert not worker.run_once() assert not store.active_gpu_uuids() clock[0] = epoch('2026-11-11T21:00:00+08:00') assert worker.run_once() assert store.get(production['id'])['state'] == 'succeeded' assert not store.active_gpu_uuids()