Human–Machine Convergence

Categories, morphisms and composition

Rajesh Ranjan Mahapatra

A first-principles guide to categories, morphisms and composition, with worked examples, failure cases and an executable finite-category validator.

© 2026 Rajesh Ranjan Mahapatra. 28 min read

Categories, morphisms and compositionAll Human–Machine Convergence

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

  1. A category describes objects together with the transformations allowed between them.
  2. Composition, not the object list, creates the main explanatory leverage.
  3. Identity and associativity make long routes reusable, regroupable and testable.
  4. Equal endpoints do not make two routes the same transformation.
  5. 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.

A category is not an inventory of places. It is a navigable world whose lawful routes are part of the specification.
A small category drawn as a navigable world Four island-like regions represent objects. Curved one-way routes represent morphisms. A composed route from checked to loaded passes through screened, while a dotted maintenance shortcut is visibly outside the permitted route. Checked object A Screened object B Sealed object C Loaded object D screen seal load maintenance shortcut: visible, but not admitted identity: remain checked
Figure 1. The navigable world. Objects locate admissible states; morphisms specify admissible movement. The dotted shortcut reaches the same endpoint but is not thereby an allowed morphism. Illustrative.Alt text: A map of checked, screened, sealed and loaded states connected by permitted routes, plus a dotted maintenance shortcut outside the admitted route.

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.

Worked example 1 · three rooms

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.

g ∘ idA is undefined unless g starts at A;   f ∘ idA = f;   idB ∘ f = f
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.

IngredientOperational questionAirport exampleFailure if omitted
ObjectsWhich states or types are inside the model?Checked, screened, sealed, loadedArrows have no typed endpoints.
MorphismsWhich transformations are admitted?Screen, seal, loadAny causal story can be drawn after the fact.
IdentityWhat counts as a genuine no-op?Inspect without changing statusUnchanged and silently changed states are confused.
CompositionHow do valid transitions form a valid route?Load ∘ seal ∘ screenLocal steps cannot support an end-to-end claim.
Established mathematical structure. The object, morphism, identity and associative-composition formulation descends from the founding account of Eilenberg and Mac Lane and remains standard in modern texts.1234
The argument in one pass
Chart · flow
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
A structural route through Categories, morphisms and composition: from The world made of allowable moves to Earn abstraction through compositional…. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

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

Mechanism

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.

Same endpoint is an observation. Same morphism is a claim about the route.
Causal intervention on the screening route The upper route passes from checked through screened to loaded. The lower intervention removes screening and directly loads the bag. Both end at loaded, but the lower route has no screening receipt and is marked rejected. Observed route Checked Screened Loaded screen load receipt ✓ Intervention: delete screening Checked Loaded bypass: same endpoint, different morphism
Figure 2. Delete one causal step. The intervention preserves the terminal label while removing the screening transformation and its receipt. Endpoint matching therefore cannot certify route equivalence. Illustrative causal intervention.Alt text: Two paths end at loaded. The accepted path includes screening and a receipt; a dotted bypass removes screening and is rejected.

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.

Worked example 2 · a mental calculation

Let f(x)=x+1, g(y)=2y, and h(z)=z mod 3. For x=2:

h(g(f(2))) = h(g(3)) = h(6) = 0
(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.

Associativity moves brackets, not events. The temporal order remains f, then g, then h.
Two bracketings of one ordered trajectory A top timeline groups f and g first, while a bottom timeline groups g and h first. Both timelines keep the event order f, g, h and converge on the same composite. Group the first pair f g h g ∘ f h ∘ (g ∘ f) Group the second pair f g h h ∘ g (h ∘ g) ∘ f
Figure 3. Regrouping without reordering. Associativity permits modular reasoning because either bracketing denotes the same ordered composite. It says nothing about swapping f, g and h. Illustrative.Alt text: Two timelines contain f, g and h in the same order. The upper groups f with g; the lower groups g with h; both represent the same complete composition.

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.

Compositional contracts can turn route-by-route rechecking into reusable local evidence, but only under an explicit preservation assumption.
Illustrative growth of route variants and local implementations A line chart compares two to the power of depth route variants with twice the depth local implementations for one to six stages. Route variants rise from two to sixty-four while local implementations rise from two to twelve. 016324864 123456 workflow stages count route variants: 2ᵈ local implementations: 2d
Figure 4. The composition dividend under a strict contract. With two alternatives at each of d stages, routes grow as 2d while local implementations grow as 2d. Reuse is justified only when local contracts and their preservation under composition are actually established. Illustrative synthetic counts.Alt text: A chart shows route variants increasing steeply to sixty-four across six stages while local implementations increase slowly to twelve.

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.

Worked example 3 · a commuting square

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.

A diagram commutes only relative to the morphism equality chosen by the category.
Annotated commuting square of finite functions Set A containing one, two, three maps across the top by add one and then double to set D containing four, six, eight. Across the lower route, double then add two reaches the same values. Matching rows show both composites agree for each input. A 123 B 234 D 468 C 246 +1 ×2 ×2 +2 for every x in A 2(x+1) = 2x+2 Two routes, one function
Figure 5. A commuting square of functions. The two paths are equal because they agree on every input under ordinary function equality. Add unmodelled logging or authority effects and the square may cease to commute in a richer category. Illustrative finite-set example.Alt text: A square maps one, two, three to four, six, eight by two routes. The equation two times x plus one equals two x plus two shows the routes define the same function.

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.

The word “morphism” has no fixed worldly meaning. The chosen category decides what a route preserves or forgets.
Three categorical worlds compared A triptych compares a path category, a category of finite sets and functions, and a thin preorder category. The path panel keeps distinct routes, the function panel identifies extensionally equal computations, and the preorder panel records only reachability. Paths Functions Preorder AB route proute q Keeps p and q distinct source and target are not enough XY 12 ab Equal when outputs agree implementation can disappear abc At most one arrow per pair records order, not route
Figure 6. Three meanings of arrow. A path category retains route identity, Set retains extensional input-output behaviour, and a preorder retains only reachability. The model’s explanatory power depends on choosing the right equality. Illustrative synthesis based on standard examples.14Alt text: Three panels show two distinct paths, a function between finite sets, and a three-step order relation, each preserving different information.

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.

A square can commute for returned values while failing for effects, authority or evidence.
A non-commuting governance square Two routes from request to result return the same value. The authorised route passes through policy and produces a receipt. The shortcut calls an effect directly and lacks authority and receipt. A value projection says equal, while the governed observation says not equal. Request Authorised action Direct effect Result 42 receipt R17 no receipt value projection:equal governed observation:not equal
Figure 7. The adversarial path. Both routes return 42. Only the upper route carries policy authority and an effect receipt. The square commutes after projecting to value, but not after observing governance-relevant effects. Illustrative failure case.Alt text: An authorised upper route and a direct-effect lower route both reach result forty-two. The authorised route has a receipt; the shortcut does not.
How the claim changes under pressure
Chart · state
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 --> [*]
The revision loop begins with The minimum formal machinery and keeps counterexamples inside the reasoning path. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

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.

Worked example 4 · a synthetic service credit

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.

Keep proposal, authority, action, evidence and verified outcome as separate typed stages.
System boundary for a governed AI action route A horizontal route moves from intent record to bounded proposal, authorised action, effect receipt and verified outcome. A model boundary surrounds proposal generation; an authority boundary surrounds policy decision and execution. A dotted direct path from proposal to effect is rejected. model proposal boundary deterministic authority and execution boundary Intentrecord Boundedproposal Authorisedaction Effectreceipt Verifiedoutcome reason authorise execute read back proposal → effect bypass: prohibited Composition invariant Every effect must be reachable through a current authority decision and must yield a receipt that a separate readback can verify.
Figure 8. A governed action category. The system boundary separates probabilistic proposal from deterministic authority. Composition is permitted only through typed action and evidence stages; a direct proposal-to-effect route is absent. Practitioner synthesis.Alt text: A governed action pipeline separates intent, proposal, authorised action, effect receipt and verified outcome, with a rejected bypass from proposal directly to effect.

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 stepQuestionEvidence soughtFailure signal
1. BoundaryWhich state, time, authority and effects are inside each object?Typed state inventoryA retry changes the world without changing the object.
2. ArrowWhat exact transformation does each morphism permit?Preconditions, postconditions, actorAn arrow label hides several materially different actions.
3. ClosureDoes every compatible pair have a named composite?Composition table or implementation ruleA chain is drawn but its end-to-end meaning is undefined.
4. IdentityWhat is the real no-op for each object?State and receipt comparison“Do nothing” refreshes, logs, charges or expires something.
5. AssociativityCan regrouping a fixed order change the outcome?Triple-composition testsBuffer flushes, exceptions or shared state alter the result.
6. Path equalityWhich parallel routes are declared equal, and under which observations?Explicit path equationsOnly terminal values were compared.
7. InterventionWhich deletion, swap, retry or boundary move could falsify the model?Failure-injection protocolThe 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.

Executable lab

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
JavaScript · finite-category validator
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)] };
}
Use an ordinary category when interfaces are stable and relevant context is explicit. Expand the model as hidden context rises.
Figure 9. The category-use decision surface. Interface stability raises the value of composition. Hidden context lowers confidence that ordinary morphisms capture the real process. The matrix directs the modeller towards use, qualification or boundary work. Practitioner decision instrument.Alt text: A three-by-three matrix recommends category modelling most strongly when interfaces are stable and hidden context is low, and recommends instrumentation first when the reverse is true.
Open research hypothesis

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.
Strongest boundary

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.

The evidence conversation
Chart · sequence
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
Question, mechanism, evidence and decision exchange the burdens developed in Categories, morphisms and composition. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

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

  1. Eilenberg, S. and Mac Lane, S. (1945). General theory of natural equivalences. Transactions of the American Mathematical Society, 58(2), 231–294.
  2. Mac Lane, S. (1998). Categories for the Working Mathematician, second edition. Springer.
  3. Riehl, E. (2016). Category Theory in Context. Dover Publications.
  4. Leinster, T. (2014). Basic Category Theory. Cambridge University Press.
  5. Fong, B. and Spivak, D. I. (2019). Seven Sketches in Compositionality: An Invitation to Applied Category Theory. Cambridge University Press.
  6. Spivak, D. I. (2012). Functorial data migration. Information and Computation, 217, 31–51.
  7. Spivak, D. I. and Kent, R. E. (2012). Ologs: A categorical framework for knowledge representation. PLOS ONE, 7(1), e24274.
  8. Spivak, D. I. (2014). Category Theory for the Sciences. MIT Press.