EP-0252: Universal Semiring Propagation, Parameterized Tries & Domain Unification¶
| Field | Value |
|---|---|
| EP | 0252 |
| Title | Universal Semiring Propagation, Parameterized Tries & Domain Unification |
| Author | Eran Rivlis eran@rivlis.info, Antigravity |
| Sponsor | Core Maintainers |
| Delegate | 🧭 Explorer (Vision) & ⚖️ Noether (Symmetry) |
| Status | Final |
| Type | Standards Track |
| Created | 2026-11-26 |
| Updated | 2026-11-28 |
| Replaces | — |
| Superseded-By | — |
Abstract¶
This proposal restores end-to-end algebraic parameterization across AlgebraX's higher-level domains. It introduces a shared zero-predicate helper (make_zero_predicate / is_algebraic_zero) honoring HasZeroPred without per-iteration isinstance checks, upgrades AlgebraicTrie and tensor.einsum/outer_product/dot to preserve live parameterized Semiring instances with hash-join contractions, fixes ignored coefficient structures in SparseChainComplex.hodge_laplacian, Cochain/CochainAlgebra, GroupHopfAlgebra, pagerank, and automata, and unifies TopologicalKTheoryRing onto algebra.CommGrothendieckRing.
Motivation¶
AlgebraX's signature architectural strength is universal parameterization: swapping StandardSemiring for TropicalSemiring, ModularField(7), GaloisField, Fraction, or PolynomialAlgebra should work seamlessly across matrices, tensors, topology, Hopf algebras, and automata. The Second Grand Council Audit revealed multiple islands where this contract breaks silently:
- Parameterized Semiring Destruction in
trie.py&tensor/core.py: AlgebraicTrie.__init__only accepts a class (type[Semiring[V]]) and invokes zero-argumentsemiring();__getstate__drops live instance state viatype(self.semiring).tensor.einsumandtensor.outer_productcreate outputs viaAlgebraicTrie(semiring=type(semiring)), either crashing withTypeError(ModularField(7),PAdicField(5),PolynomialAlgebra(...)) or silently resetting parameters (ModularSemiring(7)\(\to\)ModularSemiring(2),GaloisField(3, ...)\(\to\)GF(2^8)), and never callSemiring.normalize(semiring).tensor.einsumuses unindexed recursive Cartesian loops (\(O(\prod_t \text{nnz}_t)\)), andtensor.dotcrashes withIndexErroron empty tensors.- Silently Ignored Coefficient Rings/Semirings & Hardcoded Float Operators:
SparseChainComplex.hodge_laplacianpassessemiring=s_insttodot()forl_downandl_up, then callsadd(l_down, l_up)withoutsemiring=s_inst(and__init__aliases callerboundary_matrices).CochainAlgebra(complex, coefficient_ring)storesself._ringand uses it only in.one, whileadd,neg,sub,smul, andmul(cup_product) ignoreself._ring(andself._complex). Worse,Cochainitself hardcodes Python unary-(breakingModularField/GaloisFieldorientation signs) andcup_product/cap_productfilter via_is_non_zero(v, tol)(silently deleting validTropicalSemiring.one == 0.0entries!).GroupHopfAlgebra(group, coeff_semiring=...)hardcodesfloatgenerics,float(...),sum(...), and1e-15incoproduct,counit, andantipode.analysis.calculus.pagerankpassessemiringtovec_matbut hardcodes Python*and+in damping/teleportation.- Isolated Domain Islands:
automata.py(nfa_step,simulate_nfa) hardcodesdefaultdict(float)and*, ignoringSemiring(BooleanSemiring,TropicalSemiring,ViterbiSemiring,StringSemiring) and Kleene closure viamatrix.closure.matrix_star, and returns aliasedstart_stateson 0-step runs.TopologicalKTheoryRing(topology/k_theory.py) re-implements(pos, neg)formal-difference ring arithmetic from scratch instead of composingalgebra.CommGrothendieckRing.
Rationale¶
- 🧭 The Explorer (Cross-Domain Synergy): Connecting
AlgebraicTrie,tensor,topology,automata, andk_theorythrough normalizedSemiring/Ring/CommGrothendieckRingprimitives unlocks algebraic tensor networks over finite/polynomial fields, weighted finite automata over Kleene algebras, and exact modular/rational cohomology rings with minimal code. - ⚡ Claude Shannon (Efficiency): Hash-join subscript indexing accumulating into a flat
dictinsidetensor.einsumturns three-way diagonal contraction from \(O(N^3)\) to \(O(N)\); hoistinggetattr(sr, 'is_zero', None)once outside loops avoids per-element@runtime_checkableoverhead; maintaining an \(O(1)\)_sizecounter inAlgebraicTrie.__len__removes full-tree DFS scans. - ⚖️ Emmy Noether (Symmetry): Every API accepting a
semiringorcoefficient_ringhonors it identically across every operation while respecting genuine mathematical boundaries (CochainAlgebraandGroupHopfAlgebrarequire aRingfor negation;nfa_closurerequires aStarSemiring;pagerankrequires real/probability-compatible numeric carriers).
Specification¶
0. Shared Zero-Predicate Helper (src/algebrax/converters.py)¶
Neither Semiring nor Ring guarantees an .is_zero() method (HasZeroPred is required only on DivisionRing/Field). Add a shared Layer-1/2 utility consumed across EP-0252 and EP-0254:
def make_zero_predicate(structure: Any, tol: float = 0.0) -> Callable[[Any], bool]:
"""Return a hoisted zero-check callable: uses structure.is_zero if present, else == structure.zero."""
def is_algebraic_zero(structure: Any, value: Any) -> bool:
"""Single-value zero check delegating to structure.is_zero when available, else value == structure.zero."""
Callers in inner loops must hoist is_zero = make_zero_predicate(sr) once outside the loop (never calling @runtime_checkable isinstance(sr, HasZeroPred) per entry).
1. Instance-Aware AlgebraicTrie & Hash-Join tensor.core¶
src/algebrax/trie.py,src/algebrax/clifford.py&src/algebrax/algebra/_field.py:- Update
AlgebraicTrie.__init__(self, semiring: Semiring[V] | type[Semiring[V]] | str = StandardSemiring)to normalize viaSemiring.normalize(semiring), preserving live parameterized instances and serializing the livesemiringinstance cleanly in__getstate__/__setstate__. - Convert local closures
key_op/quotient_fninsideCliffordAlgebra/GeneralizedCliffordAlgebra/QuantumCliffordAlgebra(clifford.py) andGaloisField(algebra/_field.py) to picklable bound methods soAlgebraicTrie(CliffordAlgebra(...))andAlgebraicTrie(GaloisField(...))pickle cleanly. - Maintain an exact \(O(1)\)
_sizecounter across__setitem__(insert, overwrite, and algebraic-zero pruning),__delitem__, and zero-pruning inadd()(usingmake_zero_predicate(self.semiring)and pruning emptied intermediate trie branches so dead subtrees do not accumulate). src/algebrax/tensor/core.py:- Add
Semiring.normalize(semiring)and acceptSemiring[V] | type[Semiring[V]] | str | Noneineinsum,outer_product, anddot. - When
semiring=Noneand multipleAlgebraicTrieoperands are supplied, verify that their live semirings are structurally equivalent and raiseValueErroron mismatch (passsemiring=...explicitly to override). - Pass the normalized live
semiringinstance directly toAlgebraicTrie(semiring=semiring)ineinsum,outer_product, anddot. - In
einsum: contract left-to-right with hash-join indexing on shared already-bound subscripts, accumulating results in a flatdict[tuple[Any, ...], V](pruning zeros via hoistedis_zero) before loading the finalAlgebraicTrieonce. - In
dot(tensor_a, tensor_b, ...): check emptiness in \(O(1)\) vialen(...)and inspect keys directly without double-materializing items, returning an emptyAlgebraicTrie(semiring=semiring)early whenever either operand is empty.
2. End-to-End Coefficient Propagation¶
src/algebrax/topology/homology.py&dec.py:- Forward
semiring=s_instinSparseChainComplex.hodge_laplacian:return add(l_down, l_up, semiring=s_inst). - Copy caller
boundary_matrices({k: {r: dict(row) for r, row in m.items()} for k, m in boundary_matrices.items()}) inSparseChainComplex.__init__so external mutation cannot corrupt the complex. - Add
| strtosemiringtype annotations onSparseChainComplex.verify_nilpotency,SparseChainComplex.hodge_laplacian, anddec.hodge_laplacian. src/algebrax/topology/cohomology.py:- Upgrade
Cochainto support an optionalring: Ring[V] | None = None(orneg_fn+zero+tol=0.0for exact rings) so orientation sign flips in__init__,__getitem__, andgetusering.neg(val)instead of Python unary-val(makingModularField(p)andGaloisFieldwork end-to-end). - Fix
cup_productandcap_productto prune zeros strictly viamake_zero_predicate(s_inst)(applyingabs(v) <= tolonly whens_inst.zero == 0andisinstance(v, (int, float, complex))) soTropicalSemiring.one == 0.0is never deleted. - Route
CochainAlgebra.add,neg,sub,smul, andmulcompletely throughself._ringandself._complex(passingcomplex=self._complex, semiring=self._ringtocup_product), and validate inCochainAlgebra.__init__thatcoefficient_ringis aRing(orStandardSemiringfor backwards compatibility), rejecting non-negatable semirings (BooleanSemiring,TropicalSemiring, etc.) upfront withTypeError. src/algebrax/algebra/_hopf.py:- Generalize
GroupHopfAlgebraclass generics toGeneric[T](MonoidAlgebra[Any, T], HopfAlgebra[T, SparseVector[Any, T]]), type and validatecoeff_semiring: Ring[T] | None = Noneupfront withTypeErrorfor non-Ringsemirings, and routecoproduct,counit, andantipodethroughself.coeff_semiring(zero,add,mul, and hoistedmake_zero_predicate) instead of hardcodedfloat/sum/1e-15. src/algebrax/analysis/calculus.py:- In
pagerank, acceptstrin thesemiringannotation, propagatesem.add/sem.mul/sem.zeroconsistently across the damping and teleportation blend, validate real/numeric carriers (raisingTypeErrorupfront for non-numeric carriers likeStringSemiringandBooleanSemiring), and document that probability-sum normalization gives coherent semantics for multiplicative \([0, 1]\) semirings (StandardSemiring,ViterbiSemiring,BottleneckSemiring) rather than additive-cost semirings.
3. Semiring-Parameterized Weighted Automata (src/algebrax/automata.py)¶
- Add optional
semiring: Semiring[V] | type[Semiring[V]] | str | None = Nonetonfa_stepandsimulate_nfa(retaining a fast native float path whensemiring is Nonethat skips zero weights and prunes zero cancellations for exact parity withsemiring=StandardSemiring(float)). Return a fresh shallow copydict(start_states)on 0-stepsimulate_nfacalls. - Add Kleene reachability bridge:
- When
symbol is None, project the 3-level transition tensor into a 2-level matrix \(M_{s, t} = \bigoplus_{a \in \Sigma} \delta(s, a, t)\); whensymbolis given, extract \(M_{s, t} = \delta(s, \text{symbol}, t)\). - Require
isinstance(sr, HasStar)(rejecting non-star semirings such asStringSemiringcleanly perEP-0250) before delegating tomatrix.closure.matrix_star.
4. Unified GrothendieckRing K-Theory Bridge (src/algebrax/topology/k_theory.py)¶
- Define
VectorBundleSemiringwitnessingCommSemiring[DiscreteOrthogonalConnection | None](with.zero = None, direct sum \(\oplus\), tensor product \(\otimes\), and trivial line bundle as.one). - Compose
TopologicalKTheoryRingdirectly onalgebra.CommGrothendieckRing(fromEP-0250) overVectorBundleSemiring, eliminating duplicated(pos, neg)formal-difference arithmetic. - Define bundle equivalence
_bundles_equivvia spanning-tree axial-gauge fundamental cycle holonomies \(H_e = P[v]^T \rho(u, v) P[u] \in O(d)\) per connected component, verifying full Newton spectral power traces \(\operatorname{tr}(H_e^k)\) for \(k = 1, \dots, d\) (exact \(O(d)\)-conjugacy for all dimensions \(d\)) and pairwise chord product traces \(\operatorname{tr}(H_i H_j), \operatorname{tr}(H_i H_j^T)\) for simultaneous conjugacy across multi-cycle components.
Acceptance Criteria¶
AlgebraicTrie(ModularField(7)),AlgebraicTrie(GaloisField(3, [1, 0, 2])), andAlgebraicTrie(CliffordAlgebra(2, 0, 0))preserve live instances acrosseinsum,outer_product,dot, andpickle.loads(pickle.dumps(trie));len(trie)runs in \(O(1)\) and matchessum(1 for _ in trie)after inserts, overwrites, zero-pruning__setitem__, deletions, and zero-cancellingadd().tensor.doton empty tensors returns an emptyAlgebraicTriewithoutIndexError;tensor.einsum('ii,ii,ii->i', t, t, t)scales linearly \(O(N)\) rather than \(O(N^3)\); conflictingAlgebraicTriesemirings raiseValueErrorunlesssemiring=...is explicitly provided.SparseChainComplex.hodge_laplacian(k, semiring=ModularSemiring(5))equalsadd(l_down, l_up, semiring=ModularSemiring(5)), and mutating callerboundary_matricesafter construction does not affect the complex.CochainAlgebra(complex, ModularField(5))andCochainAlgebra(complex, GaloisField(2, [1, 1, 1]))passverify_ring_lawswhile non-negatable semirings (BooleanSemiring,TropicalSemiring) raiseTypeErrorupfront;cup_product(..., semiring=TropicalSemiring())preserves0.0(TropicalSemiring.one) entries.GroupHopfAlgebra(S3, coeff_semiring=ModularField(5))andGroupHopfAlgebra(S3, coeff_semiring=StandardField(Fraction))passverify_hopf_algebra_lawswith exact arithmetic.pagerankpropagatesStandardSemiring,ViterbiSemiring, andBottleneckSemiringconsistently and raisesTypeErroronStringSemiring.simulate_nfaworks overBooleanSemiring,TropicalSemiring,ViterbiSemiring, andStringSemiring, returns a non-aliased copy onsymbols=[], maintains exact zero-pruning parity betweensemiring=Noneandsemiring=StandardSemiring(float)innfa_step, andnfa_closurecomputes Kleene reachability overBooleanSemiring/TropicalSemiringwhile raisingTypeErroronStringSemiring.TopologicalKTheoryRingdelegates formal-difference arithmetic toalgebra.CommGrothendieckRingand passesverify_comm_ring_laws, distinguishes opposite-holonomy, multi-cycle, and \(d \ge 5\) bundles while identifying gauge-transformed bundles via spanning-tree axial-gauge holonomy invariants;VectorBundleSemiringcomplies withEP-0002(AMDS) andtests/algebrax/test_docstrings.py.
Backwards Compatibility¶
- Existing callers passing semiring classes (
AlgebraicTrie(TropicalSemiring)) or omittingsemiringinautomatacontinue working identically. pageranknow raisesTypeErrorupfront for non-numeric semirings (previously crashed mid-iteration).TopologicalKTheoryRingretains its public API while delegating internals toCommGrothendieckRing.
How to Teach This / Documentation Plan¶
- Ensure
VectorBundleSemiringand updated classes conform toEP-0002(AMDS) andtests/algebrax/test_docstrings.py. - Update
docs/guide/tensor/trie.mdanddocs/guide/tensor/einsum.mdwith parameterized semiring examples (ModularField(7),GaloisField,TropicalSemiring). - Update
docs/guide/discrete/automata.mdwith weighted NFA examples andnfa_closure. - Update
docs/guide/topology/cohomology.md,docs/guide/topology/k_theory.md,docs/guide/algebra/coalgebras_and_hopf.md, anddocs/guide/analysis/discrete_calculus.md.
Reference Implementation¶
Target files verified in the Second Grand Council Audit & Review:
- src/algebrax/converters.py, src/algebrax/trie.py, src/algebrax/clifford.py, src/algebrax/algebra/_field.py, src/algebrax/tensor/core.py
- src/algebrax/topology/{homology.py,cohomology.py,dec.py,k_theory.py}
- src/algebrax/algebra/{_hopf.py,_monoid_algebra.py}, src/algebrax/automata.py, src/algebrax/analysis/calculus.py, src/algebrax/verification/_algebra.py
Rejected Ideas¶
- Keeping
AlgebraicTrieRestricted to Zero-Arg Semiring Classes and AddingParameterizedTrie: - Rejected: Violates Shannon's minimalism;
Semiring.normalize()handles instances, classes, and strings uniformly. - Inventing a
VarietySemiringCarrier invariety/k_theory.py: - Rejected:
AffineVarietyrequiresn_vars >= 1(cannot represent \(\mathbb{A}^0 = \mathbf{1}\)), disjoint unions do not live in a single \(\mathbb{A}^n\), andmotivic_point_count_homomorphismis a crisp 7-line subtraction. Adding a synthetic semiring wrapper fails the Freshman Test. - Greedy Contraction-Order Optimization in
tensor.einsumin Phase 8.5: - Rejected: Left-to-right hash-join indexing into a flat
dictalready resolves the \(O(\prod \text{nnz})\) blowup cleanly without adding hypergraph-planning complexity. - Parameterizing
topology/persistence.pyOverModularField(p)inEP-0252: - Rejected: Persistent homology over \(\mathbb{F}_p\) involves boundary-matrix column reduction and belongs in a dedicated topology EP rather than semiring propagation.
Open Questions¶
None. All Council review items (is_algebraic_zero, Cochain/cup_product, pagerank, nfa_closure, VarietySemiring drop, einsum order, persistence.py deferral, and Post-Implementation Council Review refinements) are resolved.
Change Log¶
- 2026-11-26:
- Initial Draft authored from the Second Grand Council Codebase Audit (Explorer, Noether, Shannon, Russell).
- 2026-11-27:
- Incorporated Grand Council Pre-Implementation Review revisions: added shared
make_zero_predicate/is_algebraic_zeroinconverters.py, movedtyping.N/RectSparseMatrixtoEP-0251, fixedCochainorientation negation &cup_producttropical0.0bug, generalizedGroupHopfAlgebragenerics and Ring contract, resolvedpagerankandnfa_closurespecs (aligning withEP-0250onStringSemiring), ensuredCliffordAlgebrapicklability and flat-dicteinsumaccumulation, absorbedautomata/homologydefensive copies fromEP-0254, dropped speculativeVarietySemiring, added Acceptance Criteria and AMDS/guide checklist, and promoted status toAccepted. - 2026-11-28:
- Implemented all 8 Acceptance Criteria (
make_zero_predicate/is_algebraic_zero, live parameterizedAlgebraicTriewith \(O(1)\)len()and picklableCliffordAlgebra/GaloisField, \(O(N)\) hash-jointensor.einsum& empty-safetensor.dot,SparseChainComplex.hodge_laplacianpropagation & defensive copy,Cochain/CochainAlgebrafinite-field rings & tropical0.0preservation, Ring-parameterizedGroupHopfAlgebra+ semiring-aware Hopf verifiers, validatedpageranksemiring propagation, weightedautomata+nfa_closure, andTopologicalKTheoryRingcomposed onCommGrothendieckRingoverVectorBundleSemiring), updated all 7 user guides and AMDS docstring tests, and promoted status toFinal. - Incorporated Grand Council Post-Implementation Review refinements: upgraded
TopologicalKTheoryRing._bundles_equivto spanning-tree axial-gauge fundamental cycle holonomies with full Newton spectral power traces (\(k = 1, \dots, d\)) and pairwise chord product traces for simultaneous conjugacy; alignedautomata.nfa_stepzero-pruning parity betweensemiring=NoneandStandardSemiring(float); added algebraic-zero pruning and branch cleanup toAlgebraicTrie.__setitem__; guardedCochainAlgebra.__init__against non-negatable semirings and tightenedGroupHopfAlgebra.__init__annotation toRing[T] | None; added operand semiring mismatch validation intensor._resolve_semiringand eliminated duplicate item materialization intensor.dot; clarified probability-normalization semiring semantics inpagerankdocstring.