Developer notes
On this page

GammaLoop architecture

ImplementedSystem architecturecurrent

Application shell, domain core, state lifecycle, integration and event pipelines, persistence, concurrency, and tests.

View the source note

Lifecycle
current
Owner
Ownership decision required
Review
2026-08-18 · c9f4e32acd2c
Freshness
stale
Evidence
Not an evidence record
Verified scopes
  • gammaloop_api::state::State::load
    crates/gammaloop-api/src/state.rs · digest 335a0218f873
    entire file
  • gammaloop_api::commands::integrate::Integrate::default_workspace_path
    crates/gammaloop-api/src/commands/integrate.rs · digest e33c7d55fa35
    entire file
  • gammalooprs::integrands::evaluation::EvaluationResult
    crates/gammalooprs/src/integrands/evaluation.rs · digest 08e1c5149ca6
    entire file
  • gammalooprs::integrands::process::ProcessIntegrand::warm_up
    crates/gammalooprs/src/integrands/process/mod.rs · digest 603f0e7e4c14
    entire file
  • gammalooprs::observables::events::GenericEvent
    crates/gammalooprs/src/observables/events.rs · digest fa6a16013959
    entire file
  • gammalooprs::observables::EventProcessingRuntime
    crates/gammalooprs/src/observables/mod.rs · digest 64446686b754
    entire file
  • gammaloop_api::python::GammaLoopAPI
    crates/gammaloop-api/src/python.rs · digest 995d59847586
    entire file
  • gammalooprs module topology
    crates/gammalooprs/src/lib.rs · digest edec06f9908c
    entire file
  • feynkit_generator::Generator::generate
    crates/feynkit-generator/src/generation.rs · digest bc246aad8a69
    entire file
  • feynkit_model::Model
    crates/feynkit-model/src/model.rs · digest 26c52a78eff3
    entire file
  • feynkit_graph::FeynmanDiagram
    crates/feynkit-graph/src/lib.rs · digest b8c0353a7086
    entire file
  • feynkit_tensor public reduction API
    crates/feynkit-tensor/src/lib.rs · digest f424864aa88e
    entire file
  • gammalooprs::graph::Graph DOT import boundary
    crates/gammalooprs/src/graph/parse/mod.rs · digest 8879a6a74c83
    from pub fn import_dot(input: &str, model: &Model) -> Result<Vec<Self>> { up to pub fn dot_serialize(&self, settings: &DotExportSettings) -> String { (excluded)
  • three_dimensional_reps::generation::ltd::LtdBuilder::build
    crates/three-dimensional-reps/src/generation/ltd.rs · digest 332be3cb8d30
    entire file
  • three_dimensional_reps::expression::ThreeDExpression::select_ltd_residue
    crates/three-dimensional-reps/src/expression/ltd.rs · digest ccbd32fabd88
    entire file

Reviewed: 2026-08-18 against the verified source scopes registered in docs/developers.toml.

Lifecycle: Current implementation architecture. The review checked the state, evaluator, event-processing, integration, and quantity contracts named below against their implementations.

Scope

This document describes the current, implemented architecture of the GammaLoop application. It is not an architecture overview of the entire multi-product repository; Linnet, Spenso, Idenso, and Vakint have their own manuals and reference surfaces.

The GammaLoop application is organized around two principal Rust crates while using those shared workspace libraries:

  • gammalooprs (crates/gammalooprs): core physics/domain logic, graph processing, integrand construction, evaluation, and integration.
  • gammaloop-api (crates/gammaloop-api): CLI, REPL, Python bindings, command parsing, and persisted state orchestration.

High-Level Architecture

At a high level, gammaLoop uses a layered architecture with a stateful application shell.

User / Automation
  -> CLI binary (`gammaloop`) and REPL
  -> Python module (`_gammaloop` via pyo3)
  -> run cards (`run.toml`)

Application Layer (`gammaloop-api`)
  -> clap command parsing
  -> command execution against mutable `State`
  -> state/load/save and logging control

Domain Layer (`gammalooprs`)
  -> model + parameter cards
  -> graph and process representations (amplitude/cross-section)
  -> shared preprocessing and CFF/LTD generation
  -> GL integrand construction + evaluator stacks
  -> differential event generation, selectors, and observables
  -> Monte Carlo integration and stability checks

Infrastructure
  -> filesystem persistence (`gammaloop_state/`)
  -> optional local scratch persistence (`.local/scratch/...`)
  -> Symbolica state import/export
  -> tracing/logging

Main Components

1. Entry Points and Interfaces

  • CLI entry point: crates/gammaloop-api/src/cli.rs.
  • Main app orchestration: crates/gammaloop-api/src/lib.rs (OneShot::load, OneShot::run).
  • Python module entry: crates/gammaloop-api/src/python.rs (#[pymodule(name = "_gammaloop")]).
  • Python package shim: crates/gammaloop-api/python/gammaloop/__init__.py.

1.1 CLI architecture

  • The CLI is state-centric: every session operates on one active state folder and one active in-memory RunHistory.
  • Startup is orchestrated by OneShot:

    • resolve the state folder from CLI / boot card / defaults
    • load or create the state
    • load persisted settings and run history
    • optionally apply a boot card before entering the REPL or running a one-shot subcommand
  • Command execution is centralized in crates/gammaloop-api/src/session.rs (CliSession):

    • top-level commands
    • boot-card replay
    • nested run execution
    • command-history recording policy
    • command-block-definition mode
  • The REPL layer in crates/gammaloop-api/src/repl.rs is state-aware:

    • prompt text reflects the active state settings
    • tab completion is driven from the active state, active command blocks, and clap argument metadata

1.2 Python session architecture

  • The _gammaloop module exposes a stateful GammaLoopAPI. One instance owns its State, CLISettings, RunHistory, default RuntimeSettings, and CliSessionState.
  • Construction delegates startup to StateLoadOption::load, so Python and CLI sessions share state-folder, settings, boot-card, and logging setup.
  • Command strings run through CliSession; structured sample evaluation uses the shared EvaluateSamples command. Python integration uses api.run("integrate ..."). The retained typed GammaLoopAPI.integrate() entrypoint remains disabled in the source. Its command-building helper covers slot selection, workspace/resume settings, and optional Gaussian-reference acceptance; signed and componentwise absolute integration-result classes remain registered, without a supported structured Python integration producer.
  • GammaLoopAPI is a PyO3 unsendable class: each instance remains bound to its Python thread, while native work invoked by it may still use internal parallelism.
  • read_only_state blocks writes inside the state directory. It does not make the session immutable: commands may still change in-memory state, settings, caches, observables, and history.

IntegrandInfo and its Python counterpart derive the ordered representation inventory from persisted integrand payloads, not mutable generation settings. Native residue counts come from the graph’s generated expressions; execution orientations come from its runtime layout. The CLI shows both and marks imported diagrams without an integrand as ungenerated. Generation reports retain aggregate GenerationTimings and an ordered list of disjoint representation timings. Shared graph, four-dimensional UV, and helper work is the aggregate remainder. The existing generation summary renders these partitions, including compilation, without double counting. Graph-job duration sums can overlap under parallel generation and are not process wall time.

Python’s get_residue_map exposes the stored graph-level native expression through python/residue_map.rs. Detached snapshots retain immutable keys built from complete directions and affine loop/edge maps, exact Fraction coefficients, all scalar variants, denominator trees, surfaces and convention metadata. Equal keys retain their separate native IDs. This inspection boundary does not rebuild representations; it replaces the former direction-only get_orientations endpoint.

2. Application State and Command Model

  • Central mutable app state: crates/gammaloop-api/src/state.rs (State).
  • Command history and run cards: CommandHistory, RunHistory.
  • Command dispatch: crates/gammaloop-api/src/commands/mod.rs with concrete subcommands in commands/*.

The command model is stateful by design: commands mutate a long-lived State that can be saved and resumed.

Integrand generation validates the selected representations and initial runtime settings before clearing processes, parsing the process specification or running diagram generation. --only-diagrams defers these integrand-specific checks.

Selective loading filters processes and integrands before loading their heavy payloads. The retained in-memory process IDs are dense, and loaded generation reports are rebound to those IDs. This selection uses the same manifest and version validation as a complete state load.

Generation preserves the original forward sides by default. The optional --symmetrize-left-right-states CP optimization remains a user assertion about the selected theory, process and coupling point, with warnings at generation and runtime warm-up. Models declare covariant cut multiplets, and generated integrands retain their physical event representatives. Regenerate saved processes and integrands after the phase/model changes; see the generation options and generated-state contract.

Standalone Physics Toolkit (FeynKit)

FeynKit exposes reusable physics operations through focused crates rather than through GammaLoop’s application state:

Within this family, dependencies point from foundations to consumers:

feynkit-model ------> feynkit-graph, feynkit-generator, feynkit-ufo
feynkit-kinematics -> feynkit-graph
feynkit-graph ------> feynkit-amplitude, feynkit-generator, feynkit-cff
feynkit-amplitude -> feynkit-generator
feynkit-graph,
spenso, idenso ------> feynkit-tensor

focused crates -> feynkit / feynkit-py

symbolica-notation owns the small structured IndexDisplay tree and its bounded MathML/Typst/plain rendering and existing portable user-data encoding. It depends on Symbolica, thiserror and the XML parser roxmltree, below both Spenso and linnet-render-py; graph presentation no longer needs Spenso for these labels. This extraction preserves rendering and the spenso.math-display attachment format. Representation palettes, classes and rows remain owned by Spenso. Notation::register and Notation::lookup provide process-local, immutable shared notation with idempotent registration and typed conflict/poison errors. Renderers resolve callbacks, process-local notation, and escaped symbol names in that order. Display-only symbol tags and tensor-head user data are not read. Python MathML mappings use a bounded presentation allowlist and reconstruct escaped markup. Typst exports carry notation in explicit document settings; canonical symbol strings and saved states contain no display-only tags. Identity-derived index attachments retain their portable encoding. Portable presentation export will require a later explicit opt-in attachment.

No FeynKit crate depends on gammalooprs, gammaloop-api, GlobalSettings, or GammaLoop State. Generation receives explicit GenerationOptions, and progress/cancellation are callback- and token-based. The CI metadata guard also checks this direction transitively and rejects source references that bypass a Cargo dependency.

An explicit GenerationOptions::threads(1) performs interaction assignment, diagram construction and numerator/group preparation on the calling thread. Unspecified and multi-worker native requests retain their dedicated Rayon pool; browser kernels remain serial. This avoids acquiring a second Symbolica thread license for an otherwise serial caller. Numerical algorithms and input order remain unchanged; fresh paired measurements qualify any timing effect.

Rust clients load the canonical Model, construct a generation request, and receive finalized FeynmanDiagram values. Enabling feynkit/ufo exposes an attached-interpreter loader that returns the same model type directly. Python clients use this ownership flow through symbolica.community.hepkit; the curated PyO3 API does not expose GammaLoop runtime details.

Generation and grouping share one first-use registration of the six overall-factor bookkeeping heads. Together with ordered coupling declaration, this removes generation-worker races in their creation order. The serial, parallel and Born-first regressions compare fresh processes; this does not reorder symbols already registered by other consumers. Canonical model export ordering remains a separate contract.

The canonical model retains exact rational electric charges and optional left- and right-handed hypercharges. Model-supplied parameter labels are registered in declaration order, followed by coupling names in model order, before their expressions are parsed. Coupling expansion matches both names and replacement expressions literally. Propagator lookup, including antiparticle orientation, belongs to the model and is reused by generation. Chemical potentials are optional validated parameter identifiers in that same model and survive JSON and binary round trips. Exact internal zero expressions are propagated through dependent masses and chemical potentials when the model is constructed or restricted. An external parameter whose current numerical value is zero remains adjustable; it does not establish a structural zero. Validation of a massive covariant cut multiplet additionally rejects a known zero numerical pole mass, because that polarization basis requires a massive state. This check does not change the particle’s structural classification. Model expression export uses canonical ordering, so fingerprints and JSON round trips do not depend on process-local symbol-registration order. Generated sewn connections retain exact incoming labels; permitted initial-state permutations move both paired partners together. Default loop routing starts at the outgoing attachment, preserving the documented sampling-coordinate convention. Converting a generation result into a coherent amplitude requires its completed status; cancellation cannot silently publish a complete amplitude.

Python diagram, edge, and vertex numerators use Spenso’s TensorExpression directly, wrapping their retained tensors without re-inferring their interfaces or discarding scoped index history. Diagram denominators use the same scalar tensor interface and Spenso Minkowski products, with symbolic masses owned by the canonical particle model. They contain one quadratic factor per internal edge, excluding widths and the imaginary prescription. Local superficial UV power counting lives in feynkit-graph. The diagram method combines its stored local numerator degrees with the loop measure and quadratic internal denominators; GammaLoop’s vertex, edge, and rescaled-integrand checks use the same momentum-scaling trait. This bound excludes global projectors/prefactors and does not replace subdivergence analysis.

Python’s model-bound Process describes external states independently of calculation kind. Its generate_diagrams(), generate_amplitude(), and generate_cross_section() methods accept generation settings as keywords and construct the same Rust options. The corresponding Rust methods receive the model explicitly. Generation mode belongs to the method call; GammaLoop persists it on ProcessDefinition alongside the neutral process. Python dictionaries support reusable configurations; no mutable Python options builder accumulates filters. The Python boundary owns the process-dependent topology filter defaults. Explicit None disables a filter default; Ellipsis requests automatic filter settings. Numerator grouping defaults to None and must be enabled explicitly with a NumeratorGrouping value. Python permits tree exchanges and applies LoopOneParticleIrreducible to positive-loop individual graphs, including in mixed ranges; external legs are excluded from bridge counts. Explicit numeric bridge limits still apply to every graph, and None disables the default. When the requested minimum loop order is positive, the policy also prunes enumeration. Python permits self-loops; the reusable low-level Rust options remain explicit. Coupling upper bounds prune impossible vertex signatures before enumeration. Numerator construction reuses identical comparison/output diagrams, validation avoids expanding equal factored expressions, and unchanged cut inventories are retained. Coupling orders accept exact integers or inclusive ranges, while filter and grouping values wrap their Rust settings. Numerical numerator preparation restricts symbolic contraction to color; complete Lorentz contraction follows momentum sampling. Canonical comparison retains its symbolic tensor view and honors the concrete-color option even when no numerical samples are requested. Scalar rescaling ratios and grouped normalizations use exact rational arithmetic; conjugation is accepted only when its argument remains a model/color scalar. Vanishing weighted classes are removed before cut transport, while surviving provenance retains original source identities. Graph numerator products and powers are not distributed by these scalar-normalization operations.

Valid requests admitting no graphs return a completed empty result through the same generation pipeline; invalid settings remain errors, and token-cancelled requests are marked incomplete. Both Python entry points share signal-aware execution: native generation runs on a worker while the Python caller polls signals and cancels through the existing generator hook. Browser kernels poll the same hook on their calling thread. Signal-handler exceptions are preserved and re-raised, rather than being converted to partial generation results. The same execution boundary delivers coalesced GenerationProgress stage/count snapshots and synchronous partial-topology filter requests on the calling Python thread. A rejected filter prunes an enumeration branch; callback exceptions cancel and propagate. The filter receives Symbolica’s existing Graph, with integer external-leg labels and particle PDG edge data. Until Symbolica exposes a Rust constructor for its Python graph, the bridge uses its Python node/edge construction API. Generation, topology queries and pruning remain owned by the existing Symbolica graph implementation.

The graph crate registers momentum and index symbols before parsing or generation. Index identities retain their source, sink, edge, or vertex head; label metadata drives Spenso’s shared plain, LaTeX, and Typst printers, including portable render trees. Momentum heads retain their algebraic names and carry spenso::tensor-label:q; the shared indexed-symbol printer and portable Typst head resolver display them as 𝑞 with the edge identifier and tensor index.

FeynKit graph figures and GammaLoop drawings share the canonical particle-to-style mapping and Typst physics callbacks. Line patterns and labels derive from model metadata; the Python host embeds those same styles for standalone notebook rendering. The Python graph APIs share linnet-render-py, which renders native SVG through Linnest and loads verified font resources supplied by the host. The application retains its separate Typst drawing workflow.

FeynKit’s DOT importer treats native vertex bindings, serialized numerators, and external-state metadata as annotated input even when the graph fingerprint is missing. That input must pass native model-fingerprint validation; ordinary compact labels and num expressions retain the compact-input boundary.

GammaLoop’s DOT importer selects one explicit source boundary: a canonical FeynKit diagram, a finalized GammaLoop runtime artifact, or compact model DOT. It validates that dialect without retrying malformed artifacts through another parser. Compact model input instantiates missing model rules and the default external-state projector while retaining explicitly supplied local factors, including literal zero or one. Native topology parsing alone does not apply Feynman rules; rule construction belongs to the generator’s explicit extension. Compact and runtime source annotations pass graph-specific momentum checks before tensor admission. Graph-wide validation borrows the retained tensor payload and scalar overall factor, checking all Q3 structures before Q edge bounds without rebuilding a raw numerator. Compact cross sections pair incoming/outgoing dangling legs using is_cut tags. Imported edge mass overrides are installed before the parameter and energy map is built; overridden mass evaluators use that completed parameter layout. Selection-only cross-section diagrams retain the spectator cuts that selected them. They support listing and canonical DOT/JSON export, while integrand generation rejects them. Import infers final states from physical cuts only and never from selection metadata. A file in which every graph is selection-only therefore needs an explicit --process-spec; a file that also contains graphs with physical cuts reimports without one.

A compact cross section’s final_state attribute lists comma-separated particles, with | between allowed alternatives; physical cuts are the deduplicated union, while topology threshold candidates and the declared loop basis are independent of this filter. An optional n_cut_blobs attribute, one count or the ordered bounds min,max (default one), bounds the blobs on each side of a physical cut as --n-cut-blobs does in generation; threshold candidates found only by the external-leg search need connected sides whatever this range. Canonical DOT export keeps the resulting cut inventories, not this input filter.

Cross-section construction transfers the finalized physical cut inventory to the runtime cross-section owner, and every generation reselects process cuts from that full inventory. Native DOT export reattaches the full inventory and threshold catalogue only in a temporary graph view. The FeynKit builder preserves the original half-edge order, edge orientations, local factors and loop coordinates; conversion checks every routing signature before export. No rule generation or cut enumeration occurs at this boundary. Native import also restores runtime metadata such as names, mass overrides and threshold directives.

Compact GammaLoop expressions enter the native index frame before finalization. Only represented half-edge local index labels change from zero-based to one-based; momentum owners and other literal tags keep their meaning. The exact source map from finalization transports those fragments and their metadata into the runtime graph. Canonical and finalized artifact expressions already have their declared frame and do not receive that compact-input conversion. Runtime graph operations resolve particle and rule identifiers through the supplied canonical model rather than retaining a second model representation. Process-level projector owners are external-leg labels. The generator resolves them to each topology’s edge and attached half-edge before finalization, while the GammaLoop CLI applies the same local-slot conversion used by compact input. They must not be interpreted as provisional internal-edge identifiers.

GammaLoop converts each finalized diagram once into its evaluator-oriented runtime graph. That conversion translates identifiers and builds derived caches; it does not repeat model loading, rule lookup, canonicalization, numerator construction, grouping, or momentum routing. FeynKit and GammaLoop share the CFF recursion in three-dimensional-reps. FeynKit exposes its generalized generation API and adapts topology-only callers to that same recursion. GammaLoop adds its runtime surface classification and numerical behavior. Integrands, compiled evaluators, numerical threshold/subtraction machinery, events, observables, and histogramming remain downstream.

Model recipes and DOT/JSON expression strings remain source boundaries. Live FeynmanDiagram fragments, aggregate numerators, prefactors and projectors retain SymbolicTensor<PartialStructure>, as do the generator’s localized factor caches and prepared grouping values. Diagram fragment products use SymbolicTensor::multiply_many: consecutive named interfaces share a metadata merge with canonical free-axis order, while positional factors use the existing tensor multiplication operation. Live typed reconstruction retains logical ports, including those of ranked zero, and scoped index history. JSON/DOT serialization retains the expression and logical ports. Grouping samples which still carry color ports retain tensors; only completed scalar components and ratios are Atoms. Runtime Graph checks that every public port is explicitly indexed and transfers these carriers into SymbolicTensor<IndexedStructure> edge/vertex Autogen fields and GlobalPrefactor, preserving reversible index encoding, logical interfaces and reduction state. IndexedStructure retains the Canonicalized layout around OrderedStructure<LibraryRep, AbstractIndex>; unresolved public ports are rejected rather than assigned dummy labels. Closed scalar shorthand remains valid. Native export back to FeynKit transfers the same tensor into its more general interface without an Atom round-trip. UltravioletGraph::numerator returns Result<Numerator<AppliedFeynmanRule>>; its SymbolicExpression<Local> stores that same carrier. Reduced-graph composition, color algebra and later UV operations use it directly. get_single_atom is an explicit decoded expression view for exports, diagnostics and external algebra consumers, rather than the handoff between typed generation stages.

The generator’s model-bound numerator cache retains admitted templates for rules whose explicit index identities can be localized injectively. Instantiation transports their logical ports and scoped index history, including identities absent from a normalized zero. After template transport or actual-owner admission, the generator canonicalizes fully named free interfaces. This changes their logical axis order without reordering leaf arguments or changing index identities and scoped history; unresolved interfaces retain positional order. NumeratorInterface::translate owns the index transport for both templates and existing graph factors, retaining checked callback boundaries and using Idenso’s metadata-preserving index renaming. Rules with unresolved ports, callback-sensitive notation or ambiguous scoped aliases remain source expressions until localized at their actual graph owner, where they undergo checked admission. The same cache retains the resulting localized vertex and propagator factors. Template admission and symbolic callbacks run outside cache write guards. Concurrent cold callers may compute the same immutable template, but publication retains one shared value; all callers reuse that winner. Poisoned caches fail instead of continuing with potentially invalid retained tensors. PreparedNumerator retains separate typed values for exact comparison, routed sampling input and sampled results. Sampling evaluates the Lorentz sector to finite scalar components; its color sector can remain symbolic with open ports, so the combined sample remains a tensor. Canonicalization, coefficient comparison and dimension transport use the shared native owners. Dimension transport covers indexed and compact representations, including ports carried only by zero. Numerical sample budgets, seeds and scalar-ratio certification remain separate grouping policy. Exact comparison finishes numerical-content and common-factor normalization before labeling dummy indices. Factoring afterward can change the index frame and make equivalent chiral matrix products appear different. The scalar normalizations and the single native canonicalization retain their typed inputs; no graph-numerator expansion or extra canonicalization pass is introduced.

A finalized diagram’s with_numerator_prefactor consumes a retained SymbolicTensor<PartialStructure> in that diagram’s existing index frame. It replaces only the global multiplier and moves its interface and reduction proofs; local fragments, aggregate numerator, topology and routing are unchanged. ordered_propagators exposes the existing denominator construction in edge-ID order, and propagator_family delegates to that same owner. Symbolic kinematics can expose borrowed momentum/assumption views and map distinct scalar values simultaneously without changing keys, momenta or dimension. Exact complex-null Weyl charts belong to FourMomentum<Atom> and require a caller-selected nonzero pivot and the null-momentum assumption.

The shared NumeratorInterface codec owns source admission and export. Live diagram-to-runtime conversion copies the existing carriers; it does not pass them through that codec again. Diagram DOT/JSON retains expression strings and adds ordered interface metadata only when the expression cannot recover it. num_interface describes node, edge and aggregate numerator ports; numerator_prefactor_interface and projector_interface describe the two graph-wide factors. GlobalPrefactor’s own JSON uses num_interface and projector_interface beside its num and projector fields. These metadata preserve ranked zeros and logical port order without changing source recipes.

3. Domain Core (gammalooprs)

  • Root module wiring: crates/gammalooprs/src/lib.rs.
  • Initialization and shared symbol registries: crates/gammalooprs/src/initialisation.rs.
  • Diagram generation and filtering: crates/feynkit-generator; GammaLoop integration: crates/gammalooprs/src/feyngen.
  • Canonical model and parameters: crates/feynkit-model; GammaLoop numerical extension traits: crates/gammalooprs/src/model/canonical.rs.
  • Graph domain: crates/gammalooprs/src/graph/mod.rs and submodules.
  • Momentum routing and parameterization: crates/gammalooprs/src/momentum.
  • CFF construction, numerator processing, and subtraction: crates/gammalooprs/src/cff, crates/gammalooprs/src/numerator, and crates/gammalooprs/src/subtraction.
  • Process orchestration: crates/gammalooprs/src/processes/mod.rs, crates/gammalooprs/src/processes/process.rs.
  • Amplitude and cross-section pipelines:

    • crates/gammalooprs/src/processes/amplitude.rs
    • crates/gammalooprs/src/processes/cross_section.rs
  • Integrand abstraction and implementations:

    • crates/gammalooprs/src/integrands/mod.rs
    • crates/gammalooprs/src/integrands/process/mod.rs
    • crates/gammalooprs/src/integrands/process/amplitude/mod.rs
    • crates/gammalooprs/src/integrands/process/cross_section/mod.rs
  • Integration engine: crates/gammalooprs/src/integrate/mod.rs.
  • Global/runtime settings: crates/gammalooprs/src/settings/mod.rs, crates/gammalooprs/src/settings/global.rs, crates/gammalooprs/src/settings/runtime.rs.
  • Differential event/observable pipeline:

    • crates/gammalooprs/src/observables/events.rs
    • crates/gammalooprs/src/observables/mod.rs
    • crates/gammalooprs/src/observables/clustering/*
    • crates/gammalooprs/src/integrands/evaluation.rs

3.1 UV renormalization

UV generation defaults to the disconnected-capable hedge-poset backend and also supports a legacy DAG-forest backend and a comparison mode. Scheme policy remains on each Spinney while compute nodes store typed local, integrated, and cut-dependent results. Four-dimensional disconnected counterterms factorize over complete component counterterms; three-dimensional disconnected terms replay component-local operations from their common root so CFF structure is not multiplied as though it were scalar. The maintained sign, projection, marker, and backend-boundary invariants are documented in uv-renormalization.typ.

The soft/IR operator is H = U + S - US in both the direct 3D Taylor route and the route that projects local 4D counterterms to 3D. The projected route requires explicit orientation sums and computes its local 4D coefficients even when integrated counterterms are disabled. Common soft acceptance fixtures run through both routes with the same physical controls.

Integrated soft counterterms use the shared 4D integration boundary. Each completed signed sector supplies its retained active momentum frames and actual squared masses; integration must eliminate its hard coordinates. Only certified massless vacuum terms with polynomial loop numerators are discarded as scaleless. Massive soft terms remain. Equal-momentum mixed-mass propagators reduce by denominator-only partial fractions, contracting the removed serial edges while preserving the loop domain. Independent vacuum factors integrate sequentially with spectator loop vectors retained for tensor projection. MATAD also handles the one-scale sunsets with one or two massless lines; other coupled mass patterns remain subject to backend support. The resulting Laurent series keeps positive powers of ε for nested products with parent poles. Its signed finite addback completes recursive IR children and is localized once in the common nominal frame used by both final 3D routes.

For a massive quark self-energy, the OS operation adds both ordered projected branches at a fixed component-owned point 𝑝∗=𝑚𝑣 and subtracts their ordinary degree-one UV expansion. The forest minus applies once after that complete operation. The analytic scheme correction integrates only the signed vacuum remainder; the local physical branch retains the OS mass shift. Fields and couplings remain MS-bar. Parent operations act on complete child results, including owned finite coefficients, with localization kernels frozen. Projected CFF reconstructs fixed energy and spatial shifts with exact numerator and denominator certificates. The direct routes use the same certified physical source and retain their own post-residue operation and component replay. The actual-rule Ward certificate admits the stated two-loop IR gluon parent with an OS child; it does not authorize unproved mixed histories. The supported domains and independent validation requirements are maintained in the OS design note and UV renormalization architecture.

A positive-degree MUV parent over an IR child still requires the reduced-cograph subtraction of an explicit finite effective-vertex counterterm. The integrated child addback alone does not supply that local subtraction, so this mixed assignment remains rejected with integrated generation enabled.

Computed forest export belongs to Process, which pairs the runtime graph with its stored production expression and generation settings before constructing residue maps. In-memory diagnostics and disk exports use that same boundary.

3.2 Three-dimensional representations and numerator-energy ownership

GammaLoop owns production graph/source construction, UV orchestration, exact source mapping, and evaluator preparation. The three-dimensional-reps crate owns CFF and native LTD generation through the shared RepresentationMode enum. The 3Drep command and feature-gated eager evaluator are diagnostic tools, not production contracts: GammaLoop may prepare their inputs, factors, and expressions differently.

global.generation.three_dimensional_representations accepts one mode or a nonempty list of cff and ltd. Its default is ["cff"]; parsing preserves the first occurrence of each mode, and serialization emits a list. Any list containing LTD requires global.generation.uv.local_uv_cts_from_expanded_4d_integrands = true and implies complete residue summation, including when the same build also contains CFF. Generation and runtime reject orientation filters, orientation Monte Carlo and individual-orientation inspection or profiling for these builds. CFF-only orientation-local operation remains available. LTD supports only medium.mode = "vacuum" without vacuum subtraction. Finite-temperature and finite-density requests, including mixed CFF/LTD lists, fail before process mutation or representation generation. Runtime validation uses the persisted graph medium, independently of later global-settings changes.

Ordinary LTD determines complete affine loop-energy maps without CFF capacity analysis. Raised propagators use exact polynomial sampling with numerator-degree bounds to obtain higher residues without expanding or differentiating the graph numerator. The resulting denominator factors retain physical E-surfaces and dual-cancellation H-surfaces. Complete LTD sums are required for the latter’s cancellation; a residue-map row is not an independent integration contribution.

Finite-temperature and zero-temperature equilibrium share MediumMode, the structural CFF recursion, and bounded polynomial numerator reduction in three-dimensional-reps. Numerator reduction includes denominator-cancelling contact terms; each surviving denominator sector generates its own CFFVariant::thermal_weight. These weights retain cyclic orientations, thermal contraction numerators, and distribution derivatives separately from rational coefficients, keeping physical distributions outside Laurent interpolation. Distribution derivatives are ordinary energy derivatives at fixed temperature, chemical potential, and orientation. An m-edge cyclic chain has a common pole when all of its edges share the full momentum signature (loop and external) up to sign and the same symbolic mass key. Reducing it contributes (-1)^(m-1)/(m-1)! to the CFF coefficient and a distribution derivative of order m-1 on the chain’s lowest edge ID. Equal routing with distinct mass keys is not a common pole and stays a divided difference. Amplitude and cross-section warm-up call Graph::validate_denominator_hsurfaces to reject selected-orientation denominator H-surfaces that vanish identically at the current masses and external momenta, including distinct mass parameters with values equal up to sign. Each generated representation retains its source denominator IDs; only representations selected by the runtime stability stack are checked. These comparisons use exact equality; the check does not cover UV-counterterm expressions or coincidences introduced only by Cutkosky localization, including the existing CFF coincident-cut limitation. Ordinary thermal contractions require a connected virtual complement. Sources and sinks take priority; a mixed vertex needs at least three virtual boundary edges, or one incoming and one outgoing virtual edge with external attachments on both sides. External multiplicity alone cannot make a vertex eligible. Vacuum and thermal recursion prune tadpoles before selecting a vertex and retain the same contour prescription. Free tadpoles average the two closures: each vacuum orientation has weight one half, while each thermal pole has weight 1/2 + n_B(E - sigma*mu) for bosons or 1/2 - n_F(E - sigma*mu) for fermions. A contact instead inherits its parent’s contour. If that contour selects pole s0, its vacuum weight is (1 + sigma*s0)/2; the thermal weight adds n_B(E - sigma*mu) or subtracts n_F(E - sigma*mu) from that same vacuum weight. The energy orientation sigma remains separate, preserving both the numerator evaluation at sigma E and the particle/antiparticle chemical potential. The contour offset is s = sigma*s0 for a contact and s = 0 for a free tadpole. Ordinary thermal contraction numerators retain their signed distribution differences. Detachable chains with unequal poles use divided-difference contractions, leaving coincident-pole child cycles to the derivative reduction. An orientation with no admissible contraction or chain reduction fails generation explicitly. These weights survive serialization, variant fusion, source-edge remapping, and products of disconnected components. Initial-state cuts remain external energy aliases and never acquire thermal distribution factors. GammaLoop’s graph and parameter layer expands the symbolic weights using particle statistics, chemical potentials, and inverse temperature; the shared generator does not own the physics model.

Each distribution factor is the tagged call N(e, r, t, s, sigma). Here e is the edge ID and r the derivative order with respect to the positive on-shell energy E of e. The flag t is 1 at finite temperature and 0 in the zero-temperature limit. The contour offset s is +1 or −1 for a directed weight and 0 for their symmetric average. The physical energy orientation sigma = sign(e) selects the chemical potential sigma*mu and stays symbolic until orientation selection. With x = beta*(E - sigma*mu)/2, order zero is (s + tanh(x))/2 = (1 + s)/2 - n_F(E - sigma*mu) for fermions and (s + coth(x))/2 = (1 + s)/2 + n_B(E - sigma*mu) for bosons. The evaluated body keeps the occupation separate from the vacuum weight (1 + s)/2 and factors exp(-(x + |x|)) out of it, so its exponents are nonpositive and an exponentially small occupation is not lost once tanh(x) rounds to one; coth keeps n_B accurate in the soft limit. The function map registers every body once per contour offset, with s as a tag, so the vacuum weight folds symbolically and an s = -1 body is the bare occupation. As a runtime argument, s would let evaluator optimization add the constant to an exponentially small occupation first. Orders one and two are written in closed form with sech and csch; higher orders are differentiated symbolically from order two. The zero-temperature order zero is (1 + s)/2 - theta(sigma*mu - E), whose positive orders are the distributions localized below. The registered step is zero for a negative real argument and one for a positive argument up to rounding; at argument zero it is undefined (NaN). Pointwise evaluation exactly on a Fermi boundary therefore enters the numerical failure path, while localized distribution terms remain separate from that point value. Without a chemical potential it is the vacuum weight (1 + s)/2, whose derivatives vanish. Vacuum subtraction removes the value V(W) that a completed weight W takes when every factor is replaced by this vacuum weight. It does so symbolically: an order-zero factor differs from its vacuum weight by its occupation, N(s) - (1 + s)/2 = N(-1), and products follow the product rule D(a b) = D(a) V(b) + a D(b). Every term of W - V(W) thus keeps an occupation or a derivative, so the vacuum constant never cancels in floating point against occupations that round away, and the result stays linear in the number of factors. Weights with V(W) = 0 are left unchanged. At zero density, the zero-temperature tadpole weights reduce to the corresponding vacuum prescription; occupied fermionic states retain their finite-density contribution at zero temperature.

The bounded and known-factor numerator builders share occurrence sampling and polynomial reduction across all medium modes. Every resulting scalar sector, including a contact, a terminal residue basis, or the zero-edge unit, goes through LowerSectorCffBuilder. Each connected denominator graph retains its original incidence throughout generation, including shared vertices and external attachments. Products are formed only for genuinely disconnected denominator graphs. Surface shifts use the complete affine flow across the virtual boundary, including coordinates shared by cut aliases and ordinary external legs. Contact sectors use the surviving denominator rank to solve their active energies and lift the result into the parent’s coordinate namespace; this coordinate reduction does not split or reconstruct the graph. That boundary converts into the immutable source convention using the surviving denominator rank in every medium. The same scalar CFF constructor handles standalone and contact sectors. Ordered inherited contour rows, structural cuts, and embedded residue-basis context determine terminal pole preferences without splitting or projecting the graph. Occurrence interpolation preserves the scalar sector’s pole weights and introduces no additional terminal multiplicity. Variant lifting remaps thermal weights, energy IDs, surface IDs, and sign provenance before attaching numerator factors; it applies no further medium-dependent normalization. Surviving pole orientations remain independent of numerator interpolation maps, so zero or uniform-scale samples never set the chemical-potential sign. Residue map identities and labels distinguish both the pole directions and the samples.

Medium modes use direct local 3D UV subtraction. Their local UV kernels take the vacuum limit while the surrounding observable retains its medium dependence; CFF conversion wraps each completed medium coefficient as thermal_weight(W); optional vacuum subtraction replaces it with thermal_weight(W - V(W)) before local UV operations. The wrapper survives UV subtraction and final assembly, then the evaluator function map resolves it as the identity. Only thermal_weight(0) normalizes immediately, so vanishing branches are pruned. With vacuum subtraction enabled, the spinney covering all loop edges is excluded before both 4D and 3D counterterm computation, including when bridges remain in the graph; there are no separate vacuum-subtraction forest branches. Vacuum mode emits a plain unit without a thermal wrapper. Generation validation rejects combining vacuum mode with vacuum subtraction and rejects local_uv_cts_from_expanded_4d_integrands for either medium mode. The diagnostic 3Drep build command forwards the configured medium and records it alongside the serialized expression. Its model-free standalone eager evaluator rejects thermal expressions because it does not accept distribution inputs; production evaluation remains owned by GammaLoop.

Process generation configures the graph’s parameter builder with its selected medium and registers only that mode’s distribution functions. Finite-temperature energy derivatives are built incrementally. Zero-temperature registration contains only order zero; positive-order factors are removed or localized before ordinary evaluator construction, as described below. The builder persists the mode so runtime warmup can validate the current temperature, chemical potentials, bosonic mass domain, and finite real fermion masses where finite-temperature distributions or zero-temperature occupation steps are used, including after loading or updating a model. The stable finite-temperature occupation formula uses absolute values of real arguments and does not analytically continue complex shell energies. Medium warm-up also checks particle/antiparticle chemical potentials for exact opposite values and requires zero for self-conjugate particles. It uses current parameter values, treating missing or literal-zero assignments as zero; independent external inputs are allowed when consistent. Vacuum evaluation does not consume or validate these assignments. Vacuum builders register no thermal distribution functions.

integrands::process::fermi_surface::FermiSurfaceProduct localizes zero-temperature distribution derivatives. Production amplitude evaluation separates these distributions from the completed UV-subtracted expression before compiling numerical evaluators. Each positive-order thermal factor belongs to an independent cyclic chain: a derivative of order r represents delta^(r-1)(E - sigma*mu), while the CFF coefficient retains its existing cyclic-chain sign and factorial. The constructor checks the selected edge routing and chooses a loop basis containing one momentum per factor. Repeated or dependent constraints within a product are malformed expressions; fixed external shifts do not make dependent loop directions independent.

For each selected momentum, the localizer inserts a caller-supplied profile normalized over positive scale t and uses q = t*k, retaining the original spatial integration dimension. Independent energy-offset jets give the analytic root t(u) = sqrt((sigma*mu + u)^2 - m^2)/|k|. The differentiated weight includes the complete h(t)*t^3/g'(t) measure and the smooth coefficient callback. HyperDual Taylor coefficients are converted to ordinary mixed derivatives with the distribution-action signs and factorials. Only the squared mass enters the shell. Empty shells, including a zero oriented chemical potential for a massless fermion, contribute zero; degenerate onsets sigma*mu = |m| > 0, invalid radial coordinates and nonfinite results are errors. The onset check runs on selected sectors during sample evaluation, after the empty-product check, using native shell parameters at that evaluation’s precision. Binary64 warm-up cannot decide this for every later precision: a near-onset mass expression may round to equality in binary64 while retaining a regular shell in Quad or Arb. Ordinary order-zero steps do not enter this localization check. Masses and chemical potentials are held fixed during differentiation.

The callback receives momenta in the adapted basis, with all unconstrained coordinates held fixed. It must preserve the jets through every momentum-dependent factor. A future conditional Cutkosky localization can return its complete root- and Jacobian-dependent weight through this callback before the Fermi derivatives are extracted. Deltas and steps must not be differentiated numerically inside it; such boundary and intersection terms have to be expanded symbolically and validated as Fermi products first. Thermal cross sections and threshold subtraction remain rejected by the existing settings validation.

Production sector extraction collects the tagged thermal functions while retaining factorized smooth coefficients and shared numerator definitions. It runs after vacuum subtraction and both local and integrated UV contributions have been assembled. Parametric orientation branches select the complete residue key before fixing orientation signs; explicit orientation sums are extracted once. Each parametric sector compiles only its originating orientation, with local evaluator index zero mapped to that orientation’s production residue-map ID. Runtime sampling and filtering still select sectors by the graph’s orientation ID; all evaluator methods then evaluate the sector’s complete one-entry catalogue. This avoids selecting and evaluating inactive catalogue entries for every sector. Distinct signed chemical-potential supports stay separate, and the ordinary bulk retains its existing evaluator path. Only fermions with a chemical potential have Fermi surfaces. The shared edge accessor treats a missing chemical potential and literal ZERO identically; named parameters remain symbolic even at runtime value zero. Warm-up restricts bosons to |mu| < m or m = mu = 0; their zero-temperature occupation is then constant on E > 0, so extraction removes their positive orders and ignores their steps. Expanded keys with a repeated distribution are rejected. Residual fermion steps must be independent of the localized loop directions; unsupported moving step boundaries are rejected instead of differentiated pointwise. Basis completion first retains additional independent fermion routes with chemical potentials before choosing arbitrary remaining graph chords. Fermions without an occupation step cannot displace these preferred routes. This keeps an untouched occupation step independent when the input basis mixes its momentum with a localized one, as in a dotted sunset with a boson and an undotted fermion as its input LMB.

Each sector evaluates its masses and signed chemical potentials in the current numerical precision using the shared parameter builder. Warm-up applies the LU-h sampling checks to the configured positive-scale profile: a positive finite sigma, a supported power, and no exponential_ct. The profile normalization is evaluated in the active precision from its closed form, e^2 K_nu(2) for the polynomial profiles, so precision retries inherit no binary64 constants. The runtime maps the sample to its adapted loop basis, uses that profile, then routes momentum jets back to the graph basis for the smooth coefficient evaluator. Numerical representability failures enter the existing precision retry path. Model refresh, evaluator backends and saved process state include the sectors. Standalone evaluator archives cannot encode this runtime momentum localization and reject processes containing Fermi sectors; saved process state retains the complete calculation.

The tests cover analytic shell integrals, independent products, profile independence, the relation to raised-cut residue algebra, pointwise production orientation sums, model refresh and persistence. Symbolic reconstruction checks verify that vacuum subtraction and both UV contributions retain their Fermi sectors. A generated one-loop double pole is checked against an independent contour derivative, including its phase and spatial normalization, at fixed momenta inside and outside a massive Fermi sphere. A factorized two-loop graph checks numerical composition with local and integrated UV terms against that analytic cycle factor times a separately generated scalar tadpole.

The cold-dense inspection card includes the bare tennis ball and fixes its positive-scale profile explicitly. Its ordinary Fermi delta gives a pointwise value of the form B(k) + A(k)*h(t*); inspection checks that dependence across profile widths. These local values are representation dependent and are not integrated reference values. A one-loop convergence test integrates a massive fermion triple pole, including both the delta and its derivative. With unit local numerators its vacuum-subtracted integral is i*mu/(32*pi^2*m^2*sqrt(mu^2-m^2)). Production Monte Carlo runs with fixed sample budgets check this analytic target, decreasing uncertainty and independence of the normalized localization profile. Numerical convergence against multi-loop literature values remains separate work.

A genuine two-loop dotted-sunset convergence test covers a raised fermion whose momentum is not aligned with either input loop momentum. Its independent reference calculation is documented in comments in tests/resources/run_cards/fermi_surface_2l_integration.toml.

The shared LinearEnergyExpr stores exact Rational coefficients for indexed internal/external energies, the uniform scale and the constant term; CFFVariant::prefactor is also Rational. Arithmetic and cut handling retain that type until symbolic output converts it with Atom::num. Native rational serde/bincode support owns coefficient persistence; old Atom coefficient encodings are not a compatibility contract.

CFF capacities belong to independently sampled denominator occurrences. Physical sources use their EMR/source-edge identities; completed UV sources additionally accept typed canonical denominator classes, which are distinct from EdgeIndex. LMB coordinates certify routing and fixed affine carriers. They do not authorize redistributing a physical source’s energy powers or combining contours.

Both direct local-3D modes first perform the complete loop-energy integration and build the complete/global CFF expression; the UV Taylor operators then act on that CFF expression. They use the same Taylor-transformed CFF bodies. Writing the generalized residue map as { k -> C_k }, explicit_orientation_sum_only=false is sum_k sigma(k) C_k, with sigma(k) the one-hot selector for the complete residue-map key. The Taylor operator is applied independently to every keyed body and leaves that selector opaque. explicit_orientation_sum_only=true only replaces each selector by one and explicitly sums the same bodies. Neither direct mode reconstructs or projects completed local-4D Taylor structures.

Active direct-3D on-shell energies use OnShellEnergy(owner, s) = sqrt(s), where the invariant s = m^2 + q^2 retains the complete routed spatial momentum and mass scopes. Its custom derivative is dE/ds = 1/(2E); the owner has zero derivative. Only this invariant argument participates in the Taylor chain rule. Hard/soft normalization factors the common rescaling out of the invariant, with the established UV expansion/vacuum mass completion. Squared momentum sums remain factored. Ownership survives enclosing Taylor operations and is discarded only on the final evaluator copy, where even energy powers can reduce to invariant powers. The evaluator function map supplies sqrt(s).

The surrounding CFF denominator sum uses Esurface(a1, ..., an) = a1 + ... + an. Its arguments contain the signed on-shell energies and energy shifts, with their momentum and mass dependence visible to enclosing transformations. Each partial derivative with respect to an argument is one. This distinguishes the energy sum from its individual OnShellEnergy square roots.

Integrands stores BTreeMap<CutCFFIndex, Atom> dispatch roots and flat shared Arc<NumeratorDefinition> bodies. NumeratorDefinition is FnMapEntry<SymbolicTensor<IndexedStructure>>; scalar function definitions use FnMapEntry<Atom>. A root calls numerator_family(scope, coefficients...). The call is part of the coefficient program: its hidden tensor body is not inferred to be scalar. Tensor normalization acts on the retained bodies; root operations preserve the calls while transforming scalar weights and arguments. Each body is a factorized tensor expression with scalar formals. For CFF and LTD maps these include the sign multiplying an on-shell energy and the integer coefficient multiplying the independent sampling scale M. The binding uses the complete LinearEnergyExpr, including rational loop-basis and external-energy coefficients and constant shifts. It therefore does not assume that a numerator depends only on energies inside its UV component. Different complete maps remain distinct even when their production selector host is equal.

Root-only operations attach prefactors without multiplying the shared bodies. Semantic substitutions and derivatives visit both roots and definitions; exports and algebraic comparisons explicitly resolve the definitions. Saved amplitude data retains the definitions with its roots. Older saved-state layouts must be regenerated.

The projected local-4D route retains Local4dCts tensors, recursive sectors and their original post-Taylor coordinates and provenance for subsequent outer Taylor operations. Its projection view normalizes completed hard roles zero and one into exact signed denominator classes. Each class includes the component domain, routing, mass and full polynomial; physical/soft provenance, frozen localizers and cograph bindings remain explicit. The class algebra contains powered denominators and a factorized numerator, with no CFF capacities or sampling conventions. The same certified source feeds CFF or LTD projection. UV orchestration shares the four-dimensional Taylor data and integrated Vakint results across the requested representations.

Independent LTD sources can have different Laurent orders at the same physical cut or threshold. Smooth integrated-CT localization factors use the actual source’s order inventory. Final LTD addition combines the union of those orders, treating an absent coefficient as zero while retaining shared numerator definitions. Selected residue axes must agree; different physical cuts remain separate. CFF addition and all source multiplication retain their strict key-set checks.

Amplitude and cross-section owners store representation-indexed symbolic payloads and evaluator programs. Physical topology, cut identities, sampling geometry and threshold solve groups remain shared. Cut groups and threshold variants are ordered by physical cut IDs and edge support, respectively, so independently generated representations feed overlap solvers the same ordered constraints. Cache insertion order must not change overlap centers or local counterterm weights. The common surface cache gives the generated representations the same physical identity domain; it does not establish equality of their separate residue-order coefficients. In particular, a momentum-routing identity can produce nonzero, canceling CFF threshold-order weights while every consistent LTD numerator sample vanishes. Cross-representation comparisons sum those pieces for each physical degenerate higher-pole cut/residue and its common observable function. Distinct physical cuts, threshold occurrences, sampling channels and observable components remain separate; simple-pole contributions are compared individually. LTD identifies and extracts these physical residues from its own signed denominator factors, without constructing a CFF expression.

Local Taylor construction retains spinor products, chains and traces after metric simplification. Numerical tensor execution contracts them after residue mapping; the integrated-CT preparation separately performs the required analytic Dirac algebra on its copy before Vakint. An independent color pass reduces color contractions before shorthand traces are opened, preventing equal color spectators from acquiring distinct dummy-index copies while keeping kinematic coefficients factorized. This avoids expanding a local trace into scalar contractions before canonical merging and energy sampling. The local 3D, infrared and local 4D Taylor calls use the existing NumeratorAtomExt to retain an outer product’s factors that do not depend on the expansion variable. The native series engine expands the complete dependent product, including Laurent poles, and the independent product multiplies its truncated Atom once. Outer sums retain native coefficient collection, preserving literal zeros exposed by that collection. This boundary does not move a dependent mapped numerator outside Taylor or collect distinct denominators together. For a retained numerator family, direct-3D Taylor expansion computes coefficient bodies once with the energy-map coefficients left formal. Finite absolute-order Laurent probes give lower bounds for both bodies and complete products, including denominator poles. The resulting coefficient families are specialized only by their residue arguments. Independent tensor factors stay outside coefficient collection. Known multilinear dot and projector arguments are normalized before the native series call; temporary linear heads never escape that operation. Specialization must be polynomial in the formal map coefficients, so it can cancel leading terms without introducing unaccounted Laurent poles. Analytic spin preparation uses the retained symbolic carrier and the shared algebra and contraction owners. Raw backend expressions enter through explicit checked admission. Completed scalar coefficients retain their factorization, while selected tensor connections remain visible to the enabled identities. Materializing a powered tensor product allocates independent dummy scopes for each copy. No temporary tensor-coefficient alias carrier participates in this preparation. Tensor execution evaluates odd powers as paired contractions times the remaining base, preserving its free indices and the requested exponent. Both local routes simplify the reduced numerator’s color algebra before Taylor construction and the cograph’s color algebra before residue mapping. The direct 3D reduced-kernel call and both final-cograph calls select only color in AlgebraSettings, retaining the factorized momentum coefficient while reducing the collected color payload. Open color indices remain explicit; the final color pass contracts indices closed by attached UV terms and projectors. When fundamental-dimension invariant substitution is requested, the color simplifier also applies it after each local rewrite and before tensor collection. Resolved scalar Casimirs and indices therefore do not cause collection over a factorized residue sum; newly produced invariants follow the same rule. Model recipes and serialized diagram expression strings remain source boundaries; live canonical and runtime graph fragments retain the checked tensor carrier described above.

Diagram numerators requested with in_lmb=True use the stored loop-momentum basis before tensor simplification. Network parsing lowers a self-dual tensor square to a product so the selected contraction strategy also handles squares of routed momentum sums. With contracted-sum expansion enabled, Schoonschip distributes numerical coefficients after each local contraction, exposing cancellations without distributing symbolic spectator factors. Recursive parsing with no depth limit reaches contractions nested inside scalar coefficients; this does not request a global polynomial expansion.

Idenso builds a depth-limited Spenso network to plan contractions. The network shares the enclosing tensor’s admitted interfaces. A tensor’s public interface lists its surviving axes. For a self-contraction such as T(i, i), the public interface is scalar and the constructor still supplies two ordered incidences to the network. Each symbolic leaf carries its expression, ordered slots and checked index history. A leaf with a distinct boundary keeps its own declaration. The stored index history includes dummies that cancelled from the expression, so reopening a leaf or composing another tensor can still detect collisions. The tensor allocates its graph and reduction state on demand.

Typed tensor collection uses the shared graph/tape representation to select tensor sectors and preserve unrelated scalar coefficient subtrees. Selected payloads retain their complete slots, powers and shorthand structure; collection does not promise polynomial simplification of opaque coefficients. Structural cancellations and enabled tensor identities remain available without distributing a graph numerator. Algebra reduction and contraction share a regional scheduler, with independent permissions for identity families and structural connections. A color-only request therefore reduces color payloads while retaining unrelated spin and momentum structure. Callbacks validate their resulting interfaces through that same typed boundary. Chain-projector structure inference combines the exposed slots of its factor sequence when no direct slot or index-bundle arguments are present. Enabled chain and trace materialization expands the projector through its existing owner before constructing links, so symmetric, antisymmetric and cyclic sequences retain their external indices.

CFF final residue assembly validates the complete cut-key shape of every summand, then uses Symbolica’s native bulk addition once per cut order. Projected sectors and direct-route selector materialization retain their already mapped branch values until this merge. This avoids repeatedly copying the growing numerator; it merges existing top-level sums without distributing product factors or constructing common denominators. After all selected forests are assembled, final factor collection protects complete functions and powers. Inverse-containing factors and selectors stay local to each occurrence; tensor sums under products retain their original contraction boundary. The collector therefore recovers common numerator factors without clearing denominators, sharing branch guards, or pulling a summed vector across independent contractions. Repeated collection stops at a fixed point.

Vakint’s pole-order query uses absolute series depth zero, which includes every pole without searching indefinitely for a nonzero leading term in an exactly cancelling coefficient. The complete coefficient remains available to the separate finite/evanescent Laurent expansion; that expansion’s depth is unchanged.

Tensor-network edge joins use Linnet’s existing dense edge swap, which updates the moved edges through their owning half-edges. Each join therefore avoids a scan over the growing graph while preserving its edge payloads and merge flow. Operator merging uses its existing disjoint union groups to mark newly internal half-edges directly from each group’s node crowns. One shared deletion set preserves original self-loops, dangling slots and edges between groups without allocating and combining graph-sized masks for each operator island.

Ready-operation batches likewise retain sorted visible half-edge lists per operation. Disjointness checks and the optional batch union visit these lists; counts use their lengths. Node identification consumes the same ordered list and its exact membership predicate, preserving the dense subset’s representative node and newly internal edge marks, including partially hidden edges. Sequential, parallel and partial-rewrite strategies use this common payload. Only extraction materializes a dense subset for an individual operation, with the complete graph extent. Retained batch membership therefore scales with touched incidence rather than the product of graph size and ready-operation count. Root alignment uses the existing traversal’s discovery order to collect one root per visited node, without converting that traversal to child vectors. Requests for disjoint node crowns commute. The traversal is released before the graph’s node-store conversion, which still normalizes sibling ordering.

Rational-shell extraction groups equal denominator multisets through sums, products and powers while leaving denominator-free numerator subtrees opaque. It adds powers and numerators, prunes exact zeros, and never constructs a global common denominator. Positive typed denominator factors remain indivisible numerator blocks with their complete polynomial and signed binding. Compatible sectors merge before reconstruction. Exact cancellation at this boundary returns the existing typed zero with all cut-order outputs preserved, before any energy map or orientation is required. Frozen domains and localizers remain part of the compatibility test; opposite terms in different domains do not cancel. After each independent component contour, states with equal remaining requests and bindings share numerators when their carriers agree, or share carriers when their numerators agree. Grouping repeats until the state count stops decreasing, because one sum can create an equality for the next grouping pass.

Every algebra bucket retains one deterministic physical source witness. The existing source builder inherits original incidence, contracts omitted edges, and adds serial copies for raised occurrences. Only certified serial paths or pure cycles permit incidence contraction of equal channels. Nonadjacent equal channels can merge algebraically while retaining distinct edges in that witness. Exact signatures validate routing and its sign; they never infer endpoints. The source separately checks rank, measure, boundary attachments and contour. The class numerator is certified in one neutral momentum frame, independently of denominator routing, mass, multiplicity and domain. The signed occurrence lift obeys H=hR, P=rR, hence H^0=hrP^0.

Completed hard numerator factors may use any certified occurrence of their class, including occurrences inherited from different physical owners. Equal channels with unequal masses or prescriptions remain distinct pools. A hard carrier without a surviving class uses an exact fixed affine lift through retained base occurrences and external shifts; it creates no new pole family. Physical source ownership and soft crown provenance retain their restrictions. Non-vacuum exact sources retain pure-external boundaries as explicit source-crown hedges. Future on-shell insertions such as (m,0,0,0) require an explicit fixed boundary payload rather than inferred attachments.

The immutable CFF assignment is constructed compositionally. Sums take the componentwise maximum, products and registered multilinear arguments add degrees, and positive integer powers retain compressed repetitions. A deterministic checkpoint with a doubling interval detects assignment cycles after a transient while retaining one offset context, including packed tails beyond 64 occurrences. The inert cyclic, symmetric and antisymmetric tensor projectors use the same slotwise degree rule while keeping their symbolic heads intact. Freely assignable leaves use cyclic offsets within each class; opaque blocks use deterministic least-loaded placement. An ordinary affine request admits one candidate. A nonlinear request admits at most three distinct valid candidates: baseline, packed unavoidable excess, then reversal of the best-scored placement (rotation only replaces a duplicate). Each challenger changes one eligible occurrence pool, with no Cartesian search across pools.

Selection uses native generated.expression.orientations.len() before surface conversion and host selection. Maximum rank, descending rank envelope and stable candidate order break ties. The cache key preserves exact ordered capacities; identical physical energies do not authorize permuting loads. This bounded selection is not an exhaustive minimum. The sunset regression compares complete signed contours against independent residues: at energies (2,3,7), the degree-five and degree-seven values are 1213/16387080192 and -365/47775744. It covers all 126 degree-five distributions over the five equivalent occurrences and the allocator’s degree-five/seven proposals. It imposes no native row count or proposal order. All losing generation belongs to selection cost. Soft routing retains its existing exact-basis/Pareto frontier for off-shell proposals, including every fixed external shift. Its at-most-three native generation trials do not bound that separate frontier’s preparation cost. Root-expression reuse retains its established capacities.

Generation profiling includes raw physical-degree reports and the complete outer routing selection interval. Raw CFF requests separate source reconstruction, degree/preparation, native generation and postprocessing, and selection records the winner explicitly. This keeps winning generation separate while charging every losing proposal, its preparation and destruction to dispatch. Full local UV accounting uses completed nonroot forest nodes; child projection timers alone do not include the outer routing and assembly boundary.

One nonserialized Local4dProjectionContext spans all requested representations for one graph and forest backend. Shared four-dimensional results remain on the forest nodes across projections. Its deterministic LRU caches retain canonical sectors, owned source analysis and immutable numerator templates together (48 MiB, 4,096 entries), winning CFF payloads and contender counts (64 MiB, 4,096 keys), and component-local mapped subtrees (16 MiB, 16,384 entries). Owned keys, containers and symbolic payloads are charged; oversized entries bypass retention. These are retained-payload limits, not RSS limits. Clearing or evicting entries changes computation cost only. Source preparation owns its parsed incidence and signed namespace maps, so a warm hit skips reconstruction without retaining a borrowed graph adapter. The context belongs to one graph computation and cannot be reused for another graph; its keys describe that graph’s requests rather than a global graph registry. Representation-dependent generation keys retain the selected mode. Projection reuse tests compare complete coefficients with cold, warm, disabled and evicted retention, while checking only the configured byte ceiling. Hit counts, prepared entry counts and traversal order remain diagnostic observations.

PlannedExactSourceNumerator owns the assignment, prepared expression and exact signed mapping context behind an immutable Arc. A cache miss prepares the same generic template. Capture-free loop/occurrence parameters remain symbolic until a residue row arrives; each subtree records its exact dependencies. Mapping converts required energies once per row and memoizes only the relevant sample tuple. Constants are reused unchanged. Zero contact samples and the order of inactive-energy elimination are preserved. Mutable row caches live outside the immutable template and are cleared after each component wave. No graph-specific tables, global caches or serialized caches are involved.

Projected local-4D assembly maps one ordinary numerator template per compatible component family. Subsequent components see that template with earlier residue coefficients still formal; joint rows append only scalar arguments, representation-specific carriers and their source-map tuple. Families merge only when their remaining denominator powers, ordinary body, logical tensor interface and ordered formal signature agree. The final outer-CFF preparation keeps the ordinary numerator and scalar carrier visible as separate factors of the same certified routing product, then binds both with the same complete outer map. Derivatives can couple components, so this representation generally retains a joint residue sum. It does not replace that sum by a product of independent sums without a dependency proof, or copy the complete numerator into every row.

Each candidate prepares or reuses its exact immutable template before native CFF generation. Preparation certifies the occurrence diagonal in a formal spatial/temporal frame, including fixed external four-vectors. The selected payload carries this same certified template into row mapping. Profiling separates winning template construction from discarded candidate construction; all discarded preparation and cache work count toward dispatch overhead. Its only distribution is the finite projector action on an affine energy sum; numerator products and powers remain intact. A positive denominator block with a pinched hard carrier keeps its whole polynomial and an exact source-owned affine-rewrite witness. Only that witness permits joint fixed dependencies in the existing planned factor; uncertified mixed ownership and soft provenance keep their original rules.

The full reconstruction invariant, sign argument for D(Q)=D(-Q), and worked fixtures are documented in exact-powered-denominator-cff-lifting.typ.

The production numerator remains factorized. Degree analysis traverses its factors without expanding them, each UV step attaches only newly owned factors, and final assembly attaches outside and global factors exactly once. When one outer CFF serves independently evaluated residue branches, its capacity is the per-edge maximum of their separately analyzed factorized products, including the common remaining numerator. Equal branch bodies need only one rank analysis; opposite bodies remain independent and cannot cancel each other’s capacity. The analysis streams degree maps without constructing a tagged symbolic sum. Initial-cut and tree-edge energies remain outside this internal CFF capacity domain; stored production-root CFF reuse retains its existing boundary. For higher power projection, the term parser splits only the completed expression’s outer Taylor sum when its addends carry separate denominator topologies. Nested numerator sums and positive typed GS.den factors remain factorized and are never cancelled against denominator occurrences upstream; generalized CFF owns the resulting pinches and lower sectors. For higher powers, interpolation may replace an EMR energy by a*M, where a is a signed integer and M is the common auxiliary CFF numerator-sampling scale. This is an EMR substitution, never an LMB rewrite. Production evaluator parameter lists always include M, and runtime settings require M != 0 for every process. The physical result is invariant under changing its nonzero value.

The signed sampling coefficient is neither a physical edge-direction sign nor the runtime residue-map-key selector sigma(map_id). Pole signs enter the generation-time affine map, after which an orientation entry stores a in LinearEnergyExpr::uniform_scale_coeff and its interpolation weight stores the compensating inverse power in CFFVariant::uniform_scale_power. Multiple numerator maps may therefore share the same coarse orientation. Their complete loop/edge energy maps and distinct numerator_map_index values remain attached to the factorized numerator. Each such entry has its own complete map key and therefore its own sigma(map_id); entries must never be merged merely because their physical edge directions agree.

Integrated finite UV terms retain their exact source-local EMR maps. Production map-key selectors partition complete generalized residue-map entries but do not replace those maps. In orientation-local direct-3D generation, shrinking a UV subgraph preserves the orientation selected on every surviving outer edge. Among the cut-valid full orientations which extend that outer assignment, one deterministic inner orientation is selected to host the complete integrated finite counterterm; the other inner extensions receive none, so summing orientations counts the addback exactly once. In explicit-sum direct-3D generation the same reduced residue is kept once without a selector. Projected local-4D counterterms are likewise selector-free: each completed exact source owns its full source-local residue sum, independently of production-orientation IDs. After that sum, a projected sector stores only its coefficient and frozen localizing factor. Its child map lengths need not agree across Taylor topologies. Actual outer branches keep their own maps until the coefficient and remaining numerator have been mapped, then sum by cut order. Typed zeros retain the allowed cut keys without requiring a map; direct and integrated localization retain their own production-host rules. The empty UV forest is the ordinary factorized production root in both local-UV routes; the expanded-4D setting changes only proper, nonempty UV nodes.

Final assembly uses one Integrands map of cut-indexed factorized expressions. UV markers and tensor replacements act on those expressions before the ordinary evaluator preprocessing; there is no parallel deferred-body state. Direct-3D sequential forest construction composes the same local and integrated replay operations used by disconnected forests. Integrated localization registers its source surfaces before either Taylor branch reads the graph, and its normalized localizing factor remains inert under subsequent Taylor operations. Evaluator preparation skips residue-selector parametrization when the selector symbol is absent, and skips orientation collection when neither theta nor IF occurs. Expressions with conditionals retain the existing guarded-branch rewrites so inactive residue-local inverses are never evaluated.

An LTD UV source can carry higher Laurent orders at a selected physical pole than the production root. Its smooth localization factor therefore follows the actual source’s order inventory. Final addition combines these independent source maps over their union of orders, treating absent coefficients as zero while requiring the same selected physical axes. Multiplication and CFF assembly retain their strict matching-key checks; numerator definitions remain shared.

The shared CFF core also returns its surviving-denominator-rank source frame as typed metadata. GammaLoop consumes that bridge exactly once for root, reduced, and exact production CFF sources, cancelling the shared-core-local uniform convention before the physical Minkowski measure i^L/(2*pi)^(3L) is applied. Integrated UV addbacks use the same convention, with additional Vakint normalization 1. The NLO acceptance layer independently generates orientation-local direct 3D, explicit-sum direct 3D, and projected local 4D with local and integrated UV and threshold counterterms. It compares complete GL0/GL2 values at a common native- Arb point in all three routes; the fast Monte Carlo tests integrate explicit-sum 3D. DD acceptance checks the inclusive (alpha_s/pi) * LO correction, graphwise UV-mass and localization-scale independence, cancellation of total renormalization-scale dependence, opposite GL0/GL2 squared-scale logarithms, and the physical and projected EMR energy bounds. TT acceptance retains the published fully-MSbar control and adds a separate pole-mass test with OS quark self-energies and MS-bar vertex corrections. The OS test includes virtual ttbar and real ttbar-g cuts, requires agreement with an independent inclusive vector-current reference, and varies the UV mass and localization scale at the summed/integrated boundary. The full statistical scale scan belongs to the main-push suite; small exact algebra and pointwise route controls remain separate.

Direct-photon benchmarks use the off-shell spin projector -g^(mu nu) and no picobarn conversion. The inclusive lepton-process targets instead use the Eq. (7.1) normalization 2(4 pi alpha)/(3 Ecm^3) and the conversion to picobarns; individual lepton-process graph components are not assigned the unconverted published photon targets. Acceptances require positive real LO and the signed real NLO correction, checking the imaginary component separately. Diagram contributions can have either real sign. Current validation results and measured timings belong in the accompanying test evidence and PR.

The raw forward graph already contains inverse-process UFO vertices with their Hermitian-partner spin structures and couplings. An additional RHS numerator adjoint would conjugate those structures a second time. Marking vertices and virtual propagators, together with the reversed RHS virtual contours, instead gives (-1)^C_R, with boundary hairs retained in the RHS component count. The complete LU residue factor is 2*pi*i*(-1)^C_R, hence -2*pi*i for connected RHS, while retaining the cut propagator numerators exactly once. Bare, local and integrated UV, and threshold branches use this same cut-group factor. Runtime subtracts threshold helpers with left -i*pi and right +i*pi integrated coefficients; iterated terms use their product. See phase conventions and the independent conjugation audit for the cut-line i cancellation, intrinsic complex CKM phases, and the unsupported complex-mass-scheme boundary. There are no conjugation modes.

The scalar local-equivalence matrix is generated from the scalar model rather than from hand-built graph data. Its lanes without an additional numerator retain the full UFO Feynman rules; companion probes use only Feynman-rule-local edge factors, and there is no graph-specific production branch. The matrix enables local UV, integrated UV and threshold counterterms while comparing orientation-local CFF/from3D, explicit-sum CFF/from3D, CFF/from4D, and LTD/from4D, including native-Arb checks. just test_LU_scalar_xs selects the strict fast lane with ci-optim compilation and stops on the first failure. Complete acceptance separately selects the whole scalar family under ci_full, including the GL16 quartic case excluded from the fast lane. Nonzero route comparisons require finite values and precision-scaled relative agreement. Independent exact source, cut, or threshold certificates permit separate absolute-zero bounds; small magnitude alone does not qualify. Each bound is a dimensionless precision-dependent tolerance times the characteristic physical scale. For these three-loop scalar decay fixtures with six cubic vertices and numerator rank r, that scale is E_cm^(1+r). Raw additional weights include their recorded event normalization before comparison; detailed decomposition values already carry it. A certificate for a complete higher-pole residue does not certify its separate derivative-order contributions. The curated suite includes the six base scalar graphs GL00, GL02, GL04, GL08, GL09 and GL24. Each profiles direct local3D separately for every complete residue-map key and projected local4D after the complete residue sum.

Profile samples carry their candidate LMB into canonical source preparation. The source promotes the input momentum tokens exactly, then routes them into the selected graph’s stored LMB before native materialization and stability rotation. This also applies when the selected graph is a non-master member of a group. Ordinary direct momentum inspection supplies no candidate LMB and keeps its existing coordinate convention.

UV profiling defaults to only-divergent: every expected cycle union with DOD >= 0 is tested using the generation LMB when suitable, otherwise the first suitable basis in the deterministically sorted complete LMB list. The exhaustive all mode is opt-in. Amplitude and LU inputs share this behavior, with graph and Cutkosky-cut selectors for LU profiling and a colored final failure summary. Per-key profiling is defined for orientation-parametric, localized direct local3D. Selector-free explicit-sum direct local3D and projected local4D are summed representations and reject that request.

3.3 Tensor-network contraction order

Generic metric normalization retains its ordered vector, redundant-metric, vector-power, metric-power and trace passes. The first two passes traverse the factorized expression from the root downward and use conservative symbol-tag checks before applying their unchanged rules at the current node. Ordinary momentum components and scalar dots avoid unnecessary wildcard matching. A matched replacement keeps the original descendant-skipping behavior, and the redundant-metric pass still runs to a fixed point. In particular, metric-power normalization continues to precede tracing.

Evaluator construction normalizes its factorized input once, then parses each existing top-level summand into an independent Spenso network. This bounds network preparation to the current summand. Products, powers and nested sums retain their grouping. Parsing and contraction use ParamTensor<ShadowedStructure<Aind>> throughout, with symbolic Atom components. The HEP tensor library supplies ParamTensor<ExplicitKey<Aind>> entries, including exact metric and identity components. Numerical evaluation remains a later evaluator step.

Shared numerator families are lowered before this outer contraction. Preparation first groups complete contractions of family calls with their surrounding tensor factors, including trace and chain contexts. Closed additive scopes are prepared from the inside out and remain factors in surrounding products. The existing tensor collector exposes residue sums over opaque family calls while preserving inline numerator sums, scalar coefficients, independent closed products and conditional guards. Only a closed tensor interface becomes a shared joint body. Each call occurrence receives fresh scalar formals and private contraction indices; exposed ports retain their identity. Existing chains and traces own their implicit endpoint markers: chainification keeps those scopes opaque, and joint preparation rejects substitutions that would introduce nested binders. A structural template reuses this body across physical argument rows. Parameter-dependent tensor ports and formals captured by existing aliases retain their original family boundary. Only referenced bodies are then contracted, once per definition in an evaluator stack, and any remaining open tensor indices are represented by temporary tensor calls. The outer contraction closes those indices and selects the corresponding scalar component functions. Only generated functions reachable from the final roots and scalar aliases are registered; outer projectors can discard otherwise populated components. Component and scalar-alias signatures retain only their required formal arguments, including transitive alias dependencies; physical family signatures still describe the complete energy map. Known sparse zero components vanish, while unknown families and invalid index dimensions remain errors. All evaluator modes receive the resulting function-map definitions. The pinned Symbolica translator inlines these scalar functions when generating instructions, so a compact input does not by itself guarantee fewer runtime operations. Closed shared bodies avoid enumerating their open tensor components; generation and runtime effects still require measurement.

During open component enumeration, a family callback collects compact factors once per distinct raw scalar value. Equal values reuse that result within the callback. The profiling counters record requests, cache hits and unique inputs. Each component retains its original logical position and function registration order.

Before parsing a summand’s complete contraction, evaluator preparation may materialize an existing additive tensor factor of its root product. It inspects the parsed factor’s actual scalar and tensor entries and admits only Gaussian integers (integer real and imaginary parts), with a nonempty self-dual exposed boundary. Exact Gaussian-integer components retain symbolic arithmetic at arbitrary integer size. Floating coefficients decline this preparation and retain their original contraction order. Conservative Cartesian-capacity and component-size estimates reuse the 16 MiB eager tensor-sum budget. Explicit lazy tensor sums skip this preparation. Qualifying factors use the same execution and contraction strategies as the complete network, retaining their symbolic components and index ownership. Existing network multiplication joins them to the grouped residual before scalar aliasing and sum-boundary closure. When no factor qualifies, preparation parses the original summand directly. Taylor and other raw symbolic callers do not use this finite component preparation.

Each network aliases large scalar references and contracts its tensor products, then carries the root and definitions in Symbolica’s existing AliasedAtom. Selectors stay visible outside these scalar definitions. Distinct network, summand, output and concrete-orientation scopes prevent handle collisions; fresh symbols also avoid registered alternate names. Handle lookup avoids hashing subtrees larger than any key; renaming still visits their children. Explicit alias resolution retains its exact fixed point for nested or newly exposed handles, avoiding unrelated hashes and copies of alias-free results. Within a network, bulk Atom addition accepts every leaf whose existing scalar conversion succeeds, including rank-zero tensors and lazy sums with scales. The conversion preserves alias handles and rejects open tensors before the store changes. Owned scalar results move into the existing bulk or streaming sum, avoiding repeated pairwise addition of large closed-tensor results. Scalar roots and their definitions are combined before global evaluator optimization; open tensors, including open zero tensors, remain invalid scalar outputs. Optional evaluator variants borrow these scalars before the final parametric evaluator takes ownership. Root substitutions also apply to alias bodies. Concrete residue-map selection precedes physical orientation signs and prunes unused definitions, keeping inactive singular branches out of evaluation. After tensor contraction, scalar sums with the same complete residue-map condition share one lazy guard. Their bodies remain inside that guard so numeric construction can share calculations without evaluating an inactive contribution.

For scalar SingleParametric programs with runtime residue dispatch, evaluator construction compares zero and two common-pair elimination passes. The default trial requires at most 64 orientations and 1 MiB of aliased source. The zero-pass program must have at most 16,384 instructions and one million arithmetic operand pairs for the trial to run. Dual programs and retained sub-evaluators use zero passes by default. The comparison follows the exported instruction stream for every generated orientation using exact residue identifiers and orientation signs. A candidate must lower total modeled work on at least one path without increasing total work, addition work or multiplication work on any path. Unknown guards keep the zero-pass program. Explicit common-pair settings are honored, including when multiple scalar programs are merged; ordinary DAG sharing remains enabled.

The actual Symbolica evaluator registers the retained definitions in its function map. When source storage is enabled, stored roots and complete function-map entries together form the source representation, including for archive reloads. Selector-free inputs and empty function-map replacement lists retain that ownership without copying the expression. Once symbolic programs are built, unstored source expressions are released before dual and numeric programs are constructed. Profiling separates expression preparation, Symbolica construction and numeric-program conversion. At this finite component boundary, a ready tensor whose exposed indices all contract with a pending tensor sum is attached to each immediate sum branch first. One expression traversal selects all eligible disjoint outermost sums, including siblings within a product. Small product wrappers copy only the closing leaf references and their exact slot order, flow and internal traces. Native arms and sum shells stay in place; stable half-edge identifiers bind the consumed inputs while residual seams remain untouched. The wrappers are appended together, followed by one deletion and operator merge per wave. This reduces the sum’s open tensor rank before large component expressions are constructed, without repeated extraction of a whole sum or its arms. The tensor store is shared by reference and scalar spectators stay outside; sums are not multiplied through other sums, powers or opaque functions. Repeating the transformation decreases an existing sum’s exposed rank. Eligibility requires self-dual exposed sum slots, so shared edge descriptors retain their exact endpoint meaning; internal dual contractions and spectator incidence are preserved. It changes the contraction graph, leaving the input Atom, raw Taylor algebra and selected energy assignments untouched. Symbolic networks used to reconstruct numerator Atoms do not invoke this preparation.

Completed contraction waves reclaim tensors no longer referenced by the whole network graph. The owned store moves surviving entries and remaps every tensor leaf variant, including shared references and scaled sums. Tensor indices are local execution handles and may change between waves. Reclamation occurs only after replacement leaves are installed and deferred node identifications are finished; parallel workers first return all additions from their borrowed overlays. Extracted subgraphs cannot determine whole-store liveness. Scalar indices remain stable, preserving alias handles embedded inside expressions and the original definitions used during final restoration. No symbolic expression is rewritten by this storage compaction.

The default intermediate_cost preset selects MinIntermediateCost, a configuration of the existing ContractionStrategy implementation. It changes pair selection, preserving the scalar, trace, library, disconnected-product and final cleanup rules.

The greedy score first estimates copied symbolic payload, then symbolic normalization work, before using sparse support, tensor volume and rank as later criteria. For a candidate pair, let J count the estimated nonzero entry products with matching contracted coordinates. Let b and t be each operand’s mean entry bytes and top-level terms, rounded up. The two leading scores are J * (b_left + b_right) and J * (b_left * t_right + b_right * t_left). Sparse support supplies the join count without multiplying coefficients. Otherwise the fallback uses the Cartesian entry count, capped by output and contracted-coordinate volume for single tensors. That cap is not applied to lazy sums, whose terms may share coordinates. The existing bounded output-support join and deterministic operand-order ties remain in use. The bounded join counts output coordinates through borrowed slices of its immutable support groups, avoiding per-product coordinate copies while merging equal output coordinates from distinct contracted groups by their contents.

These scores estimate work before cancellations. They are not physical memory bounds or a prediction of the globally best contraction sequence. They use existing structure and scalar-size profiles, with saturating arithmetic; the planner performs no speculative contractions or numerator expansion. A higher rank intermediate can therefore be preferred when its estimated cost is lower. Performance claims require identical-input measurements of both time and memory.

The previous sparse-aware preset and all other presets remain explicit choices. To restore the preceding production configuration in a run card, use:

[cli_settings.global.generation.evaluator]
spenso_execution_mode = ["Sequential", "MinResultRank"]
tensor_network_contraction_order = "sparse_atom_aware"

Within a running session, switch the preset with the existing command set global kv global.generation.evaluator.tensor_network_contraction_order=sparse_atom_aware. Use intermediate_cost to select the default again. The preset applies to ContractionMode::MinResultRank with the supported sequential executors; explicit SmallestDegree selection is unchanged. The existing bnl_evaluator_atom_mwe diagnostic exposes the same choices through --contraction-order, using hyphenated names such as intermediate-cost.

Lifecycle and Data Flow

1. Startup

  1. CLI parses command input (OneShot::parse_env_with_capture).
  2. Initialization runs (initialise()), installs hooks and symbol registries.
  3. State is loaded from state folder if available (State::load), otherwise default state is created.
  4. CLI settings/runtime defaults are loaded and synchronized with tracing filters.

2. Process Generation Flow

  1. generate resolves command syntax into a FeynKit Process and GenerationOptions.
  2. FeynKit generates, canonicalizes, routes, constructs numerators, removes zeroes, and groups diagrams before returning GenerationResult.
  3. Each final diagram is converted once into a GammaLoop runtime graph, which adds only derived evaluator and integration state.
  4. ProcessList::preprocess delegates to amplitude/cross-section preprocessors.
  5. ProcessList::generate_integrands builds ProcessIntegrand instances from preprocessed graphs.
  6. Optional compile/export steps persist compiled evaluator artifacts and DOT/standalone outputs.
  7. Each generated integrand embeds its frozen f64 backend choice in integrand.bin:

    • eager
    • symjit
    • external c++ / assembly plus the external compile options used
  8. Runtime-only evaluator backends are then activated from that frozen metadata:

    • eager uses the saved eager evaluator directly
    • symjit is rebuilt after generation/load from the saved Symbolica evaluator
    • complete external compiled artifacts are loaded while the saved state is activated
    • missing external artifacts leave the frozen backend metadata unchanged but activate the portable eager evaluator for the current session
    • if external loading fails and startup globals explicitly opt into symjit, GammaLoop falls back to symjit for that integrand and logs it

Diagram grouping selects a common momentum chart from a colored skeleton. Ghost arrows encode physical ghost flow: reversing an edge’s stored endpoints and conjugating its particle leaves that skeleton unchanged. Mass/spin coloring identifies a ghost with its antighost, so the canonicalizer reverses the temporary skeleton arrow for a negative-PDG ghost. Sorting the final graph retains its existing endpoint and particle rules, including on a second canonicalization pass. For neutral adjoint QCD ghosts, the left/right charge-conjugation step preserves ghost number, keeping the differentiated endpoint fixed. It conjugates the quark fields using the existing particle rule. The correction is restricted to neutral color-adjoint ghosts; charged electroweak ghosts retain their existing treatment. Closed ghost loops receive their Grassmann sign. A directed self-loop’s automorphism factor already includes its symmetry and receives no extra factor of two. Generation parses and validates the original graph before grouping. When flow normalization leaves its ordered vertices, edge IDs, particle data and directions unchanged, the normalized graph reuses that parsed state. Changed flows receive a separate parse with their own momentum chart. Spatial-momentum validation examines the normalized factorized numerator and all prefactors before tensor-network parsing. Indexed printers use ordinary function notation for malformed calls, so validation can report the error.

Numerator-comparison samples use incoming and outgoing wavefunction keys with the same flow convention as amplitude generation. A sewn external edge has two occupied endpoints and therefore samples both wavefunction heads; an unsewn leg samples only its declared external state. Each head keeps its connection-local sample label. Only the explicit symmetric-polarization option shares those labels; sampling does not impose complex conjugation between the heads. Model scalars remain symbolic unless full numerical substitution is requested. The configured tensor samples retain their own Lorentz contractions and scalar substitutions. Exact comparison uses typed coefficient proofs; rescaling may cancel existing common factors but does not expand a graph numerator to prove a polynomial identity. An inconclusive comparison keeps separate graph groups. Graph numerators remain factorized throughout. After grouping, the scalar symmetry weights are combined over a common denominator before testing whether the class vanishes. This also removes zeros hidden behind polynomial denominators in the member ratios; stored provenance and nonzero coefficients retain their existing form.

The compilation snapshot persists jit_direct_translation, enabled by default. Direct translation lowers instructions to SymJIT IR and uses O2. The indirect path caps the configured level at O2 and disables its extra common-expression cache; compaction remains disabled for complex temporary layouts. Both paths consume the same saved numeric evaluator. Runtime JIT programs are rebuilt after generation or loading rather than persisted as raw MIR blobs.

Threshold directives and solve groups

graph::threshold_counterterms owns the strict versioned DOT schema and graph-independent normalization. Explicit variants require a complete parent LMB; absent declarations request the maximal inferred side defaults. The amplitude and cross-section process resolvers attach native subspaces, side ownership, physical/raised-cut associations and stable variant IDs in ResolvedThresholdCounterterms. Its materialized export combines persisted association-local bases with the original declarations; the runtime evaluator registry and flattened display rows cannot reconstruct that generation provenance.

Projected E-surface existence bounds use the surface’s own signed topological boundary and its complete affine momentum routing in the declared parent LMB. The complement stays fixed as spectator data. These signs do not come from the hosting physical cut; sewn initial-state edges are excluded at both endpoints when reconstructing the boundary.

SubspaceData::solve_signature is the shared geometry identity: selected defining edges paired with their full signed fundamental cycles, each normalized along its defining edge. Parent IDs, slot order and the complement chart are excluded. An optional explicit group_id refines this identity; incompatible signatures sharing an ID fail with all offending associations listed. Constituents of a merged higher-power residue must agree on their variant directives before aggregation. Grouped-amplitude explicit metadata uses master topology, while native implicit defaults retain member equations; cross-section non-master metadata is rejected.

The overlap owner in subtraction::overlap_subspace partitions by these identities and builds each group’s maximal overlaps and SOCP problems independently. Cross-section runtime first prepares every accepted cut’s own LU rescaling and external data. All equivalent surface instances then participate in the shared problem, including instances owned by other cuts. Foreign surfaces remain in the group’s multichannel complement even when only local counterterms are being evaluated. The chosen active center is transported by defining edge to each native parent; fixed complements, radial powers and LU Jacobians remain association specific. Incompatible spaces never share centers or threshold multichannel normalization.

threshold_multiplier owns scalar kinematic binding and eager evaluators. Shared and local function-map scopes are resolved before the existing Symbolica function-map construction; only reachable scalar functions enter evaluation. Multipliers are evaluated separately for the effective/star context of each local/integrated component, after residue differentiation, and lifted as opaque constants. Identity weights have no evaluator. Exact-zero weights do not remove geometry from overlap discovery. Left/right Cartesian products and their component contexts are generated internally; same-amplitude intersections rely on dual cancellation with compatible solve spaces. User weights must preserve the required residue and principal-value identities; schema and geometry validation alone do not prove IR safety.

The user-facing contract and worked GL297/GL638 examples live in threshold subtraction metadata.

3. Evaluation and Integration Flow

  1. Commands (inspect, evaluate, integrate) resolve process + integrand references.
  2. Integrand is warmed up (ProcessIntegrand::warm_up) to initialize rotations and caches.
  3. Sampling path parameterizes points and evaluates graph terms.
  4. Stability checks follow the ordered runtime.stability.levels stack and rotate kinematics. Each level may select three_dimensional_representation; omission selects the first generated representation. Unavailable modes fail validation before generation or runtime warm-up. Precision may repeat, for example Double/LTD, Double/CFF, then Quad/CFF. Forced Arb uses the configured Arb level’s representation, or inherits the first level’s selection when synthesizing an Arb level.
  5. Process graph evaluation returns a rich GraphEvaluationResult<T> rather than only a complex weight. This carries:

    • the graph contribution
    • grouped generated events
    • event-processing timing
    • generated / accepted event counts
  6. A shared process-layer prepared-event helper is used by both cross-section and amplitude graph evaluation:

    • it decides whether an event must be built for the current rotation
    • runs selectors immediately on that candidate event
    • retains only accepted identity-rotation events when buffering is needed
    • reports generated / accepted event counts and event-processing timing
    • selector failures zero the local contribution, so rejected events do not survive into the final retained result
  7. Stability selection checks the signed graph weight, retained absolute contributions, and Gaussian reference moments independently when present. All required checks must pass; the retained branch also carries the final grouped event payload.
  8. The final EvaluationResult contains:

    • the stable integrand_result, including each map’s Jacobian and channel partition factor, combined with the physical value at native precision
    • a unit unapplied parameterization_jacobian for x-space evaluation (None for direct momentum-space evaluation); the actual map Jacobian remains on the bridge’s map evaluation for diagnostics (the selected momentum sample carries the combined map/partition factor)
    • the separate integrator_weight, i.e. the Monte Carlo/grid weight only
    • grouped accepted events with native factors but no outer-grid weight
    • event-processing timing in evaluation_metadata
    • generated / accepted event counts in evaluation_metadata
    • ordered per-level stability results, each with precision, resolved three_dimensional_representation, relative accuracy and total time spent in that stability level
    • evaluation metadata

    Native reconstruction and stability selection return the same retained precision-tagged result to both API routes. The ordinary route checks final f64 representability of contributions and event weights; the precise Rust route keeps the native result without a preliminary f64 reporting pass.

  9. Evaluation produces one final stable EvaluationResult per input without committing observable statistics. Configured observables retain its complete event-group list. new_observable_accumulator() reuses the compiled definitions in an independent reducer. accumulate_sample(groups, coefficient) applies the explicit outer weight once and sums correlated fills before squaring. Zero coefficients still count one attempted sample. The native integrator explicitly performs this accumulation after evaluation; numerical caches and stability diagnostics remain attached to the evaluator. Native batch evaluation currently retains event contributions until the complete batch has been evaluated, then accumulates them. Peak event storage therefore depends on batch size; separating evaluation from accumulation does not itself require this buffering.
  10. Raw snapshots merge independent draws within a population. Summing independent population estimates is a distinct operation: it sums means and variances while keeping sample counts separate. The derived estimates cannot be used as raw checkpoints. Rust and Python continuous/discrete fill helpers share sample-level grouping, including underflow, overflow and empty samples. observables/sample.rs owns sample-level fill reduction and its errors; observables/estimates.rs owns the independent-population estimate combination.
  11. havana_integrate runs iterative Monte Carlo updates, merges worker-local observable accumulators, and writes integration artifacts.
  12. Interactive integration status uses a renderer-neutral snapshot and a separately owned terminal event loop, as documented in the maintained integration dashboard architecture.

Representation selection travels in the evaluation context without mutating the runtime settings. Attempts reuse the prepared sample, graph/channel selection, Jacobian and overlap geometry. Each representation has its own evaluator program and value caches. Only the accepted attempt supplies retained events and observable contributions.

CFF/from4D retains the existing explicit-sum construction: its SingleParametric program already contains the complete physical sum. CFF orientation-local modes retain their existing orientation catalogue and execution methods. LTD supplies its complete residue sum to the same generic evaluator constructor, with one execution slot. Requested SingleParametric and SummedFunctionMap programs are supported for LTD; either evaluates that complete sum. CFF numerator construction keeps its existing owner. Derivative programs retain the existing forced-inlining boundary required by the stock Symbolica vectorizer.

Every evaluator receives the auxiliary numerator sampling scale M as an input, defaulting to one. Warm-up rejects a zero runtime scale for every amplitude or cross-section integrand, including evaluators that do not use M. No source-expression scan or serialized usage flag is needed. M is an auxiliary numerator-sampling coordinate, not an LMB energy; LTD arguments can additionally contain on-shell and external energies.

Binary64 reporting may round exponentially suppressed, fully weighted components to zero. Numerical factors are combined before this rounding so a compensating factor cannot hide a meaningful contribution. UV profiling applies its scaling measure after native evaluation, so stability bounds include that measure as part of the full weight. For an averaged stability result, the mean absolute fully weighted probe value can establish underflow below the smallest normal binary64 value. This bound stays separate for each component and observable; an imaginary scale cannot excuse a meaningful real discrepancy. Overflow and invalid operations remain failures.

With stability.check_on_norm, amplitudes compare full complex magnitudes even when integration selects only Re or Im: a fixed-helicity amplitude can acquire a global phase under spatial rotation. A private sum of channel-point complex norms separately detects instability hidden by signed channel cancellation. Common-point physical terms are summed before taking each norm. The public componentwise absolute result remains the primary probe’s value. Cross sections retain checks of the selected integration components, and Gaussian-reference values and moments retain independent checks.

A generated massive OS contribution with a fixed boosted subtraction point retains its exact spatial reference with the graph term. Warm-up validates stability rotations against every retained reference, including after graph selection and state loading. A probe that rotates live momenta away from a fixed reference compares different local integrands and is rejected. The axis_angle setting supplies nontrivial rotations about that reference, using an exactly parallel axis and a cosine in [−1,1]. A cosine of zero selects a quarter-turn. Axis normalization and momentum rotation use the active numeric precision; the usual accuracy checks and precision escalation remain in force. Rest-frame OS contributions impose no spatial constraint.

3.1 Differential event-processing runtime

The differential pipeline is split into three layers:

  • Declarative settings in RuntimeSettings:

    • quantities
    • selectors
    • observables
  • A compiled runtime-only cache:

    • EventProcessingRuntime
    • owned by the process integrand
    • built in warm_up()
    • invalidated when runtime settings are mutated
  • Per-sample / per-integration results:

    • GraphEvaluationResult<T>
    • EvaluationResult
    • observable accumulator state / snapshots

The runtime-only cache is intentionally not serialized in binary state dumps. It is wrapped in a no-op Encode / default-empty Decode container and is always rebuilt from settings at warm-up time.

The same pattern is now also used for evaluator execution backends:

  • per-integrand frozen backend metadata lives inside integrand.bin
  • loaded external .so evaluators are runtime-only
  • symjit evaluators are runtime-only
  • the saved portable representation remains centered on eager Symbolica evaluators

Canonical sampling channels

The user-facing settings, supported map grammar and worked amplitude/cross-section examples are documented in Sampling channels and maps. The internal owners live together under crates/gammalooprs/src/integrands/process/sampling/:

  • maps.rs owns the Symbolica map AST, component contract, ordinary/radial kernels and compositions.
  • selection.rs resolves settings into the single canonical catalogue and compiles its graph-bound channel bridge; it also owns affine routing and ordered block plans.
  • context.rs retains conditional surface and physical-host data, support decisions and proposal policies.
  • evaluator.rs compiles shared Symbolica eager value/dual programs for Jacobians, profiles and scores.
  • joint.rs owns the supported shared-energy two-normal component and its domain certificates.
  • partition.rs evaluates support-aware positive scores and their normalized partition.
  • reference.rs substitutes normalized reference functions through the real process traversal.

SamplingChannelCatalogue supplies one zero-based channel-ID domain for grids, summed execution, direct inspection and event metadata. Generated LMB basis IDs remain routing identifiers, and physical cut IDs remain independent. Explicit generated lmb(...) selectors match admissible bases by exact ordered edges. Automatic and named selectors expand through this same catalogue; display never implements a second enumeration algorithm. Production auto:surfaces currently supplies optimized-LMB coverage without automatic surface discovery.

Estimator and statistics

Both amplitudes and cross sections map each selected cube point into the graph-group master’s raw frame. Group members reuse that point. The bridge evaluates the partition in that same frame, including foreign inverse densities. For channel c the body receives J_c * w_c, where w_c = rho_c / sum_b rho_b; adaptive cube/discrete-grid corrections remain with the integrator. This static-score partition is not a full adaptive balance heuristic. One channel’s cut host does not select the physical cuts evaluated by the body. Sampling factors stay outside raised LU residue derivatives and threshold multiplier algebra and are applied once to both results and events.

map_density and inverse_jacobian use the actual unadapted map density. OSE scores use E_cm^(-3L) product(E_cm/E_e)^alpha in the raw frame and require a complete ordinary LMB map. A named channel may override the global strategy. Explicit Symbolica proxies use raw coordinate components; they never replace a map’s actual support. Logarithmic score accumulation avoids intermediate overflow. The selected forward determinant is checked against its actual inverse density even when its partition score is OSE or a proxy.

Coverage (Full or Restricted) is separate from context/preparation requirements. Certified inverse exclusion returns None, which contributes zero to the partition. Numerical uncertainty is an error. A restricted catalogue requires an explicitly selected full-support sibling; a proxy cannot create support outside a map. An explicitly selected point must have positive density. Automatic soft coverage addresses elementary massless edges, not every compound soft/collinear stratum; explicit lmb_basis_ids retain exactly the requested order and disable augmentation.

The absolute monitor sums physical cuts, counterterms, summed orientations and graph-group members at each mapped point before taking each component’s absolute value. Summed channels add these positive terms before one outer statistics update, preserving their covariance. Taking the absolute value only after the signed sum over different mapped points would estimate a different quantity. Graph groups remain separate integration domains; sampled orientations likewise define a sampled-orientation domain. Native, precise and Python outputs expose the separate absolute_integrand_result before the outer grid weight. Integration workspace version 3 rejects checkpoints using the earlier absolute-moment convention.

Geometry, composition and absent surfaces

A regular radial chart holds its complement fixed, chooses an interior center, then solves one positive root per direction in its active subspace. The active space must have full routing rank; an energy surface cylindrical in a larger space is not a bounded radial target there. Two-energy rank-one fibers have analytic minima; general fibers use the existing SOCP solver as a candidate source and certify the actual native energy residual. Existence preparation is outside radial iteration, and complement-free preparation can be frozen at warm-up. Certified absent or pinched fibers select a normalized ordinary conditional fallback. Ambiguous signs, failed roots and unrepresentable inverse points are numerical errors, never clipped roots or hidden zero weights.

then blocks follow a routed dependency order; product requires independence. The geometry key contains the qualified equation, complete parent, active edges and ordered prerequisites. Cut/side compositions must leave the prepared physical host invariant under later displacements. The existing embedding solves the host from actual preceding coordinates and includes the full affine physical-to-raw pullback and determinant. Foreign inverses prepare the geometry of their own supplied point. Fixed signed velocities are routed before radial scaling to avoid subtracting large already-scaled host-null components.

A physical-cut block may fit radial_profile = "lu_h" to the runtime LU h-function. It samples t = R/r through a normalized log-logistic plus broad proposal, using a safeguarded inverse CDF in log(t). Its derivative is the proposal’s actual derivative, not an assumed inverse physical h. The broad component induces an ordinary raw-radius law independently of R. The profile attaches to a standalone cut or the unique physical-cut block in a composition and requires the LU fixed point to be interior. It is rejected for amplitudes. Physical h, raised derivatives and threshold localization remain unchanged; the fit is not a derivative-envelope optimizer.

The shared-energy joint kernel supports two equations in one three-dimensional active block, f1 = E0(x) + E1(x+a) - C1 and f2 = E0(x) + E2(x+b) - C2. Routing, masses and fixed external shifts must establish this form; equal edge labels are insufficient. For residuals h,z and shared energy u, the two squared equations determine x_parallel = d + e*u. With kappa = e.e - 1 > 0, the remaining physical solutions form a complete tangential circle. The kernel keeps both signs of its transverse momentum. Its smooth Jacobian in (h,z,phi) is u*(C1+h-u)*(C2+z-u)/(|a cross b|*sqrt(kappa)). Original unsquared energy signs and strict domain inequalities must hold over the entire disk, not just at its center. The normal-plane radial law gives density proportional to 1/R on that certified compact patch. A complement-dependent ordinary fallback is normalized separately; full-support sibling channels cover points outside an accepted compact patch.

Binding and physical adoption retain the original global equations, including hosted targets that are not threshold-CT associations. A relation true only at an exact LU root must not replace one of these equations at a finite residual. Directed checks compare completed-point normals and the host residual with the normal-radius accuracy budget. Tangencies, clipped-circle domains, arbitrary joint equation classes, dedicated pinched-collinear charts and CT-star pullbacks remain unsupported. In particular a future CT-star map must consume the actual common center and projection scale with a certified dependency order; adding a star label alone would not supply its inverse or Jacobian. Existing blocks/context/partition owners provide that extension boundary.

Warm-up, precision and physical centers

Each graph’s runtime-only sampling setup owns its catalogue, compiled programs and precision bridges. Warm-up runs after numeric masses and improved external kinematics are ready and publishes a complete valid binding transactionally. Settings mutation invalidates it. Workers share immutable programs and clone mutable evaluator buffers; maps and score programs are not compiled per point. Eager dual evaluators differentiate only requested active columns. Prepared parameters remain fixed; a singular derivative in an inactive column cannot contaminate an otherwise valid active Jacobian.

The source policy is fixed at warm-up for the complete integrand epoch. It selects Quad when the catalogue, requested accuracy and represented inputs permit it, otherwise fixed 256-bit or Arb precision. It does not switch maps based on a point’s physical stability. Each source draw retains its complete mapped points, J*w factors, support decisions and selected-host records in canonical storage. Physical Double/Quad/Arb attempts materialize independently from that anchor; they never redraw maps, choose another support branch or recompute the partition. Matching only discrete branch decisions would be insufficient: a point-dependent switch between two separately normalized continuous maps can change the sampled law. Direct selected momenta prepare their partition without a forward Jacobian; direct unselected momenta need neither.

Cross-section threshold overlaps have a separate immutable authority. Before choosing common centers, the physical LU owner prepares every accepted cut’s actual rescaled kinematics. The existing solve groups then choose SOCP/forced centers once in the identity frame. Subsequent rotations and precision attempts retain those centers, validate full group membership and signed solve signatures, and preserve each association’s native parent/complement and LU/alpha solves. Stored binary64 center bits are promoted exactly before native rotation. A mismatch is an error, not a reason to choose a different center. Reference targets and disabled threshold subtraction skip this physical preparation. See threshold subtraction metadata for subspace grouping, variants and multiplier semantics.

parameterization_time includes map preparation, inverses/partitions, materialization and sampling adoption checks. Physical body time excludes these nested sampling costs. Evaluator and event times are subsets of physical time; canonical sampling and physical preparation have separate subset counters. Report summed worker cost separately from elapsed wall time, and do not add subsets twice when deriving integrand overhead. These counters do not themselves establish a throughput or variance improvement.

Acceptance through the production pipeline

integrate --reference-gaussian '{"width":300}' retains graph traversal, real channel maps, partitions, adaptive grids and native stability checks while substituting a normalized raw-frame Gaussian. Re reports normalization and Im reports |K|^2 divided by its known Gaussian expectation; both targets are one. Each quantity is checked independently for stability. Summed maps aggregate values and moments before statistical squaring. Graph/orientation and outer-grid probabilities are applied once. Invalid draws fail acceptance rather than disappearing from its sample count. A fixed discrete-channel inspection is a partial partition contribution, not a unit integral by itself.

Reference descriptors resolve an omitted center to the loaded spatial dimension and require one common nonzero loop count per integrand slot. Physical selectors/observables are incompatible with this substitution. The descriptor and observable convention are persisted in the integration workspace; resume checks them before restoring settings. This is one integration engine, not a second sampler or a unit-integrand replacement of its Jacobians. Tests pair Gaussian normalization and nonconstant moments with forward/inverse, independent Jacobian, support-boundary, native retry and actual amplitude/cross-section checks. Finite reference statistics and local H/Z scans cannot establish a global bound on physical weights.

3.2 Differential event model

Events are stored in precision-homogeneous containers:

  • GenericEvent<T>
  • GenericEventGroup<T>
  • GenericEventGroupList<T>

This avoids enum-based mixed-precision layouts that would otherwise force storage to be sized by the largest precision variant.

Each event carries:

  • kinematics
  • cut metadata
  • one event weight with native normalization but no outer sampler weight
  • additional_weights

Observable-specific entry reweighting remains internal to the observable runtime; it is not stored on the event.

additional_weights.weights is a generic BTreeMap keyed by lightweight identifiers such as:

  • FullMultiplicativeFactor
  • Original
  • ThresholdCounterterm { subset_index }
  • AmplitudeThresholdCounterterm { esurface_id, overlap_group }
  • AmplitudeThresholdCountertermVariant { variant_id, esurface_id, overlap_group }

Counterterm weights are stored with the sign with which they contribute to the final event weight. Cross-section events use ThresholdCounterterm; amplitude events use AmplitudeThresholdCounterterm. The fully normalized event weight is therefore reconstructed as:

(Original + sum(the event's counterterm entries)) * FullMultiplicativeFactor.

This is populated only when settings.general.store_additional_weights_in_event = true.

Sample evaluation leaves the outer sampler weight unapplied. Explicit observable accumulation receives it as a coefficient; native integration event-list export applies it to both the event total and its recorded multiplicative factor.

Directive-enabled events can also retain an addable threshold_counterterms decomposition. A component ID refers to the graph’s static registry, while an occurrence identifies its amplitude surface/overlap or local-unitarity overlaps and raised orders. Each component records the multiplier values, effective multiplier, fully normalized weighted contribution, and bare contribution with only the user multiplier omitted. When an exact-zero multiplier skips the bare evaluation, bare is absent, weighted is zero, and evaluation_skipped is true. The Rust and Python event surfaces expose the same component and provenance boundaries. JSON omits absent decompositions and bare weights and retains the occurrence’s kind tag. Positional binary serialization keeps every optional-field marker and uses enum discriminants, preserving round trips through both formats.

For physical W/Z final states, generation includes the model-declared covariant vector, Goldstone and ghost cut states. Event construction preserves their momenta and maps their PDGs to the requested physical vector before selectors or observables run. The same event receives its bare, UV and threshold weights, so measurement functions respect the complete gauge sum. The representative map is persisted with each cross-section graph term. Ambiguous requests mixing an explicit unphysical state with its physical-vector sector are rejected; separate diagnostic requests retain their original PDGs. See the electroweak gauge contract for the required graph completeness and treatment of intentional subsets.

Serialized event additional_weights.weights is a list of [key, value] pairs. This preserves structured counterterm identifiers in JSON, including AmplitudeThresholdCounterterm { esurface_id, overlap_group }, and supports round trips without converting identifiers to display strings. inspect --json-output retains the same event weights and evaluation as ordinary inspection. Consumers of event JSON must read the pair list, including [] for no weights.

3.3 Event generation policy

Event generation is controlled by two related runtime decisions:

  • should_generate_events()

    • true when general.generate_events = true
    • or active selectors exist
    • or observables exist
  • should_buffer_generated_events()

    • true when general.generate_events = true
    • or observables exist

This means:

  • general.generate_events = false

    • selector-only evaluations still build temporary events for selector checks
    • evaluations with observables retain accepted identity-rotation events in the returned sample for later explicit accumulation
    • selector-only temporary events are not retained
  • general.generate_events = true

    • events are built, buffered, and returned even when no selector or observable is configured

The standard Rust/Python sample-evaluation helpers may temporarily override the returned-event behavior per call, but internal event generation still follows this same policy after that override is applied.

Accepted LU events are retained as grouped event lists:

  • one EventGroup per graph-group evaluation
  • all accepted cuts from graphs sharing the same group_id are merged into the same retained event group
  • each event stores its concrete graph_id and cut_id
  • incoming PDGs are sourced from the initial-state cut edges

This preserves the correlation structure needed by downstream observables.

3.4 Observable architecture

Observable definitions are shared between selector and histogram use-cases:

  • one quantity definition extracts zero or more ObservableEntry<T> values from an event
  • selectors consume those entries on a single event
  • histogram observables consume grouped events and fill per-group contributions

Histogram accumulation is based on:

  • a histogram-level sample_count
  • sparse per-bin sufficient statistics:

    • entry_count
    • sum_weights
    • sum_weights_squared
    • mitigated_fill_count
  • HistogramAccumulatorState / ObservableAccumulatorBundle for mergeable runtime state
  • ObservableSnapshotBundle for JSON / HwU output and API responses

Each Monte Carlo sample contributes exactly one statistical sample to a histogram. Contributions from all retained event groups are summed first per bin, and untouched bins are handled implicitly through the histogram-level sample_count rather than explicit zero fills.

Histogram snapshots therefore remain fully mergeable and re-constructible into live accumulator state. The Rust-facing histogram API exposes merge(...), merge_in_place(...), and rebin(...). Restoring an unlabeled continuous histogram keeps the same empty label metadata as a fresh worker. Explicit labels and discrete-bin metadata remain intact, and the merge compatibility checks still reject mismatches.

Current built-in quantities include:

  • particle with computation = scalar | count | pair
  • jet with computation = scalar | count | pair
  • afb
  • integral
  • graph_id
  • graph_group_id
  • orientation_id
  • sampling_channel_id

Current pair quantities include DeltaR. Current scalar projections include E, CosTheta, PT, y, eta, Px, Py, Pz, and Mass.

Object and pair quantities are ordered before entry_selection is applied. The ordering contract is configurable per quantity through:

  • ordering = PT | Energy | AbsRapidity | Quantity
  • order = Ascending | Descending

Family defaults are:

  • particle scalar quantities: ordering = Quantity
  • jet scalar quantities: ordering = PT
  • pair quantities: ordering = Quantity

leading_only and nth_only therefore operate on this explicit ordered list, not on incidental source/event enumeration order.

Jet clustering is implemented natively in Rust with IRC-safe algorithms:

  • kt
  • cambridge_aachen
  • anti_kt

and is validated against fjcore in tests.

Persistence and Runtime Artifacts

Primary persisted state lives under gammaloop_state/ (default):

  • state_manifest.toml (state version and UFO/subgraph printer registrations)
  • model.json, model_parameters.json
  • symbolica_state.bin
  • processes/ (amplitudes/cross_sections + integrands)
  • run.toml
  • default_runtime_settings.toml
  • global_settings.toml
  • logs/

For local experimentation, prefer an isolated path such as .local/scratch/<run>/gammaloop_state to keep repository root output minimal.

The persistence model is file-system based and intentionally human-editable for settings/run cards, mixed with binary artifacts for performance-heavy data.

Runtime graph fragments and retained numerator definitions encode the symbolic expression, its logical indexed interface, and its index history. This preserves axis order and the rank of a zero tensor. The same format covers the global numerator and projector. Runtime numerators require fully resolved ports. On load, the tensor decoder remaps symbols, checks the stored metadata for consistency, and restores the saved regional interfaces and raw leaf ports without inferring them from the expression. Reduction certificates and observed graphs remain transient. Generated amplitudes and cross sections retain their fixed OS frames, subtraction velocities and axis-angle rotations.

Canonical FeynKit models and source recipes accept raw expressions. Diagram DOT/JSON exports pair each retained numerator expression with its logical-port declaration, including an empty [] for a scalar. Standalone evaluator archives store lowered scalar programs in their own formats, amplitude version 17 and cross-section version 20.

Persistence Compatibility Contract

  • State format is versioned with state_manifest.toml (version = 25 currently).
  • Version 25 stores authoritative regional interfaces and raw leaf ports in Idenso tensor archive v2. The manifest check rejects full states through version 24 before model parsing, Symbolica import or process decoding. Regenerate those states from their source recipes.
  • Version 24 stores the full physical cut inventory, ordered CFF/LTD representation payloads and generated fixed OS frames together. Graphs carry a structural fingerprint and rebind to the state’s model.json on load. Cross sections select cuts from the full inventory on each generation. The two previous version-23 layouts were incompatible. Main stored shared-model references and the full and selected cut inventories. The on-shell branch stored the generated fixed OS frames. Regenerate states from either predecessor using their source recipes. The loader checks the manifest before parsing the model, importing symbols or decoding the process.
  • Version 22 on FeynKit stored indexed tensors with the ordered CFF/LTD expressions, evaluators and denominator catalogues. The earlier counterterms version 22 stored fixed OS frames with explicit indexed interfaces. Both layouts require regeneration.
  • Parameter builders persist authoritative entries, values and pair layout; their derived function map is rebuilt on decode and is excluded from the wire payload and resume fingerprints. Parameter identities use canonical namespaced/attributed skeletons with exact native floating-point leaves. Finite-field leaves retain their value and modulus; rational-polynomial leaves retain exact integer terms and fully qualified variable identities. Fingerprint inputs exclude process-local field and variable-list indices; range and slot order remain unchanged across process-local remapping. Standalone archives already flatten parameter entries independently and retain their own unchanged versions.
  • The older version history below describes FeynKit’s development lineage; its format20 is distinct from main’s independently evolved format20.
  • Version 21 stores explicit indexed slots rather than partial-index wire tags. The parallel OS version 21 used partial-interface tags with its fixed-frame metadata. Regenerate either version from the source recipe. The logical layout and ranked-zero axes remain retained.
  • Version 20 also retains the tensor interfaces of global numerator prefactors and projectors. Their positional runtime payload cannot be read as the former Atom fields; earlier full states must be regenerated.
  • Version 19 retains tensor interfaces in runtime graph fragments and shared numerator definitions, with checked decoding and no serialized reduction caches.
  • Version 18 combined canonical FeynKit model and graph ownership with compact runtime/evaluator records. Earlier persisted layouts must be regenerated rather than relabeled; source reconciliation does not migrate positional bincode payloads.
  • The combined layout also retains medium parameters, thermal H-surfaces and Fermi sectors with one-entry coefficient catalogues evaluated at local index zero.
  • The integrated layout also stores ordered CFF/LTD symbolic payloads, per-representation evaluators and denominator catalogues. Physical-cut reversal masks are removed; projected E-surface bounds retain each surface’s signed boundary and fixed-spectator routing.
  • Version 12 names the square-root primitive OnShellEnergy and the CFF surface sum Esurface. Older states used Esurface for the square root and must be regenerated: importing those atoms with the new callbacks would change their meaning. Standalone amplitude and cross-section archives enforce their own versioned payload boundary.
  • Version 11 persists function-inlining policies and caller-scope alias metadata. Local UV forest contributions are combined into one persisted integrand before evaluator construction. Older states must be regenerated because this changes positional bincode data.
  • Version 10 records UFO symbol names and Linnet subgraph labels with custom print callbacks, including couplings removed from the saved model by restrictions. State loading restores those registrations before parsing the model or importing Symbolica’s archive. Linnet’s existing subset printer is restored from its label without reconstructing graph topology. Model loading registers parameter names and their presentation callbacks, then predeclares coupling names before parsing expressions. Coupling predeclaration establishes symbol identity and order; it does not install parameter presentation callbacks on couplings. Symbolica cannot serialize the Rust callbacks themselves; version 9 and older states must be regenerated, not relabeled.
  • Version 9 combined Symbolica 3 evaluator/rational payloads with native sampling and threshold metadata. Version 7 stored exact CFF coefficients as native rationals. Version 6 removed obsolete deferred-integrand fields; version 5 added component-local generated-CFF ownership and prefactor metadata; version 4 added the typed global-prefactor sign.
  • Standalone amplitude and cross-section payload versions are 17 and 20, respectively. Older archives are rejected before importing symbolic state. JSON and binary archives retain the ordered mode list and representation-indexed programs; loaders validate both together. Binary loaders import the saved Symbolica state before decoding atoms. The generated standalone tools select --three-dimensional-representation, defaulting to the first generated mode. Compiled original and counterterm artifact names include the representation to prevent collisions. Physical input strides follow each stack’s derivative shape; amplitude sample values are serialized as constant jets. Cross-section callers provide their inputs.
  • State loading and direct overwrite both require exactly the current manifest version; older states must be regenerated, and states from newer binaries require a newer GammaLoop binary.
  • A missing manifest denotes an unmanifested folder rather than a legacy state and is never loaded as saved state.
  • Process settings history is saved and restored through settings_history.toml for both amplitudes and cross sections, retaining the generation settings required by UV exports after reloading a state.

Integration workspaces

Integration resume state is persisted in a dedicated integration workspace. In a normal writable session its default is <state.folder>/integration_workspace (therefore normally inside gammaloop_state/); a read-only session defaults to ./integration_workspace[_<state-name>], and --workspace-path overrides the default. manifest.json records the selected process/integrand slots, targets, effective model parameters, integrand fingerprints, training and settings slots, and sampling-correlation mode. Authoritative completed-iteration state lives in state/integration_state.bin; per-slot settings live under integrands/<process>@<integrand>/settings.toml, and observable resume snapshots live under state/observables/<process>@<integrand>/. User-facing integration_result.json and observable files are derived snapshots, not the resume authority. Workspace manifest version 3 also retains the resolved Gaussian-reference request and the convention for physical absolute contributions at distinct channel points. Earlier checkpoints require a fresh run; resume verifies the reference request before restoring settings or completed-iteration state.

Configuration Architecture

Configuration is split into:

  • Global settings (GlobalSettings): generation, logging directives, parallelism.
  • Runtime settings (RuntimeSettings): kinematics, integrator behavior, sampling, stability, subtraction, and differential event-processing configuration.

Runtime updates normalize the input aliases lmb_multichanneling, lmb_channels, and lmb_channel_weight to sampling_multichanneling, sampling_channels, and sampling_channel_weight before merging with stored settings. These aliases work with files, TOML strings, and key/value updates; one update cannot specify both spellings of the same field.

Differential runtime configuration currently includes:

  • general.generate_events
  • general.store_additional_weights_in_event
  • named quantities
  • named selectors
  • named observables
  • integrator.observables_output

This split is good: generation-time and evaluation-time concerns are separated and independently serializable.

The maintained logging and diagnostics guide documents the user-facing startup precedence, filter language, tag vocabulary, and sink-routing contract implemented by these settings.

Concurrency Model

Concurrency is explicit and use-case scoped:

  • Native generation and compile thread pools use configurable thread counts. FeynKit browser kernels process graph coloring serially with the same filtering and assignment pipeline.
  • Integrator parallelism is controlled via runtime/global settings.
  • Some loops over processes/integrands remain sequential at orchestration level while heavy operations inside are parallelized.

For the differential pipeline:

  • each worker/integrand clone owns its own mutable observable accumulator state
  • local worker results are merged back into the master integrand after chunk evaluation
  • distributed batch mode can return either grouped events or serializable observable accumulator bundles
  • observable snapshots are written only from the merged master state

Testing Architecture

Testing is organized into layers:

  • Unit tests in modules across crates/gammalooprs/src/.
  • Integration test crate: tests/ with reusable harness (tests/src/lib.rs).
  • Additional Rust integration tests in crates/gammalooprs/tests/.
  • Snapshot-heavy coverage for symbolic outputs and numerics.

Differential coverage is currently split into:

  • tests/tests/test_clustering.rs

    • compares the native jet clustering implementation against fjcore
  • tests/tests/test_differential.rs

    • validates grouped event propagation
    • selector behavior
    • observable filling and merge semantics
    • JSON / HwU snapshot output
    • API-facing result shaping using handcrafted fixtures
  • tests/tests/test_evaluation_api.rs

    • real generated-process end-to-end coverage for Rust evaluate_sample(s)
    • graph/cut grouping and incoming-PDG propagation checks
    • selectors / observables / event-group retention
    • detached observable accumulation with explicit coefficients
    • evaluation leaves accumulated statistics unchanged
    • per-sample evaluation metadata
    • x-space vs momentum-space Jacobian behavior
    • minimal-output mode
  • tests/tests/test_runs.rs

    • real generated-process end-to-end coverage for integrate
    • integration-workspace observable output in JSON / HwU formats
    • repeated save dot overwrite behavior
  • tests/tests/test_python_api.rs

    • subprocess-based end-to-end coverage for the public Python API
    • returned event grouping / ids / incoming PDGs
    • selectors / observables / returned metadata
    • minimal-output mode
    • x-space batch and momentum-space sample coverage
    • requires a separately prepared Python environment where import gammaloop already works

Architectural Strengths

  • Clear separation between application shell (gammaloop-api) and domain core (gammalooprs).
  • Rich, serializable settings model with schema generation hooks.
  • Strong process abstraction (Process, ProcessCollection, ProcessIntegrand) that supports amplitude and cross-section workflows.
  • Robust stability pipeline with multi-precision escalation and rotation checks.
  • Differential event-processing is now integrated into the core evaluation path without compromising the stable-weight selection logic.
  • Observable accumulation is mergeable across rayon workers and distributed batch outputs.
Developer architecture · documented revision cece059f4b1e