The bridge that vanished inside the machine

A delivery robot approaches a river. Its camera sees the same road, the same bridge deck and the same destination marker in two moments separated by ten minutes. In the first moment the bridge controller reports open. In the second it reports closed. The robot's perception stack retains position, destination and a visual embedding, but an upstream feature-selection step drops bridge status because it was almost constant in the training set.

Both moments therefore arrive at the planner as the same vector. The planner is asked to choose between CROSS, WAIT and ESCALATE. It cannot choose correctly in both cases. More layers can fit a more complicated boundary around the vector, more search can examine more plans, and a language model can provide a more persuasive explanation. None can recover the missing bit. The downstream system sees one state where the world contains two.

If bridges were open in 99.8 per cent of the training examples, the resulting system could look highly capable. It would cross correctly almost every time, score well on a random test split and fail exactly when the rare distinction matters. Calling this a reasoning failure mislocates the cause. The failure was committed when the representation declared two consequence-distinct worlds equivalent.

This paper's central answer follows. A representation is useful relative to a family of decisions and interventions when it keeps apart any states that demand different consequences, and compresses only variation that leaves those consequences unchanged. Some distortions destroy information. Others merely arrange it awkwardly. The distinction determines whether the remedy is better data, a better encoder, a different geometry, a richer task definition or a more capable downstream model.

Part one

The cut a representation makes

A representation may be a hand-built feature table, a token sequence, a graph, a latent vector, a database row, an activation pattern or a compact controller state. These forms differ, but each performs the same basic operation. It maps something richer into something a system can use:

φ : X → Z X is the set of possible observations or world states, Z is the internal representation space, and φ is the encoder. The map may be deterministic or stochastic. The argument here begins with the deterministic case because its information losses are easiest to see.

Every such map makes a cut through the world. Whenever φ(x₁) = φ(x₂), the downstream system receives no direct evidence that x₁ and x₂ differ. The encoder has placed them in the same equivalence class. That may be exactly right. Two photographs taken under different lighting may depict the same component. Two orderings of the same unordered set should not become different cases. A thousand sensor readings may be safely reduced to a calibrated sufficient statistic.

It may also be disastrous. A representation that merges two customers, two versions of a policy, two sides of a river or two stages of a process can erase the relation that governs the decision. The representation is therefore neither intrinsically good nor bad. It is good for something.

Relations before coordinates

Suppose the system must support a family of queries or decisions Q. Two world states are task-equivalent when every member of that family gives the same answer or demands the same consequence. Write that relation as:

x₁ ≡Q x₂ ⇔ q(x₁) = q(x₂) for every q in Q q may be a prediction target, an action rule, a value function, a permitted transformation or an intervention response. The family Q is the declared use of the representation, not every imaginable future use.

A deterministic representation is sufficient for that family when it never merges states from different task-equivalence classes:

φ(x₁) = φ(x₂) ⇒ x₁ ≡Q x₂ The implication permits useful compression. Task-equivalent states may map to one code. The reverse implication is optional: a representation can keep unnecessary distinctions and remain sufficient, although it may become harder to learn from.

This formulation turns the vague demand to “capture meaning” into a falsifiable question. Which relation does the system need, and can two states that violate it reach the same code? A representation for image identity may preserve object class while discarding illumination. A representation for robotic manipulation may need both object identity and pose. A representation for a set must ignore element order if the target is genuinely permutation invariant. A representation for a process cannot ignore order when the same events in a different sequence create a different state.

A partition first, coordinates second

It helps to separate two jobs that vector language often merges. First, the representation decides a partition: which world states count as the same internal state. Second, it supplies coordinates or structure inside the resulting space: which codes are near, ordered, composable or easy to transform. Collisions are failures of the partition. Awkward neighbourhoods are failures of the coordinates relative to a bounded consumer.

Take an ordinary ceramic cup. A stock-counting system may treat every view of the same product code as equivalent. A packing system must preserve size and fragility. A grasping system must preserve pose, occlusion and handle position. A food-safety system may need material, contamination status and last-cleaned time. None of these is the uniquely true representation of the cup. Each is a different cut licensed by a different consequence.

This thought experiment also shows why “more information” is an incomplete objective. A raw photograph contains enormous detail, yet it may omit temperature, ownership or whether the cup has been sterilised. Conversely, a compact typed record may discard texture and background while preserving everything needed for the declared decision. Richness should be judged by consequence-bearing coverage, not by byte count or visual fidelity.

The partition view is especially useful when representations are distributed across components. A token sequence may preserve words, a graph may preserve entity relations, a timestamp may preserve applicability and a calibrated score may preserve uncertainty. The operational representation is the joined state presented to the decision mechanism. Auditing one embedding in isolation can miss a collision introduced by an earlier join, filter or aggregation.

The classic review by Bengio, Courville and Vincent framed representation learning around making explanatory factors easier to extract. The information bottleneck formalised a related trade: compress an input while retaining information relevant to a target. Those are powerful starting points. The unresolved design burden remains the choice of relevance. Compression does not tell us which distinctions the future decision will regret losing.

The bridge-status collision An open-bridge state and a closed-bridge state differ in one field, but an encoder that omits bridge status maps both to the same latent code, forcing a decoder to make one action for two incompatible worlds. One omitted field creates an error floor World state 1 position: west bank bridge: OPEN World state 2 position: west bank bridge: CLOSED same latent code z = 17 CROSS WAIT
Figure 2. A collision is stronger than ordinary model error.Synthetic bridge example. The two states differ only in bridge status. Once the encoder omits that field, the best decoder must choose a compromise.

A lower bound created upstream

For a discrete action target A*, a code Z = φ(X) creates a minimum possible classification error even before a decoder is chosen:

Rmin(φ) = Σz P(Z=z) [1 − maxa P(A*=a | Z=z)] For each code z, the best possible decoder selects the most likely required action a. The remaining probability mass is unavoidable error caused by the representation. A richer decoder can approach this bound; it cannot beat it without receiving more information.

This is the precise version of the bridge intuition. If open and closed states share a code, the system can only learn their frequency-weighted majority action. When the minority case is rare but consequential, average accuracy hides the structural defect. A targeted paired test exposes it immediately.

Minimal worked example: four worlds, two codes

Strip the bridge world to two relevant bits: bridge status and urgency. Let the required action be CROSS when the bridge is open, ESCALATE when it is closed and urgent, and WAIT when it is closed and not urgent. A sufficient code keeps both bits. A cheaper code keeps urgency and drops bridge status.

The cheaper code creates two buckets. In the “not urgent” bucket, the open state requires CROSS and the closed state requires WAIT. In the “urgent” bucket, the open state requires CROSS and the closed state requires ESCALATE. If all four states are equally likely, either bucket forces one error out of two. No training algorithm changes that arithmetic.

Now change the distribution so that the bridge is open in 99 cases out of 100. The same representation attains about 99 per cent accuracy by always crossing. The code has not improved. Only the test distribution has made its collision less visible. This is why a representation audit reports both population-weighted error and collision existence on consequence-critical pairs. A rare but irreversible state should not disappear merely because its denominator is small.

Add bridge status back and the hard floor vanishes. The downstream classifier may still make ordinary estimation errors, but those errors are now, in principle, repairable with data, optimisation or a better decoder. The distinction between representation error and decoder error is operationally valuable because it tells the team where another unit of effort can help.

Part two

The four distortions

Representation failures are often grouped under labels such as “bad embeddings” or “lossy features”. That language obscures the remedy. Four distinct distortions matter: collision, neighbourhood warp, wrong transformation law and temporal or causal aliasing. Only the first necessarily destroys task information. The others can preserve information while making it expensive, brittle or misleading to use.

1. Collision: consequence-distinct states become one

A collision occurs when the code identifies two states that the declared task family must distinguish. The bridge example is exact. In learned systems, collisions are often approximate: two states land so close that a bounded decoder, quantiser or retrieval rule treats them as interchangeable. The practical test is the same. Hold most of the case fixed, vary one decision-relevant feature, and ask whether the representation moves enough for the downstream mechanism to respond.

Collisions can arise from feature selection, pooling, tokenisation, truncation, aggregation, low precision, lossy compression or an objective that rewards the wrong invariance. They can also arise because the observation never contained the necessary variable. An encoder cannot preserve bridge status if no sensor or source reports it. Representation assurance begins at the system boundary, not at the latent layer.

2. Neighbourhood warp: information survives, useful geometry does not

An injective code can preserve every state while rearranging them arbitrarily. No information is lost in principle, yet the downstream learner may need more data or a more complex decision surface. A linear probe, nearest-neighbour retriever or small controller relies on local geometry. If consequence-similar states are far apart, or consequence-distinct states are close, these restricted mechanisms inherit a harder problem.

This is why claims about “semantic space” require care. Distance is not meaning by itself. It is a design commitment about which differences should be small, which should be large and under what metric. Work on contrastive learning, including the analysis by Wang and Isola, makes geometric properties such as alignment and uniformity explicit. Those properties can support downstream tasks, but they remain relative to the positive pairs, negative pairs and transformations used to train the space.

Geometry earns its keep under a restricted consumer

To test a geometry claim, fix the downstream restriction that supposedly makes geometry valuable. A linear decoder asks whether the decision can be expressed by a low-complexity boundary. A nearest-neighbour retriever asks whether local distance ranks useful evidence ahead of misleading evidence. A small controller asks whether nearby states support similar values and transitions. Each test measures a different property.

Compare candidates at matched data, decoder capacity and optimisation. Then add a high-capacity decoder. If the structured representation wins only for the restricted decoder and the gap closes with capacity, the evidence supports an efficiency claim rather than an information claim. If every decoder fails on paired states, suspect a collision. If performance is strong in distribution and collapses only when a nuisance correlation flips, suspect shortcut-supporting geometry or an unjustified invariance.

Probe accuracy alone is insufficient because a probe can discover information the deployed consumer never uses, and a flexible probe can compensate for an inconvenient code. Conversely, poor performance from one weak probe does not prove that information is absent. The stress test should therefore combine exact collision checks, several decoder classes and interventions that reflect the real consequence. Geometry is a contract between a representation, a metric and a consumer.

3. Wrong invariance: a transformation is ignored or exaggerated

Consider the same metal wrench rotated by ninety degrees. For a parts classifier, rotation may be a nuisance. The code should remain stable enough to recognise the wrench. For a robot deciding how to grasp it, orientation changes the required motion. The code should transform predictably with the wrench rather than erase pose.

invariant: φ(gx) = φ(x)     equivariant: φ(gx) = ρ(g)φ(x) g is a transformation of the input, such as rotation or permutation. An invariant code ignores it. An equivariant code changes through a known transformation ρ(g). Which law is correct depends on the action, not on the data type alone.

Group-equivariant convolutional networks show how architecture can encode a transformation law instead of relearning it from examples. Deep Sets characterises a family of permutation-invariant set functions. Lossy Compression for Lossless Prediction connects compression to tasks invariant under declared transformations. The shared lesson is not that invariance is always desirable. It is that the transformation group must be named, and the task must justify what is collapsed.

One rotation, two correct representation laws A wrench appears at zero and ninety degrees. An identity classifier maps both to the same class code, while a grasp controller maps orientation to a rotated pose code. Rotation: nuisance for identity, state for grasp Identify the part Plan the grasp WRENCH invariant identity code equivariant pose code
Figure 3. The same transformation should be erased for one task and preserved predictably for another.Thought experiment. Rotation is nuisance for identity classification and decision state for grasp control. The analogy stops at the declared tasks; real robotic state also includes occlusion, force and uncertainty.

4. Temporal and causal aliasing: the snapshot looks the same

Two screens can display the same values while representing different processes. A payment may be pending because it was never submitted, because the network timed out after submission, or because the beneficiary bank has accepted it but confirmation is delayed. The visible snapshot “pending” does not determine whether retrying is safe. History and effect evidence matter.

Sequential decision systems therefore need a stronger relation than static label sufficiency. States may be safely merged only when they offer equivalent immediate rewards and equivalent distributions over future abstract states under each action. Bisimulation metrics make this idea precise for Markov decision processes. Work such as Ferns, Panangaden and Precup, DeepMDP and bisimulation-based visual reinforcement learning ties representation distance to differences in reward and transition consequence.

The general engineering lesson is broader than reinforcement learning. If future action depends on identity, valid time, source authority, prior effects or unresolved outcome, a representation built from the latest text or snapshot alone is underspecified. World state is a relation among evidence, time and possible consequence, not merely a pile of current-looking fields.

Four representation distortions Four panels show collision, neighbourhood warp, nuisance fracture and temporal aliasing, each with a different failure signature and remedy. Four distortions require four different remedies Collision z distinct consequences, one code Neighbourhood warp information survives; locality lies Nuisance fracture same consequence split by weather Temporal alias same snapshot, different safe retry
Figure 4. “Bad representation” is not one diagnosis.Conceptual taxonomy. Collision demands more information or a different partition. Warp demands a different metric or downstream capacity. Nuisance fracture demands justified invariance. Temporal alias demands history or effect evidence.

The bijective negative control

The strongest objection to the thesis is simple. Take every relevant world state and assign it a unique random code, like a phone book whose numbers bear no relation to names, location or role. The map is bijective. Nothing has been discarded. A sufficiently expressive decoder with enough examples can invert the code and recover any target. Therefore, a tidy latent geometry is not logically required for intelligence.

The objection is correct, and it prevents an important overclaim. Information preservation and useful geometry are different properties. A scrambled bijection defeats any claim that a particular axis, cluster or smooth manifold is necessary in principle. It also reveals why mutual-information language alone cannot certify robustness, simplicity or learnability. Amjad and Geiger identify formal difficulties in applying the information-bottleneck objective to deterministic neural networks and note invariances that leave geometry unconstrained.

The practical question is bounded. The downstream system has finite data, finite compute, a restricted architecture, latency limits and a changing environment. Under those constraints, a representation that makes the required relation simple can reduce the burden on the decoder. The relevant comparison is therefore not “can any universal function approximate the answer?” It is “at matched evidence and resource, which representation supports the required behaviour and survives the declared shifts?”

The same discipline applies to disentanglement. A visually satisfying axis for colour, pose or identity is not automatically discovered or uniquely correct. Locatello et al. showed that unsupervised disentanglement requires inductive biases and that stronger disentanglement scores did not universally translate into lower downstream sample complexity. A representation claim must name the supervision, symmetry, intervention or task that makes its preferred structure identifiable and useful.

Structured and scrambled bijective codes The same eight states appear in two latent spaces. Both are one-to-one. The structured space keeps action groups locally coherent, while the scrambled space mixes them, increasing the burden on a local decoder. Same information, different downstream burden Consequence-aligned Scrambled bijection simple local boundary same states, harder locality action family A action family B Both codes are injective. Only the geometry differs.
Figure 5. The negative control separates information from geometry.Illustrative relationship. Both maps are one-to-one, so a universal decoder could recover the task. The structured map is intended to reduce the burden on local or low-capacity decoders; that benefit must be measured rather than assumed.
Published evidence

Underspecification shows that a training pipeline can produce several predictors with comparable held-out performance but materially different behaviour under deployment-relevant tests. Shortcut learning describes decision rules that succeed on standard benchmarks and fail under more demanding conditions. Neither result proves that every failure is representational, but both justify testing which relations the learned code actually uses.

Part three

From benchmark similarity to world consequence

Representation quality is often judged indirectly. A frozen embedding supports a linear probe. Nearest-neighbour retrieval looks plausible. A two-dimensional projection forms clean clusters. These observations can be useful, but none establishes that the code preserves the relation needed by a consequential workflow. A probe shows that information is decodable under one sample and model class. A cluster shows that a chosen metric and projection expose some separation. The workflow may depend on a different relation entirely.

Worked scenario

The following covenant-monitoring case is synthetic. It is designed to expose the representation burden and must not be read as a deployment claim.

Two sentences that should not become one case

Two documents contain the sentence “Net leverage is 3.8×”. A generic text embedding places the passages almost on top of one another. In Case North, the number refers to the borrower, the current agreement sets a 4.0× ceiling, the metric uses the agreement's defined EBITDA and the observation falls inside the applicable measurement period. The candidate consequence is “within threshold”.

In Case South, the same sentence refers to a guarantor, an amended agreement sets a 3.5× ceiling, the source uses a management definition rather than the contractual definition, and the document predates the effective amendment. The candidate consequence is not a simple breach conclusion. The system must first reconcile entity role, definition, valid time and source authority.

At the sentence level, the cases are semantically similar. At the decision level, they are structurally different. A representation packet for the workflow needs more than passage meaning. It must preserve at least the metric value and unit, measured entity, role, contractual definition, threshold, agreement version, valid time, observation time, source identity and evidence location. It may also need an explicit unresolved state when those relations conflict.

The correct representation is an argument-bearing state, not a prettier sentence vector. The embedding may still help find candidate passages. It should not be asked to stand in for identity resolution, temporal entitlement or policy applicability merely because all of those facts can be rendered as text.

One workflow may require several coordinated representations

The temptation to demand one universal embedding comes partly from interface convenience. A single vector fits a standard index and supports a single similarity operation. The workflow, however, asks heterogeneous questions. “Which passage discusses leverage?” is a semantic retrieval question. “Which legal entity does it bind?” is an identity and role question. “Which clause was effective on the measurement date?” is a bitemporal applicability question. “Does the value satisfy the definition and threshold?” is a deterministic comparison after evidence reconciliation.

Forcing all four questions through one distance function creates hidden trade-offs. Making passages close because they share topic can make entity-specific exceptions look interchangeable. Making time a weak feature can improve generic retrieval while returning superseded evidence. Making every identifier dominant can protect identity but destroy useful semantic recall. There may be no single neighbourhood ordering that is optimal for all stages.

A stronger design composes representations through typed interfaces. Semantic vectors produce candidates. Exact identifiers and relation edges establish entity scope. Valid-time and transaction-time fields establish what was applicable and what was knowable. Typed quantities and definitions support calculation. Evidence pointers preserve the path back to source. The final decision state can still be compact, but its compactness is earned after these relations have been resolved.

This composition also improves diagnosis. When a case fails, the trace can distinguish candidate-recall failure, identity collision, supersession error, definition mismatch and decision error. A monolithic vector may produce one wrong answer with no visible seam. Modularity is useful here because different relations require different negative controls.

Covenant case as an argument-bearing representation Two identical leverage sentences feed different decision states once entity role, agreement version, threshold, definition, time and source authority are preserved. Text similarity is upstream of decision identity “Net leverage is 3.8×” Case North entity: borrower ceiling: 4.0× definition: contractual version: current time: applicable source: authoritative WITHIN LIMIT Case South entity: guarantor ceiling: 3.5× definition: management version: superseded time: disputed source: supporting RECONCILE FIRST representation packet: value + role + rule + time + evidence
Figure 6. A production-shaped representation must preserve applicability, not just semantic resemblance.Synthetic worked scenario. The words and number are held nearly constant while role, threshold, definition, valid time and source authority change. Those relations alter the permissible next step.

Use interventions to reveal what ordinary splits conceal

Random train and test splits mostly reproduce the joint distribution from which the representation was learned. They can therefore reward stable shortcuts. A stronger test constructs pairs that vary one candidate relation at a time: current versus superseded agreement, borrower versus guarantor, open versus closed bridge, same object under changed lighting, same event set in a different order.

Interventional data is especially valuable because it shows how the code responds when one factor changes while others are controlled. Research on interventional causal representation learning establishes identifiability results under specific intervention assumptions. An engineering stress test need not claim full causal recovery. It can still borrow the method: specify the intervention, predict the required latent behaviour, then check whether the code is invariant, equivariant or deliberately sensitive.

For the covenant example, the decisive test does not ask whether passages with the same topic are close. It toggles one relation and checks the downstream consequence. Change only the agreement version. Change only the entity role. Change only the threshold. Change only source authority. If the representation remains effectively unchanged where the permissible action changes, it has failed a preservation requirement.

Design inference

For compound systems, keep representation responsibilities typed. Use embeddings for semantic candidate generation, explicit identifiers for identity, graphs or relational structures for role and linkage, temporal fields for applicability, calibrated distributions for uncertainty, and evidence references for contestability. A single vector may carry some of these relations, but the design should not assume that it has done so without a discriminating test.

Part four

Stress the representation before the model

The executable artefact turns the bridge puzzle into a small laboratory. It enumerates 32 synthetic states from five binary variables: whether the agent is already at the target, whether the bridge is open, whether its permit is valid, whether the delivery is urgent and whether it is raining. Rain is a deliberate nuisance. The other four variables can alter the present action or the response to an intervention.

The task family is wider than current-action classification. For each state, the script records the action now and after toggling each of the four relevant variables. This five-action consequence profile distinguishes a code that supports one immediate decision from a code that supports controlled counterfactual reasoning.

Action floorMinimum current-action error forced by exact code collisions.
Profile floorMinimum error when decoding the full intervention-response profile.
Weather invarianceShare of rain toggles that correctly leave the code unchanged.
Bridge sensitivityShare of consequence-changing bridge toggles that move the code.
Distance stressRoot mean square disagreement between latent distance and consequence distance.

Five candidate representations expose different failures. consequence_profile is the positive oracle. drops_bridge omits bridge status. action_only stores only the present action. nuisance_heavy preserves the full profile but also encodes rain. scrambled_bijection uniquely identifies every relevant state through random coordinates while ignoring rain.

Measured representation stress-test results Five representations are compared. The consequence profile passes all tests. Dropping bridge status causes current and counterfactual collision floors. Action only passes current action but fails counterfactual profile. Nuisance heavy fails weather invariance. Scrambled bijection preserves information but has the highest distance stress. Five codes, five failure signatures coral bars are error or stress; teal bars are required fidelity consequence_profile drops_bridge 37.5% profile floor 0% required bridge sensitivity action_only 62.5% profile floor 33.3% bridge sensitivity nuisance_heavy 0% weather invariance 0.111 distance stress scrambled_bijection 0.513 distance stress 0% floors · 100% invariance and sensitivity Measured on the included 32-state synthetic environment.
Figure 7. The stress test separates irrecoverable loss, over-compression, nuisance leakage and geometric disorder.Measured synthetic results from the included Python artefact. Percentages use all 32 enumerated states. Distance stress is unitless root mean square error after normalising latent and consequence distances to the interval from zero to one.
RepresentationAction floorProfile floorWeather invarianceBridge sensitivityDistance stress
consequence_profile0.0%0.0%100.0%100.0%0.000
drops_bridge12.5%37.5%100.0%0.0%0.355
action_only0.0%62.5%100.0%33.3%0.172
nuisance_heavy0.0%0.0%0.0%100.0%0.111
scrambled_bijection0.0%0.0%100.0%100.0%0.513

The bridge-dropping code proves the hard case. Its 12.5 per cent current-action floor is not an empirical weakness of a particular classifier. It is the best any exact-code decoder can do over this state distribution. Its 37.5 per cent profile floor shows that the damage grows when the system must reason about interventions.

The action-only code is more deceptive. It achieves a zero current-action floor because it stores the answer itself. Yet it aliases states with different responses to changed conditions, producing a 62.5 per cent profile floor. A representation can be sufficient for today's label and insufficient for tomorrow's decision.

The nuisance-heavy code loses no target information, but every weather toggle changes the code. That fragmentation can increase sample demand or enable a shortcut when weather correlates with action in the training set. The scrambled bijection is the clean negative control. It passes collision, invariance and sensitivity checks while recording the highest geometric stress. The result supports a bounded claim: geometry matters for the chosen metric and restricted downstream mechanisms, not for information recoverability in principle.

The executable core

The script uses only the Python standard library. It includes positive assertions for the consequence-aligned code, negative assertions for the bridge-dropping code and control assertions for the scrambled bijection. The expected output is the table above.

def consequence_profile(state):
    fields = ("agent_at_target", "bridge_open", "permit_valid", "urgent")
    actions = [decide(state)]
    actions.extend(decide(intervene(state, field)) for field in fields)
    return tuple(ACTION_ID[action] for action in actions)


def irreducible_error(representation, target):
    buckets = defaultdict(list)
    for state in STATES:
        buckets[representation.encode(state)].append(target(state))
    errors = sum(
        len(values) - Counter(values).most_common(1)[0][1]
        for values in buckets.values()
    )
    return errors / len(STATES)
Open the complete runnable Python artefact

Copy the code below into representation_stress_test.py and run python3 representation_stress_test.py.

#!/usr/bin/env python3
"""Representation stress test for a synthetic bridge-control world.

The test asks whether a candidate representation preserves the consequence
relations required by a family of decisions and interventions. It uses only
the Python standard library and synthetic data.

Expected use:
    python3 representation_stress_test.py
"""

from __future__ import annotations

from collections import Counter, defaultdict
from dataclasses import dataclass
from itertools import combinations, product
import math
import random
from typing import Callable, Hashable, Iterable, Sequence


ACTIONS = ("DELIVER", "CROSS", "ESCALATE", "WAIT")
ACTION_ID = {name: i for i, name in enumerate(ACTIONS)}


@dataclass(frozen=True)
class State:
    """A fully observed synthetic world state.

    weather is deliberately irrelevant to the task family. The other four
    fields can change the current decision or its response to interventions.
    """

    agent_at_target: int
    bridge_open: int
    permit_valid: int
    urgent: int
    weather_rain: int

    @property
    def relevant(self) -> tuple[int, int, int, int]:
        return (
            self.agent_at_target,
            self.bridge_open,
            self.permit_valid,
            self.urgent,
        )


def decide(state: State) -> str:
    """Return the bounded action required by the synthetic policy."""
    if state.agent_at_target:
        return "DELIVER"
    if state.bridge_open and state.permit_valid:
        return "CROSS"
    if state.urgent:
        return "ESCALATE"
    return "WAIT"


def intervene(state: State, field: str) -> State:
    """Toggle one binary field while holding every other field fixed."""
    values = state.__dict__.copy()
    values[field] = 1 - values[field]
    return State(**values)


def consequence_profile(state: State) -> tuple[int, ...]:
    """Encode the action now and after four single-variable interventions.

    The profile defines the task family used in this stress test. Weather is
    excluded because changing it never changes a required action.
    """
    fields = ("agent_at_target", "bridge_open", "permit_valid", "urgent")
    actions = [decide(state)]
    actions.extend(decide(intervene(state, field)) for field in fields)
    return tuple(ACTION_ID[action] for action in actions)


STATES = [State(*bits) for bits in product((0, 1), repeat=5)]

# A deterministic one-to-one but geometrically arbitrary code for each
# task-relevant state. It is the serious negative control: no information is
# lost, yet local distances no longer express consequence similarity.
_rng = random.Random(17)
_scrambled_points = {
    relevant: (_rng.random(), _rng.random())
    for relevant in sorted({state.relevant for state in STATES})
}


@dataclass(frozen=True)
class Representation:
    name: str
    encode: Callable[[State], Hashable]
    distance: Callable[[Hashable, Hashable], float]


def hamming_distance(a: Sequence[object], b: Sequence[object]) -> float:
    if len(a) != len(b):
        raise ValueError("Hamming distance requires equal-length codes")
    if not a:
        return 0.0
    return sum(x != y for x, y in zip(a, b)) / len(a)


def euclidean_unit_square(a: Sequence[float], b: Sequence[float]) -> float:
    return math.dist(a, b) / math.sqrt(2.0)


REPRESENTATIONS = (
    Representation(
        "consequence_profile",
        lambda s: consequence_profile(s),
        hamming_distance,
    ),
    Representation(
        "drops_bridge",
        lambda s: (s.agent_at_target, s.permit_valid, s.urgent),
        hamming_distance,
    ),
    Representation(
        "action_only",
        lambda s: (ACTION_ID[decide(s)],),
        hamming_distance,
    ),
    Representation(
        "nuisance_heavy",
        lambda s: consequence_profile(s) + (s.weather_rain,),
        hamming_distance,
    ),
    Representation(
        "scrambled_bijection",
        lambda s: _scrambled_points[s.relevant],
        euclidean_unit_square,
    ),
)


def irreducible_error(
    representation: Representation,
    target: Callable[[State], Hashable],
) -> float:
    """Minimum classification error for any decoder of an exact code."""
    buckets: dict[Hashable, list[Hashable]] = defaultdict(list)
    for state in STATES:
        buckets[representation.encode(state)].append(target(state))

    errors = 0
    for values in buckets.values():
        errors += len(values) - Counter(values).most_common(1)[0][1]
    return errors / len(STATES)


def paired_equality_rate(
    representation: Representation,
    field: str,
    predicate: Callable[[State, State], bool],
) -> float:
    """Measure whether a code changes or stays fixed across paired toggles."""
    pairs: list[tuple[State, State]] = []
    for state in STATES:
        if getattr(state, field) == 0:
            other = intervene(state, field)
            if predicate(state, other):
                pairs.append((state, other))
    if not pairs:
        return float("nan")
    equal = sum(
        representation.encode(a) == representation.encode(b) for a, b in pairs
    )
    return equal / len(pairs)


def distance_stress(representation: Representation) -> float:
    """RMSE between latent distance and consequence-profile distance."""
    squared_errors: list[float] = []
    for left, right in combinations(STATES, 2):
        semantic = hamming_distance(
            consequence_profile(left), consequence_profile(right)
        )
        latent = representation.distance(
            representation.encode(left), representation.encode(right)
        )
        squared_errors.append((latent - semantic) ** 2)
    return math.sqrt(sum(squared_errors) / len(squared_errors))


def evaluate(representation: Representation) -> dict[str, float]:
    action_floor = irreducible_error(representation, decide)
    profile_floor = irreducible_error(representation, consequence_profile)

    # Weather should be ignored because it changes no required consequence.
    weather_same = paired_equality_rate(
        representation,
        "weather_rain",
        lambda a, b: consequence_profile(a) == consequence_profile(b),
    )

    # Bridge status must remain visible whenever toggling it changes the full
    # intervention-response profile, even if the immediate action happens to
    # stay the same in a particular state.
    bridge_same_when_change_required = paired_equality_rate(
        representation,
        "bridge_open",
        lambda a, b: consequence_profile(a) != consequence_profile(b),
    )
    bridge_sensitivity = 1.0 - bridge_same_when_change_required

    return {
        "action_floor": action_floor,
        "profile_floor": profile_floor,
        "weather_invariance": weather_same,
        "bridge_sensitivity": bridge_sensitivity,
        "distance_stress": distance_stress(representation),
    }


def pct(value: float) -> str:
    return f"{100.0 * value:5.1f}%"


def main() -> None:
    print("Synthetic bridge-control representation stress test")
    print("32 states; consequence family = current action + four interventions")
    print()
    header = (
        f"{'representation':24} {'action floor':>12} {'profile floor':>13} "
        f"{'weather inv.':>13} {'bridge sens.':>13} {'distance stress':>16}"
    )
    print(header)
    print("-" * len(header))

    results = {}
    for representation in REPRESENTATIONS:
        metrics = evaluate(representation)
        results[representation.name] = metrics
        print(
            f"{representation.name:24} "
            f"{pct(metrics['action_floor']):>12} "
            f"{pct(metrics['profile_floor']):>13} "
            f"{pct(metrics['weather_invariance']):>13} "
            f"{pct(metrics['bridge_sensitivity']):>13} "
            f"{metrics['distance_stress']:16.3f}"
        )

    # Positive and negative assertions make the artefact executable as a test.
    good = results["consequence_profile"]
    bad = results["drops_bridge"]
    control = results["scrambled_bijection"]

    assert good["action_floor"] == 0.0
    assert good["profile_floor"] == 0.0
    assert good["weather_invariance"] == 1.0
    assert good["bridge_sensitivity"] == 1.0
    assert good["distance_stress"] == 0.0

    assert bad["action_floor"] > 0.0
    assert bad["profile_floor"] > 0.0
    assert bad["bridge_sensitivity"] == 0.0

    assert control["action_floor"] == 0.0
    assert control["profile_floor"] == 0.0
    assert control["weather_invariance"] == 1.0
    assert control["bridge_sensitivity"] == 1.0
    assert control["distance_stress"] > 0.20

    print()
    print("Assertions passed:")
    print("  positive case preserves the task-family relation")
    print("  negative case creates an irrecoverable bridge-status collision")
    print("  bijective control preserves information but destroys useful geometry")


if __name__ == "__main__":
    main()
Open the verified output
Synthetic bridge-control representation stress test
32 states; consequence family = current action + four interventions

representation           action floor profile floor  weather inv.  bridge sens.  distance stress
------------------------------------------------------------------------------------------------
consequence_profile              0.0%          0.0%        100.0%        100.0%            0.000
drops_bridge                    12.5%         37.5%        100.0%          0.0%            0.355
action_only                      0.0%         62.5%        100.0%         33.3%            0.172
nuisance_heavy                   0.0%          0.0%          0.0%        100.0%            0.111
scrambled_bijection              0.0%          0.0%        100.0%        100.0%            0.513

Assertions passed:
  positive case preserves the task-family relation
  negative case creates an irrecoverable bridge-status collision
  bijective control preserves information but destroys useful geometry

The preservation contract

A representation should enter an architecture decision with a testable contract, not a promise that it “captures semantics”. The contract names the system boundary, task family, relations to preserve, variations to collapse, transformations to track, evidence needed for evaluation and the conditions under which the code must be withdrawn or rebuilt.

Representation preservation contract A central task family is surrounded by six required relation classes: identity, topology, order, transformation, intervention and uncertainty. Each relation points to a paired stress test and a release condition. Specify the relation, then specify the break test DECLARED TASK FAMILY decision + intervention Identity swap entity Topology remove edge Order permute events Transformation rotate or relabel Intervention toggle cause Uncertainty degrade evidence Release only when paired tests move the code as the contract predicts.
Figure 8. A preservation contract converts representation choice into an intervention programme.Decision instrument. The six relation classes are prompts, not a universal ontology. Add or remove classes according to the declared task and consequence.
Contract fieldQuestionDiscriminating testRelease evidence
System boundaryWhat counts as the state before encoding?Remove each source or sensor in turn.Necessary variables are observable, attributable and within entitlement.
Task familyWhich predictions, actions and interventions must the code support?Add a query outside the current label.Every supported query has a target and loss.
Preserved relationsWhich states must remain distinguishable or ordered?Matched pairs differing in one relation.No material collision; distance or order within threshold.
Permitted collapseWhich variations leave consequence unchanged?Nuisance toggles and augmentations.Invariance holds without erasing required state.
Transformation lawShould the code be invariant, equivariant or sensitive?Apply named transformation g.Observed latent response matches the specified law.
Temporal and causal scopeWhich history or intervention responses determine the future?Same snapshot, different history; one-factor interventions.Future-consequence profiles remain distinguishable.
Negative controlCould a simpler or scrambled representation perform as well?Random bijection, raw baseline or label-only code.Claimed benefit survives matched decoder, data and compute.
Withdrawal triggerWhat change invalidates the contract?New task, policy, sensor, population or failure mode.Versioned retest before reuse.

A seven-step architecture decision

  1. Name the consequence. Write the decision, action or prediction the representation must support, including abstention and escalation.
  2. Define task equivalence. State which world states may safely share a code for that family of consequences.
  3. Construct paired interventions. Vary identity, time, topology, order, transformation or evidence quality one feature at a time.
  4. Measure collision floors first. If exact or near collisions force material error, repair the boundary or encoder before tuning the decoder.
  5. Challenge geometry with restricted baselines. Compare linear, local and high-capacity decoders at matched data and compute, including a scrambled bijection.
  6. Test outside the training correlation. Use shortcut-conflicting, superseded, rare and counterfactual cases, then report slice uncertainty.
  7. Version the contract. A representation approved for one task family is not silently approved for another.

When task families conflict

Some representation requirements cannot be maximised together. Privacy may require removing a sensitive attribute while fairness evaluation needs enough information to detect unequal error. A classifier may benefit from language invariance while a communication workflow must preserve the language needed for a legally valid notice. Compression may favour one summary code while audit requires source-level reversibility.

Do not hide these conflicts inside a single quality score. Separate the consumers and decision rights. A protected operational code may omit a field from the action path while a controlled evaluation environment retains it for monitoring. A retrieval index may store a compact semantic key while an evidence store keeps the authoritative document and provenance. A controller may use an invariant identity code alongside an equivariant pose code.

The contract should state which representation each consumer receives and which joins are permitted. This prevents a useful representation for one purpose from silently becoming an authority for another. It also makes trade-offs reviewable: the question becomes whether the system has preserved the minimum relation needed by each bounded use, rather than whether one latent space is universally rich.

The failure boundary

No finite stress test proves that a representation is universally good. Future tasks may care about distinctions the current contract deliberately removes. Preserving every possible distinction approaches an identity map and gives up the benefits of abstraction. Observational data may omit the variable that matters. Interventions may be unsafe, unavailable or too narrow. A measured latent distance may correlate with a consequence without causing the downstream model to use it.

The decision rule is therefore conditional. Approve the representation for a named task family, bounded population, decoder class, evidence regime and change policy. Reopen the decision when any of those changes. Representation validity is scoped evidence, not a permanent property of a vector space.

Open hypothesis

In workflows where material errors originate from lost identity, time, role or effect relations, an explicitly typed representation plus intervention-based evaluation will reduce failure variance more than increasing general model capacity at the same operating cost. This is a testable architecture hypothesis, not an established universal result.

Source notes and evidential boundaries
  1. Bengio, Courville and Vincent, Representation Learning: A Review and New Perspectives. Primary review used for the dependence of learning on representation and explanatory factors.
  2. Tishby, Pereira and Bialek, The Information Bottleneck Method. Primary formulation of compressed codes that preserve target-relevant information.
  3. Amjad and Geiger, Learning Representations for Neural Network-Based Classification Using the Information Bottleneck Principle. Theory and limitations relevant to deterministic networks and geometry.
  4. Locatello et al., Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations. Primary negative result on identifiability and downstream benefit without inductive bias.
  5. D'Amour et al., Underspecification Presents Challenges for Credibility in Modern Machine Learning. Primary evidence that equivalent held-out performance can conceal divergent deployment behaviour.
  6. Geirhos et al., Shortcut Learning in Deep Neural Networks. Authoritative synthesis of shortcut behaviour and transfer failures.
  7. Cohen and Welling, Group Equivariant Convolutional Networks, and Zaheer et al., Deep Sets. Primary architecture results for named transformation laws.
  8. Dubois et al., Lossy Compression for Lossless Prediction. Primary work connecting declared transformation invariance to task-preserving compression.
  9. Ferns, Panangaden and Precup, Metrics for Finite Markov Decision Processes, Gelada et al., DeepMDP, and Zhang et al., Learning Invariant Representations for Reinforcement Learning without Reconstruction. Primary sources for reward and transition consequence in sequential representation.
  10. Ahuja et al., Interventional Causal Representation Learning. Primary identifiability result under stated interventional assumptions. The article does not generalise that proof to arbitrary operational data.

Build the cut before the intelligence

A machine never encounters the world without mediation. Sensors sample it, schemas name it, tokenisers segment it, databases flatten it, encoders compress it and context builders select it. By the time a learner or reasoner acts, a chain of representations has already decided which differences are visible and which relations are easy to use.

The central architecture decision is therefore earlier than model choice. Ask which states the system is permitted to treat as equivalent. If two states require different actions, predictions, permissions or intervention responses, the representation must keep them apart with enough margin for the actual downstream mechanism. If a transformation leaves every declared consequence unchanged, the code may collapse it. If the transformation changes pose, order, authority, time or reachability, the code must track it through an appropriate law.

This view also disciplines claims about latent geometry. A clean cluster is evidence about a metric and sample, not proof of meaning. A scrambled bijection reminds us that ugly geometry can preserve all information. The relevant benefit of structure is conditional: it should reduce data, capacity or shift sensitivity for a bounded decoder, and it should beat a serious control at matched resources.

The practical programme is straightforward. Write the preservation contract. Build matched pairs and interventions. Measure collision floors before average accuracy. Test invariance and equivariance separately. Include temporal and causal variants where future consequence matters. Run raw, label-only and scrambled controls. Version the result with the task family it supports.

Representation comes before intelligence because every later capability is conditional on the distinctions, neighbourhoods and transformation laws that survived the map. When those are wrong, scaling the downstream model can polish the response while leaving the missing world relation untouched. When they are explicit and tested, learning and reasoning inherit a problem whose structure is at least honest.

Changed decision: do not approve an embedding, state abstraction or context packet because it looks informative. Approve it only after the relations that govern consequence survive a paired, intervention-led stress test.