Compare commits

..
Author SHA1 Message Date
Kiko
dd3d432573 raven-image --margin: restore the IHDR size bound before any header-sized allocation, with the 2**32-1 test that pins it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:34:01 +00:00
Kiko
7b5d8bab1d raven-image --margin: pin the BG_TOL boundary, the repaint colour, every decoder refusal; drop two guards no behaviour depends on
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:24:15 +00:00
Kiko
00794e4eee raven-image --margin: Soul pass fixes: bg-referenced backdrop, interior/size validation, -n exit codes, CRC and size caps, tests that fail on mutation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:51:49 +00:00
Kiko
d0596fdc11 raven-image: --margin pins the border band during diffusion; measures, repaints and fails loudly (exit 65); --alpha keys the backdrop
Core nodes only (EmptyImage > VAEEncode > SetLatentNoiseMask, mask by SolidMask+MaskComposite): the sampler re-imposes the flat band at every step. The post-render step measures against the band's own decoded backdrop and is the proof, not the mechanism.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:11:34 +00:00
3 changed files with 13 additions and 139 deletions

View file

@ -17,22 +17,6 @@ raven-image "a full caption" --no-enhance -o out.png # skip the
Prints one line per image (`path seed size seconds`). Defaults: 1536x1024, random Prints one line per image (`path seed size seconds`). Defaults: 1536x1024, random
seed, 900 s wait per image. seed, 900 s wait per image.
**Record.** Next to every image the client writes `<image>.json` (`out.png` gets `out.json`; `-n 4` gets one per image), in
every mode: client and graph sha256, model file names, size, seed, steps, cfg, sampler, scheduler, `enhance`, `prompt` (as
typed), `caption` (the exact text the encoder saw), `vision` (whether `--vision` fed the refs to the encoder), `encoder` (the node id and class
that consumed the prompt: `CLIPTextEncode` or `TextEncodeQwenImageEditPlus`), `refs` (each as `{name, sha256}` of its content), `margin`, `bg`, seconds, UTC time. With the upsampler on
the caption is read from ComfyUI's `PreviewAny` output (node 20, on the upsampler's output), and a render whose history lacks it
fails without writing; with `--no-enhance` the caption is the prompt. `--out` may not end in `.json`.
```
raven-image --caption-only "small private space yacht" --size 1536x1024 # prints the caption, renders nothing, writes nothing
```
`--caption-only` runs only nodes 10, 11 and 20 (about 9 s, no image) and prints what the upsampler made of the prompt, so a
person or a model can read it before Raven spends a render. It matters: that prompt came back as a boat on open water, an
attractor visible only in the caption. It refuses `--no-enhance`, `--ref` and `--margin`; exit codes are as for a render.
Images stay `PreviewImage`; the client never saves into Raven's output history.
``` ```
raven-image --ref sheet.png "Using the character from <ref_image_0>, show her seated at a desk typing, ..." --size 1024x1024 -o out.png raven-image --ref sheet.png "Using the character from <ref_image_0>, show her seated at a desk typing, ..." --size 1024x1024 -o out.png
raven-image --ref a.png --ref b.png --vision "<ref_image_0> ... <ref_image_1> ..." -o out.png raven-image --ref a.png --ref b.png --vision "<ref_image_0> ... <ref_image_1> ..." -o out.png

View file

@ -5,7 +5,7 @@ Talks to ComfyUI's own API: POST /prompt, poll GET /history/<id>, GET /view,
POST /free when the queue is empty. No retry loop: an unreachable Raven exits 75 POST /free when the queue is empty. No retry loop: an unreachable Raven exits 75
with "Raven may be busy or off". See README.md next to this file. with "Raven may be busy or off". See README.md next to this file.
""" """
import argparse, datetime, hashlib, json, math, os, random, re, stat, struct, sys, time, urllib.error, urllib.parse, urllib.request, zlib import argparse, json, math, os, random, re, stat, struct, sys, time, urllib.error, urllib.parse, urllib.request, zlib
BASE = os.environ.get("RAVEN_URL", "http://10.77.0.4:8190") BASE = os.environ.get("RAVEN_URL", "http://10.77.0.4:8190")
EX_BUSY = 75 # EX_TEMPFAIL: no answer from Raven (off, busy, a read timeout mid-render, or a lock screen after a reboot); try again later, by hand EX_BUSY = 75 # EX_TEMPFAIL: no answer from Raven (off, busy, a read timeout mid-render, or a lock screen after a reboot); try again later, by hand
@ -115,7 +115,6 @@ def build(name, text, w, h, seed, enhance, refs=(), vision=False):
if enhance: if enhance:
d = math.gcd(w, h) d = math.gcd(w, h)
g["11"]["inputs"]["prompt"] = text if refs else f"TARGET CANVAS: {w // d}:{h // d}\n{text}" g["11"]["inputs"]["prompt"] = text if refs else f"TARGET CANVAS: {w // d}:{h // d}\n{text}"
g["20"] = {"class_type": "PreviewAny", "inputs": {"source": ["11", 0]}} # the caption, in history beside the image
else: else:
for k in ("10", "11"): for k in ("10", "11"):
del g[k] del g[k]
@ -257,11 +256,7 @@ def clear_edges(png, pct, alpha=False, bg=None):
return png_encode(w, h, bpp, rows, keep), back, clip, band return png_encode(w, h, bpp, rows, keep), back, clip, band
def render(g, timeout, caption_only=False): def render(g, timeout):
"""Run graph g; returns (png, caption). The caption is node 20's PreviewAny text, the upsampler's exact output, else the
text node 4 was given. caption_only: g holds no image node, png is None."""
enc = g.get("4", {}).get("inputs", {})
given = enc.get("text", enc.get("prompt"))
try: try:
r = json.loads(call("POST", "/prompt", {"prompt": g, "client_id": "raven-image"})) r = json.loads(call("POST", "/prompt", {"prompt": g, "client_id": "raven-image"}))
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
@ -277,43 +272,15 @@ def render(g, timeout, caption_only=False):
if st.get("status_str") == "error": if st.get("status_str") == "error":
msgs = [m for m in st.get("messages", []) if m[0] == "execution_error"] msgs = [m for m in st.get("messages", []) if m[0] == "execution_error"]
sys.exit(f"raven-image: render failed: {json.dumps(msgs[-1][1] if msgs else st)[:800]}") sys.exit(f"raven-image: render failed: {json.dumps(msgs[-1][1] if msgs else st)[:800]}")
outs = h.get("outputs", {}) for out in h.get("outputs", {}).values():
text = outs.get("20", {}).get("text")
caption = text[0] if text else None if "20" in g else given if isinstance(given, str) else None
if caption_only and caption is not None:
return None, caption
for out in () if caption_only else outs.values():
for im in out.get("images", []): for im in out.get("images", []):
if caption is None: # the record must hold the exact prompt: no caption, no image
sys.exit("raven-image: history has no caption from the upsampler (node 20); nothing written")
q = urllib.parse.urlencode({"filename": im["filename"], "subfolder": im["subfolder"], "type": im["type"]}) q = urllib.parse.urlencode({"filename": im["filename"], "subfolder": im["subfolder"], "type": im["type"]})
return call("GET", "/view?" + q, timeout=120), caption return call("GET", "/view?" + q, timeout=120)
if st.get("completed"): if st.get("completed"):
sys.exit("raven-image: completed with no caption" if caption_only else "raven-image: render completed with no image") sys.exit("raven-image: render completed with no image")
sys.exit(f"raven-image: no image after {timeout}s (prompt {pid} may still be running on Raven)") sys.exit(f"raven-image: no image after {timeout}s (prompt {pid} may still be running on Raven)")
def sha256(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
def write_record(path, a, g, seed, w, h, caption, bg, seconds, ref_data):
"""The image's record, beside it: what Raven was asked and the exact text its encoder saw."""
s = g["7"]["inputs"]
rec = {"client_sha256": sha256(os.path.realpath(__file__)), "graph": a.graph,
"graph_sha256": sha256(os.path.join(graph_dir(), a.graph + ".json")),
"models": {k: n["inputs"][f] for k, n in g.items() for f in ("unet_name", "clip_name", "vae_name") if f in n.get("inputs", {})},
"size": f"{w}x{h}", "seed": seed, "steps": s["steps"], "cfg": s["cfg"], "sampler": s["sampler_name"], "scheduler": s["scheduler"],
"enhance": "11" in g, "prompt": a.prompt, "caption": caption, "refs": [{"name": safe_name(r), "sha256": hashlib.sha256(d).hexdigest()} for r, d in zip(a.ref, ref_data)],
"vision": a.vision, "encoder": {"node": "4", "class_type": g["4"]["class_type"]}, "margin": a.margin,
"bg": "%06x" % bg if a.margin else None, "seconds": round(seconds, 1),
"utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
with open(path, "w", encoding="utf-8") as f:
json.dump(rec, f, ensure_ascii=False, indent=1)
f.write(chr(10))
def free_if_idle(): def free_if_idle():
q = json.loads(call("GET", "/queue")) q = json.loads(call("GET", "/queue"))
if not q.get("queue_running") and not q.get("queue_pending"): if not q.get("queue_running") and not q.get("queue_pending"):
@ -342,8 +309,6 @@ def main():
ap.add_argument("--alpha", action="store_true", help="--margin: key the backdrop connected to the band to transparent (RGBA output)") ap.add_argument("--alpha", action="store_true", help="--margin: key the backdrop connected to the band to transparent (RGBA output)")
ap.add_argument("--max-clip", type=float, default=0.5, metavar="PCT", help="--margin: largest %% of the band that may need clearing (default 0.5)") ap.add_argument("--max-clip", type=float, default=0.5, metavar="PCT", help="--margin: largest %% of the band that may need clearing (default 0.5)")
ap.add_argument("--no-enhance", action="store_true", help="send the prompt as the caption, skip the upsampler") ap.add_argument("--no-enhance", action="store_true", help="send the prompt as the caption, skip the upsampler")
ap.add_argument("--caption-only", action="store_true",
help="run only the upsampler, print the caption it makes of the prompt and render nothing (no file written)")
ap.add_argument("--timeout", type=int, default=900, help="seconds to wait per image") ap.add_argument("--timeout", type=int, default=900, help="seconds to wait per image")
ap.add_argument("--keep-loaded", action="store_true", help="skip POST /free at the end") ap.add_argument("--keep-loaded", action="store_true", help="skip POST /free at the end")
a = ap.parse_args() a = ap.parse_args()
@ -353,10 +318,6 @@ def main():
ap.error("--ref and graph flux3-klein-edit go together (the edit graph needs refs, other graphs cannot take them)") ap.error("--ref and graph flux3-klein-edit go together (the edit graph needs refs, other graphs cannot take them)")
if a.margin is not None and not 0 < a.margin <= 40: if a.margin is not None and not 0 < a.margin <= 40:
ap.error("--margin is a percentage above 0 and at most 40") ap.error("--margin is a percentage above 0 and at most 40")
if a.caption_only and (a.no_enhance or a.ref or a.margin is not None):
ap.error("--caption-only previews the upsampler and cannot be combined with --no-enhance, --ref or --margin")
if os.path.splitext(a.out)[1].lower() == ".json":
ap.error("--out must not end in .json: that name is the image's record")
if a.alpha and not a.margin: if a.alpha and not a.margin:
ap.error("--alpha needs --margin") ap.error("--alpha needs --margin")
if not re.fullmatch(r"#?[0-9a-fA-F]{6}", a.bg): if not re.fullmatch(r"#?[0-9a-fA-F]{6}", a.bg):
@ -374,13 +335,6 @@ def main():
dirty = broken = 0 dirty = broken = 0
try: try:
call("GET", "/system_stats", timeout=5) call("GET", "/system_stats", timeout=5)
if a.caption_only:
g = build(a.graph, a.prompt, w, h, seed0, True)
_, caption = render({k: g[k] for k in ("10", "11", "20")}, a.timeout, True)
print(caption)
if not a.keep_loaded:
print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded", file=sys.stderr)
return
refs = [upload(r, d) for r, d in zip(a.ref, ref_data)] refs = [upload(r, d) for r, d in zip(a.ref, ref_data)]
for i in range(a.n): for i in range(a.n):
seed = seed0 + i seed = seed0 + i
@ -388,7 +342,7 @@ def main():
g = build(a.graph, a.prompt, w, h, seed, not a.no_enhance, refs, a.vision) g = build(a.graph, a.prompt, w, h, seed, not a.no_enhance, refs, a.vision)
if a.margin: if a.margin:
pin_edges(g, w, h, a.margin, bg) pin_edges(g, w, h, a.margin, bg)
png, caption = render(g, a.timeout) png = render(g, a.timeout)
note = "" note = ""
if a.margin: if a.margin:
try: try:
@ -405,7 +359,6 @@ def main():
path = a.out if a.n == 1 else f"{root}-{i + 1}{ext}" path = a.out if a.n == 1 else f"{root}-{i + 1}{ext}"
with open(path, "wb") as f: with open(path, "wb") as f:
f.write(png) f.write(png)
write_record(os.path.splitext(path)[0] + ".json", a, g, seed, w, h, caption, bg, time.time() - t, ref_data)
print(f"{path} seed={seed} {w}x{h} {time.time() - t:.0f}s{note}", flush=True) print(f"{path} seed={seed} {w}x{h} {time.time() - t:.0f}s{note}", flush=True)
if not a.keep_loaded: if not a.keep_loaded:
print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded") print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded")

View file

@ -1,14 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Offline test of client/raven-image against an in-process fake ComfyUI on 127.0.0.1. """Offline test of client/raven-image against an in-process fake ComfyUI on 127.0.0.1.
Asserts on the POSTed /prompt graph and the multipart upload. Needs only python3. Usage: test-raven-image.py [repo-root]""" Asserts on the POSTed /prompt graph and the multipart upload. Needs only python3. Usage: test-raven-image.py [repo-root]"""
import hashlib, json, os, re, subprocess, sys, tempfile, threading import json, os, subprocess, sys, tempfile, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.dirname(os.path.abspath(__file__))) root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
tool = os.path.join(root, "client", "raven-image") tool = os.path.join(root, "client", "raven-image")
PNG = b"\x89PNG\r\n\x1a\n" + b"\0" * 32 PNG = b"\x89PNG\r\n\x1a\n" + b"\0" * 32
CAPTION = "Full-color photograph, a small private space yacht moored at a dock, soft light." seen = {"uploads": [], "prompts": [], "view": PNG}
seen = {"uploads": [], "prompts": [], "view": PNG, "drop20": False, "free": 0}
class H(BaseHTTPRequestHandler): class H(BaseHTTPRequestHandler):
@ -18,10 +17,8 @@ class H(BaseHTTPRequestHandler):
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body) self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
def do_GET(self): def do_GET(self):
if self.path.startswith("/history/"): if self.path.startswith("/history/"):
g, outs = seen["prompts"][-1], {} # like ComfyUI, report only the output nodes the posted graph has self.send(json.dumps({self.path[9:]: {"status": {"completed": True}, "outputs": {"9": {"images": [
if "9" in g: outs["9"] = {"images": [{"filename": "x.png", "subfolder": "", "type": "temp"}]} {"filename": "x.png", "subfolder": "", "type": "temp"}]}}}}).encode())
if "20" in g and not seen["drop20"]: outs["20"] = {"text": [CAPTION]}
self.send(json.dumps({self.path[9:]: {"status": {"completed": True}, "outputs": outs}}).encode())
elif self.path.startswith("/view"): self.send(seen["view"], "image/png") elif self.path.startswith("/view"): self.send(seen["view"], "image/png")
elif self.path == "/queue": self.send(b'{"queue_running":[],"queue_pending":[]}') elif self.path == "/queue": self.send(b'{"queue_running":[],"queue_pending":[]}')
else: self.send(b"{}") else: self.send(b"{}")
@ -29,7 +26,6 @@ class H(BaseHTTPRequestHandler):
body = self.rfile.read(int(self.headers["Content-Length"])) body = self.rfile.read(int(self.headers["Content-Length"]))
if self.path == "/upload/image": if self.path == "/upload/image":
seen["uploads"].append(body); self.send(json.dumps({"name": "stored%d.png" % len(seen["uploads"])}).encode()) seen["uploads"].append(body); self.send(json.dumps({"name": "stored%d.png" % len(seen["uploads"])}).encode())
elif self.path == "/free": seen["free"] += 1; self.send(b"{}")
elif self.path == "/prompt": elif self.path == "/prompt":
seen["prompts"].append(json.loads(body)["prompt"]); self.send(b'{"prompt_id":"p1"}') seen["prompts"].append(json.loads(body)["prompt"]); self.send(b'{"prompt_id":"p1"}')
else: self.send(b"{}") else: self.send(b"{}")
@ -49,13 +45,11 @@ def check(cond, what):
fails.append(what); print("FAIL:", what) fails.append(what); print("FAIL:", what)
def run(*args, url=url, keep=True): def run(*args, url=url):
seen["uploads"].clear(); seen["prompts"].clear(); seen["free"] = 0 seen["uploads"].clear(); seen["prompts"].clear()
env = dict(os.environ, RAVEN_URL=url) env = dict(os.environ, RAVEN_URL=url)
p = subprocess.run([sys.executable, "-I", tool, *(["--keep-loaded"] if keep else []), "-o", os.path.join(tmp, "o.png"), *args], p = subprocess.run([sys.executable, "-I", tool, "--keep-loaded", "-o", os.path.join(tmp, "o.png"), *args],
capture_output=True, text=True, env=env, timeout=120) capture_output=True, text=True, env=env, timeout=120)
for g in seen["prompts"]: # images stay PreviewImage and never reach Deru's playground history
check(all(n["class_type"] != "SaveImage" for n in g.values()), f"no SaveImage in the posted graph ({' '.join(args)[:60]})")
return p, (seen["prompts"][0] if seen["prompts"] else None) return p, (seen["prompts"][0] if seen["prompts"] else None)
@ -330,63 +324,6 @@ seen["view"] = mkpng(160, 160, lambda x, y: RED if x < 12 else BG)
p, g = run("--margin", "6", "--bg", "1ec85a", "-n", "2", "--size", "160x160", "--no-enhance", "cap") p, g = run("--margin", "6", "--bg", "1ec85a", "-n", "2", "--size", "160x160", "--no-enhance", "cap")
check(p.returncode == 65 and p.stdout.count("DIRTY") == 2, f"-n 2 both dirty: two reports, exit 65 ({p.returncode})") check(p.returncode == 65 and p.stdout.count("DIRTY") == 2, f"-n 2 both dirty: two reports, exit 65 ({p.returncode})")
# the record beside each image, and --caption-only
side = os.path.join(tmp, "o.json")
def has(name): return name in os.listdir(tmp) # os.path.exists is stubbed earlier in this file
def record(*args):
if has("o.json"): os.remove(side)
p, g = run(*args)
return p, g, (json.load(open(side, encoding="utf-8")) if has("o.json") else None)
p, g, rec = record("--seed", "42", "--size", "512x768", "yacht")
check(p.returncode == 0 and rec is not None and "20" in g, f"sidecar: written beside the image ({p.stderr[-200:]})")
if rec:
check(g["20"] == {"class_type": "PreviewAny", "inputs": {"source": ["11", 0]}}, "sidecar: node 20 is PreviewAny on the upsampler")
check(rec["caption"] == CAPTION and rec["prompt"] == "yacht", "sidecar: caption is the upsampler's text, prompt the argument")
check(rec["seed"] == 42 and rec["size"] == "512x768" and rec["enhance"] is True, "sidecar: seed, size, enhance")
check((rec["steps"], rec["cfg"], rec["sampler"], rec["scheduler"]) == (16, 1, "euler", "simple"), "sidecar: sampler settings")
check(rec["graph"] == "flux3-klein" and rec["graph_sha256"] == hashlib.sha256(open(os.path.join(root, "client", "graphs", "flux3-klein.json"), "rb").read()).hexdigest(), "sidecar: graph name and sha256")
check(rec["client_sha256"] == hashlib.sha256(open(tool, "rb").read()).hexdigest(), "sidecar: client sha256")
check(rec["models"] == {"1": "flux3-image-klein-int8-convrot.safetensors", "2": "qwen3vl_4b_int8_convrot.safetensors",
"3": "flux2-vae.safetensors", "10": "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors"}, "sidecar: models from the loader nodes")
check(rec["refs"] == [] and rec["margin"] is None and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", rec["utc"]), "sidecar: no refs, no margin, utc stamp")
p, g, rec = record("--no-enhance", "--seed", "7", "plain cap")
check(rec is not None and rec["caption"] == "plain cap" and rec["enhance"] is False and "20" not in g and "10" not in rec["models"], "no-enhance sidecar: caption is the prompt, no node 20")
p, g, rec = record("--ref", refs[0], "--no-enhance", "cap <ref_image_0>")
check(rec is not None and rec["refs"] == [{"name": "r0.png", "sha256": hashlib.sha256(PNG).hexdigest()}] and rec["graph"] == "flux3-klein-edit"
and rec["vision"] is False and rec["encoder"] == {"node": "4", "class_type": "CLIPTextEncode"}, "edit sidecar: ref name and content hash, edit graph, no vision")
p, g, rec = record("--ref", refs[0], "--vision", "cap <ref_image_0>")
check(rec is not None and rec["caption"] == CAPTION and "20" in g and rec["vision"] is True
and rec["encoder"] == {"node": "4", "class_type": "TextEncodeQwenImageEditPlus"}, "vision edit sidecar: upsampler caption, vision on, vision encoder")
check(rec is not None and 2 <= rec["seconds"] < 120, f"sidecar: seconds recorded ({rec and rec.get('seconds')})")
# upsampler on but node 20 missing from history: fail loudly, write nothing
seen["drop20"] = True
for f in ("o.png", "o.json"):
if has(f): os.remove(os.path.join(tmp, f))
p, g = run("yacht")
check(p.returncode != 0 and "no caption" in p.stderr and not has("o.png") and not has("o.json") and "Traceback" not in p.stderr, f"no caption in history: fails, writes nothing ({p.returncode} {p.stderr[-160:]})")
p, g = run("--caption-only", "yacht")
check(p.returncode != 0 and p.stdout == "", "caption-only with no caption in history: fails")
seen["drop20"] = False
p, g = run("-n", "2", "--no-enhance", "cap")
check(has("o-1.json") and has("o-2.json"), "-n 2: one sidecar per image")
refused(["-o", os.path.join(tmp, "x.json"), "cap"], "must not end in .json", "--out .json")
for f in ("o.png", "o.json"):
if has(f): os.remove(os.path.join(tmp, f))
p, g = run("--caption-only", "--seed", "3", "yacht")
check(p.returncode == 0 and p.stdout == CAPTION + chr(10) and p.stderr == "" and seen["free"] == 0, f"caption-only: stdout is the caption ({p.stdout!r} {p.stderr[-200:]})")
check(g is not None and sorted(g) == ["10", "11", "20"], f"caption-only: graph is nodes 10, 11, 20 only ({sorted(g or [])})")
check(g is not None and g["11"]["inputs"]["prompt"] == "TARGET CANVAS: 3:2\nyacht", "caption-only: upsampler prompt as a render would send it")
check(not has("o.png") and not has("o.json"), "caption-only: no file written")
p, g = run("--caption-only", "yacht", keep=False)
check(p.returncode == 0 and p.stdout == CAPTION + chr(10) and seen["free"] == 1 and "freed" in p.stderr, f"caption-only frees Raven's VRAM, on stderr ({seen['free']} {p.stderr[-100:]})")
for args, w in ((["--no-enhance"], "--no-enhance"), (["--ref", refs[0]], "--ref"), (["--margin", "5"], "--margin")):
refused(["--caption-only", *args, "cap"], "cannot be combined", "caption-only with " + w)
# a margin render records its margin and backdrop beside the cleared image
seen["view"] = mkpng(160, 160, lambda x, y: BG)
p, g, rec = record("--margin", "6", "--bg", "1ec85a", "--size", "160x160", "cap")
check(p.returncode == 0 and rec is not None and rec["margin"] == 6 and rec["bg"] == "1ec85a", f"margin sidecar: margin and bg ({p.stderr[-200:]})")
srv.shutdown() srv.shutdown()
print(f"{count[0] - len(fails)}/{count[0]} checks passed") print(f"{count[0] - len(fails)}/{count[0]} checks passed")
sys.exit(1 if fails else 0) sys.exit(1 if fails else 0)