8000 fix: contract remediation (README, name collision, speed, opt-in ammonium, total-N target) by rafatahmed · Pull Request #292 · rafatahmed/Flahax · GitHub
[go: up one dir, main page]

Skip to content

fix: contract remediation (README, name collision, speed, opt-in ammonium, total-N target) - #292

Merged
rafatahmed merged 13 commits into
mainfrom
fix/contract-remediation
Nov 25, 2026
Merged

rafatahmed merged 13 commits into
mainfrom
fix/contract-remediation

Conversation

@rafatahmed
Copy link
Copy Markdown
Owner

Closes #287. Closes #288. Closes #289. Closes #290. Closes #291.

Contract remediation after the 0.7.0 release audit.

Not done here: D3-D7 of the audit list, and the PHREEQC golden fixture was not re-captured.

Local checks: ruff clean; 189 of 202 test modules pass locally. Heavy ratio, pH-input and mix tests did not finish under the 5-minute limit, so CI is the verifier for them.

The troubleshooting table cited `charge_imbalance_exceeded`, which was
removed in 0.7.0 (G10/G11) and appears nowhere in src/, and `invalid_json`,
which is not in the manual's error code reference that the row links to.
Cite `invalid_value` and `invalid_type`, both listed in that reference.
Addresses local audit finding P2. Preserve distinct product calculations and report both conflicting product IDs.

(cherry picked from commit be89459f9d0b862b8860baccdc5a76e1e102b761)
Preserve the existing ID-based fitting control without changing its frozen inputs; reject ambiguous names before workflow dose resolution.

(cherry picked from commit fcf86441775e470dbc2012e7285c0ed874bf9249)
(cherry picked from commit 372e81f08e31fd3c585f6da7138e3dbde3ecb196)
P2 accounting: settled iterations retained assumed-dose nutrient rows while emitting the calculated reagent dose. Rebuild final nutrient assessments from fixed emitted quantities without changing solver tolerances or chemistry.

(cherry picked from commit 40a86d6f98cf21a9bf269e46a2bd49d00b11bf97)
(cherry picked from commit 5154c4386941acbaef52d595f2ccadaa85677c84)
…e an hour

The discovered unit suite took 3,767 s (62.8 min). Profiling and stack sampling
traced the time to three defects, each a repeated computation of a value that
had already been computed. None changes a result.

1. The packaged catalogue was parsed once per product lookup.
   engine.load_library() reads and parses the 41 KB library.json on every call.
   product_conversion.catalogue_dose_contributions() and materials._shipped_salt()
   called it for every lookup, and the optimiser's inner loops reach them through
   engine._nutrients -> material_inventory: 11,988 parses in one batch.
   Add engine.catalogue_salts_by_name(), an index built once per loader and
   used by materials.py and both product_conversion.py sites. It is keyed on
   the loader function, not the module, so tests that substitute a historical
   catalogue by replacing load_library (tests/catalogue_history.py) still get
   their own index. Unknown and unhashable names still raise unknown_product.

2. The pH sensitivity matrix was built densely from mostly zero terms.
   joint_sensitivity.equilibrium_charge_gradient summed, for every component and
   column, a Fraction product over every species, although a species touches few
   components and most partial derivatives are exactly zero: about 2.2 million
   exact multiplications per call and over half the run time of a batch.
   Accumulate the matrix, the charge row and the sums from non-zero terms only.
   The arithmetic is exact rational, so omitting zero terms and summing in a
   different order cannot change a value.

3. The joint search solved the same cold equilibrium repeatedly.
   When an iteration stalls, solve_joint_problem tries coordinate and cap-tangent
   exchanges; many clamp to the same point. 9,073 of 12,339 evaluations in the
   slowest test were exact repeats, all cold and therefore deterministic.
   Keep each cold outcome (the state, or the code that rejected the point) for
   the life of one search, bounded at 8,192 points. Warm-start evaluations depend
   on their seed and are never kept. A cold=True request is finish()'s deliberate
   fresh recheck and is never answered from memory; a first version that did so
   failed three tests, which is how that contract was found. The evaluations,
   rejectedTrials and lastError counters still count every request.

Evidence
- 124 gradients from three real formulas are bit-identical before and after.
- resolve_material output for all 29 catalogue products is byte-identical.
- The complete solve_joint_problem result, diagnostics included, is byte-identical
  on four real batches and on the 250 s scenario (52,457 bytes).
- tests/test_solver_hot_paths.py adds 8 tests: catalogue loads counted once,
  loader-keyed substitution, linear-scan equivalence, unknown and unhashable
  names, gradient values pinned from the dense implementation, and a search run
  with and without the memory that must give the same result and must repeat
  points when the memory is off. The guards were mutation-checked.
- Full suite, quiet machine, Python 3.14: 1,434 tests, OK, 20 skipped, 1,418 s.
  A Cucumber batch takes about 4 s instead of 28 s.
- ruff 0.8.4 check and format are clean; every changed line and branch is
  covered by the new and existing joint tests under coverage 7.17.0.

Not changed: some joint searches still end iteration_budget_exhausted and
search_incomplete after exhausting their budget. Fixing that alters the
optimiser's behaviour and is left for a separate decision.

(cherry picked from commit c62e4cffa2fc479135a97c953ac07cb3976e567c)
Records the P2 accounting and collision acceptance, the three repeated
computations behind the 63-minute unit suite, the CI checks run locally and
what is not verified. Local filesystem paths are removed, and a note records
that the later reconciliation finds the single-cause claim for the 65 coverage
run failures too strong.
An absent or zero N_NH4 target is no requirement and, by default, no
maximum, as the capability contract states for omitted targets (Q8, Q9).
`recommend` and `solve_weights` now default `max_ammonium_fraction` to
None; passing a fraction (0.10 is the documented Dutch soilless practice
value) selects the allowance, `ammoniumLimit` reports it with its basis,
and a declared N_NH4 maximum still replaces it. `ammonium_allowance_preset`
returns the disclosed record without applying it. Incidental ammonium
without a maximum is reported for review like any other untargeted
nutrient.

Tests that asserted the default allowance now assert the new default and
the selected preset; none is weakened. The glossary, user guide, API
reference and site pages describe the preset as optional.
…nct product names

The default recipe no longer carries an ammonium maximum (D1), so the grower,
materials and nitrogen-form tests that encoded the 10 % allowance now assert the
reported, reviewed NH4-N instead. The remedy-search fixture clones a product under
a distinct name, since an ambiguous product name is rejected before dose
resolution.
…(D2)

Total N ('N', mg/L as N) is a target in recommend, solve_weights and the workflows.
Alone it is one row over the sum of nitrate, ammonium and urea and imposes no form
split; the urea safeguard still keeps urea products out unless urea is declared.
With all three forms the forms are scored once and the declared total must agree
with their sum; with some forms both are scored and totalN.overlapForms discloses
the overlap. A total that disagrees with, or is below, the declared forms raises
InputError b
8000
efore any fitting. N stays rejected in water, maxima and assays.
The optional ammonium allowance uses the declared total.
@rafatahmed rafatahmed added the bug Something isn't working label Nov 25, 2026
@rafatahmed rafatahmed self-assigned this Nov 25, 2026
@read-the-docs-community
read-the-docs-community Bot commented Nov 25, 2026 •
Copy link
Copy Markdown

@codecov
codecov Bot commented Nov 25, 2026
Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (35eefb7) to head (e42223b).

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #292   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          140       140           
  Lines        16922     17015   +93     
  Branches      3433      3455   +22     
=========================================
+ Hits         16922     17015   +93     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rafatahmed
rafatahmed marked this pull request as ready for review November 25, 2026 03:43
@rafatahmed
rafatahmed merged commit 76ceda1 into main Nov 25, 2026
29 checks passed
@rafatahmed
rafatahmed deleted the fix/contract-remediation branch November 25, 2026 03:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
0