cytoscape.js v4 HEAD · a579fafe · built 2026-10-30 19:56Z

The renderer, the shaders and the debug harness

Read this before changing the WebGPU renderer, a shader, or anything the debug harness draws. The recurring lesson is that a renderer defect looks plausible — a graph with no labels still renders — so the harness and the fixtures need their own controls.

Pipelines compile on first use

  • A pipeline a scene may never draw is built on first use (src/render/lazy-pipeline.mts). Every created pipeline compiles when the first frame submits, drawn or not, and on SwiftShader — the adapter the visual goldens pin — that is 0.1–1 s each: the pick, casing, layer and mid-arrow variants, the per-kind cull kernels and the tween/mapper kernels were ~60% of a curved scene's first frame, in every visual test. Deferring them took --project=visual from 5:09 to 3:50 on a 16-thread box. A new variant pipeline goes behind lazyRenderPipeline/lazyComputePipeline; test/modules/lazy-pipelines.test.mjs pins the existing ones.

WGSL ships minified

  • The bundles ship minified WGSL, not the shader text as written (round 52). Multi-line WGSL literals carry the wgsl template tag (src/gpu/wgsl.mts; identity at runtime) and scripts/wgsl-minify.mjs strips comments/whitespace at build time with ${...} kept byte-for-byte opaque — so when adding a shader, tag the literal, and never put an interpolation inside a WGSL comment (a build error; spell the name in prose). The transform runs in dev builds too, deliberately: Playwright exercises the same transform that ships.
  • Round 126 measured the next step away: no identifier renaming, no WGSL-aware minifier. Every candidate needs a complete module (miniray 0.3.1 also cannot parse array<atomic<u32>> and panics in its dead-code pass; wgslender 1.4.1 handled all 23 complete shaders), and expanding each shader into its complete module duplicates the fragments (COMMON, SDF, the curve and arrow code) this representation ships once: the full minified bundle grew +49,960 bytes raw / +12,752 gzipped at best. Renaming only function locals, fragments kept shared, measured −11% raw but +10% gzipped on the corpus — descriptive names repeat, and gzip was already taking them. What shipped instead: float literals shortened (1.0 -> 1.), and scripts/const-inline.mjs splicing an interpolated module-level number (${SHAPE_SHIFT}u) into the text as the runtime join would, so the minifier collapses around it. Re-measure before re-opening; the record is plan/rounds/*rnd0126*.
  • GLSL takes the same transform under a glsl tag (round 126, for the WebGL2 renderer of round 137): block comments do not nest, and a preprocessor line keeps its newline with every whitespace run inside it kept as one space (#define F(x) and #define F (x) differ). glslx 0.4.5 was measured against GLSL ES 3.00 and is not usable as written — it rejects uniform blocks, switch and uintBitsToFloat, and renames uniforms and inputs by default — even its internal-only mode renames a uniform struct's members, which WebGL looks up by name (getUniformLocation(p, 'frame.viewport')).

debug/ — the manual harness

  • debug/: The manual dev harness (npm run watch → http://localhost:3333/), rebuilt in round 43. It currently offers twenty-five selectable networks: checked-in exports, generated fixtures, and the curated features and workflows entries, with the earlier fixture list and provenance described below. Older drawing controls remain at ?network=v3-default, node-types, edge-types, edge-arrows, and labels; they are useful for broad drawing checks, while Round 149's bounded scene routes pair labelled comparisons with focused controls. Use the harness for renderer, interaction and gesture changes that are hard to verify in unit tests alone.
    • Round 149 feature scenes are routed by ?network=features&scene=<family>&view=<view>. The catalog and family/view map live in debug/feature-scenes.js; pure builders live in debug/feature-scenes-paint.js, feature-scenes-graph.js, feature-scenes-labels.js, feature-scenes-charts.js, and feature-scenes-compounds.js. ?network=workflows&scene=<context> selects algorithms, layouts, inspector, mutation, animation, gestures, export, or runtime panels over one deterministic fixture. The main page embeds the arrow and hull galleries as overlays and retains their standalone routes. Feature settings are URL-backed and Reset rebuilds the selected view. The runtime panel reports requested rendererWorker configuration and readiness; Cytoscape's public API does not report actual worker-host identity, so do not document the request as verified placement. Browser automation using mouse or synthetic touch does not stand in for physical touch/pinch acceptance. The status build copies the v3 UMD only when it already exists locally; otherwise it publishes a sentinel and explicit unavailable pane rather than installing/building v3.
    • Feature label scenes use four vendored Open Sans Latin WOFF2 faces (weights 400 and 700, normal and italic) from @fontsource/open-sans 5.3.0, with the package's OFL license at debug/fonts/OPEN-SANS-OFL.txt. The status planner copies nested font files referenced by the stylesheet into debug/fonts/; test/modules/status-site.test.mjs checks these local CSS assets are mirrored. A browser check of the published status copy should confirm the requests return successfully and document.fonts.check() passes before judging font-weight variants. These four faces match the new feature-scene capture setup; other weights can be synthesized by the browser and should not be described as separately vendored faces.
    • Round 114.7 gave the layout section four things a person judging a layout needs: Preset restores the positions the graph loaded with (a snapshot init.js takes synchronously after cytoscape() returns — the factory runs the load layout to completion first, flow included), a force-only Live box (animateLive; Animate now tweens every layout to its finished positions), a layout-appropriate edge types box that re-applies the sheet with the curve style the layout reads best with (taxi for flow and breadthfirst, bezier for the rings, haystack for force — the table is debug/layout-config.js), and a Hover select that emphasizes the hovered neighbourhood (debug/hover.js, timed in the console): Emphasize is round 102's cy.emphasize() — O(neighbourhood), on at any size, the one to hover on ndex-x-large — and Dim / Hide are the per-element spellings it replaced, kept for comparison and off above 100k elements. The spiral extension example lives in debug/spiral-layout.js, written over the contract the way a built-in is (nodeDimensions, packComponents over its own array, finish), so it animates and avoids overlap. All three files export for the module suite, which runs the spiral headless against the real library.
    • Round 125.10 made the page the layout audit's instrument: a Live spacing slider that rescales the current positions about their centre as it is dragged (layoutConfig.scaledPositions over a snapshot taken at each layoutstop; applied through positions(), not a preset run, so the layout's own stop does not re-base it), an Airiness readout (debug/airiness.js — nearest-box and edge gaps through a quadtree, shared with the quality suite; test/modules/airiness.test.mjs pins it against a brute-force twin), and edges coloured as their source node on the workflow, npm-deps and reactome scenes (the source-band derivation in debug/fixtures.js, which the generated networks now run through as the fetched ones do).
    • Round 125.11 put every layout option on the page: an Options panel generated from debug/layout-options.js for the selected layout (its own options, then the shared plumbing; the boxes' options — animate, seed, avoidOverlap, labels, pack, tidy, spacing — stay where they are and are OWNED; function-typed options are EXCLUDED with a reason), merged over the boxes' spelling on Apply with only the fields that differ from the library's default sent, and a cy.layout({...}) readout of the exact call. test/modules/layout-options-panel.test.mjs holds the table to the declaration: every member of every layout option interface in src/public-types.mts is in the table, owned or excluded, and nothing in the table is unknown to the interface.
    • Round 118.4 added the force-only Infinite box (infinite: true — the run keeps going at no cost at rest, a dragged node reflows its neighbourhood; Stop ends it and Reheat wakes it) and a Force overlap by select (avoidOverlap: 'settle' | 'sim' | 'both' — the settle's exact pass, a separation sweep every tick, or both; pinned to sim under Infinite, where there is no settle). Both spellings are pure functions in debug/layout-config.js (forceAnimation, forceOverlap) with the module suite's specs. Driving the page by script under a live GPU run: node.position() and renderedPosition() read the CPU column, which is stale under the lease, so a scripted pointer aimed by them lands on the background (a pan) rather than the node — find the node by hovering (cy.on('mouseover') fires from the GPU pick) or stop the run first, as 118's page drive and browser spec do.
    • Round 104 added two label knobs: Declutter (the core label-declutter: cull) and Label priority: degree (fixtures.withDegree writes each node's degree as _degree, mapped to label-priority). The renderer-local winners are readable in the console: cy._renderer.labelLayer.declutter (drawn(slot), stats).
    • Round 106 added the Minimap box in the View section (?minimap=true opens it): debug/minimap.js makes a following cy.clone() in its own container (#minimap-cy) with its own dots-and-hairlines sheet, every user gesture off, a refit after each sync, the main view's extent drawn as a rectangle and a tap that centres the main view — the proof that a second view is a second instance. The clone is window.minimap for the console, and its syncs log their diff sizes. The pure half (sheet, clone options, extent rectangle, tap pan) is exported for test/modules/minimap.test.mjs, which runs it headless against the library; the renderer project's "following clone" spec checks two live canvases on one page.
    • debug/fixtures.js holds the fixture conversion and the generators, split out so test/modules/debug-harness*.test.mjs can exercise the same code: debug-harness-compile.test.mjs asserts every fixture exists at the path the page will fetch, and that every sheet compiles against that fixture's real data. Round 149 adds test/modules/feature-scenes.test.mjs, feature-workflows.mjs, schemas.mjs, and demo-coverage.mjs for scene definitions, workflow controls, schema-valid canonical states, and the family-level coverage ledger. playwright-tests/feature-workflows-renderer.spec.js checks browser behavior; the visual golden suite captures canonical feature states. The 2026-08-05 review pass added three more, each pinning a defect a person had to open the page to find: the compound fixture lays out into disjoint parent boxes (grid places leaves in declaration order and parents derive from where their children land, so the node order and cols together decide readability), the event log reads layout once per frame rather than once per event, and watch:sync binds livereload on every interface (its localhost default resolves to ::1 here while http-server -o opens 127.0.0.1, so the client never connected).
    • When the page does not come up, read the message on it: it names the phase. debug/load-error.js (round 65.13) writes it, and the phase — network, http, decode, init — is passed in by the caller rather than guessed, because guessing is what the previous version did: init.js called loadNetwork inside the fixture's promise chain, so every library error (sheet compile, cytoscape(), layout) was reported as a broken fixture, and for a wire-loaded network as "rebuild the site". The generated networks build outside any promise and showed the real error, so a WebGPU failure read as "the binary networks are broken, the built-in ones are fine" — which is how it was reported. A fatal message is also sticky now: startStats rewrites #stats twice a second and had been erasing the adapter error within half a second of it appearing.
    • debug/slim-ndex.mjs records how the 34 MB ndex-x-large fixture was derived from its 250 MB original, so the slim is re-runnable rather than a mystery blob.
    • Round 105's GeneMANIA fixtures: node debug/genemania.mjs runs the two canonical queries (the site's human example, and TP53) against genemania.org exactly as its search box does, pinned to the 2021 database, and converts them. They were fetched per checkout and gitignored until 2026-10-05 (GeneMANIA publishes no licence for its data); the maintainer, a GeneMANIA coauthor, then approved committing them, so they are checked in, validated and hosted like any other real export, and the script is how they are regenerated. test/modules/genemania-fixture.test.mjs pins each committed file to its query and the pinned database. Its sheet is the web app's own, ported — the reference for the multi-edge idiom: haystack at radius 0.5, colour by network type through an ordinal mapper over the dictionary-encoded group column.
    • The status build ships the fixtures as v4's own binary wire format (round 46.5). Measured over the five fetched fixtures: 102.5 MiB of JSON becomes 37.5 MiB, and the largest goes 34.1 -> 9.5 MiB — which is what puts every one of them under Cloudflare Pages' 25 MiB per-file cap, so the deploy carries every network itself with no off-site bucket and no CORS rule. Note what it is not: gzipped, binary and minified JSON are within 1% of each other, so this is a file-at-rest win (which is what the cap measures) and a parse win, not a transfer one. The build writes a manifest (status-config.js, generated into the output tree) naming each encoded fixture; debug/init.js prefers it and falls back to the JSON when it is absent, which is what npm run watch does — local development is unchanged. The encoder runs debug/fixtures.js's own toGpuElements and calls the built UMD bundle — build/cytoscape.umd.js, the one file debug/index.html loads — not src/, so the page decodes with exactly the code that encoded it. It read the CJS bundle until 2026-08-11, which only looked equivalent: npm run watch rebuilds the UMD alone and npm run status builds nothing, so a tree can hold a fresh UMD beside a CJS from an earlier commit. A spec pins the encoder's bundle against the page's script tag.

Something has to open the page

  • A per-frame GPU readback that only ever returns zero looks exactly like a converged sim. The force runtime's convergence poll (round 18.3) mapped a staging buffer at frame start and the frame's encode skipped the copy while the buffer was mapped — so the copy was skipped on every frame, every readback was the staging buffer's initial zero, three zeros counted as settled, and every GPU force run with the default threshold stopped after nine iterations for the whole life of the integrator until round 116.1's spec needed a converged run. The spectral seed made the result plausible, the settle's separation hid the pile, the lease spec ran with threshold: 0 and the executor-invariants spec's bounds were loose enough to pass a nine-iteration run. Two rules from it: a readback path needs a spec that asserts the value moves (finite, non-zero, changing across polls), not only that the run ends; and when a poll and a copy share a buffer, the poll must wait for a copy to have been encoded since its last map (dispCopied) rather than mapping whenever it is free — call order between the renderer's frame phases is not something a runtime should assume.
  • Something has to open the page. debug/ now has specs, and they are worth having, but round 43 shipped with its own risk note saying they prove sheets compile and not that anything still looks right — and one day later a maintainer opening the page found three defects, one of which (a conservative fit() inflating compound graphs ~2×) was in src/ and visible in every app with a compound graph. When a change touches the harness, the renderer or bounds, drive the page: npm run watch, or a scripted browser that loads debug/index.html, screenshots it, and compares against v3/debug/'s equivalent.

The adapter you got is not the GPU the box has

  • Run npm run gpu before writing "this environment has no GPU" or deferring hardware work. It launches Chromium with the harness's own WebGPU/Vulkan flags and prints a HARDWARE / SOFTWARE-ONLY / UNKNOWN verdict. Twice a session has read a SwiftShader adapter label in an ad-hoc scripted browser and concluded the box had no GPU — on a machine with a discrete RX 580 — because its launch flags fell back to software (round 93.2 was the second time). Two facts the script keeps separate: the card being present (lspci inventory) and the browser reaching it (adapter identity); only the second licenses a GPU benchmark number or a deferral. Two footguns it encodes: navigator.gpu is unavailable on about:blank (the probe serves a loopback http page), and a failed probe reports UNKNOWN (exit 1) rather than "no GPU", so a broken environment cannot manufacture the very conclusion the script exists to prevent. Goldens stay pinned to SwiftShader regardless — the verdict governs benchmarks and hardware-only work, not the visual suite.

A worker canvas remembers the first face it found

  • In Chromium, a font description resolved before its face registered stays on the fallback in that worker — on every canvas, for good. Round 141 measured it: set ctx.font = '32px "F", sans-serif' in a worker before F is in self.fonts, register F (from bytes or a url), and every later ctx.font of the same description — fresh canvases, whitespace variants, after fonts.ready — still measures the fallback; a different size, weight or family list re-resolves. WebKit re-resolves. The 2026-09-18 spike read this as "url faces never reach OffscreenCanvas": its url face was measured while still in flight. Two rules from it: a worker font probe must never measure the family before registering it (use a different family for the control), and anything that re-rasters after a late face must change the description — the glyph atlas's font epoch appends an inert, never-registered family (GlyphAtlas.reraster(true)). playwright-tests/worker-renderer.spec.js's mechanics test pins both engines' behaviour with no adapter needed, so it runs on WebKit here too.

A columnar payload can lose a whole column silently

  • A columnar payload can lose a whole column silently, and the page still looks plausible. Round 46.5 re-encoded the harness fixtures into the binary wire format, and the first reader treated a dictionary column ({ dict, indices }, 1-based, 0 = absent) as a plain array — so every string column in every fixture came back undefined. The graph still rendered: right node count, right edges, right positions, no labels and no categorical colours. Nothing throws on that. When a format has more than one column encoding, the spec has to assert each column still carries values after the round trip, not that the payload parsed; the control (read the dict as an array) must fail on every fixture.