Operon v0.15: Diagram Optimization

Cost-Annotated Wiring Diagrams, Categorical Rewriting, and Resource-Aware Execution

Bogdan Banu · bogdan@banu.be

operon-ai v0.15.0

Summary

Operon v0.15 bridges the gap between wiring diagrams as documentation and wiring diagrams as optimizable formal objects. Cost annotations enrich the wiring category over $(\mathbb{R}_{\geq 0}, +, 0)$, making resource consumption compositional. A static analyzer identifies parallelism, dead wires, critical paths, and cost hotspots. Rewriting passes—behavior-preserving endofunctors—transform diagrams into more efficient equivalents. A resource-aware executor gates module scheduling on MetabolicState, connecting diagram optimization to the metabolic intelligence framework. The release adds 36 new tests (863 total, zero regressions), a new paper section (§7), and 1 example.

1. The Problem: Diagrams Without Economics

v0.14 gave us composable coalgebras, morphogen diffusion, and optic-based routing. The wiring diagram system can describe complex multi-agent topologies with typed ports, integrity labels, prism routing, and traversal transforms. But it has a blind spot: all modules are treated as equally cheap.

The DiagramExecutor uses naive topological sort. It doesn’t know that one module costs 5 ATP and another costs 500. It can’t identify that two modules could run in parallel. It doesn’t notice that a prism wire can never fire. And it certainly doesn’t adapt its behavior when the system is running low on energy.

Biology solved this problem long ago. Cells don’t blindly run every metabolic pathway at full throttle. They perform Flux Balance Analysis—identifying rate-limiting enzymes, pruning vestigial branches, parallelizing independent pathways, and downregulating non-essential reactions under ATP depletion. The pathway structure itself reveals optimization opportunities.

The Abbott & Zardini Insight

Abbott & Zardini (2025) introduced Neural Circuit Diagrams—a diagrammatic scheme with explicit memory hierarchy awareness—and used them to derive FlashAttention by proving SoftMax-Contraction is streamable and applying group partitioning for GPU tiling. Operon v0.15 extends this insight to dynamic multi-agent systems with coalgebraic state, where optimization decisions depend on runtime metabolic conditions.

2. Cost-Annotated Diagrams

The foundation is a simple dataclass:

@dataclass(frozen=True)
class ResourceCost:
    atp: int = 0           # Energy cost (ATP units)
    latency_ms: float = 0  # Time cost
    memory_mb: float = 0   # Memory footprint

    def __add__(self, other):
        return ResourceCost(
            atp=self.atp + other.atp,
            latency_ms=self.latency_ms + other.latency_ms,
            memory_mb=self.memory_mb + other.memory_mb,
        )

ResourceCost composes additively—the cost of a path through the diagram is the sum of the costs along it. Formally, this is an enrichment of the wiring category over the commutative monoid $(\mathbb{R}_{\geq 0}^3, +, \mathbf{0})$.

Costs are attached at two levels:

A second new field, essential: bool = True, marks whether a module can be skipped under metabolic stress. Essential modules (like the Validator in a pipeline) always execute; non-essential modules (like an Enricher or Logger) can be dropped when ATP is scarce.

diagram.add_module(ModuleSpec(
    "Validator",
    inputs={"data": pt}, outputs={"valid": pt},
    cost=ResourceCost(atp=10, latency_ms=20.0),
    essential=True,  # always runs, even when starving
))
diagram.add_module(ModuleSpec(
    "Enricher",
    inputs={"data": pt}, outputs={"enriched": pt},
    cost=ResourceCost(atp=30, latency_ms=50.0),
    essential=False,  # skipped under ATP depletion
))

All annotations are backward-compatible. Modules without cost annotations default to zero cost. Modules without essential default to True. Existing code is unaffected.

Reference Implementation: ResourceCost, ModuleSpec.cost, ModuleSpec.essential, Wire.cost in operon_ai/core/wagent.py

3. Static Analysis

The analyzer examines a WiringDiagram without executing it, extracting structural information that guides optimization.

3.1 Dependency Graph and Parallel Groups

dependency_graph() builds the adjacency list of module dependencies. find_independent_groups() uses topological layering to identify sets of modules with no mutual dependencies—these can execute concurrently.

flowchart LR A["Parser (5 ATP)"] -->|wire| B["Validator (10 ATP)"] A -->|wire| C["Enricher (30 ATP)"] A -->|wire| D["Logger (2 ATP)"] B --> E["Output (3 ATP)"] C --> E D --> E
groups = find_independent_groups(diagram)
# [{'Parser'}, {'Validator', 'Enricher', 'Logger'}, {'Output'}]
#                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#                These three can execute in parallel

3.2 Dead Wire Detection

A wire is “dead” if it carries a PrismOptic whose accepted types have no intersection with the source port’s DataType. Such a wire can never transmit data—the prism will always reject.

# Source outputs JSON, but the prism only accepts ERROR
dead_prism = PrismOptic(accept=frozenset({DataType.ERROR}))
diagram.connect("Parser", "out", "ErrorSink", "err", optic=dead_prism)

dead = find_dead_wires(diagram)
# [Wire(Parser.out -> ErrorSink.err)]

Biological Parallel

Dead wires are vestigial metabolic pathways—enzymes that never encounter their substrate. Cells downregulate these through transcriptional silencing. The optimizer eliminates them outright.

3.3 Critical Path

The critical path is the longest cost-weighted path through the dependency DAG. It determines the minimum execution time under maximal parallelism—no schedule can complete faster than the critical path cost.

Definition: Critical Path

For a cost-annotated diagram $D = (M, W, c_M, c_W)$, the critical path is:

$$\text{CP}(D) = \arg\max_{P \in \text{Paths}(D)} \sum_{m \in P} c_M(m) + \sum_{w \in P} c_W(w)$$

In metabolic terms, this is the rate-limiting pathway—the bottleneck whose throughput constrains the entire system.

path, cost = critical_path(diagram)
# path = ['Parser', 'Enricher', 'Output']
# cost = ResourceCost(atp=38, latency_ms=62.0)
#
# The Enricher branch (30 ATP) dominates over
# Validator (10 ATP) and Logger (2 ATP)

3.4 Optimization Suggestions

suggest_optimizations() returns human-readable suggestions combining all analyses:

suggestions = suggest_optimizations(diagram)
# [parallel]   Modules ['Enricher', 'Logger', 'Validator'] can execute concurrently
# [dead_wire]  Wire Parser.out -> ErrorSink.err can never transmit
# [cost_hotspot] Module 'Enricher' consumes 30 ATP (58% of total)
Reference Implementation: operon_ai/core/analyzer.py

4. Rewriting Rules as Endofunctors

Each optimization pass is an endofunctor $F : \mathbf{WDiag} \to \mathbf{WDiag}$ on the category of wiring diagrams. The critical property: $F$ preserves input-output behavior. An optimized diagram is bisimilar to the original—no observer can distinguish them.

Theorem: Optimization Soundness

If $F$ only removes wires that provably never transmit (dead wire elimination) or reorders modules within the same topological layer (cost-order scheduling), then $F(D)$ is bisimilar to $D$ for all diagrams $D$.

Three concrete passes are implemented:

PassEffectBiological Analogy
EliminateDeadWires Remove provably-dead prism wires Pruning vestigial metabolic branches
ParallelGrouping Identify concurrent execution groups Independent pathway compartmentalization
CostOrderSchedule Prefer cheaper modules first within groups Low-$K_m$ enzyme preferential activation

Passes compose via the optimize() pipeline:

optimized = optimize(diagram)
# OptimizedDiagram(
#   passes_applied=['eliminate_dead_wires', 'parallel_grouping', 'cost_order_schedule'],
#   eliminated_wires=[Wire(Parser.out -> ErrorSink.err)],
#   parallel_groups=[{'Parser'}, {'Logger', 'Validator', 'Enricher'}, {'Output'}],
#   schedule=['Parser', 'Logger', 'Validator', 'Enricher', 'Output'],
# )

Note the schedule: within the parallel group, Logger (2 ATP) comes before Validator (10 ATP) comes before Enricher (30 ATP). Cheaper modules first, so if a budget cap is hit mid-group, the expensive modules are the ones that get skipped.

Reference Implementation: OptimizationPass, EliminateDeadWires, ParallelGrouping, CostOrderSchedule, optimize() in operon_ai/core/optimizer.py

5. Resource-Aware Execution

The ResourceAwareExecutor replaces the naive topological-sort executor with metabolic-state-gated scheduling. It takes an ATP_Store and adapts its behavior based on energy availability:

flowchart TB subgraph FEASTING["NORMAL / FEASTING"] direction LR F1["All modules execute"] F2["Independent groups in parallel"] F1 --- F2 end subgraph CONSERVING["CONSERVING"] direction LR C1["Cheap modules execute"] C2["Expensive non-essential deferred"] C1 --- C2 end subgraph STARVING["STARVING"] direction LR S1["Essential modules only"] S2["Non-essential skipped"] S1 --- S2 end FEASTING -->|"ATP depleting"| CONSERVING CONSERVING -->|"ATP critical"| STARVING
# Normal state: full parallel execution
store = ATP_Store(budget=200, silent=True)
executor = ResourceAwareExecutor(optimized, store, max_workers=4)
# ... register handlers ...
report = executor.execute(external_inputs={...})
# report.execution_order = ['Parser', 'Logger', 'Enricher', 'Validator', 'Output']
# report.skipped_modules = []
# report.total_cost = ResourceCost(atp=50)

# Starving state: non-essential modules skipped
store2 = ATP_Store(budget=100, silent=True)
store2.consume(92, "drain")  # 8% remaining -> STARVING
executor2 = ResourceAwareExecutor(optimized, store2)
report2 = executor2.execute(external_inputs={...})
# report2.skipped_modules = ['Logger', 'Enricher']
# Only essential modules (Parser, Validator) execute

The executor also deducts wire transmission costs from the ATP store. Each module execution and wire transmission is metered, producing a complete ResourceAwareReport with total cost and skipped module tracking.

Biological Parallel

This directly mirrors cellular starvation response. Under ATP depletion, cells shut down biosynthetic pathways (non-essential) to conserve energy for survival functions (essential). The essential flag is the software equivalent of marking a gene as required for viability under stress conditions.

Reference Implementation: ResourceAwareExecutor, ResourceAwareReport in operon_ai/core/wiring_runtime.py

6. BudgetOptic

The BudgetOptic provides wire-level cost capping. It tracks cumulative cost across transmissions and blocks further data flow once the budget is exhausted:

budget = BudgetOptic(max_cost=10)
budget.can_transmit(DataType.JSON, IntegrityLabel.VALIDATED)  # True

budget.add_cost(8)   # 8/10 spent
budget.remaining     # 2

budget.add_cost(5)   # 13/10 spent -> over budget
budget.can_transmit(DataType.JSON, IntegrityLabel.VALIDATED)  # False

This is allosteric feedback inhibition at the wire level: once a pathway has consumed its energy budget, the pathway shuts down. BudgetOptic composes with existing optics via ComposedOptic, so you can combine cost capping with prism routing or traversal transforms on the same wire.

Reference Implementation: BudgetOptic in operon_ai/core/optics.py

7. Paper Section

A new paper section (§7, Diagram Optimization via Categorical Rewriting) formalizes the above. Key definitions:

Definition: Cost-Annotated Wiring Diagram

A tuple $(M, W, c_M, c_W)$ where $M$ is a finite set of modules with typed ports, $W$ is a set of wires, $c_M : M \to \mathbb{R}_{\geq 0}^3$ assigns resource costs to modules, and $c_W : W \to \mathbb{Z}_{\geq 0}$ assigns transmission costs to wires. The path cost is $\sum c_M(m_i) + \sum c_W(w_i)$.

The section also positions operon’s approach relative to Abbott & Zardini: where they optimize IO transfer costs across GPU memory hierarchies, operon optimizes coalgebraic systems with internal state. The key differentiators are optimization target (IO costs vs. agent orchestration), dynamic state (runtime metabolic gating vs. static analysis), and scope of composition (multi-agent workflows vs. single-algorithm pipelines).

8. Test Coverage

SuiteTestsStatus
Diagram Analyzer 17 All pass
Diagram Optimizer 12 All pass
Resource-Aware Executor 7 All pass
Existing (regression) 827 All pass
Total 863 All pass

9. Example

ExampleFeature
65_diagram_optimization.py Cost annotations, static analysis, optimizer passes, naive vs. resource-aware execution, BudgetOptic

10. What’s Next

With cost-annotated diagrams and resource-aware execution in place, several directions open up:

Code and examples: github.com/coredipper/operon