Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): a restored cell that brings back the jump the repair took out is regressed, not improved
Soohong Kime9ef3e6d4643
diff --git a/docs/loop-comparison.md b/docs/loop-comparison.mdindex b867c5c..cef7dbc 100644--- a/docs/loop-comparison.md+++ b/docs/loop-comparison.md@@ -117,13 +117,15 @@ quality bounds, and [video pipeline](video-pipeline.md) for processing stages.`video-loop-repair` proposes a separate output for one damaged interior cell.It preserves the cut, metadata, normal cells, boundary cells, and actual GIF/WebPschedule. No interpolation is called. This operation has its own contract:-repair report `schema_version: 3`, comparison `schema_version: 4`,-`metric_version: source-restoration-v3`, `policy_version:-key-protected-source-copy-one-step-cap-v1`, `scope:+repair report `schema_version: 3`, comparison `schema_version: 5`,+`metric_version: source-restoration-v4`, `policy_version:+key-protected-source-copy-one-step-cap-jump-guard-v1`, `scope:processing-defect-restoration`, `operation: restore_active_cut`. The v1-comparison above is unchanged. Two unreleased drafts are not this contract:-`source-restoration-v1` copied the whole source cell and `source-restoration-v2`-never capped a pixel. Their evidence and receipts are refused, never read as v3.+comparison above is unchanged. Earlier versions are not this contract:+`source-restoration-v3` (2.39.0) made the same cell and accepted it without+[the jump guard](#the-jump-guard), and two unreleased drafts,+`source-restoration-v1` and `-v2`, copied the whole source cell and never capped+a pixel. Their evidence and receipts are refused, never read as v4.### What a restored cell is@@ -369,7 +371,8 @@ The report carries `origin`, `baseline` and `candidate` (each with its five`improved` requires that the one changed cell is byte-exact the partial copymade from the origin and the source, its coverage the source's, the candidate'sreceipt the recomputed one, at least one cleared actual fault, unchanged normal-cells and metadata bytes, and no worsening protected axis. A changed cell that+cells and metadata bytes, and no worsening protected axis, the jump around the+changed cell included. A changed cell thatis not that copy (a pixel outside the masks, a capped place left uncapped orcapped further) returns `regressed` with`changed-cell-is-not-the-verified-source-copy`; a receipt that differs returns@@ -396,6 +399,60 @@ meet them, not an exception to them. A normal cell that already carries a madeexcess is not a target and is never rewritten; `axes.key_colour.baseline`reports it as delivered.+### The jump guard++A target is a cell the jump repair replaced, and the repair replaced it because+a step into or out of the source frame at that time jumped ([loop+repair](loop-repair.md), section 2). The in-between it adopted may have melted,+and that is what restoration clears; the source frame it replaced is still the+jump. Its pixels can clear the melt and bring the jump back. `axes.jump` reads+the jump repair's own step score on the final cells of both loops:++```text+score[k] = repair.jump_scores(cells, facing, box)["score"][k] step k: cell k to cell k+1, the last to the first+facing = jump_repair.facing in the origin's loop report+box = the union box of the source's own cells (repair.union_box)+jump(c) = max(score[c - 1], score[c]) the step into cell c and the step out of it+regressed where jump(candidate) > jump(baseline) at a changed cell+```++The score is the one the jump repair picks frames by: per step, the change of+coverage over the whole box and over the hair behind the body, each over its+own median in the loop, the larger of the two. Both loops are scored on one box,+the source cells' (the jump repair reads the box of the loop as filmed), with+the facing the repair recorded. More than the baseline's is worse. No bound is+read, `JUMP_RATIO` included: the baseline is the measure. A rise is a measured+worsening, as on every other axis, so the verdict is `regressed` with+`jump:regressed`, not `unknown`, and the next independent proposal may be+tried. A fall alone does not make a candidate `improved`: that still needs a+cleared fault.++| `axes.jump` field | Meaning |+|---|---|+| `baseline`, `candidate` | Each step's score on that loop |+| `whole`, `hair` | The two parts of the scores, each with `baseline` and `candidate` |+| `facing`, `hair_box`, `box` | The recorded facing, the hair box as fractions of `box`, and `box` in cell pixels (`[left, top, right, bottom]`) |+| `cells` | Per changed cell: `cell`, `steps` (`[c - 1, c]`, cyclic), and its `baseline` and `candidate` reading |+| `status` | `regressed` when a changed cell's reading rises, `improved` when one falls and none rises, else `non_regressing` |++The jump repair records the facing it read the hair with (`video-loop+--facing`). A loop report whose repair names replaced cells but no facing, or a+facing other than `right` or `left`, cannot say which steps were read: the+request is shared `unknown` with `jump-repair-facing-unverified`. A loop whose+repair replaced no cell has no target and reads no facing; its no-op reports+`axes.jump` as `{"facing": null, "cells": [], "status": "non_regressing",+"reason": "no-jump-repaired-cell"}`.++In use, a cell the jump repair made is restored only where the in-between+jumped more than the source frame does, as when it lost coverage (a limb left a+pale ghost). Where the in-between was the smoother step and only its drawing+melted, the restored cell is `regressed` and the delivered in-between stays.++The guard reads coverage, not colour. A wrong colour in a source frame is+seen only through the jump it came with: where the in-between jumped more, the+source frame is restored with its colour, right or wrong. The comparison reads+no colour bound beyond the key colour's.+For an outline-specific UI success message, require `verdict == improved` andan `outline` entry in `cleared_faults[].faults`. `axes` contains raw baseline,reference and candidate values for outline/smear, source-relative partialdiff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex d887552..e5f9143 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -193,6 +193,9 @@ When a frame was replaced the seam gate measures the rendered cellsTo compare an active result with a final candidate after all processing, use[`video-loop-compare`](loop-comparison.md); a seam pass alone is not an improvement.+A replaced cell restored later from its source frame is compared with these+same scores around it, with the recorded `facing`: a restoration that brings+the jump back is not an improvement ([the jump guard](loop-comparison.md#the-jump-guard)).RIFE is located only when a frame is to be made. A loop with a jump and no RIFE is cut as filmedwith a warning under `--repair auto`, and fails under `--repair on` (section 1, "Without RIFE").diff --git a/scripts/dev/source_restoration_demo.py b/scripts/dev/source_restoration_demo.pyindex a164c2f..0c40539 100644--- a/scripts/dev/source_restoration_demo.py+++ b/scripts/dev/source_restoration_demo.py@@ -207,7 +207,7 @@ def write_delivered(out: Path, source: dict[str, Path]) -> tuple[dict[str, Path]"source_cut": {"source": identity, "start": 0, "length": N, "samples": list(range(N))}}report = {"kind": "sprite-gen-video-loop-report", "status": "passed", "fps": FPS, "frames_total": N,"source": identity, "cycle": {"start": 0, "length": N}, "anchor": "none",- "jump_repair": {"replaced": list(DAMAGED)}, "strip": meta, "n_out": N, "delay_ms": DELAY,+ "jump_repair": {"replaced": list(DAMAGED), "facing": "right"}, "strip": meta, "n_out": N, "delay_ms": DELAY,"note": ("synthetic stand-in for a delivered loop: cells cut by the loop recipe from drawn keyed frames; "f"cells {DAMAGED[0]} and {DAMAGED[1]} drawn as melted in-betweens (scripts/dev/source_restoration_demo.py)")}files = paths(out / "delivered")diff --git a/sprite_gen/video/restoration.py b/sprite_gen/video/restoration.pyindex cf9e480..e5133f7 100644--- a/sprite_gen/video/restoration.py+++ b/sprite_gen/video/restoration.py@@ -12,6 +12,10 @@ from it and the source, so a receipt is recomputed, never trusted.Source correspondence, proposal generation and final acceptance are separate.A failed independent proposal never hides the next one; a missing shared sourcebridge stops the operation. All quality measurements consume final pixels.++A target is a cell the jump repair replaced because a step into or out of the+source frame there jumped. Restoring that frame's pixels can restore the jump:+acceptance also reads the jump repair's own step score around the changed cell."""from __future__ import annotations@@ -31,17 +35,17 @@ from sprite_gen.frames.decontam import _cap_key_huefrom sprite_gen.frames.extract import _key_channel_split, _key_excess_field, _SPILL_FULL_MIN_TINTfrom sprite_gen.spec.runio import atomic_write_textfrom sprite_gen.util import resample-from sprite_gen.video import evidence, playback, rife, source+from sprite_gen.video import evidence, playback, repair, rife, sourcefrom sprite_gen.video.compare import KIND as COMPARISON_KIND, Loopfrom sprite_gen.video.interpolation_quality import SMEAR_WARN, OUTLINE_WARN, faults-METRIC = "source-restoration-v3"-POLICY = "key-protected-source-copy-one-step-cap-v1"+METRIC = "source-restoration-v4"+POLICY = "key-protected-source-copy-one-step-cap-jump-guard-v1"SCOPE = "processing-defect-restoration"OPERATION = "restore_active_cut"KIND = "sprite-gen-video-loop-restoration"REPAIR_SCHEMA = 3-COMPARISON_SCHEMA = 4+COMPARISON_SCHEMA = 5MAX_PROPOSALS = 3ARTIFACTS = ("strip", "meta", "report", "gif", "webp")LISTED = 256 # capped or protected pixels a report spells out; the masks always hold all of them@@ -79,6 +83,13 @@ def key_weight(rgba: Any, key: str) -> Any:return rgba[..., 3].astype(np.int64) * np.maximum(0, _key_hue(rgba, key) - _BAR)+def _jump_facing(origin: Loop) -> str | None:+ """The facing the jump repair read the origin's frames with, as its record says; None when it names none."""+ from sprite_gen.video.loop import FACINGS+ facing = (origin.source_report.get("jump_repair") or {}).get("facing")+ return facing if facing in FACINGS else None++def _source_key(src: source.Source) -> str | None:key = src.record["recipe"].get("key")if key == "auto":@@ -226,7 +237,39 @@ def _receipt(origin: Loop, src: source.Source, projection: source.Projection,"upstream_quality": "historical; final pixels require source-restoration comparison"}-def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Image], key: str) -> dict[str, Any]:+def _status(pairs: list[tuple[float, float]]) -> str:+ """One axis over (baseline, candidate) pairs where more is worse: any rise regresses it."""+ return ("regressed" if any(y > x + 1e-9 for x, y in pairs) else+ "improved" if any(y < x - 1e-9 for x, y in pairs) else "non_regressing")+++def jump(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Image], changed: list[int],+ facing: str | None) -> dict[str, Any]:+ """The jump repair's step score (`repair.jump_scores`) on the two steps into and out of each changed cell.++ Both loops are scored on one box, the source cells' union box (the jump repair reads the box of+ the loop as filmed), with the facing the repair recorded. A cell's reading is the larger of its+ two steps' scores. More than the baseline's is worse; no bound is read. None for `facing`+ only where no cell can change (`chain`): nothing is scored.+ """+ if facing is None:+ assert not changed+ return {"facing": None, "cells": [], "status": "non_regressing", "reason": "no-jump-repaired-cell"}+ box = repair.union_box(ref)+ a, b = (repair.jump_scores(row, facing=facing, box=box) for row in (before, after))+ n = len(before)+ cells = [{"cell": c, "steps": [(c - 1) % n, c],+ "baseline": max(float(a["score"][s]) for s in ((c - 1) % n, c)),+ "candidate": max(float(b["score"][s]) for s in ((c - 1) % n, c))} for c in changed]+ return {"baseline": a["score"].tolist(), "candidate": b["score"].tolist(),+ "whole": {"baseline": a["whole"].tolist(), "candidate": b["whole"].tolist()},+ "hair": {"baseline": a["hair"].tolist(), "candidate": b["hair"].tolist()},+ "facing": facing, "hair_box": list(repair.hair_box(facing)), "box": list(box), "cells": cells,+ "status": _status([(c["baseline"], c["candidate"]) for c in cells])}+++def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Image], key: str,+ facing: str | None) -> dict[str, Any]:"""The protections over final pixels, from one loop's cells to the next's."""changed = [k for k, (a, b) in enumerate(zip(before, after)) if a.tobytes() != b.tobytes()]a_final, b_final, reference = measure(before, before), measure(after, after), measure(ref, ref)@@ -236,8 +279,7 @@ def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Ia, b = ([max(0, q[metric] - threshold) for q in row] for row in (a_final, b_final))axes[metric] = {"baseline": [q[metric] for q in a_final], "candidate": [q[metric] for q in b_final],"reference": [q[metric] for q in reference], "threshold": threshold,- "status": "regressed" if any(y > x + 1e-9 for x, y in zip(a, b)) else- "improved" if any(y < x - 1e-9 for x, y in zip(a, b)) else "non_regressing"}+ "status": _status(list(zip(a, b)))}a_partial, b_partial = ([max(0, q["partial_excess"] - r["partial_excess"]) for q, r in zip(row, reference)]for row in (a_fixed, b_fixed))axes["introduced_partial"] = {"baseline": a_partial, "candidate": b_partial,@@ -252,6 +294,8 @@ def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.I"introduced_excess": [int(r.sum()) / 255 for r in raised],"introduced_pixels": [int((r > 0).sum()) for r in raised], "tint_threshold": _BAR,"status": "regressed" if any(r.any() for r in raised) else "non_regressing"}+ # A rise brings back what the jump repair took out: a measured worsening, so `regressed`, as on every axis.+ axes["jump"] = jump(before, after, ref, changed, facing)cleared = [{"cell": k, "faults": sorted(set(faults(a_final[k])) - set(faults(b_final[k])))} for k in changed]regressed = [k + ":regressed" for k, v in axes.items() if v["status"] == "regressed"]if regressed:@@ -269,6 +313,7 @@ def judge(before: list[Image.Image], after: list[Image.Image], ref: list[Image.Iclass Chain:projection: source.Projectionkey: str+ facing: str | None # the jump repair's; None only when it replaced no cell, so there is no targetshown: list[int]applied: list[dict[str, Any]]@@ -303,10 +348,13 @@ def chain(origin: Loop, current: Loop, src: source.Source) -> tuple[Chain | Nonekey = _source_key(src)if key is None:return None, "source-key-colour-unverified"+ facing = _jump_facing(origin)+ if facing is None and projection.record["repair_hints"]:+ return None, "jump-repair-facing-unverified"schedule = playback.mapping(origin)if schedule is None:return None, "playback-schedule-unverified"- state = Chain(projection, key, schedule[0], [])+ state = Chain(projection, key, facing, schedule[0], [])if receipt is None:return state, Noneapplied = receipt.get("applied")@@ -326,7 +374,7 @@ def chain(origin: Loop, current: Loop, src: source.Source) -> tuple[Chain | Nonepart = partial(origin.frames[target], projection.frames[target], projection.cropped[target], key)after = [part.frame if k == target else f for k, f in enumerate(frames)]if (part.alpha_conflict or _portable(entry) != _portable(_entry(target, part, origin, previous, frames, src, projection))- or judge(frames, after, projection.frames, key)["verdict"] != "improved"):+ or judge(frames, after, projection.frames, key, facing)["verdict"] != "improved"):raise ValueError("an applied restoration is not reproduced by the origin, the source and the protections")state.applied.append(entry)frames = after@@ -348,6 +396,8 @@ def _base(origin: Loop, baseline: Loop, candidate: Loop, src: source.Source) ->"a restored cell is, at each place, the source's pixel, the source's pixel with its key hue ""capped one step to the bar, or the origin's; never the whole source drawing","one step is the least a channel can change: a bound on the cap, not a verdict on how it looks",+ "the jump guard reads coverage, not colour: a wrong colour in a source frame is seen only "+ "through the jump it came with","source and origin receipts bind supplied bytes; they are not signatures of the original producer"]}@@ -411,7 +461,7 @@ def compare(origin: Loop, baseline: Loop, candidate: Loop, src: source.Source, *receipt = _receipt(origin, src, projection, [*state.applied, entry])if _portable(candidate.source_report) != _portable({**baseline.source_report, "restoration": receipt}):return finish("unknown", ["candidate-report-differs-from-verified-receipt"])- measured = judge(baseline.frames, candidate.frames, ref, state.key)+ measured = judge(baseline.frames, candidate.frames, ref, state.key, state.facing)result["axes"] = {**measured["axes"], "seam": {"status": "non_regressing", "reason": "strip-and-playback-boundary-cells-and-durations-exact"}}result["gait"]["source_order"] = "preserved"diff --git a/tests/video/test_source_restoration.py b/tests/video/test_source_restoration.pyindex 0f93e1f..ddeff76 100644--- a/tests/video/test_source_restoration.py+++ b/tests/video/test_source_restoration.py@@ -12,7 +12,7 @@ import numpy as npimport pytestfrom PIL import Image, ImageDraw-from sprite_gen.video import evidence, source, restoration, playback, loop+from sprite_gen.video import evidence, source, restoration, playback, loop, repair as repair_modfrom sprite_gen.cli import mainfrom sprite_gen.util.gif_utils import save_clean_giffrom sprite_gen.util.resample import resize_cell@@ -20,7 +20,7 @@ from sprite_gen.video.compare import LoopW, H, N = 64, 80, 12FILL = (210, 160, 110, 255)-METRIC, POLICY = 'source-restoration-v3', 'key-protected-source-copy-one-step-cap-v1'+METRIC, POLICY = 'source-restoration-v4', 'key-protected-source-copy-one-step-cap-jump-guard-v1'# Two colours under the green key's bar (hue excess -6 each), one led by red and one by blue:# their even mix (105, 114, 105) is one step over it. ROSE and IRIS are the same for magenta.WARM, COOL = (120, 114, 90, 255), (90, 114, 120, 255)@@ -74,11 +74,12 @@ def cells(paths):return restoration.read_loop(paths)[0].frames-def build(tmp_path, zoom=1, key='green', paint=None):+def build(tmp_path, zoom=1, key='green', paint=None, facing='right'):"""A loop with two damaged cells and its keyed source, `zoom` times the cell's size.At zoom 1 a cell is a copy of its frame; at 2 every cell is a resample, as a delivered loop's are.- `paint` draws on chosen source frames before the loop is cut from them.+ `paint` draws on chosen source frames before the loop is cut from them. `facing` is the one the+ jump repair records, as `video-loop --facing` writes it."""if not shutil.which('ffmpeg') or not loop.img2webp_supports_exact():pytest.skip('ffmpeg and img2webp >=1.5 required')@@ -103,7 +104,7 @@ def build(tmp_path, zoom=1, key='green', paint=None):m={'frames':12,'w':64,'h':80,'delay_ms':41.67,'cycle_seconds':.5,'cycle_frames':12,'subsampled':False,'loop':True,'scale':1/zoom,'source_rect':[0,0,W*zoom,H*zoom],'sample_indices':list(range(12)),'foot_anchor':'none'}src=source.Source.read(**inputs)m['source_cut']={'source':src.record['source'],'start':0,'length':12,'samples':list(range(12))}- report={'kind':'sprite-gen-video-loop-report','status':'passed','fps':24.,'frames_total':12,'source':src.record['source'],'cycle':{'start':0,'length':12},'anchor':'none','jump_repair':{'replaced':[2,8]},'strip':m,'n_out':12,'delay_ms':42}+ report={'kind':'sprite-gen-video-loop-report','status':'passed','fps':24.,'frames_total':12,'source':src.record['source'],'cycle':{'start':0,'length':12},'anchor':'none','jump_repair':{'replaced':[2,8],'facing':facing},'strip':m,'n_out':12,'delay_ms':42}paths['meta'].write_text(json.dumps(m)); paths['report'].write_text(json.dumps(report))write_strip(paths,bad)return paths, inputs, clean@@ -164,7 +165,7 @@ def test_source_restoration_preserves_normal_motion_and_timing(case,tmp_path):assert result['origin_artifacts']==result['baseline_artifacts']comparison=compare_result(case,result)assert comparison['verdict']=='improved', comparison['reasons']- assert (comparison['metric_version'],comparison['policy_version'],comparison['schema_version'])==(METRIC,POLICY,4)+ assert (comparison['metric_version'],comparison['policy_version'],comparison['schema_version'])==(METRIC,POLICY,5)target=result['target']a,b=cells(case[0]),cells(outputs(result))assert all(x.tobytes()==y.tobytes() for k,(x,y) in enumerate(zip(a,b)) if k!=target)@@ -299,7 +300,7 @@ def test_cli_real_json_needs_the_origin(case,tmp_path,capsys):assert not comparison.exists()assert main(['video-loop-compare',*baseline,*origin,*candidate,*src,'--repair-evidence',str(report),'--report',str(comparison)])==0c=json.loads(comparison.read_bytes())- assert c['verdict']=='improved' and c['schema_version']==4 and c['metric_version']==METRIC+ assert c['verdict']=='improved' and c['schema_version']==5 and c['metric_version']==METRICassert set(c['candidate']['artifacts'])==set(c['origin']['artifacts'])=={'strip','meta','report','gif','webp'}assert c['origin']['artifacts']==r['origin_artifacts']@@ -380,7 +381,7 @@ def test_less_total_key_spill_cannot_hide_new_local_key_spill(case,tmp_path):src=source.Source.read(**inputs)state,_=restoration.chain(o,o,src)whole=[state.projection.frames[k] if k==target else f for k,f in enumerate(o.frames)]- judged=restoration.judge(o.frames,whole,state.projection.frames,state.key)+ judged=restoration.judge(o.frames,whole,state.projection.frames,state.key,state.facing)assert sum(f for f in judged['axes']['key_colour']['candidate'])<sum(judged['axes']['key_colour']['baseline'])assert judged['axes']['key_colour']['introduced_pixels'][target]==4assert judged['verdict']=='regressed' and 'key_colour:regressed' in judged['reasons']@@ -691,6 +692,9 @@ def test_replaced_origin_or_source_is_error(case,tmp_path,adopted):def test_other_policy_receipt_is_not_read_as_this_one(case,tmp_path,adopted):origin,first,current=adoptedfor change in (lambda r: r['restoration'].update(policy_version='another-policy'),+ # The released contract before the jump guard: its cells were accepted without it.+ lambda r: r['restoration'].update(metric_version='source-restoration-v3',+ policy_version='key-protected-source-copy-one-step-cap-v1'),# The same cell under the contract before this one, which never capped: its receipt is not this one's.lambda r: r['restoration'].update(metric_version='source-restoration-v2',policy_version='key-protected-source-copy-v1'),lambda r: r.update(restoration={'operation':'restore_active_cut','metric_version':'source-restoration-v1',@@ -712,7 +716,8 @@ def test_old_proposal_cannot_be_compared_on_the_new_baseline(case,tmp_path,adoptcompare_result(case,second,baseline=case[0],origin=origin)# Evidence of another schema or metric is not this contract's.for field,value in (('schema_version',2),('metric_version','source-restoration-v2'),- ('policy_version','key-protected-source-copy-v1'),('policy_version','another-policy')):+ ('policy_version','key-protected-source-copy-v1'),('metric_version','source-restoration-v3'),+ ('policy_version','key-protected-source-copy-one-step-cap-v1'),('policy_version','another-policy')):with pytest.raises(ValueError,match='does not bind'):compare_result(case,{**second,field:value},baseline=current,origin=origin)# A candidate whose receipt drops the earlier cell is not the verified one.@@ -723,6 +728,73 @@ def test_old_proposal_cannot_be_compared_on_the_new_baseline(case,tmp_path,adoptassert (outcome['verdict'],outcome['reasons'])==('unknown',['candidate-report-differs-from-verified-receipt'])+def shifted(dx):+ """The whole drawing moved `dx` pixels sideways: the same lines, fills and coverage, all of it somewhere else."""+ def paint(f):+ moved=Image.new('RGBA',f.size); moved.paste(f,(dx,0)); f.paste(moved)+ return paint++[email protected]('facing',['right','left'])+def test_the_jump_around_a_restored_cell_is_the_jump_repairs_own_score(tmp_path,facing):+ # The melted in-between filled the part-covered line, so the steps into and out of it changed more+ # coverage than the source's do. The restored cell gives those steps back the source's.+ case=build(tmp_path,facing=facing)+ paths,_,clean=case+ r=repair(case,tmp_path)+ c=r['comparison']+ assert c['verdict']=='improved', c['reasons']+ axis,target=c['axes']['jump'],r['target']+ # Both loops scored on the source cells' box, with the facing the jump repair recorded.+ box=repair_mod.union_box(clean)+ a,b=(repair_mod.jump_scores(cells(p),facing=facing,box=box) for p in (paths,outputs(r)))+ assert (axis['facing'],axis['hair_box'],axis['box'])==(facing,list(repair_mod.hair_box(facing)),list(box))+ assert (axis['baseline'],axis['candidate'])==(a['score'].tolist(),b['score'].tolist())+ assert axis['whole']=={'baseline':a['whole'].tolist(),'candidate':b['whole'].tolist()}+ assert axis['hair']=={'baseline':a['hair'].tolist(),'candidate':b['hair'].tolist()}+ # A cell reads the larger of its two steps, the step into it and the step out of it.+ steps=[target-1,target]+ assert axis['cells']==[{'cell':target,'steps':steps,'baseline':max(a['score'][steps]),'candidate':max(b['score'][steps])}]+ assert axis['cells'][0]['candidate']<=axis['cells'][0]['baseline'] and axis['status']!='regressed'++[email protected]('facing',['right','left'])+def test_a_restored_cell_that_brings_its_jump_back_is_not_improved(tmp_path,facing):+ # The source frame under the melted cell is the jump the repair took out: its whole drawing stands+ # six pixels to one side of its neighbours'. Its pixels clear the melt and bring the jump back.+ case=build(tmp_path,facing=facing)+ repaint_source(case,2,shifted(6))+ outcomes={r['target']:r for r in (repair(case,tmp_path,k) for k in (1,2))}+ r=outcomes[2]+ assert r['status']=='candidate' and r['partial']['alpha_equals_source'] and r['partial']['protected']['count']==0+ c=r['comparison']+ assert (c['verdict'],c['reasons'])==('regressed',['jump:regressed'])+ # The melt is cleared and every other protection holds: the jump alone refuses the cell.+ assert c['cleared_faults']==[{'cell':2,'faults':['outline']}]+ assert all(v['status']!='regressed' for k,v in c['axes'].items() if k!='jump')+ cell=c['axes']['jump']['cells'][0]+ assert (cell['cell'],cell['steps'])==(2,[1,2]) and cell['candidate']>cell['baseline']+ assert compare_result(case,r)['verdict']=='regressed'+ # The other cell is independent of it.+ assert outcomes[8]['comparison']['verdict']=='improved'++[email protected]('facing',[None,'sideways'])+def test_a_jump_repair_record_without_its_facing_is_shared_unknown(case,tmp_path,facing):+ # The jump repair records the facing its hair box was read with. Without it, which steps of a+ # replaced cell jumped is not known, so none of its cells is proposed.+ paths,_,clean=case+ rewrite_receipt(paths,lambda r: r['jump_repair'].pop('facing') if facing is None else r['jump_repair'].update(facing=facing))+ r=repair(case,tmp_path)+ assert (r['status'],r['common_failure'],r['reasons'],r['outputs'])==('unknown',True,['jump-repair-facing-unverified'],{})+ # A loop the repair left alone needs none: a request on it is the byte-exact no-op.+ write_strip(paths,clean)+ rewrite_receipt(paths,lambda r: r.update(jump_repair={'applied':False,'why':'--repair off'}))+ noop=repair(case,tmp_path,out='noop')+ assert noop['status']=='no_change' and noop['comparison']['verdict']=='non_regressing'+ assert noop['comparison']['axes']['jump']=={'facing':None,'cells':[],'status':'non_regressing','reason':'no-jump-repaired-cell'}++@pytest.mark.parametrize('scaled,left,right,mixed,capped',[('green',WARM,COOL,(105,114,105,255),(105,113,105,255)),('magenta',ROSE,IRIS,(109,100,109,255),(108,100,108,255))],indirect=['scaled'])@@ -743,7 +815,7 @@ def test_cli_restores_a_resampled_cell_with_its_made_excess_capped(scaled,tmp_pacomparison=tmp_path/'comparison.json'assert main(['video-loop-compare',*baseline,*origin,*candidate,*src,'--repair-evidence',str(report),'--report',str(comparison)])==0c=json.loads(comparison.read_bytes())- assert (c['verdict'],c['schema_version'],c['metric_version'],c['policy_version'])==('improved',4,METRIC,POLICY), c['reasons']+ assert (c['verdict'],c['schema_version'],c['metric_version'],c['policy_version'])==('improved',5,METRIC,POLICY), c['reasons']key=c['axes']['key_colour']assert (key['introduced_pixels'][target],key['introduced_excess'][target],key['candidate'][target])==(0,0,0)assert c['cleared_faults']==[{'cell':target,'faults':['outline']}]@@ -770,7 +842,7 @@ def test_whole_source_cell_with_a_made_excess_is_still_refused(scaled,tmp_path):o,_=restoration.read_loop(paths)state,_=restoration.chain(o,o,source.Source.read(**inputs))whole=[state.projection.frames[k] if k==target else f for k,f in enumerate(o.frames)]- judged=restoration.judge(o.frames,whole,state.projection.frames,state.key)+ judged=restoration.judge(o.frames,whole,state.projection.frames,state.key,state.facing)assert judged['axes']['key_colour']['introduced_pixels'][target]==6assert judged['verdict']=='regressed' and 'key_colour:regressed' in judged['reasons']# Written out as the candidate, one capped place given the source's pixel back is not the verified cell.