Functional Weave
Code in Python

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 be
  • allergen_matrix(ingredients ×2, GB, 2026-09-23) → ×14 contains beats may-contain, and only the containing ingredient is a source
  • allergen_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.

def allergen_matrix(ingredients: Sequence[IngredientAllergens], jurisdiction: str, on_date: str) -> List[AllergenRow]
ingredientsIngredientAllergens[]every ingredient of the dish, with the allergens its supplier declares
jurisdictionstringGB
on_datedatethe date the dish is served, which decides the list in force
returnsAllergenRow[]one row per regulated allergen, in the legal order

The types it declares, generated into your project

@dataclass(frozen=True)
class IngredientAllergens:
    """One ingredient and what its specification or label declares."""

    name: str
    #: allergen codes the ingredient contains
    contains: List[str]
    #: codes of precautionary "may contain" statements
    may_contain: List[str]

AllergenStatus = Literal["contains", "may-contain", "none"]

@dataclass(frozen=True)
class AllergenRow:
    """One allergen and whether the dish has it."""

    code: str
    name: str
    #: contains beats may-contain
    status: AllergenStatus
    #: the ingredients responsible, in the order given
    sources: List[str]

Your code names it in one line, in the file that uses it

from fune.hospitality.allergen_matrix import allergen_matrix  # hospitality.allergen-matrix@^1
impl/python.py · 68 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, Optional, Sequence

from .dates_add_days import add_days  ← from dates.add-days ^1.0.0 · built alongside by fune
from .hospitality_allergen_matrix_data import ALLERGENS, ALLERGENS_HISTORY, Allergen  ← this capability’s own data, compiled from data/allergens.json into the same file by fune build
from .hospitality_allergen_matrix_types import AllergenRow, IngredientAllergens


def _list_in_force(jurisdiction: str, on_date: str) -> List[Allergen]:
    rows = [
        a
        for a in ALLERGENS
        if a.jurisdiction == jurisdiction and a.valid_from <= on_date and (a.valid_to is None or on_date <= a.valid_to)
    ]
    if rows:
        return sorted(rows, key=lambda a: a.annex_number)
    # A history-pruned build may have dropped the list that applied then; say so
    # rather than answering with nothing.
    if ALLERGENS_HISTORY != "full":
        earliest: Optional[str] = None
        for a in ALLERGENS:
            if a.jurisdiction == jurisdiction and (earliest is None or a.valid_from < earliest):
                earliest = a.valid_from
        if earliest is not None and on_date < earliest:
            raise ValueError(
                "no allergen list for %s on %s: this build was installed with history=%s, so it only carries lists from %s"
                % (jurisdiction, on_date, ALLERGENS_HISTORY, earliest)
            )
    raise ValueError("no allergen list for %s on %s" % (jurisdiction, on_date))


def _dedupe(names: List[str]) -> List[str]:
    seen: List[str] = []
    for name in names:
        if name not in seen:
            seen.append(name)
    return seen


def allergen_matrix(ingredients: Sequence[IngredientAllergens], jurisdiction: str, on_date: str) -> List[AllergenRow]:
    """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.
    """
    add_days(on_date, 0)
    allergens = _list_in_force(jurisdiction, on_date)
    known = {a.code for a in allergens}
    for ingredient in ingredients:
        for code in list(ingredient.contains) + list(ingredient.may_contain):
            if code not in known:
                raise ValueError(
                    'unknown allergen "%s" in "%s": not on the %s list on %s' % (code, ingredient.name, jurisdiction, on_date)
                )
    rows: List[AllergenRow] = []
    for allergen in allergens:
        contains = [i.name for i in ingredients if allergen.code in i.contains]
        may = [i.name for i in ingredients if allergen.code in i.may_contain]
        rows.append(
            AllergenRow(
                code=allergen.code,
                name=allergen.name,
                status="contains" if contains else "may-contain" if may else "none",
                sources=_dedupe(contains if contains else may),
            )
        )
    return rows

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Python 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. Or pin a range in fune.project and build in one step:

fune add hospitality.allergen-matrix
Download for Python hospitality.allergen-matrix-1.0.0-python.fune · 32,733 bytes sha256 5a4669c0e42277aa4bc21687bc3d366099b2a8325a9abac16eefeff5f8030f38

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./hospitality.allergen-matrix-1.0.0-python.fune, or fetch it from a terminal with fune pull hospitality.allergen-matrix@1.0.0:python.

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.

CaseArgumentsExpected
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
CaseArgumentsExpected
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

PathBytes
README.md3,670
data/allergens.json3,435
impl/python.py2,958
impl/rust.rs4,577
impl/typescript.ts2,733
vectors.json15,769