Back to Shiftfield
SOURCE / PINNED RELEASE

Made of little things.

Shiftfield

Release
5a170c505f6b…
Author-recorded commit
a2e23e0171aa…
License
LICENSE
Author’s source reference
nostr://npub16nzc4ql748r2kv9202rgzrt0fmtk4n3tzsjl86yf6ty9agqe9u0qjcc7hc/wss%3A%2F%2Fgit.napplet.soy%2F/n-e4fb6341ccd

Archive hash verified: 66de7623efd91da1…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

tests/perf.test.mjs
/* Minesweeper DX — blast-window frame harness (P1/P2 acceptance gate).
 *
 * Measures dropped frames in the 750 ms after a fatal boom, A/B WITHIN ONE
 * PAGE SESSION (cross-run frame timing is too noisy to see 1-3 dropped
 * frames — see docs/perf review in the llm-wiki).
 *
 * A/B mechanism: the P1a fix is the CSS rule
 *   .overlay:has(.death-blast) { backdrop-filter: none; }
 * so "as-built baseline" is reproduced at runtime by injecting an
 * !important rule that restores the blur during the death blast. Runs
 * alternate baseline/fixed (counterbalanced) and stats are pooled.
 *
 * Caveat (same as the original review): headless SwiftShader software
 * raster exaggerates blur cost; relative numbers are the signal.
 *
 * Run: pnpm test:perf   (requires pnpm build; NOT part of `verify` — run on
 * demand, software-raster hosts may flake the absolute drop counts)
 */
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { dirname, join, extname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';

const root = dirname(dirname(fileURLToPath(import.meta.url)));
const dist = join(root, 'dist');

const MIME = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
};

async function serveDist() {
  const server = createServer(async (req, res) => {
    const path = req.url === '/' ? '/index.html' : req.url.split('?')[0];
    try {
      const body = await readFile(join(dist, path.slice(1)));
      res.writeHead(200, { 'content-type': MIME[extname(path)] ?? 'application/octet-stream' });
      res.end(body);
    } catch {
      res.writeHead(404).end('not found');
    }
  });
  await new Promise((ok) => server.listen(0, '127.0.0.1', ok));
  const { port } = server.address();
  return { url: `http://127.0.0.1:${port}/`, close: () => server.close() };
}

const BLAST_WINDOW_MS = 750;
const FRAME_BUDGET_MS = 33; // 2× of a 60 Hz frame
const ROUNDS = 3; // per condition

const service = await serveDist();
const browser = await chromium.launch();

// Records rAF deltas for BLAST_WINDOW_MS starting immediately before the
// fatal click; returns { median, p95, overBudget }. The detonation is a REAL
// DOM click (not an engine call): the boom fx pipeline and the .death-blast
// mark are gated to Board.afterAction, so only a clicked death shakes.
async function blastRun(page) {
  return page.evaluate(
    async ([windowMs, budget]) => {
      const g = window.minesweeperDx;
      const eng = g.board.game;
      eng.firstClickSafe = false;
      const mine = eng.world.tiles.find((t) => t.hasMine && t.state === 'HIDDEN');
      const cell = document.querySelector(`.cell[data-cell="${mine.coord[0]},${mine.coord[1]}"]`);
      const frames = [];
      let last = performance.now();
      const t0 = last;
      await new Promise((done) => {
        const tick = (now) => {
          frames.push(now - last);
          last = now;
          if (now - t0 < windowMs) requestAnimationFrame(tick);
          else done();
        };
        // Detonate inside the sampling window, frame 1 = boom frame.
        cell.click();
        requestAnimationFrame(tick);
      });
      frames.shift(); // first delta is the sampling-start gap, not a frame
      const sorted = [...frames].sort((a, b) => a - b);
      const q = (p) => sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
      return {
        frames: frames.length,
        median: +q(0.5).toFixed(1),
        p95: +q(0.95).toFixed(1),
        overBudget: frames.filter((f) => f > budget).length,
      };
    },
    [BLAST_WINDOW_MS, FRAME_BUDGET_MS],
  );
}

async function startRun(page) {
  await page.click('#startRunBtn');
  await page.waitForFunction(() => window.minesweeperDx.phase === 'running');
}

async function resetToMenu(page) {
  await page.click('#summaryMenuBtn');
  await page.waitForFunction(() => window.minesweeperDx.phase === 'menu');
}

try {
  const page = await browser.newPage({ viewport: { width: 900, height: 600 } });
  await page.goto(service.url, { waitUntil: 'load' });
  await page.waitForFunction(() => window.minesweeperDx !== undefined);

  // Baseline condition: force the blur back ON during the death blast
  // (reverts the P1a fix at runtime, !important beats the fix rule).
  // The tag is disabled for the "fixed" condition.
  await page.addStyleTag({
    content: `/* perf: revert P1a */
      .overlay:has(.death-blast) { backdrop-filter: blur(3px) !important;
      -webkit-backdrop-filter: blur(3px) !important; }`,
  });
  await page.evaluate(() => {
    for (const s of document.querySelectorAll('style')) {
      if (s.textContent.includes('perf: revert P1a')) s.dataset.perfBaseline = '1';
    }
  });

  const results = { baseline: [], fixed: [] };
  for (let round = 0; round < ROUNDS; round++) {
    // Counterbalance order so drift cannot favor one condition.
    const order = round % 2 === 0 ? ['baseline', 'fixed'] : ['fixed', 'baseline'];
    for (const cond of order) {
      await page.evaluate(
        (enable) => {
          const tag = document.querySelector('[data-perf-baseline]');
          if (!tag) throw new Error('baseline style tag not found');
          tag.disabled = !enable;
        },
        cond === 'baseline',
      );
      await startRun(page);
      const stat = await blastRun(page);
      results[cond].push(stat);
      await resetToMenu(page);
    }
  }

  const pool = (arr) => ({
    median: arr.map((s) => s.median),
    p95: arr.map((s) => s.p95),
    drops: arr.map((s) => s.overBudget),
  });
  const base = pool(results.baseline);
  const fix = pool(results.fixed);
  const maxDrops = (d) => Math.max(...d);
  console.log(`baseline (blur during blast): p95 ${base.p95.join('/')} ms, >${FRAME_BUDGET_MS}ms drops ${base.drops.join('/')}`);
  console.log(`fixed    (no blur in blast) : p95 ${fix.p95.join('/')} ms, >${FRAME_BUDGET_MS}ms drops ${fix.drops.join('/')}`);

  assert.ok(
    maxDrops(fix.drops) === 0,
    `P1 acceptance: fixed condition must show 0 frames > ${FRAME_BUDGET_MS} ms in the blast window, got ${fix.drops.join('/')}`,
  );
  console.log('PASS: 0 frames over budget in the blast window with the P1a fix active');

  // ---------------- P2 suite: fx-on vs fx-off ---------------------------
  // P2 acceptance (perf doc): with the P1 blur already off, the fx canvas
  // must cost NOTHING measurable in the blast window — dropping the whole
  // layer (`#fx{display:none}`) has to leave drop counts IDENTICAL to the
  // as-built fx-on run. Before P2 the review measured fx-off still shedding
  // a frame relative to all-off; the empty-frame skip + blast-clamped
  // chroma ghosts + single screen pass are what closes that gap.
  await page.evaluate(() => {
    document.querySelector('[data-perf-baseline]').disabled = true; // P1 fix stays ON
  });
  await page.addStyleTag({
    content: '/* perf: fx off */ #fx { display: none !important; }',
  });
  await page.evaluate(() => {
    for (const s of document.querySelectorAll('style')) {
      if (s.textContent.includes('perf: fx off')) s.dataset.perfFxoff = '1';
    }
  });

  const fxResults = { 'fx-on': [], 'fx-off': [] };
  for (let round = 0; round < ROUNDS; round++) {
    const order = round % 2 === 0 ? ['fx-on', 'fx-off'] : ['fx-off', 'fx-on'];
    for (const cond of order) {
      await page.evaluate(
        (fxOff) => {
          const tag = document.querySelector('[data-perf-fxoff]');
          if (!tag) throw new Error('fx-off style tag not found');
          tag.disabled = !fxOff;
        },
        cond === 'fx-off',
      );
      await startRun(page);
      fxResults[cond].push(await blastRun(page));
      await resetToMenu(page);
    }
  }

  const fxOn = pool(fxResults['fx-on']);
  const fxOff = pool(fxResults['fx-off']);
  console.log(`fx-on  (as-built P2 fix): p95 ${fxOn.p95.join('/')} ms, >${FRAME_BUDGET_MS}ms drops ${fxOn.drops.join('/')}`);
  console.log(`fx-off (#fx display:off): p95 ${fxOff.p95.join('/')} ms, >${FRAME_BUDGET_MS}ms drops ${fxOff.drops.join('/')}`);

  assert.deepEqual(
    fxOn.drops,
    fxOff.drops,
    `P2 acceptance: fx-on drop counts must be identical to fx-off, got ${fxOn.drops.join('/')} vs ${fxOff.drops.join('/')}`,
  );
  assert.ok(
    maxDrops(fxOn.drops) === 0,
    `P2 acceptance: fx-on must show 0 frames > ${FRAME_BUDGET_MS} ms in the blast window, got ${fxOn.drops.join('/')}`,
  );
  console.log('PASS: fx canvas layer is drop-neutral in the blast window (fx-on === fx-off, 0 drops)');
} finally {
  await browser.close();
  await service.close();
}