Maintaining this book
A textbook is only worth reading if it stays true. This book explains why sciencekit is
built the way it is, and sciencekit is not finished — the roadmap (docs/PRD.md) maps out
new algorithms in phases that stretch from preprocessing all the way to trees, ensembles,
clustering and Python bindings. Every one of those algorithms will change the library, and
every change risks turning a sentence in this book into a lie. This chapter is the
contract that keeps the book truthful: a small set of rules that decide when to add a
chapter, when to edit one, and how every update flows safely from a branch to the published
site.
1. The problem we were solving
Documentation rots. It is not a bug in any single sentence; it is a slow drift. Someone adds
a new algorithm, nobody updates the matching page, and six months later the book describes a
SKKNeighborsClassifier that behaves nothing like the code. A reader who trusts the book
builds the wrong mental model, and the wrong mental model produces subtle, expensive bugs.
You cannot stop change, so the only fix is to make keeping up a mechanical habit. sciencekit
already commits to this habit at the repository level — its AGENTS.md requires that every
code change ships a companion documentation change on its own branch, merged separately.
This chapter is where that general rule becomes a concrete procedure for this book: when a
feature lands you add a chapter; when behavior changes you update the chapter; and both are
done through the same worktree-and-branch machinery that keeps main clean.
2. The decisions — and the roads not taken
| Decision | Why we chose it | Alternatives we discarded |
|---|---|---|
| A new feature or algorithm → a NEW chapter | A genuinely new algorithm is a new concept with new objects, new tests and new rationale. It deserves a teaching arc of its own; bolting it onto an existing chapter would bury it and make that chapter too long to follow. The roadmap’s phases arrive one algorithm at a time, so the book grows one chapter per algorithm. | Amending every feature into a giant “everything” chapter — it becomes an unreadable dump. |
| A bug fix or refactor → UPDATE the existing chapter | A bug fix or refactor changes behavior, not concept: the chapter’s question (“why does this object exist?”) stays valid, but some of its answers change. Editing in place keeps the story honest without duplicating it. The rule is therefore update, never fork — do not leave a stale chapter and add a “new and improved” twin. | Copying the chapter and writing a parallel “v2” version — two chapters drift apart and readers never know which is current. |
Every doc change ships on its own docs/<name> branch merged into docs/documentations | The book is a deployable artifact: pushing to docs/documentations rebuilds and publishes it to GitHub Pages. Working on a dedicated branch means main and docs/documentations never receive half-finished prose, and the same change can be reviewed independently of the code PR that motivated it. | Committing doc edits straight to docs/documentations — risky, unreviewed, and it bypasses the two-worktree discipline used for code. |
3. The concepts, taught from zero
What “shipping a doc change” means
In most projects you might finish a feature and also remember to update the docs. In
sciencekit that is not optional and not deferred: AGENTS.md says every code change is
paired with a documentation change that updates the mdBook for the newly introduced
behavior, “on its own doc branch and its own PR merged into docs/documentations”. The doc
branch is created at the same time as the code change, not after it.
The two documentation branches
docs/documentationsis the landing branch: the finished book lives here, and the GitHub Actions workflow (.github/workflows/deploy-documentation.yml) builds and deploys it to GitHub Pages on every push.docs/<name>is a working branch. You never write ondocs/documentationsdirectly; you open a worktree for your change and merge it in when it is ready.
This is deliberately separate from the -openspec planning branch, which only holds the
OpenSpec planning artifacts. Documentation (the book) and planning (the spec) are two
different concerns and use two different branches.
What “worktree” means here
A git worktree lets you check out a branch into a separate folder without disturbing your
current checkout. Every docs change lives in temporary/worktrees/docs/<name> on branch
docs/<name>. temporary/ is git-ignored, so these working copies are never committed —
they are scratch space that keeps each change isolated.
4. Each object, explained
The chapter file
What it is — a markdown file under docs/src/development-explained/, one per chapter,
following the anatomy in the chapter template (CHAPTER_TEMPLATE.md).
Why it exists — each chapter is the durable record of one concept’s design rationale, taught from zero for a reader who knows programming but not Rust or numerical computing.
What we rejected — putting everything in one huge page; a single page cannot teach or be maintained.
The worktree and branch
What it is — temporary/worktrees/docs/<name> on branch docs/<name>.
Why it exists — it isolates a doc change so the deployable docs/documentations branch
only ever receives finished, reviewed prose.
What we rejected — editing docs/documentations directly; unreviewed edits reach the
published site immediately.
The build gate
What it is — mdbook build docs, run locally before pushing.
Why it exists — it validates every chapter and its links before the change is merged; the
book’s config uses create-missing = false, so a broken link fails the build rather than
silently generating an empty page. The gate must pass with zero warnings.
What we rejected — relying on the remote deploy workflow to catch errors; that would let broken content reach the published book.
5. A real walk-through: adding an algorithm’s chapter
Here is the exact procedure, using a hypothetical new algorithm from a later roadmap phase (say a tree model arriving in Phase 4).
Step 1 — open the worktree. Create the docs change alongside the code change:
git worktree add temporary/worktrees/docs/sk-decision-tree docs/sk-decision-tree
Step 2 — write the chapter. Create docs/src/development-explained/chNN-*.md following
the template: the plain-language problem, the decisions table, concepts taught from zero,
each object explained, and a walk-through built from the real *_tests.rs tests. Keep code
identifiers exactly as they are in the source.
Step 3 — register the chapter. Add it to the table of contents in
docs/src/SUMMARY.md under the right part of the book, in the position that matches the
reading order.
Step 4 — run the gate.
mdbook build docs
Fix every warning. A warning here means the published book could be broken.
Step 5 — merge. Open a PR for branch docs/sk-decision-tree into docs/documentations.
When it merges, the deploy workflow rebuilds and publishes the book automatically.
The successive-halving chapter (chapter 53) is the worked example of this path for a new
algorithm: the search lives in crates/sciencekit_model_selection/src/halving/, its companion
tests (halving_scheduler_tests.rs, halving_trace_tests.rs, halving_subsample_tests.rs,
halving_evaluation_tests.rs, halving_aggressive_tests.rs, the per-family halving_refit_tests.rs
modules, the concurrency and representation tests, and acceptance_tests/halving/) are cited by
name in the chapter, and the chapter, its SUMMARY.md entry and the halving rows in
docs/src/algorithms.md all landed together on the docs/halving-grid-search-book branch.
Updating, not forking
If the change is a bug fix or refactor, replace the affected part of the existing chapter — the decisions table, the object descriptions, the walk-through — and adjust any prose that now contradicts the code. Do not copy the chapter and add a “v2”. The book stays truthful because there is exactly one place where a given behavior is explained, and it is always the current explanation.
docs/PRD.md. When a roadmap phase flips from "Planned" to "In
progress", the roadmap page and the new chapter should move together.
6. Look inside
flowchart LR
accTitle: How a code change flows into the documentation
accDescr: A code change opens a code worktree branch and a docs worktree branch. The code branch becomes a code pull request. The docs branch must pass mdbook build with zero warnings, then becomes a doc pull request merged into docs/documentations, which deploys to GitHub Pages.
C[code change] --> B1[worktree code branch]
C --> B2["worktree docs branch"]
B1 --> P1[code PR]
B2 --> G["mdbook build docs<br/>zero warnings"]
G --> P2["doc PR → docs/documentations"]
P2 --> D["deploy → GitHub Pages"]
The docs branch is created at the same moment as the code branch, runs through its own build
gate, and lands on docs/documentations through its own PR — the same “two coexisting
worktrees, two separate PRs” discipline that governs code.
7. Recap
- A new feature or algorithm → add a new chapter, registered in
SUMMARY.md. - A bug fix or refactor → update the existing chapter in place; never add a parallel twin.
- Every code change ships its doc change on a
docs/<name>branch merged intodocs/documentations— created alongside the code change, never deferred. mdbook build docsmust pass with zero warnings before you push; broken links fail the build, and the deploy happens automatically on merge.- Keep counts, phases and status in sync with
docs/PRD.md.
Next chapter: we step down from the meta and back into the code, where the algorithms built
with these rules — SKStandardScaler,
SKMinMaxScaler,
SKRobustScaler, the
encoders, the
imputers, the first supervised model
SKLinearRegression, the first regularized one,
SKRidge, and the L1-regularized pair
SKLasso & SKElasticNet — and the first classifier,
SKLogisticRegression — show the whole procedure in action.
The stochastic-gradient family
(SKSGDClassifier & SKSGDRegressor) then shows the
same rules applied to an estimator whose cost does not depend on the dataset size. The
source-provider chapter closes the streaming story:
one seam that accepts both a concrete source and a reopenable factory, and the epoch rule
each estimator class follows. The
owned feature block chapter completes it: sparse data
streams without ever being densified, and implicit zeros shape every statistic. The
metrics foundation chapter then turns all of that work into
numbers: a label space, a confusion matrix, per-class scores, regression errors and the
mergeable accumulators that make evaluation streaming and parallel. The
deterministic randomness chapter adds the seed
convention every stochastic estimator shares: SplitMix64, pure sub-seed derivation and
thread-count invariance. The
sparse distance chapter then shows how one
dispatcher serves all four dense/sparse representation pairs without ever densifying a
sparse design. The ranking metrics chapter closes the
evaluation story with ROC/AUC, precision-recall, log loss, balanced accuracy and MCC. The
type-safe pipeline chapter then composes transformers and
a final estimator into a chain whose validity is checked by the compiler, not at fit time.
The spatial index chapter adds exact k-d and ball trees: lower
bounds, deterministic tie ordering, and the dense-only exception applied to geometry. The
dataset interop chapter adds the engine-neutral seam: ordered
schema, explicit selection, one missing-value policy, typed batches, streaming sources and the
async bridge. The k-means chapter adds the first unsupervised
estimator: seeded k-means++, the Lloyd iteration, Elkan pruning, empty-cluster repair and
the typed cluster assignments. The
decision tree chapter adds CART: impurity, dense and sparse
split search, deterministic ties, feature subsampling, class weights and importances. The
model selection chapter adds train/test split, the three
K-fold flavours, row gathering and cross-validation scoring. The
C ABI chapter adds the stable boundary every non-Rust binding wraps:
opaque handles, borrowed and owned arrays, status codes, panic containment and persistence.
The clustering metrics chapter adds silhouette, ARI, NMI,
homogeneity/completeness/V-measure and the centroid indices. The
k-nearest neighbours chapter adds the brute-force searcher, the
runtime strategy dispatch, weighting and the estimator representation parity. The
k-NN imputer chapter adds the NaN-aware donor search, chunked
distance blocks, weighting with a column-mean fallback and the dense-only contract. The
grid search chapter adds candidate enumeration, shared folds,
deterministic best selection, error policies and the refit. The
Lua bindings chapter adds the embedded interpreter, userdata
lifecycle, table conversion and the packaged module. The
Go bindings chapter adds the cgo boundary, C-owned copies,
finalizers, structured errors and the build/CI story. Both bindings now live in their own
repositories — neurono-ml/sciencekit-go and
neurono-ml/sciencekit-lua — and consume
the sciencekit_ffi C ABI that this repository keeps. The
Arrow interop chapter adds the neutral schema mapping, the
borrowed primitive columns, the missing-value policies over Arrow nulls, the C Data
Interface in both directions and the columnar file sources with projection pushdown. The
GPU compute contracts chapter adds the device
inventory and capabilities, the deterministic selection rule, the validated device
buffers, the closed kernel catalogue and the execution plan that records a backend and a
fallback reason.
The randomized SVD chapter adds the seeded range finder, the
thin Householder QR, the small Gram SVD, the sparse products without densification, the
implicit centering and the accuracy bound against the exact decomposition. The
random forest chapter opens sciencekit_ensemble with
seeded per-tree bootstrap sampling, de-correlated Sqrt feature subsampling, lock-free
parallel CART fitting, out-of-bag accuracy and $R^2$ scoring, normalized mean feature
importances and non-densifying CSR parity. The
support-vector machines chapter adds the Mercer and similarity kernel
catalogue in sciencekit_math, the pure-Rust second-order SMO solver with a bounded LRU
kernel-row cache, one-vs-one SKSVC with Platt scaling and Wu–Lin–Weng pairwise coupling,
and $\varepsilon$-insensitive SKSVR over support-vector-only dense and CSR blocks.
The DBSCAN chapter adds density reachability over spatial trees and
sparse brute force, the core/border/noise taxonomy with typed SKClusterLabel::Noise,
deterministic component numbering and the nearest-core predict_clusters extension.
The PCA chapter builds SKPCA in sciencekit_decomposition on top of
the randomized SVD kernel: feature centering, the Full/Randomized/CovarianceEigh
solver portfolio and Auto resolution, component-sign determinism, epsilon-floored
whitening, and the explicit sparse-densification contract.
fallback reason. The
feature union chapter adds parallel transformer fan-out inside
sciencekit_pipeline: tuple and boxed member collections, CSR-preserving horizontal
concatenation, member-indexed error context and nested pipeline composition.
The JSON debug format chapter adds the deterministic
human-readable SKModelState schema, the pretty and compact writer, the duplicate-aware
validating reader and the round-trip acceptance guarantees across scalar and tensor types.
The Truncated SVD chapter adds SKTruncatedSVD in
sciencekit_decomposition: uncentered randomized low-rank factorization for latent semantic
analysis, non-densifying CSR fit/transform/inverse_transform parity, two-pass sparse
variance ratios and thread-count-invariant 256-row chunking.
The generic bagging chapter extends sciencekit_ensemble with
SKBaggingClassifier<B> and SKBaggingRegressor<B>: compile-time supervision bounds over
any base estimator, independent row and feature bootstrap streams, non-densifying CSR
feature-subset routing, two-tier SKBaggingError<E> propagation and out-of-bag accuracy
and $R^2$ scoring.
The gradient boosting chapter extends sciencekit_ensemble with
SKGradientBoostingClassifier<F> and SKGradientBoostingRegressor<F>: a loss-agnostic stage loop
that fits structure-only trees to the negative gradient, replaces leaves with damped Newton steps
$-\sum g / (\sum h + \lambda)$, shrinks every stage by the learning rate, subsamples rows without replacement from
per-stage seeds, and early-stops by truncating back to the best held-out validation stage, over dense
and non-densified CSR input for binary, multiclass and all three regression losses.
The outlier detection chapter closes Wave 5 in
sciencekit_outlier and sciencekit_common: the one-byte SKOutlierLabel and
SKOutlierPredictor<F> contract, seeded random isolation trees over SKTree, harmonic BST
path-length scoring, Auto and quantile contamination offsets, and non-densifying CSR-to-CSC
representation parity.
The incremental PCA chapter extends sciencekit_decomposition
out-of-core with SKIncrementalPCA: exact Chan-Golub-LeVeque scatter merging, Neumaier-compensated
sparse CSR Gram updates without densification, symmetric eigh finalization matching SKPCA,
chained partial_fit updates and reopenable multi-epoch fit_streaming.
The mini-batch k-means chapter adds
SKMiniBatchKMeans<F> in sciencekit_cluster: the exact per-center learning-rate update in
closed form over dense and non-densified CSR batches, seeded bounded-sample initialization with
best-of-n_init inertia selection, deterministic low-count center reassignment, incremental
partial_fit, multi-epoch fit_streaming over reopenable providers with positive-tolerance
early stopping, and the typed SKMiniBatchKMeansModel<F> prediction, transform and state
export surface.
The extended Safetensors format chapter adds the
binary SKModelState persistence adapter in sciencekit_interop::safetensors: standard
single-file Safetensors compatibility, sciencekit.* header metadata, SKShardPlan
multi-shard splitting with atomic .index.json manifests, dual-region header and payload
padding for in-place seek appends with automatic shard overflow, and optional magic-byte
auto-detected Gzip, Brotli and Snappy compression.
The runtime DAG pipelines chapter adds SKPipelineGraph on top of
sciencekit_pipeline: the mandatory builder and private constructors, cycle/single-sink/reachability
validation, the deterministic level order with ascending node identifiers, the edge-weight merge
order that concatenates incoming blocks in exact connect order without densifying CSR, the
node-attributed SKPipelineGraphNodeError checked variants and the type-erased SKBoxedFinalModel
behind the typed classifier and regressor wrappers.
The OpenTelemetry export chapter adds production three-signal
telemetry in sciencekit_telemetry: builder-validated OTLP gRPC and HTTP configuration,
resource metadata propagation, error-enriched trace spans, trace-correlated structured logs,
closed-vocabulary operation metrics and the process-wide SKTelemetry init, force_flush,
shutdown and Drop lifecycle with a silent zero-traffic default.
The streaming pipelines chapter extends sciencekit_pipeline
with an out-of-core composition layer: the SKStreamingTransformer contract, the
SKStreamingPipeline builder and its chained fitting through the shared prefetch executor,
one-shot materialization within memory_budget_bytes, multi-epoch replay on reopenable providers,
the bounded SKFinalizerBuffer that preserves CSR, stage-indexed error propagation and the
Send + Sync fitted pipeline with its SKStreamingFitReport.
The Polars and DataFusion sources chapter adds the
feature-gated tabular sources in sciencekit_interop: the materialized
SKTabularDataset<F> with SKColumnKind, SKTabularSourceConfig and the owned
SKNominalMatrixOwned; Polars DataFrame/LazyFrame conversion with categorical labels read
from their strings; DataFusion 46 DataFrame/RecordBatch conversion plus a true
record-batch stream and Parquet-through-DataFusion; and the missing-value mapping shared by
both engines.
The memory-mapped sources chapter adds the memmap feature of
sciencekit_interop: read-only memmap2 mappings behind SKMappableSource and SKLazySource,
raw binary matrices with explicit descriptors and exact length validation, zero-copy NumPy .npy
float rows with Fortran-order, endianness and alignment rejection plus an explicit casting path,
footer-indexed Arrow IPC random access with per-batch decoding, bounded sequential blocks and
Send + Sync concurrent readers.
The linear support-vector machines chapter completes
sciencekit_svm with SKLinearSVC<F>: the LIBLINEAR-style dual coordinate descent for the
L1-hinge and L2-squared-hinge losses, the SKDenseLinearSvcDesign /
SKSparseLinearSvcDesign abstraction that scans CSR stored entries without densifying, the
unpenalized intercept recovered by a one-dimensional bisection, parallel one-vs-rest heads
with deterministic order and smallest-index tie-breaking, class-weighted box capacities, the
explicit NotConverged { iterations } budget, and the deliberate UnsupportedOperation from
predict_probabilities.
The histogram gradient boosting chapter adds the
histogram_boosting module of sciencekit_ensemble: deterministic quantile binning
(SKNumericBinning, SKFeatureBinning, SKBinnedDataset) with a reserved missing bin and a
column-major u8 store, parallel gradient/Hessian accumulation, the Newton gain prefix scan,
parent-child histogram subtraction, gain-ordered leaf-wise growth under maximum_leaf_nodes and
minimum_samples_leaf, bitvec categorical membership masks with an unknown-category direction,
learned default_left missing routing, and the SKHistGradientBoostingClassifier /
SKHistGradientBoostingRegressor builders, models and prediction surface that reuse the W4.4 loss
contract and early-stopping monitor while binning dense and CSR queries without densification.
The OpenCL backend chapter adds the first real device backend
behind the contracts of sciencekit_gpu: the opencl feature (re-exported by the
sciencekit_gpu_opencl package through gpu-opencl), the exact opencl3 0.12.0 pin whose
dynamic loader opens libOpenCL.so.1, deterministic enumeration through the ICD loader,
capability reporting with the full kernel catalogue, SKOpenClBackendBuilder with strict and
fallback construction, resident SKOpenClBuffer<F> allocations with device-memory and capacity
validation, explicit accounted transfers (SKOpenClTransferReport), runtime-compiled and cached
pairwise-distance, tiled GEMM, elementwise and tree-prediction kernels with CPU-parity tests,
concurrent dispatch parity, span fields recording opencl, the device and the bytes moved, and
an honest SKFallbackReason::NoDeviceAvailable for feature-off, device-less and failed-build
configurations.
The model export retrofit chapter adds the shared
SKExportable / SKImportable round trip to every retrofitted family: the single
SK_MODEL_FORMAT_VERSION, the dotted tensor naming scheme, the dense/CSR-preserving
support-vector and training-design codecs, the NaN-aware determinism check
(sk_states_equal), and the companion tests that fit, export, import and compare
predictions — including the nested tree states of the forests and gradient boosters.
The chapter’s coverage table names the families still pending so the book never claims
more than the code delivers.
The ONNX export chapter extends the neutral export
contract with a translator to ONNX: the sciencekit_onnx crate, the
SKToOnnx<F> blanket implementation over SKExportable<F>, the validated
SKOnnxGraphBuilder over prost-declared protobuf messages, opset 17 plus
ai.onnx.ml 3, the per-family operator subset (scalers, one-hot, linear and
logistic, ONNX-ML tree ensembles, neighbours, k-means, PCA/SVD and pipelines),
the dtype/metadata rules, and the coverage matrix that keeps unsupported
families explicit. When you add an exporter, extend sk_onnx_coverage, add a
Rust-parity test that writes a fixture, and rerun
crates/sciencekit_onnx/validation/compare_with_onnxruntime.py so the claim
stays backed by a real runtime.
The ONNX import chapter closes the interoperability
loop: sciencekit_onnx decodes a model into the shared serde-onnx IR (the
exporter now assembles that same IR), validates the opset, the documented
operator subset, external data and the interface, and runs the graph with a
dependency-ordered interpreter behind SKOnnxPredictor<F> and
SKOnnxPredictorBuilder<F>. When you add an importer operator, extend
SK_ONNX_SUPPORTED_OPERATORS (or SK_ONNX_SUPPORTED_ML_OPERATORS), add the
dispatch arm and a companion test, then rerun the three-way harness after
cargo run -p sciencekit_onnx --example validate_import <fixture-root> so the
imported prediction stays proven against both the Rust model and onnxruntime.
The native model import chapter closes the
round trip: SKNativeImport<F> rebuilds a real fitted type from a neutral
state, with structural format detection, typed rejections at the trust
boundary, exact tensor-set and class-table validation, continued fitting for
the families that keep a learning state, and an ONNX mapper for the documented
affine/scaler/tree subset. When you add a family, extend
sk_native_import_coverage and the ONNX mapper, add a round-trip test that
compares predictions with the original, keep the external fixture in
crates/sciencekit_onnx/validation/external/ reproducible with
validation/compare_native_import.py, and update this chapter rather than
adding a parallel one.
The low-rank adapter chapter adds the
parameter-efficient path to the same export contract: SKLoraAdapter<F> and its
builder, the frozen SKLoraBaseModel<F>, the A/B factors of
SKLoraAttachedModel<F>, merge/unmerge parity, the persisted
lora.<target>.a/.b tensors, and the registry that rejects duplicate
identifiers. When you extend adapter coverage, keep the zero-adapter identity,
the merge identity and the persisted-shape validation tests green, extend the
lora_*_tests.rs companions and this chapter rather than adding a parallel one.
The umbrella crate chapter explains the entry point
rather than an algorithm: why one package re-exports twenty-one, how the
umbrella lives in the existing workspace-root package (a crates/sciencekit
would have duplicated the package name), how the curated prelude differs from a
glob import, which names collide across families (SKClassWeight is three
distinct policies; SKFeatureBlock is one shared identity), and how the
integration features forward with dep: while the default build stays
core-only. When you add a family, extend src/<family>.rs, add the name to the
prelude only when it is broadly useful, forward any heavy dependency through a
feature, and extend reexports_tests, prelude_tests and features_tests so
the chapter’s claims stay executable.
The workflows CLI chapter turns the library into a
process: the sciencekit binary, the versioned workflow record, the
flags > environment > file > defaults resolution, the stable exit-code
contract, every subcommand, and the feature-gated Parquet/YAML/ONNX paths. When
you add a command or a workflow key, extend cli/arguments.rs,
workflow/schema.rs, workflow/validation.rs and config/precedence.rs
together, add a process-level test beside the existing ones in
crates/sciencekit_cli/tests/, and update this chapter rather than adding a
parallel one.