Skip to content

Commit 0809c98

Browse files
committed
fix(producer,engine): gate drawelement on ancestor background-image + tail verify sample
1 parent d51fa7e commit 0809c98

5 files changed

Lines changed: 194 additions & 1 deletion

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { describe, expect, it } from "vitest";
2+
import { computeDeVerifySampleFractions } from "./frameCapture.js";
3+
4+
describe("computeDeVerifySampleFractions", () => {
5+
it("pins the last sample at 95% so late-onset damage is sampled", () => {
6+
const fractions = computeDeVerifySampleFractions(4);
7+
expect(fractions).toEqual([0.25, 0.5, 0.75, 0.95]);
8+
});
9+
10+
it("keeps the requested sample count", () => {
11+
for (const k of [1, 2, 3, 4, 8]) {
12+
expect(computeDeVerifySampleFractions(k)).toHaveLength(k);
13+
}
14+
});
15+
16+
it("uses only the tail sample when k is 1", () => {
17+
expect(computeDeVerifySampleFractions(1)).toEqual([0.95]);
18+
});
19+
20+
it("returns an empty grid when verification is disabled", () => {
21+
expect(computeDeVerifySampleFractions(0)).toEqual([]);
22+
expect(computeDeVerifySampleFractions(-2)).toEqual([]);
23+
});
24+
25+
it("stays strictly increasing within (0, 1) for every supported k", () => {
26+
for (let k = 1; k <= 8; k++) {
27+
const fractions = computeDeVerifySampleFractions(k);
28+
for (let i = 0; i < fractions.length; i++) {
29+
const f = fractions[i] ?? 0;
30+
expect(f).toBeGreaterThan(0);
31+
expect(f).toBeLessThan(1);
32+
if (i > 0) expect(f).toBeGreaterThan(fractions[i - 1] ?? 0);
33+
}
34+
}
35+
});
36+
});

‎packages/engine/src/services/frameCapture.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3107,6 +3107,19 @@ export async function getCompositionDuration(session: CaptureSession): Promise<n
31073107
* init-time screenshot → the render falls back to the screenshot path (slower,
31083108
* never wrong). Cost when passing: ~K×(seek+screenshot) ≈ 150–300ms at init.
31093109
*/
3110+
/**
3111+
* Timeline fractions the self-verify samples. First k-1 evenly spaced, last
3112+
* pinned at 95%: late-onset damage (an end-of-comp reveal exposing pixels DE
3113+
* paints wrong) was invisible to the old (i+1)/(k+1) grid, whose final sample
3114+
* sat at 80% — measured miss: a body-gradient drop starting at ~79% of the
3115+
* timeline passed verification while the drained output bottomed at 30.9 dB.
3116+
*/
3117+
export function computeDeVerifySampleFractions(k: number): number[] {
3118+
if (k <= 0) return [];
3119+
if (k === 1) return [0.95];
3120+
return [...Array.from({ length: k - 1 }, (_, i) => (i + 1) / k), 0.95];
3121+
}
3122+
31103123
async function captureDeVerificationFrames(
31113124
session: CaptureSession,
31123125
page: Page,
@@ -3153,7 +3166,7 @@ async function captureDeVerificationFrames(
31533166
// render (the detectCssEffectRisk lesson), and because DE frames and truth
31543167
// would share the corruption, PSNR would pass on the damaged output.
31553168
// Seeking 0 → ascending reproduces the render's own seek order.
3156-
const fractions = Array.from({ length: k }, (_, i) => (i + 1) / (k + 1));
3169+
const fractions = computeDeVerifySampleFractions(k);
31573170
const seekTo = async (t: number): Promise<void> => {
31583171
await page.evaluate((tt: number) => {
31593172
const hf = (

‎packages/producer/src/services/htmlCompiler.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
collectExternalAssets,
99
compileForRender,
1010
injectSdkPositionEditsRenderScript,
11+
detectAncestorBackgroundImage,
1112
detectRenderModeHints,
1213
detectShaderTransitionUsage,
1314
detectThreeDTransformUsage,
@@ -718,6 +719,65 @@ describe("detectThreeDTransformUsage", () => {
718719
});
719720
});
720721

722+
describe("detectAncestorBackgroundImage", () => {
723+
const wrap = (headCss: string, bodyAttrs = "", inner = "") =>
724+
`<!doctype html><html><head><style>${headCss}</style></head><body${bodyAttrs ? ` ${bodyAttrs}` : ""}>` +
725+
`<div id="root" data-composition-id="main" data-duration="10">${inner}</div></body></html>`;
726+
727+
it("detects a linear-gradient body background from a style rule", () => {
728+
expect(
729+
detectAncestorBackgroundImage(
730+
wrap("body { background: linear-gradient(135deg, #1b2735, #090a0f); }"),
731+
),
732+
).toBe(true);
733+
});
734+
735+
it("detects a url() background-image on html", () => {
736+
expect(detectAncestorBackgroundImage(wrap('html { background-image: url("bg.png"); }'))).toBe(
737+
true,
738+
);
739+
});
740+
741+
it("detects an inline gradient style on body", () => {
742+
expect(
743+
detectAncestorBackgroundImage(
744+
wrap("", 'style="background: radial-gradient(circle, #111, #000)"'),
745+
),
746+
).toBe(true);
747+
});
748+
749+
it("detects a class-selected wrapper between body and the root", () => {
750+
const html =
751+
"<!doctype html><html><head><style>.page-bg { background-image: linear-gradient(#111, #000); }</style></head>" +
752+
'<body><div class="page-bg"><div data-composition-id="main" data-duration="10"></div></div></body></html>';
753+
expect(detectAncestorBackgroundImage(html)).toBe(true);
754+
});
755+
756+
it("ignores background-image on elements inside the composition root", () => {
757+
expect(
758+
detectAncestorBackgroundImage(
759+
wrap(
760+
"#hero { background-image: linear-gradient(#111, #000); }",
761+
"",
762+
'<div id="hero"></div>',
763+
),
764+
),
765+
).toBe(false);
766+
});
767+
768+
it("ignores plain background-color ancestors", () => {
769+
expect(detectAncestorBackgroundImage(wrap("html, body { background: #0d1117; }"))).toBe(false);
770+
});
771+
772+
it("returns false without a composition root", () => {
773+
expect(
774+
detectAncestorBackgroundImage(
775+
"<html><head><style>body { background: linear-gradient(#111, #000); }</style></head><body></body></html>",
776+
),
777+
).toBe(false);
778+
});
779+
});
780+
721781
describe("detectShaderTransitionUsage", () => {
722782
it("detects authored HyperShader initialization", () => {
723783
const html = `<!doctype html>

‎packages/producer/src/services/htmlCompiler.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ export interface CompiledComposition {
7878
usesThreeDTransforms: boolean;
7979
/** Author HTML/CSS use mix-blend-mode (pre-CDN-inline scan). */
8080
usesMixBlendMode: boolean;
81+
/** Ancestors of the composition root carry a background-image (gradient/url). */
82+
hasAncestorBackgroundImage: boolean;
8183
}
8284

8385
/** Adapts linkedom's `parseHTML` to the `checkSubCompositionUsability` contract. */
@@ -324,6 +326,64 @@ function detectMixBlendModeUsage(html: string): boolean {
324326
return MIX_BLEND_MODE_PATTERN.test(html);
325327
}
326328

329+
/** A background declaration whose value paints an image (gradient or url). */
330+
const BACKGROUND_IMAGE_DECL_PATTERN =
331+
/(?:^|;|\{)\s*background(?:-image)?\s*:[^;}]*(?:\bgradient\s*\(|url\s*\()/i;
332+
333+
/**
334+
* Background-image signals on ancestors of the composition root.
335+
* drawElementImage only paints the captured subtree; drawElementService's
336+
* per-frame ancestor fill replicates what lies behind it by walking up the
337+
* DOM for the nearest non-transparent `backgroundColor`. A background-IMAGE
338+
* (linear-gradient, url) on <body>/<html>/a wrapper reads as transparent in
339+
* that scan, so a deeper ancestor's solid color paints instead — measured:
340+
* a body `linear-gradient` replaced by the html background color wherever
341+
* the subtree left pixels uncovered (30.9 dB min vs baseline), and the
342+
* damage can set in late enough to slip past the self-verify sample grid.
343+
* Backgrounds on elements INSIDE the root are painted correctly and are
344+
* deliberately not matched — this walks only the root's ancestor chain and
345+
* the style rules that select into it.
346+
*/
347+
export function detectAncestorBackgroundImage(html: string): boolean {
348+
const { document } = parseHTML(html);
349+
const root = document.querySelector("[data-composition-id]");
350+
if (!root) return false;
351+
const ancestors: Element[] = [];
352+
for (let el = root.parentElement; el; el = el.parentElement) ancestors.push(el);
353+
if (document.documentElement && !ancestors.includes(document.documentElement)) {
354+
ancestors.push(document.documentElement);
355+
}
356+
// Inline styles on the ancestor chain.
357+
for (const el of ancestors) {
358+
const style = el.getAttribute("style");
359+
if (style && BACKGROUND_IMAGE_DECL_PATTERN.test(`{${style}}`)) return true;
360+
}
361+
// <style> rules: any rule carrying an image-painting background declaration
362+
// whose selector resolves to an ancestor of the root. Selector matching goes
363+
// through querySelectorAll so class/id/compound selectors on wrappers are
364+
// covered, not just literal `body`/`html`.
365+
for (const styleEl of document.querySelectorAll("style")) {
366+
const css = styleEl.textContent ?? "";
367+
for (const rule of css.matchAll(/([^{}]+)\{([^}]*)\}/g)) {
368+
const [, selectorList = "", declarations = ""] = rule;
369+
if (!BACKGROUND_IMAGE_DECL_PATTERN.test(`{${declarations}}`)) continue;
370+
for (const selector of selectorList.split(",")) {
371+
const sel = selector.trim();
372+
if (!sel || sel.startsWith("@")) continue;
373+
if (/^(?:html|:root)$/i.test(sel)) return true;
374+
try {
375+
for (const matched of document.querySelectorAll(sel)) {
376+
if (ancestors.includes(matched)) return true;
377+
}
378+
} catch {
379+
// Selector syntax linkedom can't parse (e.g. vendor pseudo) — skip.
380+
}
381+
}
382+
}
383+
}
384+
return false;
385+
}
386+
327387
const SHADER_TRANSITION_USAGE_PATTERN =
328388
/\b(?:(?:window|globalThis)\s*\.\s*)?HyperShader\s*\.\s*init\s*\(|\b__hf\s*\.\s*transitions\s*=/;
329389

@@ -1706,6 +1766,7 @@ export async function compileForRender(
17061766
// composition that loads GSAP from a CDN.
17071767
const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
17081768
const usesMixBlendMode = detectMixBlendModeUsage(sanitizedHtml);
1769+
const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
17091770

17101771
const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
17111772
injectTextRenderingRule(
@@ -1881,6 +1942,7 @@ export async function compileForRender(
18811942
hasShaderTransitions,
18821943
usesThreeDTransforms,
18831944
usesMixBlendMode,
1945+
hasAncestorBackgroundImage,
18841946
};
18851947
}
18861948

‎packages/producer/src/services/render/stages/compileStage.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,28 @@ export async function runCompileStage(input: CompileStageInput): Promise<Compile
200200
"for this render. Capture uses the platform's baseline route.",
201201
);
202202
}
203+
// Fast-capture ancestor-background-image gate, same shape as the gates above.
204+
// drawElementService's per-frame ancestor fill replicates only the nearest
205+
// non-transparent ancestor background-COLOR behind the captured subtree; a
206+
// background-image (linear-gradient, url) on <body>/<html>/a wrapper reads
207+
// as transparent there, so a deeper ancestor's solid color paints instead
208+
// wherever the subtree leaves pixels uncovered (measured: body gradient
209+
// replaced by html color, 30.9 dB min vs baseline — and late-onset, so the
210+
// self-verify grid can miss it). HF_FAST_CAPTURE_ANCESTOR_BG=true bypasses
211+
// for R&D.
212+
if (
213+
cfg.useDrawElement &&
214+
process.env.HF_FAST_CAPTURE_ANCESTOR_BG !== "true" &&
215+
compiled.hasAncestorBackgroundImage
216+
) {
217+
cfg.useDrawElement = false;
218+
deCompileGate = "ancestor_background_image";
219+
log.info(
220+
"[Render] Fast capture: composition root's ancestors (body/html/wrapper) carry a " +
221+
"background-image — disabling drawElementImage for this render. Capture uses the " +
222+
"platform's baseline route.",
223+
);
224+
}
203225
// Shader-transition comps: page-side compositing is the faster, purpose-built
204226
// path for them, and resolveConfig force-disables it whenever drawElement is
205227
// on. With drawElement default-on that trade is backwards — prefer page-side

0 commit comments

Comments
 (0)