Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Authenticate review evidence and expose missing measurements

Sina Atalay5e4915ba06e1
diff --git a/tests/integration/review/app.py b/tests/integration/review/app.py
index e501158b..c07f2437 100644
--- a/tests/integration/review/app.py
+++ b/tests/integration/review/app.py
@@ -16,7 +16,7 @@ from typing import Literal
from fastapi import FastAPI, HTTPException, Response
from fastapi.staticfiles import StaticFiles
from PIL import Image
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from tests.integration.corpus import references, typecheck
from tests.integration.corpus.case import (
FPS,
@@ -34,7 +34,7 @@ from tests.integration.corpus.case import (
settings,
)
from tests.integration.corpus.compare import slots
-from tests.integration.corpus.frames import Pixels, decode
+from tests.integration.corpus.frames import Pixels, decode, frame_hash
PANEL = Path(__file__).resolve().parent / "web" / "dist"
@@ -102,7 +102,7 @@ class RenderIn(BaseModel):
class SettingsIn(BaseModel):
metric: str
- tolerance: float
+ tolerance: float = Field(ge=0, le=255, allow_inf_nan=False)
class SettingsOut(SettingsIn):
@@ -116,10 +116,10 @@ class TypeReports:
def __init__(self) -> None:
self._lock = threading.Lock()
self._report: typecheck.TypeReport | None = None
- self._made_for: tuple[int, ...] = ()
+ self._made_for: tuple[tuple[str, str], ...] = ()
def get(self, cases: list[Case]) -> typecheck.TypeReport:
- stamp = tuple(case.scene.stat().st_mtime_ns for case in cases)
+ stamp = tuple((case.name, case.source_hash()) for case in cases)
with self._lock:
if self._report is None or stamp != self._made_for:
self._report, self._made_for = typecheck.report(cases), stamp
@@ -300,11 +300,9 @@ def _frames(name: str, engine: Engine, stamp: int) -> dict[str, Pixels]:
render = None if facts is None else facts.render(engine)
if facts is None or not isinstance(render, Frames):
return {}
- hashes = render.hashes()
found: dict[str, Pixels] = {}
- for index, pixels in enumerate(decode(case.video(engine), facts.size)):
- if index < len(hashes) and hashes[index] not in found:
- found[hashes[index]] = pixels
+ for pixels in decode(case.video(engine), facts.size):
+ found.setdefault(frame_hash(pixels.tobytes()), pixels)
return found
diff --git a/tests/integration/review/web/package.json b/tests/integration/review/web/package.json
index 96cc281b..45869418 100644
--- a/tests/integration/review/web/package.json
+++ b/tests/integration/review/web/package.json
@@ -7,7 +7,8 @@
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
- "check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json"
+ "check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json",
+ "test": "bun run check && bun test && bun run build"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.3.0",
diff --git a/tests/integration/review/web/src/lib/Compare.svelte b/tests/integration/review/web/src/lib/Compare.svelte
index 527a0f9d..9070143c 100644
--- a/tests/integration/review/web/src/lib/Compare.svelte
+++ b/tests/integration/review/web/src/lib/Compare.svelte
@@ -121,7 +121,9 @@
<figure>
<figcaption>where they differ: black, then red → yellow → white as the difference grows</figcaption>
{#key `${ce} ${manimgx}`}
- <canvas {@attach differences(ce, manimgx)}></canvas>
+ <canvas {@attach differences(ce, manimgx, (message) => {
+ review.error = `Cannot compare frames: ${message}`
+ })}></canvas>
{/key}
</figure>
{:else}
diff --git a/tests/integration/review/web/src/lib/Timeline.svelte b/tests/integration/review/web/src/lib/Timeline.svelte
index 2b39cf29..50294e9d 100644
--- a/tests/integration/review/web/src/lib/Timeline.svelte
+++ b/tests/integration/review/web/src/lib/Timeline.svelte
@@ -16,11 +16,12 @@
let { slots, at, metric, tolerance, onselect }: Props = $props()
- type Kind = 'same' | 'differs' | 'manimgx-only' | 'ce-only'
+ type Kind = 'same' | 'differs' | 'unmeasured' | 'manimgx-only' | 'ce-only'
const legend: { kind: Kind; text: string }[] = [
{ kind: 'same', text: 'same' },
{ kind: 'differs', text: 'differs' },
+ { kind: 'unmeasured', text: 'not compared' },
{ kind: 'manimgx-only', text: 'manimgx only' },
{ kind: 'ce-only', text: 'ce only' },
]
@@ -28,7 +29,9 @@
const kind = (slot: Slot): Kind => {
if (slot.ce === null) return 'manimgx-only'
if (slot.manimgx === null) return 'ce-only'
- return (slot.errors?.[metric] ?? 0) <= tolerance ? 'same' : 'differs'
+ const error = slot.errors?.[metric]
+ if (error === undefined) return 'unmeasured'
+ return error <= tolerance ? 'same' : 'differs'
}
const kinds = $derived(slots.map(kind))
@@ -92,6 +95,10 @@
background: var(--differs);
}
+ .unmeasured {
+ background: var(--faint);
+ }
+
.manimgx-only {
background: var(--manimgx-only);
}
diff --git a/tests/integration/review/web/src/lib/differences.ts b/tests/integration/review/web/src/lib/differences.ts
index a8b5646c..e79ded97 100644
--- a/tests/integration/review/web/src/lib/differences.ts
+++ b/tests/integration/review/web/src/lib/differences.ts
@@ -16,33 +16,41 @@ function pixels(image: HTMLImageElement): Uint8ClampedArray {
/** Draws where two frames differ: each pixel's largest channel difference, as heat (black,
* then red, yellow, white as the difference grows; square-rooted, so faint differences show). */
-export function differences(a: string, b: string): Attachment<HTMLCanvasElement> {
+export function differences(
+ a: string,
+ b: string,
+ onError: (message: string) => void,
+): Attachment<HTMLCanvasElement> {
return (canvas) => {
let live = true
- Promise.all([load(a), load(b)]).then(([first, second]) => {
- if (!live) return
- const width = first.naturalWidth
- const height = first.naturalHeight
- const one = pixels(first)
- const two = pixels(second)
- canvas.width = width
- canvas.height = height
- const context = canvas.getContext('2d')!
- const heat = context.createImageData(width, height)
- for (let p = 0; p < one.length; p += 4) {
- const d = Math.max(
- Math.abs(one[p]! - two[p]!),
- Math.abs(one[p + 1]! - two[p + 1]!),
- Math.abs(one[p + 2]! - two[p + 2]!),
- )
- const v = Math.sqrt(d / 255) * 765
- heat.data[p] = v
- heat.data[p + 1] = v - 255
- heat.data[p + 2] = v - 510
- heat.data[p + 3] = 255
- }
- context.putImageData(heat, 0, 0)
- })
+ Promise.all([load(a), load(b)])
+ .then(([first, second]) => {
+ if (!live) return
+ const width = first.naturalWidth
+ const height = first.naturalHeight
+ const one = pixels(first)
+ const two = pixels(second)
+ canvas.width = width
+ canvas.height = height
+ const context = canvas.getContext('2d')!
+ const heat = context.createImageData(width, height)
+ for (let p = 0; p < one.length; p += 4) {
+ const d = Math.max(
+ Math.abs(one[p]! - two[p]!),
+ Math.abs(one[p + 1]! - two[p + 1]!),
+ Math.abs(one[p + 2]! - two[p + 2]!),
+ )
+ const v = Math.sqrt(d / 255) * 765
+ heat.data[p] = v
+ heat.data[p + 1] = v - 255
+ heat.data[p + 2] = v - 510
+ heat.data[p + 3] = 255
+ }
+ context.putImageData(heat, 0, 0)
+ })
+ .catch((error: unknown) => {
+ if (live) onError(error instanceof Error ? error.message : String(error))
+ })
return () => {
live = false
}
diff --git a/tests/integration/review/web/tests/evidence.test.js b/tests/integration/review/web/tests/evidence.test.js
new file mode 100644
index 00000000..839dae93
--- /dev/null
+++ b/tests/integration/review/web/tests/evidence.test.js
@@ -0,0 +1,69 @@
+// Missing evidence must stay visibly distinct from measured equality.
+import { afterAll, afterEach, expect, test } from 'bun:test'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { compile } from 'svelte/compiler'
+import { render } from 'svelte/server'
+import { differences } from '../src/lib/differences.ts'
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)))
+const source = join(root, 'src/lib/Timeline.svelte')
+const compiled = compile(readFileSync(source, 'utf8'), { filename: source, generate: 'server' })
+const directory = mkdtempSync(join(root, 'node_modules/.timeline-test-'))
+const module = join(directory, 'Timeline.mjs')
+writeFileSync(module, compiled.js.code)
+const { default: Timeline } = await import(module)
+afterAll(() => rmSync(directory, { recursive: true }))
+
+for (const errors of [null, {}, { mae: 0 }]) {
+ test(`unmeasured timeline slots are not labelled equal: ${JSON.stringify(errors)}`, () => {
+ const { body } = render(Timeline, {
+ props: {
+ slots: [{ time: 0, ce: 0, ce_time: 0, manimgx: 0, errors }],
+ at: 0,
+ metric: 'max',
+ tolerance: 0,
+ onselect() {},
+ },
+ })
+ expect(body).toMatch(/<button class="block unmeasured /)
+ expect(body).not.toMatch(/<button class="block same /)
+ })
+}
+
+test('a measured zero remains an equality', () => {
+ const { body } = render(Timeline, {
+ props: {
+ slots: [{ time: 0, ce: 0, ce_time: 0, manimgx: 0, errors: { max: 0 } }],
+ at: 0,
+ metric: 'max',
+ tolerance: 0,
+ onselect() {},
+ },
+ })
+ expect(body).toMatch(/<button class="block same /)
+})
+
+const image = globalThis.Image
+afterEach(() => {
+ globalThis.Image = image
+})
+
+for (const detached of [false, true]) {
+ test(`missing diff images report an error only to a live view: detached=${detached}`, async () => {
+ const pending = Promise.withResolvers()
+ globalThis.Image = class {
+ decode() {
+ return pending.promise
+ }
+ }
+ const errors = []
+ const dispose = differences('missing.png', 'other.png', (error) => errors.push(error))({})
+ if (detached) dispose()
+ pending.reject(new Error('reference image unavailable'))
+ // Image.decode, load, Promise.all, and its attached catch all settle before this task.
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(errors).toEqual(detached ? [] : ['reference image unavailable'])
+ })
+}
diff --git a/tests/integration/test_review.py b/tests/integration/test_review.py
new file mode 100644
index 00000000..b0dc5c2a
--- /dev/null
+++ b/tests/integration/test_review.py
@@ -0,0 +1,71 @@
+"""The review panel must show and approve the evidence it identifies."""
+
+import io
+import os
+from fractions import Fraction
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+from PIL import Image
+from tests.integration.corpus import case as corpus
+from tests.integration.corpus.frames import Recorder, frame_hash
+from tests.integration.review import app as panel
+
+
+def case(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> corpus.Case:
+ monkeypatch.setattr(corpus, "CASES", tmp_path)
+ monkeypatch.setattr(corpus, "SIZE", (8, 8))
+ example = corpus.Case("first")
+ example.dir.mkdir()
+ example.scene.write_text("value: int = 1\n", encoding="utf-8")
+ panel._frames.cache_clear()
+ panel._png.cache_clear()
+ return example
+
+
+def movie(case: corpus.Case, color: tuple[int, int, int]) -> corpus.Frames:
+ recorder = Recorder((8, 8), 10, case.video("manimgx"), compact=False)
+ recorder.add(bytes(color) * 64)
+ return corpus.Frames(recorder.close(), Fraction(1, 10), ((Fraction(0), 1),))
+
+
+def test_frame_url_identifies_decoded_pixels_not_recorded_frame_position(
+ case: corpus.Case,
+) -> None:
+ red = movie(case, (255, 0, 0))
+ case.write_facts(
+ corpus.Facts(case.source_hash(), (8, 8), 10, red, red, "test", None)
+ )
+ blue = movie(case, (0, 0, 255))
+ with pytest.raises(HTTPException) as missing:
+ panel.read_frame(case.name, "manimgx", red.hashes()[0])
+ assert missing.value.status_code == 404
+ response = panel.read_frame(case.name, "manimgx", blue.hashes()[0])
+ assert response.media_type == "image/png"
+ pixels = Image.open(io.BytesIO(bytes(response.body))).convert("RGB").tobytes()
+ assert frame_hash(pixels) == blue.hashes()[0]
+ assert "immutable" in response.headers["cache-control"]
+
+
[email protected]("change", ["rename", "edit"])
+def test_type_report_cache_tracks_source_and_case_identity(
+ case: corpus.Case, change: str
+) -> None:
+ reports = panel.TypeReports()
+ case.scene.write_text('value: int = "wrong"\n', encoding="utf-8")
+ before = reports.get([case])
+ assert before.problems(case)
+ stamp = case.scene.stat()
+ if change == "rename":
+ case.dir.rename(case.dir.with_name("renamed"))
+ case = corpus.Case("renamed")
+ else:
+ case.scene.write_text("value: int = 1\n", encoding="utf-8")
+ os.utime(case.scene, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
+ assert case.scene.stat().st_mtime_ns == stamp.st_mtime_ns
+ after = reports.get([case])
+ assert after is not before
+ assert bool(after.problems(case)) == (change == "rename")
+ assert reports.get([case]) is after
diff --git a/tests/integration/test_review_settings.py b/tests/integration/test_review_settings.py
new file mode 100644
index 00000000..40f7017f
--- /dev/null
+++ b/tests/integration/test_review_settings.py
@@ -0,0 +1,11 @@
+"""Only meaningful RGB comparison budgets can be persisted by the review server."""
+
+import pytest
+from pydantic import ValidationError
+from tests.integration.review import app as panel
+
+
[email protected]("value", [-1, 256, float("inf"), float("nan")])
+def test_review_settings_reject_impossible_channel_error_budgets(value: float) -> None:
+ with pytest.raises(ValidationError):
+ panel.SettingsIn(metric="max", tolerance=value)