Guidance for AI coding agents working in this repository. Human contributors should start with CONTRIBUTING.md; this file adds the context an agent needs to make correct changes without exploring the whole package first.
What this package is
tidywater is an R package of water quality models for drinking water treatment. It bundles published, peer-reviewed empirical and chemistry-based models in one consistent interface so they can be chained into a full treatment train inside a tidyverse workflow.
The output of this package is used to make real engineering decisions. Numeric accuracy and fidelity to the published sources matter more than elegance, brevity, or convenience.
Domain guardrails — read before changing any model
These rules are not negotiable without a human maintainer’s explicit approval:
- Do not change model equations, coefficients, or fitted constants unless the change is backed by a specific published reference (author, year, equation or table number). If you believe a model is wrong, say so and stop — do not “fix” it. Model math that looks like a bug is usually the published model.
- Do not extend a model outside its applicability range. Each model was fit over a bounded range of pH, temperature, DOC, dose, etc. Silently allowing input outside that range is a correctness bug, not a usability improvement.
-
Warnings and errors about out-of-range or missing inputs are a feature. Do not remove them, loosen them, or wrap calls in
suppressWarnings()to make something pass. (Tests are the exception: existing tests usesuppressWarnings()deliberately to isolate the behavior under test.) -
Any change that alters numeric output is a breaking change. It needs a
NEWS.mdentry under “Breaking changes” and should be flagged prominently in the PR description, even if the difference looks negligible. -
New or modified models need a citation. Add
@sourceroxygen tags and make sure the reference is on the reference list wiki. -
Data files must be reproducible. Everything in
data/is generated bydata-raw/compile_tidywater_data.R. Never add an.rdathat a script indata-raw/cannot regenerate. Note that.csvand.xlsxfiles are gitignored on purpose.
Architecture
The water S4 object
Everything revolves around the water class defined in R/waterclass.R. It has ~60 slots covering general parameters (ph, temp, alk, tds), carbon (toc, doc, uv254, dic), ions, pH-dependent species, disinfectants, and DBPs.
- A
wateris created bydefine_water()and then transformed by model functions, each of which returns a newwater. -
Internal units are molar (M). mg/L and similar units are converted at the boundary by
convert_units()/convert_units_private(). Assume a slot is molar unless its documentation says otherwise. - Unset slots are
NA. Model functions callvalidate_water(water, c("ph", "doc", ...))to fail fast when a required slot is missing.
Function naming
Model functions follow treatmentapplied_modelapplied:
| Category | Examples |
|---|---|
| Chemical dosing |
chemdose_ph, chemdose_toc, chemdose_dbp, chemdose_chloramine
|
| Solving for a value |
solvedose_ph_alk, solvect_chlorine, solveresid_o3, solvemass
|
| Treatment process |
gac_toc, pac_toc, biofilter_toc, ozonate_bromate
|
| Corrosion / solubility |
dissolve_pb, dissolve_cu, calculate_corrosion
|
One file per function in R/, named after the function. Helper variants live in the same file as their base function.
The single-water / dataframe pair
Every exported model function has two forms, and both must exist:
-
foo(water, ...)— takes onewaterand returns onewater(or a numeric or data frame, for thesolve*functions). -
foo_df(df, input_water = ..., output_water = ..., ...)— takes a data frame with a list-column ofwaterobjects and returns that data frame with a new water column added.pluck_cols = TRUEalso spreads the relevant slots into ordinary columns;water_prefix = FALSEdrops the column-name prefix.
Arguments in _df functions default to "use_col", meaning “look for a column of this name in the data frame.” They also accept a literal value or an unquoted column name.
To write a new _df function, mirror the structure of an existing one — see R/chemdose_toc.R. In order, it should:
- Wrap each
"use_col"argument intryCatch(arg, error = function(e) enquo(arg))so unquoted column names don’t error. - Call
validate_water_helpers(df, input_water). - Call
construct_helper()to resolve argument sources into final column names. - Merge in any new columns, then call
handle_defaults()to fill defaults. -
lapplyover rows calling the single-water function, usingwithCallingHandlers()to collect warnings so a repeated warning is reported once with a row count viacli::cli_warn()— never emit one warning per row. - Drop the temporary default columns, and apply
pluck_water()whenpluck_colsisTRUE.
Shared infrastructure lives in R/general.R (validate_water, validate_water_helpers, validate_args, construct_helper, handle_defaults, convert_units, the calculate_alpha* speciation helpers) and in R/convert_pluck_water.R (pluck_water).
Deprecated patterns — do not write new ones
_chain and _once helpers were replaced by _df in 0.10.0. The shims in R/rename_helpers.R exist only for backward compatibility and call lifecycle::deprecate_warn(). Never add a new _chain or _once function, and use _df in all new examples, tests, vignettes, and documentation.
Commands
Run from the package root in R:
pak::local_install_dev_deps() # first-time setup
devtools::load_all() # load for interactive work
devtools::document() # regenerate man/ and NAMESPACE after roxygen edits
devtools::test() # run the testthat suite
testthat::test_file("tests/testthat/test-chemdose_toc.R") # single file
devtools::check() # full R CMD check — must pass before opening a PRGenerated files — never edit by hand: everything in man/ (the .Rd files), NAMESPACE, and data/*.rda. Edit the roxygen comments or the data-raw/ script and regenerate.
Style and conventions
- Tidyverse style guide. Formatting is enforced by Air (
air.toml): 120-character lines, 2-space indent, spaces not tabs. - Do not reformat code unrelated to your change.
- roxygen2 with markdown enabled. A model function’s documentation block should include
@title,@description(mentioning bothfooandfoo_df), a@paramfor every argument with its units stated,@sourcefor each reference,@seealso,@examples,@export, and@returnsdescribing both forms. - testthat 3rd edition. Every
R/file has a matchingtests/testthat/test-*.R. New models need tests covering: a zero / no-op dose, invalid arguments erroring, missing required slots erroring, out-of-range warnings, and at least one check of numeric output against a hand-calculated or published value. -
Slow tests must be skipped on CRAN. CRAN caps total check time, and tests here can be expensive —
_dfhelpers loop the model over every row, and the pH solver is iterative. Puttestthat::skip_on_cran()as the first line of anytest_that()block that is slow, and as a rule for every_dfhelper test. This is already the convention: roughly a third of the suite is skipped this way (seetests/testthat/test-balance_ions.Rfor the pattern). Keep the fast single-water tests running on CRAN so the package is still meaningfully checked there. - Default to
|and&in conditions. Use||or&&only when short-circuiting is actually needed, e.g.is.null(x) || is.na(x), where the right side would error or returnlogical(0)if evaluated. Reviewers find unneeded||/&&confusing, and it has been a recurring review comment. - R >= 4.1 is the floor, so the native
|>pipe is available;%>%is also re-exported and used throughout.
Numeric regression (golden) tests
tests/testthat/test-regression-*.R pin the current output of every exported model: every slot of every returned water, over a wide grid of scenario waters and options. They exist so refactors can’t silently change results. They are not validation. Reference checks against published values stay in the regular test-*.R files. Never edit those to make a change pass.
-
expect_golden(list(case = output, ...), "name")(intests/testthat/helper-regression.R) writes_snaps/regression-<topic>/<name>.txt, onecase :: output = valueline per value. Later runs compare each number with|new - old| <= abs_tol + rel_tol * |old|. Text andNAmust match exactly. - The default is
rel_tol = 1e-8. Loosen only where a solver limits precision, and say why in a comment. Current exceptions: CCPP andopensys_ph(unirootat its default tolerance,rel_tol = 1e-4), andchemdose_chloramine(ODE; differs ~1e-6 across platforms, sorel_tol = 1e-4,abs_tol = 1e-12M). -
regression_waters()returns the shared scenario waters; their own outputs are pinned intest-regression-define_water.R. -
test-regression-wrappers.Rchecks that every_dfhelper equals its base function row by row, and that the deprecated wrappers forward each argument to the parameter of the same name. - The regression files are kept out of the built package (
.Rbuildignore), soR CMD checkdoesn’t run them.R-CMD-check.yamlruns them in a separate step withtestthat::test_local(filter = "regression")on every OS, and uploads any changed.new.txtsnapshots when that step fails. Locally,devtools::test(filter = "regression"). - Every
test_that()block in a regression file starts withtestthat::skip_on_cran(). - On CI a missing snapshot is a failure, so commit new
.txtfiles. Snapshots are plain text because*.csvis gitignored.
When a golden test fails:
-
Refactor (no intended numeric change): the refactor changed the numbers. Fix the code. Never run
testthat::snapshot_accept()or edit_snaps/in a refactor PR. -
Intended numeric change: this is a breaking change (see guardrail 4). Review the diff with
testthat::snapshot_review(), then accept only the affected files. In the PR, list which goldens changed and why. -
New
waterslot: every whole-water golden gains a line per slot. Confirm the snapshot diff only adds lines for the new slot (no existing value changes) before accepting.
Known bugs are pinned as-is. A case that captures a filed bug carries a # KNOWN-BUG #<issue> comment, and a _knownbug<issue> name suffix where the case exists for that bug. When you fix the issue, accept the new values for those cases only, remove the tag, and confirm nothing else moved. grep "KNOWN-BUG #<n>" finds every test an issue touches. Issue #532 tracks open questions about model behavior that are pinned but unconfirmed.
New function or option: add cases to the matching test-regression-*.R. Pass whole water objects so every slot is pinned. Keep each golden under about 3000 lines and each file under about 30 s.
Performance — benchmark changes to core functions
A handful of functions sit on the hot path of every workflow: they are called once per row by every _df helper, and often several times per row when models are chained. A small slowdown in one of them multiplies across a user’s whole dataset.
Treat these as performance-sensitive:
-
define_water()(R/define_water.R) -
chemdose_ph()(R/chemdose_ph.R) -
solve_ph()(R/solve_ph.R) — iterative, usually the single largest cost - Everything in
R/general.R, especiallyvalidate_water(),validate_water_helpers(),validate_args(),construct_helper(),handle_defaults(),convert_units(),correct_k(),K_temp_adjust(), and thecalculate_alpha*()speciation helpers -
pluck_water()(R/convert_pluck_water.R)
Before opening a PR that touches any of them, benchmark before and after and put the numbers in the PR description. Measure the unchanged code first (check out the base commit or a separate worktree), then the change, on the same machine in the same session:
# representative workload: the model applied across many waters
df <- tidywater::water_df |>
define_water_df() |>
chemdose_ph_df(naoh = 10)
bench::mark(
define_water(ph = 7, temp = 25, alk = 100, toc = 3.7, doc = 3.5, uv254 = 0.1),
iterations = 200
)bench::mark() is preferred (it reports median time and allocations); system.time() over a loop is acceptable if bench isn’t available. profvis is useful for finding where the time actually went.
bench and profvis are deliberately not package dependencies. Install them in your own session and use them in one-off, throwaway code — never add them to DESCRIPTION, and never commit benchmark scripts to the package. Report the numbers in the PR description instead.
Guidance on results:
- A median-time regression above roughly 10% needs justification in the PR, or a fix.
- Watch memory allocations too, not just time — a change that copies the
waterobject per iteration can look fine on a small benchmark and fall apart at scale. - Correctness wins over speed. If a fix is necessarily slower, say so explicitly with the measured cost rather than quietly shipping it.
- Speed-ups are welcome, but the guardrails above still apply: an optimization that changes numeric output is a breaking change, not an optimization.
Pull requests
- Branch from
main. - Add a
NEWS.mdbullet at the top for any user-facing change, following the tidyverse NEWS style. The issue number and GitHub username are only needed for contributors outside the tidywater core team (Sierra Johnson @sierrajohnson, Libby McKenna @libbymckenna, Jiaming Yuan @jiamingy5). - The PR body should contain
Fixes #issue-number. - If the PR is entirely agent-generated, say so at the top of the description, not the bottom.
- Follow AI_POLICY.md: state how AI was used and which part of its section 3 (a, b, or c) the change falls under.
- Keep PR descriptions brief. Mention each issue or PR number only once.
- For minor changes, test results don’t need to be reported in the PR description.
- Don’t run the full test suite locally; CI runs it. Run tests only for the files you touch, e.g.
devtools::test(filter = "ozonate_bromate"). -
CI fails on NOTEs, not just errors and warnings —
R-CMD-check.yamlsetserror-on: '"note"'. Undocumented arguments, mismatched usage sections, and non-standard files in the package root will all fail the build. Update.Rbuildignorewhen adding a top-level file. - CI also runs gitleaks, pkgdown, and test-coverage workflows.
- Include before/after benchmark numbers if the change touches a core function (see Performance).
Ask a human before
- Anything that changes a model’s numeric output, including accepting changed golden snapshots.
- Adding or removing a
waterslot — it affects every function and all stored data. - Adding a new package dependency.
- Changing default argument values on exported functions.
- Deprecating or renaming an exported function.
