Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# CLAUDE_PEER_REVIEW - PL-0500 per-pack sustainability figures - V02 (re-review of V01 fixes)

Reviewer: Claude Code independent peer reviewer (subagent), 2026-12-04. Read-only review; did not author the code.
Source: origin/main 89ccec8a. Fix commit b0089c20 (in PR #77, merge b5859149).
Scope: TASKS.md PL-0500 only (pack-to-product ratio, material mass split, declared recycled content). Recyclability class out of scope.

Verdict: PASS_WITH_FIXES (code). Task stays [ ] (no consumer; see Integration).

Evidence (reviewer-run): pytest tests/core/test_pack_sustainability.py tests/core/test_erp_contract.py: 73 passed. GitHub Actions on b0089c20: Python Quality and Signing Guard success. 12 mutations: 11 killed, 1 survived (pct lower bound 0.0 <=).

V01 findings: V01-1 enum normalisation FIXED (lines 68-75); V01-2 product_contact bool FIXED (line 66); V01-3 non-str id/name FIXED (lines 63-65); V01-4 NITs accepted documented limits.

New findings:
1. LOW lines 76, 81, 110: non-number mass/pct/product mass -> TypeError, not PackSustainabilityError (fails closed; breaks error contract).
2. LOW same lines: bool accepted as mass/percentage (silent wrong figure).
3. LOW test gap: negative recycled_content_pct untested (surviving mutation).
4. NIT line 108: component_id not stripped for duplicate check.
5. NIT lines 56-58: optional text fields not type-checked (fails closed in json.dumps).

Integration: no app/server consumer; key mismatch with erp_contract.py:272-286 and no adapter; passing declared-mass % straight through would overstate pack recycled content when coverage < 100 %. Keep PL-0500 [ ] until a consumer and coverage-aware mapping exist.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# CLAUDE_PEER_REVIEW - PL-0500 per-pack sustainability figures - V03 (re-review of V02 fixes, PR #115)

Reviewer: Claude Code independent peer reviewer (subagent), 2026-12-04. Read-only review; did not author the code.
Source: PR #115 head ebaebc46 (branch feat/pl-0500-v02-fixes), base origin/main 89ccec8a.
Scope: TASKS.md PL-0500 only (pack-to-product ratio, material mass split, declared recycled content). Recyclability class out of scope.

Verdict: PASS (code). CI NOT_VERIFIED at review time (Locked Python quality IN_PROGRESS; signing-material scan SUCCESS). Task stays [ ] unless coordinator accepts closure without a consumer (no producer of erp_spec holds component declarations).

Evidence (reviewer-run): pytest tests/core/test_pack_sustainability.py tests/core/test_erp_contract.py: 82 passed. mypy --no-incremental core apps server tools: no issues (352 files). ruff check core apps server tools tests: clean; ruff format on committed contents of changed files: clean. New tests vs base module: collection fails (no erp_sustainability); with a mass-only stub 8 failed / 15 passed (-1.0 pct passes on base, by design: closes V02 survivor). 12/12 targeted mutations killed (incl. V02 survivor pct lower bound, strip, all-declared -> rounded coverage/any/True, contract and DECLARED guards). spec_content output validated with jsonschema against povu-contract.schema.json sustainability subschema.

V02 findings: 1 FIXED (_is_number, lines 25-26, 80, 85, 114); 2 FIXED (bool rejected); 3 FIXED (negative pct test); 4 FIXED (line 112); 5 accepted NIT. Integration: coverage-aware mapping erp_sustainability (lines 158-175) added; keys/units/rounding match erp_contract.py:272-288 and schema; recycled % emitted only when every component declares (then equals pack-mass-weighted %). No consumer: correctly reported.

New findings:
1. LOW lines 165-174: provenance only by contract string; tampered figures accepted, revision_id not re-verified; malformed dicts raise KeyError not PackSustainabilityError.
2. LOW lines 133/169: pack_mass_g rounded to 3 dp; a sub-0.5 mg pack maps to mass_per_pack "0" g.
3. NIT line 172: assert used for narrowing, stripped under -O; only exception type changes, unreachable from real figures.
4. NIT lines 90/117: ids stripped only for the duplicate check; output/revision keep raw whitespace.
5. NIT integration: no check that packaging_item/empty_weight describe the same pack as mass_per_pack (future consumer's job).

Coordinator decision: merge on green CI; LOW 1-2 deferred to the future consumer (release producer), PL-0500 stays [ ].
33 changes: 29 additions & 4 deletions core/src/packlab_core/pack_sustainability.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ class PackSustainabilityError(ValueError):
pass


def _is_number(value: object) -> bool:
return not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value)


class MaterialFamily(StrEnum):
HDPE = "HDPE"
LDPE = "LDPE"
Expand Down Expand Up @@ -73,12 +77,12 @@ def __post_init__(self) -> None:
object.__setattr__(self, "mass_source", MassSource(self.mass_source))
except ValueError as exc:
raise PackSustainabilityError("unknown_mass_source") from exc
if not (math.isfinite(self.mass_g) and self.mass_g > 0.0):
if not (_is_number(self.mass_g) and self.mass_g > 0.0):
raise PackSustainabilityError("mass_must_be_positive")
if type(self.units_per_pack) is not int or self.units_per_pack < 1:
raise PackSustainabilityError("units_per_pack_must_be_positive")
pct = self.recycled_content_pct
if pct is not None and not (math.isfinite(pct) and 0.0 <= pct <= 100.0):
if pct is not None and not (_is_number(pct) and 0.0 <= pct <= 100.0):
raise PackSustainabilityError("recycled_content_out_of_range")

def as_dict(self) -> dict[str, object]:
Expand All @@ -105,9 +109,9 @@ def pack_sustainability(
"""Figures for one sales pack holding ``product_net_mass_g`` of product."""
if not components:
raise PackSustainabilityError("components_required")
if len({c.component_id for c in components}) != len(components):
if len({c.component_id.strip() for c in components}) != len(components):
raise PackSustainabilityError("duplicate_component_id")
if not (math.isfinite(product_net_mass_g) and product_net_mass_g > 0.0):
if not (_is_number(product_net_mass_g) and product_net_mass_g > 0.0):
raise PackSustainabilityError("product_mass_must_be_positive")

masses = {c.component_id: c.mass_g * c.units_per_pack for c in components}
Expand Down Expand Up @@ -151,11 +155,32 @@ def pack_sustainability(
return result


def erp_sustainability(figures: dict[str, object]) -> dict[str, object]:
"""The ``sustainability`` argument of ``erp_contract.spec_content`` from these figures.

Recycled content goes out only when every gram of the pack is declared: the declared-mass
percentage would overstate the pack when undeclared components exist, so it is then omitted
(the contract key is optional). Estimated masses are refused; a release is not an estimate.
"""
if figures.get("contract") != PACK_SUSTAINABILITY_CONTRACT:
raise PackSustainabilityError("not_pack_sustainability_figures")
if figures["figure_status"] != "DECLARED":
raise PackSustainabilityError("estimated_mass_not_releasable")
out: dict[str, object] = {"mass_per_pack_g": figures["pack_mass_g"]}
# Every component, not the rounded coverage figure: 99.996 % would round to 100.
components = figures["components"]
assert isinstance(components, list)
if all(c["recycled_content_pct"] is not None for c in components):
out["recycled_content_percent"] = figures["recycled_content_pct_of_declared_mass"]
return out


__all__ = [
"PACK_SUSTAINABILITY_CONTRACT",
"MassSource",
"MaterialFamily",
"PackComponent",
"PackSustainabilityError",
"erp_sustainability",
"pack_sustainability",
]
57 changes: 57 additions & 0 deletions tests/core/test_pack_sustainability.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import pytest

from packlab_core.erp_contract import SpecDimension, spec_content
from packlab_core.pack_sustainability import (
MassSource,
MaterialFamily,
PackComponent,
PackSustainabilityError,
erp_sustainability,
pack_sustainability,
)

Expand Down Expand Up @@ -80,6 +82,12 @@ def test_units_per_pack_multiply_and_revision_is_stable() -> None:
{"mass_g": 0.0},
{"mass_g": float("inf")},
{"recycled_content_pct": 101.0},
{"recycled_content_pct": -1.0},
{"recycled_content_pct": "30"},
{"recycled_content_pct": True},
{"mass_g": "1.0"},
{"mass_g": True},
{"mass_g": None},
{"units_per_pack": 0},
{"component_id": " "},
{"material_family": "UNOBTAINIUM"},
Expand Down Expand Up @@ -109,6 +117,55 @@ def test_pack_level_refusals() -> None:
pack_sustainability(_bottle_pack(), 0.0)
with pytest.raises(PackSustainabilityError):
pack_sustainability(_bottle_pack() + _bottle_pack()[:1], 1.0)
for product_mass in ("1000", True, None):
with pytest.raises(PackSustainabilityError):
pack_sustainability(_bottle_pack(), product_mass) # type: ignore[arg-type]
spaced = PackComponent(" cap ", "cap", MaterialFamily.PP, 1.0, MassSource.WEIGHED, True)
with pytest.raises(PackSustainabilityError, match="duplicate_component_id"):
pack_sustainability([*_bottle_pack(), spaced], 1.0)


def _spec_sustainability(mapped: dict[str, object]) -> object:
content = spec_content(
company_id="00000000-0000-4000-8000-000000000001",
packaging_item={"id": "00000000-0000-4000-8000-000000000004", "code": "PK-BOTTLE"},
asset_id="bottle_1l",
revision_id="bottle:" + "a" * 64,
packlab_family="CARTON",
dimensions=[SpecDimension("height", 200.0, "measured", "metric_verified", 0.5, 0.5)],
sustainability=mapped,
)
return content["sustainability"]


def test_erp_mapping_omits_recycled_content_below_full_coverage() -> None:
# cap undeclared: 28.64 % of declared mass must not go out as the pack's recycled content
mapped = erp_sustainability(pack_sustainability(_bottle_pack(), 1000.0))
assert mapped == {"mass_per_pack_g": 48.0}
assert _spec_sustainability(mapped) == {"mass_per_pack": {"value": "48", "unit": "g"}}


def test_erp_mapping_passes_recycled_content_at_full_coverage() -> None:
pack = _bottle_pack()
pack[1] = PackComponent(
"cap", "cap", MaterialFamily.PP, 4.0, MassSource.WEIGHED, True, recycled_content_pct=0.0
)
mapped = erp_sustainability(pack_sustainability(pack, 1000.0))
assert mapped == {"mass_per_pack_g": 48.0, "recycled_content_percent": 26.25} # 12.6 / 48
block = _spec_sustainability(mapped)
assert isinstance(block, dict) and block["recycled_content_percent"] == "26.25"
# an undeclared 1 mg part rounds coverage to 100.0 but is still undeclared
speck = PackComponent("speck", "liner", MaterialFamily.PP, 0.001, MassSource.WEIGHED, False)
figures = pack_sustainability([*pack, speck], 1000.0)
assert figures["recycled_content_declaration_coverage_pct"] == 100.0
assert "recycled_content_percent" not in erp_sustainability(figures)


def test_erp_mapping_refuses_estimates_and_foreign_dicts() -> None:
with pytest.raises(PackSustainabilityError, match="estimated_mass_not_releasable"):
erp_sustainability(pack_sustainability(_bottle_pack(MassSource.ESTIMATED), 1000.0))
with pytest.raises(PackSustainabilityError, match="not_pack_sustainability_figures"):
erp_sustainability({"pack_mass_g": 1.0})


def test_plain_strings_are_converted_to_the_enums() -> None:
Expand Down