Frontend developer inspecting web font registration and loading status in browser developer tools.

Why document.fonts.check() Can Return True for Missing Web Fonts

Wed, Nov 25, 2026

A unique font family that does not exist in document.fonts can still make document.fonts.check() return true. That result is not contradictory once the API contract is read precisely: check() answers whether rendering the supplied text/font combination would require an unloaded matching face, not whether the application actually registered the family it intended. The CSS Font Loading specification explicitly calls out the nonexistent-name case and says an empty matching-face list produces true; the corresponding FontFaceSet.load() algorithm can fulfill with an empty sequence because there are no matching faces to load.

For release verification, that distinction is large enough to require a different gate. The application should prove that an explicitly owned FontFace exists in the document's FontFaceSet, that its descriptors agree with the authored query, that the owned object has loaded, that document.fonts.load() returns the same in-page object when a match is expected, and that every required ASCII code point is within the admitted faces' declared unicodeRange. A fulfilled promise or check() === true is evidence, but neither is sufficient admission evidence by itself. MDN likewise describes load() as resolving to an array of loaded FontFace objects and notes that its text argument filters by Unicode-range overlap rather than individual glyph coverage.

The laboratory below is deliberately unexecuted. Every F01–F10 behavior is EXPECTED / NOT EXECUTED as of November 25, 2026. Playwright Python 1.62.0 is the runner baseline; its release documentation identifies bundled Chromium version 151.0.7922.34. The research metadata supplied for this laboratory records packaged Chromium revision 1234. Those are package descriptors, not evidence that a browser binary was installed or launched. An actual laboratory run must separately record browser.version().

Define what the font gate must prove

The narrow contract is owned font-resource readiness, not “the intended font rendered every glyph.” An accepted row means the intended application-owned FontFace is present in document.fonts, has the declared family/style/weight/stretch and source identity, is loaded, is returned by the matching FontFaceSet.load() request where the policy requires that return, and collectively covers the fixture's required ASCII code points according to authored unicodeRange descriptors.

That contract has four separable questions:

Layer

Required evidence

What it does not prove

Registration

document.fonts.has(expectedFace) === true

Loading completion

Loading

owned FontFace.status === "loaded"

Current set membership

Query matching

returned FontFace identities and manifest/query agreement

Complete required-text coverage

Declared coverage

each required A/B code point is inside an admitted owned range

Binary glyph presence, shaping, or rendered font choice

The distinction between an object and the document set matters because the CSS Font Loading API permits a FontFace to load before or after it is added to a FontFaceSet; MDN explicitly states that a face must be added before it can be used for drawing. The status values are unloaded, loading, loaded, and error.

The application therefore owns a manifest rather than asking the browser to infer application intent. For each case it records the case ID, unique family, stable application face ID, immutable fixture revision, actual SHA-256 once the asset is prepared, source path, style, weight, stretch, authored unicodeRange, required text and code points, expected membership, and expected loading evidence. Developers who need prerequisite markup and CSS context can review Refonte Learning's HTML and CSS foundations; the gate here begins after those fundamentals and tests the CSS Font Loading API rather than basic font styling.

The ownership ID is an application identifier. JavaScript object identity is checked inside the page with ===, Map, and FontFaceSet.has(). JSON receives only assigned IDs and descriptors. Serializing two object descriptions that happen to look equal must never be treated as proof that they were the same FontFace.

first-img-fonts

Trace the documented empty-match behavior

The decisive behavior is in the CSS Font Loading Module Level 3 matching algorithm. The user agent parses the supplied CSS font shorthand, determines candidate families and style attributes, selects available matching faces, records whether any family/style face was found, and then removes faces whose declared Unicode range does not contain at least one character from the supplied text. The default text is a single space, which is why this fixture never relies on that default: each call supplies "A", "B", or "AB" explicitly.

FontFaceSet.check() then returns true if the resulting face list is empty, or if every remaining face is loaded or is a system font. The specification specifically highlights two counterintuitive outcomes: a nonexistent or misspelled family returns true, and a family whose candidate faces are all filtered out by unicode-range can also return true. In both situations there is no matching unloaded face whose later completion would cause the font-loading transition that check() is designed to detect.

MDN summarizes the same boundary: check() means the supplied text can be handled without attempting to use not-yet-loaded faces from the set. Its nonexistent-font example explicitly evaluates to true. That shorthand is useful, but the specification is the authority for the exact selection and filtering steps.

FontFaceSet.load() performs the matching operation without the check() method's boolean return. It calls load() for each selected face and resolves after those faces' status promises settle. If selection produced zero faces, waiting for all promises in an empty list produces an empty sequence. Therefore await document.fonts.load(query, text) fulfilling does not by itself prove that the requested family existed. Inspect the returned identities and count.

Read an empty match set correctly

The APIs expose different evidence types. check() yields a boolean; load() yields a promise whose fulfillment value is an array of FontFace objects. Do not collapse those into “font succeeded.”

Situation

check()

load() fulfillment

Owned-face evidence

Unique absent family

true expected

[] expected

absent

Matching unloaded registered face

false expected before load

eventually [face] if load succeeds

present

Matching loaded registered face

true expected

[face] expected

present

Existing face filtered out by required text

true expected

[] expected

face may exist, but not for that text

Loaded object never registered

true expected for its absent family in the set

[] expected

object exists independently

The mistake is treating true as an existence predicate. It is not. The release predicate has to add the inventory requirement that the browser API was never asked to infer.

Pin the browser and own the font fixture

The fixture uses a same-origin local HTTP server, one empty shell document per case, JavaScript-created FontFace objects, and one vendored Ahem font. WPT documents Ahem as a deliberately controlled web-testing font and recommends loading it as a web font rather than relying on installed machine fonts. Its documentation also recommends a minimum 20px computed size for stable Ahem testing; this laboratory uses the requested 20px "<family>" query.

The font bytes must be prepared before execution from an official WPT distribution identified by that documentation. Record the immutable distribution revision, copied filename, and SHA-256. This research did not download the binary and therefore supplies no digest. The runner below refuses to start without a declared expected digest and verifies the local file before browser launch. An absent or digest-mismatched fixture is HOLD_ENVIRONMENT; substituting a system font is not permitted.

W3C's Ahem documentation maps the large ASCII span U+0028–U+006F, which contains both A (U+0041) and B (U+0042). That makes A/B suitable fixture inputs, but this documentation is contextual evidence about the asset, not a browser observation that a particular binary rendered either character in an executed run.

Playwright Python 1.62.0 is the runner baseline. Official Python release notes list Chromium 151.0.7922.34; the supplied package-metadata inspection records revision 1234. Neither fact substitutes for executing browser.version().

After fixture preparation, all browser requests remain same-origin and local: /case.html, /lab.js, /fonts/ahem.ttf, plus /fonts/deliberate-404.ttf, which intentionally returns HTTP 404. If a served asset path is wrong, repair and validate assets after a frontend build change independently; this article does not broaden into build-tool migration.

Establish independent face and source identities

A run-specific ASCII token prevents accidental matching with another case. Each case gets a family such as OwnedAhem_r7c9_F05; F06 additionally creates a distinct typo-query name. No generic fallback and no local() source appears in the test shorthand or FontFace source.

The manifest uses fixed descriptors:

{
  style: "normal",
  weight: "400",
  stretch: "normal",
  unicodeRange: "U+0041-0042"
}

The restricted controls instead declare U+0041. Source identity is (fixtureRevision, sha256, localPath), while face identity is the actual page-side FontFace object associated with an assigned ID such as face:F05:primary.

The page registry therefore has two directions: id -> {face, metadata} and face -> id. Returned API objects are translated through the second map. An unrecognized returned object becomes UNKNOWN_FONTFACE and causes verification to fail rather than being silently accepted.

Reproduce a missing family that passes the check

F01 is the smallest demonstration. The document contains no manually registered face for its unique family and no CSS @font-face. The shell creates no text node that uses the family before measurement.

The case asks:

const query = 20px "${family}";
const checked = document.fonts.check(query, "AB");
const loaded = await document.fonts.load(query, "AB");

According to the specification, the expected result is checked === true and loaded.length === 0, because no family/style candidate exists.

A test that reads only the first line would falsely admit the case. The stricter gate requires an expected owned face and therefore produces HOLD_MISSING_FACE.

ID

Controlled condition

Expected API evidence

Decision

F01

Unique family has no registered face

check=true; load=[]; expected face absent

HOLD_MISSING_FACE

All entries in this article remain EXPECTED / NOT EXECUTED. A report template for this row must therefore retain observed.check, observed.loadReturnedFaceIds, actual browser version, timestamps from execution, and request observations as null until a run actually occurs.

This is the central false-positive assumption: document.fonts.check() is behaving according to its documented contract. The application was asking the wrong question.

Awaiting ready still does not create an intended font

F02 prevents a common attempted repair: “wait for document.fonts.ready, then call check().”

FontFaceSet.ready resolves when the document is done with the font loading and relevant layout work represented by that set. The specification describes it as a mechanism for waiting until the document's font-loading work has settled; it is not a declaration that every font an application hoped to register is now present.

The case starts with an empty controlled document, awaits:

await document.fonts.ready;

and only then queries its absent unique family. The expected sequence remains ready fulfilled, check(query, "AB") === true, load(query, "AB") fulfilled with [], and no expected face in the set. Decision: HOLD_MISSING_FACE.

The important ownership boundary is conceptual. The browser knows which faces are in its FontFaceSet; it does not possess the application's external manifest saying “F02 should contain face:F02:primary sourced from revision X.” If registration code never ran, ready has no missing-intent inventory to compare against.

A release gate therefore treats ready as sequencing evidence only. It can establish that the current document font-set loading lifecycle reached its ready condition. It cannot manufacture or certify an application requirement that is absent from that set.

Separate loaded objects from registered faces

F03–F05 isolate the three states that often get conflated: registered-but-unloaded, loaded-but-unregistered, and registered-and-loaded.

F03 creates a valid URL-backed face with U+0041-0042, adds it to document.fonts, and deliberately does not call either FontFace.load() or FontFaceSet.load() before measurement. URL-backed faces begin unloaded when their definition is valid; MDN distinguishes this from binary-backed construction and documents the normal status transitions.

Expected F03 evidence is document.fonts.has(face) === true, face.status === "unloaded", and document.fonts.check(query, "AB") === false. load is NOT_REQUESTED, not []. Those two states mean different things: an empty array is an observed fulfilled call, while NOT_REQUESTED means the API was intentionally not invoked so the pre-load state could be preserved. Decision: HOLD_NOT_LOADED.

F04 reverses the ownership relationship. It creates the face and calls await face.load() directly but never adds the object to document.fonts. MDN explicitly allows loading before adding. Expected evidence is face.status === "loaded" but document.fonts.has(face) === false. A set query for that unique family still sees no registered matching face, so check() is expected true and document.fonts.load() returns [].

The independent object is real and owned, but it is not admitted to the document set. F04 is therefore HOLD_MISSING_FACE.

F05 creates, registers, and loads the positive face. The set query for "AB" must return the exact registered object, not merely some face with equivalent serialized descriptors. Expected evidence is has=true, status loaded, check=true, and one returned ID equal to face:F05:primary. The explicit coverage policy also confirms both U+0041 and U+0042 are inside the face's declared range. Only then does the decision become ACCEPT_OWNED_FACE_READINESS.

Compare unloaded, unregistered, and admitted states

Case

Owned object

In document.fonts

Object status

Set load()

Decision

F03

yes

yes

unloaded

NOT_REQUESTED

HOLD_NOT_LOADED

F04

yes

no

loaded

expected []

HOLD_MISSING_FACE

F05

yes

yes

loaded

expected exact owned face

ACCEPT_OWNED_FACE_READINESS

This compact comparison is why neither FontFace.status nor FontFaceSet.has() is sufficient alone. Readiness requires both current set membership and completed loading, followed by query identity and declared-coverage checks.

Validate the query against the manifest

F06 holds the loaded object, source, descriptors, and document membership constant while changing the query family to another run-specific name.

Suppose the intended face family is:

OwnedAhem_r7c9_F06

but the query is:

20px "OwnedAhem_r7c9_F06_typo"

The expected API behavior is another empty match: check === true and load === []. The intended face still exists, is loaded, and is in document.fonts; it simply is not the face named by the query. The specification explicitly uses misspelled names as an example of the nonexistent-family true result.

This deserves its own decision, HOLD_QUERY_MISMATCH, rather than HOLD_MISSING_FACE. The resource is present; the caller asked for the wrong family.

The laboratory therefore performs query/manifest agreement independently of API results. Because the fixture owns the shorthand, it need not write a general CSS parser. It constructs the only legal query form from manifest data and compares the actual requested family and expected 20px normal-style/400/normal-stretch policy with that authored value.

That separation prevents a dangerous circular test: “the API returned nothing, therefore perhaps nothing was expected.” The manifest decides what was expected before the API call.

Test partial text overlap before accepting coverage

Unicode-range filtering creates the second major false-positive shape.

F07 registers an unloaded face whose authored descriptor is unicodeRange: "U+0041", then queries the family with explicit text "B". The family and style can match initially, but U+0042 is outside the face's declared range. The specification removes a face when its range contains none of the characters in the supplied text. Once that only face is removed, check() sees an empty list and is therefore expected to return true; load() is expected to fulfill with [], leaving the face unloaded.

That does not mean “B is ready in the owned font.” It means no selected face in this set needs loading for B. F07 is HOLD_DECLARED_COVERAGE.

F08 is more subtle. Register the same A-only face and load it first. Query "AB". The matching algorithm tests whether a face's declared Unicode range includes at least one character from the supplied text. Since U+0041 overlaps A, the face remains selected despite B being outside its authored range. The expected load() result is therefore nonempty and contains the owned face.

A verifier that checks only returned.length > 0 would accept F08 incorrectly. The local policy must iterate every required code point and require that each one is covered by at least one intended, admitted owned face.

For this fixture, that checker can remain deliberately tiny:

function requiredCodePoints(text) {
  return Array.from(text, ch => ch.codePointAt(0));
}

function covers(cp, ranges) {
  return ranges.some(([lo, hi]) => cp >= lo && cp <= hi);
}

function declaredCoverage(text, admittedFaces) {
  return requiredCodePoints(text).map(cp => ({
    codePoint: U+${cp.toString(16).toUpperCase().padStart(4, "0")},
    covered: admittedFaces.some(face => covers(cp, face.ranges)),
  }));
}

There is no reason to implement a general unicode-range grammar for a test whose only legal policies are [[0x41,0x42]] and [[0x41,0x41]].

Ahem's published mapping includes A and B, supporting their selection as controlled inputs, but the descriptor gate does not inspect the binary's actual cmap, shape text, or observe fallback.

The boundary also keeps this laboratory away from another concern: grapheme boundaries are a separate text contract. Here the complete authored text universe is fixed ASCII "A", "B", and "AB"; there is no segmentation problem to solve.

A nonempty load result can still miss a required range

F08 demonstrates why “nonempty load()” and “complete required coverage” are different predicates.

required text:      A B
declared U+0041:    ✓ ✗
load() selected:    face:F08:primary
application gate:   HOLD_DECLARED_COVERAGE

The policy is descriptor-based. It says every authored required code point must belong to the declared ranges of admitted intended faces. It does not prove that a font binary contains a usable glyph, that shaping selected that glyph, that fallback did not participate, or that visual output is correct. MDN similarly warns that the text parameter's range filtering is not an individual-glyph-coverage test.

Preserve load failures as failures

F09 uses a separately owned URL, /fonts/deliberate-404.ttf, which the local server always answers with status 404 and a controlled content type.

The face is added to document.fonts, then the case invokes:

await document.fonts.load(query, "AB");

inside a bounded promise deadline. FontFaceSet.load() rejects if a selected font fails to load; FontFace.load() likewise exposes loading failure through rejection and the face status moves to error.

Expected F09 evidence is therefore a rejection, an owned face in status error, and a subsequent matching check() result of false because the matching face is neither loaded nor a system font. The exact rejection name and message are not predicted in the expected ledger; they must be captured from an actual execution rather than fabricated. Decision: HOLD_LOAD_ERROR.

The error path must not transform rejection into:

.catch(() => [])

and then treat that empty array as success. Preserve the rejection as first-class evidence.

Likewise, a deadline firing is not evidence that the font “does not exist.” It means the laboratory lacks complete evidence. The verifier rejects unresolved deadlines. Timing bounds are operational controls, not semantic shortcuts.

The local HTTP server records the 404 request status and served content type when execution occurs. In this unexecuted laboratory those observed request fields remain null.

Revalidate membership after deletion and repair

F10 uses one positive face object across three mandatory phases.

Pre-delete: create the face, add it, load it, and query "AB". Expected evidence is the F05 positive state: has=true, status loaded, check=true, and the returned identity equals the same owned object. Decision: ACCEPT_OWNED_FACE_READINESS.

After-delete: call:

document.fonts.delete(face);

and retain the JavaScript reference. The object's status remains loaded, but document.fonts.has(face) is now expected false. Querying the former family again should produce check=true and load=[] because the set no longer contains that face. Decision: HOLD_MISSING_FACE.

After-readd: add the exact same loaded object back to document.fonts. Membership becomes true again; a new set load(query, "AB") is expected to return that same object without requiring the application to invent a replacement identity. Decision: ACCEPT_OWNED_FACE_READINESS.

FontFaceSet is set-like and exposes add(), has(), and delete() for manually managed faces.

second-img-fonts

Treat each membership change as new evidence

Holding a loaded FontFace reference in JavaScript is not proof that the document's current font set contains it. F04 demonstrates that before registration; F10 demonstrates it after deletion.

That is why F10 may not be reduced to its final green state. All three phases belong under one case ID and must appear in order: pre-delete, after-delete, after-readd. A report missing the middle hold is incomplete, even though the final state is healthy.

Reconcile the full case and phase inventory

The expected matrix is the specification-derived hypothesis for this fixture, not a test transcript.

ID

Controlled condition

Expected API evidence

Readiness decision

F01

No registered face for unique family

check=true; load []; face absent

HOLD_MISSING_FACE

F02

Await ready, then absent family

ready fulfills; check=true; load []

HOLD_MISSING_FACE

F03

Registered valid face, not loaded

has=true; unloaded; check=false; load NOT_REQUESTED

HOLD_NOT_LOADED

F04

Directly loaded, never registered

loaded; has=false; check=true; load []

HOLD_MISSING_FACE

F05

Registered and loaded, query AB

has=true; loaded; exact face returned

ACCEPT_OWNED_FACE_READINESS

F06

Positive face, typo query family

intended face present; check=true; load []

HOLD_QUERY_MISMATCH

F07

Registered unloaded A-only, query B

check=true; load []; remains unloaded

HOLD_DECLARED_COVERAGE

F08

Registered loaded A-only, query AB

nonempty exact-face load; B outside range

HOLD_DECLARED_COVERAGE

F09

Registered face backed by owned 404

load rejects; status error; matching check expected false

HOLD_LOAD_ERROR

F10

load → delete → re-add same object

accept → missing → accept

three phase decisions

The following page-side file is complete; there are no omitted central functions.

// lab.js
(() => {
  "use strict";

  const idToEntry = new Map();
  const faceToId = new Map();

  const stamp = () => new Date().toISOString();

  function registerOwnedFace(id, family, source, descriptor, ranges) {
    if (idToEntry.has(id)) throw new Errorduplicate face id: ${id});
    const face = new FontFace(family, url("${source}"), descriptor);
    const entry = { id, face, family, source, descriptor, ranges };
    idToEntry.set(id, entry);
    faceToId.set(face, id);
    return entry;
  }

  function returnedIds(faces) {
    return faces.map(face => faceToId.get(face) ?? "UNKNOWN_FONTFACE");
  }

  function codePoints(text) {
    return Array.from(text, ch => ch.codePointAt(0));
  }

  function coverage(text, entries) {
    return codePoints(text).map(cp => ({
      codePoint: U+${cp.toString(16).toUpperCase().padStart(4, "0")},
      covered: entries.some(e =>
        e.ranges.some(([lo, hi]) => cp >= lo && cp <= hi)
      )
    }));
  }

  function snapshot(entry) {
    return {
      at: stamp(),
      has: entry ? document.fonts.has(entry.face) : false,
      status: entry ? entry.face.status : null,
      ownedSetIds: [...idToEntry.values()]
        .filter(e => document.fonts.has(e.face))
        .map(e => e.id)
    };
  }

  function queryFor(family) {
    return 20px "${family}";
  }

  function assertQueryAgreement(spec, actualFamily) {
    const expected = queryFor(spec.family);
    return {
      expectedQuery: expected,
      actualQuery: queryFor(actualFamily),
      agrees: actualFamily === spec.family &&
              spec.descriptor.style === "normal" &&
              spec.descriptor.weight === "400" &&
              spec.descriptor.stretch === "normal"
    };
  }

  async function bounded(promise, ms) {
    let timer;
    const timeout = new Promise((_, reject) => {
      timer = setTimeout(() => {
        const e = new Errordeadline ${ms}ms exceeded);
        e.name = "DeadlineError";
        reject(e);
      }, ms);
    });
    try { return await Promise.race([promise, timeout]); }
    finally { clearTimeout(timer); }
  }

  async function setLoad(query, text, deadlineMs) {
    try {
      const faces = await bounded(document.fonts.load(query, text), deadlineMs);
      return { state: "FULFILLED", returnedFaceIds: returnedIds(faces),
               rejection: null };
    } catch (e) {
      return { state: "REJECTED", returnedFaceIds: null,
               rejection: { name: e.name, message: String(e.message) } };
    }
  }

  function admitted(entry) {
    return entry && document.fonts.has(entry.face) &&
           entry.face.status === "loaded";
  }

  function make(spec, restricted = false, bad = false) {
    return registerOwnedFace(
      spec.faceId,
      spec.family,
      bad ? "/fonts/deliberate-404.ttf" : "/fonts/ahem.ttf",
      {
        style: "normal",
        weight: "400",
        stretch: "normal",
        unicodeRange: restricted ? "U+0041" : "U+0041-0042"
      },
      restricted ? [[0x41, 0x41]] : [[0x41, 0x42]]
    );
  }

  async function probe(spec, entry, family, text, callLoad = true) {
    const query = queryFor(family);
    const before = snapshot(entry);
    const checked = document.fonts.check(query, text);
    const load = callLoad
      ? await setLoad(query, text, spec.deadlineMs)
      : { state: "NOT_REQUESTED", returnedFaceIds: null, rejection: null };
    const after = snapshot(entry);
    return {
      phase: spec.phase ?? "main",
      query,
      requiredText: text,
      requiredCodePoints: codePoints(text).map(cp =>
        U+${cp.toString(16).toUpperCase().padStart(4, "0")}),
      queryAgreement: assertQueryAgreement(spec, family),
      before, check: checked, load, after,
      coverage: entry && admitted(entry) ? coverage(text, [entry]) :
        coverage(text, [])
    };
  }

  async function runCase(spec) {
    idToEntry.clear();
    faceToId.clear();
    const startedAt = stamp();
    let phases = [];

    if (spec.id === "F01") {
      phases.push(await probe(spec, null, spec.family, "AB"));
    } else if (spec.id === "F02") {
      await bounded(document.fonts.ready, spec.deadlineMs);
      phases.push(await probe(spec, null, spec.family, "AB"));
    } else if (spec.id === "F03") {
      const e = make(spec);
      document.fonts.add(e.face);
      phases.push(await probe(spec, e, spec.family, "AB", false));
    } else if (spec.id === "F04") {
      const e = make(spec);
      await bounded(e.face.load(), spec.deadlineMs);
      phases.push(await probe(spec, e, spec.family, "AB"));
    } else if (spec.id === "F05") {
      const e = make(spec);
      document.fonts.add(e.face);
      phases.push(await probe(spec, e, spec.family, "AB"));
    } else if (spec.id === "F06") {
      const e = make(spec);
      document.fonts.add(e.face);
      await bounded(e.face.load(), spec.deadlineMs);
      phases.push(await probe(spec, e, spec.queryFamily, "AB"));
    } else if (spec.id === "F07") {
      const e = make(spec, true);
      document.fonts.add(e.face);
      phases.push(await probe(spec, e, spec.family, "B"));
    } else if (spec.id === "F08") {
      const e = make(spec, true);
      document.fonts.add(e.face);
      await bounded(e.face.load(), spec.deadlineMs);
      phases.push(await probe(spec, e, spec.family, "AB"));
    } else if (spec.id === "F09") {
      const e = make(spec, false, true);
      document.fonts.add(e.face);
      phases.push(await probe(spec, e, spec.family, "AB"));
    } else if (spec.id === "F10") {
      const e = make(spec);
      document.fonts.add(e.face);
      await bounded(e.face.load(), spec.deadlineMs);

      spec.phase = "pre-delete";
      phases.push(await probe(spec, e, spec.family, "AB"));

      document.fonts.delete(e.face);
      spec.phase = "after-delete";
      phases.push(await probe(spec, e, spec.family, "AB"));

      document.fonts.add(e.face);
      spec.phase = "after-readd";
      phases.push(await probe(spec, e, spec.family, "AB"));
    } else {
      throw new Errorunknown case ${spec.id});
    }

    return {
      caseId: spec.id,
      faceId: spec.faceId,
      family: spec.family,
      sourceRevision: spec.sourceRevision,
      sourceSha256: spec.sourceSha256,
      descriptor: spec.descriptor,
      startedAt,
      endedAt: stamp(),
      phases
    };
  }

  window.FontLab = { runCase };
})();

The local server and Playwright runner follow. They refuse unknown fixture hashes, use a fresh page per case, preserve raw evidence, and separately execute negative comparator controls.

# run_font_gate.py
import argparse, copy, hashlib, importlib.metadata, json, platform
import threading, uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from playwright.sync_api import sync_playwright

EXPECTED_PW = "1.62.0"
PACKAGED_CHROMIUM = {"revision": "1234",
                     "version": "151.0.7922.34"}
CASE_IDS = [f"F{i:02d}" for i in range(1, 11)]
F10_PHASES = ["pre-delete", "after-delete", "after-readd"]
DECISIONS = {
    "F01": ["HOLD_MISSING_FACE"],
    "F02": ["HOLD_MISSING_FACE"],
    "F03": ["HOLD_NOT_LOADED"],
    "F04": ["HOLD_MISSING_FACE"],
    "F05": ["ACCEPT_OWNED_FACE_READINESS"],
    "F06": ["HOLD_QUERY_MISMATCH"],
    "F07": ["HOLD_DECLARED_COVERAGE"],
    "F08": ["HOLD_DECLARED_COVERAGE"],
    "F09": ["HOLD_LOAD_ERROR"],
    "F10": ["ACCEPT_OWNED_FACE_READINESS",
            "HOLD_MISSING_FACE",
            "ACCEPT_OWNED_FACE_READINESS"],
}

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(131072), b""):
            h.update(block)
    return h.hexdigest()

class State:
    font = None
    js = None
    requests = []
    lock = threading.Lock()

class Handler(BaseHTTPRequestHandler):
    def log_message(self, *_): pass

    def record(self, status, content_type):
        with State.lock:
            State.requests.append({
                "path": self.path,
                "status": status,
                "contentType": content_type
            })

    def send_owned(self, status, content_type, body):
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)
        self.record(status, content_type)

    def do_GET(self):
        if self.path.startswith("/case.html"):
            body = b"""<!doctype html><meta charset="utf-8">
<title>Font gate fixture</title><script src="/lab.js"></script>"""
            self.send_owned(200, "text/html; charset=utf-8", body)
        elif self.path == "/lab.js":
            self.send_owned(200, "text/javascript; charset=utf-8", State.js)
        elif self.path == "/fonts/ahem.ttf":
            self.send_owned(200, "font/ttf", State.font)
        elif self.path == "/fonts/deliberate-404.ttf":
            self.send_owned(404, "application/octet-stream", b"")
        else:
            self.send_owned(404, "text/plain; charset=utf-8", b"not found")

def manifest(run_id, revision, digest):
    descriptor = {"style": "normal", "weight": "400",
                  "stretch": "normal", "unicodeRange": "U+0041-0042"}
    rows = []
    for cid in CASE_IDS:
        fam = f"OwnedAhem_{run_id}_{cid}"
        row = {
            "id": cid,
            "faceId": f"face:{cid}:primary",
            "family": fam,
            "queryFamily": fam,
            "sourceRevision": revision,
            "sourceSha256": digest,
            "descriptor": dict(descriptor),
            "deadlineMs": 5000
        }
        if cid in ("F07", "F08"):
            row["descriptor"]["unicodeRange"] = "U+0041"
        if cid == "F06":
            row["queryFamily"] = fam + "_typo"
        rows.append(row)
    return rows

def verify(report):
    cases = report["cases"]
    ids = [c["caseId"] for c in cases]
    if ids != CASE_IDS or len(set(ids)) != 10:
        raise AssertionError("case inventory mismatch")

    known = {c["faceId"] for c in cases}
    for c in cases:
        phases = [p["phase"] for p in c["phases"]]
        if c["caseId"] == "F10":
            if phases != F10_PHASES:
                raise AssertionError("F10 phase inventory mismatch")
        elif phases != ["main"]:
            raise AssertionError(f"{c['caseId']} phase mismatch")

        for p in c["phases"]:
            ids_returned = p["load"]["returnedFaceIds"]
            if ids_returned:
                for fid in ids_returned:
                    if fid not in known:
                        raise AssertionError(f"unknown returned face id {fid}")
            if p["load"]["state"] == "REJECTED":
                r = p["load"]["rejection"]
                if not r or not r.get("name"):
                    raise AssertionError("missing rejection evidence")

    return True

def negative_controls(report):
    altered = copy.deepcopy(report)
    f05 = next(c for c in altered["cases"] if c["caseId"] == "F05")
    for p in f05["phases"]:
        if p["load"]["returnedFaceIds"]:
            p["load"]["returnedFaceIds"] = ["face:F99:copied"]
    try:
        verify(altered)
        raise AssertionError("altered F05 identity was accepted")
    except AssertionError:
        pass

    missing = copy.deepcopy(report)
    missing["cases"] = [c for c in missing["cases"] if c["caseId"] != "F08"]
    try:
        verify(missing)
        raise AssertionError("missing required case was accepted")
    except AssertionError:
        pass

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ahem", required=True)
    ap.add_argument("--ahem-sha256", required=True)
    ap.add_argument("--ahem-revision", required=True)
    ap.add_argument("--lab-js", default="lab.js")
    ap.add_argument("--output", default="font-gate-evidence.json")
    args = ap.parse_args()

    package_version = importlib.metadata.version("playwright")
    if package_version != EXPECTED_PW:
        raise SystemExit(f"HOLD_ENVIRONMENT: playwright={package_version}")

    actual_digest = sha256(args.ahem)
    if actual_digest.lower() != args.ahem_sha256.lower():
        raise SystemExit("HOLD_ENVIRONMENT: Ahem SHA-256 mismatch")

    State.font = Path(args.ahem).read_bytes()
    State.js = Path(args.lab_js).read_bytes()
    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    origin = f"http://127.0.0.1:{server.server_port}"
    run_id = uuid.uuid4().hex[:10]
    specs = manifest(run_id, args.ahem_revision, actual_digest)

    report = {
        "executionState": "EXECUTED",
        "runner": {
            "playwrightPackageVersion": package_version,
            "packagedChromiumDescriptor": PACKAGED_CHROMIUM,
            "actualBrowserVersion": None,
            "os": platform.platform(),
            "headless": True,
            "origin": origin
        },
        "fixture": {
            "sourceRevision": args.ahem_revision,
            "sha256": actual_digest,
            "path": str(Path(args.ahem).resolve())
        },
        "manifest": specs,
        "cases": []
    }

    try:
        with sync_playwright() as pw:
            browser = pw.chromium.launch(headless=True)
            report["runner"]["actualBrowserVersion"] = browser.version
            for spec in specs:
                page = browser.new_page()
                with State.lock:
                    State.requests.clear()
                page.goto(origin + "/case.html", wait_until="domcontentloaded")
                result = page.evaluate(
                    "(spec) => window.FontLab.runCase(spec)", spec)
                with State.lock:
                    result["requests"] = copy.deepcopy(State.requests)
                result["expectedDecisions"] = DECISIONS[spec["id"]]
                report["cases"].append(result)
                page.close()
            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    verify(report)
    negative_controls(report)

    # Raw report is written only after collection; verifier works on copies.
    Path(args.output).write_text(
        json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")
    print(args.output)

if name == "__main__":
    main()

Preparation is intentionally explicit:

python -m pip install "playwright==1.62.0"

# Prepare an official vendored Ahem copy separately.
# Record its immutable source revision and compute its real digest.
sha256sum vendor/ahem.ttf

# Only after confirming that digest:
python run_font_gate.py \
  --ahem vendor/ahem.ttf \
  --ahem-sha256 '<ACTUAL_SHA256>' \
  --ahem-revision '<IMMUTABLE_WPT_DISTRIBUTION_REVISION>' \
  --lab-js lab.js \
  --output font-gate-evidence.json

No digest placeholder is evidence. In this article the runner has not been invoked, so the correct evidence ledger is executionState: "NOT_EXECUTED" with observed fields null.

Prove that the verifier rejects incomplete evidence

The comparator has two deliberate negative controls. One copies the report and replaces F05's returned owned face ID with an unknown ID. The other removes F08. Both altered copies must be rejected while the original raw record remains unchanged.

A production verifier should also reject duplicate case IDs, missing F10 phases, unknown returned IDs, unresolved deadline markers, a source SHA/revision different from the manifest, or a query whose family differs from the declared family except in the intentionally negative F06 case.

The reason for these controls is methodological: a green comparator that cannot reject known-corrupt evidence proves very little. A release gate should be falsifiable.

Turn the evidence into a bounded release decision

The final policy separates browser evidence from application admission logic.

Condition

Required decision

Intended owned face absent from current set

HOLD_MISSING_FACE

Intended face exists but is not loaded

HOLD_NOT_LOADED

Query family/descriptors disagree with manifest

HOLD_QUERY_MISMATCH

Required code point outside admitted declared ranges

HOLD_DECLARED_COVERAGE

Selected face load rejects or reaches error

HOLD_LOAD_ERROR

Intended owned face is present, loaded, exact returned identity is correct, query agrees, required declared coverage passes

ACCEPT_OWNED_FACE_READINESS

An accepted result is intentionally narrower than “font works.” It establishes that, for this fixture and declared matching/coverage policy, the expected owned resource is currently registered and loaded and the required A/B code points fall inside the declared ranges of the admitted intended faces.

It does not establish which font rendered every glyph in an arbitrary page. It does not prove complete shaping coverage, visual correctness, metric correctness, layout stability, application-wide family selection, or cross-browser conformance. It also says nothing about whether a separately authored CSS rule wins the cascade; when that matters, verify CSS priority independently.

A green run may therefore contain multiple HOLD_* rows. That is correct: F01, F02, F03, F04, F06, F07, F08, F09, and F10's middle phase are controls designed to demonstrate that the gate refuses states it should refuse.

Because the cited CSS Font Loading document is an editor's draft, retain actual runtime evidence if execution differs from the expected algorithm. Investigate matching, descriptor parsing, source behavior, or browser implementation differences rather than editing the expected ledger after the fact. The test is useful precisely because expectation and observation remain separate.

Repair registration and assign ownership

A failed gate should direct the repair rather than collapse every failure into “font missing.”

For HOLD_MISSING_FACE, inspect the registration lifecycle. Confirm that the intended application registry creates the correct FontFace, records its stable application ID, and adds that exact object to document.fonts. If the source path itself is unavailable, repair the asset route and revalidate its recorded revision and SHA before browser execution.

For HOLD_QUERY_MISMATCH, do not reload the same resource and hope the result changes. Repair the authored family/descriptors or the manifest, whichever is actually wrong, and rerun in a fresh document.

For HOLD_DECLARED_COVERAGE, correct the application's declared matching policy only if the intended resource is genuinely meant to cover the required fixture points. Do not enlarge unicodeRange merely to make the test pass; that would change the contract instead of demonstrating it.

For HOLD_LOAD_ERROR, preserve the HTTP response and rejection evidence. Fix the owned URL or fixture preparation, then rerun rather than replacing the error with an empty result.

For explicit lifecycle changes, treat add() and delete() as ownership transitions. Reopening a page is not evidence of repair; the affected cases must execute again against the new source revision while the previous raw report remains preserved.

The same scope discipline applies outside font readiness. Font registration evidence does not validate geometry, remembered intrinsic sizes, or other rendering lifecycle state; those should validate layout state separately.

The operational record should therefore retain both revisions: the evidence that caused the hold and the evidence produced after the repair. That makes the change reviewable without pretending a later successful run rewrites the earlier state.

Develop frontend verification skills with Refonte Learning

This laboratory sits on broader frontend foundations: precise HTML/CSS ownership, JavaScript object and promise semantics, browser APIs, performance-aware resource handling, accessibility discipline, version control, and reproducible testing.

Refonte Learning's FrontEnd Developer Program currently lists HTML5/CSS3, JavaScript ES6+, React, Redux, APIs/AJAX, Git, responsive design, accessibility, performance optimization, advanced CSS, and a capstone. Its page states a four-month period and a dedication of 10–12 hours per week; the general program requirement says basic programming concepts are needed and HTML/CSS familiarity is a plus, while the admissions section separately states that applicants must be working toward a bachelor's degree or higher. It describes “Potential Internship,” names an educational mentor, and lists a Training Certificate and Certificate of Internship upon successful completion.

The program page does not establish that CSS Font Loading API semantics, Ahem-based browser fixtures, Playwright testing, or this specific font-readiness laboratory are taught, nor does it specify a specialized mentorship cadence for this topic.

The relevant connection is therefore modest: its verified JavaScript/CSS, performance, and accessibility foundations support the kind of disciplined reasoning this gate requires, while the specialized API contract remains a separate engineering exercise. The practical habit to carry forward is narrower and more durable than any single browser API: define the resource the application owns, capture browser evidence without upgrading it into a stronger claim, and admit the release only when the evidence satisfies the declared contract.