API Conventions

September 2, 2026 · View on GitHub

Applies to: anofox-statistics v0.3.0 and later Status: Authoritative — Phase 6 doc-SQL validation checks examples against this document


1. Function Naming Convention

Pattern

{model}_{verb}[_{suffix}]

All functions are unprefixed and uniform. The anofox_stats_ prefix that existed in pre-v0.3.0 versions has been dropped (breaking change — see §5).

Model component

The statistical model or family name, using snake_case:

Model componentDescription
olsOrdinary Least Squares
ridgeRidge (L2-penalized) regression
elasticnetElastic-net (L1+L2) regression
wlsWeighted Least Squares
huberHuber robust regression
ransacRANSAC robust regression
rlsRecursive Least Squares
blsBounded Least Squares
nnlsNon-Negative Least Squares
theil_senTheil-Sen robust regression (note: was theilsen pre-v0.3.0)
glmGeneralized Linear Model
poissonGLM with Poisson family
logisticGLM with Binomial/Logistic family
gammaGLM with Gamma family
nbGLM with Negative Binomial family
aftAccelerated Failure Time (survival)
aidAnomaly / Influence Detection
t_testStudent's t-test
pearsonPearson correlation
spearmanSpearman correlation
kendallKendall correlation
distance_corDistance correlation
iccIntraclass correlation
chisq_testChi-squared test
chisq_gofChi-squared goodness-of-fit
fisher_exactFisher's exact test
g_testG-test (likelihood ratio)
mcnemarMcNemar's test
tostTwo One-Sided Tests (equivalence)
vifVariance Inflation Factor

Verb component

The verb describes what the function does:

VerbDescription
fitFit a model, returning a STRUCT with coefficients and diagnostics
fit_predictFit and return predictions (in-sample or with new X)
predictPredict from previously computed coefficients
testHypothesis test, returning a result STRUCT

Suffix component

SuffixWhen used
_aggDuckDB aggregate function (use with GROUP BY or OVER)
(none)Scalar or table function

Full examples

FunctionTypeDescription
ols_fit(y, X)ScalarOLS fit on literal arrays
ols_fit_agg(y, x_col)AggregateOLS fit across groups
ols_fit_predict(y, X, X_new)TableOLS fit + predict from table-function call
ols_fit_predict_agg(y, x_col)Window aggregateRolling OLS predictions
theil_sen_fit(y, X)ScalarTheil-Sen fit on literal arrays
theil_sen_fit_agg(y, x_col)AggregateTheil-Sen fit across groups
poisson_fit_agg(y, x_col)AggregateGLM Poisson fit
t_test_agg(x, y)AggregateTwo-sample t-test
vif(y, X)ScalarVariance Inflation Factors
bls_fit_agg(y, x_col)AggregateBounded Least Squares fit
nnls_fit_agg(y, x_col)AggregateNon-Negative Least Squares fit

2. Option-Map Keys

Options are passed as a DuckDB MAP literal, e.g.:

SELECT ols_fit_agg(y, [x1, x2], {'fit_intercept': true, 'compute_inference': true}) FROM tbl;

Key convention

All option keys are snake_case matching the Rust core. Unknown keys are rejected at bind time:

-- This raises: "unknown option 'intercept_mode'; valid keys: fit_intercept, ..."
SELECT ols_fit_agg(y, [x], {'intercept_mode': true}) FROM tbl;

Common option keys

KeyTypeDefaultApplies toDescription
fit_interceptBOOLEANtrueAll regressionFit a constant intercept term
interceptBOOLEANAll regressionAccepted alias for fit_intercept
compute_inferenceBOOLEANfalseOLS, Ridge, WLSCompute std errors, t-values, p-values
confidence_levelDOUBLE0.95All with CIsConfidence level for intervals; must be in (0, 1)
alphaDOUBLERidge, Elastic-netRegularization strength (L2 penalty); must be > 0
l1_ratioDOUBLE0.5Elastic-netMix of L1 vs L2; must be in [0, 1]
lambdaDOUBLERidgeAlias for alpha
max_iterationsINTEGERIterative solversMaximum iterations
toleranceDOUBLEIterative solversConvergence tolerance
hc_typeVARCHAR'HC3'OLS robust SEsHeteroscedasticity-consistent SE type
weight_colVARCHARWLSColumn name for observation weights
huber_epsilonDOUBLE1.35HuberEpsilon threshold
max_trialsINTEGER100RANSACMaximum RANSAC trials
residual_thresholdDOUBLERANSACInlier threshold
min_samplesINTEGERRANSACMinimum inlier sample size
linkVARCHARGLMLink function override
familyVARCHARGLMDistribution family
distributionVARCHARAFTSurvival distribution
interval_typeVARCHAR'confidence'Prediction'confidence' or 'prediction'

Option value ranges are enforced at bind time. Providing a value outside the documented range raises InvalidInputException immediately.


3. Return-Struct Field Names

Result structs use snake_case field names. The standard field set for regression families is:

FieldTypeDescription
coefficientsDOUBLE[]Fitted coefficients (excluding intercept)
interceptDOUBLEIntercept term (or 0 if fit_intercept: false)
std_errorsDOUBLE[]Standard errors of coefficients (when compute_inference: true)
t_valuesDOUBLE[]t-statistics for each coefficient
p_valuesDOUBLE[]Two-sided p-values
r_squaredDOUBLECoefficient of determination R²
adj_r_squaredDOUBLEAdjusted R²
f_statisticDOUBLEOverall F-statistic for the fitted model
f_pvalueDOUBLEp-value of the overall F-statistic
residual_std_errorDOUBLEResidual standard error
n_obsBIGINTNumber of observations used
n_featuresBIGINTNumber of features (predictors)
ci_lowerDOUBLE[]Lower confidence-interval bounds
ci_upperDOUBLE[]Upper confidence-interval bounds

Per-family exceptions (intentional — do NOT force z → t)

GLM families (Poisson, Logistic, Gamma, Negative Binomial):

GLM uses z_values instead of t_values because the Wald statistic under GLM asymptotic theory follows a standard-normal (z) distribution, not a t distribution. This is the correct statistical convention for these families.

FieldTypeDescription
z_valuesDOUBLE[]Wald z-statistics (replaces t_values)
log_likelihoodDOUBLELog-likelihood at convergence
devianceDOUBLEModel deviance
null_devianceDOUBLENull-model deviance
aicDOUBLEAkaike Information Criterion
bicDOUBLEBayesian Information Criterion
n_iterationsINTEGERIterations to convergence

Note: GLM does not include r_squared (not a meaningful statistic for non-Gaussian families).

AFT survival models:

AFT survival analysis uses z_values for Wald statistics (survival convention) and omits r_squared.

FieldTypeDescription
z_valuesDOUBLE[]Wald z-statistics
log_likelihoodDOUBLELog-likelihood at convergence
aicDOUBLEAkaike Information Criterion
scaleDOUBLEScale parameter

ALM / Additive models:

ALM (Additive Linear Models) uses a different core field set: omits r_squared, carries log_likelihood, aic, bic, and scale.


4. Error Messages

When a function receives invalid input, it throws an exception with the format:

{function_name}: {problem}; expected {shape} (got {actual})

Exception taxonomy

Exception classRaised when
InvalidInputExceptionUser data/shape problems — dimension mismatch, insufficient rows (n < n_features + 1), all-non-finite input, constant/zero-variance column, unknown option key, option value out of range
FunctionExceptionNumerical failures — singular matrix (non-invertible), convergence failure, internal panic

Unknown option keys

Unknown option-map keys are rejected at bind time:

-- Raises: "unknown option 'typo_key'; valid keys: fit_intercept, compute_inference, ..."
SELECT ols_fit_agg(y, [x], {'typo_key': true}) FROM tbl;

Degenerate window frames

When a _fit_predict_agg function is used with OVER (... ROWS BETWEEN ...) and the window frame has fewer than n_features + 1 rows, the function returns NULL for that row (rather than raising an error). This is standard rolling-regression behavior — degenerate frames at the start of a partition simply have insufficient data to fit.


5. Breaking Changes in v0.3.0

Dropped anofox_stats_ prefix

All functions previously registered under the anofox_stats_ prefix are now registered under unprefixed names only. There are no deprecated aliases.

Migration: Remove the anofox_stats_ prefix from every function call.

-- Before (v0.2.x):
SELECT anofox_stats_ols_fit_agg(y, [x1, x2]) FROM tbl;

-- After (v0.3.0+):
SELECT ols_fit_agg(y, [x1, x2]) FROM tbl;

theilsen renamed to theil_sen

The Theil-Sen estimator functions were previously named theilsen_*. They are now theil_sen_* (underscore inserted for consistency).

-- Before:
SELECT anofox_stats_theilsen_fit_agg(y, [x]) FROM tbl;

-- After:
SELECT theil_sen_fit_agg(y, [x]) FROM tbl;

.r2 field removed; use .r_squared

The return-struct field was always named r_squared in the C++ type builder; some older test examples used .r2 which was not a valid field path. The correct field is .r_squared.

-- Correct:
SELECT (ols_fit([1.0, 2.0, 3.0], [[1.0, 2.0, 3.0]])).r_squared;

No deprecated aliases

No backward-compatibility aliases are provided. All callers must update to the new names.


6. Validation Rules

Phase 6 doc-SQL validation checks

When Phase 6's documentation-SQL validator runs, it checks every SQL example in docs/ against the live extension. Examples must:

  1. Use unprefixed function names (no anofox_stats_ prefix).
  2. Use r_squared (not r2) for the coefficient of determination.
  3. Use theil_sen_* (not theilsen_*).
  4. Use z_values for GLM and AFT results (not t_values).
  5. Pass only known option keys (no typos silently ignored).