1. Introduction

What This Project Does

spreadsheet-handling is a Python toolkit for roundtrip workflows between structured data and human-editable spreadsheets. A configurable pipeline projects data into spreadsheet form for review and editing, then re-imports it deterministically. Semantics are kept explicit: cross-references, coded cell values, and FK helper columns are all configuration-driven, not inferred from sheet layout.

Two Repositories

The library (spreadsheet-handling) and a demo integration (spreadsheet-handling-demo) are separate repositories. The demo is the main user entry point and contains runnable examples and sample data.

This guide documents the framework surface shipped with a specific library release.

Scope of This Guide
  • Pipeline workflow overview and starting points

  • Transformation catalog: step names, parameters, roundtrip guarantees

Demo data, runnable scripts, and integration walkthroughs live in the demo repository.

2. Workflow

The Core Idea

A pipeline transforms data bidirectionally between a normalized relation form (YAML-friendly) and a human-editable spreadsheet. The same configuration drives both directions, so re-import is deterministic.

Practical workflows tend to grow in rings: start with a plain tabular roundtrip (data in → spreadsheet out → back in), then add FK helper columns for display, then introduce cross-table or compact-cell encoding for multi-valued relations. Each ring adds one transform pair from the catalog.

A runnable walkthrough of this spiral is available in the spreadsheet-handling-demo repository.

Pipeline YAML Structure

A pipeline is a YAML list of step entries. Each entry names a registered transform and supplies its parameters inline:

pipeline:
  - step: expand_xref
    matrix: role_permissions
    output: permission_rows
    row_keys: role_id
    drop_empty: true

Available step names, required parameters, and roundtrip guarantees are listed in the Transformation Catalog.

Running a Pipeline

sheets-run is the primary runtime command for executing a documented pipeline. For an ad-hoc pipeline file like the one above, provide the steps file and input/output locations. The pipeline steps transform the loaded frames; the CLI input and output options choose how those frames are read and written:

sheets-run --steps pipeline.yaml \
  --in-kind yaml_dir --in-path data/input \
  --out-kind yaml_dir --out-path build/output

The spreadsheet-handling-demo repository contains the full first-hour walkthrough with checked-in input data, pipeline files, and expected outputs. The user guide focuses on the configuration concepts and transform catalog rather than duplicating that tutorial.

One-Shot Schema Column Maintenance

Use sheets-schema-maintain when you need an explicit, reviewable column schema change over loaded Frames: add a column, drop a column, rename a column, or reorder columns. It is a maintenance command, not a normal pipeline step. Use ordinary roundtrip editing when the change belongs in the spreadsheet payload itself; use schema maintenance when the column contract has changed and you want the tool to check recognized metadata references before writing output.

The command is dry-run by default. In dry-run mode the loaded Frames pass through the orchestrator and then into the output-only discard saver, so no output artifact is written. Add --write to allow a user-selected output write; write mode requires both --out-kind and --out-path.

Every run emits a machine-readable JSON report outside Frames and outside _meta. If --report is omitted, the report is printed to stdout. If --report is supplied, the report is written to that path. Blocking failures stop the write before the saver runs, but the report is still emitted.

Supported operations:

  • add_column

  • drop_column

  • rename_column

  • reorder_columns

Metadata handling is deliberately conservative. Recognized metadata references are updated, pruned, or blocked according to explicit rules. Ambiguous, malformed, or unsupported structured references block the operation. Unknown plugin-owned metadata is not string-searched or heuristically rewritten; it blocks only when a structured frame/column reference is detected. _meta.derived is non-authoritative and does not drive schema decisions.

Known limitations:

  • no public sheets-run YAML step and no public pipeline registry step;

  • no generic migration framework;

  • no workbook-header inference;

  • no dynamic projection schema handling;

  • FK relation drops remain blocked.

Dry-run rename with the report printed to stdout:

sheets-schema-maintain \
  --in-kind json_dir --in-path data/input \
  --op rename_column \
  --frame characters \
  --source-column name \
  --target-column display_name

Write-mode rename from json_dir to json_dir with a report file:

sheets-schema-maintain \
  --in-kind json_dir --in-path data/input \
  --write \
  --out-kind json_dir --out-path build/schema-updated \
  --op rename_column \
  --frame characters \
  --source-column name \
  --target-column display_name \
  --report build/schema-maintenance-report.json

Drop with explicit pruning of supported references:

sheets-schema-maintain \
  --in-kind json_dir --in-path data/input \
  --write \
  --out-kind json_dir --out-path build/schema-updated \
  --op drop_column \
  --frame characters \
  --source-column obsolete_note \
  --prune \
  --report build/drop-obsolete-note-report.json

--prune only removes explicitly supported references. Unsupported structured references still block, including FK relations that touch the dropped column.

3. Transformation Catalog

Reading This Catalog

Step names used in pipeline YAML must match the runtime_name values in pipeline_step_registry.json (under core/registries/), which is the authoritative registry artifact.

Inverse kinds
bijective

Fully reversible. The inverse step reconstructs the original exactly.

conditionally bijective

Reversible when the stated conditions hold (see each entry).

relation-preserving

No data is lost, but column order or frame shape may change.

projection-only

One-way; the inverse step cannot reconstruct the original.

validation-only

Read-only; no frames are changed.

configuration-only

Writes workbook metadata only; no data frames are changed.

Groups
Bijective transforms

Paired expand/contract steps that form the core of the bidirectional workflow.

Supporting steps

FK helpers, validation, configuration, and infrastructure steps listed in a reference table.

Bijective Transforms

These steps come in expand/contract pairs. The expand direction converts a compact or matrix representation into an explicit relation (long form). The contract direction reverses it. Losslessness is conditional — see each entry.

expand_xref / contract_xref

Category: primitive · Inverse: conditionally bijective

Expand a matrix frame (rows × columns of marker cells) into explicit long-form relation rows, or contract them back. Typical use: a role × permission table where each cell marks whether the role has the permission.

See also: concept doc technical_model/ch04_concepts/crosstab_binary_xref.adoc and compact_transforms.adoc.

expand_xref parameters

Parameter Required Description

matrix

yes

Name of the input matrix frame.

output

yes

Name of the output relation frame to produce.

row_keys

yes

Column name (string) or list of column names that form the row identifier.

value_columns

no

Columns to expand. Defaults to all non-key columns.

column_key

no

Field name in the output relation that stores the column-axis address value (default: column_key). This is a field name, not a list of axis values — see column_keys on contract_xref for that.

value

no

Column name in the output holding the cell value (default: value).

drop_empty

no

If true, omit rows where the cell value is empty or blank. Default: false. With base_relation: a blank in-scope cell removes the matching base tuple. Without base_relation: a blank cell either produces a tuple with empty value (false) or is omitted (true).

base_relation

no

Optional name of an existing relation frame for scoped recomposition. When absent, expand_xref converts the matrix to a new relation (standard mode). When present, the matrix cells define the update scope and the matching base-relation tuples are replaced or removed; relation rows whose addresses fall outside the matrix scope are preserved and appended to the output. First-run pipelines with no prior relation omit this parameter.

drop_source

no

Assert that the expanded relation fully supersedes the matrix and mark the matrix for carrier-neutral final domain cleanup (_meta.pipeline_cleanup). Rejected when an explicit value_columns subset would leave unexpanded matrix columns behind. Default: false. Workbook helper/technical columns must be removed by their owning projection step (or made explicit) before a full expansion.

name

no

Override the step name shown in logs.

Losslessness condition: lossless when drop_empty: false, or when the original matrix had no empty cells in the expanded columns. With drop_source: true, the checkable value-loss condition (an unexpanded value_columns subset) fails fast; shape recovery of empty-only columns under drop_empty: true needs dense column intent or a retained matrix.

- step: expand_xref
  matrix: role_permissions
  output: permission_rows
  row_keys: role_id
  drop_empty: true

contract_xref parameters

Parameter Required Description

relation

yes

Name of the input long-form relation frame.

output

yes

Name of the output matrix frame to produce.

row_keys

yes

Column name(s) forming the row identifier (must match expand_xref config).

column_key

no

Field name in the relation that holds the column-axis address values (default: the literal column_key; configure it to match the preceding expand_xref). This is a field name, not a list of axis values — see column_keys below.

value

no

Column in the relation holding cell values (default: the literal value; configure it to match the preceding expand_xref).

column_keys

no

Explicit ordered list of column-axis values that become the visible matrix columns. (column_key names the field; column_keys lists the values in that field.) When supplied together with dense_axes.columns_from, both must resolve to the same ordered list — a mismatch fails fast.

fill_value

no

Value to place in cells with no matching relation row. Default: empty string.

dense_axes

no

Map with optional rows_from and/or columns_from keys. Each specifies an entity frame and key field whose unique values drive the corresponding axis. When columns_from is supplied, the resolved value list must match any explicit column_keys exactly (consistency contract, not precedence).

drop_source

no

Assert that the contracted matrix fully supersedes the relation and mark the relation for carrier-neutral final domain cleanup (_meta.pipeline_cleanup). Rejected when the relation carries fields beyond row_keys + column_key + value (the matrix represents nothing else), or when the matrix columns do not cover every relation column key (a matrix that silently drops relation pairs cannot supersede the relation). Default: false.

name

no

Override the step name shown in logs.

Losslessness condition: lossless when relation rows are unique per (row_keys, column_key) combination. With drop_source: true, uncovered relation column keys fail fast instead of silently dropping pairs.

Persisted XRef intent

Both steps record one entry under _meta.xref_crosstable.<id> holding the minimal feature-local inverse intent: relation and matrix frame names, row_keys, and optional dense_axes.rows_from / columns_from. The relation / matrix names may legitimately reference a frame that final domain cleanup has removed — a reverse pipeline needs exactly that intent to recreate the absent side. Run-local resolution (column_keys, dense_axes.resolved) never survives the persistence boundary. When intent is looked up by frame name and more than one entry matches, the lookup fails (in the transformations, in sparse-default targeting, and in column-role resolution alike); name the intended transform explicitly — or pass explicit key_columns to role-consuming steps — to disambiguate.

Carrier-stable column identities

XRef distinguishes matrix-axis identities from physical frame column labels, and applies a different rule to each.

Matrix-axis identities — the values that participate in the persisted matrix/relation roundtrip — must be unique, non-empty strings. Spreadsheet carriers realize matrix headers as strings, so numeric, missing (None/NaN/pd.NA), mixed-type (1 vs "1"), duplicate, or unhashable identities would silently change type, collide, or produce non-scalar cells on readback. Both steps enforce this on every axis-identity source — relation column_key values, explicit and metadata-derived column_keys, dense-axis-derived identities (live and stored), scoped base_relation column identities, and the full physical matrix header row (matrix headers are themselves axis identities) — and fail with explicit diagnostics before any drop_source cleanup command is recorded. Explicit value_columns are validated as axis identities before they are compared against row_keys, so a missing, numeric, or array-valued selector fails with the same diagnostic rather than a raw pandas/NumPy error.

Physical frame column labels — the labels used to address a column on a participating relation or base_relation frame — carry a weaker, still strict contract: they must be non-missing, hashable, uniquely and deterministically comparable, and safe for scalar column selection (so row[label] yields a scalar, never a Series). They are not required to be strings: a unique numeric label, for example, is accepted. Missing-like (None/NaN/pd.NA), ambiguous-equality (for example a multi-element array), unhashable (for example a Python list), or duplicate physical labels are rejected before any output or cleanup. Hierarchical/tuple physical labels and the separation of stable technical identity from visible header labels remain future design work; they are neither promised nor prohibited by a global string-only rule.

Malformed field declarations fail the same way, before any output or cleanup: duplicate physical column labels on the relation, matrix, or base_relation frame; duplicate configured row_keys; and explicit value_columns that overlap row_keys.

row_keys and dense-axis selectors are narrower still. A physical label is nominated as a durable selector reference the moment it is configured as row_keys (either step) or a dense-axis rows_from/columns_from key/keys — directly, or inherited through Compact Multiaxis’s forwarding. That selection is also persisted as _meta intent, so the label must additionally be an exact, non-empty native string (type(value) is str and value != "", no coercion): only a string physical column label reloads under the identical name on every currently maintained carrier (JSON directory, XLSX, ODS). A numeric physical label, for example, is no longer accepted in this specific role, even though it remains a fully legal ordinary physical column label everywhere it is not nominated as a selector. Whitespace-only strings remain accepted.

- step: contract_xref
  relation: permission_rows
  output: role_permissions
  row_keys: role_id
column_key vs column_keys

column_key and column_keys look similar but carry different information:

Parameter Meaning

column_key

Field name — the name of the field in the long/relation frame that holds the column-axis address (e.g. character_name, context_id, product_id).

column_keys

Value list — an explicit, ordered list of concrete axis values that become the visible matrix columns (e.g. [Galli, Donzo, Rexi]).

Example: character_name is the field name; Galli, Donzo, Rexi are the values.

- step: contract_xref
  relation: story_cast_role_named
  output: story_cast_role_matrix
  row_keys: [story_id]
  column_key: character_name      # field name in the relation
  column_keys: [Galli, Donzo, Rexi]   # concrete axis values
  value: value

column_key does not have to be a technical primary key. A configured unique alternate key (such as character_name) is valid when it is declared unique.

Column-axis key sources (contract_xref only):

  1. column_keys only → list used directly.

  2. dense_axes.columns_from only → list resolved from the entity frame at runtime.

  3. Both supplied → must match exactly; a mismatch fails fast (consistency contract, not precedence).

  4. Neither → falls back to column_keys stored in meta from a prior run, then to relation column order.

Sparse-default cells and expand_xref

expand_xref does not interpret sparse-default metadata. If blank cells in the matrix represent a compressed default (introduced by sparse_collapse), run sparse_expand before expand_xref to restore explicit default values. sparse_collapse / sparse_expand are separate transformations with their own registered steps.


decode_cell_values / encode_cell_values

Category: primitive · Inverse: conditionally bijective

Decode a compact cell string (e.g. "A,B,C") into one row per code, or encode code rows back into a compact cell string. Used inside the compact multiaxis chain or independently for coded single-column cells.

See also: concept doc technical_model/ch04_concepts/compact_transforms.adoc.

Both steps require explicit codec intent; there is no metadata fallback and no _meta.cell_codecs entries are written. Two contracts exist:

  • Position-based (codec_intent): several participating columns are joined into one compact column and split back by position.

  • Historical code-row (mode + codec parameters): rows of codes are joined into a delimited cell and split back. Consumed primarily by the compact-multiaxis composition; available directly when mode is passed explicitly.

Cell Codec is string-oriented and writes no metadata

Cell Codec follows the string substrate (ADR-VISIBLE-CELL-TYPING-STRING-SUBSTRATE): position-based participating values must be non-empty strings or empty; numeric, boolean, or date values fail with an explicit diagnostic instead of silently changing type through the compact-cell roundtrip. Empty and missing values encode as the configured absent_value token and decode back to "". There is no escaping or quoting. The position grammar keeps encode unambiguously decodable with a narrow rule: codec_intent.separator must be exactly one Unicode character. Because the separator is a single character, and a real value containing the separator fails encoding while the absent marker must not contain it, an accepted encode joins tokens that contain no separator character, so no separator occurrence can be formed across a token boundary and decode recovers the same fields. (A multi-character separator does not have this property and is rejected.) A split_tokens historical token containing its delimiter also fails serialization. Duplicate physical column labels, duplicate configured columns, and output-column collisions fail before any output is produced. Codec intent lives entirely in explicit step configuration; no _meta.cell_codecs entries are produced (legacy entries in old sidecars or workbooks are ignored pass-through sediment).

Position-based codec_intent (same mapping for both steps)

Key Required Description

participating_columns

yes

Ordered structured columns joined into (encode) or recreated from (decode) the compact cell. Must be unique and must exist on the encode source; on decode they must not already exist next to the compact column.

compact_column

yes

Name of the compact cell column. Must not be a participating column and must not collide with a passthrough column.

separator

yes

Token separator inside the compact cell. Must be exactly one Unicode character (no-escaping grammar). Values containing it fail encoding.

absent_value

yes

Token representing an empty/missing attribute. Must differ from the separator and must not contain it; a real value equal to it fails encoding; decodes to "".

- step: encode_cell_values
  source: profiles
  output: profiles_compact
  codec_intent:
    participating_columns: [delivery, language, auth]
    compact_column: profile
    separator: "/"
    absent_value: "-"

decode_cell_values historical code-row parameters

Parameter Required Description

source

yes

Name of the input frame containing encoded cell strings.

output

yes

Name of the output frame with one row per decoded token.

mode

yes (for this contract)

whole_cell_code (the entire cell is one code; punctuation such as - stays part of the code) or split_tokens (split on delimiter).

value

no

Column in source holding the encoded string. Default: value.

code

no

Column name in output for the decoded token. Default: code.

passthrough_columns

no

Columns from source to copy unchanged into every output row. Default: every non-value column.

drop_empty

no

If true (default), empty cells produce no output row; if false, an empty cell produces one row with an empty token.

delimiter

no

Token separator for split_tokens mode. Default: -.

allowed_codes / allowed_tokens

no

Explicit list of valid code/token strings. Validation fails on unknown values.

allowed_from_legend

no

Name of a legend block from which to derive the allowed-value set.

normalize_case

no

upper, lower, or omit to leave case unchanged.

strip

no

If true, strip whitespace from each token. Default: false.

name

no

Override the step name shown in logs.

Losslessness condition: lossless when drop_empty: false and token order is preserved (or canonical_order is set on the encode side).

- step: decode_cell_values
  source: assignments
  output: assignment_codes
  mode: split_tokens
  value: codes
  code: code
  delimiter: ","
  passthrough_columns: [employee_id, project_id]

allowed_from_legend refers to a legend block authored under meta.legend_blocks. You may author legend blocks as either a mapping keyed by block name or a list of block mappings — for a list, the block name is taken from name, then id, then a positional legend<n> fallback:

# Mapping form (canonical)
_meta:
  legend_blocks:
    status_codes:
      entries:
        - {token: A, label: Active}

# List form (equivalent authoring sugar)
_meta:
  legend_blocks:
    - name: status_codes
      entries:
        - {token: A, label: Active}

Both forms are accepted through the CLI/config path and are equivalent: the library normalizes list form to the canonical mapping automatically, and persisted output is always mapping form. Authoring the same block name twice (or a positional name that collides with an explicit one) is rejected.

encode_cell_values historical code-row parameters

Parameter Required Description

source

yes

Name of the input frame with one row per code.

output

yes

Name of the output frame with encoded cell strings.

group_by

yes (for this contract)

Column name(s) to group rows before joining into a cell string. Must be unique.

mode

yes (for this contract)

Matches decode_cell_values mode (whole_cell_code / split_tokens).

code

no

Column containing the token to encode. Default: code.

value

no

Column name in output for the encoded string. Default: value.

delimiter

no

Separator for split_tokens mode. Default: -. A token containing the delimiter fails serialization (the cell would be ambiguous to decode).

canonical_order

no

Explicit ordered list of codes; determines output token order.

allowed_codes / allowed_tokens

no

Validation whitelist.

allowed_from_legend

no

Legend block name for allowed-value derivation.

normalize_case

no

upper, lower, or omit.

strip

no

Strip whitespace before encoding.

name

no

Override the step name shown in logs.

- step: encode_cell_values
  source: assignment_codes
  output: assignments
  mode: split_tokens
  group_by: [employee_id, project_id]
  code: code
  value: codes
  delimiter: ","

expand_compact_multiaxis / contract_compact_multiaxis

Category: composite · Inverse: conditionally bijective

Compose expand_xref and decode_cell_values (or their inverses) to handle compact multi-axis matrices where each cell encodes multiple coded values. Parameters are a superset of the two constituent steps.

The steps use explicit configuration. Their persisted _meta.compact_multiaxis entry is a diagnostics-only trace and is never read as configuration or inverse intent. XRef metadata created for the internal temporary relation is suppressed before the composite returns. Sparse Defaults is not part of this composite; configure sparse_collapse / sparse_expand separately when needed.

expand_compact_multiaxis accepts an optional base_canonical_relation for scoped recomposition of partial spreadsheet projections. It names a frame holding the canonical relation [*row_keys, column_key, code (, group)] (the pre-codec shape the composite produces on the forward path) — not the compact XRef-boundary shape that the expand_xref base_relation parameter takes. When supplied, the composite Cell-Codec-encodes that canonical base under the same effective codec configuration to the compact encoded relation, hands it to the wrapped expand_xref as its base_relation, and decodes the merged result. Rows outside the visible matrix scope are preserved; matrix-covered addresses replace (or, when cleared, delete) exactly the visible scope; no parallel merge logic exists in the composite. Omitting the parameter reproduces the pre-existing full-replacement behavior, so full-matrix pipelines are unaffected. See functional_model/ch04_use_case_concepts/compact_multiaxis.adoc and FTR-COMPACT-MULTIAXIS-SCOPED-RECOMPOSITION-P4A.

Full parameter documentation planned.


split_by_discriminator / merge_by_discriminator

Category: primitive · Inverse: conditionally bijective

Split one frame into multiple named frames partitioned by a discriminator column value, recording frame-name → discriminator mapping in meta. merge_by_discriminator reconstructs the original frame from the split parts.

Full parameter documentation planned.


sparse_collapse / sparse_expand

Category: primitive · Inverse: conditionally bijective

Replace configured default values in editable crosstable cells with a sparse blank placeholder (sparse_collapse), or restore blanks to the configured default (sparse_expand). Used to make sparse matrices more readable in spreadsheet form.

Full parameter documentation planned.


flatten_headers / unflatten_headers

Category: primitive · Inverse: conditionally bijective

Flatten MultiIndex or tuple-like DataFrame column headers into scalar string labels (flatten_headers), or split scalar string headers back into MultiIndex form (unflatten_headers).

Full parameter documentation planned.


project_axis_labels / restore_axis_keys

Category: primitive · Inverse: conditionally bijective

Swap the axis-identity vocabulary of a relation’s axis-identity column (default column_key) between stable canonical keys and readable, flat one-level visible labels, composed around unchanged contract_xref / expand_xref. project_axis_labels (outbound) replaces each canonical key with its visible label so a following contract_xref renders readable matrix headers; restore_axis_keys (inbound) replaces each visible label produced by expand_xref with its canonical key. XRef still owns matrix/relation shape and cell addressing — only the axis-key vocabulary changes.

The bijection is resolved on every run from a live source frame mapping a canonical key column to a single visible-label column, via the reviewed axis mapping resolver (FTR-XREF-AXIS-MAPPINGS-P4A2 Slice 1). Nothing is persisted: if the source frame is absent, the step fails rather than trusting stale or visible text. This slice is flat one-level only; hierarchical (tuple) labels and grouped multi-row headers are later slices.

Typical outbound placement: project_axis_labels → contract_xref. Typical inbound placement: expand_xref → restore_axis_keys.

Parameter Required Description

relation

yes

Name of the input relation frame. Outbound: canonical keys in its axis-identity column. Inbound: visible labels in its axis-identity column (typically the expand_xref output).

output

yes

Name of the output relation frame to produce (a new frame; the input relation is not mutated).

source_frame

yes

Name of the live frame holding the key/label mapping. Read on every run and never persisted.

key_column

yes

Column in source_frame holding the canonical axis keys.

label_column

yes

Column in source_frame holding the single visible label per key (flat one-level).

order_policy

no

source_row (default) or columns, forwarded to the resolver. It affects only the resolver’s internal member order, which value substitution does not consume, so a projection roundtrip is identical under both policies. source_row order is defined relative to the caller-supplied source_frame row order; this step defines no serialized ordering contract.

order_columns

no

Ordered column names used when order_policy: columns. Default: empty.

column_key

no

Field name in the relation that holds the axis identity (default: the literal column_key; configure it to match the surrounding XRef steps).

drop_source

no

Assert that the projected output supersedes the input relation and mark the relation for carrier-neutral final domain cleanup (_meta.pipeline_cleanup). Requires a distinct output. Because this is a one-to-one column substitution, no rows or columns are lost, so no value-loss guard applies. Default: false.

Losslessness condition: an exact bijection when the inverse step resolves the same key/label mapping from the same live source_frame and configuration. A canonical key used by the relation but missing from the mapping source (outbound), or a visible label that does not resolve to a canonical key (inbound), fails fast before any output or _meta mutation is published. Duplicate source keys or duplicate visible labels fail the bijection. Existing flat XRef pipelines that already carry readable names as their axis key remain valid and unaffected; axis projection is opt-in.

# outbound: canonical keys -> readable labels, then contract to a matrix
- step: project_axis_labels
  relation: story_cast_role
  output: story_cast_role_named
  source_frame: characters
  key_column: char_id
  label_column: char_name
- step: contract_xref
  relation: story_cast_role_named
  output: story_cast_role_matrix
  row_keys: [story_id]

# inbound: expand the edited matrix, then restore canonical keys
- step: expand_xref
  matrix: story_cast_role_matrix
  output: story_cast_role_named
  row_keys: [story_id]
- step: restore_axis_keys
  relation: story_cast_role_named
  output: story_cast_role
  source_frame: characters
  key_column: char_id
  label_column: char_name
contract_grouped_xref / expand_grouped_xref

Category: composite · Inverse: conditionally bijective

Project a canonical relation onto a grouped matrix whose dynamic column headers carry multi-level visible label tuples (for example ("Kredit", "Annuitätendarlehen")), and restore it exactly. contract_grouped_xref runs unchanged contract_xref to build the flat canonical matrix, then attaches the visible label tuples; expand_grouped_xref restores the canonical headers and runs unchanged expand_xref. XRef still owns matrix/relation shape and cell addressing; the resolver (FTR-XREF-AXIS-MAPPINGS-P4A2 Slice 1) owns the key/label bijection.

Unlike the flat project_axis_labels / restore_axis_keys pair, which swaps a relation column between a canonical key and a single flat label, the grouped composites carry an arity-N visible tuple per dynamic column and keep the flat canonical matrix and its descriptor together.

Runtime representation. contract_grouped_xref publishes a GroupedMatrix under output: an internal domain carrier bundling the flat canonical-string matrix DataFrame with a GroupedHeader descriptor of the per-column visible tuples. Since GX-3b/GX-4 it is also a workbook carrier: a GroupedMatrix composes into an exact multi-row header grid for both XLSX and ODS, and GX-5 makes that path reachable through the public configuration surface (see Configured grouped workbook roundtrip below).

expand_grouped_xref reads the GroupedMatrix from its matrix frame. It exposes no descriptor parameter. Raw GroupedMatrix(…​) construction is rejected; grouped_matrix_from_canonical(frame, header, mapping=…​) is the public construction seam and proves that the current canonical flat column schema projects to exactly the supplied descriptor. The inverse repeats that proof under its live mapping before restoration, so reordered dynamic columns, moved row keys, stale descriptors, MultiIndex, and altered headers fail rather than silently assigning values to different canonical keys. Matrix cell values remain intentionally editable; the pairing check concerns column identity and position, not value immutability.

The axis mapping is resolved on every run from a live source frame mapping a canonical key column to N ordered visible-label columns. Nothing is persisted: if the source frame is absent, the step fails rather than trusting stale or visible text. xref_config_id is forwarded to the wrapped XRef step and selects its _meta.xref_crosstable identity; metadata ownership stays with XRef. In YAML, name is instead the generic pipeline step/log name and is never an XRef config ID. The grouped composites add no metadata root and persist no mapping, resolution, fingerprint, or header depth.

Workbook readback (GX-3b/GX-4) reconstructs exact visible tuples, resolves the live mapping, restores a canonical flat string header sequence in physical order, and enters through grouped_matrix_from_canonical via the reconstruct_grouped_matrix step. GX-2 itself added no XLSX/ODS read/write; that carrier support arrived in GX-3b/GX-4 and became publicly configurable in GX-5.

Typical forward placement: contract_grouped_xref alone (it wraps contract_xref). Typical inverse placement: expand_grouped_xref alone (it wraps expand_xref).

Parameter Required Description

relation / matrix

yes

Forward relation: the input canonical relation frame. Inverse matrix: the input frame holding a validated GroupedMatrix carrier (a bare DataFrame or direct raw construction is rejected).

output

yes

Name of the output frame to produce (a new frame; the input is not mutated). Forward: the GroupedMatrix. Inverse: the canonical relation.

row_keys

yes

Row-identity column(s), forwarded to XRef and used to classify row-key vs dynamic columns. A string, list, tuple, or one-shot iterable is owned once as a tuple; XRef retains element/duplicate/existence validation.

source_frame

yes

Name of the live frame holding the key/label mapping. Read on every run and never persisted.

key_column

yes

Column in source_frame holding the canonical axis keys.

label_columns

yes

Ordered columns in source_frame holding the visible label per level (top to leaf). Their count is the tuple depth.

column_key / value

no

Forwarded to XRef (defaults column_key / value).

column_keys / dense_axes / fill_value

no

Forward only, forwarded to contract_xref.

value_columns / base_relation

no

Inverse only, forwarded to expand_xref.

level_names

no

Forward only. Descriptor level names (top to leaf); defaults to label_columns.

order_policy / order_columns

no

source_row (default) or columns, forwarded to the resolver. They affect only resolver member order, which the header projection does not consume, so a roundtrip is identical under both policies.

drop_source

no

Assert that the output supersedes the input and mark the input for carrier-neutral final domain cleanup (_meta.pipeline_cleanup), only on full success. Forward marks relation; inverse marks matrix. Requires a distinct output. XRef’s own value-loss guards remain authoritative. Default: false.

xref_config_id

no

Exact optional XRef metadata identity. Direct Python and YAML use this same spelling; it is forwarded to unchanged XRef. When omitted, XRef keeps its relation/output fallback.

name (YAML/config only)

no

Generic pipeline step name used for logs. Consumed by the builder and not passed to contract_grouped_xref / expand_grouped_xref; direct Python calls have no grouped name parameter.

Losslessness condition: an exact bijection when the inverse resolves the same key/label mapping from the same live source_frame and configuration. A used canonical key missing from the source (forward), or a visible tuple that no longer resolves — for example after the source mapping changed between runs (inverse) — fails fast before any output or _meta mutation is published. Duplicate source keys or duplicate complete visible tuples fail the bijection. As with flat XRef, a sparse relation densifies through contract_xref’s `fill_value; use a dense relation (or XRef’s drop_empty on the flat path) when an exact relation roundtrip is required.

# forward: canonical relation -> grouped matrix (visible label tuples on headers)
- step: contract_grouped_xref
  name: contract_loan_terms_for_log
  xref_config_id: loan_product_axis
  relation: loan_terms
  output: loan_terms_matrix
  row_keys: [account_id]
  source_frame: products
  key_column: product_id
  label_columns: [category, product]

# inverse: grouped matrix -> canonical relation
- step: expand_grouped_xref
  name: expand_loan_terms_for_log
  xref_config_id: loan_product_axis
  matrix: loan_terms_matrix
  output: loan_terms
  row_keys: [account_id]
  source_frame: products
  key_column: product_id
  label_columns: [category, product]

Configured grouped workbook roundtrip (GX-5). The grouped carrier reaches a real XLSX/ODS file through the public configuration path. configure_workbook_view selects the GroupedMatrix frame and renames its physical sheet; the router-facing save_xlsx / save_ods savers preserve the carrier to the exact multi-row header grid. On readback, the opt-in exact_header_depths backend option (keyed by the physical visible sheet name, value = tuple depth) yields a core.ExactTable, apply_workbook_view_sheet_mappings re-keys that visible sheet to the logical frame, and reconstruct_grouped_matrix → expand_grouped_xref restores the canonical relation. A grouped sheet supports inclusion, order, and rename only: helper_columns, editable_columns, protection, and generic per-sheet options are rejected for a grouped sheet because grouped identity is the full visible tuple.

# forward: build the grouped matrix, then declare the renamed visible sheet
- step: contract_grouped_xref
  relation: loan_terms
  output: loan_terms_matrix
  row_keys: [account_id]
  source_frame: products
  key_column: product_id
  label_columns: [category, product]
- step: configure_workbook_view
  sheets:
    - frame: loan_terms_matrix
      sheet: Loan Terms Matrix        # renamed physical sheet
# ... then orchestrate/save through the router saver (save_xlsx / save_ods)

# reverse: load with exact_header_depths[physical sheet], then remap + expand
#   input.options.extra.exact_header_depths: {"Loan Terms Matrix": 2}
- step: apply_workbook_view_sheet_mappings
  logical_frames: [loan_terms_matrix]
- step: reconstruct_grouped_matrix
  table: loan_terms_matrix
  output: loan_terms_matrix_rebuilt
  row_keys: [account_id]
  source_frame: products
  key_column: product_id
  label_columns: [category, product]
- step: expand_grouped_xref
  matrix: loan_terms_matrix_rebuilt
  output: loan_terms
  row_keys: [account_id]
  source_frame: products
  key_column: product_id
  label_columns: [category, product]
Supporting Steps

The following steps handle FK helpers, validation, configuration, and infrastructure concerns. Full parameter documentation is planned; this table gives the step name, category, inverse kind, and purpose for quick reference.

FK Helpers and Lookup

FK-helper primitives are policy consumers: they read the v2 relation policy under meta.helper_policies.fk (and derived helper provenance under _meta.derived.sheets.*.helper_columns). Either configure_fk_helpers (explicit / manual policy) or infer_fk_relations (heuristic policy) must run before add_fk_helpers, reorder_fk_helpers, validate_fk_helpers, and remove_fk_helpers. Missing policy is a clear error that names the producer step; primitives no longer infer relations from column names. The cell-level id(<target>) convention is the wire format on roundtrip and the default heuristic of infer_fk_relations; it is no longer interpreted by primitives.

Step Category Inverse Purpose

infer_fk_relations

configuration

configuration-only

Heuristic producer: scan data frames and write v2 FK relation policy under meta.helper_policies.fk with produced_by.mode: naming_convention (currently the only mode). Use it when FK columns follow the id(<target>) convention.

configure_fk_helpers

configuration

configuration-only

Explicit / manual producer: take per-target policy from the YAML and write the v2 relation list under _meta.helper_policies.fk with produced_by.mode: explicit. Use it when you want to spell relations, helper fields, and target_key out by hand.

add_fk_helpers

primitive

projection-only

Materialize FK helper columns from the v2 relation policy. Requires that configure_fk_helpers or infer_fk_relations ran earlier. Writes derived helper provenance for later cleanup and validation.

reorder_fk_helpers

primitive

relation-preserving

Move FK helper columns next to their FK column using derived helper provenance and the v2 relation policy. Does not consult FK_PATTERN.

validate_fk_helpers

primitive

validation-only

Validate FK-helper consistency against the v2 relation policy and derived helper provenance (no convention inference).

remove_fk_helpers

primitive

projection-only

Remove materialized FK helper columns using the derived provenance written by add_fk_helpers. Frames without provenance or explicit policy are an error. Recovery from externally-edited workbooks without provenance is a separate opt-in concern and is not part of this step.

add_lookup_helpers

primitive

projection-only

Join a source frame to a lookup frame and materialize helper columns. The join key is symmetric by default (key/keys, one name present in both frames); the opt-in source_key/lookup_key pair matches a source-side key against a differently named lookup-side key. Only the source key appears in the output. An explicit source_key/lookup_key pair is authoritative for join-key selection: it ignores a configured helper-policy key while still consuming the policy’s non-key settings (helper fields, allowed fields, order, missing behaviour, and helper value mode). A symmetric inline key, by contrast, is reconciled against the policy key and fails on conflict. A requested helper or temporary sort field that equals the source key or the lookup key is rejected with a clear error before projection, so the source key is never overwritten and the lookup key never leaks; this holds even when the explicit asymmetric key names are equal (sorting by that key stays valid). Requesting the same helper column twice is rejected before projection so output labels and provenance stay unambiguous.

configure_lookup_helpers

configuration

configuration-only

Resolve lookup-helper policy and persist it as canonical metadata.

Helper value mode: formula vs. values

add_fk_helpers and add_lookup_helpers accept a helper_value_mode setting. values (the default) materializes a plain copied value in each helper cell. formula instead writes a backend-neutral lookup-formula intent that the writer renders as a live spreadsheet formula, so the helper cell recalculates when the source FK value changes.

On the ODS backend, formula mode requires a LibreOffice version with XLOOKUP support (verified against LibreOffice 25.2.3.2); the ODS writer serializes the lookup as LibreOffice’s extension-qualified COM.MICROSOFT.XLOOKUP, since plain XLOOKUP is not part of the standard OpenFormula vocabulary and LibreOffice does not recognize it as a valid name. helper_value_mode: values remains the broader-compatibility fallback for spreadsheet applications or versions without live-formula support; unlike formula mode it does not update the displayed helper value when the source FK is edited without a full re-export.

Validation
Step Category Inverse Purpose

add_validations

configuration

validation-only

Write validation constraints into workbook metadata for later rendering.

validate_references

primitive

validation-only

Validate frame contracts (required_columns, non_empty), PK, uniqueness, FK, reference-tuple integrity, and no_helper_columns assertion rules against frame data.

validate_graph

primitive

validation-only

Validate node/edge networks for endpoint existence and duplicate edge identities.

validate

primitive

validation-only

Validate duplicate IDs and unresolved FK references with severity policy. (transitional status — prefer validate_references)

validate_references frame-contract rules are consumer-neutral and, like the other rule types, honour when / enabled_when and the step’s mode:

- step: validate_references
  mode: fail
  rules:
    # The frame exists and has these columns; `exact: true` also rejects any
    # other column. Column order is never part of the contract.
    - {type: required_columns, frame: products, columns: [id, name, kind], exact: true}
    # Every listed cell holds a value (not missing, null or the empty string);
    # `trimmed: true` also rejects text with leading or trailing whitespace.
    - {type: non_empty, frame: products, columns: [id, name, kind], trimmed: true}
    - {type: primary_key, frame: products, columns: [id]}

A missing frame or missing column is reported as a finding rather than raised, so every problem of a run is listed together.

add_validations supports explicit column targets and role-based targets. For dynamic workbook views, prefer an explicit frame: when using roles:. The sheet: field names the visible workbook sheet where the validation is rendered. The frame: field names the frame used for column-role resolution. In projected workbook views, this is usually the semantic source frame that carries row-key, xref, helper-column, or other role metadata; it is not necessarily the final display/helper frame used to render the visible sheet. frame: may be omitted when the visible sheet and role-resolution frame are unambiguous, but keeping it explicit is recommended for consumer pipelines that use projected workbook views.

- step: add_validations
  rules:
    - target:
        sheet: story_groups
        frame: story_group_matrix
        roles: [matrix_value]
      rule:
        type: from_legend
        legend: story_group_codes
        include_empty: true

roles: accepts the foundation roles row_identity, display_helper, and matrix_value. It is mutually exclusive with explicit column: or columns: targets. Use roles: [matrix_value] for dynamic matrix value columns that previously required consumer-side fan-out plugins such as add_from_legend_constraints_for_matrix.

Configuration
Step Category Inverse Purpose

configure_workbook_view

configuration

configuration-only

Declare which prepared frames render as workbook sheets (names, order, protection, helper/editable columns, and concrete renderer options).

apply_workbook_view_sheet_mappings

primitive

relation-preserving

Re-key visible sheets to logical workbook-view frames on readback using persisted mappings.

apply_derived_column_policy

primitive

projection-only

Drop helper/derived columns using registered _meta.derived provenance, falling back to durable workbook-view helper declarations (_meta.sheets.<frame>.helper_columns) for drop identity after workbook reimport. Pair with validate_references / no_helper_columns when the pipeline should assert that cleanup happened before writing canonical data.

configure_pipeline_cleanup

configuration

configuration-only

Declare the carrier-neutral final domain cleanup: either name frames to drop (drop_frames) or name the final frame set to retain (keep_frames). The orchestrator executes and consumes these commands implicitly before the output adapter runs.

Practical Workbook View Roundtrip

Use configure_workbook_view after the transformations that prepare the logical frames intended for the workbook. Each frame is the configured logical frame name used by the pipeline. Each sheet is the distinct name shown to a spreadsheet user. The order of the sheets declarations is the physical order of the visible sheets.

Without an explicit workbook_view.sheets list, every remaining logical frame is selected. With the list, it is authoritative. Workbook rendering does not infer inclusion or omission from frame names, canonicality, roles, provenance, or legacy lifecycle fields.

For example, assume earlier forward steps have prepared task_matrix_view, project_summary_view, and reference_codes:

pipeline:
  # Earlier steps prepare the three logical frames used below.
  - step: configure_workbook_view
    sheets:
      - frame: task_matrix_view
        sheet: Tasks
      - frame: project_summary_view
        sheet: Summary
      - frame: reference_codes
        sheet: Reference Codes

This declaration produces the visible order Tasks, Summary, then Reference Codes. The order is intentional; it is not derived from lexical frame or sheet-name sorting.

On reimport, apply the persisted sheet mappings before any downstream step that addresses a configured logical frame or, where applicable, reverses a logical projection back into its canonical source frame:

pipeline:
  - step: apply_workbook_view_sheet_mappings

  # Later steps may now address task_matrix_view and the other logical frames.
  # A matching reverse transformation may subsequently update canonical data.

The concrete relationships in this example are:

  • task_matrix_view is the logical frame prepared for and referenced by the Workbook View;

  • tasks may be the source frame that a preceding transformation projected into task_matrix_view — that relationship lives in the transformation family’s own metadata (for example xref_crosstable intent), not in the Workbook View mapping;

  • Tasks is the visible sheet name; and

  • its declaration as the first visible sheet gives it the first physical position in this configuration.

These are practical relationships among frames, names, mappings, and order, not new identity types. Workbook View does not create the source frame or the logical projection; the relevant transformations do that before export and, where applicable, reverse it after reimport. The persisted mapping records only visible-sheet-to-logical-frame identity (sheet and frame).

The persisted _meta.workbook_view.sheet_mappings entries are authoritative on reimport. apply_workbook_view_sheet_mappings uses them to re-key Tasks back to task_matrix_view. It does not infer the logical frame from a visible label or physical position. Reordering visible sheets therefore does not change their logical-frame associations while the persisted mapping remains intact.

The mapping contract fails instead of guessing when the Workbook View mapping metadata is missing or malformed, when visible-sheet or logical-frame mappings are duplicated, when an actual visible sheet is undeclared, or when a declared visible sheet is missing from the workbook.

For the conceptual boundary and its separation from domain transformations, see the Functional Model’s Workbook View Boundary.

Removing a read-only display helper before the inverse

When a Workbook View sheet carries a read-only display helper (for example a title column materialized before the row key by add_lookup_helpers), remove that helper on reimport by the visible sheet name, before apply_workbook_view_sheet_mappings. This ordering is a public sequencing contract, not an implementation detail:

  • The durable helper identity after workbook readback comes from _meta.sheets.<visible-sheet>.helper_columns, written by configure_workbook_view and preserved across the persistence boundary.

  • The transient _meta.derived lookup provenance that add_lookup_helpers writes in-run is not the carrier across persistence; it is pruned at the boundary, so inbound cleanup cannot rely on it.

  • apply_workbook_view_sheet_mappings re-keys frames from the visible sheet name to the logical frame name but does not re-key _meta.sheets. After mapping, apply_derived_column_policy addressed by the logical frame name no longer finds the visible-sheet-keyed declaration and leaves the helper in place, where the XRef inverse (expand_xref / expand_compact_multiaxis) would melt it into the relation. Logical-frame cleanup after mapping is therefore not equivalent under the current metadata-key contract.

The settled inbound sequence is:

pipeline:
  - step: apply_derived_column_policy
    source: Matrix View        # the visible sheet name
    policy: drop

  - step: validate_references   # recommended cleanup postcondition
    mode: fail
    rules:
      - { type: no_helper_columns, frame: Matrix View }

  - step: apply_workbook_view_sheet_mappings
    logical_frames: [matrix_view]

  - step: expand_xref           # or expand_compact_multiaxis
    matrix: matrix_view
    # ...

Core cannot infer that a particular consumer column is a display helper from its name: the removal binds only to the declared _meta.sheets.<visible-sheet>.helper_columns. An edited read-only helper value is discarded under policy: drop (the drop is value-blind); it is never melted into the relation or written back to the authoritative lookup.

The no_helper_columns guard is declaration-bound, not a declaration-completeness check

apply_derived_column_policy and the no_helper_columns rule read the same durable declaration, _meta.sheets.<visible-sheet>.helper_columns. The guard is therefore a declaration-bound cleanup postcondition, not a declaration-completeness check.

Declaration present (helper_columns: [title]):

  • cleanup removes title;

  • the guard fails before cleanup while the declared helper is still present, and passes after successful cleanup;

  • so the guard catches an omitted or ineffective cleanup that leaves a declared helper behind.

Declaration absent or mistyped:

  • Core does not infer title by name, so cleanup obtains an empty helper set and does nothing;

  • the guard also obtains an empty helper set, reports no finding, and passes;

  • title therefore survives and the state is unsafe for the inverse, even though the guard passed.

Because both steps bind to the same declaration, pairing the drop with no_helper_columns cannot detect a missing declaration. Verifying that each Workbook View sheet actually declares its display helper is a consumer-owned static/configuration check (for the Worldbuilding matrix sheets this is Slice-3 work): statically verify helper_columns: [title] for all five matrix sheets. The inbound no_helper_columns rule remains valuable as defense in depth against a declaration-present cleanup that was omitted or left the helper behind.

Final Domain Cleanup

Pipelines that project relational data into editable views often accumulate intermediate frames that should not remain part of the final logical result. Final domain cleanup removes such frames carrier-neutrally: the cleaned frame set is what every output adapter observes, whether the output is a JSON/YAML/XML directory or a spreadsheet workbook.

Cleanup executes only explicit commands. It never infers removal from roles, canonicality, provenance, or rendering labels. Commands come from two producers:

  • a feature transformation whose own contract establishes that its source frame is fully superseded may contribute a drop command behind an explicit parameter — for example contract_xref / expand_xref with drop_source: true;

  • the pipeline builder declares cleanup with configure_pipeline_cleanup, because generic steps cannot know whether their outputs are terminal data or disposable intermediates.

The builder step supports two mutually exclusive authoring modes:

# Drop mode: name the frames to remove.
- step: configure_pipeline_cleanup
  drop_frames: [story_place_relation, story_place_named]
# Keep mode: name the final frame set; everything else is removed.
- step: configure_pipeline_cleanup
  keep_frames: [stories, characters, places]

A declaration containing both modes fails. Drop declarations compose across invocations and with transformation-produced drop commands (duplicate identical drops are idempotent). At most one keep_frames declaration may exist per run; a frame that is both kept and dropped is a conflict and fails. There is no override precedence: compatible declarations compose, contradictory declarations fail.

The cleanup itself is not a pipeline step. The orchestrator runs it implicitly after the configured steps and before the persistence boundary, then consumes the commands, so they never persist into _meta or roundtrip through a workbook. An explicit drop command targeting a frame explicitly mapped by workbook_view fails before anything is written. A keep-mode implied removal may coexist with a stale reimported mapping; structured output may retain the mapping, but a later spreadsheet render fails explicitly on the missing mapped frame before creating a workbook. Transformation intent metadata (for example xref_crosstable entries) that references a removed frame is preserved — inverse transformations need it to recreate the frame on reimport.

Note: steps that write files mid-pipeline (write_structured_yaml, write_key_value_resources) emit their artifacts before final cleanup runs; those artifacts reflect the frame state at that earlier point.

Infrastructure and Output
Step Category Inverse Purpose

bootstrap_meta

infrastructure

—

Merge profile defaults, persisted metadata, and runtime overrides into payload metadata.

apply_overrides

infrastructure

—

Load or apply workbook and sheet override metadata.

extract_frame

primitive

extraction

Derive a named frame by selecting columns, filtering rows, renaming, adding constants.

pivot_frame

primitive

projection-only

Derive a display frame by pivoting long-form rows into configured index and value columns.

join_frames

primitive

projection-only

Derive a view frame by joining two frames with configured keys, mode, and projections.

normalize_resource_overrides

primitive

projection-only

Normalize long-form resource override tuples according to a default-context and empty-value policy.

write_structured_yaml

infrastructure

extraction

Write nested YAML files from tabular frames and record a generated-file report frame.

write_key_value_resources

infrastructure

projection-only

Write key-value (.properties-style) files partitioned by template column values.

write_artifact_manifest

infrastructure

projection-only

Merge writer report frames into a deterministic manifest; optionally compute checksums.

identity

infrastructure

bijective

Return the pipeline payload unchanged. Useful as a no-op placeholder.

plugin

plugin

—

Run a caller-provided dotted callable as an explicit pipeline extension point.