EP-0254: Ergonomics, State Safety, Ecosystem Bridges & Codebase Hygiene¶
| Field | Value |
|---|---|
| EP | 0254 |
| Title | Ergonomics, State Safety, Ecosystem Bridges & Codebase Hygiene |
| Author | Eran Rivlis eran@rivlis.info, Antigravity |
| Sponsor | Core Maintainers |
| Delegate | 💡 Feynman (Clarity), 🌿 Steward (Harmony) & 🛡️ Golem (Safety) |
| Status | Final |
| Type | Standards Track |
| Created | 2026-11-26 |
| Updated | 2026-11-29 |
| Replaces | — |
| Superseded-By | — |
Prerequisites: Runs fifth in Phase 8.5 (EP-0250 → EP-0251 → EP-0252 → EP-0253 → EP-0254 → EP-0255), consuming canonical_sort_keys from EP-0251 and make_zero_predicate from EP-0252, splitting verification/_{algebra,rep}.py and tests/verifications/ after EP-0253 lands, and providing the hardened display.py & RichDisplayable foundation consumed by EP-0255.
Abstract¶
This proposal addresses codebase-wide safety, ergonomics, ecosystem bridge, and maintainability findings from the Second Grand Council Audit. It fixes HTML-escaping and sentinel bugs in display.py (plus a minimal RichDisplayable protocol unblocking EP-0222), negative-index wraparound and format bugs in converters.py, defensive boundary crashes (ZeroDivisionError, aliased mutable state on ExplicitGroupRep/ExplicitLieRep and markov_step, non-bijective permutation signatures) in core utilities, and cleans up structural debt: decomposing oversized verification/ and tests/verifications/ modules (with automated docs/verification.md traceability checks), consolidating duplicated sparse helpers in Layer-1/2 converters.py, fixing leaked/incomplete __all__ exports, cleanly removing redundant verify_padic_ultrametric, re-enabling Ruff F401, and eliminating all internal EP-XXXX references from src/. (Command-line interface hardening in algebrax.__main__ is owned by EP-0255 alongside the unified structure registry.)
Motivation¶
While AlgebraX's mathematical breadth has grown to 111 modules and 36.6k LOC, peripheral ergonomics, defensive boundaries, and structural hygiene have accumulated friction that hurts both newcomers (the Freshman Test) and long-term maintainers:
- Rich Display Escaping, Sentinel & Protocol Gaps:
display.pyinterpolates titles, keys, and values into raw HTML withouthtml.escape(broken rendering / XSS in Jupyter), uses''as a missing-cell sentinel (hiding genuine empty-string''entries in string-valued matrices), and lacks a formalRichDisplayableprotocol needed by Phase 9 (EP-0222). (CLI catalog/verify/inspect gaps inalgebrax.__main__are addressed holistically inEP-0255on top of the unified structure registry.)- Ecosystem Bridge & Defensive Boundary Bugs:
converters.to_numpyomitsr >= 0 and c >= 0(silently wrapping negative keys via NumPy indexing), callsmax(matrix.keys())even whenshapeis provided, and silently drops non-intkeys with no index-map option;from_numpyraisesValueErrorinstead ofTypeErrorfor non-np.ndarrayinputs;to_scipyignoresformaton empty matrices and lacks symmetric non-int/negative key validation;from_scipyhas an unusedimport scipy.sparse as sp, and_get_shapehas a deadcurrent_depthparameter.analysis.calculus.laplacian_smoothinguses an implicitany(w < 0 ...)heuristic to guess whethergraphis already a Laplacian—silently corrupting signed adjacency matrices.- Aliased mutable state leaks from
probability.markov_step(steps=0),ExplicitGroupRep.__call__, andExplicitLieRep. - Unhandled
ZeroDivisionError/ silent corruption ingroup.permutation.signature(non-bijection{0: 1, 1: 1}returns-1and formats"broken cycle at None"),lattice.harmonic_mean(a == -b),lattice.join(wiping negative values viamax(v, 0)),lattice.product(union scan whendefault == 0),transforms.dft/idft(n <= 0/ negative keys),transforms.lorentz_boost(axis=0), andprobability.bayes_update(evidence <= 0) /entropy/cross_entropy/kl_divergence/mutual_information(base == 1or negative probabilities). - Maintainability, Export & Lint Hygiene:
verification/_algebra.py(1,767 lines) andverification/_rep.py(1,107 lines) are monolithic; 3 identical sparse-matrix equality helpers sit inverification/_rep.py(plus duplicates inrep/lie.pyandrep/quiver.py); 5 ad-hoc sparse zero-pruning helpers use 5 different tolerances (1e-9to1e-15).tests/verifications/has grown to 6,708 lines across 12 flat files, with 60.5% (4,059 lines) concentrated in oracle-groupedtest_differential_*.pymonoliths—most acutelytest_differential_sympy.py(1,569 lines across 7 unrelated domains),test_differential_topology_prob.py(809 lines),test_differential_numpy.py(768 lines), andtest_differential_graphs.py(672 lines)—plustest_mms_sheaves_and_categories.py(646 lines), while hard top-level imports ofnumpy/scipy/sympybypassconftest.py's optional-dependency skip guards.analysis/__init__.pyleaks private_get_common_neighborsand_is_graph_weightedin__all__;analysis/calculus.pyre-exportstopologyhelpers;matrix/__init__.pyomitsblock,hstack,vstack,slice_matrix,element_wise_binary_op;converters.pydocstring omits 10 of 18 exported functions.pyproject.toml:165globally suppressesF401, hiding unused imports acrosssemiring/algebraic.py,converters.py, andverification/_algebra.py;verify_padic_ultrametricduplicatesverify_padic_ultrametric_inequality.- 14 internal
EP-XXXXreferences leak intosrc/docstrings across 13 files, violating EP non-leakage rules.
Rationale¶
- 💡 Richard Feynman (Clarity & Freshman Test): Error messages, Jupyter HTML tables, and exception types fail loudly, clearly, and predictably—with clean cuts and zero dead aliases.
- 🛡️ The Golem (Safety & State Gravity): Freeze internal matrix dicts once at construction via
types.MappingProxyType(zero per-call copy overhead, protectingEP-0230's inner loops) and eliminate implicit negative-weight heuristics and negative-index wraparound. - 🌿 The Steward (Harmony & Layering): Consolidating shared sparse-equality and zero-pruning utilities inside Layer-1/2
converters.py(neververification/_common.py) preserves clean downward dependencies acrossrep/,matrix/, andverification/.
Specification¶
1. Rich Display Hardening & Protocol (display.py)¶
src/algebrax/display.py:- Escape all rendered text via
html.escapeacrossdisplay_matrix,display_vector,display_trie, andsemiring_card. - Replace the
''missing-cell sentinel with a private_MISSING = object()sentinel so genuine empty-string''entries render accurately. - Define and export a minimal 2-method protocol in
algebrax.display.__all__(unblocking Phase 9EP-0222without importingdisplayfrom Layer-2algebra/or retrofitting legacy classes): - (CLI hardening for
src/algebrax/__main__.py— including parameterized--semiringerrors, dynamic catalog domains, version unification, and fullverify --allcoverage — has been moved toEP-0255so__main__.pyis rewritten once against the unified structure registry.)
2. Converters & Defensive Utility Boundaries¶
src/algebrax/converters.py:- In
to_numpy: enforcenot isinstance(r, bool) and isinstance(r, int) and 0 <= r < h(and same forc), skipmax(matrix.keys())whenshapeis explicitly supplied, and add optionalreturn_keys: bool = Falsefor key-polymorphic sparse matrices (str, simplex tuples,StalkCoord). - In
from_numpy: raiseTypeErrorstrictly whennot isinstance(arr, np.ndarray)(preservingValueErrorforarr.ndim != 2). - In
to_scipy: honor the requestedformat(csr,csc,coo, etc.) even whenmatrixis empty, and add symmetric non-int/negative key validation andreturn_keys: bool = Falseparity withto_numpy. - Remove unused
import scipy.sparse as spinfrom_scipy, remove deadcurrent_depthparameter in_get_shape, and document all 18 exported converter functions inconverters.py's module docstring. src/algebrax/analysis/calculus.py:- Replace
laplacian_smoothing's negative-weight heuristic (any(w < 0 ...)) with an explicitis_laplacian: bool = Falsekeyword argument. - State Gravity / Immutability:
- Return a fresh shallow copy
dict(state)on 0-step calls inprobability.markov_stepand validatesteps >= 0(ValueErrorfor negativesteps). (Zero-stepautomata.simulate_nfacopy andSparseChainComplex.__init__copy land inEP-0252.) - Freeze internal matrix dicts once in
__post_init__via nestedtypes.MappingProxyTypeon bothExplicitGroupRep(rep/group.py) andExplicitLieRep(rep/lie.py) for \(O(1)\) zero-copy immutability (EP-0253widensverification/_common.py:45toMapping). - Boundary Guards & Regression Tests (owning the boundary tests relocated from
EP-0253): group/permutation.py: validate bijectivity (set(mapping.keys()) == set(mapping.values()), raisingValueError) and captureprev = currbeforemapping.get(curr)insignature.lattice.py: guarda + b == 0(ValueError) inharmonic_mean; preserve single-side negative values injoin; useset.intersectionwhendefault == 0inproduct,geometric_mean, andharmonic_mean; raiseValueErrorfor opposite-sign real inputs ingeometric_mean.transforms.py: validaten > 0and non-negative integer signal indices indft/idft/deconvolve; validateisinstance(axis, int) and not isinstance(axis, bool) and axis >= 1inlorentz_boost(preserving \(D\)-vector boosts foraxis >= 4while rejectingaxis == 0andbool).probability.py: validatebase > 0 and base != 1and non-negative probabilities inentropy,cross_entropy,kl_divergence, andmutual_information; inbayes_update, raiseValueErrorwhen explicitevidence <= 0while returning{}for disjoint support whenevidence is None.
3. Module Decomposition, Shared Utilities & Public Hygiene¶
- Canonical Layer-1/2 Sparse Utilities (
src/algebrax/converters.py): - Consolidate the 5 ad-hoc zero-pruning helpers (
prune_sparse,vec_clean,_prune_matrix,_is_non_zero,_prune_vector) behind one shared helper inconverters.pyusing hoistedmake_zero_predicate(EP-0252)—never callingisinstance(..., HasZeroPred)inside inner loops. - Consolidate the duplicated sparse-matrix equality helpers (
verification/_rep.py,rep/lie.py,rep/quiver.py) intoconverters.py(sparse_matrices_equal) sorep/andverification/both depend downward on Layer-1/2converters.pywith zero circular imports. - Firm God-Module Decomposition Decisions (Zero Breaking Public Imports):
- Split
verification/_algebra.pyinto focused internal submodules (_magma_group.py,_ring_field.py,_hopf_normed.py,_groebner.py) re-exported identically viaverification/__init__.py. When extracting_hopf_normed.py, document and preserve the shared_carrier_basishelper convention used byverify_coassociativity,verify_counitality,verify_antipode_axiom, and_tensor_mul_generic(which lifts coproduct basis keys to sparse-dict carrier elements, or passesMappingelements through unchanged), noting the assumption for any future non-dictBialgebracarrier. - Split
verification/_rep.pyinto_rep_group_lie.pyand_rep_quantum_quiver.pyre-exported viaverification/__init__.py. - Remove
topologyre-exports fromanalysis/calculus.pycleanly (shrinkingcalculus.pywithout breakinganalysis/__init__.py). - Defer splitting
matrix/core.py(high cross-function coupling, no user benefit in Phase 8.5). tests/verifications/Namespace Decomposition & Traceability Hygiene (lands afterEP-0253):- Reorganize the 5 oracle-grouped
test_differential_*.pyfiles into a domain-scopedtests/verifications/differential/sub-package with shareddifferential/_helpers.py(consolidating sparse/dense and SymPy polynomial adapters) and standardized module-levelpytest.importorskip(...)guards:differential/test_linalg_and_tensors.py(fromtest_differential_numpy.py: core matrix algebra, solvers, decompositions, tensors, converters, norms & RKHS)differential/test_transforms.py(fromtest_differential_numpy.py: DFT/IDFT, Hilbert, convolution, Walsh–Hadamard, Z-transform, Gelfand/Legendre–Fenchel, Lorentz boost)differential/test_path_semirings.py(fromtest_differential_graphs.py: Tropical, Boolean, Arctic, Bottleneck, Viterbi/Reliability, Log DAG closures & Hypothesis APSP)differential/test_spectral_graphs.py(fromtest_differential_graphs.py: Laplacians, spectrum, Fiedler/algebraic connectivity, bipartition, PageRank, eigen-centrality, discrete calculus, Forman–Ricci)differential/test_statistical_semirings.py(relocated fromtest_differential_statistical_semirings.py)differential/test_lie_galois_and_clifford.py(fromtest_differential_sympy.py: exactFractionmatrices, Lie/RootSystems/BCH/Killing, Galois fields, Clifford/octonions/Jordan, finite groups & permutations)differential/test_representations.py(fromtest_differential_sympy.py: group representations/character tables, Clebsch–Gordan/Lieexpm, Molien/Casimir, quantum \(U_q(\mathfrak{sl}_2)\)/Jones, quivers/Gabriel ADE)differential/test_polynomials_and_varieties.py(fromtest_differential_sympy.py: univariate polynomials, autodiff semirings, Gröbner bases, affine varieties)differential/test_topology.py(fromtest_differential_topology_prob.py: simplicial homology, Discrete Hodge, DEC/Stokes, Helmholtz–Hodge, persistent homology, cohomology cup/cap)differential/test_probability_and_discrete.py(fromtest_differential_topology_prob.py: information theory, moments, Bayes/Markov, automata, fractal metrics)
- Split
test_mms_sheaves_and_categories.py(646 lines) into atests/verifications/mms/sub-package:mms/test_sheaves_and_geometry.py(cellular sheaves, harmonic extensions, connections/holonomy, Alexander–Whitney, K-theory/Chern, Langlands/\(p\)-adic)mms/test_categories_and_algebra.py(Kleisli/Kan, distributive lattices, algebraic tries, matrix category/Lawvere, quotient ring isomorphism, path groupoids/CCC)
- Keep cohesive
< 470-line methodology modules intact at top level (test_axiomatic_properties.py,test_metamorphic_invariants.py,test_pit_symbolic.py,test_certificates.py,test_smt_z3_proofs.py) alongside recursivetests/verifications/conftest.py. - Synchronize all 138
*.py::test_*traceability references indocs/verification.mdand the directory tree inEP-0003, and add a fast CI test asserting every*.py::test_*entry indocs/verification.mdresolves to an existing test function undertests/verifications/. - Public Exports & Exception Consistency:
- Remove
_get_common_neighborsand_is_graph_weightedfromanalysis/__init__.__all__. - Align
matrix/__init__.__all__withmatrix/core.py:__all__(addingblock,hstack,vstack,slice_matrix,element_wise_binary_op, addingcg_solvetocore.__all__). - Keep
KeyErroronSemiring.normalize('bad')(catalog lookup semantics); normalizerep/quiver.pyinvalid vertex/edge validation onValueError. - Lint, Clean Removal & EP Non-Leakage Hygiene:
- Remove global
F401frompyproject.toml:165, scopingper-file-ignores = {"**/__init__.py" = ["F401"]}, and prune all dead imports (semiring/algebraic.py,converters.py,verification/_algebra.py). - Clean Cut: Remove redundant alias
verify_padic_ultrametricfromverification/__init__.pyand updatetests/algebrax/test_langlands_and_padic.py:253toverify_padic_ultrametric_inequality. - Strip all 14
EP-XXXXreferences fromsrc/docstrings across 13 files (verifying AMDS_SIG_REextraction stays green intest_docstrings.py) and add a CI test asserting zeroEP-\d{4}matches anywhere insrc/.
Acceptance Criteria¶
display_matrixescapes<script>HTML payloads and distinguishes''entries from_MISSINGcells;isinstance(obj, RichDisplayable)works for objects implementing_repr_html_and_repr_latex_.to_numpyandto_scipyreject negative/boolkeys, supportreturn_keys=Truefor string/tuple keys, and honorformaton empty matrices;from_numpy(non_ndarray)raisesTypeErrorwhilefrom_numpy(np.array([1, 2]))raisesValueError.ExplicitGroupRepandExplicitLieRepraiseTypeErroron external mutation of returned matrices without per-call deep copies;markov_step(state, P, steps=0)returns a non-aliased copy and rejectssteps < 0.- Boundary regression tests pass for
transforms(n <= 0,lorentz_boost(axis=0)raisesValueError,lorentz_boost(axis=4)succeeds),probability(base=1, negative probabilities,mutual_information,bayes_update(..., evidence=0)),lattice(harmonic_mean(1, -1), negativejoin,default=0product), andgroup.permutation.signature(non-bijections). rep/contains zero imports fromverification/;verification/_algebra.pyandverification/_rep.pyare cleanly decomposed while all existingalgebrax.verificationpublic exports (minus cleanly removedverify_padic_ultrametric) remain intact.tests/verifications/is cleanly organized intodifferential/(10 domain modules +_helpers.py) andmms/(2 modules) with module-levelpytest.importorskip(...)guards;uv run pytest tests/verifications/ -m differentialand-m mmscollect and pass all existing verification tests with zero test loss;docs/verification.mdandEP-0003are synchronized, and the CI traceability test confirms 100% of*.py::test_*references indocs/verification.mdresolve to live test functions.ruff check .passes withF401enabled globally (except**/__init__.py),tests/algebrax/test_docstrings.pypasses, and the new CI test confirms zeroEP-\d{4}occurrences insrc/.
Backwards Compatibility¶
- Module splits are non-breaking: All public symbols remain importable from
algebrax.verification,algebrax.matrix, andalgebrax.analysis. - Verification suite commands remain unchanged:
pytest tests/verifications/and marker selections (-m differential,-m mms, etc.) behave identically; only direct file-path invocations referencing legacy monoliths (e.g.,tests/verifications/test_differential_sympy.py) move to their new domain paths undertests/verifications/{differential,mms}/. - Intentional clean cuts & bug fixes:
verify_padic_ultrametricis cleanly removed; useverify_padic_ultrametric_inequality.analysis.__all__no longer exports private_get_common_neighborsand_is_graph_weighted.laplacian_smoothingrequires explicitis_laplacian=Truewhen passing a precomputed Laplacian.from_numpy(non_ndarray)raisesTypeErrorinstead ofValueError.group.permutation.signatureraisesValueErroron non-bijective mappings;bayes_update(..., evidence=0)raisesValueError;lorentz_boost(axis=0)raisesValueError.ExplicitGroupRepandExplicitLieRepreturn read-onlyMappingProxyTypematrix views.
How to Teach This / Documentation Plan¶
- Ensure
RichDisplayableand updated converter/display utilities passtests/algebrax/test_docstrings.py(with zeroEP-XXXXleaks insrc/). - Update
docs/guide/matrix/core.md(converter &to_numpy/to_scipyreturn_keysdocs) anddocs/guide/analysis/discrete_calculus.md(laplacian_smoothing(..., is_laplacian=...)). - Update
docs/guide/probability/information.md,docs/guide/transforms/spectral.md, anddocs/guide/algebra/lattices_and_order.mdwith boundary precondition notes. - Synchronize all 138 traceability paths in
docs/verification.mdand the suite layout tree inEP-0003to reflecttests/verifications/differential/andtests/verifications/mms/.
Reference Implementation¶
Implemented across the codebase:
- src/algebrax/{display.py,converters.py,lattice.py,transforms.py,probability.py}
- src/algebrax/group/permutation.py, src/algebrax/rep/{group.py,lie.py,quantum.py,quiver.py}
- src/algebrax/analysis/{__init__.py,calculus.py}, src/algebrax/matrix/{__init__.py,core.py}
- src/algebrax/verification/{_common.py,_magma_group.py,_ring_field.py,_groebner.py,_hopf_normed.py,_rep_group_lie.py,_rep_quantum_quiver.py,_topology.py,__init__.py}
- tests/algebrax/test_hygiene.py, tests/verifications/ (differential/, mms/, conftest.py), docs/verification.md, and docs/proposals/EP-0003-axiomatic-verification-and-property-based-testing.md
- pyproject.toml (F401 globally enabled) and all 13 src/ files cleaned of EP-\d{4} references.
Rejected Ideas¶
- Consolidating
rep/Sparse Equality Intoverification/_common.py: - Rejected: Creates a circular dependency because
verification/importsrep/. Layer-1/2converters.pyis the proper home. - Deep-Copying
ExplicitGroupRepMatrices on Every__call__: - Rejected: Allocates \(O(|G|^2)\) dict copies in representation/Fourier hot loops (
EP-0230). Construction-timeMappingProxyTypeprovides zero-overhead immutability. - Changing
Semiring.normalize('bad')FromKeyErrortoValueError: - Rejected:
Semiring.normalizeis a catalog mapping lookup;KeyErroralready obeys Pythonic exception semantics. - Splitting
matrix/core.pyin Phase 8.5: - Rejected: High cross-function coupling with negligible user benefit during a hardening phase.
- Over-Splitting Cohesive
< 470-Line Verification Files or Grouping All Verification Tests Strictly by Domain: - Rejected: Splitting
test_axiomatic_properties.py,test_metamorphic_invariants.py,test_pit_symbolic.py,test_certificates.py, ortest_smt_z3_proofs.pyadds boilerplate without reducing cognitive load, while replacing methodology-level grouping with pure domain directories mixes Z3/Hypothesis/SymPy imports and obscures the 8-layer verification architecture (EP-0003).
Open Questions¶
None. All Council review items (bayes_update, Semiring.normalize, RichDisplayable, god-module split scope, tests/verifications/ decomposition, verify_padic_ultrametric clean removal, and converters.py utility placement) are resolved.
Change Log¶
- 2026-11-26:
- Initial Draft authored from the Second Grand Council Codebase Audit (Feynman, Steward, Golem, Shannon, Popper, Explorer).
- 2026-11-27:
- Incorporated Grand Council Pre-Implementation Review revisions: declared Phase 8.5 sequencing prerequisites, moved sparse-equality/zero-pruning consolidation to
converters.py(preventing circularrep/→verification/imports), formalized minimalRichDisplayableprotocol forEP-0222, specifiedMappingProxyTypeimmutability onExplicitGroupRep&ExplicitLieRep, fixedlorentz_boost(axis >= 1), addedmutual_informationandmarkov_step(steps < 0)guards, addedto_scipyparity, fixed CLI/display/from_scipy/doc-link inaccuracies, keptKeyErroronSemiring.normalize, cleanly removedverify_padic_ultrametric, finalized god-module split scope, absorbed boundary regression tests fromEP-0253, added Acceptance Criteria, and promoted status toAccepted. - Added
tests/verifications/namespace refactoring to§3: decompose oracle-grouped differential monoliths intotests/verifications/differential/(10 domain modules +_helpers.pywithpytest.importorskipguards) andtest_mms_sheaves_and_categories.pyintotests/verifications/mms/(2 modules), synchronizedocs/verification.md&EP-0003, and add a CI traceability verification test. - Cleanly handed off
src/algebrax/__main__.pyCLI hardening and_registryconsumption toEP-0255per Grand Council review, sequencingEP-0254→EP-0255. - 2026-11-29:
- Documented the shared
_carrier_basissparse-dict carrier lifting convention (_tensor_mul_generic, coalgebra, and Hopf verifiers fromEP-0253) under§3'sverification/_algebra.py→_hopf_normed.pysplit specification. - Completed full implementation across
display,converters,probability,transforms,lattice,group,rep,analysis,matrix,verification/, andtests/verifications/(differential/+mms/), addedtests/algebrax/test_hygiene.py, enabled RuffF401globally, purged allEP-\d{4}leaks fromsrc/, updated all five User Guides and verification traceability docs, verified all tests and site build, and promoted status toFinal.