"""Variant rules and worker resource limits. Runs INSIDE the worker container (Pillow + app code): docker compose exec -T --index 1 worker python - < student-tests/variants_check.py """ import io import json import os import resource import subprocess import sys import tempfile import time from PIL import Image sys.path.insert(0, "/app") from app import config # noqa: E402 FAILS = [] def check(cond, msg): print(("ok " if cond else "FAIL ") + msg, flush=True) if not cond: FAILS.append(msg) def run_child(path, mem_mb=config.WORKER_CHILD_MEMORY_MB, cpu=config.JOB_TIMEOUT_SECONDS, max_pixels=config.MAX_IMAGE_PIXELS): out = tempfile.mkdtemp() def limits(): resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20)) resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 5)) start = time.monotonic() done = subprocess.run([sys.executable, "-m", "app.imageproc", path, out, str(max_pixels)], capture_output=True, preexec_fn=limits, timeout=120, env={"PATH": os.environ["PATH"], "MALLOC_ARENA_MAX": "2"}) usage = resource.getrusage(resource.RUSAGE_CHILDREN) produced = {v["name"]: v for v in json.loads(done.stdout)} if done.returncode == 0 else {} return done.returncode, produced, time.monotonic() - start, usage.ru_maxrss / 1024 def save(img, fmt, **kw): path = tempfile.mktemp(suffix="." + fmt.lower()) img.save(path, fmt, **kw) return path def dims(v): return v["width"], v["height"] def real(v): with Image.open(v["file"]) as im: return im.format, im.size, "exif" in im.info, im # 1. fixture 320x200 -> 256x160, crop 128, optimized not upscaled rc, p, _, _ = run_child("/app/tests/fixtures/sample.png" if os.path.exists("/app/tests/fixtures/sample.png") else save(Image.new("RGB", (320, 200), "red"), "PNG")) check(rc == 0 and dims(p["thumbnail"]) == (256, 160), "320x200 -> thumbnail 256x160") check(dims(p["crop"]) == (128, 128), "crop 128x128") check(dims(p["optimized"]) == (320, 200) and real(p["optimized"])[0] == "WEBP", "optimized WebP 320x200, no upscale") check(real(p["thumbnail"])[0] == "JPEG" and real(p["crop"])[0] == "JPEG", "thumbnail/crop are JPEG") # 2. small source: no upscale for thumbnail, upscale allowed for crop rc, p, _, _ = run_child(save(Image.new("RGB", (40, 10), "blue"), "PNG")) check(dims(p["thumbnail"]) == (40, 10) and dims(p["crop"]) == (128, 128), "40x10: thumbnail 40x10, crop 128x128") # 3. extreme aspect ratio: floor rounding, minimum 1 px rc, p, _, _ = run_child(save(Image.new("RGB", (3000, 2), "blue"), "PNG")) check(dims(p["thumbnail"]) == (256, 1) and dims(p["optimized"]) == (1280, 1), "3000x2 -> 256x1 / 1280x1 (min 1px)") rc, p, _, _ = run_child(save(Image.new("RGB", (1001, 999), "blue"), "PNG")) check(dims(p["thumbnail"]) == (256, 255), "1001x999 -> 256x255 (floor)") # 4. EXIF orientation 6 (rotate 90): stored 400x200 -> upright 200x400 -> thumbnail 128x256; EXIF stripped exif = Image.Exif() exif[0x0112] = 6 img = Image.new("RGB", (400, 200), "white") img.paste((255, 0, 0), (0, 0, 200, 200)) # left half red rc, p, _, _ = run_child(save(img, "JPEG", exif=exif.tobytes(), quality=95)) fmt, size, has_exif, im = real(p["thumbnail"]) check(size == (128, 256), "EXIF orientation applied: 400x200 (o=6) -> 128x256") with Image.open(p["thumbnail"]["file"]) as t: top = t.convert("RGB").getpixel((64, 20)) check(top[0] > 200 and top[1] < 80, "rotated content: red half on top after orientation 6") check(not has_exif and "exif" not in Image.open(p["optimized"]["file"]).info, "EXIF removed from thumbnail/optimized") # 5. alpha composited on white for JPEG, kept for WebP rgba = Image.new("RGBA", (100, 100), (0, 0, 0, 0)) rc, p, _, _ = run_child(save(rgba, "PNG")) with Image.open(p["thumbnail"]["file"]) as t: px = t.convert("RGB").getpixel((50, 50)) check(min(px) >= 250, "transparent PNG -> white JPEG thumbnail") check(Image.open(p["optimized"]["file"]).mode == "RGBA", "WebP optimized keeps alpha") # 6. 16-bit grayscale PNG, CMYK JPEG, palette PNG rc16, _, _, _ = run_child(save(Image.new("I;16", (300, 300), 40000), "PNG")) rcc, _, _, _ = run_child(save(Image.new("CMYK", (300, 300), (0, 255, 0, 0)), "JPEG")) rcp, _, _, _ = run_child(save(Image.new("P", (300, 300), 3), "PNG", transparency=3)) check(rc16 == 0 and rcc == 0 and rcp == 0, "16-bit PNG, CMYK JPEG, palette+transparency PNG are processed") # 7. limits: pixels (exit 4), not an image (exit 3), memory (exit 5), CPU (SIGXCPU) rc, _, _, _ = run_child(save(Image.new("RGB", (100, 100)), "PNG"), max_pixels=5000) check(rc == 4, "pixel limit enforced before decode -> image_too_large (exit 4)") junk = tempfile.mktemp() open(junk, "wb").write(b"\x89PNG\r\n\x1a\n" + os.urandom(2000)) rc, _, _, _ = run_child(junk) check(rc == 3, "corrupted PNG -> invalid_image (exit 3)") big = save(Image.new("RGB", (6000, 6000), "green"), "PNG") rc, _, _, _ = run_child(big, mem_mb=160) check(rc == 5, "36 Mpx PNG with 160 MiB address-space limit -> image_too_complex (exit 5), got %s" % rc) # 8. largest allowed inputs under the real limits: time and child peak RSS for name, w, h, fmt in (("png", 7900, 5000, "PNG"), ("jpeg", 7900, 5000, "JPEG")): noise = Image.effect_noise((w // 10, h // 10), 60).convert("RGB").resize((w, h)) path = save(noise, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 1})) rc, p, secs, rss = run_child(path) check(rc == 0 and dims(p["thumbnail"]) == (256, 162), "%.1f Mpx %s (%d MB file) ok in %.1fs, peak child RSS %.0f MiB" % (w * h / 1e6, name.upper(), os.path.getsize(path) >> 20, secs, rss)) if fmt == "PNG": rc, _, _, _ = run_child(path, cpu=0) check(rc == -24, "CPU limit exhausted -> SIGXCPU (worker: permanent image_too_complex), got %s" % rc) print("RESULT:", "PASS" if not FAILS else "FAIL %s" % FAILS) sys.exit(1 if FAILS else 0)