EP-0194: Atomic Algebraic Mixins & Diamond-Free Protocol Composition¶
| Field | Value |
|---|---|
| EP | 0194 |
| Title | Atomic Algebraic Mixins & Diamond-Free Protocol Composition |
| Author | Eran Rivlis eran@rivlis.info, Antigravity |
| Sponsor | Council Framework |
| Delegate | 🧩 Russell (Taxonomy & Type Theory) & ⚖️ Noether (Algebraic Invariants) |
| Status | Superseded |
| Type | Standards Track |
| Created | 2026-11-01 |
| Updated | 2026-11-12 |
| Replaces | — |
| Superseded-By | EP-0005 |
Abstract¶
This proposal refactors the protocol architecture in algebrax.algebra (established in EP-0190 and EP-0191) to eliminate deep inheritance chaining and diamond inheritance graphs. By separating Atomic Operational Mixins (HasZero, HasZeroPred, HasOne, HasAdd, HasNeg, HasMul, HasInv, HasScale / HasSMul, HasStar, HasJoin, HasMeet, HasBounds, HasComplement, HasOp, HasIdentity, HasBracket) from Named Algebraic Protocols (Monoid, Group, Semiring, Ring, Field, Module, Algebra, Lattice), every named algebraic protocol becomes a flat, depth-2 composition of orthogonal primitives. Because Python's @runtime_checkable Protocol evaluates structural subtyping via attribute supersets (__protocol_attrs__), both runtime isinstance() checks and static type checking (mypy / pyright / ty / pyrefly) automatically preserve all mathematical subtyping relationships without diamond Method Resolution Orders (MROs).
Following unanimous Grand Council review (Noether, Russell, Popper, Shannon, The Golem, Feynman, The Explorer), this proposal enforces explicit (R, M) generic parameter ordering on two-sorted protocols, preserves zero-divisor predicates via HasZeroPred, keeps __protocol_attrs__ strictly minimal for unboxed duck-typing, eliminates cross-module protocol imports, and establishes the permanent Law of Flat Protocol Composition for Phases 7 and 8.
Motivation¶
In EP-0190 and EP-0191, algebraic protocols were chained nominally on top of one another (Algebra -> NonAssocAlgebra -> Module -> Semimodule -> AddCommMonoid -> AddMonoid -> AddSemigroup -> AddMagma). While mathematically intuitive at first glance, this nominal chaining conflated reusable operational building blocks with named mathematical bundles, producing three structural liabilities:
- Pervasive Diamond Inheritance:
Ringinherits fromNonAssocRing[V]andMonoid[V], both of which independently inherit fromMagma[V].Fieldinherits fromDivisionRing[V]andCommRing[V], both of which independently inherit fromRing[V].Algebrainherits fromNonAssocAlgebra[R, M]andRing[M], both of which independently inherit fromNonAssocRing[M]andAddCommGroup[M].CommGroupinherits fromGroup[V]andCommMonoid[V], both of which inherit fromMonoid[V].-
BooleanAlgebrainherits fromBoundedLattice[V]andDistributiveLattice[V], both of which inherit fromLattice[V]. -
Duplicated Derived Operations (
sub,div,is_zero) & Inter-Module Coupling: - Default derived operations like
div(a, b) = mul(a, inv(b))were duplicated acrossGroup(_group.py) andDivisionRing(_ring.py), while binary exponentiation (nsum,power) was duplicated verbatim betweenSemiring(_semiring.py) and_helpers.py. -
Protocol modules formed a 5-deep import chain (
_module -> _ring -> _group -> _monoid -> _magma). -
Obscured Signatures & Redundant
Protocol[V]Boilerplate: - Inspecting
class Algebra(NonAssocAlgebra[R, M], Ring[M], Protocol[R, M])required tracing 8 classes across 4 files to discover the actual required methods (zero,one,add,neg,sub,mul,smul). - Every intermediate protocol repeated
Protocol[V]orGeneric[V]even when type parameters were already bound by parent bases.
The Mental Model (The Periodic Table of Algebra)¶
Instead of a tangled family tree where every cousin marries back into the same ancestors, think of algebraic structures like molecules assembled from atomic elements and functional groups:
- Elementary Atoms (Single-Operation Mixins): Each
Has*protocol represents a single mathematical capability: HasZero(\(\mathbf{0}\)),HasOne(\(\mathbf{1}\)),HasAdd(\(+\)),HasMul(\(\cdot\)),HasScale/HasSMul(\(r \cdot m\)),HasStar(Kleene \(a^*\)),HasJoin(\(\vee\)),HasMeet(\(\wedge\)),HasBounds(\(\bot, \top\)),HasComplement(\(\neg\)),HasOp(\(\operatorname{op}\)),HasIdentity(\(\operatorname{id}\)),HasBracket(\([\cdot, \cdot]\)).- Bonded Functional Groups (Derived-Generator Mixins): Just as a hydroxyl group (\(\text{-OH}\)) in chemistry is a bonded pair, three mixins bundle an operation with its prerequisite so their derived operation comes for free:
HasNeg(HasAdd[V], Protocol): Bundlesaddandneg(\(-a\)) with default subtractionsub(a, b) = add(a, neg(b)).HasInv(HasMul[V], Protocol): Bundlesmulandinv(\(a^{-1}\)) with default divisiondiv(a, b) = mul(a, inv(b)).HasZeroPred(HasZero[V], Protocol): Bundleszero(\(\mathbf{0}\)) with default zero-testis_zero(a) = (a == zero)for division rings and fields.- Molecules & Structural Isomers (Named Algebraic Protocols):
Every named protocol (
Monoid,Group,Semiring,Ring,Field,Module,Algebra) is a flat formula of atoms and functional groups. When two named protocols share the exact same operational formula—such asRing[V]andCommRing[V], orMagma[V],Semigroup[V], andBand[V]—they are algebraic isomers (like graphite and diamond, both pure carbon): the mixins define the operational syntax (checked byisinstanceandmypy), while the named protocols declare the mathematical laws (checked byverify_*_laws).
Rationale & Council Alignment¶
- 🧩 Russell (Taxonomy & Type Theory): Aligns directly with Lean 4 Mathlib's unbundled operational typeclasses (
Zero,One,Add,Neg,Sub,Mul,Inv,Div,SMul). Eliminates all diamond MRO paths acrossalgebrax.algebrawhile preserving 100% of the named mathematical protocols, including the domain-agnosticOp*branch,Quasigroup, andGroupAction. - ⚖️ Noether (Algebraic Invariants & Duality): Places derived operations (
sub,div,is_zero) on their exact algebraic symmetry generators: additive inversion generates subtraction (HasNeg.sub), multiplicative inversion generates division (HasInv.div), and additive identity generates zero-testing (HasZeroPred.is_zero). - 🔬 Popper (Falsifiability &
__protocol_attrs__Minimality): Protects unboxed duck-typing by keepingHasZero,HasOne,HasAdd, andHasMulstrictly minimal ({'zero'},{'one'},{'add'},{'mul'}). Standalone polymorphic algorithms (nsum,zsmul,power,zpow,fold_*) remain inalgebrax.algebra._helpersso duck-typedMonoid,Group, andRingclasses do not need to implement.power()or.nsum()to satisfyisinstance(). - ⚡ Shannon (Information Density & Dependency Flattening): Flattens MRO depth from 8 levels to 2 levels and drops the internal protocol import graph depth from 5 to 1 (every protocol module imports exclusively from
_mixins.py). DeduplicatesSemiring.nsumandSemiring.powerby delegating directly to_helpers.py. - 🛡️ The Golem (Runtime & Static Subtyping Invariants): Enforces
HasScale[R, M]as the first base class alongside explicitProtocol[R, M]on all two-sorted protocols (Semimodule,Module,VectorSpace,NonAssocAlgebra,Algebra) socls.__parameters__is strictly locked to(R, M)rather than inverted to(M, R). - 💡 Feynman (Self-Documenting Clarity): Every named protocol declaration reads identically to its formal mathematical tuple \(\langle S, +, \cdot, \mathbf{0}, \mathbf{1} \rangle\), and
HasSMulis provided as an exact alias forHasScaleto match the.smul()method name. - 🧭 The Explorer (Frontier Synthesis): Establishes the Law of Flat Protocol Composition and introduces
HasBracket[V], preventing multi-diamond explosions in Phase 7 & 8 structures (PoissonAlgebra,Bialgebra,HopfAlgebra,NormedSpace).
Specification¶
1. Layer 1: Atomic Operational Mixins (src/algebrax/algebra/_mixins.py)¶
A new foundational module _mixins.py defines all orthogonal single-operation atoms and bonded functional groups:
from typing import Protocol, TypeVar, runtime_checkable
V = TypeVar('V')
R = TypeVar('R')
M = TypeVar('M')
@runtime_checkable
class HasZero(Protocol[V]):
r"""Additive neutral element $\mathbf{0}$.
Algebraic Signature:
$\langle V, \mathbf{0} \rangle$
"""
@property
def zero(self) -> V: ...
@runtime_checkable
class HasZeroPred(Protocol[V]):
r"""Zero-divisor predicate `is_zero(a)` testing whether an element equals $\mathbf{0}$.
Algebraic Signature:
$\langle V, \operatorname{is\_zero} \rangle$
"""
def is_zero(self, a: V) -> bool:
"""Return True if element is the additive zero."""
return a == self.zero # type: ignore[attr-defined]
@runtime_checkable
class HasOne(Protocol[V]):
r"""Multiplicative neutral element $\mathbf{1}$.
Algebraic Signature:
$\langle V, \mathbf{1} \rangle$
"""
@property
def one(self) -> V: ...
@runtime_checkable
class HasAdd(Protocol[V]):
r"""Binary addition operation $+: V \times V \to V$.
Algebraic Signature:
$\langle V, + \rangle$
"""
def add(self, a: V, b: V) -> V: ...
@runtime_checkable
class HasNeg(Protocol[V]):
r"""Additive inverse $-: V \to V$ and derived subtraction $a - b = a + (-b)$.
Algebraic Signature:
$\langle V, - \rangle$
"""
def neg(self, a: V) -> V: ...
def sub(self, a: V, b: V) -> V:
"""Difference a - b = a + neg(b)."""
return self.add(a, self.neg(b)) # type: ignore[attr-defined]
@runtime_checkable
class HasMul(Protocol[V]):
r"""Binary multiplication operation $\cdot: V \times V \to V$.
Algebraic Signature:
$\langle V, \cdot \rangle$
"""
def mul(self, a: V, b: V) -> V: ...
@runtime_checkable
class HasInv(Protocol[V]):
r"""Multiplicative inverse $^{-1}: V \to V$ and derived quotient $a / b = a \cdot b^{-1}$.
Algebraic Signature:
$\langle V, ^{-1} \rangle$
"""
def inv(self, a: V) -> V: ...
def div(self, a: V, b: V) -> V:
"""Quotient a / b = a * inv(b)."""
return self.mul(a, self.inv(b)) # type: ignore[attr-defined]
@runtime_checkable
class HasScale(Protocol[R, M]):
r"""External scalar multiplication $\cdot: R \times M \to M$.
Algebraic Signature:
$\langle M, R, \cdot \rangle$
"""
def smul(self, r: R, m: M) -> M: ...
HasSMul = HasScale # Canonical Mathlib-aligned alias matching .smul()
@runtime_checkable
class HasStar(Protocol[V]):
r"""Kleene closure operation $a^* = \mathbf{1} \oplus a \oplus a^2 \oplus \cdots$.
Note: Denotes idempotent/convergent Kleene star closure in semirings and automata,
distinct from involutive conjugate/adjoint operations ($a^\dagger$) in $^*$-algebras.
Algebraic Signature:
$\langle V, ^* \rangle$
"""
def star(self, a: V) -> V: ...
@runtime_checkable
class HasJoin(Protocol[V]):
r"""Lattice least upper bound (join) $\vee: V \times V \to V$.
Algebraic Signature:
$\langle L, \vee \rangle$
"""
def join(self, a: V, b: V) -> V: ...
@runtime_checkable
class HasMeet(Protocol[V]):
r"""Lattice greatest lower bound (meet) $\wedge: V \times V \to V$.
Algebraic Signature:
$\langle L, \wedge \rangle$
"""
def meet(self, a: V, b: V) -> V: ...
@runtime_checkable
class HasBounds(Protocol[V]):
r"""Lattice bottom ($\bot$) and top ($\top$) bounds.
Algebraic Signature:
$\langle L, \bot, \top \rangle$
"""
@property
def bot(self) -> V: ...
@property
def top(self) -> V: ...
@runtime_checkable
class HasComplement(Protocol[V]):
r"""Unary lattice complement $\neg: V \to V$.
Algebraic Signature:
$\langle B, \neg \rangle$
"""
def complement(self, a: V) -> V: ...
@runtime_checkable
class HasOp(Protocol[V]):
r"""Domain-agnostic binary operation $\operatorname{op}: V \times V \to V$.
Algebraic Signature:
$\langle M, \operatorname{op} \rangle$
"""
def op(self, a: V, b: V) -> V: ...
@runtime_checkable
class HasIdentity(Protocol[V]):
r"""Domain-agnostic neutral identity element.
Algebraic Signature:
$\langle M, \operatorname{identity} \rangle$
"""
@property
def identity(self) -> V: ...
@runtime_checkable
class HasBracket(Protocol[V]):
r"""Bilinear bracket operation $[\cdot, \cdot]: V \times V \to V$.
Algebraic Signature:
$\langle \mathfrak{g}, [\cdot, \cdot] \rangle$
"""
def bracket(self, a: V, b: V) -> V: ...
[!IMPORTANT] Purely Orthogonal Mixins (Zero Mixin-to-Mixin Inheritance): Every
Has*mixin in_mixins.pyinherits directly and exclusively fromProtocol. NeitherHasNeg,HasInv, norHasZeroPredinherits fromHasAdd,HasMul, orHasZero. Consequently, every Named Protocol explicitly lists all of its constituent operational mixins in its class declaration (e.g.,Group(HasOne[V], HasMul[V], HasInv[V], Protocol)), making every class header 100% self-documenting and mathematically transparent while guaranteeing zero diamond inheritance by construction.
2. Layer 2: Flat Named Algebraic Protocols¶
Every named algebraic protocol is composed directly from the orthogonal mixins in _mixins.py with zero imports between named protocol modules:
| Named Protocol | Flat Mixin Composition | Mixin-Aligned Algebraic Signature |
|---|---|---|
Magma[V] / Semigroup[V] / Band[V] |
(HasMul[V], Protocol) |
\(\langle V, \cdot \rangle\) |
Quasigroup[V] |
(HasMul[V], Protocol) (+ ldiv, rdiv) |
\(\langle V, \cdot, \backslash, / \rangle\) |
AddMagma[V] / AddSemigroup[V] |
(HasAdd[V], Protocol) |
\(\langle V, + \rangle\) |
OpMagma[V] / OpSemigroup[V] |
(HasOp[V], Protocol) |
\(\langle V, \operatorname{op} \rangle\) |
Monoid[V] / CommMonoid[V] |
(HasOne[V], HasMul[V], Protocol) |
\(\langle V, \mathbf{1}, \cdot \rangle\) |
AddMonoid[V] / AddCommMonoid[V] |
(HasZero[V], HasAdd[V], Protocol) |
\(\langle V, \mathbf{0}, + \rangle\) |
OpMonoid[V] / OpCommMonoid[V] |
(HasIdentity[V], HasOp[V], Protocol) |
\(\langle V, \operatorname{identity}, \operatorname{op} \rangle\) |
Group[V] / CommGroup[V] |
(HasOne[V], HasMul[V], HasInv[V], Protocol) |
\(\langle V, \mathbf{1}, \cdot, ^{-1} \rangle\) |
AddGroup[V] / AddCommGroup[V] |
(HasZero[V], HasAdd[V], HasNeg[V], Protocol) |
\(\langle V, \mathbf{0}, +, - \rangle\) |
GroupAction[G, X] |
(Protocol[G, X]) (+ gact) |
\(\langle G, X, \operatorname{gact} \rangle\) |
Semiring[V] |
(HasZero[V], HasAdd[V], HasOne[V], HasMul[V], HasStar[V], Protocol) |
\(\langle V, \mathbf{0}, +, \mathbf{1}, \cdot, ^* \rangle\) |
NonAssocRing[V] |
(HasZero[V], HasAdd[V], HasNeg[V], HasMul[V], Protocol) |
\(\langle V, \mathbf{0}, +, -, \cdot \rangle\) |
Ring[V] / CommRing[V] |
(HasZero[V], HasAdd[V], HasNeg[V], HasOne[V], HasMul[V], Protocol) |
\(\langle V, \mathbf{0}, +, -, \mathbf{1}, \cdot \rangle\) |
DivisionRing[V] / Field[V] |
(HasZero[V], HasZeroPred[V], HasAdd[V], HasNeg[V], HasOne[V], HasMul[V], HasInv[V], Protocol) |
\(\langle V, \mathbf{0}, \operatorname{is\_zero}, +, -, \mathbf{1}, \cdot, ^{-1} \rangle\) |
Semimodule[R, M] |
(HasScale[R, M], HasZero[M], HasAdd[M], Protocol[R, M]) |
\(\langle R, M, \cdot_s, \mathbf{0}, + \rangle\) |
Module[R, M] / VectorSpace[R, M] |
(HasScale[R, M], HasZero[M], HasAdd[M], HasNeg[M], Protocol[R, M]) |
\(\langle R, M, \cdot_s, \mathbf{0}, +, - \rangle\) |
NonAssocAlgebra[R, M] |
(HasScale[R, M], HasZero[M], HasAdd[M], HasNeg[M], HasMul[M], Protocol[R, M]) |
\(\langle R, M, \cdot_s, \mathbf{0}, +, -, \cdot \rangle\) |
Algebra[R, M] |
(HasScale[R, M], HasZero[M], HasAdd[M], HasNeg[M], HasOne[M], HasMul[M], Protocol[R, M]) |
\(\langle R, M, \cdot_s, \mathbf{0}, +, -, \mathbf{1}, \cdot \rangle\) |
JoinSemilattice[V] |
(HasJoin[V], Protocol) |
\(\langle V, \vee \rangle\) |
MeetSemilattice[V] |
(HasMeet[V], Protocol) |
\(\langle V, \wedge \rangle\) |
Lattice[V] / DistributiveLattice[V] |
(HasJoin[V], HasMeet[V], Protocol) |
\(\langle V, \vee, \wedge \rangle\) |
BoundedLattice[V] |
(HasJoin[V], HasMeet[V], HasBounds[V], Protocol) |
\(\langle V, \vee, \wedge, \bot, \top \rangle\) |
BooleanAlgebra[V] |
(HasJoin[V], HasMeet[V], HasBounds[V], HasComplement[V], Protocol) |
\(\langle V, \vee, \wedge, \bot, \top, \neg \rangle\) |
[!CAUTION] Two-Sorted Generic Parameter Order (
[R, M]): OnSemimodule[R, M],Module[R, M],VectorSpace[R, M],NonAssocAlgebra[R, M], andAlgebra[R, M],HasScale[R, M]must appear first in the base list andProtocol[R, M]must be explicitly subscripted. Otherwise, ifHasZero[M]appeared beforeHasScale[R, M]with unsubscriptedProtocol, Python'sGenericmetaclass would collectTypeVarparameters in order of first appearance as(M, R), inverting the scalar ring typeRand carrier typeM!
3. Verification of Diamond-Free MRO & _helpers.py Delegation¶
- Zero Duplicate MRO Paths:
Every protocol in
algebrax.algebrahas a strictly flat, depth-2 MRO of orthogonal mixins ordered by Additive cluster \(\to\) Multiplicative cluster \(\to\) Closure/Bounds: Group.mro():[Group, HasOne, HasMul, HasInv, Protocol, Generic, object]Algebra.mro():[Algebra, HasScale, HasZero, HasAdd, HasNeg, HasOne, HasMul, Protocol, Generic, object]Field.mro():[Field, HasZero, HasZeroPred, HasAdd, HasNeg, HasOne, HasMul, HasInv, Protocol, Generic, object]-
BooleanAlgebra.mro():[BooleanAlgebra, HasJoin, HasMeet, HasBounds, HasComplement, Protocol, Generic, object] -
Deduplication of
Semiring.nsumandSemiring.power: Insrc/algebrax/algebra/_semiring.py,Semiring.nsum(self, a: V, n: int) -> VandSemiring.power(self, a: V, n: int) -> Vdelegate directly tonsum(self, a, n)andpower(self, a, n)insrc/algebrax/algebra/_helpers.py, eliminating 40 lines of duplicated binary exponentiation loops while keepingHasZero,HasOne,HasAdd, andHasMulfree of extra__protocol_attrs__methods.
4. Preservation of Structural Subtyping (isinstance and Static Typing)¶
Because Python's @runtime_checkable _ProtocolMeta.__instancecheck__ verifies whether an instance provides all attributes in cls.__protocol_attrs__:
- Fields & Division Rings (
StandardField,ModularField): Provide{zero, is_zero, one, add, neg, sub, mul, inv, div}: isinstance(field, DivisionRing)\(\to\)Trueisinstance(field, CommRing)/isinstance(field, Ring)/isinstance(field, NonAssocRing)\(\to\)Trueisinstance(field, AddCommGroup)/isinstance(field, AddGroup)/isinstance(field, AddCommMonoid)/isinstance(field, AddMonoid)\(\to\)Trueisinstance(field, CommGroup)/isinstance(field, Group)/isinstance(field, CommMonoid)/isinstance(field, Monoid)\(\to\)True(reflecting operational subsumption whereinvanddivact on the multiplicative group of units \(F^\times = F \setminus \{\mathbf{0}\}\) and raiseZeroDivisionErrorat \(\mathbf{0}\))- Associative Unital Algebras (
CliffordAlgebra,PolynomialAlgebra,DualNumberAlgebra,CochainAlgebra): Provide{zero, one, add, neg, sub, mul, smul}: isinstance(alg, Algebra)/isinstance(alg, NonAssocAlgebra)\(\to\)Trueisinstance(alg, Module)/isinstance(alg, Semimodule)\(\to\)Trueisinstance(alg, Ring)/isinstance(alg, NonAssocRing)\(\to\)True- Non-Associative Algebras (
LieAlgebra): Provide{zero, add, neg, sub, mul, smul, bracket}(and notone): isinstance(lie, NonAssocAlgebra)/isinstance(lie, Module)/isinstance(lie, NonAssocRing)\(\to\)Trueisinstance(lie, Ring)/isinstance(lie, Algebra)\(\to\)False(missingone)SemiringvsRing/FieldBoundary:- Every
Semiringinstance structurally satisfiesAddCommMonoid,AddMonoid,AddSemigroup,AddMagma,CommMonoid,Monoid,Semigroup, andMagma. - Domain algebras that subclass
Semiring(CliffordAlgebra,PolynomialAlgebra,DualNumberAlgebra,StandardSemiring) satisfy bothSemiringandRing/Algebra. - General
RingandFieldprotocols do not includeHasStar(star()) because arbitrary rings and fields (StandardField,ModularField,CochainAlgebra) do not admit a total Kleene closure \(a^* = 1 + a + a^2 + \cdots\). - Runtime
isinstancevsissubclassNote (PEP 544): - Callers must always use
isinstance(instance, Protocol)at runtime and protocol type annotations for static subtyping; per PEP 544, Python'sissubclass(Cls, Protocol)raisesTypeErroron protocols with@propertymembers (zero,one,bot,top,identity) whenProtocolis not inCls.__mro__.
5. Forward Compatibility: The Law of Flat Protocol Composition (Phases 7 & 8)¶
To prevent diamond inheritance from ever re-entering the codebase in Phases 7 and 8 (EP-0200–EP-0215), this proposal establishes a permanent architectural invariant:
The Law of Flat Protocol Composition: No Named Algebraic Protocol (Layer 2) may ever inherit from another Named Algebraic Protocol—only from Layer 1 Atomic Operational Mixins (
Has*) andProtocol. Structural subtyping between Layer 2 protocols is guaranteed automatically by PEP 544 attribute superset inclusion.
For example, in Phase 7:
- PoissonAlgebra[R, M] (EP-0204): Composes (HasScale[R, M], HasZero[M], HasOne[M], HasNeg[M], HasMul[M], HasBracket[M], Protocol[R, M])—avoiding diamond collisions between CommAlgebra and LieAlgebra and keeping .mul() (commutative associative product) distinct from .bracket() (Lie bracket).
- Bialgebra[R, M] & HopfAlgebra[R, M] (EP-0206): Compose Algebra mixins with coalgebraic mixins (HasCoproduct, HasCounit, HasAntipode) at depth 2 with zero diamonds.
Backwards Compatibility¶
- 100% Public Symbol Compatibility:
- All existing 31 protocol names and aliases (
Magma,Semigroup,Band,Quasigroup,Monoid,CommMonoid,CommutativeMonoid,Group,CommGroup,AbelianGroup,GroupAction,AddMagma,AddSemigroup,AddMonoid,AddCommMonoid,AddGroup,AddCommGroup,OpMagma,OpSemigroup,OpMonoid,OpCommMonoid,Semiring,NonAssocRing,Ring,CommRing,CommutativeRing,AbelianRing,DivisionRing,Field,Semimodule,Module,VectorSpace,NonAssocAlgebra,Algebra,JoinSemilattice,MeetSemilattice,Lattice,BoundedLattice,DistributiveLattice,BooleanAlgebra) remain exported fromalgebrax.algebra. - All atomic mixins (
HasZero,HasZeroPred,HasOne,HasAdd,HasNeg,HasMul,HasInv,HasScale,HasSMul,HasStar,HasJoin,HasMeet,HasBounds,HasComplement,HasOp,HasIdentity,HasBracket) are exported fromalgebrax.algebra. - Concrete Implementations Unchanged:
- Concrete classes (
StandardSemiring,StandardField,ModularField,PolynomialAlgebra,DualNumberAlgebra,CliffordAlgebra,LieAlgebra,CochainAlgebra) require zero changes to their public APIs.
How to Teach This / Documentation Plan¶
- Update EP-0193 (Documentation Architecture Realignment) to introduce the Periodic Table of Algebraic Mixins (Atoms, Functional Groups, Molecules, and Isomers) in
docs/concepts.mdanddocs/guide/algebra/magmas_and_monoids.md. - Show how complex structures (
Ring,Field,Algebra) are flat combinations of elementary operational capabilities rather than deep OOP inheritance trees.
Reference Implementation¶
Implementation targets src/algebrax/algebra/ and tests/algebrax/test_type_safety.py:
- src/algebrax/algebra/_mixins.py (new atomic mixins)
- src/algebrax/algebra/_magma.py (imports only from _mixins.py)
- src/algebrax/algebra/_monoid.py (imports only from _mixins.py)
- src/algebrax/algebra/_group.py (imports only from _mixins.py)
- src/algebrax/algebra/_semiring.py (composes mixins and delegates nsum/power to _helpers.py)
- src/algebrax/algebra/_ring.py (imports only from _mixins.py)
- src/algebrax/algebra/_field.py (imports only from _mixins.py for protocols)
- src/algebrax/algebra/_module.py (imports only from _mixins.py)
- src/algebrax/algebra/_lattice.py (imports only from _mixins.py)
- src/algebrax/algebra/__init__.py (exports all mixins and named protocols)
- tests/algebrax/test_type_safety.py (verifies diamond-free MROs, (R, M) parameter order, and __protocol_attrs__ subtyping lattice)
Rejected Ideas¶
- Retaining Deep Nominal Protocol Chaining:
- Rejected: Caused 5 distinct diamond inheritance patterns across
Ring,Field,Algebra,CommGroup, andBooleanAlgebra, and forced redundantProtocol[V]declarations at every level. - Placing
nsum,power, oris_zeroDirectly onHasZero/HasOne: - Rejected: In Python's
@runtime_checkableProtocol, any method with a default body defined on a protocol is added tocls.__protocol_attrs__. Addingnsumoris_zerotoHasZeroorpowertoHasOnewould cause unboxed/duck-typedMonoid,Group, andRingclasses that do not define.nsum(),.power(), or.is_zero()to failisinstance()checks. Keepingis_zeroonHasZeroPred(used byDivisionRingandField) and keepingnsum/powerin_helpers.py(and onSemiring) preserves duck-typing minimality. - Removing Named Protocols in Favor of Only Mixins:
- Rejected: Mathematicians and domain engineers think in terms of
Ring,Field,Group,Module, andAlgebra, not(HasZero[V], HasOne[V], HasNeg[V], HasMul[V]). Named protocols provide essential semantic clarity while mixins provide the clean compositional substrate.
Open Questions¶
- [x] Should
HasNeg,HasInv, andHasZeroPredinherit fromHasAdd,HasMul, andHasZeroor remain purely orthogonal? (Resolved: Purely orthogonal—each inherits directly fromProtocol[V]so every named protocol explicitly lists all of its operational mixins in its class declaration, e.g.Group(HasOne[V], HasMul[V], HasInv[V], Protocol)). - [x] How should
DivisionRing.is_zeroandField.is_zerobe shared without pollutingHasZero? (Resolved: ViaHasZeroPred(Protocol[V])used alongsideHasZero[V]inDivisionRingandField). - [x] How should
(R, M)generic type parameter ordering be preserved on two-sorted protocols? (Resolved: PlaceHasScale[R, M]first in the base tuple and explicitly subscriptProtocol[R, M]).
Change Log¶
- 2026-11-01:
- Initial Draft authored by Eran Rivlis & Antigravity.
- Accepted following unanimous Grand Council review: added
HasZeroPredforDivisionRing/Field.is_zero, locked(R, M)parameter order on two-sorted protocols viaHasScale[R, M]-first ordering, addedHasOp,HasIdentity,HasBracket, andHasSMulalias, completed Section 2 table (Quasigroup,GroupAction,Op*), deduplicatedSemiring.nsum/powervia_helpers.py, and codified the Law of Flat Protocol Composition for Phases 7 & 8.