const assert = require("node:assert/strict");
const { assertExactSuccessfulVotesTraffic } = require("./hermetic-api-contract");
const SHORTS_PLACEHOLDER_POOL_SIZE = 10;
const SHORTS_PLACEHOLDER_POOL_HOPS = 10;
const SHORTS_PLACEHOLDER_POOL_VIDEO_IDS = Object.freeze(
Array.from({ length: SHORTS_PLACEHOLDER_POOL_HOPS + 1 }, (_, index) => `PoolVid${String(index).padStart(4, "0")}`),
);
const SHORTS_PLACEHOLDER_POOL_COUNTS = Object.freeze(
Object.fromEntries(
SHORTS_PLACEHOLDER_POOL_VIDEO_IDS.map((videoId, index) => [
videoId,
Object.freeze({ dislikes: 210 + index * 17, likes: 1_100 + index * 31 }),
]),
),
);
const SHORTS_PLACEHOLDER_POOL_ACTION_ORDER = Object.freeze(["like", "dislike", "comments", "share", "remix", "pivot"]);
const SHORTS_PLACEHOLDER_POOL_MARKER = "rydShortsPlaceholderPool=1";
const SHORTS_SYNTHETIC_DISLIKE_SELECTOR = "[data-ryd-synthetic-shorts-dislike]";
const SHORTS_DUPLICATE_NORMALIZATION_HOP = 3;
const SHORTS_NATIVE_CLEANUP_HOP = 5;
const SHORTS_EVENTLESS_RETURN_HOP = 7;
const SHORTS_NATIVE_LIKE_PAINT_HOP = 1;
const SHORTS_PIXEL_ORACLE_HOPS = new Set([0, 1, SHORTS_PLACEHOLDER_POOL_HOPS]);
const SHORTS_FRESH_ROUTE_EPOCH_MS = 250;
const SHORTS_TRANSITION_OBSERVATION_PHASES = Object.freeze([
"route-current-active-offscreen",
"partial-active-ambiguous",
"visible-active-data-null-after-timeout",
]);
function createShortsPlaceholderPoolFixture() {
const fixtureConfig = JSON.stringify({
actionOrder: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
counts: SHORTS_PLACEHOLDER_POOL_COUNTS,
freshRouteEpochMs: SHORTS_FRESH_ROUTE_EPOCH_MS,
hops: SHORTS_PLACEHOLDER_POOL_HOPS,
marker: SHORTS_PLACEHOLDER_POOL_MARKER,
nativeLikePaintHop: SHORTS_NATIVE_LIKE_PAINT_HOP,
poolSize: SHORTS_PLACEHOLDER_POOL_SIZE,
syntheticSelector: SHORTS_SYNTHETIC_DISLIKE_SELECTOR,
videoIds: SHORTS_PLACEHOLDER_POOL_VIDEO_IDS,
});
return `
Shorts pre-rendered placeholder pool fixture
`;
}
async function installShortsPlaceholderPoolRoute(context, { onUnexpectedRequest = () => {} } = {}) {
if (!context?.route) throw new TypeError("A Playwright browser context is required.");
await context.route("https://www.youtube.com/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
if (
request.resourceType() === "document" &&
url.pathname === `/shorts/${SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[0]}` &&
url.searchParams.get("rydShortsPlaceholderPool") === "1"
) {
await route.fulfill({
body: createShortsPlaceholderPoolFixture(),
contentType: "text/html; charset=utf-8",
status: 200,
});
return;
}
onUnexpectedRequest({ method: request.method(), resourceType: request.resourceType(), url: request.url() });
await route.abort("blockedbyclient");
});
}
function shortsPlaceholderPoolUrl() {
return `https://www.youtube.com/shorts/${SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[0]}?${SHORTS_PLACEHOLDER_POOL_MARKER}`;
}
async function readShortsPlaceholderPoolSurface(page, videoId, logicalIndex) {
return page.evaluate(
({ actionOrder, expectedVideoId, index, syntheticSelector }) => {
const visibleInViewport = (element) => {
if (!element?.isConnected || element.closest("[hidden], [aria-hidden='true'], [inert]")) return false;
let opacity = 1;
for (let current = element; current; current = current.parentElement) {
const style = getComputedStyle(current);
if (style.display === "none" || ["hidden", "collapse"].includes(style.visibility)) {
return false;
}
const currentOpacity = Number.parseFloat(style.opacity || "1");
if (Number.isFinite(currentOpacity)) opacity *= currentOpacity;
}
if (opacity <= 0.01) return false;
const box = element.getBoundingClientRect();
return (
box.width > 0 &&
box.height > 0 &&
box.bottom > 0 &&
box.right > 0 &&
box.top < innerHeight &&
box.left < innerWidth
);
};
const box = (element) => {
if (!element) return null;
const bounds = element.getBoundingClientRect();
return {
bottom: bounds.bottom,
height: bounds.height,
left: bounds.left,
right: bounds.right,
top: bounds.top,
width: bounds.width,
};
};
const topHitAtCenter = (element) => {
if (!element) return false;
const bounds = element.getBoundingClientRect();
if (bounds.width <= 0 || bounds.height <= 0) return null;
const x = Math.min(innerWidth - 1, Math.max(0, bounds.left + bounds.width / 2));
const y = Math.min(innerHeight - 1, Math.max(0, bounds.top + bounds.height / 2));
return typeof document.elementFromPoint === "function"
? document.elementFromPoint(x, y)
: document.elementsFromPoint?.(x, y)?.[0] ?? null;
};
const hitTestedAtCenter = (element) => {
const hit = topHitAtCenter(element);
return hit === element || element.contains(hit);
};
const describeElement = (element) =>
element
? `${element.tagName.toLowerCase()}${element.id ? `#${element.id}` : ""}${[...element.classList]
.map((name) => `.${name}`)
.join("")}`
: null;
const fixture = globalThis.__shortsPlaceholderPoolFixture?.snapshot();
const renderer = document.querySelector(
`.reel-video-in-sequence-new[data-fixture-logical-index="${index}"] > ytd-reel-video-renderer`,
);
const actionBar = renderer?.querySelector("reel-action-bar-view-model") ?? null;
const actionHosts = [...(actionBar?.children ?? [])];
const actions = actionHosts.map((host) =>
host.matches(syntheticSelector) ? "dislike" : host.getAttribute("data-fixture-action"),
);
const buttons = actionHosts.map((host) =>
host.querySelector("button, a[href], a[role='button'][tabindex='0'], tp-yt-paper-button#button"),
);
const synthetic = actionBar?.querySelector(syntheticSelector) ?? null;
const nativeDislikes = actionBar?.querySelectorAll("dislike-button-view-model, #dislike-button") ?? [];
const dislike = actionHosts.find(
(host) => host.matches(syntheticSelector) || host.matches("dislike-button-view-model, #dislike-button"),
);
const visibleDocumentSynthetic = [...document.querySelectorAll(syntheticSelector)].filter(visibleInViewport);
const visibleDocumentActionButtons = [
...document.querySelectorAll(
"reel-action-bar-view-model button, reel-action-bar-view-model a[role='button'][tabindex='0']",
),
].filter(visibleInViewport);
const renderers = [...document.querySelectorAll("ytd-reel-video-renderer")];
const staleSyntheticOwners = [...document.querySelectorAll(syntheticSelector)]
.filter((control) => {
const owner = control.closest("ytd-reel-video-renderer")?.getAttribute("video-id");
return control.getAttribute("data-ryd-video-id") !== owner;
})
.map((control) => ({
controlVideoId: control.getAttribute("data-ryd-video-id"),
rendererVideoId: control.closest("ytd-reel-video-renderer")?.getAttribute("video-id") ?? null,
}));
return {
actionOrder,
actions,
actionBarBox: box(actionBar),
actionBarDataReady: Boolean(actionBar?.data),
actionBarPainted: actionBar?.getAttribute("data-fixture-painted") ?? null,
actionBarVisible: visibleInViewport(actionBar),
activeRenderers: renderers.filter((candidate) => candidate.hasAttribute("is-active")).length,
buttonBoxes: buttons.map(box),
buttonEnabled: buttons.map(
(button) => Boolean(button) && !button.disabled && button.getAttribute("aria-disabled") !== "true",
),
buttonHitTested: buttons.map(hitTestedAtCenter),
buttonTopHits: buttons.map((button) => describeElement(topHitAtCenter(button))),
buttonVisible: buttons.map(visibleInViewport),
dislikeCount: dislike?.querySelector("#text, [role='text']")?.textContent?.trim() ?? null,
dislikeKind: dislike?.matches(syntheticSelector) ? "synthetic" : dislike ? "native" : null,
dislikePressed: dislike?.querySelector("button")?.getAttribute("aria-pressed") ?? null,
fixture,
hostBoxes: actionHosts.map(box),
hostVisible: actionHosts.map(visibleInViewport),
pathname: location.pathname,
rendererBox: box(renderer),
rendererHydrated: renderer?.getAttribute("data-fixture-hydrated") ?? null,
rendererVideoId: renderer?.getAttribute("video-id") ?? null,
rendererVisible: visibleInViewport(renderer),
staleSyntheticOwners,
nativeDislikes: nativeDislikes.length,
syntheticCount: synthetic?.querySelector("#text, [role='text']")?.textContent?.trim() ?? null,
syntheticElements: actionBar?.querySelectorAll(syntheticSelector).length ?? 0,
syntheticOwner: synthetic?.getAttribute("data-ryd-video-id") ?? null,
syntheticPressed: synthetic?.querySelector("button")?.getAttribute("aria-pressed") ?? null,
visibleDocumentActionButtons: visibleDocumentActionButtons.length,
visibleDocumentRenderers: renderers.filter(visibleInViewport).length,
visibleDocumentSynthetic: visibleDocumentSynthetic.length,
videoId: expectedVideoId,
};
},
{
actionOrder: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
expectedVideoId: videoId,
index: logicalIndex,
syntheticSelector: SHORTS_SYNTHETIC_DISLIKE_SELECTOR,
},
);
}
function assertShortsPlaceholderPoolTransitionSafety(fixture, { logicalIndex, videoId }) {
assert.deepEqual(
fixture?.prematureSyntheticInsertions,
[],
`hop ${logicalIndex} inserted Dislike before the managed action bar reached hydration/readiness`,
);
assert.deepEqual(
fixture?.corruptedVideoIds,
[],
`hop ${logicalIndex} lost its native action stack after premature placeholder mutation`,
);
assert.deepEqual(
fixture?.freshEpochViolations,
[],
`hop ${logicalIndex} reused stale stability evidence after an eventless route round trip`,
);
assertNativeLikePaintHydrationSafety(fixture, { logicalIndex, videoId });
if (logicalIndex === 0) return;
const observations = fixture?.phaseObservations?.filter(
(observation) =>
observation.videoId === videoId && SHORTS_TRANSITION_OBSERVATION_PHASES.includes(observation.phase),
);
assert.deepEqual(
observations?.map((observation) => observation.phase),
SHORTS_TRANSITION_OBSERVATION_PHASES,
`hop ${logicalIndex} skipped a placeholder readiness phase`,
);
const [offscreen, partial, visibleDataNull] = observations;
const previousVideoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex - 1];
assert.deepEqual(offscreen.candidateVideoIds, [previousVideoId, videoId].sort());
assert.equal(offscreen.actionBarDataReady, false);
assert.equal(offscreen.hydrated, false);
assert.equal(offscreen.inViewport, false);
assert.equal(offscreen.meaningfulViewport, false);
assert.equal(offscreen.syntheticCount, 0, `hop ${logicalIndex} performed a premature control mutation`);
assert.deepEqual(partial.candidateVideoIds, [previousVideoId, videoId].sort());
assert.equal(partial.actionBarDataReady, false);
assert.equal(partial.hydrated, false);
assert.equal(partial.inViewport, true);
assert.equal(partial.meaningfulViewport, false);
assert.ok(partial.viewportRatio > 0 && partial.viewportRatio < 0.5);
assert.equal(partial.syntheticCount, 0, `hop ${logicalIndex} performed a premature control mutation`);
assert.deepEqual(visibleDataNull.candidateVideoIds, [videoId]);
assert.equal(visibleDataNull.actionBarDataReady, false);
assert.equal(visibleDataNull.hydrated, false);
assert.equal(visibleDataNull.inViewport, true);
assert.equal(visibleDataNull.meaningfulViewport, true);
assert.ok(visibleDataNull.viewportRatio >= 0.5);
assert.equal(visibleDataNull.syntheticCount, 0, `hop ${logicalIndex} performed a premature control mutation`);
}
function assertNativeLikePaintHydrationSafety(fixture, { logicalIndex, videoId }) {
if (logicalIndex !== SHORTS_NATIVE_LIKE_PAINT_HOP) return;
const observations = fixture?.nativeLikePaintObservations?.filter((observation) => observation.videoId === videoId);
assert.deepEqual(
observations,
[
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 0,
nativeLikeSvgPresent: false,
phase: "native-like-button-shell-only",
syntheticCount: 0,
videoId,
},
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 0,
nativeLikeSvgPresent: true,
phase: "native-like-empty-svg",
syntheticCount: 0,
videoId,
},
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 1,
nativeLikeSvgPresent: true,
phase: "native-like-painted-svg",
syntheticCount: 0,
videoId,
},
],
`hop ${logicalIndex} inserted Dislike before the exact native Like icon painted`,
);
}
function assertShortsPlaceholderPoolSurface(snapshot, { counts, dislikeKind = "synthetic", logicalIndex, videoId }) {
assert.equal(snapshot.pathname, `/shorts/${videoId}`, `hop ${logicalIndex} URL targets a stale Short`);
assert.equal(snapshot.fixture?.transitioning, false, `hop ${logicalIndex} fixture transition did not settle`);
assert.equal(snapshot.fixture?.currentIndex, logicalIndex, `hop ${logicalIndex} fixture index is stale`);
assert.equal(snapshot.fixture?.currentVideoId, videoId, `hop ${logicalIndex} fixture video is stale`);
assert.deepEqual(snapshot.fixture?.activeVideoIds, [videoId], `hop ${logicalIndex} has an ambiguous active renderer`);
assert.equal(snapshot.fixture?.slotCount, SHORTS_PLACEHOLDER_POOL_SIZE, "the physical placeholder pool changed size");
assertShortsPlaceholderPoolTransitionSafety(snapshot.fixture, { logicalIndex, videoId });
assert.equal(snapshot.activeRenderers, 1, `hop ${logicalIndex} must have one active renderer`);
assert.equal(snapshot.visibleDocumentRenderers, 1, `hop ${logicalIndex} must have one visible renderer`);
assert.equal(snapshot.rendererVideoId, videoId, `hop ${logicalIndex} selected a stale renderer`);
assert.equal(snapshot.rendererHydrated, "true", `hop ${logicalIndex} renderer is not hydrated`);
assert.equal(snapshot.rendererVisible, true, `hop ${logicalIndex} renderer is not visible`);
assert.equal(snapshot.actionBarDataReady, true, `hop ${logicalIndex} actionBar.data is not hydrated`);
assert.equal(snapshot.actionBarPainted, "true", `hop ${logicalIndex} action stack never reached its painted state`);
assert.equal(snapshot.actionBarVisible, true, `hop ${logicalIndex} action stack is not effectively visible`);
assert.deepEqual(
snapshot.actions,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
`hop ${logicalIndex} must retain every native action and exactly one synthetic Dislike`,
);
assert.deepEqual(
snapshot.hostVisible,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
);
assert.deepEqual(
snapshot.buttonVisible,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
);
assert.deepEqual(
snapshot.buttonHitTested,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
`hop ${logicalIndex} controls have rectangles but are not topmost/hit-testable in the active renderer; top hits: ${JSON.stringify(
snapshot.buttonTopHits,
)}`,
);
assert.deepEqual(
snapshot.buttonEnabled,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
);
assert.equal(snapshot.visibleDocumentActionButtons, SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.length);
assert.equal(snapshot.dislikeKind, dislikeKind, `hop ${logicalIndex} rendered the wrong Dislike implementation`);
assert.equal(snapshot.dislikePressed, "false", `hop ${logicalIndex} Dislike has an invalid initial state`);
assert.equal(snapshot.dislikeCount, String(counts.dislikes), `hop ${logicalIndex} rendered a stale dislike count`);
if (dislikeKind === "synthetic") {
assert.equal(snapshot.visibleDocumentSynthetic, 1, `hop ${logicalIndex} must show exactly one synthetic Dislike`);
assert.equal(snapshot.syntheticElements, 1, `hop ${logicalIndex} did not normalize duplicate synthetic controls`);
assert.equal(snapshot.nativeDislikes, 0, `hop ${logicalIndex} unexpectedly retained a native Dislike control`);
assert.equal(snapshot.syntheticOwner, videoId, `hop ${logicalIndex} Dislike targets a stale video`);
assert.equal(snapshot.syntheticPressed, "false", `hop ${logicalIndex} synthetic Dislike has an invalid state`);
assert.equal(
snapshot.syntheticCount,
String(counts.dislikes),
`hop ${logicalIndex} rendered a stale dislike count`,
);
} else {
assert.equal(snapshot.visibleDocumentSynthetic, 0, `hop ${logicalIndex} retained a visible synthetic Dislike`);
assert.equal(snapshot.syntheticElements, 0, `hop ${logicalIndex} retained duplicate synthetic controls`);
assert.equal(snapshot.nativeDislikes, 1, `hop ${logicalIndex} did not preserve exactly one native Dislike`);
}
assert.deepEqual(snapshot.staleSyntheticOwners, [], "an offscreen or current synthetic control has stale ownership");
assert.ok(snapshot.rendererBox?.width > 0 && snapshot.rendererBox?.height > 0, "the current renderer collapsed");
assert.ok(
snapshot.actionBarBox?.left >= snapshot.rendererBox.left - 1 &&
snapshot.actionBarBox?.right <= snapshot.rendererBox.right + 1 &&
snapshot.actionBarBox?.top >= snapshot.rendererBox.top - 1 &&
snapshot.actionBarBox?.bottom <= snapshot.rendererBox.bottom + 1,
`hop ${logicalIndex} action stack is outside the active rendered container`,
);
for (let index = 0; index < SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.length; index += 1) {
const host = snapshot.hostBoxes[index];
const button = snapshot.buttonBoxes[index];
assert.ok(host?.width >= 47 && host?.height >= 69, `hop ${logicalIndex} ${snapshot.actions[index]} host collapsed`);
assert.ok(
button?.width >= 47 && button?.height >= 47,
`hop ${logicalIndex} ${snapshot.actions[index]} button collapsed`,
);
assert.ok(button.left >= host.left - 1 && button.right <= host.right + 1, "an action button escaped its host");
if (index > 0) {
const previous = snapshot.hostBoxes[index - 1];
assert.ok(host.top >= previous.bottom - 1, `hop ${logicalIndex} action controls overlap`);
assert.ok(host.top <= previous.bottom + 1, `hop ${logicalIndex} action controls have an unexpected gap`);
}
}
}
function interactionRequests(records) {
return records.filter(
(record) => record.method === "POST" && ["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
);
}
async function waitForFixtureIndex(page, logicalIndex) {
await page.waitForFunction((index) => {
const snapshot = globalThis.__shortsPlaceholderPoolFixture?.snapshot();
return snapshot?.currentIndex === index && snapshot.transitioning === false;
}, logicalIndex);
}
async function waitForValidSurface(page, videoId, logicalIndex, { dislikeKind = "synthetic" } = {}) {
const counts = SHORTS_PLACEHOLDER_POOL_COUNTS[videoId];
await page.waitForFunction(
({ expectedCount, expectedDislikeKind, expectedOrder, expectedVideoId, index, syntheticSelector }) => {
const renderer = document.querySelector(
`.reel-video-in-sequence-new[data-fixture-logical-index="${index}"] > ytd-reel-video-renderer[is-active]`,
);
const actionBar = renderer?.querySelector("reel-action-bar-view-model");
const actions = [...(actionBar?.children ?? [])].map((host) =>
host.matches(syntheticSelector) ? "dislike" : host.getAttribute("data-fixture-action"),
);
const synthetic = actionBar?.querySelector(syntheticSelector);
const nativeDislike = actionBar?.querySelector("dislike-button-view-model, #dislike-button");
const dislike = expectedDislikeKind === "synthetic" ? synthetic : nativeDislike;
return (
location.pathname === `/shorts/${expectedVideoId}` &&
renderer?.getAttribute("video-id") === expectedVideoId &&
Boolean(actionBar?.data) &&
JSON.stringify(actions) === JSON.stringify(expectedOrder) &&
(expectedDislikeKind === "synthetic"
? actionBar?.querySelectorAll(syntheticSelector).length === 1 &&
!nativeDislike &&
synthetic?.getAttribute("data-ryd-video-id") === expectedVideoId
: actionBar?.querySelectorAll(syntheticSelector).length === 0 && Boolean(nativeDislike)) &&
dislike?.querySelector("#text, [role='text']")?.textContent?.trim() === expectedCount
);
},
{
expectedCount: String(counts.dislikes),
expectedDislikeKind: dislikeKind,
expectedOrder: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
expectedVideoId: videoId,
index: logicalIndex,
syntheticSelector: SHORTS_SYNTHETIC_DISLIKE_SELECTOR,
},
);
}
async function assertSurfaceSoak(
page,
videoId,
logicalIndex,
{ dislikeKind = "synthetic", durationMs = 240, intervalMs = 40 } = {},
) {
const deadline = Date.now() + durationMs;
let samples = 0;
do {
const snapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
dislikeKind,
logicalIndex,
videoId,
});
samples += 1;
if (Date.now() >= deadline && samples >= 2) break;
await page.waitForTimeout(intervalMs);
} while (true);
return samples;
}
async function assertActionBarPixelOracle(page, videoId, logicalIndex) {
const actionBar = page.locator(
`.reel-video-in-sequence-new[data-fixture-logical-index="${logicalIndex}"] > ` +
`ytd-reel-video-renderer[video-id="${videoId}"] reel-action-bar-view-model`,
);
const screenshot = await actionBar.screenshot({ animations: "disabled", scale: "css" });
// Playwright already ships this decoder; keeping the oracle on its pinned
// dependency avoids platform-specific golden screenshots and another package.
const { PNG } = require("playwright-core/lib/utilsBundle");
const image = PNG.sync.read(screenshot);
assert.ok(image.width >= 47, `hop ${logicalIndex} pixel oracle captured a collapsed action stack`);
assert.ok(image.height >= 419, `hop ${logicalIndex} pixel oracle captured a truncated action stack`);
const brightPixelsByAction = SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map((action, actionIndex) => {
const startY = Math.floor((actionIndex * image.height) / SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.length);
const endY = Math.floor(((actionIndex + 1) * image.height) / SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.length);
let brightPixels = 0;
for (let y = startY; y < endY; y += 1) {
for (let x = 0; x < image.width; x += 1) {
const offset = (y * image.width + x) * 4;
const red = image.data[offset];
const green = image.data[offset + 1];
const blue = image.data[offset + 2];
const alpha = image.data[offset + 3];
if (alpha >= 200 && red >= 160 && green >= 160 && blue >= 160) brightPixels += 1;
}
}
assert.ok(brightPixels >= 12, `hop ${logicalIndex} ${action} has geometry but no painted high-contrast pixels`);
return brightPixels;
});
return { brightPixelsByAction, height: image.height, logicalIndex, videoId, width: image.width };
}
function assertNativeDislikeCleanupSurface(snapshot, { logicalIndex, videoId }) {
assert.deepEqual(
snapshot.fixture?.seededNormalizationStates?.find(
(state) => state.phase === "native-and-multiple-synthetics" && state.videoId === videoId,
),
{
nativeDislikes: 1,
phase: "native-and-multiple-synthetics",
syntheticCount: 3,
videoId,
},
`hop ${logicalIndex} did not seed the native-plus-duplicate cleanup state`,
);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
dislikeKind: "native",
logicalIndex,
videoId,
});
}
function assertDuplicateSyntheticNormalization(snapshot, { logicalIndex, videoId }) {
assert.deepEqual(
snapshot.fixture?.seededNormalizationStates?.find(
(state) => state.phase === "duplicate-synthetics" && state.videoId === videoId,
),
{
nativeDislikes: 0,
phase: "duplicate-synthetics",
syntheticCount: 2,
videoId,
},
`hop ${logicalIndex} did not seed the duplicate-only synthetic state`,
);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
logicalIndex,
videoId,
});
}
function assertEventlessSameVideoReturnSafety(fixture, { logicalIndex, videoId }) {
assert.deepEqual(
fixture?.freshEpochViolations,
[],
`hop ${logicalIndex} reused stale pre-route stability evidence for ${videoId}`,
);
const observations = fixture?.phaseObservations?.filter(
(observation) =>
observation.videoId === videoId &&
["eventless-pending-before-route-away", "eventless-same-video-return-fresh-epoch"].includes(observation.phase),
);
assert.deepEqual(
observations?.map(
({ actionBarDataReady, candidateVideoIds, hydrated, meaningfulViewport, phase, syntheticCount }) => ({
actionBarDataReady,
candidateVideoIds,
hydrated,
meaningfulViewport,
phase,
syntheticCount,
}),
),
[
{
actionBarDataReady: true,
candidateVideoIds: [videoId],
hydrated: true,
meaningfulViewport: true,
phase: "eventless-pending-before-route-away",
syntheticCount: 0,
},
{
actionBarDataReady: true,
candidateVideoIds: [videoId],
hydrated: true,
meaningfulViewport: true,
phase: "eventless-same-video-return-fresh-epoch",
syntheticCount: 0,
},
],
`hop ${logicalIndex} inserted before a fresh same-video stability epoch elapsed`,
);
}
async function runShortsPlaceholderPoolContract({ page, readRequests, runtimeName }) {
if (!page || typeof readRequests !== "function") {
throw new TypeError("The shared Shorts placeholder-pool contract requires page and readRequests().");
}
assert.ok(["extension", "userscript"].includes(runtimeName), `Unsupported runtime ${runtimeName}`);
const documentIdentity = await page.evaluate(() => {
const marker = `${Date.now()}-${Math.random()}`;
globalThis.__shortsPlaceholderPoolDocumentIdentity = marker;
return marker;
});
const results = [];
for (let logicalIndex = 0; logicalIndex <= SHORTS_PLACEHOLDER_POOL_HOPS; logicalIndex += 1) {
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
if (logicalIndex > 0) {
await page.locator("#fixture-next-short").click();
await waitForFixtureIndex(page, logicalIndex);
}
const transitionFixture = await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture?.snapshot());
assertShortsPlaceholderPoolTransitionSafety(transitionFixture, { logicalIndex, videoId });
await waitForValidSurface(page, videoId, logicalIndex);
let snapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
logicalIndex,
videoId,
});
const pixelOracle = SHORTS_PIXEL_ORACLE_HOPS.has(logicalIndex)
? await assertActionBarPixelOracle(page, videoId, logicalIndex)
: null;
let soakSamples = await assertSurfaceSoak(page, videoId, logicalIndex);
if (logicalIndex === SHORTS_DUPLICATE_NORMALIZATION_HOP) {
await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture.seedSyntheticDuplicates());
await waitForValidSurface(page, videoId, logicalIndex);
snapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertDuplicateSyntheticNormalization(snapshot, { logicalIndex, videoId });
}
if (logicalIndex === SHORTS_NATIVE_CLEANUP_HOP) {
await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture.seedNativeDislikeAndSyntheticDuplicates());
await waitForValidSurface(page, videoId, logicalIndex, { dislikeKind: "native" });
const nativeSnapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertNativeDislikeCleanupSurface(nativeSnapshot, { logicalIndex, videoId });
soakSamples += await assertSurfaceSoak(page, videoId, logicalIndex, {
dislikeKind: "native",
durationMs: 160,
});
await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture.removeNativeDislikeForSyntheticRecovery());
await waitForValidSurface(page, videoId, logicalIndex);
snapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
logicalIndex,
videoId,
});
}
if (logicalIndex === SHORTS_EVENTLESS_RETURN_HOP) {
await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture.eventlessSameVideoReturn());
const eventlessFixture = await page.evaluate(() => globalThis.__shortsPlaceholderPoolFixture.snapshot());
assertEventlessSameVideoReturnSafety(eventlessFixture, { logicalIndex, videoId });
await waitForValidSurface(page, videoId, logicalIndex);
snapshot = await readShortsPlaceholderPoolSurface(page, videoId, logicalIndex);
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
logicalIndex,
videoId,
});
}
assert.equal(
await page.evaluate(() => globalThis.__shortsPlaceholderPoolDocumentIdentity),
documentIdentity,
`hop ${logicalIndex} replaced the document instead of using SPA navigation`,
);
const requests = readRequests();
assertExactSuccessfulVotesTraffic(
requests,
SHORTS_PLACEHOLDER_POOL_VIDEO_IDS.slice(0, logicalIndex + 1),
`Shorts placeholder-pool hop ${logicalIndex}`,
);
assert.deepEqual(
interactionRequests(requests),
[],
`hop ${logicalIndex} submitted a vote without a reaction click`,
);
results.push({ logicalIndex, pixelOracle, soakSamples, snapshot, videoId });
}
assert.equal(results.length - 1, SHORTS_PLACEHOLDER_POOL_HOPS);
assert.ok(SHORTS_PLACEHOLDER_POOL_HOPS >= 10, "the placeholder-pool contract must exercise at least ten Next clicks");
assert.deepEqual(
results.at(-1).snapshot.fixture.logicalIndexes,
Array.from({ length: SHORTS_PLACEHOLDER_POOL_SIZE }, (_, index) => index + 1),
"the final hop did not cross the pre-rendered pool boundary into a recycled physical slot",
);
return results;
}
module.exports = {
SHORTS_DUPLICATE_NORMALIZATION_HOP,
SHORTS_EVENTLESS_RETURN_HOP,
SHORTS_FRESH_ROUTE_EPOCH_MS,
SHORTS_NATIVE_CLEANUP_HOP,
SHORTS_NATIVE_LIKE_PAINT_HOP,
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
SHORTS_PLACEHOLDER_POOL_COUNTS,
SHORTS_PLACEHOLDER_POOL_HOPS,
SHORTS_PLACEHOLDER_POOL_MARKER,
SHORTS_PLACEHOLDER_POOL_SIZE,
SHORTS_PLACEHOLDER_POOL_VIDEO_IDS,
assertActionBarPixelOracle,
assertDuplicateSyntheticNormalization,
assertEventlessSameVideoReturnSafety,
assertNativeLikePaintHydrationSafety,
assertNativeDislikeCleanupSurface,
assertShortsPlaceholderPoolSurface,
assertShortsPlaceholderPoolTransitionSafety,
createShortsPlaceholderPoolFixture,
installShortsPlaceholderPoolRoute,
readShortsPlaceholderPoolSurface,
runShortsPlaceholderPoolContract,
shortsPlaceholderPoolUrl,
};