Skip to content
Draft. This essay is a stub or a work in progress — read it as a sketch, not settled documentation.

The underlying space tree ​

Every node in a GoFish scenegraph carries two pieces of information about each of its two axes (x and y):

  • its type: the kind of data space the node has established there, and for a continuous axis the data interval it covers. A type says what the axis means. It has no σ in it.
  • its size claim (an Extent): how much room the node's content needs on that axis, as piecewise-linear functions of the scale factor σ. A claim says how big the content is.

The types form an intermediate representation called the underlying space tree. The claims are computed by a second walk over the same tree, after every type is known. The types live at src/ast/underlyingSpace.ts, and the claims at src/ast/extent.ts. The two walks are _node.ts's resolveUnderlyingSpace() and resolveExtent(). Layout, axis rendering, posScale construction, and ordinal scale building all consume both afterwards.

This doc explains what the tree is, why it exists, what each space kind means, and where to look in the code. If you're adding an operator that introduces or transforms an axis, this is the abstraction you're working with.

What and why, in brief ​

A data-driven graphic maps data space to visual space. Typically data space is described by a data schema like {lake: string, count: number}. Visual space is typically described using shapes and screen positions (i.e., SVG or Canvas attributes).

Most of the logic in GoFish lives in between data and visual space, for example computing scales and performing layout. The underlying space tree keeps that logic organized. Here are some kinds of things we need to figure out about a graphic that underlying space helps us answer:

  • If we overlay a scatterplot and a line chart in the same region of the screen (such as drawing a regression line), what should the axis domains be? What about when the two charts have different data spaces on one axis (like in a dual axis chart)?
  • If we draw a bar chart with vertically centered bars, what is the y-axis?
  • If we create faceted chart regions, how should those faceted regions relate to each other?
  • What if an operator arranges shapes in free space, but those objects have data-driven sizes that need to be scaled to fit the available screen space? (As when using the spread operator.)

In all of these cases, we have some information about data spaces and their encodings to positions and sizes of shapes. Operators compose this information together to create more complex relationships between data and visual space. Underlying space keeps track of this information explicitly so that we can more easily write algorithms that resolve scales and draw axes. For example, to resolve scale domains in the case of the overlaid scatterplot and line chart, we first have to determine whether the two charts' domains can be merged and then we can merge the domains. This information is later used to draw axes for the combined chart. We need to store intermediate results about these domains, and that's basically the role of the underlying space data structure.

The one equation, and three roles for one unknown ​

Every continuous axis is, in the end, one affine map — per σ-scope (the region over which a single scale is shared):

px(d) = σ·d + originPx          σ = pixels per data unit

σ (sigma) is the slope: pixels per unit of data. originPx is the pixel of data 0, the baseline: the screen coordinate of the node's local data-0, and the one position unknown per node and axis. It is kept in pixels, so pixel overhead before the data (padding or spacing on the low side) is simply part of where data 0 lands, never a data value divided by σ. The origin state of an axis is literally the status of originPx: pinned means something fixes it (a data anchor, or a scope's box edge plus overhead), free means it is a gauge the parent sets (a free node's local 0 is its baseline, and its parent translates it), and none means there is no data 0, so there is no originPx at all, only differences. Three things that the word "origin" historically ran together must be kept distinct, because each lives at a different stage of the pipeline:

  • alignment is a constraint: equations between per-node baselines (baseline_A = baseline_B, and analogous relations for other anchors). It says nothing about pixels; it only records which baselines must agree.
  • the origin state (free | pinned | none) is the abstract value: is the baseline under-determined, fixed, or impossible? This is all that bottom-up space resolution can know — it runs before pixels exist, so it computes the determinacy of the baseline, not the baseline itself.
  • originPx is the concrete value: the solved baseline of a σ-scope, in pixels. It exists only after σ and the frame anchor resolve, so it is always a derived read, never stored state.

A false friend to never conflate with that intercept: a claim's width value carries its own intercept — the σ-independent pixel part of an extent (spacing, fixed chrome), the intercept of the size-vs-σ line size = slope·σ + intercept. That is an intercept of the size equation, not of the data→screen map; the two never mean the same thing.

The single scale carrier. Layout threads one per-axis record downward (see Layout dispatch): the AxisScale = { sigma?, map? } (domain.ts). sigma is the slope σ for unanchored extents — a free magnitude has no committed baseline, so its intercept is implicit in where its parent places it (baseline placement + transform.translate) and never travels with the scale. map is the whole anchored map, with the intercept explicit as data rather than closed over a function: px(d) = sigma·d + originPx, evaluated by pxOf. So "anchored" shows up operationally as "has a map"; "unanchored" as "has only a sigma." This single record replaced the former two parallel channels (scaleFactors = slope-only, posScales = whole map) in Stage 4 of the σ-affine plan.

One slope per σ-scope, and the two-scope carrier. The carrier's two slopes — its sigma and its map.sigma — are not independent numbers. Each is the σ of a distinct σ-scope solved once by the scope registry (below): sigma is the axis's SIZE scope (what a magnitude is scaled by), map.sigma is the axis's POSITION scope (what an anchored coordinate is mapped by). No site fabricates either — every scope root solves both from one call, solveScope (or the equal-measure step, equalizeMeasure). Within any one scope there is therefore exactly one slope, by construction. When both halves are present and sigma ≠ map.sigma, the axis genuinely carries two scopes, and each half is read by the channel it belongs to — magnitudes read sigma, anchored positions read map. That happens when a sub-budget layer scales size against a local extent but positions against an inherited map (a sub-budget vs inherited split) — two honest scopes on one axis, the multi-scale reading of the same equation, not a slope with a redundant, drifting twin. A niced-ticks-vs-raw-content split is not a sanctioned case: that was the #659 bug (a panel's own domain escaping the old pre-layout nice walk), and since nicing moved onto the solve (below) a scope's map and σ read one domain by construction.

Why an explicit IR ​

Conventional grammars of graphics treat a scale as a function from a data domain to a visual range. Quantitative x-scale: [30, 50] mpg → [0, 100] px. Color scale: species name → palette entry. Convenient — but too unstructured. If scales are arbitrary functions, the system can change their domains and ranges freely, slot them in anywhere, and inference doesn't know which combinations are meaningful.

In practice every visualization system relies on stronger invariants than "function from domain to range" can express. Domains can be merged only when they're compatible. Spatial continuous ranges aren't independent parameters at all — they're derived from available layout space. Some extents have meaningful origins; others only have meaningful differences. Some operators glue subspaces together; others separate them. Coordinate transforms preserve, warp, or erase parts of the underlying structure.

Discrete position scales make the mismatch concrete. D3 and Vega-Lite use point and band scales to handle categorical positions. Operationally, a band scale gives each category a continuous position together with a uniform bandwidth. That's already the abstraction carrying layout information indirectly. It also breaks down for bar-like charts whose elements have different widths, because the allocation of space is no longer a uniform function of category.

This kind of richer semantics shows up in the implementation of every serious grammar system, even when it isn't reified:

  • Vega-Lite parses each child view recursively, assigns scale-resolution policies (shared vs independent), and conditionally merges child scale components when their types are compatible. Compatibility groups several scale types together (e.g. temporal + ordinal-position). The merged result is a flat record keyed by channel — the tree structure of view composition guides merging, then disappears.
  • Observable Plot distributes inference across channels (fill, stroke, opacity, symbol first infer which named scale they should use), a scale-name registry, scale-type inference (using user-specified types, mark-imposed channel types, explicit domains, channel values, color schemes, special defaults like r getting a sqrt scale), domain-union inference, and range inference that depends on both domain and scale kind. Modular, but no single spatial IR owns the accumulated semantics — Plot's stack transform, for example, rewrites a length channel into y1/y2 so they can later participate in ordinary scale inference.

Each piece can be clean in isolation, but without an explicit source of truth for the inferred spatial semantics, scale and domain facts have to be passed around and reconstructed across the implementation. That's particularly limiting in GoFish, where users define new operators and new spaces — not just new marks inside a fixed scale-resolution pipeline.

GoFish's solution is to give the inference an explicit shared data structure to contribute to. Marks introduce local spatial facts; operators merge or separate them; coordinate transforms annotate them; and later passes consume the tree for layout, scale construction, and guide generation.

The three space kinds ​

Each axis (x and y) of each node has a type of one of three kinds: continuous, ordinal, or undefined. A continuous type stores one data fact in one shape for every continuous axis: a signed dataInterval in data units about the axis's local origin, plus the state of that origin, origin. The origin state is the whole placement fact (is this extent positioned?): pinned has committed a position, free can still be given one, and none can never have one. Every such question is the one read originOf(space) (or originIs(space, "pinned"), and hasOrigin(space) for pinned-or-free):

ts
// underlyingSpace.ts
type Origin = "pinned" | "free" | "none";

type CONTINUOUS_TYPE = {
  kind: "continuous";
  dataInterval: Interval; // signed data extent about the local origin
  origin: Origin; // where that origin sits
  measure?: UnitRecord; // { unit?, titles, summands? }
  mirrored?: true;
  cells?: readonly Cell[]; // every region placed along the axis is a cell
  profile?: Fun<Interval>; // the interval covered at each u across
};
type ORDINAL_TYPE   = { kind: "ordinal";   domain?: string[]; titles?: string[]; ... };
type UNDEFINED_TYPE = { kind: "undefined"; ... };

The three origin states are the old POSITION / SIZE / DIFFERENCE, and there is one constructor for all of them, CONTINUOUS(interval, origin, measure?):

  • pinned: the local origin is data 0, so the interval is the absolute data domain. A scatter's x axis over [30, 50] is CONTINUOUS(interval(30, 50), "pinned").
  • free: the extent hangs from a baseline that nothing has placed yet, and the interval is [−descent, ascent] about it. A bar of value v is CONTINUOUS(interval(0, v), "free"), which is [0, 30] for 30 and [−20, 0] for −20. Marks build it with magnitude(size), which also carries the datum's measure.
  • none: there is no origin at all, only a width, so the interval is [0, width] and only differences along it mean anything. A middle-aligned overlay is one. An overlay of an origin-less child and a free one seated on its baseline keeps the free child's interval, so it can start below 0 (none [−20, 7] for a bar of −20 beside an origin-less bar of 7). Only its width means anything, so what reads one reads its width from the content's start (differenceSpan). It is a length scale: it draws no axis, and its guide is a length entry in the legend.

Because the three share one shape, pinning a free extent is "shift the interval and pin the origin": anchorAt(space, at) turns free [−d, a] into pinned [at − d, at + a]. Every place that pins does exactly this, in data: a glued stack shifts each part by the running sum of the parts before it, and the position operator shifts by its datum offset. Alignment does not pin: it establishes a shared baseline (see below). What places a free baseline is placement: a parent constraint, a data anchor, or the scope root (placeBaseline).

The profile. A continuous type may also hold a profile: for each position u on the other axis, in that axis's data units, the interval the content covers along this one, about the same local origin. It is a function value, Fun<Interval> (ast/fun.ts), and dataInterval is its hull. A type with no profile covers its dataInterval at every u, as a box does, and everything reads a type's profile through crossSectionOf(space), which gives that box a constant one over the whole line. So nothing asks whether a type has a profile. A profile that is constant is never stored (withProfile), so a box's type stays as it is. The shape form of ribbon (ribbon({ x, h })) makes one: the interval between its baseline and its edge at each x.

A function value built from rows is exact: it holds one polynomial per interval between knots (degree 0 for Curve.step, 1 for Curve.linear, and the cubics of spline.ts for Curve.monotone and Curve.smooth). Sums, scales, envelopes and their maxima are exact again, so the folds below get the same numbers from constant profiles as from plain intervals. So are products (multiply) and running integrals (antiderivative): a polynomial piece integrates in closed form. A function the module cannot see into (a kernel density) is read to a tolerance, and its running integral is a set of cubic pieces that match it to that tolerance. A function can also be read over a new parameter u = a·t + b (reparameterize), exactly when it has pieces: this is how a band takes its edges from data units to pixels in layout.

The folds carry profiles pointwise. A stack's chain fold runs at every u (tailSides and chainFold take and return functions), and its type's interval is the largest reach over u, not the sum of each part's largest reach. An overlay (overlay in alignment.ts) takes the lower envelope of its parts' low edges and the upper envelope of their high edges. anchorAt shifts the profile with the interval.

The data interval has no σ in it. Pixel overhead (a spread's spacing, a nest's padding, a fixed pitch, a transform.scale) is never part of the data interval. It lives only in the claim. So when bars 25 px apart are lined up on a baseline, the data domain is the bars' data, not the bars plus 100 px of spacing read as if it were data.

Ascent and descent (#773). An extent is measured from its data 0 on both sides, like a font's ascent and descent. In the type the two sides are the two ends of the interval: the ascent is max and the descent is −min. In the claim they are two values in σ. A rect of value 30 has data ascent 30 and claims ascent 30σ; a rect of value −20 has data descent 20 and claims descent 20σ (a rect length is signed, while a text, image, or treemap size is a nonnegative magnitude). Most extents sit wholly above their data 0 and never spell the descent. Every claim is measured from data 0, whatever its origin state, so a side can be negative: a pinned [30, 50] claims ascent 50σ and descent −30σ (its low edge lies 30σ above its 0), and its width is 20σ. A middle-aligned overlay's origin-less interval starts at 0, so its descent is 0. The claim's width is ascent + descent, computed once by the Extent constructor, and it is what a scope solves σ against. The places that read the two sides:

  • An overlay of free children (unionChildSpaces) is the union of their free intervals, so it takes the larger data extent on each side, and its claim (unionChildExtents) takes the larger claim on each side, which keeps the σ-affine intercepts. So a group of signed bars keeps both sides. A child with no data coordinates (a text, a box of literal size) sits at the overlay's origin, so it reaches its own ascent and descent about 0.
  • Under baseline alignment, resolveAlignmentSpace (spread's cross axis) unions the children's intervals about the shared baseline, so a signed bar chart is pinned over a domain that includes its negative values. Under start, end, or middle alignment the children line up at a box edge or center instead, so each child counts as its whole box [0, width] and the union spans the widest.
  • A nest pads its claim on each side: ascent + padding and descent + padding (nestedExtent). Its type keeps the inner's data interval.
  • anchorAt puts the baseline at the given coordinate: [at − descent, at + ascent].
  • A sized node over a free extent (the chart root, or a layer with a size of its own) fits the claim's ascent + descent to its box and seats the baseline at the scope's originPx: descent·σ above the box's low edge, overhead below the baseline included.
  • A stack lays its parts end to end, in order, as vectors. Each part's baseline sits on the previous part's head, where the head is the baseline moved by ascent − descent, so a negative part goes back. The stack spans everything its parts cover, starting from its first part's baseline at 0: parts (30, −25, 10, −50) have running sums 0, 30, 5, 15, −35, so the stack spans [−35, 30]. Parts that cancel overlap. A diverging stacked bar (all positives up from 0, all negatives down from 0) is not a stack option: it is spelled by grouping by sign first, so that each stack holds one sign. The type lays out the parts' data intervals this way, and the claim lays out their claims the same way (stackClaim), measured from the stack's 0. A part's tail is where placement puts it (tailSides): a free part's tail is its baseline, and a pinned or origin-less part, which has no data baseline for placement, lies above its tail as a box.
  • The 0 of a stack is its baseline (StackBaseline in distribute.ts, the Baseline family, families/baseline.ts). The parts run from the start of the chain (the first part's tail) to its end (the last part's head). Baseline.start() is the start, as above, and the default. Baseline.end() is the end, Baseline.middle() is halfway between, and Baseline.at(part, point) is a point on one part: a fraction of the way from its tail to its head, or one of its anchors ("baseline" is its own 0, as alignment reads it: a bar's tail, or a nested spread's or stack's baseline). chainFold computes the 0 at every u and measures both reaches from it. The fold sees a part with no data baseline as a box from its start, so for such a part "baseline" is its start there, while placement seats the part's own 0 (a declared shortcut, TODO at pointOnPart). In a flow, the at part is a value of the by column, which the split turns into a child index (stackBaseline in schema.ts). A part the data lacks takes no room, so the split places the 0 on the boundary where it would be, by the column's declared order (baselineAlongOrder); with no declared order that is an error. On the way down the part is a child index, an operand of the constraint, and then an index into the parts in placement order (resolveBaseline). Placement reads the same 0 from the parts' data offsets (stackPlaces, below): each part states its own 0 to the free-origin seat (StackPoint in placementFacts.ts) as its offset times σ before its tail.
  • A spread takes baseline too, every value but wiggle (an error: its 0 moves with the cross-sections a stack glues). It is placement only: the spread's fold ignores it, and its space stays a sequence of separate spaces. It states its 0 to the free-origin seat as a point on one part, or a place along the whole chain for end and middle. The way along is a ChainPath, from its first part's start to its last part's end, through the anchors its edges tie (end to start, or a pitch's anchor), and its gaps, fr included, are part of the way. The split resolves an at part as for a stack, and a HasMidpoint column sets it the same way. A spread with no baseline states no 0, and keeps its sequence origin, its start. So alignment: "start" | "middle" | "end" on a parent draws what each child's Baseline.start(), .middle() or .end() under the default alignment: "baseline" draws.
  • A stack whose by column has HasMidpoint (see Column types) is Baseline.at at the midpoint of the column's order: the split builds that baseline from the trait, and the fold shifts the extent so the midpoint sits at 0. The parts before the midpoint (and the share of the level it falls in that lies before it) lie below 0, the rest above. Parts (5, 10, 20, 40, 25) centered on the middle of the 20 span [−25, 75]. The parts of a centered stack must be nonnegative: each lies on the side of the midpoint its level is on, so a negative one is an error naming HasMidpoint. The split tells the fold that the column has the trait (hasMidpoint, beside hasOrder). A stack given both the trait and a baseline is an error: the trait already puts the 0.
  • Under Baseline.middle() and Baseline.wiggle() the stack's 0 is no data value, so the stack's space has no origin ("none"): a position on it is no amount, so it draws no axis: its scale gets a length entry in the legend. Two things are apart here. The space's data origin says whether a position is an amount from 0. The node's own 0 is where a parent lines it up, and that is a placement fact: the point its baseline names. The placement solve seats a stack's baseline point at the layer's data 0 when the layer has one, and at the layer's own 0 (pixel 0) when it has none (solveRank2Axis). So a spread of middle stacks with alignment: "baseline" lines their middles up on one line. Baseline.wiggle() moves its 0 with u: its slope is the average slope of the parts' middles, weighted by their thickness, Σ wᵢ mᵢ′ / Σ wᵢ (wiggleZero), integrated from the first u. That is d3's stackOffsetWiggle in the limit of fine data. It is defined on the functions, so more knots on the same curves do not move it. Over boxes every slope is 0 and it is the start.
  • A stack moves each part by an offset function: the part's tail measured from the stack's 0 at every u, in data units (stackPlaces in distribute.ts, from the same chain as chainFold). Over boxes, and over bands of one thickness under a baseline that does not move with u, every offset is a constant. Part k's offset is the sum of the thicknesses before it, moved by the baseline. Each band keeps its thickness at every u; only its cross-section moves. Outside its own domain a band's thickness is 0 (add in fun.ts reads 0 there), so series sampled at different u stack. wiggle here reads the function-level wiggleZero, never the box shortcut. Each part reaches over [min_u(offset − descent), max_u(offset + ascent)] about the stack's 0 (StackPlace.reach).
  • A stack whose parts are all nonnegative amounts (no part reaches below its tail), on a 0 that is data 0, builds a mirrored space (CONTINUOUS_TYPE.mirrored): both sides of 0 hold amounts measured away from it, so an axis over it labels each tick with its distance from 0. The fold reads this from the parts, not from the baseline (a middle or wiggle stack, which has no origin, is never mirrored). With the 0 at the first part's tail every tick is already a distance, so this changes nothing for a plain stack; a centered stack's axis reads 40 20 0 20 40. A stack with a negative part keeps signed labels. A union stays mirrored only when every part is.
  • A spread lays its parts by the same chain fold as a stack (chainFold), with a different step: an edge chain lays each part's box after the previous one's end plus the spacing, and a fixed-pitch chain lays each part's anchor one pitch from the previous one's. A baseline-pitched part keeps its signed sides about its baseline; any other part is a box.

With every descent 0, all of this reduces to a single width.

ORDINAL carries titles: its grouping fields (e.g. "lake"), and no unit, since categories set up no scale. It's set from the grouping operator (spread's by) when the ordinal space is built (distributeSpaceFold → ORDINAL(keys, by)), and unionChildSpaces unions the titles of the ordinals it overlays, in order. So spaceTitle(space) reads a title off both continuous and ordinal kinds (only UNDEFINED has none), which is what lets an axis name itself off its own resolved space — a continuous axis by its quantity names, an ordinal axis by its grouping field (see the layout passes). A quantity may have no name (a distribution family's variable, in its location column's unit but not that column): it titles nothing, and with no declared unit its unit is a fresh unknown that binds nothing else.

An ORDINAL can also hold cells (ORDINAL_TYPE.cells, the cells in order of their starts, as CONTINUOUS_TYPE.cells holds them; a key is its cell's id). A split keyed by a binned key (field(x).bin(p)) gives each child node its cell (keyCell, set in createOperator beside the key, which is the cell's id), the distribute fold reads a child's cell as its key (keyOf in compose.ts), and ordinalOver builds the ordinal over those keys, with the cells when every key is a cell of a line. unionChildSpaces keeps them when every unioned ordinal has them and they are the cells of one partition (mergeCells, see Partition). The type is what tells the axis it places cells, not points: an axis over cells labels each cell between its boundary ticks (Axes). It is read off the space, never off a datatype flag on the column.

An ORDINAL also says whether its keys have an order (ORDINAL_TYPE.hasOrder). Cells are ordered by nature, so an ordinal over cells has it. A split over a column the chart's schema declares ordered (HasOrder) says so too: spread's split reads the by column's type and returns hasOrder in its layout options, and the spread passes it through its distribute (DistributeOptions.hasOrder) to ordinalOver, as it passes the grouping field as the measure. unionChildSpaces keeps it when every unioned ordinal has it. The axis reads it to place an outer level's labels: at the start of each run of ordered keys, centered over unordered ones (Axes).

A datum value can also carry a field: the data field it was read from, set by inferColor when a color channel names one. That is provenance, not a quantity: it never enters resolveColumn or unit unification, and only the color scale reads it (see Color Scale Resolution).

A companion predicate, isPositioningSpace, folds the two axis-bearing kinds together: it holds for POSITION (a data axis) and ORDINAL (a category axis) but not for SIZE (a mark's own extent) or UNDEFINED. In other words it answers "does this space lay marks out along an axis?" — the question you ask when you want the axis a set of siblings is arranged on rather than each sibling's own size. Its first consumer is a connector with no curve: a line / ribbon reads the underlying space its endpoints resolved to and, when that space is a positioning one whose measure is continuous, smooths the path (the monotone cubic) instead of drawing straight segments — so a line over a continuous x auto-curves while one over discrete categories stays polylinear. The same test picks the spline's knots when the run has no parameter of its own (the times of the keyframes a line threads, or the path tier's key, inferred.along, read through projectBy). On a continuous connection axis, the points' positions along it are the knots when the points are in order along it. A run with neither falls back to centripetal knots, which are computed from distances on screen (runKnots in connect.tsx). When the knots are the positions on the connection axis, that axis draws the run's parameter; the step curve reads this (along with inferred.parameterAxis for a parameter taken from the path tier) to hold every other coordinate.

The guide a space supports keys on the origin state (data-space), never on the claim:

typeguideplacementexample
pinnedquantitative (absolute) axisdeterminedscatter x, stacked-bar y
nonemagnitude / delta guideconflictstreamgraph centered count
freenone (a legend, not an axis)freea bar's height before placing
(kind ordinal)labels at laid-out keys—bars by category, facets
(kind undefined)no guide—an aesthetic / literal-px dim

These map directly onto the σ-affine layout solve (see the one equation, Size resolution, and the solver): the claim's width is the abstract SIZE (slope·σ + intercept), and placement is the abstract value of the baseline — its determinacy (free / determined / conflict), not its pixel intercept. The underlying-space pass is essentially an abstract interpretation of the solve: it computes the structure (which extents are sized, which are positioned) bottom-up before the concrete pixels — and therefore the concrete baseline intercept — exist. Reading placement off the origin state is what lets alignment ask "is this child already positioned?" directly (see The contract) instead of reconstructing it.

This shape is the endpoint of issue #586's collapse and of the type/claim split after it. The old POSITION/SIZE/DIFFERENCE were one semantic thing — a data-driven extent — observed at three pipeline stages; carrying that as three kinds baked a stage distinction into the type. A first cut collapsed them to a single overloaded origin: number | "free" | "impossible" scalar, but that conflated the layout fact with the data fact (a baseline magnitude vs a data axis anchored at 0 — which build no posScale vs a posScale). The next form kept one dataDomain field (Interval | "delta" | undefined) next to the claim in one record, so a free extent's data size existed only inside its claim, and every fold that pinned a free extent had to read the claim at σ = 1 to find it, pixel overhead included. The current form gives every continuous type one interval about its own origin and keeps the origin state separate from it, so a free magnitude and a data axis pinned at 0 stay distinct (free [0, 10] vs pinned [0, 10]) and pinning is a shift.

The pre/post-solve distinction is handled by when σ is substituted, not by which kind: σ is always the claim's width.inverse(size), and the extent at σ is always width.run(σ). The one genuine state transition is middle-alignment drops the origin — centering scrambles the children's baselines, so the result is origin-less (the streamgraph). An origin-less extent is absorbing: no fold gives it an origin back.

The pinned data interval is read back with continuousInterval(space) (used by posScale construction and axis nicing), which is undefined for a free or origin-less space. The folds that union extents regardless of pinning read space.dataInterval directly.

These kinds map closely to Stevens's statistical data types, but not cleanly: a pinned interval covers both interval and ratio, and an origin-less one is weaker than interval — only within-instance differences are defined. ordinal isn't "a band scale"; it's a statement that the values are discrete keys whose spatial allocation is the responsibility of layout. undefined represents spaces with no data-driven information (the literal-pixel value is handled at layout time by computeAesthetic).

One continuous path, and the differences that remain ​

The three origin states share one interval shape, and the code runs one path over it. One scope solve (solveScope) serves every continuous scope root: σ from the claim, and, when the axis has an origin, originPx from where the claim's baseline lands. One overlay fold (overlay in alignment.ts) serves layers, Porter-Duff operators, alignments, and coords: the union of the children's seated intervals. One chain fold serves every spread and stack target. The folds no longer ask whether a child is a magnitude or a position except where that question means something. These are the places it does, each inherent to what the origin states are:

  • Who applies originPx: one seating rule (seatInScope in solver/scopes.ts), used by the render root, a coord, and every layer (a sized layer included). A pinned child shares its parent's frame, so it sits at 0 and places its data through the frame's map; a free child has a frame of its own whose 0 is its baseline ({σ, 0}, frameOf), so its parent places that baseline at the frame's originPx; a child with no data 0 sits at 0 and has no frame. This is the split between "a constraint fixes the baseline" and "the parent sets it". A scope root seats its content in its solved scope, whatever its type's origin. A scope with no data 0 (a spread of magnitudes) has no frame to seat its content, so the rule's seat there is the content's box at the scope's start edge, as the render root places its box. The rule returns that seat (a Seat: a baseline or a box start, at a pixel), and every scope root reads it: the render root (placeRoot), a coord, a layer's seatChild, and the claim of a node with a literal size (fixedClaim), which runs from the start edge exactly where the content is seated by its box. So a sized node starts at its start edge on every axis, whatever reaches before its content's 0 (a label hanging before the first bar, or below the bars' baseline).

  • Seating in a fold: a pinned child sits at its own data coordinates; a free child sits there too when the fold seats children on their baselines (an overlay, a baseline alignment), and is a box from the aligned edge otherwise; an origin-less child is always a box, and adds nothing to a pinned result's data interval (it has no data 0 to give it). A stack seats each part by its tail, as placement does: a free part on its baseline, any other part as a box from its start.

  • A stack glues, a spread separates: a stack glues its parts into ONE continuous space along its direction (positions are running data totals); a spread's result along its direction is a sequence of separate spaces, ORDINAL by its keys (anonymous for positional keys) or UNDEFINED, whatever its spacing or pitch, and each target keeps its own continuous space inside. Its room is its claim: a spread of magnitudes (free targets, or targets that are themselves spreads of magnitudes) shares the enclosing scope's σ, so it claims the chain of their claims plus spacing, on an ordinal or undefined type; a spread of pinned frames (facet panels) claims nothing, and each panel roots its own scope in its slice. A marimekko is a stack, so its widths still add up to one axis. Since a stack adds data amounts, every part must be continuous on the stack's direction: it does not make sense to stack pixels. A part with no data space there (a pixel box, a text, a spread) is an error at the fold (requireAmount) that points at spread({ spacing: 0 }), since parts that only touch are a spread with no spacing. A part with only a data width (origin "none") is an amount, and lies from its start as a pinned part does.

  • A share is a claim (#493 piece 3): on an axis where nothing in a scope is sized or placed by data (GoFishNode.carriesData), σ has no data unit, and it is the room a node with no size of its own takes (GoFishNode.sharesRoom). Such a leaf in a slot, or inside a node in a slot, claims one σ, so a spread of n bands with spacing g claims n·σ + (n − 1)·g, and whatever hangs off a band (a value label, the half of a category label past the last band) takes room in the same claim, which narrows the bands. A share is a σ weight in its nearest scope, and a node whose room is given (a facet panel, a cell, a tile) is a scope, so a panel is a share of the chain that holds it. A band of no size in a chain sized by data is one σ, one data unit, and the layout warns (mixed-sizes). A leaf in no slot (a rule laid over a bar chart) claims nothing, and fills the room of what holds it.

  • A length is a claim, too (#1176 step 6, ast/length.ts): fr(k) is kσ, a share of weight k, so a band is fr(1) and a node sized with fr is a scope for its own content (GoFishNode.shareOf, read by isScope). percent(p) is (p/100)·room, where the room is found by GoFishNode.roomFor, walking up from the node that asks: a node with a literal or percent size of its own, the canvas at the root (the render size, or 400 px), or a band (isBand: a share whose content fills it), whose room is σ. A node with no size of its own hugs its content, so it passes the question to its parent; a room-given node (a facet panel, a cell, a tile, a coord) is not asked, and a percent under one throws. So a percent is a constant at a scope, which acts as pixels, or a σ term in a band, which is a share. The length stays in the node's own box as its size, a fourth kind beside pixels, data and none (OwnSize in ast/dims.ts), and each reader of that size says what a length is to it: the type pass reads no data in it (sizeForType), a layout reads the size the node fixes for itself (GoFishNode.fixedSize: the length's pixels where its room is a constant, none where it is a share, which fills the room it is given), and the length itself is read where it is laid out (GoFishNode.lengthOn, ownLength). Either way it is a Pwl value before the solve, and no claim carries an unknown parent size. Spacing is the same: a spread's length gap, and a table's gap between tracks, is laid out against the layer's own room by one reader (GoFishNode.gapOf, once per constraint and axis): a percent of the room, or a σ term for fr. It is read, never written into the constraint: the claim walk and layout pass the reader to the placement lowering (GapOf), as they pass a grid's tracks. Which gap a constraint lays out on an axis is one rule (spacingOn, constraints/gap.ts): a table's gap there, and a chain's spacing on the axis it runs along. An fr gap with no room (an unsized root, GoFishNode.sharesHaveNoRoom) is 0 at the σ of 0 that root lays out at, and warns (no-room); an fr in a data scope warns mixed-sizes, once per chain (warnFlexibleSizes). A length has no content minimum: fixed parts larger than a sized layer warn fixed-overflow.

  • A plot claim beside the claim: a layer's plan also computes the claim of the plot, the part of the layer its axes visualize. A layer's space is a collection of its children's spaces, not one space. The type pass gives each child, on each axis, the space it is in in the layer (ClaimWalk.parts, composeLayerTypes in layer):

    • a child the layer nests in its own space (at a datum a position places it at, in a distribute's slot, in a grid's track) is in the space the layer reports there;
    • a child a literal pixel position places elsewhere is in none;
    • a box placed whole (a chart's box, or a node with a size of its own, GoFishNode.plotIsBox) is in none either: it solves its own σ, so to the layer it is a box of pixels;
    • any other child is in its own type, which a nest has unified with the inner it pads (applyNestSpacePlan), so the outer box of a nest is in the inner's space;
    • a ref stand-in is in the part its target is in, in its target's layer (refHome in layer). Reading that layer's parts types it, and where it is being typed already (GoFishNode.beingTyped) that would be a cycle: a layer that encloses this one, which the bottom-up type pass types after this one, or a sibling layer whose own ref names a node of this one. A ref into a layer being typed takes its own part in this layer during the type pass, and its target's in the claim walk, when every layer is typed. This is a declared shortcut around evaluation order (#1318). Two layers that each place a node by a ref into the other are a cycle in the claim walk too, which reports it (resolveExtent);
    • a child that is in no continuous or ordinal part by the rules above, and that a point or "span" align places at a partner that is in one, is in its partner's part on that axis (alignedParts in layer). An align has no offset or gap, so the child's anchor is at the partner's anchor, which is a datum there: the child is at a datum, as a circle is, with a size of its own in pixels. A polar chart aligned to the end of its stem (Forward Syntax/Flower Chart) is in the stem's y part, though it is placed whole. A "span" align ties both endpoints of the child to its partner's, so both are at data and the child joins its partner's part the same way. A "size" align ties only a length and leaves the child's position free, so no endpoint is at a datum and the child joins nothing. Aligns chain, and a ref operand counts as its target's part. A gap is a distribute's spacing, not an align, and a node an enclose draws around refs is aligned to nothing, so neither joins a part this way.

    This is a shortcut tied to the deferred pixel offset semantics (#1053, #1054). A pixel .translate() on an aligned child would put its anchor at a datum plus pixels, which is in no data space. Today the align's solve overrides that translate, so the child sits at the datum and joins. Once pixel offsets have semantics of their own, a child an align places at a pixel offset should stay out of its partner's part.

    The layer's axes attach to the children whose part is continuous or ordinal (isVisualized in underlyingSpace.ts; the claim walk hands placeByClaims the answer as ClaimChild.visualized). Every other child of a layer that has such a part is dressing (placeByClaims): it is beside the part or over it. An enclose drawn around refs, a line or ribbon connecting refs, a .label() text a gap sets past its mark's ref (on the axis of the gap; on the axis an align centers it, it is in the mark's part, and a label at "center" is in it on both), and a chart of those layered over a scatter (.layer(chart(selectAll("points")).mark(enclose()))) all have type undefined on both axes, so they are dressing of the layer that holds them, while the layer's own type stays the scatter's continuous one. A layer with no such part (a layer of literal shapes, or a chart placed whole with a caption at a literal pixel beside it) has no dressing. This is a deliberate shortcut until data types and space types are aligned: pixels are no space here, so a text at a literal pixel beside a scatter whose marks the layer holds is dressing, while beside a chart placed whole it is plot.

    The plot also leaves out a shape's outline (half its stroke past its box, which its claim reaches and its plot leaves out; a node a nest derives reaches its own outline past the padded inner's plot, applyNestExtentPlan) and the chrome rings of a nested node, short of a node whose plot is its whole box (a node with a size of its own, or the outermost ring of a chart(): a parent lays a chart out whole, GoFishNode.plotIsBox). Chrome is laid beside a third claim, the box without its dressing (ChildForms.bare, GoFishNode.resolveBareExtent and GoFishNode.localSpan("bare", …); each is undefined where it is the box). Neither of the other two is it. The box holds the dressing, so ovals that reach past a scatter would push its axes out. The plot of a node with a size of its own is its whole box, dressing included, since a parent lays it out whole (#1210); and the plot of a ring leaves out its chrome, so a title laid beside it would cover the tick labels. The box without its dressing keeps inner chrome and leaves the dressing out, and a node with a size of its own has its content's at the σ it solved. So the axes attach to the part of the layer whose space is continuous, and dressing draws over them. A chain of parts of the plot lays them by their plots, so dressing never moves the parts it dresses: it reaches past the chain, or sits in the gaps (ClaimChild.plot in placeByClaims). The plot leaves out what is placed beside a stand-in, so a chain with a stand-in reaches, in its plot, only as far as its stand-ins. A chart with a size of its own maps its plot into that size (see Chrome around a chart).

  • Alignment establishes a baseline; it does not pin: aligning or overlaying free children gives a free result with one shared baseline (overlayOrigin: pinned only when a child is pinned, none when a child has no origin, and none for middle). The bars of a bar chart are one free magnitude until the scope root places its baseline.

  • Which guide renders (domainOver, axisOver): pinned maps "positions" and renders an absolute axis. None maps "widths": it is a length scale, so it renders no axis and its scale gets a length entry in the legend (Legends). Free renders none, until placed. The render root places a free space's baseline at its originPx (placeBaseline; GoFishNode. placedSpace), so a free root renders an absolute axis, niced about its 0; the axis's frame seats the free content's baseline at its data 0 (the content is left unpinned and the frame's map places it).

A coordinate space is a σ-scope root like any other, so it reports nothing upward on either axis: to its parent it is a pixel box. It keeps its own type for its own scope, solves that scope in layout, and draws its own axes and their titles in lower (see Flattening the Scenegraph). An UNDEFINED child carries no opinion in every fold, alignments included.

The contract ​

Each node implements two hooks, one per half. The type hook, _resolveUnderlyingSpace:

ts
type ResolveUnderlyingSpace = (
  childSpaces: Size<UnderlyingSpace>[], // one [x, y] tuple per child
  childNodes: GoFishAST[],
  shared: Size<boolean>, // [shared on x, shared on y]
  constraints: ConstraintSpec[] // this node's positioning constraints
) => FancySize<UnderlyingSpace>;

returns the node's own [xSpace, ySpace], computed bottom-up from the already-resolved child types. The claim hook, _resolveExtent:

ts
type ResolveExtent = (
  childExtents: Size<Extent | undefined>[], // one [x, y] claim pair per child
  childSpaces: Size<UnderlyingSpace>[], // the children's resolved types
  spaces: Size<UnderlyingSpace>, // this node's own resolved types
  childNodes: GoFishAST[],
  constraints: ConstraintSpec[]
) => Size<Extent | undefined>;

returns the node's own claim pair, computed bottom-up from the children's claims, with every type already resolved. Both traversals are memoized on the node (resolveUnderlyingSpace() and resolveExtent()), and clearUnderlyingSpace() drops both.

Why two walks, and why this direction. A type never depends on a claim: the data interval a stack or an overlay covers is a sum or union of its children's data intervals, not of their pixel sizes. A claim does depend on types: a pinned overlay's claim is the width of the union of its children's spans, and where a pinned child sits in that union is a type fact. So the claim walk runs second and reads the types, and the type walk never sees a claim. The direction is enforced, not just followed. UnderlyingSpace holds no claim value and underlyingSpace.ts does not import extent.ts, the type hook's arguments carry no claim, and resolveExtent() throws if it is called while a type hook is running. One walk returning a pair would have let a type fold reach into the claim half next to it, which is exactly the coupling the split removes.

Most nodes write only the type hook. The claim hook is optional. A node without one claims what its types imply (impliedExtents): each side of a continuous axis is its data extent times σ, with no pixel overhead. The nodes that write a claim hook are the ones whose claim is more than their data: a shape with a pixel size of its own (a text, measured when the claims are resolved, or a rect or ellipse of literal size, boxExtent; #493), the ones that add pixels (a spread's spacing or pitch, a nest's padding, a transform.scale), the ones that compose their children's claims (an overlay, an alignment, a stack, a layer placing its children, placeByClaims), and the pass-throughs that keep their child's claim as it is (offset, the position operator, a ref). A layer claims its plan (buildPlan in solver/plan.ts): one solve over all its children in values in σ, by their boxes. Layout seats each child from the same plan, evaluated at the σ it lays out at (solver/formula.ts, see Piecewise-Linear Values). The plan reads three forms of each child: its box, which it places, its plot, which a chain lays it by, and all it draws, which takes room. A layer's forms are the envelopes of its children's where its plan places them, so an outline takes room only at the ends of the hull. Any other node's box is its own claim rule run over its children's boxes (GoFishNode.composeExtent). A child that places itself at a literal pixel stays there; a child whose y runs the other way is read reflected about its data 0; and a transform.scale scales the forms about data 0, reflecting them when it is negative. A layer that is a scope of its own on an axis (a dims size, which a spread's size option sets once the scopes around it are known) is read by its claim there, not its plan. A node nested in a child is placed by composing plans (planPlacement): its box in its parent's plan, moved by each ancestor's data 0 in the next one's, reflected where y runs the other way. A constraint operand nested in a child is placed the same way up to that child only (planPlacementInChild): its offset in the child, which holds wherever the layer's solve places the child. A child drawn around refs (an enclose of refs) has the box its refs give it as its forms, so a node nested past it is placed too. Every continuous axis has exactly one claim; resolveExtent() checks this. Another axis has one when its content's room depends on σ, or when its content has a pixel size of its own (a claim with no σ in it); content that takes whatever room it is given (a rect with no size) has none.

The constraints argument lets constraints participate in space resolution — each positioning-constraint kind carries a space fold, a typing rule that composes its targets' spaces into the layer's claim on that axis:

  • Constraint.position contributes a fragment: the layer folds the datum coordinates into a POSITION domain on the constrained axis (collectPositionDomains), unioned with the children's spaces. (Literal-pixel coordinates are not data and don't contribute; neither do discrete scatter slots, which resolve directly from the already-known layer size.) That domain is what the layer later turns into a data→pixel scale to resolve those constraints. Only a constraint whose targets are in the layer's own set on that axis contributes (see Sharing sets below). A chrome ring's ticks are each a set of their own (wrapRing), so their datums place them in the ring's frame but are no part of the type the ring reports: a chart's box reports its content's type, and its chrome never re-types it (#1170). A bar chart beside a caption is still a free magnitude to the spread that holds them, so the spread gives it the room its bars claim.

  • Constraint.distribute contributes the stack fold to the type (distributeSpaceFold, constraints/distribute.ts). The chain moves every target to its place, so it reads each one, pinned or free, as a box. A spread separates: its type is ORDINAL of its keys, or UNDEFINED, and its claim is its layer's plan's, the chain of the targets' claims with the spacing added (for an edge chain, the sum of the widths plus spacing·(n−1)), for the enclosing scope to solve σ against (see the differences that remain). With glue: true (stack semantics) the extents are laid end to end and pinned over the range of their running sums ([0, Σ] when no part has a descent), by the chain fold (chainFold) in data for the type, and by the plan's solve for the claim, which places each part by its data offset (below). A glued target that is not continuous is an error (requireAmount), and so is a target of content with a size of its own in pixels (a layer w: 100 around data): it solves its own σ in that size, so it is a box of pixels to the stack (composePlanSpaces).

  • Constraint.align contributes the alignment fold (resolveAlignmentSpace) on its axis — but only for a point-anchor value; "span"/"size" (#726, below) contribute nothing to the space fold, since their target is UNDEFINED on that axis by construction.

  • Constraint.nest contributes the nesting fold (nestedSpace for the type, nestedExtent for the claim, constraints/nest.ts) and a deterministic dependency plan (constraints/nestPlan.ts). It is the first size-setting constraint: on each constrained axis outer = inner + 2·padding, with padding always known, so the unknown is which side is derived. The nest plan dispatches on which side carries the size (an own args.dims, a composite that shrink-wraps, or any inside-out-derived outer from the same-axis nest graph): inner sized and outer not → inside-out (outer = inner + 2·padding); outer sized, or neither (the layer sizes outer) → outside-in (inner = outer − 2·padding — CSS padding). Only the inside-out direction folds here: outer's type is inner's type, whatever its origin (padding is pixels, so it is no part of the type), and outer's claim is inner's padded on both sides of its baseline, a Pwl.addConstant, which stays exact (hence invertible), so a nested pair participates in auto-fit exactly like a stack — a parent spread/layer solving a scale factor sees outer as inner shifted up by the constant padding. The layer derives these outer spaces in dependency order (source before derived) so chained nests compose (A⊇B⊇C: C's request feeds B's, B's feeds A's), then feeds them into the union below. The outside-in direction derives nothing at space-resolution time — outer's own claim (or fill/undefined) flows through the union normally, and inner = outer − 2·padding is handled purely as a layout-time pixel proposal. (Likewise when an inside-out inner is not continuous — fixed-pixel content — there is no rule to fold; the proposal inner.dims + 2·padding sizes outer.) At most one nest may derive a given (node, axis), and a nest that resolves inside-out on one axis and outside-in on the other is rejected as mixed — the layer enforces both at constraint-collection time (see size-claims).

  • The interval form of Constraint.position ({ x: [min, max] }, lowered by constraints/position.ts to two strong edge pins — a start pin at min and an end pin at max) is the second size-setting constraint: pin BOTH edges of a target on an axis and the size falls out — the relation place()'s position-only protocol cannot express. It is built on the linear-system bbox (constraints/bbox.ts, #39): a per-axis 2-unknown system in (min, size) where each box key (min/max/center/size) is one equation; two independent keys are rank 2, so the rest are inferred (two edges ⇒ a size), and a third, dependent write is a structured over-determination report rather than a silent last-writer-wins. An interval's datum endpoints feed the axis's POSITION domain via collectPositionDomains (like a point coordinate does), and planConstraintComposition treats an interval position as an extent-establisher (like a distribute), so the cross-axis align fold still runs — a histogram is an interval position on x plus an align on y, and it is that align fold (SIZE→POSITION) that makes the count axis. The solved (min, size) is bridged into GoFish's (local box, translate) split by keeping the local box's own min (where the target's layout put it), stamping the solved size, and deriving the translate as the absolute min less that local min through the placement ledger. The local min must stay: a container's children are placed in its local frame, so moving its min to 0 would draw them away from its box by the old min (on an upward y, a spread pinned across a cell drew its bars one cell away). The interval also sizes the target before its layout: the layer proposes the span's pixel length as the child's size on that axis (buildChildSpans, constraints/proposalPlan.ts), so the child's content fills the span it will be pinned across rather than being laid out in the whole layer and then stretched. scatter uses both forms of Constraint.position: plain x/y → a point coordinate, range xMin/xMax/yMin/yMax → an interval coordinate (the operator no longer has a bespoke layout). A position constraint may instead give its target a region (region: PositionRegion, #1059), which is what partition uses. It sizes its target as an interval does, but pins only the target's middle at the cell's middle, so the target keeps the size its layout gave it (see Partition). A categorical scatter channel such as x: "lake" lowers to discrete placement coordinates i / count · axisSize; those are placement coordinates, not datum values, so they become numeric placement facts without affecting the layer's data domain.

  • A Constraint.position may read its datums in another node's frame (in: ref, #1257): datum(v) is then the point v in the frame of the node ref names, wherever that node sits below the layer, not in the layer's own frame. Chrome uses it: an axis's ticks sit on the plot's scale even when the plot is a scope of its own that the ticks are outside of. Such a datum is no part of the layer's domain and does not join its target to the layer's set (planSharing treats it as a pixel). The claim walk reads the frame as two points of the named node's plan, its data 0 and its data 1, carried up the plans to the layer (frameIn in solver/plan.ts); layout measures the same two points off the laid-out node (GoFishNode.layoutFrames) and the translates between. It is internal for now (#1289).

  • align's "span"/"size" values (#726, constraints/align.ts) are the third size-setting mechanism — ships the unbound-target case from the "lingering open item" operators-vs-constraints flags (a bound target is still an ownership conflict, not a silent write; see operators-over-placed-nodes §3.5): "span" reads the source's already-solved (min, size) at lowering time and emits two strong anchor-pin facts on the target (start/end) — the same two-edge cell-closure route position's interval form uses, so it reaches rank 2 through the existing bbox machinery with no new solver phase. "size" needs a genuinely rank-1 write (a size with no position coupling), which the anchor-pin vocabulary can't express (every anchor maps to a min/max/ center box key) — it gets its own SizePinFact/emitter.pinSize that writes the size box key directly. closeSizes reads a box's size key even when the box never reaches rank 2 (a direct pin, not just the solved system), so a size-pin with no companion anchor pin still surfaces a determined size with no solved position; the write-back for that case is a new rank-1 sibling of setExtent, GoFishNode.setSizeOnly (writes intrinsicDims[dir].size only — no ledger, no translate), so the target's position is left to whatever else determines it (a companion align, or the parent-seed placeUnplacedChild fallback). Both values are scoped to an unbound target — spaceOn(axis) is UNDEFINED (no w/h/data binding on that axis) — checked before any fact is emitted; a bound target is an ownership conflict, reported per the paragraph below rather than clobbered.

The layer composes these per axis — children not covered by a constraint max-union in as overlay siblings. On an axis a constraint does cover, that fold is authoritative and overrides the layer's default unionChildSpaces — even when the fold is UNDEFINED. This matters for an align over ORDINAL cross-axis children: the alignment fold is UNDEFINED (no anchored axis), and if the default union were allowed to win it would resurrect an ORDINAL space and a spurious axis (a waffle's chunk(n) row index leaking a row "axis"). The composition is planned once from the constraints and the child nodes alone (planConstraintComposition, constraints/compose.ts): which children each distribute and align covers, on which axis. The type fold (composePlanSpaces) evaluates it; the covered-axis type fold, UNDEFINED included, is what it reports. The claim is the layer's plan's (solver/plan.ts), which places the same children by the same constraints. At layout time the layer then solves the budget: its claim is inverted against the layer's allotted size to derive a local scale factor. Each child that is a share is proposed its claim at that σ (a band is one σ, childLayoutSizeProposal's own), so a chain of fill children is laid out as its claim says, not by dividing the box. This is what makes constraint-assembled layers reach the same expressive ceiling as the spread pipeline, auto-fit included (issue #475). Composition beyond one distribute (+ one align) per axis falls back to unionChildSpaces; the general algebra is sketched in constraints-as-core.

Sharing sets. A second plan reads the same inputs, the constraints and the child nodes: planSharing (constraints/compose.ts) splits a layer's children, per axis, into sharing sets. Two children in one set read their data values on that axis in one frame. Set 0 is the layer's own set, and a child in any other set is detached on that axis. A literal pixel position detaches its child, a spread's distribute detaches each part and nests it in its slot, a grid does both on both axes, and align, a stack's glued distribute and nest join their children. One classifier, positionCoordKind (constraints/position.ts), says whether a coordinate is pixels (a number, or an interval of numbers) or a datum (a datum point, or an interval with a datum endpoint). A position's coordinate on an axis is its point or interval there, or its region's span there (axisCoordinates): a partition cell's edges are datums, so a cell's child is nested at its cell, as a scatter's glyph is at its point. Detaches run first and joins second, so an align beats a position on the same axis. The nested half is the datum placements plus the spread slots and grid cells. The plan also returns the datum placements on their own (datumPlaced), which the layer's own union leaves out. Unlike planConstraintComposition, the plan exists for every layer, point positions included. The layer's type hook, the keyed domain table and the GOFISH_DUMP_SHARING dump read it. It is step 3 of the measure-keyed domains design, which lists what each construct contributes. planSharing is the layer's sharing rule. Like the type hook, each node type has its own rule (resolveSharing, read through GoFishNode.sharing(), which memoizes the plan and clears it with the types), and a node without one lets every child share (shareAll). Three rows of the table are node-level rules: a layer with a data-valued w/h nests its content on that axis, a treemap detaches each child and nests it in its tile on both axes (nestEach), and the position operator detaches its child on an axis with a pixel offset and keeps it shared on an axis with a datum offset.

distribute's spacing (a Spacing value, families/spacing.ts) picks which pair of anchors the chain relates between adjacent children. createDistributeConstraint normalizes it once (spacingOf: a bare amount is Spacing.box(amount), and the strategy is checked against the Spacing family, even under glue, which then uses a zero box), and distributePlacementAnchors dispatches on its kind. Spacing.box(gap) relates the facing edges (prev.end → cur.start, spacing = the gap between them, content-dependent); Spacing.pitch(distance, { at }) relates the same anchor on both sides (prev.at → cur.at, spacing = anchor-to-anchor pitch, content-independent) — at[i+1] = at[i] + distance, with at one of "start" | "middle" | "end" | "baseline", default "baseline". A glued distribute (glue: true, i.e. stack) relates no anchors: each part is placed by its data offset (below). A part's tail is where its baseline sits, or its start when it is not a baseline magnitude; its head is the point as far in from its end as the tail is from its start, which is the baseline moved by ascent − descent. A positive bar's tail is its start and its head its end; a negative bar's tail is its end and its head its start, so the next part starts where it ends. A middle pitch is the old mode: "center" (later anchor: "middle"); the other pitches reuse the same anchor vocabulary align already uses (constraints/shared.ts's AlignAnchor). The claim is the layer's plan (solver/plan.ts), which lays the chain by the placement solve layout runs: each part sits about its chain point by its anchor, the next chain point is one step on, and the claim is the highest reach above the chain's start plus the lowest reach below it, over every part. A pitched chain's claim steps its anchors one pitch at a time in the chain's axis order, and reads each part's claim in that order too: the plan reads the claim of a part that reads y the other way reflected about its data 0, as its view in the layer's order (orientView) places it. So a ridgeline's rows (chained down a y that reads top-down, each growing upward from its anchor, see Axis direction) reach back over the rows chained before them. Each part sits about its anchor:

  • "middle": half its width above the anchor, half below.
  • "baseline": its own signed sides, ascent above and descent below.
  • "start": its whole width above the anchor.
  • "end": its whole width below the anchor.

So with one-sided parts the claim is (n−1)·s plus the tallest reach past the chain's end rows: max_k(h_k − k·s)⁺ + (n−1)·s for rows that reach back over the rows before them, as a ridgeline's do (k in chain order, the binding row being whichever peak clears the rows chained above it; usually the first row). A "middle" row taller than both end rows binds too, and a "baseline" row's descent counts below its anchor. The solve runs in values in σ, so an all-linear chain's claim is an exact envelope that a scope inverts exactly (before, a pitched chain's claim was a closure, solved by a numeric search that could overshoot its box by a fraction of a pixel). The fold's child order is the chain order (compose.ts passes placement order).

The type fold has no data part of the chain: a spread separates, so its type is ordinal (or undefined) whatever its pitch, and the chain lives only in the claim. That claim is measured from the chain's origin, where layout seats the first part's anchor, as its parent overlays it: an edge chain starts there, and a pitched chain reaches past it on both sides (a ridgeline's first peak rises above its first baseline).

A spread chain on y needs no paint-side handshake. The chain places each target's anchor in the spread's own axis order, and the target is read through that order like any child (see Axis direction): a ridgeline row, whose y is continuous, has its baseline placed at the chained anchor and grows upward from it, so the painted anchors sit exactly at the solved pitch and the layer's box is the rows' real pixel extent. (Before #681 the rows were laid out growing down and mirrored about their anchors at paint, which needed a pitchAnchorY stamp, a mirrored bbox fold and a swapped overhang attribution.)

resolveLayerBaseSpaces is the default bottom-up type resolver before composed constraint overrides: union child spaces, and overlay datum-valued position/span domains on that union as a pinned space (a free union seated at data 0, where the layer places its free children), with constraint measures taking precedence. A layer's claim is its plan's, which scales by the layer's transform.scale whatever its origin. A transform.scale is a pixel-space operation, like translate, so it scales the claim and never the data interval. childLayoutSizeProposal is the final per-child proposal priority before nest: the cell's own track extent (grid), else the child's claim at σ when it is a share, else the full layer box; then, on an axis an interval position spans, the span's pixel length (the pins set the child's extent there, whatever else proposed one). buildLayerConstraintLayoutPlan packages the per-layer execution plan — which children skip baseline placement, nest source-before-derived order, and datum-position target axes — so the layer executes deterministic artifacts rather than recomputing them inline. Nest sizing is split into a dependency plan and concrete layout arithmetic: buildNestPlan decides, per constrained pair, whether the source size flows inside-out (outer = inner + 2·padding) or outside-in (inner = outer − 2·padding) and orders children so the source has been laid out first. The bottom-up walks apply only the inside-out portion, the type walk via applyNestSpacePlan and the claim walk via applyNestExtentPlan, which reads the types the first one produced; once the source has concrete dimensions, applyNestLayoutProposal does the corresponding layout-time arithmetic on the derived axes. Grid is a track equation under the same sizing rule, not a separate layout regime (Stage 6e). Per axis, gridTracks sets

track claim = Pwl.max(claims of the cells in that track)      (max, +)
grid claim  = Pwl.add(track claims) + gaps                    (the σ-frame)

A cell's claim counts whatever it is: a magnitude, a pixel size of its own, or the one σ a cell that fills a share claims (#493 piece 3). A track whose cells claim nothing is not sized by its content, so it is a share of its scope, fr(1): one σ. So an all-fill grid claims n·σ + gaps, and the scope it is in solves it to give each track (allocated − gaps)/n. Content-sized tracks size to their widest cell, and are fixed parts, like the pixel gaps; a gap may also be a percent of the table's room or an fr weight, a term of the claim. The grid claim is the layer's claim on the track axis: its plan composes the tracks and gaps as a chain does (placeByClaims), so the one fit of its nearest scope (ScopeRegistry.fit) solves σ for it, with the one overflow warning and the one fallback, and a table nested in a chain claims its shares in the chain's scope. Because a categorical track axis cannot simultaneously be a SIZE magnitude, the grid's reported space stays ORDINAL over the columns/rows (gridSpaces, for axis rendering; ordinalOver the keys table's split found, so a binned column or row key gives an ordinal over its cells, as a spread's does: the split runs splitEntries once per key, as spread does, and each cell of the table holds the rows in both groups) while its claim is the tracks'. A track is sized by its cells' boxes, in the claim walk and in layout alike: what a cell draws past its box (an outline, a label) overhangs its track. Layout reads the same track rule over the same boxes, the forms of the layer's plan (cellBoxesOf), at the σ the layer lays its cells out at (gridCellSizesAt), and proposes each cell its track's extent; the plan then centers each cell in its track from the laid-out cell sizes, one source every reader of the placement shares, so they cannot drift. Where the layer has no σ on an axis (an unsized root, where shares have no room), a box that grows with σ sizes no track, as the layer proposes a spread's band no size from its claim; a track no box sizes has no extent, and its cells keep their default size there, as a spread's bands do. Every reader finds a cell by the grid's own refs (CellOf), in the grid's row-major order. A track no cell's box sizes, in a scope that data sizes, is one data unit wide, and the table warns mixed-sizes as a chain with a flexible part does (shareTracks, warnFlexibleSizes).

The grid now genuinely composes with sibling constraints: its per-track claim participates in the fold and its cell-center pins solve jointly with any align / position / z-order on the same layer (a position pin on a cell overrides its track centering — the authoritative-pin pattern). The Stage-3 containment throw is gone. selectGridConstraint keeps the one remaining rule: at most one grid per layer (two track partitions would be source-order-sensitive) is still a proposal conflict. Grid has no public factory; it is table's private elaboration target. The same proposal plan marks datum-valued position targets (buildPositionTargetDims) so the layer does not also forward the consumed data→pixel scale to that child axis; literal pixel pins are not marked because they do not consume a data scale. The placement solver resolves datum positions against the layer's frame (solveLayerScales): the frame it is handed, or its own when it is sized. Child scale forwarding reads the same frame (childPosScalesFor): unowned axes forward inherited/base scales, while owned axes forward the layer's effective scale only to non-target children whose own space is POSITION.

After sizing, the layer emits placement constraints into a per-axis rank-2 solve (constraints/placementSolver.ts) that resolves each (node, axis) box (min, size) — not just a single min unknown. The fact datatype lives in constraints/placementFacts.ts: the anchor program (axes: [AnchorFact[], AnchorFact[]]) of anchor pins, anchor relations, and participants. A fact names a node anchor (start/middle/end/baseline) directly, with no numeric offset pre-evaluated at lowering-time — the offset from min is derived later, in the solver, once sizes are known. Named constraints first lower to this inspectable program; solving consumes it rather than mutating solver state during lowering. Constraint-specific lowerers live with their constraints: align.ts, distribute.ts, position.ts, nest.ts, and grid.ts own their policy choices, while placementLowering.ts orchestrates them and placementProgramLowerer.ts emits anchor facts (guarding only that the target exists). During lowering, PlacementOwnershipPlan records pre-existing placements, authoritative position overrides, and axes claimed by position facts (a point pin or an interval's edges) so legacy read-vs-write policy is explicit data rather than scattered set checks.

The solve is two phases per axis. Cell closure feeds each node's STRONG anchor pins into a per-axis linear-system bbox (constraints/bbox.ts): two independent edges are rank 2, so the size falls out (the interval/span case) — this is where a target's size is determined, with the node's own weak layout size the default when no strong equation reaches it. A bbox over-determination (two conflicting intervals on one target) is a named-owner conflict naming both owners. Then the difference graph (constraints/differenceGraph.ts): with sizes known, every anchor reduces to min + offset — start/baseline/tail at 0, middle at size/2, end/head at size for a size-strong cell (read off the closed box, strongAnchorOffset), else the node's local-frame anchor offset (anchorOffset; a stack part's tail is its free baseline's offset, or 0, and its head is size − tail). position, align, distribute, nest, and grid pins/relations over those reduced min values go through BFS components + pin offsets + free/distribute/normalized-origin fallbacks. The solve is written once over an Arith (see Piecewise-Linear Values). It runs once, in the claim walk, where the targets are boxes read off claims and a datum maps through a symbolic σ, and its results are formulas that layout evaluates at the solved σ with what it measured: the laid boxes, the pixel of data 0, and the place of each child that places itself (a shape at a literal pixel or a data position, an axis span or a connect, which set placedByLayout). On an axis with no position scale a datum that is not a number has no pixel, so it emits no fact; against a real position scale it is an error (compilePlacementCoordinate). Every solved cell writes back through one path: a size-strong cell sets its extent (setExtent({min, max})), a position-only cell pins its min anchor, a rank-1 size-with-no-position cell (align "size", above) sets its size only (setSizeOnly) — replacing the old three-way branch and the size side-channel. A bbox conflict throws (both intervals' owners named in the message) rather than the silent last-writer-wins an ungoverned second write would otherwise produce (#725/#726). The solve runs in the claim walk, where the boxes are formulas, so it records each over-determined box as a check (Arith.agree), and layout makes the check at σ when it seats the children. Align "span"/"size" reuse this exact path for their unbound-target check, and lowerAlignPlacement separately warns (not throws) when a constraint ends up with nothing movable — every listed operand already placed — except where an operand is placed by its own data (a scatter facet, a nested partition's cell: isDataPositioned), which stays silent.

Before any of this, every placement operand of the layer is resolved to a node inside it (resolveReferences, _ref.tsx), and the solve keys each one by that node's uid (keyOf). An operand a user writes is a name, and it goes through the same lookup as ref("name") (see Name Resolution & Scoping), once per distinct name. Operators such as spread and the axis, legend, and label chrome refer to their own children by slot (SlotOperand), so no name is looked up. A missing, ambiguous, or out-of-layer operand throws (#819), so a constraint can no longer bind nothing in silence. An operand that is a direct child is its child's placeable, as before. An operand nested inside a direct child is a NestedOperand (constraints/nestedOperand.ts): its box is the container's box plus the constant offset the container's own layout gave it (the plan input gap:@n), and the solve adds one rigid anchor-relation (container start → operand start) per axis the operand takes part in. Only a directly named child skips phase-1 baseline placement, so an unnamed container stays put and the nested operand is a fixed reference; a named container moves in the solve and carries the operand with it. The container does the write-back; the stand-in's own placement writes are no-ops, and its size writes throw, because a layer cannot resize something another child already laid out.

The placement-coordinate compiler preserves the literal/datum distinction until facts are emitted: literals are pixels, while datum coordinates elaborate through the already-solved data→pixel scale plus any post-scale offset. A box placed by a data center (circle({ cy: "value", r: 5 }), a rect with cx) is a glyph like a text or an image: its axis space is glyphAxis of the center, and its layout puts the center through the scale and takes the box's middle, measured from its origin, off (positionOf in dims.ts, which every box mark places its origin by: a rect, an ellipse, a text and an image). The middle is half the box's pixel size, except in x for a text, whose origin is its anchor point inside its box. Its claim reads the same rule before the scales exist (literalStart in extent.ts). This keeps the unified constraint semantics without a generic dense linear solver: strong facts win, relation cycles are checked for contradiction, and components without an absolute pin are normalized so the minimum solved coordinate in that component is 0. Two kinds of component are the exception. One whose free nodes share a baseline seats it at the layer's free-child origin (below). Ordered distribute components are the other: their directed chain source is a deterministic sequence origin, so negative spacing remains authored overlap instead of being erased by min-normalization. If a graphic needs a floating component to appear at a particular absolute coordinate, that placement must be explicit. A layer's .relate() can also hold drawing clauses (an arrow, an enclose over refs), which are children of the layer that read positions instead of writing them. The layer lays out its plain children and runs the solve first, then lays out each drawing clause, in the order scheduleRelate (constraints/relate.ts) computes from what each clause reads; a clause is placed at the layer's baseline origin like any unconstrained child. See Name Resolution & Scoping.

The legacy per-constraint apply helpers have been retired from the constraint path; spread, scatter, table, axes, and hand-written constraints all lower to the same solver entrypoint. An incompatible same-solve interval + point position on the same target/axis reports an over-determined placement instead of letting one silently yield to the other.

Placement-time alignment dispatches on the same resolution. align emits relations between child anchors and never pins. Where a floating component lands is the solver's fallback, and its first rule is the free-child origin (#773). A free child (a baseline magnitude, such as a rect with a data h) has a baseline that stands for the measure's origin, the value a signed h/w grows from. That origin is data 0 of the owning layer's frame, and its pixel is the frame's originPx, by the one seating rule (seatInScope). The layer computes this per axis (freeOrigin). It places unconstrained free children there itself (phase-1 placement, and placeUnplacedChild for a child the solve left unplaced on an axis), and hands it to the solve as one input: in solveAxisProblem, a component with no pin whose free nodes share one baseline is offset so that baseline sits at the origin. Free nodes whose baselines differ (an end or middle alignment) have no common baseline to seat, so that component falls to the sequence or normalized origin as before. A distribute chain along the axis places its members' baselines itself (its lowering marks those relations chain), so the solver (solveRank2Axis) does not list them as free. A stack has no chain: its 0 is the 0 its running sums are measured from, and every part states it. The stack's lowering includes each part with its data offset times σ before its tail (AnchorParticipantFact.origin, { tail }), and the solver lists that point whether or not the part is a baseline magnitude, and whether or not it is size-strong (a size-strong part's tail is its start). Each part is then a component of its own, seated at the origin by its stated 0. A stack in a layer with no data 0 (a middle or wiggle stack, whose space has no origin) still has its own 0: the solver seats the stack's origin at the layer's pixel 0, where the free origin would be. Only a free node's baseline needs the layer's data 0. So a node's 0 is where its baseline says, and a node that says nothing has it at its data 0, else at its start.

Every stack is placed one way (stackPlaces). A part whose offset is a constant states its tail that offset times σ from the stack's 0, and the solve places it there, as it places any box: its claim is its own claim moved by σ·offset, its pixel dressing (a stroke) included, and nothing is added between parts. A part whose offset changes along u states its tail at the stack's 0, and the layer hands it the offset as the shear of its AxisScale on the stack's axis (composeLayerTypes → stackPlacesOf in layer.tsx). The band adds it to both edges before it maps them (band.tsx), so its box, outline and cross-section are where it is drawn, and labels, ref and selectAll read them there. Only a node with a shearAxis (a band, on its value axis) draws a shear. Any other part with a changing offset is an error that names it: a rect or text has one size along the axis, and it can't be split along a changing boundary. Every part of a stack is an amount (requireAmount), so every part has a data offset. Overhang still enters a stack's claim in two places: each part's claim, its box widened by its stroke, at the stack's two ends and on the cross axis; and a sheared band's outline (placeExtent, TODO(#1368)). So a stack seats at the origin like a single bar, a negative first part hangs below it, and two stacks of one sign each (grouped by sign) meet on the 0 tick. A stack over a HasMidpoint column carries its origin at the midpoint of the order (a fraction of the way through the part it falls in, or the tail of the first part past it), so every row of a Likert chart seats its midpoint on the 0 tick with no other code. A spread with no baseline packs boxes from its first member's start, which is not a baseline, so it lists none and keeps its sequence origin, even when its members' baselines happen to coincide. Its lowering marks its relations chain, and the difference graph gives a component that holds one no baseline at all, so a free node aligned to one of its members does not seat it either. A spread given a baseline states its 0 as a stack does: it carries an origin, the solve lists the part that carries it as stated (FreeOriginInput), and a component with a stated 0 is seated by it like a stack's. So a bar with value −35 on an axis niced to [−40, 50] grows from the 0 tick, not from the rounded −40. A free layer is itself seated by its parent at its own baseline, so its frame has that baseline at local 0 (frameOf), and so does its free-child origin: applying the map again would count the offset twice, and letting the component float would let min-normalization lift a descent off the baseline. A sized layer solves its own σ-scope, so its frame is that scope's, with its origin at the scope's originPx (descent·σ), the same rule as the chart root. A layer with no data 0 on the axis has no frame, and its components float. Anchored children share the layer's frame and stay at 0, as the next paragraph explains. Data 0 stands for the additive identity of the measure's algebraic structure, and measures do not carry that structure yet (a TODO on seatInScope).

Otherwise, if no explicit position (point or interval), self-placement, or other strong pin fixes a connected component and it has no shared free baseline, the solver normalizes that component so its minimum solved coordinate is 0. A user who needs the aligned system to appear at a particular place must say so explicitly with a placement constraint.

That normalization is also what keeps data-positioned children safe. A faceted scatter panel over [1955, 2010], anchored to the shared y data scale, should not be pulled to posScale(0) (data-zero, far below 1955). So align leaves it alone: a target its own data places is not moved, by any anchor — align shares the frame (it still unions the children's data intervals) but supplies no baseline. Its baseline is already posScale(0) of the shared scope, so all such panels co-locate by construction. The claim walk places such a target before the solve, where its frame seats it (placeByClaims), so the solve reads it as already placed. A target is placed by its data only where its layer keeps a frame of that data: a middle align over pinned children (a streamgraph's centered stacks) composes the layer to an origin-less type (none), so there the align places each child, and centers it.

The guard asks the solver, not the space pass (Stage 6f). This is the blindingly-obvious final form the whole design arc was reaching for. The question "is this target already positioned?" is answered by the placement solve's own authority record — the PlacementOwnershipPlan — through one predicate, isDataPositioned(axis, name). The fact it reads (which children are anchored to a POSITION scope on each axis) is a pure data/scope fact — a child in the layer's own set whose type on that axis is pinned, in a layer whose own type there is pinned too (placedByOwnData, the one rule the claim walk, layout and the sharing of rooms read; a free child still waits to be placed, and an origin-less one has a width but no place) — collected once at the layer boundary and handed to the solve as an explicit ownership input. The constraint path no longer reconstructs the space pass's free/determined/conflict lattice by calling a placementOn method on the target mid-lowering; there is no layout fact derived from the space pass in the guards anymore. (The space folds themselves still read the origin state — the union/middle/anchored decisions — which is where a determinacy read belongs.)

When alignment does write an anchor relation, it asks Placeable.localAnchor(axis, anchor) for the anchor's coordinate in the target's local box. GoFishNode.localAnchor() derives that from the node's intrinsic dimensions (including baseline/min/center/max), so relation solving can handle asymmetric boxes such as text and negative bars without relying on the display transform.

Because the fact is a single scope-membership input to the solve, this is the whole mechanism — no flag, no scoping. (Historically the same effect needed a guardDataPositioned flag on spread/scatter aligns plus a per-axis fromSize boolean reconstructed from the pre-fold child spaces in the layer; then a placementOn method reconstructing the placement lattice per target during lowering. All are gone — the ownership plan's per-child scope-membership read is strictly more general, handling a mix of positioned and free children that the old all-or-nothing axis guard could not.) See the spec for the "space as abstract interpretation" framing this falls out of.

Three patterns cover most operators:

Leaf shapes (rect, ellipse, petal, text, image) decide the kind from their props. A rect with data-bound h emits CONTINUOUS(interval(0, value), "free") on y (the value's positive part as ascent, its negative part as descent); the same rect with literal y and y2 emits CONTINUOUS(interval(y, y2), "pinned"). Constants (no data-bound dim) emit UNDEFINED — the literal pixel value is handled at layout time by computeAesthetic, not via the underlying-space tree. (The old anomaly where a literal-pixel min plus a data size made DIFFERENCE while an absent min made SIZE is gone: both are CONTINUOUS, differing only in their origin state — an off-scale pixel min is a difference, an absent min is a free magnitude.) A leaf writes no claim hook: its claim is the one its type implies.

Compositional operators (spread, stack, layer, enclose) combine children's spaces. spread({ glue: false }) keeps the magnitude along the stack direction so a parent can solve for shared scale factors via Pwl.solve. spread({ glue: true }) (i.e. stack) lays children's extents end to end into a POSITION over their running sums ([0, sum] for positive parts) — the operator commits the data-driven magnitudes to an anchored axis. Since the operator/constraint unification, these folds have one home: spread's resolver isdistributeSpaceFold on the stack axis and resolveAlignmentSpace on the cross axis — the same functions the constraint path uses (see The contract); its claim is its layer's plan's. layer and overlay-style operators use unionChildSpaces (alignment.ts). All of them are the one overlay fold: the union of the children's seated intervals (each on its baseline for an overlay), with the result's origin pinned when any child is, free when every child is, and none otherwise; its claim half, unionChildExtents, overlays the claims the same way, keeping the symbolic values in σ (the per-side max of the ascent and descent claims) for a free result. UNDEFINED children carry no opinion and are ignored throughout, so a fixed-pixel (UNDEFINED) sibling never vetoes the magnitude-preserving path.

Coordinate-transform operators (coord) fold their children with the same overlay fold (a category axis wins, a declared window pins), annotate the result with the transform that will later map underlying positions to display positions, and keep it for their own σ-scope; see Flattening the Scenegraph. A space is written as a layer with a coord, layer({ coord }, [...]): the layer is then the space's box, and hands the space its dims, key, axes and padding. A chart's node is such a layer over its content (frameChart), so a chart({ coord }) is one too. The space gets the layer's node children only. A ref stand-in is left out, because its place is its target's, and only a layer without a coord plans that (planPlacement).

Worked example: stacked bar chart ​

js
chart(seafood)
  .flow(spread({ by: "lake", dir: "x" }), stack({ by: "species", dir: "y" }))
  .mark(rect({ h: "count", fill: "species" }));

Each rect starts with a data-driven height and no data-driven y position: its type is [UNDEFINED, free [0, count]], and its claim on y is the implied count·σ.

The vertical stack (which is spread({ glue: true, dir: "y" })) glues each lake's species rects together. Its stack-direction children are all free magnitudes, so it lays their data intervals end to end and pins the result: pinned [0, total_lake_sum] on y, claiming the parts' claims end to end (total_lake_sum·σ). The alignment direction (x) of the stack is UNDEFINED because each rect's x is UNDEFINED.

The horizontal spread separates lakes. Its children are now stacks with [UNDEFINED on x, pinned [0, total] on y]. Stack direction (x): no children are continuous, but they're named (the "by" key produces lake keys) → ORDINAL(["Lake A", ..., "Lake F"]). Alignment direction (y): the children are pinned → pinned unionAll([0, total_i]) = pinned [0, max_total]. (Lining up unstacked bars instead gives a free [0, max]: alignment shares a baseline, it does not pin. The render root then places that baseline and renders the same absolute axis.)

So the root underlying space is [ORDINAL(lakes), pinned [0, max_total]]. The y-axis renders quantitative ticks (POSITION); the x-axis renders ordinal labels at laid-out positions (ORDINAL); both follow from the tree, with no special "bar chart" rule.

The stack's size → position transition is the important step. A single rect with a data-driven height doesn't by itself establish where that height lives in a shared coordinate system — it only says it has a quantitative extent. The stack gives those extents a common origin and glues them edge-to-edge, producing a position space from zero to the bar total. The spread doesn't glue; it separates.

Size resolution ​

To map data to screen space, we need to figure out how to scale it to fit. As a rule of thumb, we want all of underlying space to be visible. As a consequence, bar charts should never be truncated, because each bar is fully embedded in the underlying space. On the other hand, a scatterplot's points may be truncated on the edges of the frame since their sizes are not embedded in the underlying space of the graphic.

Continuous space resolution. For position and difference spaces, we are basically mapping some interval of minimum and maximum values to available physical space. This can be performed by a traditional scale function. For now, we assume these scales are always linear and lean on data pre-processing and coordinate transforms to introduce non-linearities.

Discrete space resolution. Layouts like spread's arrange things using pixel-based spacing (like putting 8 pixels of spacing between bars) so we can't compute a scale function right away. Instead, we assume we are looking for some linear scale factor (data could be scaled using a non-linear scale function before this) and we have to figure out how to scale the shapes that are being placed by creating a function from the scale factor to the output size if we use that scale factor. Then we solve.

A shape can have three kinds of sizes:

  • fixed (eg, rect({w: 10}))
  • inferred (eg, rect({w: undefined}))
  • data-driven (eg, rect({w: 'foo'}))

These correspond to three kinds of intrinsic sizes:

  • fixed: constant, non-zero size, no dependency on scale factor
  • inferred: constant, zero size, no dependency on scale factor (this seems a bit weird and may be changed later)
  • data-driven: size depends on scale factor

In truth, data-driven sizes seem to act like the inferred case as well, because they can take on any size given to them (although they sometimes have a minimum size, such as a spread operator where even if the shapes have 0 size, the spacing between the shapes yields some minimum overall size).

Glyph sizes and lengths of the space ​

A data size is one of two things, by one rule (#972).

  • A glyph size. The rule is per axis and belongs to the size's unit. A unit is a glyph unit when, on some axis, the mark is placed at a datum in another unit, and the size the mark is given on that same axis is in the unit. Its parent places it there (at a point or in a cell, when the parent's axis is in another unit), or its own value position does (a cx or x in another unit). Every size in a glyph unit is a glyph size (GoFishNode.isGlyph), so circle({ area }) placed on x only is a glyph on y too: it is given one size, in one unit, on both axes, and one unit has one σ. A glyph size is a scale of its own, keyed by its unit. No axis's σ scales it, and a coordinate transform does not warp it. A bubble in a scatter and a circle in a 2D histogram's cell are glyphs.
  • A length of the space. Every other data size is a length along its axis: one whose unit has no datum position on an axis it is given on, or one in the unit of the parent's axis that places it. The axis's σ scales it, its claim is part of the axis's claim, and a coordinate transform warps it. A bar in a stack, a circle in a spread's slot, and a histogram bar are lengths. The histogram bar sits in a bin cell on x, but its height is a size on y, where nothing places it at a datum.

Sizing and embedding ask this one question (GoFishNode.isGlyph, decided once per node and axis and memoized with the claim walk). The embedding pass keeps a glyph flat (resolveEmbedding), and layout hands a glyph its unit's σ in place of its frame's (GoFishNode.layout), so a layer passes its children its frame's σ and nothing more.

The litmus test is whether the coordinate system should warp the shape. In a bubble chart it should not: the bubble's area measures population, and the axes measure GDP and life expectancy. In a spread of circles it should: the circles are the axis's extent, as the bars of a bar chart are. A histogram bar's height should warp too: in polar it becomes a ring segment's depth.

A box declares its aspect lock once (AspectLock, from elaborateOwnDims, shared by rect and ellipse). A size the lock derives is not given on its axis, so it takes no part in the rule: it follows the size it is derived from, and its data size is that size times the ratio. circle({ h: "value" }) placed at a year on x only is given its height on y, where nothing places it, so the height is a length of y and reads against the value axis, as the histogram bar's does, and in polar it warps. Its width is the height's pixels. On x the width sits at a datum in another unit, so its pixels are at y's σ, which no claim on x can be written in: it claims nothing there (its size kind is "follows"), and the circles at the ends may reach past the plot. circle({ w: "value" }) there is given its width on x, where a year places it, so it is a glyph, and its height is the same glyph size.

Each glyph unit has one σ, found as the shared-measure σ is (#582): every glyph bounds it, and it is the smallest bound (ScopeRegistry.glyphSigma). A glyph's bound is the σ at which its own domain fills its room. A glyph in a cell has the cell for its room, which is data on the axis that places it, so its pixels are known at its frame's σ; the largest σ that fits every glyph in its cell is k = min_i(cell_i / d_i). A glyph at a point has the glyph range for its room, the same for every glyph, so the points bound σ by the range over the widest glyph of the unit (KeyedDomains.unitWidth). The range is one internal constant (GLYPH_ROOM_PX), a placeholder until chart options can set the range of a non-spatial scale. When no room bounds σ, every glyph of the unit is 0 wide and is drawn 0 wide at any σ, so σ is 0. The registry builds each unit's bounds once, before the claim walk, from every glyph's room in the final tree (ScopeRegistry.fitGlyphs: the points' bound, and per axis the smallest cell_i / d_i), and each parent's sharing plan holds the cell it places each child in (SharingPlan.cells), so sizing N glyphs takes time linear in N.

A glyph claims pixels, not σ (GoFishNode.glyphClaim). A glyph in a cell claims nothing past the cell, since the cell's data already claims the cell. A glyph at a point claims its size at its unit's σ as the claim walk knows it. So the axes the glyphs are placed on fit their positions alone, and the glyphs' sizes do not shrink the plot.

Three shortcuts remain. The claim walk runs before any frame's σ is solved, so it cannot turn a cell into pixels: it sizes a glyph at a point by the points' bound alone (glyphSigma with no frame). When a cell of the same unit binds lower (a circle in a bin on x, unplaced on y, whose cells are narrower than the glyph range), layout draws it smaller than it claims on y: the claim is an upper bound, never an overflow. Writing the exact claim needs a claim on y that reads x's σ, which a claim, a function of its own axis's σ, cannot express. A cell is turned into pixels at the σ of the frame asking for the glyph's σ, so every frame that places one unit's glyphs must map its axis at one σ, which holds within one chart. And a size in the unit of one axis its parent places it on is a length on both axes of the mark, so circle({ r: "a" }) at x: "a", y: "b" is a length of x drawn at the x and y σs, which the aspect lock reconciles by the smaller.

Layout dispatch ​

After both walks, layout proceeds on a single principle: a continuous extent's scale factor is its claim's width.inverse(size), and a pinned one also builds a position scale from its type. Before the #586 collapse this was a three-way switch on the kind (SIZE inverted a claim value, POSITION divided by an interval width, DIFFERENCE divided by a width); a pinned or origin-less claim with no pixel overhead is just linear(dataWidth, 0), so width.inverse(size) = size / dataWidth reproduces both divisions, and the switch folds away:

gofish.tsx (root):
  if root[axis] is a free magnitude     → sigma = claim[axis].width.inverse(canvas)
  if root[axis] is pinned               → map = an AxisMap over its data interval
  pass one `AxisScale` = { sigma?, map? } downward per axis — a child reads
  `sigma` for size, `map` for data position (they're mutually exclusive at root)

layer.layout, on an axis where the layer is sized (`solveLayerScales`):
    claim = KeyedDomains.scope(claim[axis]): widen to the keyed domain, nice on demand
    if claim exists → claim.width.inverse(size[axis])
    else → undefined (no σ-dependent room, e.g. an ordinal of fixed boxes)

Every scope solves σ from its claim, and originPx from its baseline. A scope root, pinned or free, solves claim.width(σ) = box (ScopeRegistry. solveScope). Pixel overhead in the claim (a spread's spacing, a nest's padding) takes its pixels, and the data part gets the rest. When the axis has an origin, the scope then fixes originPx: every claim is measured from data 0, so data 0 sits claim.descent(σ) above the box's low edge, and originPx = claim.descent(σ). For a pinned claim with no overhead that is −σ·min, the domain filling the box as it always has. An origin-less scope solves σ and has no originPx. For this to hold, a pinned child's claim must reach its parent's union intact: unionChildExtents places a child at its own data coordinates, reaching its own ascent above data 0 and its own descent below it, the same layout the scope gives it. The position operator, which moves its content's data by a datum offset v, moves its claim with it (v·σ goes from the descent to the ascent). The Position: outset-left labels story is the case that needs it: its rows are bars 25 px apart, pinned by a baseline alignment, so the root's claim is 137σ + 100 and σ leaves exactly 100 px for the spacing.

Nicing widens a claim to hold the niced domain (niceScope, widenTo), and so does widening it to a keyed domain. How follows the axis. An absolute axis's claim is measured from data 0 and is the hull of what the content draws, so each side reaches the farther of the claim and the domain's niced end: pixels drawn past the data (a mark's size at its datum, a tick label past the last tick) take room only where the domain does not already reach past them. Widths (a space with no origin) widen to a keyed domain's width centered on the claim, so each side reaches at least σ·width/2 from the middle of its claim. Widening twice to one width changes nothing.

Leaf shapes never need to compute their own scale factors — they receive the per-axis AxisScale via the scales parameter and read its sigma in computeSize (and its map via pxOf for data position).

spread/stack no longer have their own layout — they elaborate to layer + align + distribute (spread.tsx), so the dispatch above lives entirely in layer.layout. solveLayerScales is the shared layout-time planner: on each axis where the layer is sized it runs the solve in the pseudocode above (returning the failed axes so layer can warn before falling back), and elsewhere it inherits. layer recombines the per-axis σ and map into one AxisScale per child at child.layout. The result is a fresh childScaleFactors array handed to descendants — no node ever mutates the inherited σ. A scale solves at a sized node, and the result flows to descendants only, never leaking to siblings.

This dispatch is the practical embodiment of the underlying-space-kind distinction. It also happens to make the rendering pipeline more readable: once you know the kind, you know which arithmetic applies.

The one solve site: the σ-scope registry ​

Every scale above resolves the same frame equation — content(σ) = allocated, inverted once by Pwl.solve — and one registry does the inversion. A ScopeRegistry (ast/solver/scopes.ts), created once per render on the RenderSession, is the one place σ / posScale is derived: fit(meta, node, space, claim, allocated) fits a sized node's claim to its slot (through solveScope(space, claim, allocated), which solves σ and originPx, with one fallback and one warning when no σ ≥ 0 fits). A grid's tracks are part of its layer's claim, so they need no solve of their own.

Only a sized node solves; everyone else inherits (#1114). A node is sized on an axis when its size there is given to it rather than computed from σ:

  • the render root, on an axis the render gives a w/h, sized by the canvas;
  • each coordinate transform, sized by its box;
  • a node with a literal w/h;
  • a node with a data-valued w/h, whose box its parent's σ sizes and whose content it maps into that box;
  • a node whose room its parent gives it (a region's cell, a treemap tile), with content that σ sizes, sized by that room;
  • a node with pinned data in a slot its parent nests it in (a spread, grid or treemap slot: a facet panel), sized by its slot;
  • a node handed no σ at all because nothing above it could solve one, sized by the box it is given.

A node its parent places at a datum (a scatter's glyph) is not sized. It is in its parent's set, so it inherits its parent's σ. It is handed no map, since the datum places it, so its frame is its own, with its 0 at the origin its parent places (frameOf in solver/scopes.ts).

solveLayerScales (constraints/proposalPlan.ts) is the layer's form of the rule. A spread of magnitudes along its direction is not sized: its parts are parts of one chain claim, and the sized node above it solves σ against the chain. Two sized nodes that map one keyed domain into unequal sizes are an over-constrained layout, handled like any other: each node's own size wins inside it.

A render with no w/h on an axis does not size its root there: the default canvas is a fallback, not a size. The root shrink-wraps its content and maps its keyed domain at the σ the domain is solved at below it. A node with a literal size solves its scope once, in the claim walk, through the registry (ScopeRegistry.solveFixed, called from layer.tsx), which records the σ under the keyed domain the node maps; its layout reuses that solution rather than solving again. The root reads the σ recorded for its own keyed domain (ScopeRegistry.keyedSigma). When the nodes agree, the root maps the domain at that σ, and its size on the axis is its claim at that σ, so the axis it draws lines up with the marks (the NestedCharts story: four mini charts 160 px tall, rendered with no size). When no node below solves the domain (the common chart(...).render(el, {})), or they solve it at different σs, the root solves at the default canvas, as below.

Only a node that maps a domain has its claim widened (mapsDomain in extent.ts). A claim with σ in it maps one. A claim that is only pixels (content made of boxes of a literal size) is left as it is by KeyedDomains.scope: each box already mapped the domain into its own size, and widening the claim would add data-scaled room nothing fills.

A one-value domain (isOneValue: a one-point chart, or every mark at one constant datum) also maps a domain, though its claim is only pixels: it has no width for σ to scale. It is widened to its keyed domain like any other, and if it is still one value, solveScope maps that value to the middle of the box, as d3 and Vega-Lite map a zero-width linear domain to the middle of the range: σ is 0 and the claim is centered in the box (#1107). Its axis has one tick, there. So every data value has a position scale, and a data value on an axis with none is an error (computeAesthetic). A domain that includes 0 and another value, such as a bar's, is never one value.

Behind GOFISH_DUMP_SCOPES the registry prints every scope it solved as a printable frame equation, one line per solve, with kind root, coord, sized or recenter:

[scope] root   key=root  axis=y [0,140]→[0,400] = 400  σ=2.857 map=yes
[scope] sized  key=layer axis=y 140σ = 150            σ=1.071 map=yes
[scope] coord  key=coord axis=x 16σ = 6.283           σ=0.393 map=no

After them, dumpKeyedDomains prints one line per keyed domain: its space root, axis, key and domain, marked axis when an axis is drawn over it.

Behind GOFISH_DUMP_SHARING, dumpSharing prints each layer's sharing sets instead, one line per layer, skipping chrome rings. A * marks a nested child. Both dumps live in debug/dump.ts. tests/scripts/dump-scopes.ts "<filter>" --sharing prints them for a story. The marginal histogram's layer prints as:

[sharing] layer (3) [position×3,align×2] x: own{scatter,topHist} detached {rightHist} | y: own{scatter,rightHist} detached {topHist}

The registry is the sole producer of every slope. A coord boundary hands down the one σ its scope solves, which its map shares, and the #582 equal measure (equating x and y when they share a declared unit) is a named equalizeMeasure operation on the registry, so the dump records the FINAL σ. Two axes share a unit when both their spaces are in one declared unit, or when each maps keyed domains of one unit and no other, and a mark ties that unit (KeyedDomains.tiedUnitOf). An axis that also maps another unit is not in one measure with the other axis: a marginal histogram's counts on the top (y) and the right (x) sit beside the scatter's beak lengths, so the two count scales stay apart. An aspect-locked mark whose size is data, such as a circle, ties its unit (#1087): it draws one value as a length on both axes, so its unit is one length on x and y even when it is unknown. The type walk records the tie on the unit's class in the union-find (tieUnit), so it holds for every occurrence the walk unifies with it. So a row of circle({ h: "value" }) in a spread fits both axes at σ = min(H / max v, W / Σv), and the value axis reads that σ. The aspect lock gives the other axis the same data length (elaborateOwnDims's dataSize), so both axes claim it. The render root and a chart with a literal size on both axes both go through it. The chart solves its two scopes in the claim walk (solveFixed) and equalizes them there (equalizeFixed) before either claim is read. Both take the smaller σ, and on the other axis the scope root keeps its box: its claim takes the leftover pixels after the content in screen terms, so the content sits at the box's top-left and the root still claims its size. The content sits past the leftover before it by its seat (seatInScope): its data 0 where the scope has one, else its box, which starts startPx from the scope's start edge. This placement is provisional. Only an axis with a data width binds: a one-value axis (a one-point chart) has no width for σ to scale, so it takes the other axis's σ and keeps its value at the middle of its box.

Nicing is a keyed-domain operation, applied on demand ​

Domain rounding — d3.nice stretching [0, 44] to [0, 45] so ticks land on round numbers — is applied once, at a sized node's solve, to its keyed domain, so every consumer of that domain (content sizes, the position map, axis ticks) reads the same rounded domain (#659). niceContinuous (underlyingSpace.ts) is the one nicing function, and niceScope (extent.ts) widens the claim to match. It nices exactly the spaces that render an axis over their interval (axisOver), or will once placed: a pinned domain's two ends, a free one's two ends about its 0. A space with no origin draws no axis, so it is not niced: its widths fill the scope that maps them. A coord scope never nices (its domains map into a fixed coordinate range).

A domain nices to the ticks of the axis drawn over it (AxisTicks): a tick count (10) on a numeric axis, rounded with d3.nice; on a time space (zone set, see the column types below) the calendar partition of the axis's inner row, rounded outward to its cells (niceToCells in calendar.ts), so both ends of the axis are ticks. Both read the domain and the axis options only, never pixels.

And it is demand-driven: a keyed domain is niced iff some node draws a continuous axis over it. With no axis there is no tick grid to round for, so axis-less content stays at the honest raw scale. resolveAxes leaves a persistent axisDemand stamp on every axis-owning node, and the keyed domain table records each stamp against the domain of the stamping node's set (KeyedDomains.ticksOf). A time axis's stamp gains its rows at elaboration (recordDemand). Tick elaboration nices the same keyed domain through the same KeyedDomains.scope, so elaboration and the solve cannot disagree.

Scales generalize flex factors ​

A size scale whose range resolves to the parent's extent is doing exactly what CSS flexbox does with flex factors — and GoFish's version is strictly more general.

In flexbox, flex: 1 and flex: 2 on two children split the container's space in a 1:2 ratio. The numbers are weights; the container's extent is the range; the layout normalizes the weights to fill it. That is a scale, narrowly construed: a domain (the sibling weights) mapped onto a range (the container box) so the pieces sum to the whole.

This is precisely SIZE resolution. A row of datum(n)-sized children under a shared size scale composes into a claim value whose inverse against the available extent solves for the scale factor that makes the siblings fill it (see Layout dispatch). claim.width.inverse(size) is the normalization step; the datum(n) weights are the flex factors. The cut operator's relative form, cut(source, { size: [datum(1), datum(2)] }), slices a region in a 1:2 ratio by normalizing those weights over the source's extent — flexbox, expressed as data.

So flex factors are the degenerate case of a size scale: weights that happen to be literal layout constants rather than data. GoFish generalizes them along three axes the CSS model can't reach:

  • The weights can be data. datum(n) is a literal weight, but the same machinery takes a field name (rect({ h: "count" })) so the proportions come from the rows, not the spec.
  • The scale can be shared. A flex factor is local to one container; a GoFish size scale can be shared across sibling charts or facets, so the same weight means the same pixels everywhere it appears — proportions that compose across the page, not just within one box.
  • Absolute sizing coexists. Flexbox bolts flex-basis / fixed widths alongside the factors as a separate mechanism. GoFish folds both into one field/datum/literal trichotomy (issue #266): a literal 10 is absolute pixels, datum(n) is a relative weight, a field name is a per-row weight. Mixing the two in one cut is not a conflict but exactly flex resolution: the absolutes are fixed-basis claims, and the size scale's range is the parent extent minus those fixed claims, so the datum(n) weights normalize over the remainder — cut(source, { size: [100, datum(1), datum(2)] }) fixes a 100px cap and splits what's left 1:2. The mixed case makes the identification sharper, not weaker: "fixed widths next to flex items" is just a size scale whose range has been shortened by the fixed children.

The payoff is conceptual economy: "fill the container proportionally" is not a bespoke layout mode, it is what a size scale already does once its range is the parent's extent.

Sized nodes and measure-keyed domains ​

A size never splits a domain (#1114, the design note Measure-keyed domains). Which children share an axis is a fact about a node's composition, its sharing sets (planSharing in constraints/compose.ts, one rule per node type, GoFishNode.sharing()): children of a layer share both axes, a literal position detaches a child on its axis, an align joins the children it names, a stack shares its parts, and a spread or a grid gives each part a slot of its own. A layer's type is the union of its own set only; a detached child does not flow into it. Units meet through the one join, joinUnits, with shared true inside a set and false between a spread's parts.

After the type walk, one pass builds the keyed domain table (KeyedDomains in keyedDomains.ts), once per render, before chrome and labels are elaborated: per space root (the render root, each coordinate transform), per axis and per unit after unification, the union of the intervals at the top of every sharing set with that unit. The top of a set is where it stops: a child its parent detaches or nests, or the space root. A child nested while it stays in its parent's set (placed at a datum, or the content of a data-valued box) measures its own extent from the datum or the box, so its domains are keyed in a frame of its own and never widen its parent's, even in the same unit.

Every reader of a plan asks the same question of it: what is this child's place in its parent on this axis? childRole (constraints/compose.ts, next to SharingPlan) is the one answer, with four cases. A shared child is in the parent's own set and reads its values in the parent's frame. A nested child is in the own set too, but its extent is in a frame of its own: it is placed at a datum, or it is the content of a data-valued box. A slot child has a set and a frame of its own (a spread slot, a grid cell). A detached child has a set of its own and is placed elsewhere. The table build reads it, and so does GoFishNode.isScope, which a layer's σ solve asks (solveLayerScales) only for content handed a σ and no map. Values with no unit (literals) are keyed by their set. So two facet panels that plot one column share one domain, and a count histogram placed beside a scatter of millimeters keeps its own. Chrome never decides a domain, it only reads one: a ring or a label wrapper added later reads the seat of the content it wraps. Chrome does take room, as pixels: every chrome shape claims its size, and a ring's claim is the hull of what it wraps and of its shapes where its constraints place them (placeByClaims). A layer that wears chrome hands its content what its chrome leaves of its room (never less than 0), and a node with a size of its own, a chart or a plain layer, takes that size as its plot and adds what its content's dressing reaches past it (#1032; see Chrome around a chart). A child placed beside a node inside another child (a label on its mark's ref) takes room where the claim walk knows that node lands (planPlacement), a band of a category axis included (a share is a claim), and is ink where it does not (inside a coordinate space, or beside a band in a scope that mixes data and bands): left out of its layer's claim and box. A pinned child a layer pins at a literal pixel (a ring's content, seated at the ring's origin, wrapRing) shares the layer's frame from that pixel (childPosScalesFor): its map's originPx is the frame's less the pin. The axes drawn over each domain are recorded once resolveAxes has assigned them (refreshDemand, which layout() calls once, after the axes are stamped: nothing reads the demand before then). A time axis adds its rows to its stamp when it is elaborated, since its levels depend on the axes below it, and records the new stamp then (recordDemand), before any solve reads it. A space root's domain and demand maps are made on the first write to them, and a read of a root with none (one with no axis) makes none.

Every sized node maps its keyed domain into its own size: before its solve, its claim is widened to the keyed domain (widenScope in extent.ts, the same arithmetic as nicing: only the data part widens, so pixel overhead keeps its pixels), then niced on demand, then solved. The widen-then-nice is one method, KeyedDomains.scope, read by every sized layer's solve, by the render root, and by the axis drawn over the domain.

A literal w/h carries no data, so the node reports its content's type upward unchanged, and its keyed domain is shared as the sharing sets say. Its claim, though, is its own pixels: the box solves its own σ, so its content's σ claim is not room its parent can scale. The node claims the content's claim at the σ it solves, which sums to the size (fixedClaim in layer.tsx). Where its scope has a data 0, the claim keeps the content's split about it, since the node reports its content's type upward and a parent reads that type's claim from its data 0. Where the scope has none, the node places its content's box at its start edge (#1032), so the claim runs from there. It solves that σ once, through the registry (solveFixed), and its layout reuses the solution. A claim that is only pixels over a type wider than one value maps no domain (mapsDomain in extent.ts): it needs no canvas at the root, and a sized node has nothing to solve from it. A data-valued w/h (a field name, a field(...) expression, a per-entry array) is a value in its parent's unit, so the node reports a free magnitude (magnitude(size)), a leaf in its parent's set like a rect with w: "count", and its content is nested in the box: the content is the top of a set of its own, and the node maps the content's keyed domain into the box its parent's σ sized. This is the one inherent special case of the sharing table, and the note justifies it: a data-valued size already has a type on its axis, so its content is a second coordinate inside the box.

Space-filling spines: normalize nests each part ​

The space-filling spine — the conditional axis of a mosaic / marimekko — is an instance of the data-valued size above, with no layout-side special case. Its segments fill the extent in proportion to their value: stack({ by, dir, size: field("count").normalize() }).

.normalize() is a data transform, the built-in map x / Σxs, evaluated once, up front, by applyChannels (marks/createOperator.ts) via splitWindowMaps/applyWindowMaps in fieldExpr.ts. On an operator's per-entry size channel, the maps at the end of an expression, after its named fold or with no fold, run over the entries' values (the window) instead of a group's rows (hasWindowMaps); normalize is one such map, and a user's map is another. Each entry's value is the expression before them: field("n").count().normalize() is each entry's share of the counts. For each of the operator's own split entries it computes the entry's share of their sum, v_e / Σv_e, tagged with a share unit ("<base> share by <by>", via shareQuantity) so a share axis can never silently union with the base quantity's own axis.

spread/stack's size option then wraps each child in its own sized layer({ [w|h]: size[i] }, [child]), before the usual align/distribute elaboration (spread.tsx). The wrapper copies the wrapped child's key/datum/__splitBy identity onto itself so ordinal-axis labeling and resolve(..., { from }) still see the un-wrapped child's identity.

This is the whole trick behind nested mosaics. Each level plays two roles on its two axes: on its stacking axis each entry's wrapper is a share magnitude whose content is nested in it, while on its cross axis the level reports its content's type up. The class, sex and survived shares are three declared units, so each level keeps its own domain, class → sex → survived alternates y → x → y, and every level reads count raw.

Measures: units are types ​

The sharing sets above decide which children share an axis. But the marginal histogram has a subtler need at the shared boundary. When the top count histogram and the center scatter overlay on x, the union should succeed (both are beak lengths along x) and the count axis, folded into a position interval, should not pollute that millimeter domain. The shared union has to tell "same units, merge" from "foreign units, refuse" without a human reading the field names.

That distinction is a space's unit record (underlyingSpace.ts). It holds three things:

ts
// underlyingSpace.ts
type UnitRecord = {
  unit?: UnitVar; // a declared unit or an unknown, a term of the render's union-find
  titles: string[]; // the quantities on the axis: they title it
  summands?: Quantity[]; // the quantities a fold that adds the space sums
};
export type CONTINUOUS_TYPE = { kind: "continuous"; dataInterval: Interval; origin: Origin; measure?: UnitRecord; ... };

The unit decides which axes may share a scale. The titles name the axis. The two are kept apart, following the terms of metrology: a quantity is what is measured ("Production Budget"), and a unit is the scale it is measured in ("USD"). The titles are quantities, and a declared unit only adds its symbol after them, Quantity (unit) (see Titles below).

Gradual unit typing. Units are checked the way F# infers units of measure, but gradually (unannotated code is allowed, in the style of gradual typing): a column whose unit nobody declared has an unknown unit, a unit variable, which unifies with anything. A declared unit is concrete. Two different concrete units on one axis are a type error. The concrete units are:

  • a column's unit, a Unit(u) definition or the name u alone (HasUnit, see column types);
  • "instant", the unit Unit.time({ zone }) declares for every time column, so a start and an end time share an axis. The zone is a parameter of the unit (HasUnit.zone), not part of its name, so it does not split the unit: two instants in different zones unify as one unit, and the one HasUnit their class is bound to (meetUnits in unify) can read only one calendar, so two zones on one shared axis throw;
  • "count", for .count() and .distinct();
  • "duration" (Unit.duration), for a difference of two instants, such as a size read from a time column. A unit names its own difference unit (HasUnit.difference): the instant names the duration, and differenceUnits, which magnitude applies, reads that property and drops the zone. A unit that names none is its own difference, so USD − USD is USD and °C − °C is °C. Only the engine's units name one today; it is the mechanism a °C unit with a Δ°C difference will use (#1142);
  • "<base> share by <by>", for .normalize() (shareQuantity), so a share axis never silently unions with its base's own axis.

Each declared unit is a HasUnit (the column type, schema.ts): a unit name, which says which units are the same, an optional symbol, which an axis title shows, and the unit's traits, what its amounts can do, when they are known. A user's unit u has the symbol u. A Unit(u) definition writes its traits; a unit declared by its name alone writes none, so its traits are unknown. The engine's own units (INSTANT, DURATION, COUNT in measure.ts, a share) have no symbol, since a count or a share is a plain number and a time axis's ticks already read as dates, and their traits are known: a duration, a count and a share add up, and an instant does not.

Which amounts add up. CanSum (#1197) is a trait of the unit, not of a column: Unit(name, { traits: [Trait.summable()] }) defines it, and it rides on the unit (HasUnit.traits) into the Quantity read from a column. A unit is its name, so every occurrence of one name is one unit, and where two occurrences meet their traits meet by one rule, meetUnitTraits (measure.ts): unknown traits and known ones are the known ones, and two known definitions that disagree throw an error naming both columns. They meet in two places. When a chart's schema is applied, its columns of one unit name meet (meetChartUnits, schema.ts), so a column declared "USD" beside Unit("USD", { traits: [Trait.summable()] }) adds up. In the type walk, every declared unit read (unitOf) meets the figure's other occurrences of its name in the walk's Units, wherever they are, so two charts that define one unit differently throw. addsUp (measure.ts) is the rule for one quantity: it adds up when its unit has CanSum, when it has no declared unit, or when its unit's traits are unknown. Every place that adds values while a chart is built sums them with sumIn (fieldExpr.ts), which checks it with checkSummable: a size channel's sum over its rows (inferNumeric; when an aggregate op already folded the rows, the channel takes the op's value and sums nothing), .sum() in any channel or label (every caller of evalFieldValues passes the column's quantity), the total of .normalize(), and the total of the normalize(rows, field) data helper. A treemap's layout adds its tiles' weights on every pass, so the treemap checks its size channel with checkSummable once, where it is built. A cut's sizes are slices of a whole it adds up, so its per-row size channel (inferEntrySize) checks its column with checkSummable too. These sums read the unit as their chart knows it. A stack adds spaces, not values, in the type walk, so a space's UnitRecord carries summands, the quantities of its values in a declared unit (quantityUnits; a shared joinUnits unions them, each once), and distributeSpaceFold sums each free part's own list with Units.sum, which reads the unit's traits as the figure knows them. While they are unknown the sum waits, and it is checked when an occurrence that knows them is met, so a stack of "USD" in one chart throws beside a Unit("USD") in another, whichever the walk meets first. The stack reads the parts, not the unit class they joined, so a start point beside a stacked width is checked only for the width; a pinned part is not summed, since the stack adds only its width. Summing a declared unit without CanSum throws an error that names the column and says to declare Unit(name, { traits: [Trait.summable()] }); for a unit whose difference unit adds up (a time), it says to subtract a reference first (date - start gives a duration, which adds up). That message reads the unit's difference, not a calendar. An unknown unit passes, as everywhere in gradual typing. The check reads the column's type, not the rows, so a group of one row is checked like any other: whether a chart type-checks never depends on how many rows a group holds. A bar of one date or one temperature is the missing zero (HasZero, #1051), not this check.

One gap remains. A sum taken while a chart is built (a size channel, .sum(), a treemap, a cut, .normalize()) runs before the type walk, so it cannot see a definition of its unit in another chart: a bar chart of "USD" beside another chart's Unit("USD") sums its bars. Only the stack's sum, which the walk takes, sees the whole figure. Closing it needs the charts to be built inside the figure's walk scope (TODO in meetChartUnits).

A size is never read on a calendar: magnitude takes its value's differenceUnits, so a size read from a time column (h: field("day").mean()) is a duration, not a bar on a time axis from 1970, and its summands become durations, which add up. A sum of a time column as a size still throws first, at the sum.

A quantity whose unit is declared is that unit, a concrete term, and nothing more: two charts that each declare their own "value" column, one in USD and one in EUR, share nothing, and a column "count" declared in people is not the "count" of .count(). Only an unknown is a variable. A unit variable is named by its quantity: the column's declared quantity (HasQuantity, a column record's name), or, for a column a transform derived from another, the source column's quantity (bin(field)'s start/end/size are amounts of field), or else the column's name. The column name is a weak default: it makes no claim, so two columns with different names are different quantities until a declaration or a meeting says otherwise. The same name is the same variable across the whole figure. A variable binds to another variable or to a concrete unit only where a join meets them (joinUnits, below), and the binding holds for the whole render: a column bound to USD on one axis is USD everywhere, so meeting "count" on another axis is a clash. That is plain unification with a chart-wide substitution.

The union-find. Units (measure.ts) is the union-find over the render's unknowns, keyed by quantity name. unitOf(quantity) reads a quantity's unit: a declared unit is a fresh concrete term that needs no table, and an unknown is the variable of its name in the installed table. There is one table per type walk, owned by the walk's root: the render session's (RenderSession.units) when there is one, else one the root node of the first walk over the tree creates and keeps (GoFishNode.walkUnits). So it is figure-wide, and union-find gives the same classes in any order of meetings. The outermost call of the type walk (GoFishNode.resolveUnderlyingSpace) installs it with withUnits, and so do the outermost calls of the embedding pass (resolveEmbedding) and the layout pass (GoFishNode.layout, whose layers re-join their position measures in collectPositionDomains). So a datum value that becomes a space anywhere (valueUnits, used by magnitude, a point, a rect's ends, a position constraint, a position offset) takes its variable from the one table, and layout sees every binding the type walk made. A standalone node.resolveUnderlyingSpace() or node.layout(...) needs no session. A read outside all three passes is an engine bug, and currentUnits throws an internal error. A space holds its variable (a UnitVar node), so reading its unit later needs no walk: spaceUnit(space) returns the record with the unit replaced by its representative, a declared unit or the unknown its class stands for. It is THE accessor for "which domain is this": the titles (axis elaboration) read through it. Two unit variables are compared with sameUnitVar (one class, or two classes bound to one declared unit), which the #582 equal-measure step and the embedding gate use. Read units after the walk, when every binding is made.

Joining. One function, joinUnits(a, b, shared, site), joins the records that meet on one axis, in every composition: overlays and alignments (alignment.ts), spreads and stacks (distributeSpaceFold), coords, a layer's datum domain, a rect's two ends, a position offset and its content. An absent record makes no claim and yields the other side. shared says whether the two sides share the axis, and the result follows the join table of the measure-keyed domains design (#1114):

MeetingSharedNot shared
declared A, declared Aone unit Aone unit A
declared A, declared Ba MeasureClash (until #528)two units, no error
declared A, unknown xx is bound to A, for the whole renderforget: x stays unknown
unknown x, unknown xone unit (the same column)one unit (the same column)
unknown x, unknown yx and y unifyforget: two units

"Forget" records nothing and raises nothing, and the result keeps a's record. A shared join unions the titles in order, and its calendars must agree (two time zones on one shared axis throw, where unify meets the two instants). Two errors remain, both MeasureClash: two declared units on one shared axis (a stack's parts in two units among them), and one unknown bound to two declared units (a column that meets "count" on one shared axis and "mm" on another).

The sharing plan (planSharing, compose.ts) decides which children share an axis, and only the children it keeps in the layer's own set meet in the layer's union. A spread's parts each sit in a slot of their own, so the spread folds their units with shared: false; every other composition passes true. The decision is by the units alone, never by the origin state, so overlaying a count axis onto a column declared in millimeters fails loudly instead of corrupting the domain.

The position operator's offset meets its content on one shared axis too, but as a point plus a difference, not two points. When the content is pinned, it is the point and the offset is the difference that moves it. Otherwise the content is a difference (a magnitude, a width) and the offset is the point it hangs from. The difference must be in the point's difference units (differenceUnits), so the join is between differenceUnits(point) and the difference: a USD position moves by USD (whether or not its column is summable), a °C position by °C, and a time position by a duration, or by a plain number, which is bound to one. Two instants clash ("instant" against "duration"), since a time does not move a time. The result takes the point's unit and zone, titled by both sides. An ordinal axis has titles and no unit, so it takes no part in the join: a datum position beside a category spread on the same axis, or a spread whose targets mix a category spread with bars, unifies only the continuous units.

Why one policy: the units of an axis decide how many σ-scopes it needs, which is part of setting up the layout problem, not of solving it. One axis holds one unit and one σ. Under unification that is automatic: every quantity on an axis is in one class, so an axis has one unit unless two concrete units meet, which is the clash. An axis that genuinely needs two (a dual-axis chart) is multi-scale (#525), not a unit to forget.

What the gradual rule gives up: a column with no declared unit unifies with anything, so a count and a bare length on one axis, or a price and a volume, render on one scale with no message. The axis title ("count, Flipper Length") shows the mix-up. Declaring the units restores the check.

Where quantities come from. resolveColumn (channels.ts) reads a channel's quantity off its column's type (columnQuantity, measure.ts): named by HasQuantity or else the column, in the unit HasUnit (a time column's is "instant"), or else unknown. A function accessor or a literal has no column, so no quantity: its value makes no claim. inferSize/inferPos tag the value(...) they emit with it, and a pipeline that determines its own quantity (.count()) overrides it; .sum() and .mean() keep the column's. The channel aggregators are a sum for size and a mean for position (sumIn and meanOf in fieldExpr.ts), and both skip a missing value (null or undefined, isMissing, the rule dropNulls uses). The mean of no values has no value (see Cells); so has the sum of values that are all missing, as in SQL, while the sum of no rows is 0. A position with no value leaves a scatter's child unplaced and undrawn, and any data channel of a mark with no value leaves the mark undrawn, in its place (The Mark Factory). A computed column a derive makes is a fresh variable named by its column, and derive(fn, { schema }) can declare its unit. The ends of a partition's cells are read from the binned column the same way (resolveColumn on field(x).bin(p)'s x), so a histogram's x axis is x's, titled and unified as x is (see Cells).

Units must reach mark channels, not only operator channels. An operator resolves each channel's quantity once from its whole input array (which carries the column types), but a mark channel runs per split leaf — and a leaf is a fresh sub-array (groupBy/filter/slice) that doesn't inherit them. So the operator re-tags each leaf with its parent's column types at the split site (copyColumnTypes, schema.ts, applied in createOperator), letting a mark bound to a column the chart types read the column's quantity off its own data instead of falling back to the literal field name. The column types can't ride the rows across the Python derive-RPC bridge; a derive's schema puts them back on the returned rows. Every leaf is an array: an operator with no by splits by row identity (chunk(1)), so each leaf is [row] and is tagged like any other.

This same size-vs-position comparison drives embedding (baseEmbedded, data.ts): inside a coordinate space, a dim's size becomes a swept coord extent only when it is in the same unit as the dim's own position — a size in a foreign unit (a bubble's area) stays a flat point. It reads the units through the render's union-find (sameValueUnit, which compares the variables with sameUnitVar), after the walk: two unknowns are the same unit only when they are one column or met on a shared axis. A mark its parent places is compared the same way: a glyph (isGlyph, see Glyph sizes) stays a flat point. See the embedding-resolution pass under layout passes.

Constraint-domain measures. A position constraint's datum coordinate carries the same quantity, and collectPositionDomains folds the measures per axis with joinUnits — so a layer's own positioning constraints in clashing units (an interval coordinate with one endpoint in mm and the other in inch) throw at the source. The layer then merges this constraint-domain measure with its children's, like any other composition. A child that a datum position places (the sharing plan's datumPlaced, compose.ts) is left out of that union altogether: it sits where its datum maps, so its own extent and measure are in its own frame (a scatter's circle sized in its own units, a pie glyph in its angle), not in the axis's data. This restores the unit tag the scatter operator's reduction onto constraints had dropped.

Propagation through the baseline → anchored conversion. A histogram's count axis is all baseline magnitudes (origin 0) at the children, and resolveAlignmentSpace's start/end/baseline path folds them into pinned [0, max]. That conversion carries the merged child measure forward — it is load-bearing, because it is exactly how the count axis keeps its "count" unit so a later overlay union can recognize a declared foreign unit and refuse.

The error and its remedies. A clash is a MeasureClash, and it reads, for a grouped bar chart over a column declared in dollars and one in euros:

The y axis combines two different units, "USD" ("Worldwide Gross") and "EUR" ("Revenue") (where marks are lined up). One axis can show only one unit. If they are the same kind of quantity, declare the same unit for their columns in the chart's schema, e.g. schema: { "Worldwide Gross": "EUR" }. If they are different kinds of quantity, each needs its own axis: give the inner chart its own w and h so it scales on its own.

A schema is keyed by column, so the example names a column of one side, given the other side's unit, even when the column declares a quantity of another name (each class of the union-find keeps its columns beside its quantity names). A side read from no column, a count or a share, has no unit a schema can declare, so when neither side has a column the message leaves the example out.

Each side lists the quantities bound to its unit, so a clash that a binding made elsewhere caused (a variable bound to USD on one axis, meeting "count" on another) shows where the unit came from. Each fold passes its axis index and a plain phrase for the composition (a MeasureSite). The fold does not know what the axis is called, so the node whose type hook raised the clash names it on the way out (GoFishNode.axisName): x or y, or the name the innermost enclosing coordinate space gives it (r, theta, lon, lat). It reads the same axis scope the name pass uses (axisScopeFor), so a space that declares no names leaves x and y even inside a polar one. A unit's name is spelled the same in Python, so one message serves both.

The two remedies are the two escape hatches this essay already describes: declare that the units are the same, or place the foreign region apart (a literal position detaches it, see sized nodes above) so it never reaches the shared union at all.

Titles. An axis is titled by spaceTitle, the one place the title string is built, in the SI style Quantity (unit): the space's titles (its quantities), joined with ", " in the order the merge met them, then the symbol of the axis's unit in parentheses when that unit is declared and has a symbol. A histogram's edges title as their source column, an axis over lo and hi reads "lo, hi", and the four summary columns of a box plot declared { name: "Pay", unit: Unit("USD") } read "Pay (USD)". A count, a share, a time, and an unknown unit add nothing. The rule never reads the names, so a column named "Flipper Length (mm)" declared in "mm" titles "Flipper Length (mm) (mm)". The clean title comes from declaring the quantity ({ name: "Flipper Length", unit: Unit("mm") }) or from the axes option's title, which overrides all of this.

Stage 2. This is Stage 1: one unit per axis, unified or refused. The sequel is a unit-keyed family of underlying spaces per axis — true multi-scale, where a single axis can host several units at once (dual axes), keyed by spaceUnit (cf. issues #452, #386).

Column types: the chart schema ​

chart(data, { schema }) (schema.ts, #984) declares, per column, the traits the column's values have (HasLevels, HasUnit, ...). A column's entry is a unit definition, a unit's name, or a column record { name, unit }:

ts
const Likert = Unit({
  domain: Domain.discrete(LEVELS),
  traits: [Trait.diverging()],
});
chart(survey, { schema: { response: Likert } });

A unit definition (Unit(name?, { domain?, traits? }), #1197) separates which values exist, its domain, from everything else about them, its traits (an order, a midpoint, summing), as Rust separates a type from the traits it implements. Domain and Trait are strategy families (families/domain.ts, families/trait.ts), but they are not in STRATEGIES: a domain and the traits are read when the Unit is made (unitTypeOf) and never reach the wire, which carries only the traits they expand into (UnitDefinition.type, a UnitType):

DefinitionTraits
a name uHasUnit { unit: u, symbol: u, traits }
Domain.discrete(levels)HasLevels { levels }
Trait.ordered()HasOrder {}
Trait.diverging(midpoint?)HasOrder {}, HasMidpoint { at }
Trait.summable()CanSum in HasUnit.traits

Trait.diverging implies Trait.ordered, as a Swift protocol or a Lean class implies its parents: a midpoint is a point along an order, so it writes HasOrder too, and listing both is the same unit.

unitTypeOf checks the definition: a unit needs a name or a domain; a domain is a Domain value (a bare list, an interval or any kind but discrete is an error: an interval domain, Domain.continuous, is a follow-up); a domain lists at least one level and no level twice (Domain.discrete, which unitTypeOf calls again on a domain written as a record); a trait appears once; Trait.ordered and Trait.diverging need a domain of levels (an order over the reals waits for Domain.continuous, so no domain is "not supported yet"); Trait.summable needs a name, since adding up is a trait of a unit and a unit is known by its name. A unit with no name writes no HasUnit, so its columns are typed one by one, as before the unit existed. Two units of one name with different domains are not compared yet.

A column type is a record keyed by trait name (ColumnType), and the engine reads only the traits, never the definition. Seven column traits exist, and a unit has one trait of its own (CanSum):

  • HasLevels ({ levels }, from a domain): the values are the levels of a fixed list. splitEntries groups a by over the column in that order instead of first appearance, so every operator that splits (spread, stack, group, scatter, ...) follows it, and field(...).sort(...) and .reverse() still reorder from there. A color legend lists its values in the same order. A value outside the levels is a loud error naming the column and the stray values (strayLevelsError), checked where the levels are used (orderByLevels, at a split or a color scale), not when the chart types its data, so a filter in the flow can drop the stray rows first.
  • HasOrder ({}, from Trait.ordered, or implied by Trait.diverging): the levels are ordered. It is a marker over HasLevels, which columnTypeOf requires. A split over the column says its groups are ordered (SplitGroups.hasOrder), so an ordinal axis starts an outer level's labels at their runs; over levels without it, which have no order, it centers them.
  • HasMidpoint ({ at }, from Trait.diverging(midpoint)): the order has a midpoint, the point { at } along it in edge coordinates. Level i spans [i, i + 1], so 0 is the first level's leading edge, n the last level's trailing edge, and 2.25 a quarter of the way into the third level (the cutoff of ggstats' gglikert). Unit writes the default n / 2 into the record, so the wire form always carries a number: the middle of the middle level when the count is odd, the boundary between the two middle levels when it is even. It requires HasOrder: Trait.diverging writes both, and columnTypeOf rejects a wire record that has a midpoint without an order. A midpoint that is not a finite number in [0, n] is an error from checkMidpointOnOrder, which Unit calls at once and columnTypeOf calls on a wire record; Python's Unit raises the same messages, with code spelled in Python. A stack over the column takes the midpoint as its baseline (stackBaseline, then the stack fold and the free-origin seat above): inside a present level, that fraction of its part; on a boundary, or inside a level the row lacks, the tail of the first part past it (or the last part's head). A stack laid out against the order measures the fraction from the other end, so the midpoint at sits at n − at along the layout. The midpoint comes from the order, not from the parts present: a row with no responses for some level keeps the same midpoint. So does the side of it each level lies on: the split applies its field(...).sort() and .reverse() to every level of the order (orderEntries), and stackBaseline reads the stack's direction off that, so a row with one part puts it where a full row does. A split order that is neither the order nor its reverse is an error.
  • A time (Unit.time({ zone }), #1057) is a HasUnit with a zone: the values are instants, read on the calendar of the IANA zone zone (UTC by default). There is no separate calendar trait: the zone is a parameter of the unit, and nothing needs a calendar without a unit. It is the one unit that changes the data: applySchema (now async, because it loads Temporal; see calendar.ts) copies the rows and turns each value into epoch milliseconds (toEpochMs: an ISO date is the start of that day in the zone, a date-time without an offset is wall-clock time in the zone). It is also the one unit that is inferred, and only locally: a column whose first non-null value is a JS Date is a UTC time. Strings and numbers never are. A pandas, polars or pyarrow datetime column crosses from Python as an Arrow timestamp or date column, unchanged, and the widget's decode (widget-src/arrowDecode.ts) attaches Unit.time({ zone }) to the rows, as column types. A tz-aware timestamp is an instant: it decodes to epoch milliseconds, typed in its own zone. A naive timestamp or a date is a wall-clock value: it decodes to an ISO string without an offset, typed UTC, so applySchema reads it in the zone of a declared schema entry (which wins over the decoded type) exactly as it reads the same string from JS data, or in UTC without one. The decode only attaches types: whoever reads the rows converts them first with its own schema (a chart tier is chart data, a lambda accessor's values go through applySchema in serialize/fromJSON.ts, and a derive types its result with its own schema, so each holds epoch milliseconds). No schema names a value inside a list or a struct, so a time there decodes to epoch milliseconds (a naive one read in UTC), and a list of structs, a list of rows, carries its own column types. An instant has no zero. A position read from the column carries the class on its DatumValueImpl (fieldType, which inferNumeric now sets for any typed column, with createOperator passing the column it resolved from the whole input, quantity and type together, resolveColumn), and its quantity carries the unit, zone included, so the point space it builds has the zone in the unit of its measure (read with spaceZone). The one merge (joinUnits) keeps it through every fold that builds a continuous space from parts (the overlay fold, a layer's datum-position domain in compose.ts, a rect's two ends, the position operator's offset), and two parts in different zones are an error (unify, which meets the two units). Every time column is in the unit "instant", whatever its zone, so two time columns share an axis. A time space is niced to the cells of its axis's inner row (niceToCells: the smallest run of whole cells that covers the domain, so a domain of one instant, which tickPartition ticks at days, spans the day that holds it), and its axis is a time axis (Axes). An empty domain (a column of nulls) or a non-finite one is not niced at all, for numbers and times alike. Calendar cells (CalendarPartition) live in calendar.ts, which runs all calendar math on Temporal, native or the polyfill it loads when the runtime has none. The values a user writes are the Calendar strategy family (families/calendar.ts): each kind is a CalendarPartition used bare or called with its options (Calendar.month({ every: 3 }), #1133).
  • HasUnit ({ unit, symbol?, traits?, zone?, difference? }, #994, #955, #1197): the values are amounts in the declared unit unit. A column's entry declares it with a Unit(u) definition, which writes the unit's traits ({ CanSum: {} } with Trait.summable(), else {}), or with the name u alone, which writes no traits: what the unit can do is unknown. Either writes the symbol u. The engine's units are definitions too, with no symbol: Unit.time({ zone }) (the instant, with its zone and its difference, a duration) and Unit.duration. A column without it has an unknown unit, a unit variable (see measures). A column's levels must fit its other traits, so a text-level column takes no unit (checkLevelsFit in schema.ts, which only a wire record can break).
  • CanSum ({}, #1197) is not a column trait: it is a trait of the unit, in HasUnit.traits. See which units add up.
  • HasQuantity ({ name }, #955): the values are amounts of the quantity name (a column record's name, { name, unit }), when it is not the column's own name. It titles the axis and names the unit variable. A transform writes it for the columns it makes (bin(field)'s start/end/size are amounts of field's quantity, in field's declared unit if it has one; its count is in "count").
  • HasDomain ({ lo, hi, sorted }, #1059): the interval the column's values span, from the least to the greatest, in the data it was typed with. Nothing declares it: applySchema computes it for every column whose values are all finite numbers (missing values aside; a time's values are epoch milliseconds by then), after the other traits. It is what a binned key's cells cover (see Cells). sorted() gives the same values in order, for the cells of Bin.quantiles: it reads them off the typed rows on its first call only and keeps them, so a column no quantile reads is never copied.
  • HasInteger ({}): the values are integers. JS has one number type, so no JS column has it and no builder writes it: the Python hosts' Arrow decode attaches it to a column that arrived as integers, and their encode reads it to send the column back to Python as integers (see the codec). Nothing in the engine reads it. It moves with the rest of the column's type, and a derive keeps it only while the column still holds integers.

The types ride the chart's data array under the COLUMN_TYPES symbol: ChartBuilder copies the array and tags it (applySchema, which keeps the types the array already carries, such as a bin's units), createOperator copies the tag onto each split leaf, and each data-transform operator (mapOperator in marks/chart.ts) types its result by its own typing rule. A derive (typeLikeChartData, also resolve and join) types its result with applySchema too, passing the input's types as applySchema's inherited types, whether or not the function returned its input array. It keeps only those that still fit the result's values: each trait has one predicate for the values it accepts as they stand (ACCEPTS in schema.ts: a time holds instants, epoch milliseconds or Dates, an order holds text or numbers, and a unit holds numbers, plus Dates in the instant unit), and a type fits a value when every trait it has accepts it. A Date is an instant, so a time column of Dates keeps its inherited type, zone included, and its Dates become epoch milliseconds; a string needs a zone to read, so it does not fit. The inherited types never reinterpret or check values, so a date rewritten to "Mar" is plain text, not an error. Fitting reads values, not meanings: a derive that recodes a time to plain numbers (years) keeps its time unit, since any finite number is epoch milliseconds (#1089), and derive(fn, { schema }) is the fix. The result's own types override the inherited ones column by column, inference types a column of Dates as a UTC time, and derive(fn, { schema }) overrides all of that for the columns it names and converts their values like a chart's schema (a datetime column a Python callback returns arrives typed from the widget's decode). The result is a list, as all data is; derive's type says so and nothing checks it at run time. The operator never tags the array its function returned. log returns its input, types and all. A filter returns a subset of its input's row objects, so its typing rule carries the input's types over as they are, with no fit check (a predicate that changes the rows it tests is not supported); a filter that keeps a value outside an order keeps the order, so the stray-level error fires where the order is used, and that error names derive(fn, { schema }) as a fix for an order a derive's renamed values inherited. applySchema copies the rows only when some time value is not epoch milliseconds already; otherwise it tags a shallow copy of the array. So the stack's split reads its by column's type off the data it splits, and a color channel's DatumValueImpl records the type of the field it read (fieldType), which lets the categorical color scale list its domain in the column's order. A later trait (HasZero, HasCycle, ...) is one more key on the record.

A column's unit is one of these traits, HasUnit, so a unit moves with the rest of the column's type, by the same rules: it survives a split, a filter, and a derive whose column still holds numbers, and a schema entry that names the column replaces it with the rest of the type (#994). chart(data, { schema }) and derive(fn, { schema }) declare it with a Unit(u) or the name u. columnTypeOf turns every entry (a builder, a column record { name, unit }, a Unit, a unit's name) into its record of traits, the wire form, in one place (traitsOf), which Python's chart mirrors before it serializes. A wire record may have only the keys of the types: each trait's record has only its own keys, and a HasUnit's traits is a record keyed by unit trait name. Both key lists are tables the compiler holds to the types (TRAIT_KEYS, UNIT_TRAIT_KEYS), so a misspelled key throws instead of being dropped.

A column's domain (HasDomain) moves with the rest of its type, by the rules above, with one difference: it is of the rows it was computed over. applySchema computes it for the chart's data and for each derive's result over the rows it types, and drops the domains it inherits or finds on the array, so a derive never keeps its input's. copyColumnTypes hands it to each split leaf and to a filter's result with the other traits, the same record, so a split leaf holds one group's rows and its column still has the domain of the whole data. A chart over a selection (chart(selectAll(...))) types a list of refs, so ChartBuilder passes applySchema the rows the refs stand for (rowsReached, which carries the column types of the bags it reads the rows from), and the domain is over those. Declaring a domain is not supported yet: a schema record that gives a column one ({ HasDomain: { lo, hi } }, which no builder writes) is a loud error in columnTypeOf.

Domains are types. A column's domain is part of its type, decided where the data is typed, so a subset keeps it. A group-by or a filter picks out rows. It does not change which values the column can take, just as filtering a list of Int gives a list of Int. So every group's field(x).bin(p) computes the same cells, empty ones included, with no group reading another's rows. This recasts Vega-Lite's resolve: { scale: "shared" | "independent" }, a setting on the composition, as type inference. Sharing is the default, because the type flows with the data from the place it was inferred, as TypeScript infers number[] for an array literal where it is defined. Independence is narrowing: a group that wants its own domain re-types its rows to the narrower type. In type-theory terms a domain is a refinement type, such as { v: number | 0 ≤ v ≤ 99 }: a group inherits its parent's refinement by default, an independent group narrows to the one its own rows give (a subtype, since its rows are a subset), and groups that meet again on a shared axis combine at their join, the smallest domain that covers them all, which is what Vega-Lite's shared resolve computes. Units work the same way already (a unit is a type, and a mismatch is a type error). #1147 applies the same rule to categorical levels.

Field expressions: a pipeline orthogonal to channel aggregation ​

field(name) (fieldExpr.ts, #700) returns a chainable expression — a Polars-column-expression-style builder where each method appends one op to an ordered pipeline (field("age").bin().reverse() bins first, then reverses the resulting cells). The pipeline is read off either a live FieldExpr instance or its deserialized wire shape ({ type: "field", name, ops? }, what the Python bridge/IR produce directly) by the same getFieldOps helper, so every evaluation site handles both forms identically.

Two op families consume disjoint slots, and mixing them is a checked error rather than silently doing the wrong thing:

  • Domain ops (.sort(by?, order?), .reverse(), .bin(partition?), .dropNulls()) apply to a by grouping key. splitEntries (datumProjection.ts) is the shared split-plus-ops helper behind spread/stack/group/scatter/treemap's by (and time.sequence's, which splits keyframes the same way — its groups are laid out in one shared frame, so the space they occupy is the space of the whole dataset, which is what keeps a playing chart's axes still; the TimeTier it hands a time.transition() is declared in the same module and carries the clock, the keyframes, the cycle of the time axis when the sequence is cyclic, and the clock's milliseconds per unit of the field). A build-in stagger's by reuses splitEntries for the order of its groups (src/animation/grouping.ts). dropNulls filters out rows whose value at the field is null/undefined FIRST (so it composes the same regardless of where it sits in the chain — every other domain op re-derives its grouping from these filtered rows), then it groups the remaining rows by the key splitKeyFn gives each row. That reads a field(...)'s .name exactly like a bare string, passes a key function the row and its position, and keys a chunk(size) by position alone, floor(i / size) (an operator with no by splits by chunk(1), row identity), and the groups come in order of first appearance, or in the order of the column's levels when the data declares them (HasLevels, from Domain.discrete, see Column types). A binned key (bin, or a binned struct) instead keys each row by its cell, and its groups are the cells of its partition, in order, one entry per cell, empty cells included (binEntries; see Cells). The same key function keys a stagger's children by their cell, so they group the same way the split did. A fused connector's default split reads no key function: it keys each ref by the keys the flow's splits gave the groups it is in (each split stamps the nodes it makes with its by, GoFishNode.keyBy, beside the key), since a single row does not carry the domain its cell is over. Then it applies each remaining domain op in pipeline order: sort reorders the resulting entries, either by the group key itself or by the SUM of another named field over each group's rows; reverse reverses the entries. An aggregate op or normalize reaching a by slot throws — a domain op describes which groups exist, not what a group's value is.
  • Aggregate ops (.sum(), .mean(), .median(), .count(), .distinct()) apply to a value channel slot (a mark's h/w/x/y, or an operator's entry-flagged size) and fold a group's rows to a single value — evalFieldValues in fieldExpr.ts. A domain op or a second aggregate reaching a value slot throws (the fold happens once).
  • Maps and reduces (.map(fn), .reduce(fn), stack profiles S10) are the general form of the value slot, and the named methods are built-in callbacks of them on one path, evalGroup in fieldExpr.ts. Its pipeline is read in three parts, in order: maps (each a function of all the values: map's fn(x, i, xs) on each, or normalize's shares), at most one fold (a user's reduce, or sum, mean, median, count, distinct from the NAMED_FOLDS table), and then the members a lifted result is read through ({ op: "member", name, args }). A member after a named fold, or anything but a member after a lifted result, is the chaining error: nothing chains after a value. A map after a named fold is the chaining error too, except on an operator's size channel, where it runs over the entries' values (the window).

Lifting a reduce's result ​

A reduce's result is lifted by its shape, which is known only when it runs (liftLeaf). A number, or no value, is a value; a Fun is a function of t, which only the shape form of ribbon and line reads (groupFun in groupExpr.ts asks per group); a record is read through the members after it, a method member called with its arguments; an array is an error. A function value a spec writes (fun(at, { domain })) is an expression that holds a Fun (heldFun) and is not one, so liftLeaf reads the Fun it holds wherever one appears in the result. The expression holds the members as ops, so the spec can name a member before the reduce has run: field(x).reduce(fn) is a Proxy over the expression (lifted), whose every property but its own wire and the hooks the runtime probes (OWN_KEYS) is a member method. The types mirror this: Lift<V> in groupExpr.ts maps a number to ValueExpr, a Fun<number> to FunctionExpr (as it maps a FunValue), a record to one method per member, and an array to a LiftError, which no channel takes.

Each step runs once per group. evalGroup keeps what a map or a fold computed by its op object and the rows array it ran on (stepCache, two WeakMaps), so the channels of one mark, the extent pass and the drawing pass all read the one result. A named fold goes through the cache too, so there is one path. A Python map or reduce has only a batch form: before inference, resolveChannelAccessors (channels.ts) calls it once over every group the channel will read (resolveGroupSteps), one bridge call whose input is each group's values and whose reply is one result per group, and fills the cache. Reading a Python step on a group it was not resolved over is an error, not a silent call.

Distributions ​

A distribution is the record Dist (dist.ts): density, cdf and domain, each a Fun<number> over one interval, quantile(p), median, mean and mass. It is a plain record, so a reduce that returns one is lifted by the rule above with no case of its own: d.density() is a member that is a Fun, d.quantile(0.9) a method member, d.median() a number. Its domain member is the identity over the interval density is drawn over, which is what the generic domain() of a Fun gives too, so d.domain() and d.density().domain() are the same function. The record has the member; a bare Fun has the generic rule in liftLeaf. Neither knows about the other.

Every Dist is built in one place, distOf in dist.ts, from a distribution's data form (DistData), a plain tagged record that crosses to and from Python: { type: "dist", family, params }, a family with numbers for its parameters, or { type: "dist", family: "kde", params: { values, bandwidth? } }, a kernel density. A kernel density is one self-consistent distribution (kernelDist): a normal kernel on each value with Silverman's bandwidth when none is given (silvermanBandwidth in overlap.ts), drawn from 3 bandwidths below the least value to 3 above the greatest (KDE_CUT, seaborn's cut=3), with area the number of values over the whole line; its cdf is the mean of the kernels' cdfs, the density's integral over the mass, its quantile inverts that cdf (Newton's method in a bracket), and its mean is the values' mean, the density's mean. distOf caches each data form's Dist by identity.

A column holds a distribution after derive(kde("x")), which writes the data form into it. evalGroup asks heldDist (fieldExpr.ts) whether the group's column holds one: the first row that is not missing decides, and a row with a different one (by identity, then by its JSON) is an error that says to split the rows so each group holds one. A column that holds one is lifted like a reduce's result: liftLeaf reads the Dist through the expression's member ops (distMembers; median() and mean() become members, every other fold is an error naming the members). A column of numbers has no distribution: a member op with no fold before it is an error in stepsOf that names derive(kde(...)). A family, Dist.normal({ mean, sd }), is its own expression (DistExpr in distExpr.ts, wire { type: "dist", family, params, ops }): evalGroup reads its parameters over the group's rows (exprDist), builds the family's data form, and lifts its Dist through its member ops.

A partition by a key over a variable gives each group its cell, and the cell's distribution is the whole one restricted to it. The group's rows array carries a tag (groupCell.ts, a symbol on the array, as the column types are): the variable, a column name or a family's identity, the cell's interval, and the whole rows. splitEntries writes it for a field binned on the line and for a family binned with d.bin(p) (distEntries, whose cells are distributionCells over the density's interval, each holding every row). A split inside a cell (a spread by species in a binned partition) keeps the cell (keepCell): each of its groups gets the cell's interval, and its whole is the group the same split gives for its rows in the cell's whole, so a species' density in a cell is that species' density restricted to the cell. A group that is a cell of its own keeps its own; a group holds one cell, so a split binned on a second variable replaces the first's. Three leaves read it, and only when their variable is the cell's: a family's exprDist restricts the whole group's Dist (restrictDist; a family is drawn from its 0.001 to its 0.999 quantile, so a cell at an end of that interval also holds the tail past it), a column that holds a distribution restricts it the same way (groupDist; splitEntries cuts a field binned over such a column at the distribution's own cells, distCells, as it does a family's), and bandOfRows builds the band through the whole rows and restricts both edges to the cell, so the bands in neighboring cells meet. A distribution of another variable is read whole. A fold over the cell's rows that is not a distribution, such as median() of the column, needs no tag: the cell's rows are the values in the cell.

A fold that lifts says the quantity of each leaf (FoldStep.lift). A reduce reads its unit option. A Dist reads its variable (distQuantities): the domain, the quantiles, the median and the mean are amounts of the variable (the column; for a family, a quantity with no name in its location column's unit, since the variable is not that column), so their axes join; the density is the mass per the variable's unit, or per its difference unit (a density over instants is per duration), with CanSum, so densities stack; the cdf is a ratio, which does not add up.

The unit option mirrors the result's shape: one unit for every number below it, or a record with a unit per member (quantityAt). A number with no declared unit gets a quantity marked undeclared, whose unit has no CanSum, so checkSummable refuses to sum or stack it and says to declare the unit. A named fold keeps the column's quantity (none of its own), as before; count and distinct report counts.

.between(lo, hi, { closed }) is deliberately not an op. It returns a row predicate (row) => boolean for the filter flow operator, and a predicate belongs to none of the three slots: it never decides which groups exist, never folds a group to a value, and never scales anything. Giving it an op would mean a fourth slot that every evaluation site had to learn to ignore. For the same reason it THROWS when the expression carries ops: field("x").bin(Bin.step(10)).between(...) would have tested the raw x, silently. closed is polars' is_between argument, comparing by value (SQL RANGE) rather than by row count (Vega's window frame). The bounds are plain numbers; a window that follows a timer() is a lambda around the bare-value form, exported as between(v, lo, hi, { closed }) — which is also the loose-ends spelling of contains in util/interval.ts.

The predicate still serializes. It carries its description { field, between: [lo, hi], closed? } beside the function (fieldPredicate builds both from that description), and filter puts it on the wire as { type: "filter", predicate }. The description travels with the operator, never in the expression's ops, so the three slots stay as they are.

Cells: a binned key ​

field(x).bin(p) (#1058) is a value transform: it maps each value of x to its cell in the partition p (cells.ts). A partition is a Calendar value (calendar.ts), Bin.step(size), Bin.thresholds(countOrEdges) (a count, or a list of edges), or Bin.quantiles(countOrProbabilities), the three Bin kinds that bin one field (families/bin.ts). Those three are objects of a class, StepBin, ThresholdsBin and QuantilesBin, whose own keys are their wire form ({ kind: "step", size }) and whose .format(fn) is held off those keys, as a Calendar value's is. The wire form of the op is { op: "bin", partition? } with the partition's own wire form, a Calendar value's { kind: "month", every: 1 } or a Bin kind's, one union told apart by kind. checkPartition reads either form, and rejects a Bin kind that bins two fields, naming struct({ x, y }).bin. A Cell keeps the whole value: the interval [start, end) (its region), its id (its start, as text, so String(cell) is the key a node gets), its label (the partition's .format(fn), else the default: "0.5–1", or the calendar label), and, for a calendar cell, its calendar fields, partition and zone. Every cell also records the bin that made it (KeyCell.bin). The column the cells bin is recorded once, on the ordinal space over them: the field it groups by (its title, the split's by), so an axis can tell levels that partition one value (a year and a month of one date) from categories of different columns (Axes). A split says whether its keys have an order with its groups (SplitGroups.hasOrder from splitEntries): cells always do, and so do the levels of a column declared ordered. Cells are ordered by start.

The cells are defined over the column's domain, not over the rows of the group being split. binCells takes the domain the column's type carries (HasDomain, see Column types), read off the rows being split (domainOf in datumProjection.ts), and returns the cells in order and the cell each value falls in (cellOf). Since every split leaf has its column's type, splitEntries gives every group of a nested split the same cells in the same order, an entry per cell, empty or not, and a count picks its step from the whole domain (#763); no group reads another group's rows. A value outside the domain has no cell, which is an error. A column with values that are not all finite numbers has no domain (the cells of a line have no cell at an infinity), so binning it is an error that names the column, and the value when the group holds one; a column with no values has no cells. The cells of a domain are built once per partition value and column (a cache keyed by the HasDomain record and the op's partition object), so the groups share the very same Cell objects.

A group with no rows. An empty cell is a group with no rows, and every operator over it is well defined: an operator over no rows makes no children and draws nothing (a node with no lowering of its own and no children lowers to nothing, see Rendering). A position read from a group's rows is a statistic of them, so a group with no rows has none: a position channel is a mean (inferPos), and the mean of no rows is no value (meanOf in fieldExpr.ts; a sum or a count of no rows is 0, which is a value). A position with no value is in no domain, since only defined positions make position constraints. And scatter, which places each child at its position, does not draw a child that has no value in a placement it is given (placedChildren in scatter.tsx): there is no place to draw it. So scatter({ by: field("x").bin(p), x, y }) draws one point per cell that holds rows, and the empty cells leave the scale of the others alone.

A cell holds its start and not its end, and a Calendar value or a Bin.step puts a value in the cell that holds it whatever the domain (March 1 is in March). A Bin.thresholds partition is fitted to the domain, so it covers the closed domain: the count's step is the one a numeric axis with that many ticks uses (tickIncrement), and the largest value falls in the last cell when it sits on an edge, as in numpy's histogram and d3's bin. A Bin.quantiles partition is fitted the same way, with its inner edges at type-7 quantiles (quantileSorted) of the column's values in the data it was typed with (HasDomain.sorted), so it too reads no group's rows. Two edges at one value, as many equal values give, throw rather than merge, as polars' qcut does. A column of one value has no quantiles to cut at, and throws saying the column is constant; a probability given twice is caught earlier, by the list's uniqueItems in the descriptor.

Cycles, products and chains. A calendar level binned alone is a part of the next larger level (CalendarPartition.cycle): Calendar.month is the month of the year, so all Junes are one cell, and Calendar.weekday (a day, labeled by its day of the week) is the day of the week, so all Mondays are one cell. A week is a part of nothing (weeks do not nest in months or years) and nothing holds a year, so those stay on the line. A week's parts depend on its first day, so a weekday carries a start, its reference week starts on that day (REFERENCE_WEEK), and a weekday is a part of a week only when both start on the same day (CalendarPartition.whyNotAPart, the one is-a-part-of relation, which also needs the outer level's cells to be one unit each, and says why when a level is not a part). A weekday is a day, so an hour is a part of it ([Calendar.weekday, Calendar.hour], the hours of the week). Its part, and the weekday field of every calendar cell, is the ISO day of the week (1 for Monday), whatever the start; the start only orders the parts. The parts are not cells of the line: a CycleCell (cells.ts) has an id (its field values, "6" for June), a label, its place in the cycle, and no region. The cells of a cycle are read off one cell of the cycle unit, the reference cycle (referencePeriod in calendar.ts: the leap year 2000, so February 29 is a part of the year; its 31-day January for the days of a month), so a key over them has every part, in order, whatever the data holds. That is the key's HasCycle: the order, the whole cycle, and the cycle's unit as a partition whose every cell is one cycle (unit: Calendar.year for the months of a year, Calendar.week with the parts' week start for the parts of a week). An axis level that groups the parts asks that partition whether it is a part of a cycle (calendarLevel in axes/elaborate.tsx), and partition's error over a key of parts, which names the whole key, fixes it with that unit first, as one product of all the levels or as a chain of them. A value falls in the part named by its own fields in the column's zone (CalendarPartition.part). A part's .format(fn) reads a CalendarPart (kind: "part", cycleFields in calendar.ts): only the fields below its cycle, so no field is a stand-in NaN. A cell of the line gives a CalendarCell (kind: "cell") instead, so the formatter narrows on kind. TODO(#1052): a spread over a cycle in polar space should leave the same gap between its last part and its first as between any two; that default is not built.

A list is a product, [Calendar.year, Calendar.month] (checkProduct): each level after the first is a part of the one before it, which has a step of 1, so the cells where one cell of each level meets one of the next are each one interval, the finest level's cells (the June of 2015 is the 2015 year met with every June). Its label names every level at once (productLabeler, which resolves its formatter once per levels and zone: "Jun 2015"). With a first level on the line its cells are cells of the line, every one in the range of the domain; with a first level that is a part ([Calendar.month, Calendar.day]) they are the parts of a cycle. A second bin op is a chain (chainCells): it splits each cell of the bin before it, and each cell keeps the cell it was split from (KeyCell.parent). On the line the next bin must be finer, its cells are read on the line, and a cell it shares with two cells before it is cut in two (refine); on a cycle the next bin must be a part of the one before it, as in a product. So .bin(Calendar.year).bin(Calendar.month) and .bin([Calendar.year, Calendar.month]) have the same leaves; only the chain keeps their years, which an ordinal axis over it shows as a level (Axes). The type follows the cells: a key first binned by a part (RegionOf in fieldExpr.ts, read off the level's unit) has no region, and a chain keeps the kind of its first bin (the phantom binned flag).

The keys of a split may now be cells (SplitKey). Everything that reads a key as text or a number reads the cell's id (its start, or a part's field values), so .sort() orders cells of the line by start and parts of a cycle by their place in it, and time.sequence keys its frames at cell starts.

Partition: each group in its cell ​

spread, stack and table read a cell's id and order. Only the partition operator (graphicalOperators/partition.tsx) reads its region: it gives each group its cell's interval [start, end) on one continuous scale, so a 29-day February is narrower than a 31-day March and an empty cell keeps its place (it is a group with no rows, and it is still placed). Its key must have a region. Only .bin(p) with cells of the line makes one, so the type of a field expression says whether it does (FieldExpr<true>, a phantom hasRegion flag that domain ops keep and aggregates drop, and that a part of a cycle does not set), and the split checks the wire form from Python with an error that names the fix (for a part of a cycle: bin by the year too, as a product or a chain).

It has no layout code of its own. It is a layer with one position constraint per child that gives it its cell (Constraint.position({ region }), with a PositionRegion per cell) and one align on each axis where nothing gives the children a cell (the other axis, for a top-level 1D key), as in a scatter.

A partition pushes its scale and its cells down. The cell is in data, so the partition's position scale maps it: the layer resolves the cell's two edges through its frame, as it resolves an interval (compilePlacementCoordinate). The child is proposed the cell's length as its size there (buildChildSpans, childLayoutSizeProposal, constraints/proposalPlan.ts), and the cell places the child's middle at the cell's middle. The claim walk reads the cell as an interval on that axis (constraintsOn, constraints/claimPlacement.ts), and seats a child with a size of its own in the middle of it, not across it (placeByClaims). A cell handed to the placement solve directly lowers to the same pin of the child's middle (lowerPositionPlacement, constraints/position.ts). So a rect with no size there fills its cell, a stack or spread inside a cell divides the cell, and a circle or a text keeps its own size and sits in the middle of the cell. An interval would pin both edges instead, which sets the child's size and would stretch a circle into an ellipse. A child placed by its data in the layer's frame is not pinned (placedByOwnData, isDataPositioned), and neither is one that placed itself: they are where they are. The ownership plan (PlacementOwnershipPlan, constraints/placementLowering.ts) records a cell's axes as pinned for its children, as it does an interval's, so an align on that axis defers to the cell: it moves only children with no cell there, to the first child that has one. (The layer's type fold does not yet agree: an align on an axis that a cell or an interval places replaces the layer's position frame there, so end to end the cell loses its map; an expected failure in region.test.ts. partition aligns only on axes where its children have no cell.)

A region is placed by its data. The region mark reads its cell from the partition around it (enclosingCell, constraints/position.ts: the region a position constraint gives the nearest of it and its ancestors). Its type on each axis its cell spans is the cell's interval, CONTINUOUS and pinned, so it shares the frame of the layer it is in, as a rect with a data x and x2 does, and the partition hands it the map of its scale through the one seating rule (childPosScalesFor, seatInScope, frameOf). It maps the cell's edges through that map, and draws the outline of a cell of the plane as the shape its parent hands it (see below). Since its type claimed the cell, its parent leaves it where its data puts it (placedByOwnData, _node.ts, the one rule for a child its own data places: its cell is not its room, and no constraint in its parent but a position moves it, a middle align included), so a datum it cannot map (no map on that axis, as under a spread on the cell's axis, or a corner that is not a number) is an error that names the axis, not a box at the size it is offered. Only on an axis with no cell is it as long as its proposed size. A layer of marks in a cell (a region and a curve, or a dot at a median) is pinned too, so every mark in it reads the same scale. Such a layer is not pinned to the cell's middle, and nothing places a mark in it that has no position of its own: a text in a layer beside a region is placed by an align that names the two, not by the cell, and the align moves the text to the region, whether the region is bare or inside a layer of its own (that layer's data places it the same way). A region composite (intersect and the others) is no different: its region() operand reads its cell, and its ref operand is where its target is.

A partition inside a cell divides that cell. A partition reads the cell it is in (enclosingCell) when its constraints are built, and the partitions around it have built theirs by then, since the hooks run top-down (resolveAliases). On each axis its key does not place, each child's region spans the cell the partition is in (PositionRegion's enclosing), so the child is placed there as a child of the outer partition is: centered in it, or filling it. The inner partition's layer is then pinned on that axis, over the cell, so it shares the outer partition's frame and resolves the cell through the outer scale. Nothing is left to align there. The cell pushed down is the outer partition's, so it makes no cells of the inner layer on that axis: PositionRegion.placed says which axes the key places, and collectPositionDomains folds an enclosing cell's span into the domain as an interval, not as a cell. The axis that draws the cells is the outer partition's.

The cell pushed down is read in the outer partition's frame, and nothing checks that the nodes in between share that frame. A row with a size of its own, whose content is placed by other data (a density's pdf), maps its axis in a frame of its own, so an inner partition or region there reads the outer cell through the wrong scale (an expected failure in region.test.ts). Whether a node has a frame of its own is decided at layout (solveLayerScales), after enclosingCell runs.

The region holds its cell (a RegionCell, cells.ts: an id, a label when it has one, a span per axis, and an outline when it is not a box) and the column each axis it is placed along reads, as a map from a value to its datum. It reads the cell through them once: PositionRegion.spans holds, per axis, the cell's two edges as datums, and each datum carries what the column says about its values (its quantity and declared unit, so a histogram's x axis is titled and unified as x is, and its schema type, so a time column gives a time axis). collectPositionDomains reads a region's spans as it reads an interval (the domain, and the units with their calendar), and collects its cell when it is a cell of a line placed along that axis, so the layer's type on that axis holds the cells (CONTINUOUS_TYPE.cells). A union keeps them only when every part has them and they are the cells of one partition (mergeCells), as an ordinal over cells does. That is read off the cells, not off how they were binned: no two cells overlap (a cell in two parts is one interval in both, so [0, 10) and [5, 10) are of two partitions), and calendar cells share a calendar partition (CalendarPartition.sameCells), since a time axis labels them all by one partition's rows. A Bin.step over two domains gives the cells of one partition; a Bin.thresholds fitted to two domains may not. The type is what tells the axis that it places cells: a time axis over calendar cells ticks at their partition and labels each cell between its two boundary ticks (Axes). A numeric axis over numeric cells keeps its round-number ticks.

A top-level partition gives each child its cell on dir and no span on the other axis, where alignment places the children (bars on a shared baseline). Inside another partition's cell, a partition gives each child that cell on the other axis as well, so the child sits in a rectangle and there is nothing left to align. That is why two nested 1D partitions, one per axis, place each leaf the same way in either order; only the order of the children differs (cells.test.ts checks this for regions, rects, circles, and texts of different widths).

The product form. partition({ by: { x, y } }) divides both axes. It is defined as the 1D partition on x, then the 1D partition on y, and it is built by that rewrite (compose, in JS and in Python alike), so it adds no layout of its own, and on the wire it is the two partitions. Empty cells are groups with no rows, as in 1D, so a count over one is 0 and is drawn.

Regions with an outline. A region may also hold an outline, the same shape the boundary geometry query (#974) returns, but given from parent to child: a PositionRegion holds the cell's outline in datums (outline, [x, y] per corner) when the cell has one and is placed along both axes. The layer of the partition maps it through both of the child's scales into the child's frame, in the same walk that gives the child its span (buildChildSpans, constraints/proposalPlan.ts), and hands it to the child as its shape, the same channel a treemap hands its tiles down and an enclose its outline (see The shape a parent gives a child). A layer passes its shape on to a child it proposes its own box (childLayoutSizeProposal), so a region in a layer in a cell gets it too. A corner that does not map is an error that names the axis. The region mark draws its shape as a path when it has one, and its box otherwise (under a nonlinear coordinate space, resampled, so a hexagon in polar coordinates draws curved). The cells of a binned struct, below, are what make outlines. One step is left for later (a TODO in PositionRegion): a 1D partition inside a hexagon gives its children the hexagon's box cut down to their cells, not the hexagon's outline clipped to them.

Cells of the plane: a binned struct ​

A hexagon depends on two fields together, so a .bin on each field cannot express it. struct({ x, y }) (structExpr.ts, after polars' pl.struct) is a key that reads two columns, one per axis, and .bin(b) bins it with a strategy of the Bin family (families/bin.ts): Bin.hex({ radius }) or Bin.voronoi({ seeds }), the two kinds that bin two fields (a kind that bins one field, such as Bin.step, is an error here that names field(x).bin). Its type carries the same phantom flag as a field expression (StructExpr<true> once binned), so partition over an unbinned struct is a type error, and the split checks the wire form. The class's own fields are its wire form ({ type: "struct", fields, ops? }), so the instance and the object Python sends are read the same way.

splitEntries groups the rows of a struct key by the cells of the plane (polygonCells.ts), by the same key function as a binned field (binKey). A PolygonCell has an id, an outline in data, and the box that holds it (its span on each axis), and no order. The cells are those of the two columns' domain, as in 1D, so every group of a nested split sees the same cells and empty cells are kept (a cache keyed by the two columns' HasDomain records, the bin object and the two columns).

  • Hexagons. A pointy-top grid (as in d3-hexbin, ggplot2's geom_hex and Observable Plot) with a hexagon centered on (0, 0), so the grid does not move with the data, as Bin.step cells are aligned to multiples of the step. The radius is in data units, one number or one per axis; a hexagon is the unit hexagon scaled by the x radius on x and the y radius on y. A point goes to the hexagon with the nearest center (axial coordinates and cube rounding), so a point on an edge goes to one of its two hexagons, the same one every time. The cells are every hexagon whose inside meets the box of the domain (a separating-axis test over the box's two axes and the hexagon's three edge normals). A point on the box's edge may lie on the edge of a hexagon that only touches the box; it falls in the hexagon beside it that is a cell and holds it too. A box with no area (a column whose values are all one) may meet no hexagon's inside, so it adds the hexagon of each of its corners that no cell holds.
  • Voronoi cells. One cell per seed (d3-delaunay, over Delaunator), clipped to the box that holds the domain and the seeds, so every seed has a cell; seeds at one point share the first one's cell. A cell's id is its seed's index among all the seeds (the first one's, for seeds at one point). A point goes to its nearest seed (Delaunay.find). Distances are measured in data units, so the cells mean something only when the two fields share a unit (longitude and latitude, two lengths in millimeters).

partition's plane form is the same split and the same constraints as the 1D form: the struct's two columns are placed along x and y, so each child's one region spans both axes (the cell's box) and holds the cell's outline, and no axis is left to align. The boxes make the axes' domains, and since a polygon cell is no cell of one axis alone, each axis is a plain continuous axis (collectPositionDomains collects only a cell of a line, a Cell). A region draws the outline, and answers it as its outline geometry query (see Layout Calculation); any other mark is placed in the box, so a circle or a text sits at a hexagon's center. region({ inset }) draws the cell in by inset pixels on each axis where the region has a span (insetConvex for an outline, a smaller box otherwise). The inset is paint only: the region's box, which layout reads, stays the cell, and its outline query answers what it draws, so intersect cuts the drawn-in cell. A cell thinner than twice the inset draws nothing, and its outline is exact and empty (no pieces), so an intersect with it is exactly empty and draws nothing either.

Expression evaluation is orthogonal to the channel's own aggregation.inferSize/inferPos's shared core (inferNumeric in channels.ts) always called a sum or a mean over the raw per-row values; it now instead calls evalFieldValues(accessor, data, column) first — running any pipeline ops (an aggregate, if the accessor carries one). The rows are folded once: when the pipeline already folded them to a singleton (evalFieldValues reports folded, the one place that decides it), the channel takes that value as it is and applies no aggregation of its own (so a size channel sums nothing and checks no CanSum); otherwise it applies its own sum or mean to the per-row values. So rect({ h: field("weight").mean() }) reports the mean, not mean-of-a-1-element-array-nonsense. A bare string or plain function accessor carries no ops, so this is a strict superset of the pre-#700 behavior, not a new code path for the common case. The color and raw channels, which read the first row, fold an aggregate the same way: region({ fill: field("a").count() }) colors a cell by its count, and the count of a group with no rows is 0.

Unit implications. count/distinct report values that are counts, not the source field's own units — evalFieldValues reports the quantity "count", in the declared unit "count", for them. Every other pipeline without a map reports no quantity of its own, leaving resolveColumn to the channel as before, so .sum() and .mean() keep the column's unit. .normalize()'s share values get their own declared unit, shareQuantity(base, byName) — see Space-filling spines above for why a share is a distinct unit (0–1, not the base quantity's own units) that must never silently union with it. An area channel (#972, CHANNEL_INFER.area in channels.ts) roots its sum, and the root is in a unit of its own too, √q (sqrtQuantity in measure.ts), so a circle sized by area: "count" never shares a scale with a bar of h: "count". A declared unit stays declared, as √unit, with its symbol rooted too, and an unknown one stays unknown, the variable √name. The root keeps none of the unit's traits: a square root does not preserve sums (√(a + b) is not √a + √b), so √unit has no CanSum and a stack of area circles is refused by the sum check. It keeps no difference or zone either (an area channel sums its rows first, so amounts of an instant never reach it), and it records no column, since its values are not the column's.

Axis inference ​

Conceptually, axis inference splits into two independent questions:

  1. What guide could this space support? Answered by the space's origin state. A pinned interval permits a quantitative axis. An origin-less one permits a magnitude guide but not an axis with a meaningful zero. A free magnitude wants a legend, not an axis. ORDINAL permits labels at laid-out keys. UNDEFINED contributes nothing.
  2. Should that guide be drawn here? Independent of the kind. The root of a stacked bar may have a POSITION y-space that permits a quantitative axis; a nested stack inside a more complex diagram might have the same kind without deserving its own visible axis. Conversely, a facet operator might explicitly request labels for the ORDINAL spaces it creates.

Both questions are now answered by a tree walk. resolveAxes (_node.ts) performs (2): a top-down pass that tags each node's axis.x / axis.y as true (this node owns a visible axis on that dimension), "budget" (a layer sibling owns it), or false (suppressed via an operator's axes: override). It honors per-operator overrides and short-circuits coordinate-transform subtrees (polar axes are handled separately by coord.tsx). The space then answers (1): anchored CONTINUOUS → quantitative ticks, unanchored → delta labels, ORDINAL → labels at laid-out keys.

Selection is no longer tied to the root. A faceted chart tags an axis on each facet-owning node, and an outer operator can suppress an axis its child would otherwise produce. The flags are consumed by the axis elaboration pass (elaborateChrome, src/ast/axes/elaborate.tsx), which wraps each flagged node in a Layer of ordinary tick/label shapes constrained to the inferred domain — so axes are not a privileged node type and the layout engine carries no axis-specific budget machinery. See Axes for the full elaboration story.

Discrete non-position channels ​

The tree is for spatial channels (x and y). Discrete non-position channels — color, symbol, texture, stroke pattern, marker shape — don't create an underlying spatial structure and aren't represented here. They still need shared resolution (categories should map consistently across a graphic; users should be able to override defaults; operators should be able to introduce or delimit scopes), but the right model may be closer to a theming API than to axis inference: a discrete color or symbol channel resolves by looking up a category in an inherited theme scope, with local operators or marks able to override the palette.

The current code does this with a unit.color map on scaleContext (seeded by resolveColorScale in _node.ts), which is enough for GoFish today but is not yet a general theming system. Future work. See Color Scale Resolution for what is implemented today.

Adding a new operator ​

Four things to consider:

  1. What kinds of children does it expect? If your operator only ever sees anchored, data-positioned children, you don't need to handle the symbolic-magnitude path. If it can be the parent of a data-driven stack, you do.
  2. What kind does it produce? Pick the most informative result that honestly describes the space. A spread-style operator that lays children out side-by-side without summing should keep the magnitude (a CONTINUOUS at origin 0, symbolic in σ) along its stack direction. An operator that fixes children to specific coordinates should produce an anchored CONTINUOUS (a POSITION). An operator that introduces a categorical axis should produce ORDINAL.
  3. Does it transform spaces or merely pass them through? A coord transform annotates without changing the kind. enclose and wrap- style overlays use unionChildSpaces. position is a pass-through. Match the existing patterns in graphicalOperators/ and don't reinvent the merge logic per-operator.
  4. Does it add pixels, or compose or pass through its children's claims? If so, write a claim hook (resolveExtent) next to the type hook, using the claim half of the fold you used for the type (unionChildExtents, resolveAlignmentExtent, ...). If not, leave it out: the node then claims what its types imply. Never put pixels into a type.

If your operator is layout-time-only (no contribution to the kind tree), return [UNDEFINED, UNDEFINED] and rely on the children to drive inference upward through your wrapper (e.g. via unionChildSpaces from a parent layer).

Prior art ​

The general lesson — that graphical structure determines scale structure — is shared with Vega-Lite's resolver, Observable Plot's distributed inference, and Atom's recursive layout (Park et al. 2017). GoFish's contribution is generalizing that lesson into an explicit per-node intermediate representation rather than a set of operator-specific conventions. Anyone can add an operator that contributes, transforms, or consumes underlying-space facts; nothing in the layout, posScale, or guide pipelines is privileged.

The design also borrows from compiler architecture, especially typed intermediate representations and the value of an explicit elaboration pass that turns a convenient surface specification into a more precise representation that later passes can consume without re-inferring the same facts.

For a longer treatment, see the "Underlying Space Tree" section of GoFish's thesis chapter (parts/theory/underlying-space.typ in the companion thesis repo). The first write-up of the data, underlying, and display spaces, from before the tree was built, is kept in Spaces.

Pointers ​

  • The type definitions and constructors: src/ast/underlyingSpace.ts.
  • The claim record and its helpers: src/ast/extent.ts.
  • The traversal drivers: _node.ts's resolveUnderlyingSpace() and resolveExtent().
  • Per-shape resolvers: src/ast/shapes/{rect,ellipse,petal,text,image}.tsx.
  • Per-operator resolvers (each colocated with the operator): src/ast/graphicalOperators/{spread,layer,scatter,enclose,porterDuff,position,connect,arrow,table,coord}.tsx.
  • Overlay union helpers: src/ast/graphicalOperators/alignment.ts.
  • Constraint space folds: src/ast/constraints/{distribute,align}.ts.
  • The piecewise-linear value algebra used by claim composition: src/ast/solver/pwl.ts.
  • Layout consumption: gofish.tsx's layout() for root-level dispatch; layer.tsx's layout for the per-scope scale-factor solve and the constraint budget inversion (spread/stack elaborate to layer, so they have no layout of their own).
  • Companion factory docs: The Mark Factory, The Operator Factory.