Formal bridges and comparison discipline
Categories, morphisms and composition
A system becomes categorically intelligible when its allowable transformations compose coherently, because composition lets us reason about long routes without reopening every object, provided hidden state, side effects and authority have not been erased.
TLDR
- A category describes objects together with the transformations allowed between them.
- Composition, not the object list, creates the main explanatory leverage.
- Identity and associativity make long routes reusable, regroupable and testable.
- Equal endpoints do not make two routes the same transformation.
- A category model fails when relevant state, effects or permissions sit outside its arrows.
At an airport, two bags arrive at the same loading bay. The tracking screen records both as “loaded”. One bag followed the intended route: check-in, screening, seal, then loading. The other crossed a maintenance door and reached the bay directly.
From the viewpoint of the final label, the bags are identical. From the viewpoint of aviation security, they are not. The difference is not inside the bag. It lies in the route, in which transitions were permitted, and in whether the route carried the required evidence.
Most informal system diagrams hide this distinction. They draw boxes for states and arrows for movement, then treat any path with the same endpoint as interchangeable. The hidden assumption is that an endpoint contains everything that matters about how it was reached. That assumption fails whenever provenance, authority, cost, risk or irreversible effects travel with the process.
Category theory begins by refusing to throw the arrows away. It asks what the objects are, which morphisms are allowed, when two morphisms can be composed, what counts as doing nothing, and when two complete routes are genuinely equal. Its power comes from a severe economy: once those rules are correct, a long chain can be reasoned about through its parts. Its danger comes from the same economy: a modeller can choose arrows that omit exactly what matters.
The world made of allowable moves
Imagine receiving a map with cities and one-way roads. You can answer whether Delhi has a road to Jaipur. You cannot yet answer whether a Delhi-to-Jaipur road followed by a Jaipur-to-Udaipur road counts as one admissible Delhi-to-Udaipur journey. A directed graph gives points and arrows. A category adds the law for joining arrows.
This difference sounds small because ordinary travel supplies composition automatically. Drive the first road, then the second. In engineered and conceptual systems, the join is often the hard part. A temperature reading in Celsius may enter a Fahrenheit converter, but a signed payment instruction may not enter an unsigned executor. A model proposal may enter a policy check, but it may not enter a bank account. Types, permissions and state decide which arrows can meet.
A graph can still be the right starting point. It records generators: the primitive moves we are willing to name. To obtain a category, we must decide what every finite route means. The least committal choice is to keep each route as a distinct morphism. A more opinionated choice declares some routes equal. “Normalise, then validate” might be required to equal “validate with normalisation built in”. That equation is not drawn merely for tidiness. It says every observation admitted by the model must treat the two composites as the same transformation.
This is why a category is better understood as a world of lawful substitution than as a decorated network. When two paths are equal, one may replace the other inside any larger compatible route. When they are not equal, the model preserves a distinction that later composition may expose. The choice affects what can be proved, what can be replaced and what can fail.
The minimum formal machinery
A category C contains objects such as A, B and C. For each ordered pair, it may contain morphisms from the first object to the second. We write a morphism as f: A → B. If g: B → C, the codomain of f matches the domain of g, so the pair can be composed. The result is another morphism g ∘ f: A → C, read from right to left: first f, then g.
Two laws make this a category rather than a loose network. Every object A has an identity morphism idA: A → A. Composing it before or after a compatible morphism changes nothing. Composition is associative: for f: A → B, g: B → C and h: C → D, both ways of placing brackets yield the same complete morphism.
Modern notation often gathers all morphisms from A to B into a collection written HomC(A,B). The subscript names the category because the same apparent objects can admit different morphisms in different contexts. Between two sets, one category may allow every function. Another may allow only bijections. Between software states, one category may admit every executable transition; another may admit only transitions authorised by a current policy. The objects alone never determine the category.
A gallery has a red room, a blue room and a green room. Door f leads from red to blue. Door g leads from blue to green. The composed route g ∘ f leads from red to green. Staying in the red room is idred; it must not lock a door, alter the ticket or start a timer, otherwise it is not an identity for the state we claimed to model.
Now add a direct emergency passage e from red to green. The category does not force e = g ∘ f. If the indirect route scans two exhibits and the emergency passage does not, they should remain parallel but distinct morphisms. A path equation may identify them only after the modeller states which observations are being ignored.
h ∘ (g ∘ f) = (h ∘ g) ∘ f
The first displayed phrase is a useful warning. Composition is typed. One cannot compose arbitrary arrows merely because their names sound compatible. The laws also say less than newcomers often assume. Associativity does not say that order is irrelevant. Usually g ∘ f differs from f ∘ g, and one of them may be undefined. Identities are not inverses. A morphism need not be reversible.
The identity law also carries more content than the phrase “do nothing” suggests. A health-check call that refreshes a lease is not an identity on a state that includes lease expiry. A dry-run that increments a billable counter is not an identity on an account state. An unchanged payload can therefore conceal a changed object. The cure is not to argue about the word identity. It is to enlarge or refine the object until the claimed no-op really leaves every modelled component unchanged.
| Ingredient | Operational question | Airport example | Failure if omitted |
|---|---|---|---|
| Objects | Which states or types are inside the model? | Checked, screened, sealed, loaded | Arrows have no typed endpoints. |
| Morphisms | Which transformations are admitted? | Screen, seal, load | Any causal story can be drawn after the fact. |
| Identity | What counts as a genuine no-op? | Inspect without changing status | Unchanged and silently changed states are confused. |
| Composition | How do valid transitions form a valid route? | Load ∘ seal ∘ screen | Local steps cannot support an end-to-end claim. |
flowchart LR A["The world made of allowable moves"] --> B["Why composition carries the<br/>explanation"] B --> C["Three small worlds, three<br/>meanings of arrow"] C --> D["From formal shape to operating<br/>instrument"] D -. "re-test" .-> A classDef first fill:#0a1424,stroke:#087A98,stroke-width:2px,color:#e6f3ff classDef step fill:#0a1424,stroke:#3f7da0,stroke-width:1px,color:#e6f3ff class A first class B,C,D step
Why composition carries the explanation
Objects attract attention because they are easy to name. A database, model, sensor or person appears to be the thing doing the work. Yet most system behaviour lies between named things. A sensor becomes useful through calibration; a model output becomes consequential through authorisation; a mathematical object becomes comparable through the maps that preserve its structure.
Category theory changes the unit of analysis. Instead of asking only, “What is this object made of?”, it asks, “What can enter it, what can leave it, and which routes remain coherent?” Riehl describes this as a shift from direct characterisation towards transformations among objects of the same general type.3 Fong and Spivak emphasise the accompanying demand for coherence: combining a chain of chains must agree with combining the long chain.5
Composition creates reuse. Once a morphism has a stable domain, codomain and behavioural contract, it can participate in every compatible route without being redefined for each route. Associativity then permits regrouping. A team can verify a subsystem, replace it with a compositionally equivalent subsystem, and reason about the larger route at the level of the composite.
Associativity is a regrouping guarantee
Take three ordinary functions. Let f add one, g double the result, and h take the remainder after division by three. Starting with 2 gives 3 after f, 6 after g, and 0 after h. We can first combine “add one, then double” and then apply the remainder operation. Or we can first combine “double, then take the remainder” and apply that composite after adding one. The order of actions is unchanged. Only the brackets move.
Let f(x)=x+1, g(y)=2y, and h(z)=z mod 3. For x=2:
(h ∘ g) ∘ f = h ∘ (g ∘ f)
The equation is valid because these are total, deterministic functions and composition means ordinary function composition. Add a mutable counter, a clock-dependent branch or an exception that changes shared state, and the plain function model may no longer describe the real operation.
For example, suppose g flushes a buffer whenever it is called as a standalone operation, while an optimiser fuses g with h and delays the flush. The two bracketings can then produce different external traces. Mathematics has not failed. The operations were never accurately represented as ordinary functions on the stated objects. The buffer and trace belonged in the state.
The composition dividend
Suppose a workflow has six stages, with two certified implementations available at each stage. There are 64 end-to-end implementation routes. There are only 12 local implementations. Under a strong assumption that each implementation honours the same typed contract and that composition preserves the stated invariant, local certificates can be reused across many routes. This does not abolish end-to-end testing. It changes what must be retested after a local substitution.
The distinction is between evidence about a component and evidence that travels through composition. A unit test may show that a converter returns the expected values. A compositional contract additionally states the accepted input type, produced output type, preserved invariant and effect boundary. Only the latter can support a reasoned substitution inside routes not individually enumerated. Even then, integration tests remain necessary for assumptions that the contract deliberately excludes, such as latency, contention or correlated failure.
The dividend is not fewer tests by decree. It is the ability to explain which tests are reusable and why. Without that explanation, a modular architecture may simply distribute uncertainty across more interfaces.
Three small worlds, three meanings of arrow
The same category axioms can organise very different worlds. That flexibility is a strength only when the meaning of an arrow remains explicit. A path, a function and an order relation can all be morphisms, but they preserve different information. The following examples make that difference visible.
World one: paths remain paths
Start with a directed map. Build a category whose objects are locations and whose morphisms are finite directed paths. Composition concatenates paths; the identity at a location is the empty path that starts and ends there. This construction is called the free category on a graph. It adds all composites required by the category laws without adding equations that identify distinct routes.
Two journeys from Checked to Loaded can therefore remain different morphisms even if they begin and end at the same objects. This is exactly what the airport puzzle needed. Source and target constrain a morphism, but do not exhaust it.
A modeller can then add path equations. If a direct route r is certified to have exactly the same observable behaviour as load ∘ screen, the equation r = load ∘ screen may be imposed. Algebraically, this forms a quotient of the free path category by the chosen equations. Operationally, it licenses substitution: any longer route containing r may use the composite instead, and vice versa.
That licence is powerful enough to deserve suspicion. An equation imported from a process diagram may conceal timing, cost or provenance. A commuting diagram is therefore not a picture of things that “roughly lead to the same place”. It is a claim that specified composites are equal in the chosen category. The equality needs a witness, such as a proof, exhaustive finite check, contract test or accepted semantic rule.
World two: functions compute
In the category of sets, objects are sets and morphisms are functions. Composition is ordinary function composition, and identity morphisms are identity functions. Here two functions are equal when they return the same output for every input. Internal algorithms do not matter to this category. A lookup table and a formula can be the same morphism if they define the same function.
Keep the same underlying sets but change the morphisms, and a different category appears. Groups use homomorphisms that preserve multiplication and identity. Topological spaces use continuous maps that preserve neighbourhood structure. Vector spaces use linear maps. The adjective “structure-preserving” is not decorative. It states which features must survive movement. An arbitrary function between the carrier sets of two groups is a morphism in Set but may not be a group homomorphism. The categorical question is always relative to a declared context.
This relativity blocks a common philosophical overreach. Category theory can characterise an object through its relations inside a category, but it does not say that every internal description is unreal or dispensable. Change the allowable probes and transformations, and the relational profile changes. What looks like “the same object” in one category may split into several distinctions in another.
Let A={1,2,3}. The upper path adds one and then doubles. The lower path doubles and then adds two. Both send 1, 2 and 3 to 4, 6 and 8. In the category of sets, the two composites are equal functions. The square commutes.
Change the lower operation to “double and log the original input”. The returned numbers still match, but the operation now has an extra effect not represented in the output set. The equality remains true only for the impoverished model that ignores the log.
World three: a preorder forgets the route
A preorder is a reflexive, transitive relation. It becomes a category by taking its elements as objects and placing a morphism a → b whenever a ≤ b. There is at most one morphism between any pair. Reflexivity supplies identities; transitivity supplies composition. Such a category is called thin.
Suppose objects are evidence strengths: observed ≤ corroborated ≤ verified. Once the relation says observed evidence can be strengthened to verified evidence, the thin category does not retain which corroboration route was used. That information has been intentionally collapsed. This may be perfect for proving reachability and disastrous for auditing provenance.
The opposite compression also occurs. A monoid, such as strings under concatenation or non-negative integers under addition, can be viewed as a category with one object. Every monoid element becomes an endomorphism of that single object, and the monoid operation becomes composition. The example is a useful shock: a category with one object can still contain rich process structure. The number of objects is not a measure of categorical complexity.
Together, paths, functions, preorders and one-object categories dismantle the idea that category theory merely replaces nouns with arrows. It supplies a grammar for many kinds of arrows. The modeller must still decide whether an arrow means a journey, computation, proof, refinement, permission, physical process or something else.
A ladder of route equality
The examples support a practical distinction. Endpoint equality means two routes finish at states carrying the same selected value. Morphism equality means the category declares the complete transformations equal. Governed equality means the routes also preserve the authority, effects, evidence and recovery obligations relevant to the decision.
The third phrase is practitioner synthesis, not a standard category-theory term. Its purpose is to prevent a common systems error: importing function equality into a domain where side effects and permissions are decisive. Before equating two paths, state which downstream observations are allowed to distinguish them.
stateDiagram-v2 [*] --> Claim state "The minimum formal machinery" as Claim state "Associativity is a regrouping<br/>guarantee" as Test state "The composition dividend" as Revision Claim --> Test: expose mechanism Test --> Decision: evidence survives Test --> Revision: rival survives Revision --> Claim: narrow or rebuild Decision --> [*]
From formal shape to operating instrument
A category is useful in engineering when it makes composition obligations explicit. Consider a consequential AI-assisted action. Intent, identity, world state, permitted context, model proposal, authority, typed action, evidence, verified outcome and recovery are different things. Treating them all as “context” or “memory” hides who may transform what.
A minimal governed route might use the following typed objects: an IntentRecord, a BoundedProposal, an AuthorisedAction, an EffectReceipt and a VerifiedOutcome. The model may propose a transformation from intent and permitted context to a bounded proposal. A deterministic authority kernel may transform that proposal into an authorised action or an abstention. A typed executor may turn an authorised action into an effect receipt. A separate readback may turn the receipt into a verified outcome.
The composite describes an end-to-end route. It does not imply that the model itself has authority. Authority belongs to the morphism that checks and grants permission, not to fluency at the preceding object. A direct arrow from proposal to effect is either absent or explicitly marked as a rejected path.
A customer asks for a 120-unit service credit. The intent record identifies the account and requested remedy. Permitted context adds the current contract, prior credits and policy version. A model proposes 120 units with a rationale. The authority morphism checks the actor, policy ceiling and cumulative credit, then emits either an AuthorisedCredit or an Abstention. The executor posts the credit under an idempotency key and returns receipt R17. Readback confirms that the ledger contains exactly one 120-unit credit linked to R17.
Now compare a shortcut that writes 120 directly to the ledger. The terminal balance can match. The path does not. It lacks a policy decision, typed authority and the evidence needed for replay or recovery. A category of returned balances identifies too much. A governed action category keeps the routes distinct.
The worked scenario also exposes a modelling choice. Abstention should not be represented as a failed authorised action if it has different obligations. It is a legitimate codomain of the authority decision, with its own later morphisms such as request-more-evidence or route-to-human-review.
The composition audit
The article’s practical contribution is a seven-question audit for deciding whether a categorical model earns its abstraction. It begins with the transformations because object labels are often inherited from organisation charts rather than from causal structure.
The audit is deliberately ordered. Boundary comes before arrow because a transformation cannot be typed until relevant state is located. Closure comes before identity and associativity because there is no algebra to test if compatible steps lack composites. Path equality comes after the laws because equality concerns complete routes, not attractive visual symmetry. Intervention comes last because a model that cannot be stressed may be internally elegant and empirically empty.
For a small system, the output can be a composition table. Rows name the morphism executed second; columns name the morphism executed first; each compatible cell names the result. For a large system, the same obligations can live in typed interfaces, proof assistants, property-based tests or executable contracts. The representation changes. The causal questions do not.
Published applications show what this discipline can look like without settling the modelling choice for a new system. Spivak formalises data migration between database schemas, Spivak and Kent use categorical structure for ologs, and Spivak develops compositional models across scientific domains.678 These works establish reusable methods, not a licence to treat every workflow diagram as a category.
| Audit step | Question | Evidence sought | Failure signal |
|---|---|---|---|
| 1. Boundary | Which state, time, authority and effects are inside each object? | Typed state inventory | A retry changes the world without changing the object. |
| 2. Arrow | What exact transformation does each morphism permit? | Preconditions, postconditions, actor | An arrow label hides several materially different actions. |
| 3. Closure | Does every compatible pair have a named composite? | Composition table or implementation rule | A chain is drawn but its end-to-end meaning is undefined. |
| 4. Identity | What is the real no-op for each object? | State and receipt comparison | “Do nothing” refreshes, logs, charges or expires something. |
| 5. Associativity | Can regrouping a fixed order change the outcome? | Triple-composition tests | Buffer flushes, exceptions or shared state alter the result. |
| 6. Path equality | Which parallel routes are declared equal, and under which observations? | Explicit path equations | Only terminal values were compared. |
| 7. Intervention | Which deletion, swap, retry or boundary move could falsify the model? | Failure-injection protocol | The model survives only because decisive variables cannot be perturbed. |
A positive audit does not prove that the selected category is the only or deepest description. It establishes that the specification is internally compositional for the observations it names. A negative audit is equally useful. It locates where the ordinary category abstraction is too thin, where the boundary must expand, or where a richer structure is required.
Several repairs are possible. Hidden mutable state can be moved into the objects. Partial operations can be represented with explicit failure objects or a structure designed for partiality. Nondeterministic proposals can be treated as data passed to deterministic validators, or modelled in categories whose morphisms are relations or stochastic kernels. Concurrent and open systems may require monoidal, double or enriched structures. The point is not to name the most advanced formalism. It is to let a failed law tell us what the simpler model omitted.
Finite category integrity checker
The lab validates a small, explicit category specification. It checks object and morphism references, total composition for every composable pair, identity laws and associativity. Choose a supplied example, edit the JSON, then run the validator.
Begin with the valid airport chain. Remove the composite screen_then_load, and closure will fail because the compatible pair no longer has a result. Load the buffering example, and the validator finds a triple whose two bracketings produce flush_early and flush_late. Repairing the JSON requires either identifying those outcomes or changing the state space so the distinction becomes explicit.
Edit the finite category specification, then select Validate category.
Ready
Select Validate category to run the checks.
Interpretation
A pass permits the narrow conclusion that the finite specification satisfies the category axioms under name-based morphism equality. A failure identifies a missing or inconsistent law. Neither result establishes that the arrows correspond to real operations, that hidden state is absent, or that the chosen equality is decision-relevant.
View the validator’s core JavaScript
function validateCategory(spec) {
const errors = [];
const objects = new Set(spec.objects || []);
const arrows = new Map((spec.morphisms || []).map(m => [m.name, m]));
const key = (after, before) => `${after}∘${before}`;
const composition = new Map(
(spec.composition || []).map(c => [key(c.after, c.before), c.result])
);
for (const m of arrows.values()) {
if (!objects.has(m.from) || !objects.has(m.to)) {
errors.push(`Unknown endpoint on ${m.name}`);
}
}
for (const object of objects) {
const identityName = spec.identities?.[object];
const identity = arrows.get(identityName);
if (!identity || identity.from !== object || identity.to !== object) {
errors.push(`Invalid identity for ${object}`);
}
}
const composablePairs = [];
for (const before of arrows.values()) {
for (const after of arrows.values()) {
if (before.to === after.from) composablePairs.push([after, before]);
}
}
for (const [after, before] of composablePairs) {
const resultName = composition.get(key(after.name, before.name));
const result = arrows.get(resultName);
if (!result) {
errors.push(`Missing composite ${after.name}∘${before.name}`);
} else if (result.from !== before.from || result.to !== after.to) {
errors.push(`Wrong endpoints for ${after.name}∘${before.name}`);
}
}
for (const f of arrows.values()) {
const left = composition.get(key(spec.identities[f.to], f.name));
const right = composition.get(key(f.name, spec.identities[f.from]));
if (left !== f.name) errors.push(`Left identity fails for ${f.name}`);
if (right !== f.name) errors.push(`Right identity fails for ${f.name}`);
}
for (const f of arrows.values()) {
for (const g of arrows.values()) {
for (const h of arrows.values()) {
if (f.to !== g.from || g.to !== h.from) continue;
const gf = composition.get(key(g.name, f.name));
const hg = composition.get(key(h.name, g.name));
const left = composition.get(key(h.name, gf));
const right = composition.get(key(hg, f.name));
if (left !== right) errors.push(
`Associativity fails for ${h.name}, ${g.name}, ${f.name}: ${left} ≠ ${right}`
);
}
}
}
return { valid: errors.length === 0, errors: [...new Set(errors)] };
}
Instrument state and effects before abstracting.
Model time, exceptions and authority explicitly.
Stable types help, but ordinary arrows may hide side effects.
Expect object and arrow definitions to move.
Test identities, triples and path equations.
Add explicit effect and receipt objects.
Keep the scope narrow while interfaces settle.
Composition can support reusable proofs and tests.
Stable contracts and explicit state earn abstraction.
Composition-complete action contracts will reduce integration failures under component substitution more than endpoint-only tests with the same test budget.
- Strengthens it
- Across matched workflows, contract-based systems show fewer failures after swaps, retries and boundary changes.
- Weakens it
- The advantage disappears after controlling for ordinary type checks and integration-test coverage.
- Rival account
- The gain comes from better documentation or engineering discipline, not categorical structure.
- Do not apply
- Exploratory domains whose objects, interfaces and effects are still changing rapidly.
- Smallest test
- Two four-stage synthetic workflows, one with explicit composition and path obligations, one with endpoint assertions, exposed to the same injected faults.
A correct category can be useless. Define every runtime state as an object and every complete history as a morphism, and associativity may hold while nothing has been simplified. Conversely, choose a thin category and decisive distinctions may vanish. Category theory guarantees consequences from a specification; it does not guarantee that the specification isolates the right causes.
sequenceDiagram participant Q as Question participant M as Mechanism participant E as Evidence participant D as Decision Q->>M: The world made of allowable moves M->>E: The minimum formal machinery E-->>M: compare rival explanations E->>D: Earn abstraction through compositional tests D-->>Q: revise scope or act
Earn abstraction through compositional tests
When faced with a complicated system, do not begin by cataloguing components. Begin by selecting one consequential route. Name the state before each step. Type the allowable transformations. Ask what counts as doing nothing, whether every compatible pair has a composite, and whether regrouping a fixed chain can change its effect.
Then inspect parallel routes. If they share an endpoint, resist the urge to call them equivalent. Decide which observations matter: returned value, timing, provenance, authority, resource use, side effects, receipts or recoverability. Declare path equality only at that level. The airport shortcut, privacy leak and duplicate payment all survive endpoint testing because the decisive evidence lives in the morphism.
Use the categorical lens when composition is the problem you need to control. It is especially valuable when components will be substituted, routes will be reused, or claims must transfer across representations. Stop and expand the boundary when identities have effects, retries alter the world, or associativity fails under hidden state.
The practical decision is therefore not “apply category theory” or “avoid abstraction”. It is more exact: earn abstraction by proving that the selected transformations compose under the observations the decision actually cares about.
That proof may be tiny. Three typed states, six morphisms and one associativity test can be enough to reveal a hidden effect. The value lies not in maximal abstraction, but in making the smallest composition claim that can survive intervention.
Glossary
- Object
- A state, type or mathematical entity selected as a node in a category.
- Morphism
- An allowed transformation from one object to another.
- Domain
- The source object of a morphism.
- Codomain
- The target object of a morphism.
- Composition
- The operation that combines compatible morphisms into a new morphism.
- Identity
- The distinguished no-op morphism for an object.
- Associativity
- The law that regrouping an ordered chain does not change its composite.
- Commutative diagram
- A diagram in which specified parallel paths have equal composites.
- Thin category
- A category with at most one morphism between any ordered pair of objects.
- Free category
- The category generated by a directed graph, whose morphisms are finite paths.
References
- Eilenberg, S. and Mac Lane, S. (1945). General theory of natural equivalences. Transactions of the American Mathematical Society, 58(2), 231–294.
- Mac Lane, S. (1998). Categories for the Working Mathematician, second edition. Springer.
- Riehl, E. (2016). Category Theory in Context. Dover Publications.
- Leinster, T. (2014). Basic Category Theory. Cambridge University Press.
- Fong, B. and Spivak, D. I. (2019). Seven Sketches in Compositionality: An Invitation to Applied Category Theory. Cambridge University Press.
- Spivak, D. I. (2012). Functorial data migration. Information and Computation, 217, 31–51.
- Spivak, D. I. and Kent, R. E. (2012). Ologs: A categorical framework for knowledge representation. PLOS ONE, 7(1), e24274.
- Spivak, D. I. (2014). Category Theory for the Sciences. MIT Press.