"""Video input (wald-serve 0.2.2): sources and limits, the two routes' decoding, the request rewrite, the engine path with a stub vLLM, the default (no-video) responses against wald-serve 0.2.1, the temperature pin and the vLLM limits. No model, no GPU; needs opencv-python-headless (skipped without it).""" import base64 import hashlib import json import sys import threading import urllib.error import urllib.request from http.server import ThreadingHTTPServer from pathlib import Path import pytest cv2 = pytest.importorskip("cv2") np = pytest.importorskip("numpy") HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import record_default_fixtures as rec # noqa: E402 import stubengine # noqa: E402 from wald_serve import native, video as V, vision_v2 # noqa: E402 from wald_serve.native_vision import NativeV2Vision, handler, video_vllm_args, VISION_VLLM_ARGS # noqa: E402 TEMP = HERE.parents[1] / "temperature.json" FIXTURES = HERE / "fixtures/default-responses-0.2.1.json" Q = {"door": {"type": "choice", "instructions": "Where is the door?", "criteria": {"A": "left", "B": "right", "C": "behind"}}, "moving": {"type": "noul", "instructions": "Does anything move?"}, "risk": {"type": "score", "instructions": "How risky is the scene?", "criteria": ["none", "low", "high"]}} def make_video(path, n=40, fps=10.0, size=(480, 360)): w = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, size) assert w.isOpened() for i in range(n): f = np.zeros((size[1], size[0], 3), np.uint8) f[:] = ((i * 37) % 256, (i * 11) % 256, 255 - (i * 5) % 256) cv2.putText(f, str(i), (20, size[1] // 2), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 5) w.write(f) w.release() return Path(path) @pytest.fixture(scope="module") def clip(tmp_path_factory): return make_video(tmp_path_factory.mktemp("v") / "clip.mp4") def data_uri(p): return "data:video/mp4;base64," + base64.b64encode(Path(p).read_bytes()).decode() # ---- the evaluated client protocol (the VisualDecisionBench-video client's frame sampler), verbatim ---- def vdb_frames(path, n=16, max_px=131072): cap = cv2.VideoCapture(str(path)); total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)); fps = cap.get(cv2.CAP_PROP_FPS) or 0 imgs = [] if total <= 0: allf = [] while True: ok, f = cap.read() if not ok: break allf.append(f) total = len(allf); get = lambda i: allf[i] else: def get(i): cap.set(cv2.CAP_PROP_POS_FRAMES, int(i)); ok, f = cap.read() return f if ok else None idx = np.linspace(0, total - 1, n).round().astype(int) for i in idx: f = get(i) if f is None: continue h, w = f.shape[:2]; s = min(1.0, (max_px / (h * w)) ** 0.5) if s < 1: f = cv2.resize(f, (max(28, int(w * s)), max(28, int(h * s))), interpolation=cv2.INTER_AREA) ok, enc = cv2.imencode(".jpg", f, [cv2.IMWRITE_JPEG_QUALITY, 95]) imgs.append((float(i) / fps if fps else None, enc.tobytes())) cap.release() return imgs def vdb_wire_parts(path): parts = [] fr = vdb_frames(path) for k, (t, b) in enumerate(fr): parts.append({"type": "text", "text": f"Frame {k + 1}/{len(fr)}" + (f" at t = {t:.1f} s:" if t is not None else ":")}) parts.append({"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(b).decode()}}) return parts # ---------------------------------------------------------------------------------------------------------- sources def test_sources_data_uri_raw_base64_and_path(clip, tmp_path): raw = clip.read_bytes() cfg = V.VideoConfig() assert V.load(data_uri(clip), cfg) == raw assert V.load(base64.b64encode(raw).decode(), cfg) == raw assert V.load({"url": data_uri(clip)}, cfg) == raw with pytest.raises(V.VideoError, match="video_source"): V.load(str(clip), cfg) # paths are off by default cfg = V.VideoConfig(video_dir=str(clip.parent)) assert V.load(str(clip), cfg) == raw and V.load("file://" + str(clip), cfg) == raw and V.load("clip.mp4", cfg) == raw outside = tmp_path / "x.mp4"; outside.write_bytes(raw) with pytest.raises(V.VideoError, match="video_source"): V.load(str(outside), cfg) with pytest.raises(V.VideoError, match="video_source"): V.load(str(clip.parent / ".." / tmp_path.name / "x.mp4"), cfg) def test_bad_sources(): cfg = V.VideoConfig() with pytest.raises(V.VideoError, match="video_format"): V.load("data:video/x-unknown;base64,AAAA", cfg) with pytest.raises(V.VideoError, match="video_format"): V.load("data:image/png;base64,AAAA", cfg) with pytest.raises(V.VideoError, match="video_format"): V.load("data:video/mp4;base64," + base64.b64encode(b"not a video at all" * 10).decode(), cfg) with pytest.raises(V.VideoError, match="video_format"): V.load("data:video/mp4;base64,@@@@", cfg) with pytest.raises(V.VideoError, match="video_too_large"): V.load("data:video/mp4;base64," + "A" * 400, V.VideoConfig(max_bytes=100)) with pytest.raises(V.VideoError, match="video_source"): V.load("http://127.0.0.1:9/x.mp4", cfg) # public policy: loopback refused before any fetch with pytest.raises(V.VideoError, match="video_source"): V.load("http://169.254.169.254/latest", cfg) with pytest.raises(V.VideoError, match="video_source"): V.load("https://example.com/x.mp4", V.VideoConfig(url_policy="off")) def test_url_fetch_any_policy(clip): from http.server import BaseHTTPRequestHandler raw = clip.read_bytes() class H(BaseHTTPRequestHandler): def log_message(self, *a): pass def do_GET(self): self.send_response(200); self.send_header("Content-Length", str(len(raw))); self.end_headers(); self.wfile.write(raw) s = ThreadingHTTPServer(("127.0.0.1", 0), H); t = threading.Thread(target=s.serve_forever, daemon=True); t.start() try: u = f"http://127.0.0.1:{s.server_port}/clip.mp4" assert V.load(u, V.VideoConfig(url_policy="any")) == raw with pytest.raises(V.VideoError, match="video_too_large"): V.load(u, V.VideoConfig(url_policy="any", max_bytes=1000)) finally: s.shutdown(); s.server_close() # ---------------------------------------------------------------------------------------------------------- decoding def test_frames16_is_the_evaluated_client_protocol(clip): d = V.decode(clip.read_bytes(), "frames16", V.VideoConfig()) ref = vdb_frames(clip) assert [b for _, b in ref] == d.frames and [t for t, _ in ref] == d.times and len(d.frames) == 16 assert d.image_parts() == vdb_wire_parts(clip) img = cv2.imdecode(np.frombuffer(d.frames[0], np.uint8), cv2.IMREAD_COLOR) assert img.shape[0] * img.shape[1] <= 131072 and img.shape[:2] != (360, 480) def test_native32_sampling_and_metadata(clip): d = V.decode(clip.read_bytes(), "native32", V.VideoConfig()) assert d.indices == np.linspace(0, 39, 32).round().astype(int).tolist() and len(d.frames) == 32 m = d.media_io_kwargs()["video"] assert m == {"num_frames": 32, "fps": 10.0, "frames_indices": d.indices, "total_num_frames": 40, "duration": 4.0} assert d.mm_processor_kwargs() == {"max_pixels": 32 * 131072, "min_pixels": 4096} url = d.video_url() assert url.startswith("data:video/jpeg;base64,") and url.count(",") == 32 # frames are the source frames (full size), in order: the drawn counter colour of frame i for k in (0, 31): img = cv2.imdecode(np.frombuffer(d.frames[k], np.uint8), cv2.IMREAD_COLOR) assert img.shape[:2] == (360, 480) i = d.indices[k] assert np.abs(img[5, 5].astype(int) - [(i * 37) % 256, (i * 11) % 256, 255 - (i * 5) % 256]).max() < 12 short = V.decode(make_video(clip.parent / "short.mp4", n=10).read_bytes(), "native32", V.VideoConfig()) assert short.indices == list(range(10)) def test_limits(clip, tmp_path): raw = clip.read_bytes() with pytest.raises(V.VideoError, match="video_too_long"): V.decode(raw, "frames16", V.VideoConfig(max_seconds=2)) with pytest.raises(V.VideoError, match="video_too_long"): V.decode(raw, "native32", V.VideoConfig(max_seconds=2)) with pytest.raises(V.VideoError, match="video_pixels"): V.decode(raw, "native32", V.VideoConfig(max_source_pixels=480 * 360 - 1)) with pytest.raises(V.VideoError, match="video_route"): V.decode(raw, "native64", V.VideoConfig()) bad = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 500 with pytest.raises(V.VideoError, match="video_malformed"): V.decode(bad, "frames16", V.VideoConfig()) def test_cache_decodes_once(clip, monkeypatch): cache = V.FrameCache(64); n = {"k": 0} real = V.decode_native def counting(*a, **k): n["k"] += 1; return real(*a, **k) monkeypatch.setattr(V, "decode_native", counting) raw = clip.read_bytes() a = V.decode(raw, "native32", V.VideoConfig(), cache); b = V.decode(raw, "native32", V.VideoConfig(), cache) assert a is b and n["k"] == 1 and cache.hits == 1 tiny = V.FrameCache(0) V.decode(raw, "native32", V.VideoConfig(), tiny); V.decode(raw, "native32", V.VideoConfig(), tiny) assert n["k"] == 3 and not tiny.items # ---------------------------------------------------------------------------------------------------------- requests def test_prepare_shapes(clip): cfg = V.VideoConfig(); u = data_uri(clip) msg = {"state": {"messages": [{"role": "user", "content": [{"type": "text", "text": "Kitchen camera."}, {"type": "video_url", "video_url": {"url": u}}]}]}, "questions": Q} assert V.prepare(msg, cfg, None, False).route == "native32" # the default route p = V.prepare({**msg, "video_route": "frames16"}, cfg, None, False) assert p.route == "frames16" and "video_route" not in p.request assert p.request["state"]["messages"][0]["content"] == [{"type": "text", "text": "Kitchen camera."}] + vdb_wire_parts(clip) top = V.prepare({"videos": [u], "state": "Kitchen camera.", "questions": Q, "video_route": "frames16"}, cfg, None, False) assert top.request["state"] == {"messages": [{"role": "user", "content": vdb_wire_parts(clip) + [{"type": "text", "text": "Kitchen camera."}]}]} obj = V.prepare({"videos": [u], "state": {"camera": "kitchen"}, "questions": Q, "video_route": "frames16"}, cfg, None, False) assert list(obj.request["state"]) == ["video", "camera"] and obj.request["state"]["video"].startswith("Frame 1/16 at t = 0.0 s:\ndata:image/jpeg") nat = V.prepare({**msg, "video_route": "native32"}, cfg, None, False) (mark, d), = nat.markers.items() assert nat.route == "native32" and nat.request["state"]["messages"][0]["content"][1] == {"type": "text", "text": mark} with pytest.raises(V.VideoError, match="video_count"): V.prepare({"videos": [u, u], "state": "s", "questions": Q}, cfg, None, False) with pytest.raises(V.VideoError, match="video_route"): V.prepare({**msg, "video_route": "native32"}, cfg, None, True) fb = V.prepare(msg, cfg, None, True) assert fb.route == "frames16" and fb.fallback with pytest.raises(V.VideoError, match="video_unavailable"): V.prepare(msg, V.VideoConfig(enabled=False), None, False) def test_lift_native_marker_to_video_slot(clip): p = V.prepare({"videos": [data_uri(clip)], "state": "s", "questions": Q, "video_route": "native32"}, V.VideoConfig(), None, False) out, uris, pat = vision_v2.lift(p.request, 16, p.markers) assert len(uris) == 1 and isinstance(uris[0], V.Decoded) and len(pat.findall(out["state"])) == 1 and "wald-video" not in out["state"] parts = vision_v2.to_parts("<|im_start|>user\n" + out["state"] + "<|im_end|>", uris, pat) assert [x["type"] for x in parts] == ["text", "video_url", "text"] and parts[1]["video_url"]["url"].startswith("data:video/jpeg") # ---------------------------------------------------------------------------------------------------------- engine path def engine(monkeypatch, **kw): e = NativeV2Vision("http://unused", TEMP, noul_decisive_floor=0.81, **kw) _, calls = stubengine.install(monkeypatch, lp=stubengine.hashed_lp, engine=e) return e, calls def chats(calls): return [b for p, b in calls if p == "/v1/chat/completions"] def test_frames16_request_equals_client_frames_request(clip, monkeypatch): """Served video == the evaluated client-side frames: the same vLLM chat bodies and the same answers.""" e, calls = engine(monkeypatch) client = e({"state": {"messages": [{"role": "user", "content": vdb_wire_parts(clip)}]}, "questions": Q, "effort": "none"}) a = chats(calls); calls.clear() served = e({"state": {"messages": [{"role": "user", "content": [{"type": "video_url", "video_url": {"url": data_uri(clip)}}]}]}, "questions": Q, "effort": "none", "video_route": "frames16"}) b = chats(calls) assert a == b and len(a) == 3 and a[0]["chat_template"] == vision_v2.CHAT_TEMPLATE assert {k: v for k, v in served.items() if not k.startswith("video") and k != "images"} == \ {k: v for k, v in client.items() if k != "images"} assert served["video_route"] == "frames16" and served["videos"] == 1 and served["video_frames"] == [16] and served["images"] == 0 calls.clear() top = e({"videos": [data_uri(clip)], "state": None, "questions": Q, "effort": "none", "video_route": "frames16"}) assert chats(calls) == a and top["answers"] == served["answers"] def test_native32_request(clip, monkeypatch): e, calls = engine(monkeypatch) n = {"k": 0}; real = V.decode_native def counting(*a, **k): n["k"] += 1; return real(*a, **k) monkeypatch.setattr(V, "decode_native", counting) r = e({"videos": [data_uri(clip)], "video_route": "native32", "state": "Kitchen camera.", "questions": Q, "effort": "auto"}) cs = chats(calls) assert n["k"] == 1 and len(cs) >= 3 # one decode for every question (and any thought) for c in cs: assert c["chat_template"] == vision_v2.VIDEO_CHAT_TEMPLATE assert [p["type"] for p in c["messages"][0]["content"]].count("video_url") == 1 assert c["media_io_kwargs"]["video"]["num_frames"] == 32 and c["mm_processor_kwargs"]["max_pixels"] == 32 * 131072 assert r["video_route"] == "native32" and r["video_frames"] == [32] and set(r["answers"]) == set(Q) vparts = [next(p for p in c["messages"][0]["content"] if p["type"] == "video_url") for c in cs] assert vparts[0]["video_url"]["url"].startswith("data:video/jpeg;base64,") and vparts[0]["uuid"].startswith("wald-video-") assert all(p == {"type": "video_url", "video_url": None, "uuid": vparts[0]["uuid"]} for p in vparts[1:]) # frames sent once e({"videos": [data_uri(clip)], "video_route": "native32", "state": "Again.", "questions": Q, "effort": "none"}) assert n["k"] == 1 # LRU: same content, no second decode def test_native32_cache_miss_resends_frames(clip, monkeypatch): e, calls = engine(monkeypatch) import eval.systemone_vllm as sov stub = sov.Client.post def post(self, path, body, retries=1): if path == "/v1/chat/completions" and any(p.get("type") == "video_url" and p.get("video_url") is None for p in body["messages"][0]["content"]): calls.append(("miss", None)) raise ValueError("400: Cache miss for video at index 0 but data is not provided.") return stub(self, path, body, retries) monkeypatch.setattr(sov.Client, "post", post) r = e({"videos": [data_uri(clip)], "video_route": "native32", "state": "s", "questions": Q, "effort": "none"}) assert set(r["answers"]) == set(Q) and sum(1 for p, _ in calls if p == "miss") == 2 assert all(next(p for p in c["messages"][0]["content"] if p["type"] == "video_url")["video_url"] for c in chats(calls)) def test_mixed_image_and_video(clip, monkeypatch): e, calls = engine(monkeypatch) img = rec.png_uri() r = e({"images": [img], "videos": [data_uri(clip)], "state": "Shelf photo, then the aisle video.", "questions": Q, "effort": "none"}) c = chats(calls)[0] types = [p["type"] for p in c["messages"][0]["content"]] assert types.count("image_url") == 17 and r["images"] == 1 and r["video_frames"] == [16] assert r["video_route"] == "frames16" and r["video_route_fallback"] == "images in the request" # default native32 falls back def test_http_errors(clip, monkeypatch): e, _ = engine(monkeypatch) s = ThreadingHTTPServer(("127.0.0.1", 0), handler(e)); t = threading.Thread(target=s.serve_forever, daemon=True); t.start() def post(body): req = urllib.request.Request(f"http://127.0.0.1:{s.server_port}/v1/systemone", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) try: return 200, json.loads(urllib.request.urlopen(req).read()) except urllib.error.HTTPError as err: return err.code, json.loads(err.read()) try: code, r = post({"videos": [data_uri(clip)], "state": "s", "questions": Q, "effort": "none"}) assert code == 200 and r["video_route"] == "native32" assert post({"videos": ["data:video/mp4;base64,AAAA"], "state": "s", "questions": Q})[0] == 400 assert post({"videos": [data_uri(clip)], "video_route": "x", "state": "s", "questions": Q})[0] == 400 code, r = post({"videos": ["/etc/passwd"], "state": "s", "questions": Q}) assert code == 400 and "video_source" in r["error"] h = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{s.server_port}/health").read()) assert h["video"]["default_route"] == "native32" and h["video"]["max_videos"] == 1 finally: s.shutdown(); s.server_close() # ---------------------------------------------------------------------------------------------------------- unchanged def test_requests_without_video_are_byte_identical_to_0_2_1(): """The 16 responses recorded with the unmodified wald-serve 0.2.1 (org2ai/Wald-4B @ ce3286f7, same stub).""" data = json.loads(FIXTURES.read_text()) assert data["recorded_with"] == "wald-serve 0.2.1" and len(data["cases"]) == 16 for case in data["cases"]: mp = pytest.MonkeyPatch() try: assert rec.run_case(case, mp) == case["response_json"] finally: mp.undo() def test_image_request_keeps_the_image_template(monkeypatch): e, calls = engine(monkeypatch) e({"images": [rec.png_uri()], "state": "s", "questions": Q, "effort": "none", "video_route": "native32"}) for c in chats(calls): assert c["chat_template"] == vision_v2.CHAT_TEMPLATE and "media_io_kwargs" not in c and "mm_processor_kwargs" not in c def test_temperature_pin_from_table_dir(tmp_path): raw = TEMP.read_bytes(); sha = hashlib.sha256(raw).hexdigest() assert native.table_pin(TEMP, "/some/model") == native.TEMPERATURE_SHA other = json.loads(raw); other["table_meta"] = {"note": "refit"} d = tmp_path / "g3"; d.mkdir(); t = d / "temperature.json"; t.write_text(json.dumps(other)) osha = hashlib.sha256(t.read_bytes()).hexdigest() assert native.table_pin(t) == native.TEMPERATURE_SHA # no manifest: the frozen pin (refused later) (d / "SHA256SUMS").write_text(f"{osha} temperature.json\n") assert native.table_pin(t) == osha (d / "serving.json").write_text(json.dumps({"temperature": "temperature.json", "temperature_sha256": "f" * 64})) assert native.table_pin(t) == "f" * 64 # serving.json wins; a mismatch is still refused with pytest.raises(ValueError, match="hash mismatch"): native.NativeV2("http://unused", t, temperature_sha256=native.table_pin(t)) (d / "serving.json").write_text(json.dumps({"temperature": "temperature.json", "temperature_sha256": osha})) native.NativeV2("http://unused", t, temperature_sha256=native.table_pin(t)) # loads assert sha == native.TEMPERATURE_SHA def test_vllm_limits(): args = video_vllm_args(VISION_VLLM_ARGS) i = args.index("--limit-mm-per-prompt") assert json.loads(args[i + 1]) == {"image": 32, "video": 2} and args[:i] == VISION_VLLM_ARGS[:i] and args[i + 2:] == VISION_VLLM_ARGS[i + 2:] assert json.loads(video_vllm_args(["--limit-mm-per-prompt", '{"image": 40, "video": 0}'])[1]) == {"image": 40, "video": 2}