Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adding a Regression Model (Embedders)

Embedding Pulse, not contributing to it. This recipe registers a REG_<NAMESPACE>_<NAME> model through pulse.Options.Extensions.Regressions and the public extend package. Built-in regressions (REG_OLS, REG_GLM, REG_BAYES_LINEAR) live in internal/processing/ and embedders cannot import it. The full field-by-field contract is in Extension Points; this page walks the order you meet it in.

Audience: an embedder who needs a fit the built-ins do not cover — a nonlinear saturation curve, a pooled model, a robust estimator — and wants it to behave like a built-in everywhere: predict, manifest, MCP, feature profiles, multiplicity, resample / selection, ATTR_REG_PREDICT, saved models and compose sweeps.

1. Pick the form

You needDeclareInterface
one pass over rows, mergeable state (sums, co-moments)Streamable: trueextend.StreamingRegression: UpdateRow, Merge, Finalize
every row at once, iteration (Newton, Levenberg–Marquardt, EM)Streamable: falseextend.BufferedRegression: Fit(rows)

The declaration decides the execution path in predict and at runtime, and pulse.New probes the factory against it (PULSE_EXTENSION_STREAMABLE_MISMATCH when they disagree). The engine owns row admission — listwise deletion on target and every predictor, and on a weighted WeightAware slot only rows with a valid positive weight — so the model never sees a null predictor.

2. A streaming model

A through-the-origin slope: it keeps two sums, so Merge is addition.

type slope struct{ y, x string; sxy, sxx, syy float64; n int }

func (m *slope) UpdateRow(rec extend.Record) error {
    y, _ := rec.NumericValue(m.y)
    x, _ := rec.NumericValue(m.x)
    m.sxy += float64(x * y)
    m.sxx += float64(x * x)
    m.syy += float64(y * y)
    m.n++
    return nil
}

func (m *slope) Merge(other extend.StreamingRegression) error {
    o := other.(*slope) // built by the same factory from the same spec
    m.sxy, m.sxx, m.syy, m.n = m.sxy+o.sxy, m.sxx+o.sxx, m.syy+o.syy, m.n+o.n
    return nil
}

func (m *slope) Finalize() (extend.RegressionOutput, error) {
    if m.n < 2 || m.sxx == 0 {
        return extend.RegressionOutput{}, errors.NewCodedError(
            errors.PROCESSING_REGRESSION_INSUFFICIENT_DATA, "REG_ACME_SLOPE needs two rows with x != 0")
    }
    b := m.sxy / m.sxx
    sse := m.syy - float64(b*m.sxy)
    se := math.Sqrt(sse / float64(m.n-1) / m.sxx)
    return extend.RegressionOutput{
        Coefficients: []extend.RegressionCoefficient{{Name: m.x, Estimate: b, StdErr: extend.Figure(se)}},
        Fit:          extend.RegressionFit{ResidualStdErr: extend.Figure(math.Sqrt(sse / float64(m.n-1)))},
        Outputs:      map[string]any{"sxx": m.sxx},
    }, nil
}

reg := pulse.RegressionRegistration{
    Name:        "REG_ACME_SLOPE",
    Description: "Slope through the origin.",
    Streamable:  true,
    Factory: func(spec *types.RegressionSpec, _ *encoding.Schema) (extend.Regression, error) {
        if len(spec.Predictors) != 1 {
            return nil, fmt.Errorf("REG_ACME_SLOPE takes exactly one predictor")
        }
        return &slope{y: spec.Target, x: spec.Predictors[0]}, nil
    },
    OutputSchema: []pulse.RegressionOutputMeta{{Key: "sxx", JSONType: "number", Description: "Σx²."}},
}

Keep the arithmetic FMA-free (float64(x * y) before an add) when a result must match across amd64 and arm64.

3. A buffered model

An iterative fit sees rows extend.Rows (Len, At(i)), valid only for the call, and may loop over them as often as it needs. The reference extension used by Pulse’s own tests, REG_TESTNLS_EXP (internal/integration/extensions_testnls_exp_test.go), is a nonlinear least-squares fit of an exponential approach to an asymptote, y = a + Σ b_j·(1 − exp(−x_j/τ)), on optimize.LeastSquares — it is the pattern to copy for anything iterative:

type nlsExp struct{ target string; predictors []string }

func (m *nlsExp) Fit(rows extend.Rows) (extend.RegressionOutput, error) {
    // read rows.At(i).NumericValue(name), iterate to convergence, then
    // return one coefficient per parameter and τ as an Output.
    // Report Fit.Iterations; return a coded PROCESSING_REGRESSION_NO_CONVERGE
    // when the iteration fails, which fails the slot alone.
}

A nonlinear parameter is a coefficient too, named by the model. Outputs carries what has no coefficient slot: per-channel k and s objects, a convergence flag, a pooled variance.

A fit that can run long (a sampler, a wide search) also implements extend.ContextRegression beside Fit; the engine then calls FitContext instead — on the run, every resample / selection refit and the pulse.New probe — with the operation’s ctx, done on a caller cancel or when Options.Limits.RequestTimeout elapses. Check it between iterations and return its error:

func (m *sampler) Fit(rows extend.Rows) (extend.RegressionOutput, error) {
    return m.FitContext(context.Background(), rows)
}

func (m *sampler) FitContext(ctx context.Context, rows extend.Rows) (extend.RegressionOutput, error) {
    for it := 0; it < m.iters; it++ {
        if err := ctx.Err(); err != nil {
            return extend.RegressionOutput{}, err // cancel / PULSE_LIMIT_EXCEEDED
        }
        // one iteration
    }
    // ...
}

The probe runs FitContext under a background ctx, so refuse the eight synthetic probe rows cheaply (a coded PROCESSING_REGRESSION_INSUFFICIENT_DATA, say) rather than run a full fit on them.

A fit that returns figures it does not fully trust (a sampler whose chains did not mix, a solver that stopped on a bound) says so in Warnings, never by failing:

out.Warnings = append(out.Warnings, &types.ResponseWarning{
    Code:    string(errors.PROCESSING_REGRESSION_DIAGNOSTIC),
    Message: fmt.Sprintf("max R-hat %.3f exceeds 1.01", rhat),
    Details: map[string]any{"reason": "rhat", "rhat": rhat, "threshold": 1.01},
})

The code must be a registered Pulse code and the message non-empty (else PULSE_EXTENSION_REGRESSION_OUTPUT_MISMATCH). The warning rides the result’s warnings, is lifted onto the response warnings and the envelope, and under Strict fails the slot with its own code. A data refusal that leaves no figure to report is still a coded error (PROCESSING_REGRESSION_NO_CONVERGE, …), which fails the slot alone.

For the iteration itself, use the public bounded Levenberg–Marquardt solver optimize.LeastSquares. Its Writing a model pack section covers the row copy, FMA-free callbacks, bounds, the convergence code and the covariance from JTJ.

Every coefficient name the fit reports is readable in an expression: coef("<fit>", "<name>"), with "lower" / "upper" (the engine’s conf_level interval) and "se", NaN where the fit reports no figure. Outputs are not coefficients, so coef() cannot read them — give a scalar a downstream expression needs a coefficient of its own. An unknown name is PULSE_MODEL_TERM_UNKNOWN. Predict judges it exactly as the run does against a loaded model file, which names the fit’s coefficients; against a Compose fits entry the names exist only once the model runs, so predict accepts any term on an extension fit and the run refuses an unknown one (a built-in fit is judged at predict either way).

4. Declare params, outputs and what the model accepts

Registration fieldWhat it is forRefused when undeclared
Params []pulse.ParamMetathe keys of regressions[i].params — JSONType, Required, Descriptionany params key is PULSE_REQUEST_UNKNOWN_FIELD; with declared params a wrong-typed value or a missing Required one is PULSE_REQUEST_PARAM_INVALID (predict ≡ runtime). No declared params: values pass through and predict advises PULSE_ADVISORY_EXTENSION_PARAMS_UNDECLARED
OutputSchema []pulse.RegressionOutputMetathe Outputs keys the model may fill (Key, JSONType, Description); listed in the manifestan undeclared key is PULSE_EXTENSION_REGRESSION_OUTPUT_MISMATCH
Accepts []encoding.FieldTypefield types for target and predictors; empty = the built-in analytics-numeric setPULSE_FIELD_TYPE_UNSUPPORTED
WeightAwarethe model reads Record.Weight()any weight in force is PULSE_EXTENSION_NOT_WEIGHT_AWARE
Vcovhonours vcov: true; Vcov in the output is then requiredPROCESSING_CONFIG {regression, slot: "vcov"}
PValuesthe model reports coefficient p-values, so multiplicity can correct them and predict counts themp_values is null on every coefficient (under resample too); a non-none multiplicity method is PULSE_MULTIPLICITY_INVALID; a finite PValue in the output is _OUTPUT_MISMATCH undeclared_p_value
Penaltyreads penalty / alpha / l1_ratio itselfPROCESSING_CONFIG {slot: "penalty"}
CovarianceTypesthe robust types it computes itself (cluster, hac, …)PROCESSING_CONFIG {slot: "covariance"}
SupportsSelectiona refit over a predictor subset is meaningful; every fit reports Fit.DeviancePROCESSING_CONFIG {slot: "selection"}; a fit without a deviance is _OUTPUT_MISMATCH missing_deviance
Marginsthe fitted model implements extend.MarginsRegression: after the fit the engine asks it once for each requested term’s effect and delta-method SE (per outcome for a categorical response — Outcomes, keys "<outcome>:<term>") and writes the statistic, p-value and intervalPROCESSING_CONFIG {slot: "margins", requires: "declared_margins"}; declared, a model without the interface is _OUTPUT_MISMATCH missing_margins, effects off the request margins_shape
Comparethe fitted model implements extend.CompareRegression: after a fit a Compose compare entry names, the engine asks it once for its terms, coefficients, covariance, deviance and residual df, and runs the likelihood-ratio and Wald testsPULSE_COMPARISON_INVALID type_unsupported; declared, a model without the interface is _OUTPUT_MISMATCH missing_compare, figures off the spec compare_shape
Scorerscores rows from the fit, enabling ATTR_REG_PREDICT, save and holdoutPULSE_MODEL_SCORE_INVALID no_scorer (ATTR_REG_PREDICT, holdout); save refused
FieldInputsfields the model reads beyond target, predictors and weighta buffered request decodes every field
Validatean extend.SpecValidator[types.RegressionSpec]: refuse a spec from the spec alone (a params value out of range), so predict reports it toonothing is refused: a refusal raised in the factory surfaces only at run time
NoResampleopt OUT of resample: a row-subset refit would break the model (it reads row order) or cost too muchset, resample and its knobs are PROCESSING_CONFIG {slot: "resample"} (predict ≡ runtime); rng_seed still reaches the factory
RequiresOrderfunc(*types.RegressionSpec) bool: the model reads its rows in order (an adstock, a lag); return true for every spec that needs ita spec without order is PROCESSING_CONFIG {slot: "order", reason: "order_required"} (predict ≡ runtime); with one, the rows arrive sorted by order.field (per order.partition), contiguous — never sort them yourself

Declare or refuse. Every shared RegressionSpec slot is either honoured or refused with PROCESSING_CONFIG {regression, slot} — never silently ignored. resample is honoured unless NoResample, conf_level, order and rng_seed always; family, link, max_iters, tol and prior are always refused (carry the model’s own settings in params).

Intervals are the engine’s. Report each coefficient’s StdErr and the fit’s residual Fit.DF where they exist: the engine writes ci_lower / ci_upper at conf_level as estimate ∓ q·SE, q the Student-t quantile on the reported df (REG_OLS’s rule) or the standard normal when no df is reported (REG_GLM’s Wald rule); a coefficient without a standard error gets a null interval. The complete slot table is in Extension Points.

Refuse at predict with Validate. A check your factory makes on the spec alone belongs in Validate instead, so predict reports it:

Validate: func(spec *types.RegressionSpec) error {
    var p struct{ Scale float64 `json:"scale"` }
    if err := json.Unmarshal(spec.Params, &p); err == nil && p.Scale < 0 {
        return fmt.Errorf("params.scale must be non-negative, got %g", p.Scale)
    }
    return nil
},

Predict runs it on a slot every engine rule accepted, the run calls it before the factory (and before any resample / selection refit), and both report the same error: your *errors.CodedError as is, any other error (or a panic) as PULSE_EXTENSION_SPEC_REFUSED with details {category: "regression", type, slot: "regressions"} plus the slot’s name. It sees a copy of the spec as the adapter receives it — the weight in force stamped, an expression-valued param resolved — on both sides, never a record or the schema; it must accept the probe spec (section 7). Full contract: Extension Points.

5. The scorer

A Scorer (extend.RegressionScorerFactory) builds an immutable, concurrency-safe extend.RowScorer from extend.FittedRegression alone — type, target, predictors, Coefficients and Outputs in their JSON form. Because it never sees the request, a fit and the same fit reloaded from a saved model score identically. Anything scoring needs beyond the coefficients (a Hill k and s) must therefore be in Outputs.

Scorer: func(fit extend.FittedRegression) (extend.RowScorer, error) {
    b := fit.Coefficients["x"]
    return slopeScorer{x: fit.Predictors[0], b: b}, nil
},

type slopeScorer struct{ x string; b float64 }
func (s slopeScorer) Columns() []string { return []string{s.x} } // each must be a predictor
func (s slopeScorer) Score(r extend.ScoreRow) (float64, bool) {
    v, ok := r.NumericValue(s.x)
    return float64(s.b * v), ok // ok=false is a null score
}

The scorer scores the whole model: params.terms and a lower / upper bound are refused. A saved fit is a model file listing feature outputs; loading it on an instance that does not register (or a profile hides) the type is PULSE_MODEL_REGRESSION_UNREGISTERED.

6. Resample and selection

Nothing to write: resample (jackknife, bootstrap) refits a fresh model from your factory per replicate with the built-in drivers and replaces std_errors, statistics and p_values with the replicate figures (p_values only when you declare PValues) and re-attaches the intervals as the normal ones on the replicate SE, so the factory must be re-entrant and report the same coefficient names on every fit (_OUTPUT_MISMATCH replicate_coefficients). selection needs SupportsSelection and a Fit.Deviance. Both read the request deadline before every refit, and a ContextRegression refit gets the ctx too. A model a row-subset refit would break, or that is too slow to refit bootstrap_iters times, sets NoResample and the slot is refused instead.

7. The registration probe

pulse.New builds the factory against a synthetic schema (probe_y ~ probe_x1 + probe_x2, plus a weight field), hands it params satisfying your declaration (every Required param, and the first member of each ExactlyOneOf group, gets its ParamMeta.Example when you declare one, else a placeholder of its JSONType; a Required array gets the probe’s two predictor names), fits it over eight synthetic rows and checks the output. A factory may refuse an absent Required param; one that refuses the value it was handed fails pulse.New with PULSE_EXTENSION_FACTORY_PANIC and details.probe_params — declare an Example it accepts (an Example not of its JSONType is PULSE_EXTENSION_PARAM_INVALID, reason example_type_mismatch). A Validate hook runs on the probe spec first: refusing it or panicking is PULSE_EXTENSION_FACTORY_PANIC with details.stage validate. A data-dependent refusal (PROCESSING_REGRESSION_*) on the eight rows is tolerated. Output with no coefficients, an empty or repeated name, a missing / misshapen Vcov or a finite PValue without PValues is _OUTPUT_MISMATCH, checked again on every run.

8. Feature profiles, guidance and multiplicity

  • A registration may carry Purpose, Interpretation and DependsOn exactly as the other categories do; the manifest lists it under extensions.regressions, pulse schema and the MCP regressions[].type enum include it, and a feature profile that omits it makes the name act never-registered.
  • A custom-only profile meets the REG_* dependency edges of ATTR_REG_PREDICT, capability:model_save, capability:regression_holdout and capability:compose_fits (a Scorer for all but the last).
  • Declare PValues: true when the model reports p-values. Then only a coefficient carrying a PValue joins a default multiplicity family (an explicit multiplicity.coefficients list names the model’s own coefficients), and predict counts one p-value per non-intercept predictor (basis lower_bound). Without it the model emits none: predict counts none, and a multiplicity block with any method but none is refused with PULSE_MULTIPLICITY_INVALID at predict and at runtime alike.

A regression cannot read a window label computed in the same request: windows run after regression inputs are bound. For a two-step pipeline (an adstock window, then a fit over it) Materialize the window into a derived cohort first and run the regression against that.

9. Test it

Mirror the in-repo suites, which import only public packages:

  • internal/integration/extensions_regression_test.go — an OLS clone matching REG_OLS within 1e-9 (unweighted, frequency, probability), byte-identical across DecodeWorkers / ShardWorkers.
  • internal/integration/extensions_regression_nls_test.go — a nonlinear fit recovering its generating curve, a scorer through ATTR_REG_PREDICT, save and reload, bootstrap, manifest and profile hiding.
  • internal/integration/extensions_regression_validate_test.go — a Validate hook’s refusals (uncoded, coded, panic) equal at predict and at run time, and the probe’s stage: validate refusal.
  • TestExtensions_* — the parity suites: predict equals runtime for every refusal, and the manifest, schema and MCP enum list the model.

Then run make sites ARGS="categories" for the surfaces an extension category touches, and see Extension Points for the full error-code table.