Fix ComfyUI API Returning Identical Cached Frames in Batches
Prompt executed in 0.02 seconds (cached) | All 10 batch outputs have identical SHA-256 hash OR every queued shot animates the final uploaded input image Your automated ComfyUI API script loops through 10 seeds or 8 storyboard shots, completes suspiciously fast (under 0.1 seconds per job), and downloads 10 byte-for-byte identical images or videos—or renders every shot in the batch using only the very last opening keyframe.
Four ComfyUI execution-cache traps: (1) patching inputs.seed on graphs that use SamplerCustomAdvanced + RandomNoise (which reads inputs.noise_seed); (2) expecting browser-only control_after_generate="randomize" to work over the headless /prompt API; (3) overwriting one shared LoadImage filename (current.png) across concurrent queued jobs; (4) mutating one shared Python dictionary without deepcopy or unique filename_prefix values.
Copy-Paste Verified Fix
# Cache-safe, race-free ComfyUI API batch helper (Python stdlib only)
cat <<'PY' > comfy_batch_patch.py
import copy, hashlib, json, mimetypes, os, sys, uuid, urllib.request
COMFY_URL = os.environ.get("COMFY_URL", "http://127.0.0.1:8188").rstrip("/")
def upload_unique_image(local_path):
raw = open(local_path, "rb").read()
digest = hashlib.sha256(raw).hexdigest()[:8]
stem, ext = os.path.splitext(os.path.basename(local_path))
unique_name = f"{stem}_{digest}{ext or '.png'}"
boundary = f"----ComfyBoundary{uuid.uuid4().hex}"
mime = mimetypes.guess_type(unique_name)[0] or "image/png"
body = (
f"--{boundary}
"
f'Content-Disposition: form-data; name="image"; filename="{unique_name}"
'
f"Content-Type: {mime}
"
).encode() + raw + (
f"
--{boundary}
"
f'Content-Disposition: form-data; name="overwrite"
true
'
f"--{boundary}--
"
).encode()
req = urllib.request.Request(
f"{COMFY_URL}/upload/image",
data=body,
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())["name"]
def build_unique_job(template_graph, seed, remote_image_name, output_prefix):
job = copy.deepcopy(template_graph)
patched_seeds = 0
for nid, node in job.items():
ctype = node.get("class_type", "")
inputs = node.get("inputs", {})
# Strip UI-only widget metadata if accidentally exported
inputs.pop("control_after_generate", None)
if ctype == "RandomNoise" or "noise_seed" in inputs:
inputs["noise_seed"] = int(seed)
patched_seeds += 1
elif "seed" in inputs:
inputs["seed"] = int(seed)
patched_seeds += 1
if ctype == "LoadImage" and remote_image_name:
inputs["image"] = remote_image_name
if ctype in ("SaveImage", "SaveVideo", "VHS_VideoCombine") and "filename_prefix" in inputs:
inputs["filename_prefix"] = output_prefix
if patched_seeds == 0:
raise ValueError("No seed or noise_seed node found in template graph—batch would cache-collide!")
return job
if __name__ == "__main__":
tpl = json.load(open(sys.argv[1]))
remote = upload_unique_image(sys.argv[2]) if len(sys.argv) > 2 else None
for idx, seed in enumerate([10101, 20202, 30303], start=1):
job = build_unique_job(tpl, seed, remote, f"batch/take{idx:02d}_s{seed}")
req = urllib.request.Request(
f"{COMFY_URL}/prompt",
data=json.dumps({"prompt": job, "client_id": f"batch-{seed}"}).encode(),
headers={"Content-Type": "application/json"},
)
print(f"Take {idx} (seed {seed}):", urllib.request.urlopen(req, timeout=20).read().decode())
PY
python3 comfy_batch_patch.py workflow.api.json keyframes/shot01.png Before vs. After (Broken Pattern vs. Verified Fix)
for i, img in enumerate(shots):
upload_image(img, name="frame.png", overwrite=True) # Clobbers pending jobs!
graph["8"]["inputs"]["seed"] = 1000 + i # RandomNoise ignores "seed"!
requests.post(f"{COMFY}/prompt", json={"prompt": graph}) for i, img_path in enumerate(shots):
job = copy.deepcopy(template)
remote_name = upload_hashed_png(img_path) # e.g. shot01_9f2a1c4b.png
patch_all_seeds(job, explicit_seed=42000 + i) # Patches both seed & noise_seed
patch_load_image_and_prefix(job, remote_name, f"batch/shot{i:02d}_s{42000+i}")
post_prompt(job) Why this works: Content-hashed uploads eliminate race conditions in queue_pending, while patching both seed and noise_seed on a deep-copied graph forces ComfyUI to compute a fresh cache signature for every shot.
Why This Failure Happens in Real Pipelines
ComfyUI executes workflows through a content-addressed DAG cache: before running any node, the server hashes that node’s class_type, scalar inputs, and upstream node signatures. If nothing changed from the previous prompt, ComfyUI skips sampling entirely and finishes in 10–30 milliseconds. Modern DiT workflows (FLUX, Wan 2.2, LTX-2) overwhelmingly replace legacy KSampler with SamplerCustomAdvanced paired with a RandomNoise node whose seed field is named noise_seed rather than seed. When a batch script sets node["inputs"]["seed"] = new_seed on a RandomNoise node—or assumes the browser UI’s control_after_generate: "randomize" widget runs server-side—ComfyUI ignores the unrecognized field, hashes the exact same static integer, and replays the cached render over and over.
A second devastating batch bug hits Image-to-Video queues when scripts upload every opening frame to the same filename using POST /upload/image with overwrite=true (for instance overwriting input.png on every loop iteration). Because POST /prompt returns immediately as soon as a job enters queue_pending, looping through Shots 1 to 8 in two seconds overwrites ComfyUI/input/input.png eight times BEFORE Shot 1 even finishes loading weights. When Shot 1 through Shot 7 eventually start executing on the GPU, LoadImage reads Shot 8’s image off disk for every single clip.
Eliminating silent cache duplicates takes three deterministic safeguards in your batch dispatcher: deep-copy the template graph on every iteration, upload every input still under a content-hashed unique filename (shot01_<sha256_8>.png), dynamically patch every RandomNoise (noise_seed), KSampler / KSamplerAdvanced (seed), and SaveImage / SaveVideo (filename_prefix) node, and verify output file SHA-256 uniqueness before marking the batch green.
Step-by-Step Resolution & Verification
- 01
Audit exact seed field names inside your exported API JSON
Inspect your .api.json file for RandomNoise ("noise_seed") versus KSampler ("seed") nodes, and confirm your batch script raises an error if zero seed inputs are patched on any job.
- 02
Replace fixed upload names with content-hashed filenames
Hash each opening PNG with SHA-256 (for example shot01_9f2a1c4b.png) before uploading via POST /upload/image so concurrent pending jobs in ComfyUI never overwrite each other’s LoadImage input file.
- 03
Assign unique filename_prefix strings and verify SHA-256 uniqueness post-batch
Stamp shot ID and seed directly into SaveImage / SaveVideo filename_prefix (batch/shot01_s10101), then run the shasum uniqueness check across downloaded artifacts before passing files into FFmpeg conform.
shasum -a 256 renders/*.mp4 renders/*.png 2>/dev/null | awk '{print $1}' | sort | uniq -d | wc -l 0 # Zero duplicate SHA-256 hashes across all batch takes (any number > 0 flags a cached duplicate) How to Prevent This Error From Recurring
Never trust browser UI randomize or increment widgets in API JSON
Always generate explicit 32-bit or 64-bit integer seeds in your Python or Node controller and record them in comfy-manifest.json so winning takes remain 100% reproducible.
Always deepcopy() workflow dictionaries inside batch loops
In async or threaded dispatchers, mutating a shared dict object corrupts queued payloads before serialization completes.
Gate batch downloads with a duplicate-hash assertion
Running a 1-line SHA-256 uniqueness check across ./renders/ catches accidental cache hits in milliseconds before you waste editing time.
Troubleshooting FAQs
- Why did ComfyUI still skip sampling after I changed the filename_prefix on SaveImage?
- ComfyUI caches every upstream node independently. Changing filename_prefix on SaveImage re-runs only SaveImage—writing the exact same cached VAEDecode tensor to a new filename on disk without touching the sampler.
- Can I pass the same seed with two different positive text prompts and still get distinct renders?
- Yes. Modifying CLIPTextEncode text changes the upstream conditioning hash and invalidates the sampler cache automatically—provided you did not accidentally mutate the wrong node ID or leave an unlinked prompt node.
- How do I check which exact node IDs hold seeds in any arbitrary ComfyUI API JSON?
- Run a quick one-liner: python3 -c "import json; g=json.load(open('wf.api.json')); print([(k,n['class_type'],[x for x in n['inputs'] if 'seed' in x]) for k,n in g.items() if any('seed' in x for x in n.get('inputs',{}))])" to list every seed-bearing node ID.
- Why does ComfyUI ignore my negative seed (-1) when sent via API?
- In ComfyUI’s web frontend, -1 is intercepted by JavaScript and replaced with a random positive integer before sending the HTTP request. Sending -1 straight to /prompt either throws a validation range error or hashes -1 identically on every call.