hospitality.allergen-matrix
Which of the 14 UK major allergens a dish contains or may contain, from its ingredients' declared allergens.
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 16 tests, run in TypeScript, Python and Rust.
Not professional advice. This capability calculates food-safety figures from published rules. It is a software component for developers, not food-safety advice. Rules change and every rate here has an effective date. Check that the dates cover your case. Verify results against the official sources listed in its README, and have a food safety officer (EHO) review how you use it, before anyone relies on the output. Provided “as is” under its licence, without warranty.
What it does
Status: needs review by a food-safety professional before it is published; it summarises declared data, it does not detect allergens.
Given each ingredient of a dish and the allergens its supplier declares, this returns one row for each of the 14 regulated allergens, in legal order: `contains`, `may-contain` or `none`, and which ingredients are the source. That is one row of the allergen matrix a kitchen keeps for every dish.
For example
allergen_matrix(ingredients ×4, GB, 2026-09-23)→ ×14 margherita: gluten and milk contained, sesame and soya only may beallergen_matrix(ingredients ×2, GB, 2026-09-23)→ ×14 contains beats may-contain, and only the containing ingredient is a sourceallergen_matrix(ingredients ×3, GB, 2026-09-23)→ ×14 several ingredients can be the source of one allergen
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
pub fn allergen_matrix(ingredients: &[IngredientAllergens], jurisdiction: &str, on_date: &str) -> Vec<AllergenRow>
| ingredients | IngredientAllergens[] | every ingredient of the dish, with the allergens its supplier declares |
| jurisdiction | string | GB |
| on_date | date | the date the dish is served, which decides the list in force |
| returns | AllergenRow[] | one row per regulated allergen, in the legal order |
The types it declares, generated into your project
/// One ingredient and what its specification or label declares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IngredientAllergens {
pub name: String,
/// allergen codes the ingredient contains
pub contains: Vec<String>,
/// codes of precautionary "may contain" statements
pub may_contain: Vec<String>,
}
// AllergenStatus is a string in Rust, one of: "contains", "may-contain", "none".
// Parameters take it as &str and results hold it as String.
/// One allergen and whether the dish has it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AllergenRow {
pub code: String,
pub name: String,
/// contains beats may-contain
pub status: String,
/// the ingredients responsible, in the order given
pub sources: Vec<String>,
}
Your code names it in one line, in the file that uses it
fune!(hospitality.allergen-matrix@^1); // then call allergen_matrix(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::dates_add_days::add_days; ← from dates.add-days ^1.0.0 · built alongside by fune
use super::hospitality_allergen_matrix_data::{Allergen, ALLERGENS, ALLERGENS_HISTORY}; ← this capability’s own data, compiled from data/allergens.json into the same file by fune build
fn list_in_force(jurisdiction: &str, on_date: &str) -> Vec<&'static Allergen> {
let mut rows: Vec<&'static Allergen> = ALLERGENS
.iter()
.filter(|a| {
a.jurisdiction == jurisdiction && a.valid_from <= on_date && a.valid_to.map_or(true, |to| on_date <= to)
})
.collect();
if !rows.is_empty() {
rows.sort_by_key(|a| a.annex_number);
return rows;
}
// A history-pruned build may have dropped the list that applied then; say so
// rather than answering with nothing.
if ALLERGENS_HISTORY != "full" {
let earliest = ALLERGENS.iter().filter(|a| a.jurisdiction == jurisdiction).map(|a| a.valid_from).min();
if let Some(earliest) = earliest {
if on_date < earliest {
panic!(
"no allergen list for {} on {}: this build was installed with history={}, so it only carries lists from {}",
jurisdiction, on_date, ALLERGENS_HISTORY, earliest
);
}
}
}
panic!("no allergen list for {} on {}", jurisdiction, on_date)
}
fn dedupe(names: Vec<String>) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
for name in names {
if !seen.contains(&name) {
seen.push(name);
}
}
seen
}
/// The regulated allergens in a dish, from what its ingredients declare.
///
/// Every allergen on the list gets a row, in the legal order, so a menu or
/// allergen chart shows "none" as a decision rather than a gap. An allergen any
/// ingredient contains is "contains"; otherwise one any ingredient may contain
/// is "may-contain". The sources say which ingredients to check.
///
/// # Panics
/// Panics on a bad date, no list for the jurisdiction and date, or an
/// allergen code that is not on the list.
pub fn allergen_matrix(ingredients: &[IngredientAllergens], jurisdiction: &str, on_date: &str) -> Vec<AllergenRow> {
add_days(on_date, 0);
let list = list_in_force(jurisdiction, on_date);
for ingredient in ingredients {
for code in ingredient.contains.iter().chain(ingredient.may_contain.iter()) {
if !list.iter().any(|a| a.code == code.as_str()) {
panic!(
"unknown allergen \"{}\" in \"{}\": not on the {} list on {}",
code, ingredient.name, jurisdiction, on_date
);
}
}
}
list.iter()
.map(|allergen| {
let contains: Vec<String> = ingredients
.iter()
.filter(|i| i.contains.iter().any(|c| c == allergen.code))
.map(|i| i.name.clone())
.collect();
let may: Vec<String> = ingredients
.iter()
.filter(|i| i.may_contain.iter().any(|c| c == allergen.code))
.map(|i| i.name.clone())
.collect();
let status = if !contains.is_empty() {
"contains"
} else if !may.is_empty() {
"may-contain"
} else {
"none"
};
AllergenRow {
code: allergen.code.to_string(),
name: allergen.name.to_string(),
status: status.to_string(),
sources: dedupe(if contains.is_empty() { may } else { contains }),
}
})
.collect()
}
fn strings(v: &Value) -> Vec<String> {
v.as_arr().iter().map(|s| s.as_str().to_string()).collect()
}
pub fn ingredient_allergens_from_value(v: &Value) -> IngredientAllergens {
IngredientAllergens {
name: v.get("name").as_str().to_string(),
contains: strings(v.get("contains")),
may_contain: strings(v.get("mayContain")),
}
}
pub fn allergen_row_to_value(r: &AllergenRow) -> Value {
Value::obj(vec![
("code", Value::str(&r.code)),
("name", Value::str(&r.name)),
("status", Value::str(&r.status)),
("sources", Value::Arr(r.sources.iter().map(|s| Value::str(s)).collect())),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let ingredients: Vec<IngredientAllergens> = args[0].as_arr().iter().map(ingredient_allergens_from_value).collect();
Value::Arr(
allergen_matrix(&ingredients, args[1].as_str(), args[2].as_str())
.iter()
.map(allergen_row_to_value)
.collect(),
)
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add hospitality.allergen-matrix
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./hospitality.allergen-matrix-1.0.0-rust.fune, or fetch it from a terminal with fune pull hospitality.allergen-matrix@1.0.0:rust.
The whole function, every language, is one file too: hospitality.allergen-matrix-1.0.0.fune, 40,318 bytes, sha256 66a9509d8ec6a3e6966493ac91fb7ecc9534558d01df6e9be9a11cca92e7ba7c. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before hospitality.allergen-matrix
after — your function gets the result and the arguments, and returns the final result.
// fune: after hospitality.allergen-matrix
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace dates.add-days in hospitality.allergen-matrix
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show hospitality.allergen-matrix --steps.
// fune: step hospitality.allergen-matrix after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| margherita: gluten and milk contained, sesame and soya only may be | ingredients ×4, GB, 2026-09-23 | → | ×14 |
| contains beats may-contain, and only the containing ingredient is a source | ingredients ×2, GB, 2026-09-23 | → | ×14 |
| several ingredients can be the source of one allergen | ingredients ×3, GB, 2026-09-23 | → | ×14 |
| may-contain from two ingredients lists both | ingredients ×2, GB, 2026-09-23 | → | ×14 |
| an ingredient listing an allergen twice is one source | ingredients ×1, GB, 2026-09-23 | → | ×14 |
| the same ingredient name twice is one source | ingredients ×2, GB, 2026-09-23 | → | ×14 |
| all fourteen in one dish, in the legal order | ingredients ×1, GB, 2026-09-23 | → | ×14 |
| shellfish: crustaceans and molluscs are separate allergens | ingredients ×3, GB, 2026-09-23 | → | ×14 |
| a dish with no declared allergens still lists all fourteen as none | ingredients ×2, GB, 2026-09-23 | → | ×14 |
| no ingredients at all | , GB, 2026-09-23 | → | ×14 |
Show the other 6 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the first day the list applied | ingredients ×1, GB, 2014-12-13 | → | ×14 |
| a code that is not on the list is an error, not ignored | ingredients ×1, GB, 2026-09-23 | → | error: unknown allergen "tree-nuts" in "walnut cake" |
| an unknown may-contain code is an error too | ingredients ×1, GB, 2026-09-23 | → | error: unknown allergen "gluten free" |
| before the regulation applied there is no list | , GB, 2014-12-12 | → | error: no allergen list for GB on 2014-12-12 |
| a jurisdiction with no data is an error | , FR, 2026-09-23 | → | error: no allergen list for FR on 2026-09-23 |
| an impossible date is an error | , GB, 2026-02-30 | → | error: is not a real calendar date |
More from the author
## How the status is decided
- **contains**: at least one ingredient declares it. The sources are those ingredients only. - **may-contain**: no ingredient contains it, but at least one carries a precautionary "may contain" statement for it. That is a cross-contamination warning from the supplier, not an ingredient, and it is kept separate so the menu can say so rather than claim the allergen is an ingredient or leave it out. - **none**: nothing declared. Every allergen gets a row, so "none" is shown as a checked answer, not left out.
Sources keep the order the ingredients were given, without duplicates.
## Codes
`gluten`, `crustaceans`, `eggs`, `fish`, `peanuts`, `soybeans`, `milk`, `nuts`, `celery`, `mustard`, `sesame`, `sulphites`, `lupin`, `molluscs`. An unknown code (`tree-nuts`, `gluten free`) is an error rather than being ignored, because an allergen dropped by a typo is the failure that hurts someone.
## What it does not do
- It does **not** detect allergens. It trusts the declarations it is given, and an ingredient whose specification is missing or out of date gives a wrong answer. Keep specifications current, and re-run the matrix when a supplier or recipe changes. - It does not name the specific cereal or nut. The law requires "wheat", "almonds" and so on, not just "cereals containing gluten" or "nuts". Carry that detail in the ingredient name. - Sulphites only count above 10 mg/kg or 10 mg/litre (as SO2). Whether an ingredient crosses that threshold is for its declaration to say. - It says nothing about cross-contact in your own kitchen, which the FSA expects a business to manage and communicate separately.
## The list is data
The 14 are dated rows in `data/allergens.json`, keyed by jurisdiction, and the function takes the date the food is served. If the list changes, that is a data release, not a code change. The rows apply from 13 December 2014, when Regulation (EU) No 1169/2011 (FIC) began to apply. Lupin and molluscs were already on the earlier list, added by Directive 2006/142/EC. A date before then, or a jurisdiction with no rows, is an error.
`GB` covers England, Scotland and Wales under the retained regulation. Northern Ireland applies the EU regulation directly and has the same 14 today, but it is not in this data.
## Sources
- Regulation (EU) No 1169/2011 on the provision of food information to consumers, Annex II, *Substances or products causing allergies or intolerances*, as retained in GB law: https://www.legislation.gov.uk/eur/2011/1169/annex/II - The Food Information Regulations 2014 (SI 2014/1855), which enforce it in England. Regulation 5 covers allergen information for food that is not prepacked, and regulation 5A covers food prepacked for direct sale ("Natasha's Law", from 1 October 2021): https://www.legislation.gov.uk/uksi/2014/1855/contents . Scotland, Wales and Northern Ireland have parallel regulations. Note that the list of 14 itself is in Annex II of the EU regulation, not in a Schedule of the 2014 Regulations. - Food Standards Agency, *Allergen guidance for food businesses*: https://www.food.gov.uk/business-guidance/allergen-guidance-for-food-businesses
Files
| Path | Bytes |
|---|---|
| README.md | 3,670 |
| data/allergens.json | 3,435 |
| impl/python.py | 2,958 |
| impl/rust.rs | 4,577 |
| impl/typescript.ts | 2,733 |
| vectors.json | 15,769 |