"""The kernel's imagegen binding over a fake host, in process. The defects: a generated image published partly, over an existing file, or lost when saving fails after the quota was spent; a temporary file left behind when nothing complete was kept; an invalid response published; a cancelled generation not cancelled on the host; and a reference, output, prompt, provider or page argument, given or rewritten by a hook, that reaches the host unchecked. The binding talks to the daemon only through its host routes, so a fake host that fails at any one of them reaches every failure point a daemon could, without a provider or a kernel. """ import asyncio import base64 from contextlib import redirect_stdout from dataclasses import dataclass, field import io import json import os from pathlib import Path import struct import sys import tempfile from typing import Any, Awaitable, Callable, cast import unittest from unittest.mock import patch import zlib ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "python")) sys.path.insert(0, str(ROOT / "test")) import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 from albedo_plugins import hook # noqa: E402 import albedo_plugins.imagegen as imagegen_module # noqa: E402 from albedo_plugins.imagegen import Imagegen # noqa: E402 def png(width: int, height: int) -> bytes: def chunk(kind: bytes, data: bytes) -> bytes: body = kind + data return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) rows = b"".join(b"\0" + b"\x80\x40\x20" * width for _ in range(height)) return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") ) IMAGE = png(3, 2) @dataclass class FakeHost: """The daemon's image routes, answering with `reply` unless told to fail at one of them. Every call is kept, in order.""" reply: dict[str, object] = field( default_factory=lambda: { "data": base64.b64encode(IMAGE).decode(), "mime_type": "image/png", "request_id": "request", "generation_id": "generation", } ) fail_at: str | None = None # Runs while the generation is out, before it answers. during: Callable[[], Awaitable[None]] | None = None calls: list[tuple[str, dict[str, object]]] = field(default_factory=list) async def __call__(self, route: str, args: dict[str, object]) -> object: self.calls.append((route, args)) if route == self.fail_at: raise RuntimeError(f"injected {route} failure") if route == "imagegen.generate": if self.during is not None: await self.during() return self.reply if route == "imagegen.references": return {"images": [], "next_after": 0, "has_more": False} return None def routes(self) -> list[str]: return [route for route, _ in self.calls if route.startswith("imagegen.")] class Storage: """`os` for the binding, failing at one step of saving the image.""" def __init__(self, failure: str) -> None: self.failure = failure def __getattr__(self, name: str) -> object: return getattr(os, name) def fsync(self, descriptor: int) -> None: if self.failure == "fsync": raise OSError(5, "injected fsync failure") os.fsync(descriptor) def link(self, source: str, destination: str) -> None: if self.failure == "link": raise OSError(5, "injected link failure") os.link(source, destination) def fdopen(self, *args: Any, **kwargs: Any) -> "Saving": opened: Any = os.fdopen return Saving(opened(*args, **kwargs), self.failure) class Saving: def __init__(self, file, failure: str) -> None: self.file = file self.failure = failure def __getattr__(self, name: str) -> object: return getattr(self.file, name) def write(self, data: bytes) -> int: if self.failure == "partial_write": self.file.write(data[: len(data) // 2]) raise OSError(5, "injected partial_write failure") return self.file.write(data) def flush(self) -> None: if self.failure == "buffered_flush": raise OSError(5, "injected buffered_flush failure") self.file.flush() if self.failure == "flush": raise OSError(5, "injected flush failure") def __enter__(self): return self def __exit__(self, kind, value, trace): result = self.file.__exit__(kind, value, trace) if kind is None and self.failure == "close": raise OSError(5, "injected close failure") return result class Workspace: """A scratch directory the binding runs in, as a kernel's cwd.""" def __enter__(self) -> Path: self.directory = tempfile.TemporaryDirectory() self.before = os.getcwd() os.chdir(self.directory.name) return Path(self.directory.name) def __exit__(self, *_: object) -> None: os.chdir(self.before) self.directory.cleanup() def files(root: Path) -> dict[str, bytes]: return { str(path.relative_to(root)): path.read_bytes() for path in root.rglob("*") if path.is_file() } def run(host: FakeHost, call): """`call(imagegen)` with hooks answered by `host` too.""" async def body(): # A cancelled generation prints its advice; keep the log quiet. with patch.object(hook, "host", host), redirect_stdout(io.StringIO()): return await call(Imagegen(host)) return asyncio.run(body()) # What can go wrong between asking for an image and publishing it. POINTS = [ "none", "imagegen.begin", "imagegen.generate", "not_png", "jpeg_label", "truncated", "bad_base64", "no_data", "partial_write", "buffered_flush", "flush", "fsync", "close", "link", "raced", "cancelled", ] class PublicationTests(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(120)) @given( st.sampled_from(POINTS), st.sampled_from([None, "named.png", "deep/er/named.PNG"]), st.lists(st.sampled_from(["a.txt", "keep.png"]), max_size=2, unique=True), ) def test_a_generation_publishes_one_complete_image_or_nothing( self, point, output, others ): host = FakeHost() if point in ("imagegen.begin", "imagegen.generate"): host.fail_at = point broken: dict[str, dict[str, object]] = { "not_png": {"data": base64.b64encode(b"not png").decode()}, "jpeg_label": {"data": host.reply["data"], "mime_type": "image/jpeg"}, "truncated": { "data": base64.b64encode(IMAGE[:-8]).decode(), "mime_type": "image/png", }, "bad_base64": {"data": "%%%", "mime_type": "image/png"}, "no_data": {"mime_type": "image/png"}, } if point in broken: host.reply = broken[point] with Workspace() as root: for name in others: (root / name).write_bytes(b"theirs") before = files(root) destination = None if output is None else (root / output).absolute() async def race(): assert destination is not None destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(b"competing writer") async def cancel(): raise asyncio.CancelledError if point == "raced" and destination is not None: host.during = race if point == "cancelled": host.during = cancel async def generate(imagegen): return await imagegen.generate( "an image", output=None if output is None else str(destination) ) storage = ( Storage(point) if point in ( "partial_write", "buffered_flush", "flush", "fsync", "close", "link", ) else os ) outcome: object with patch.object(imagegen_module, "os", storage): try: outcome = run(host, generate) except (Exception, asyncio.CancelledError) as error: outcome = error after = files(root) added = {name: data for name, data in after.items() if name not in before} # Nothing that was there is changed. for name, data in before.items(): self.assertEqual(after[name], data) routes = host.routes() # Every attempt begins once before it generates, and never twice. self.assertEqual(routes[:1], ["imagegen.begin"]) self.assertLessEqual(routes.count("imagegen.generate"), 1) temporary = {n: d for n, d in added.items() if ".imagegen-" in n} published = {n: d for n, d in added.items() if ".imagegen-" not in n} if point == "none" or (point == "raced" and destination is None): self.assertNotIsInstance(outcome, BaseException, outcome) self.assertEqual(list(published.values()), [IMAGE]) self.assertEqual(temporary, {}) [name] = published self.assertEqual(getattr(outcome, "path"), str(root / name)) elif point == "cancelled": self.assertIsInstance(outcome, asyncio.CancelledError) self.assertEqual(added, {}) begun = host.calls[[r for r, _ in host.calls].index("imagegen.begin")] cancels = [a for r, a in host.calls if r == "imagegen.cancel"] self.assertEqual(cancels, [{"call_id": begun[1]["call_id"]}]) elif point in ( "fsync", "flush", "buffered_flush", "close", "link", "raced", ): # The quota was spent and the image is whole: it is kept # beside the destination, and the error says where. self.assertIsInstance(outcome, OSError) self.assertEqual(list(temporary.values()), [IMAGE]) expected = {output: b"competing writer"} if point == "raced" else {} self.assertEqual(published, expected) [kept] = temporary self.assertIn(str(root / kept), str(outcome)) else: self.assertIsInstance(outcome, Exception) self.assertEqual(added, {}) if point in broken: self.assertIn("invalid image response", str(outcome)) if point == "imagegen.begin": self.assertNotIn("imagegen.generate", routes) class RefusalTests(unittest.TestCase): """Arguments that never reach the host: checked before the hooks are asked, and again after a hook rewrote them.""" def refused_before_host(self, call, host=None): host = host or FakeHost() with self.assertRaises((ValueError, TypeError, FileExistsError, OSError)): run(host, call) self.assertEqual(host.routes(), []) return host def test_bad_arguments_never_reach_the_host_or_the_hooks(self): invalid = [ {"prompt": "x", "references": ["transcript:" + "1" * 30 + ":0"]}, {"prompt": "x", "references": ["transcript:9223372036854775808:0"]}, {"prompt": "x", "references": ["transcript:1:9223372036854775808"]}, {"prompt": "x", "references": ["transcript:1:" + "0" * 50]}, {"prompt": "x", "references": ["transcript:1:0"] * 6}, {"prompt": "x" * 32769}, {"prompt": "é" * 16385}, {"prompt": " "}, {"prompt": "x", "references": ["x" * 32769 + ".png"]}, {"prompt": "x", "output": "x" * 32769 + ".png"}, {"prompt": "x", "provider": ""}, {"prompt": "x", "provider": 123}, {"prompt": "x", "provider": "x" * 129}, {"prompt": "x", "provider": "é" * 65}, {"prompt": "x", "transparent_background": 1}, ] with Workspace(): for kwargs in invalid: with self.subTest(kwargs=str(kwargs)[:80]): host = self.refused_before_host( lambda imagegen, kwargs=kwargs: imagegen.generate(**kwargs) ) self.assertEqual(host.calls, []) for page in ({"after": 9223372036854775808}, {"after": -1}, {"limit": 0}): host = self.refused_before_host( lambda imagegen, page=page: imagegen.references(**page) ) self.assertEqual(host.calls, []) def test_files_that_cannot_be_used_are_refused_before_generation(self): with Workspace() as root: (root / "existing.png").write_bytes(b"keep me") fifo = root / "pipe.png" os.mkfifo(fifo) (root / "dangling.png").symlink_to(root / "missing.png") (root / "not-image.png").write_bytes(b"not an image") for kwargs in [ {"output": str(root / "existing.png")}, {"output": str(root / "dangling.png")}, {"output": str(root / "image.jpg")}, {"references": [str(fifo)]}, {"references": [str(root / "not-image.png")]}, ]: with self.subTest(kwargs=kwargs): self.refused_before_host( lambda imagegen, kwargs=kwargs: imagegen.generate("x", **kwargs) ) self.assertEqual((root / "existing.png").read_bytes(), b"keep me") self.assertFalse((root / "missing.png").exists()) self.assertEqual(list(root.glob(".imagegen-*")), []) def test_combined_local_references_over_five_mib_are_refused(self): with Workspace() as root: # A valid PNG of about 3 MiB: incompressible pixel data. rows = os.urandom(1024 * 1024 * 3) width = 1024 height = len(rows) // (width * 3) raw = b"".join( b"\0" + rows[y * width * 3 : (y + 1) * width * 3] for y in range(height) ) def chunk(kind, data): body = kind + data return ( struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) ) image = ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b"") ) source = root / "three-mib.png" source.write_bytes(image) self.assertLess(len(image), 5 * 1024 * 1024) self.assertGreater(2 * len(image), 5 * 1024 * 1024) host = FakeHost() with self.assertRaises(ValueError): run( host, lambda imagegen: imagegen.generate( "x", references=[str(source)] * 2 ), ) self.assertEqual(host.routes(), []) # One of them alone is sent. run(host, lambda imagegen: imagegen.generate("x", references=[str(source)])) [(_, generate)] = [c for c in host.calls if c[0] == "imagegen.generate"] [reference] = cast(list[dict[str, str]], generate["references"]) self.assertEqual(base64.b64decode(reference["data"]), image) def test_a_generated_png_over_five_mib_is_not_published(self): host = FakeHost() host.reply = { "data": base64.b64encode(IMAGE + b"\0" * (5 * 1024 * 1024)).decode(), "mime_type": "image/png", } with Workspace() as root: with self.assertRaises(ValueError): run(host, lambda imagegen: imagegen.generate("x", output="big.png")) self.assertEqual(files(root), {}) def test_hook_rewrites_are_checked_before_the_image_routes(self): rewrite: dict[str, object] = {} class Rewriting(FakeHost): async def __call__(self, route, args): if route == "hook.call": self.calls.append((route, args)) changed = json.loads(args["arguments"]) changed.update(rewrite) return {"arguments": json.dumps(changed)} return await super().__call__(route, args) with Workspace(): changes: list[dict[str, object]] = [ {"references": ["transcript:9223372036854775808:0"]}, {"references": ["transcript:1:0"] * 6}, {"output": "x" * 32769 + ".png"}, {"prompt": "x" * 32769}, {"provider": ""}, {"provider": 123}, {"provider": "x" * 129}, {"provider": "é" * 65}, ] for change in changes: rewrite = change with self.subTest(change=str(change)[:60]): host = self.refused_before_host( lambda imagegen: imagegen.generate("bounded"), Rewriting() ) self.assertEqual(host.calls[0][0], "hook.call") rewrite = {"after": 9223372036854775808} self.refused_before_host( lambda imagegen: imagegen.references(), Rewriting() ) rewrite = {"prompt": "valid prompt rewritten by hook"} host = Rewriting() run(host, lambda imagegen: imagegen.generate("original prompt")) [(_, generate)] = [c for c in host.calls if c[0] == "imagegen.generate"] self.assertEqual(generate["prompt"], "valid prompt rewritten by hook") if __name__ == "__main__": unittest.main()