Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(examples): add an EPCIS 2.0 product passport sample (#2128)
Abdelhadi Salmaoui05dc7cce25b1
diff --git a/examples/epcis/README.md b/examples/epcis/README.mdnew file mode 100644index 00000000..ed8f89d2--- /dev/null+++ b/examples/epcis/README.md@@ -0,0 +1,99 @@+# EPCIS 2.0 — product passport chain++A runnable walk down one product's history: eight EPCIS events go in, a product+passport comes out as RDF. Offline, from a clean checkout, in one command.++```bash+python examples/epcis/walk_chain.py+```++```+Product passport for urn:epc:id:sgtin:0614141.107346.2026+ 1. 2026-09-02T08:12:00.000+02:00 ObjectEvent BizStep-commissioning at urn:epc:id:sgln:0614141.00001.0+ 2. 2026-09-02T09:40:00.000+02:00 AggregationEvent BizStep-packing at urn:epc:id:sgln:0614141.00001.0+ 3. 2026-09-03T06:05:00.000+02:00 ObjectEvent BizStep-shipping at urn:epc:id:sgln:0614141.00002.0+ 4. 2026-09-03T14:22:00.000+02:00 ObjectEvent BizStep-receiving at urn:epc:id:sgln:0614141.00003.0+ 5. 2026-09-05T10:31:00.000+02:00 ObjectEvent BizStep-retail_selling at urn:epc:id:sgln:0614141.00003.1++Passport written to <temp dir>/0614141.107346.2026.ttl+42 triples, 5 steps, read back and checked+```++Nothing is installed beyond what the core package already pulls in: `rdflib` is+a core dependency, and the export goes through `RDFExporter.export_to_rdf()` in+`semantica/export/rdf_exporter.py`. `--out` writes the passport where you want+it, `--format` takes `turtle` (default) or `ntriples`. JSON-LD is not offered:+the exporter's serializer turns the passport's relationships into their own+nodes and writes event classes as `semantica:type`, so the chain links this+sample checks would not survive the round trip.++The event set holds two products. Asking for the second one gives its own,+shorter chain:++```bash+python examples/epcis/walk_chain.py --epc urn:epc:id:sgtin:0614141.107346.2027+```++## Where the events come from++`events.json` is an **EPCIS 2.0** document (`schemaVersion: "2.0"`, JSON+binding, `@context` pointing at+`https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld`).++The eight events were written by hand for this sample. They are not a capture+from a live system and contain no real company data: the SGTIN, SSCC and SGLN+identifiers use the `0614141` GS1 prefix that GS1 keeps as its own example+prefix, and the one business transaction points at+`https://example.org/purchase-orders/4711`. The shapes follow the standard —+`ObjectEvent` and `AggregationEvent`, CBV business steps (`commissioning`,+`packing`, `shipping`, `receiving`, `retail_selling`), `readPoint` and+`bizLocation` as SGLN.++One field is ours, not the standard's: **`parentEventID`**. EPCIS 2.0 has no+event-to-event link. It orders events by `eventTime`, and `parentID` means the+container an aggregation was about (the SSCC here), not the event that came+before. To walk a chain instead of sorting timestamps, each event carries the+`eventID` of the event it follows. It is a sample-level convention, kept in the+event set and in the passport's own `passport#` namespace rather than dressed+up as GS1 vocabulary:++| predicate | means |+|---|---|+| `passport#hasEvent` | this product appears in that event |+| `passport#followedBy` | this event came before that one |+| `passport#bizStep` | CBV business step, as a `https://ref.gs1.org/cbv/` IRI |+| `passport#bizLocation` | where it happened |+| `passport#eventTime` | when |++The class of each event is the real one, `https://ref.gs1.org/epcis/ObjectEvent`+and `.../AggregationEvent`, so the passport reads against the GS1 vocabularies+where they apply.++## A hole in the event set is reported, not raised++```bash+python examples/epcis/walk_chain.py --events examples/epcis/events_missing_parent.json+```++```+error: 1 event(s) point at a parent that is not in the document:+ urn:uuid:5f0f4a3e-0003-...-0000000000a3 points at parent urn:uuid:5f0f4a3e-0002-...-0000000000a2+```++Exit code is 2 and there is no traceback. `events_missing_parent.json` is+`events.json` with the packing event removed, so the shipping event is left+pointing at an event that is no longer there.++The same guard covers the other ways an event set stops being a chain: a+missing `eventID`, a duplicate `eventID`, a wrong `schemaVersion`, an `EPC` that+the set never mentions, and the two events for one product that both claim to+be first.++## What this sample does not do++It walks one product. It does not implement EPCIS 2.0: no query interface, no+capture interface, no `TransformationEvent` handling beyond reading the EPCs it+carries, no JSON-LD expansion (the compact IRIs are expanded by hand from the+prefixes the context binds), no validation against the standard's JSON schema.+The point is the path — an event document arrives, a passport leaves — not+coverage of the standard.diff --git a/examples/epcis/events.json b/examples/epcis/events.jsonnew file mode 100644index 00000000..a2910e8b--- /dev/null+++ b/examples/epcis/events.json@@ -0,0 +1,120 @@+{+ "@context": "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld",+ "type": "EPCISDocument",+ "schemaVersion": "2.0",+ "creationDate": "2026-10-21T09:00:00.000+02:00",+ "epcisBody": {+ "eventList": [+ {+ "eventID": "urn:uuid:5f0f4a3e-0001-4a3e-9b1a-0000000000a1",+ "type": "ObjectEvent",+ "eventTime": "2026-09-02T08:12:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-02T08:12:04.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "ADD",+ "bizStep": "cbv:BizStep-commissioning",+ "disposition": "cbv:Disp-active",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00001.0"}+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0002-4a3e-9b1a-0000000000a2",+ "type": "AggregationEvent",+ "eventTime": "2026-09-02T09:40:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-02T09:40:02.000+02:00",+ "parentID": "urn:epc:id:sscc:0614141.1234567890",+ "childEPCs": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "ADD",+ "bizStep": "cbv:BizStep-packing",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "parentEventID": "urn:uuid:5f0f4a3e-0001-4a3e-9b1a-0000000000a1"+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0003-4a3e-9b1a-0000000000a3",+ "type": "ObjectEvent",+ "eventTime": "2026-09-03T06:05:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-03T06:05:11.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "OBSERVE",+ "bizStep": "cbv:BizStep-shipping",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00002.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00002.0"},+ "bizTransactionList": [+ {"type": "po", "bizTransaction": "https://example.org/purchase-orders/4711"}+ ],+ "parentEventID": "urn:uuid:5f0f4a3e-0002-4a3e-9b1a-0000000000a2"+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0004-4a3e-9b1a-0000000000a4",+ "type": "ObjectEvent",+ "eventTime": "2026-09-03T14:22:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-03T14:22:09.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "OBSERVE",+ "bizStep": "cbv:BizStep-receiving",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00003.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00003.0"},+ "parentEventID": "urn:uuid:5f0f4a3e-0003-4a3e-9b1a-0000000000a3"+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0005-4a3e-9b1a-0000000000a5",+ "type": "ObjectEvent",+ "eventTime": "2026-09-05T10:31:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-05T10:31:01.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "OBSERVE",+ "bizStep": "cbv:BizStep-retail_selling",+ "disposition": "cbv:Disp-sold",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00003.1"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00003.1"},+ "parentEventID": "urn:uuid:5f0f4a3e-0004-4a3e-9b1a-0000000000a4"+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0006-4a3e-9b1a-0000000000b1",+ "type": "ObjectEvent",+ "eventTime": "2026-09-02T08:14:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-02T08:14:03.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2027"],+ "action": "ADD",+ "bizStep": "cbv:BizStep-commissioning",+ "disposition": "cbv:Disp-active",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00001.0"}+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0007-4a3e-9b1a-0000000000b2",+ "type": "AggregationEvent",+ "eventTime": "2026-09-02T09:41:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-02T09:41:02.000+02:00",+ "parentID": "urn:epc:id:sscc:0614141.1234567891",+ "childEPCs": ["urn:epc:id:sgtin:0614141.107346.2027"],+ "action": "ADD",+ "bizStep": "cbv:BizStep-packing",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00001.0"},+ "parentEventID": "urn:uuid:5f0f4a3e-0006-4a3e-9b1a-0000000000b1"+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0008-4a3e-9b1a-0000000000b3",+ "type": "ObjectEvent",+ "eventTime": "2026-09-03T06:07:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "recordTime": "2026-09-03T06:07:05.000+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2027"],+ "action": "OBSERVE",+ "bizStep": "cbv:BizStep-shipping",+ "readPoint": {"id": "urn:epc:id:sgln:0614141.00002.0"},+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00002.0"},+ "parentEventID": "urn:uuid:5f0f4a3e-0007-4a3e-9b1a-0000000000b2"+ }+ ]+ }+}diff --git a/examples/epcis/events_missing_parent.json b/examples/epcis/events_missing_parent.jsonnew file mode 100644index 00000000..3ea76a26--- /dev/null+++ b/examples/epcis/events_missing_parent.json@@ -0,0 +1,31 @@+{+ "@context": "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld",+ "type": "EPCISDocument",+ "schemaVersion": "2.0",+ "creationDate": "2026-10-21T09:00:00.000+02:00",+ "epcisBody": {+ "eventList": [+ {+ "eventID": "urn:uuid:5f0f4a3e-0001-4a3e-9b1a-0000000000a1",+ "type": "ObjectEvent",+ "eventTime": "2026-09-02T08:12:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "ADD",+ "bizStep": "cbv:BizStep-commissioning",+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00001.0"}+ },+ {+ "eventID": "urn:uuid:5f0f4a3e-0003-4a3e-9b1a-0000000000a3",+ "type": "ObjectEvent",+ "eventTime": "2026-09-03T06:05:00.000+02:00",+ "eventTimeZoneOffset": "+02:00",+ "epcList": ["urn:epc:id:sgtin:0614141.107346.2026"],+ "action": "OBSERVE",+ "bizStep": "cbv:BizStep-shipping",+ "bizLocation": {"id": "urn:epc:id:sgln:0614141.00002.0"},+ "parentEventID": "urn:uuid:5f0f4a3e-0002-4a3e-9b1a-0000000000a2"+ }+ ]+ }+}diff --git a/examples/epcis/walk_chain.py b/examples/epcis/walk_chain.pynew file mode 100644index 00000000..bee7032f--- /dev/null+++ b/examples/epcis/walk_chain.py@@ -0,0 +1,387 @@+"""+EPCIS 2.0 - walk a product passport chain end to end++Reads an EPCIS 2.0 event set (JSON), keeps the events that touch one product,+orders them into a chain and exports the resulting product passport as RDF.++Run it from the repository root:++ python examples/epcis/walk_chain.py++ python examples/epcis/walk_chain.py --epc urn:epc:id:sgtin:0614141.107346.2027+ python examples/epcis/walk_chain.py --events examples/epcis/events_missing_parent.json++The event set ships with the sample in events.json; README.md says where the+events come from and which part of them is EPCIS and which part is ours.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import tempfile+from pathlib import Path+from typing import Any, Dict, Iterable, List, Optional++# Set before importing semantica: the progress bars would otherwise interleave+# with the chain this sample prints.+os.environ.setdefault("SEMANTICA_DISABLE_PROGRESS", "1")++from semantica.export import RDFExporter # noqa: E402 (after the env var)++HERE = Path(__file__).resolve().parent++#: Prefixes the EPCIS 2.0 JSON-LD context binds, kept here because this sample+#: reads plain JSON: nothing in it runs a JSON-LD processor, so compact IRIs+#: like ``cbv:BizStep-shipping`` have to be expanded by hand.+EPCIS_PREFIXES = {+ "epcis": "https://ref.gs1.org/epcis/",+ "cbv": "https://ref.gs1.org/cbv/",+ "gs1": "https://gs1.org/voc/",+}++#: Where the EPC in each event type sits.+EPC_FIELDS = ("epcList", "childEPCs", "inputEPCList", "outputEPCList")++#: The chain predicates. EPCIS 2.0 has no event-to-event link (it orders events+#: by time, and parentID only says which container an aggregation was about),+#: so the two links below are this sample's own and live in their own+#: namespace rather than being passed off as GS1 vocabulary.+PASSPORT_NS = "https://semantica.dev/examples/epcis/passport#"+HAS_EVENT = PASSPORT_NS + "hasEvent"+FOLLOWED_BY = PASSPORT_NS + "followedBy"+BIZ_STEP = PASSPORT_NS + "bizStep"+BIZ_LOCATION = PASSPORT_NS + "bizLocation"+EVENT_TIME = PASSPORT_NS + "eventTime"+++class EpcisChainError(Exception):+ """The event set cannot be walked into a chain. Message is for the reader."""+++def expand(term: str) -> str:+ """Expand a compact IRI from the EPCIS context; leave anything else alone."""+ prefix, sep, local = term.partition(":")+ if sep and prefix in EPCIS_PREFIXES:+ return EPCIS_PREFIXES[prefix] + local+ return term+++def local_name(term: str) -> str:+ """The readable end of a compact or full IRI: ``cbv:BizStep-shipping`` -> ``BizStep-shipping``."""+ expanded = expand(term)+ return expanded.rsplit("/", 1)[-1].rsplit("#", 1)[-1]+++def load_events(path: Path) -> List[Dict[str, Any]]:+ """Read an EPCIS document and return its event list."""+ try:+ document = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ raise EpcisChainError(f"no event set at {path}")+ except json.JSONDecodeError as exc:+ raise EpcisChainError(+ f"{path.name} is not valid JSON: {exc.msg} (line {exc.lineno})"+ )++ if not isinstance(document, dict):+ raise EpcisChainError(+ f"{path.name} is not an EPCIS document: expected an object at the top, "+ f"found {type(document).__name__}"+ )+ if document.get("type") != "EPCISDocument":+ raise EpcisChainError(+ f"{path.name} is not an EPCIS document: expected type 'EPCISDocument', "+ f"found {document.get('type')!r}"+ )+ version = str(document.get("schemaVersion", ""))+ if version != "2.0":+ raise EpcisChainError(+ f"{path.name} is EPCIS {version or 'of unknown version'}; this sample reads EPCIS 2.0"+ )++ body = document.get("epcisBody")+ if not isinstance(body, dict):+ raise EpcisChainError(f"{path.name} has no epcisBody object")+ events = body.get("eventList")+ if not isinstance(events, list) or not events:+ raise EpcisChainError(f"{path.name} has no epcisBody.eventList")+ return events+++def index_events(events: Iterable[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:+ """Map eventID -> event, refusing duplicates and events without an id."""+ by_id: Dict[str, Dict[str, Any]] = {}+ for position, event in enumerate(events):+ event_id = event.get("eventID")+ if not event_id:+ raise EpcisChainError(+ f"event #{position} has no eventID, so nothing can point at it"+ )+ if event_id in by_id:+ raise EpcisChainError(f"eventID {event_id} appears twice")+ by_id[event_id] = event+ return by_id+++def check_parents(+ events: Iterable[Dict[str, Any]], by_id: Dict[str, Dict[str, Any]]+) -> None:+ """Every parent reference must resolve, and the parent links must not loop."""+ dangling = []+ for event in events:+ parent = event.get("parentEventID")+ if parent and parent not in by_id:+ dangling.append((event["eventID"], parent))+ if dangling:+ lines = [+ f" {event_id} points at parent {parent}" for event_id, parent in dangling+ ]+ raise EpcisChainError(+ f"{len(dangling)} event(s) point at a parent that is not in the document:\n"+ + "\n".join(lines)+ )++ for event_id in by_id:+ seen = set()+ current: Optional[str] = event_id+ while current:+ if current in seen:+ raise EpcisChainError(f"the parent links loop back to {current}")+ seen.add(current)+ current = by_id[current].get("parentEventID")+++def products(events: Iterable[Dict[str, Any]]) -> List[str]:+ """Every EPC the event set mentions, in the order they first appear."""+ found: List[str] = []+ for event in events:+ for field in EPC_FIELDS:+ for epc in event.get(field) or []:+ if epc not in found:+ found.append(epc)+ return found+++def touches(event: Dict[str, Any], epc: str) -> bool:+ return any(epc in (event.get(field) or []) for field in EPC_FIELDS)+++def chain_for(events: List[Dict[str, Any]], epc: str) -> List[Dict[str, Any]]:+ """The events that touch ``epc``, ordered root first along parentEventID."""+ own = [event for event in events if touches(event, epc)]+ if not own:+ raise EpcisChainError(f"no event in the set mentions {epc}")++ own_ids = {event["eventID"] for event in own}+ children: Dict[str, str] = {}+ starts = []+ for event in own:+ parent = event.get("parentEventID")+ # A parent outside this product's own events (the pallet it was packed+ # into, say) is not a hole in the document: it just means the chain+ # starts here. check_parents() already rejected the real holes.+ if parent and parent in own_ids:+ if parent in children:+ raise EpcisChainError(+ f"the events for {epc} branch: {parent} is followed by "+ f"{children[parent]} and {event['eventID']}"+ )+ children[parent] = event["eventID"]+ else:+ starts.append(event["eventID"])++ if len(starts) != 1:+ raise EpcisChainError(+ f"the events for {epc} form {len(starts)} separate chains instead of one: "+ + ", ".join(sorted(starts))+ + " - add the missing parentEventID links"+ )++ order = []+ current: Optional[str] = starts[0]+ by_id = {event["eventID"]: event for event in own}+ while current:+ order.append(by_id[current])+ current = children.get(current)+ return order+++def build_graph(chain: List[Dict[str, Any]], epc: str) -> Dict[str, Any]:+ """Turn the chain into the entity/relationship shape RDFExporter takes."""+ entities: List[Dict[str, Any]] = [+ {+ "id": epc,+ "text": f"Product passport for {epc}",+ "type": "https://gs1.org/voc/Product",+ }+ ]+ relationships: List[Dict[str, Any]] = []++ for event in chain:+ event_id = event["eventID"]+ step = local_name(event.get("bizStep", ""))+ entities.append(+ {+ "id": event_id,+ "text": f"{event.get('type', 'Event')} {step}".strip(),+ "type": expand(f"epcis:{event.get('type', 'Event')}"),+ "metadata": _event_metadata(event),+ }+ )+ relationships.append(+ {"source_id": epc, "target_id": event_id, "type": HAS_EVENT}+ )++ for previous, following in zip(chain, chain[1:]):+ relationships.append(+ {+ "source_id": previous["eventID"],+ "target_id": following["eventID"],+ "type": FOLLOWED_BY,+ }+ )++ return {+ "entities": entities,+ "relationships": relationships,+ "metadata": {+ "num_entities": len(entities),+ "num_relationships": len(relationships),+ },+ }+++def _event_metadata(event: Dict[str, Any]) -> Dict[str, Any]:+ """The fields worth carrying into the RDF, as they are written in EPCIS."""+ metadata: Dict[str, Any] = {}+ if event.get("bizStep"):+ metadata["bizStep"] = expand(event["bizStep"])+ if event.get("bizLocation"):+ metadata["bizLocation"] = event["bizLocation"].get("id")+ if event.get("eventTime"):+ metadata["eventTime"] = event["eventTime"]+ return metadata+++#: Metadata keys the exporter will not guess a namespace for (issue #1146), so+#: the sample says where its own keys belong.+METADATA_TERMS = {+ "bizStep": BIZ_STEP,+ "bizLocation": BIZ_LOCATION,+ "eventTime": EVENT_TIME,+}+++def render_passport(chain: List[Dict[str, Any]], epc: str) -> str:+ """The chain as a human reads it: one line per step, in order."""+ lines = [f"Product passport for {epc}"]+ for number, event in enumerate(chain, start=1):+ location = (event.get("bizLocation") or {}).get("id", "-")+ step = local_name(event.get("bizStep", "?"))+ lines.append(+ f" {number}. {event.get('eventTime', '?')} {event.get('type', '?')} "+ f"{step} at {location}"+ )+ return "\n".join(lines)+++def read_back(+ graph_path: Path, chain: List[Dict[str, Any]], epc: str, graph_format: str+) -> int:+ """Parse the passport we just wrote and check the links survived.++ The parser has to match what was written: a Turtle parser reading a triple+ file raises before any check runs.+ """+ from rdflib import Graph, URIRef++ graph = Graph()+ graph.parse(graph_path, format="nt" if graph_format == "ntriples" else graph_format)++ for event in chain:+ event_ref = URIRef(event["eventID"])+ if (URIRef(epc), URIRef(HAS_EVENT), event_ref) not in graph:+ raise EpcisChainError(+ f"the passport lost the link from {epc} to {event['eventID']}"+ )+ for previous, following in zip(chain, chain[1:]):+ if (+ URIRef(previous["eventID"]),+ URIRef(FOLLOWED_BY),+ URIRef(following["eventID"]),+ ) not in graph:+ raise EpcisChainError(+ f"the passport lost the link from {previous['eventID']} to {following['eventID']}"+ )+ return len(graph)+++def main(argv: Optional[List[str]] = None) -> int:+ parser = argparse.ArgumentParser(+ description="Walk an EPCIS 2.0 product passport chain."+ )+ parser.add_argument("--events", type=Path, default=HERE / "events.json")+ parser.add_argument(+ "--epc",+ default=None,+ help="the product to walk (default: the first one in the set)",+ )+ parser.add_argument(+ "--format",+ default="turtle",+ choices=("turtle", "ntriples"),+ help=(+ "passport syntax; JSON-LD is not offered because the exporter "+ "reifies the relationships this sample checks"+ ),+ )+ parser.add_argument(+ "--out", type=Path, default=None, help="where to write the passport"+ )+ args = parser.parse_args(argv)++ try:+ events = load_events(args.events)+ by_id = index_events(events)+ check_parents(events, by_id)++ available = products(events)+ if not available:+ raise EpcisChainError(+ f"{args.events.name} mentions no product EPC in {', '.join(EPC_FIELDS)}"+ )+ epc = args.epc or available[0]+ if epc not in available:+ raise EpcisChainError(+ f"{epc} is not in {args.events.name}; it mentions {', '.join(available)}"+ )++ chain = chain_for(events, epc)+ print(render_passport(chain, epc))++ graph = build_graph(chain, epc)+ passport = RDFExporter().export_to_rdf(+ graph, format=args.format, metadata_terms=METADATA_TERMS+ )++ out_dir = args.out or Path(tempfile.mkdtemp(prefix="epcis-passport-"))+ out_dir.mkdir(parents=True, exist_ok=True)+ suffix = {"turtle": "ttl", "jsonld": "jsonld", "ntriples": "nt"}[args.format]+ graph_path = out_dir / f"{epc.rsplit(':', 1)[-1]}.{suffix}"+ graph_path.write_text(passport, encoding="utf-8")++ triple_count = read_back(graph_path, chain, epc, args.format)+ print(f"\nPassport written to {graph_path}")+ print(f"{triple_count} triples, {len(chain)} steps, read back and checked")+ except EpcisChainError as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_epcis_example.py b/tests/test_epcis_example.pynew file mode 100644index 00000000..864d2cf0--- /dev/null+++ b/tests/test_epcis_example.py@@ -0,0 +1,218 @@+"""The EPCIS sample runs from a clean checkout and refuses a broken event set (issue #2023).++One test runs the sample the way the README says to -- a command and an exit+code, which is the sample's own definition of done. The rest call ``main()``+directly: importing semantica costs more than running the sample does, and+paying that once per test would make a small sample expensive to keep honest.+"""++from __future__ import annotations++import importlib.util+import json+import subprocess+import sys+from pathlib import Path++import pytest+from rdflib import Graph, URIRef+from rdflib.namespace import RDF++REPO_ROOT = Path(__file__).resolve().parents[1]+EXAMPLE = REPO_ROOT / "examples" / "epcis" / "walk_chain.py"+EVENTS = REPO_ROOT / "examples" / "epcis" / "events.json"+BROKEN_EVENTS = REPO_ROOT / "examples" / "epcis" / "events_missing_parent.json"++EPC = "urn:epc:id:sgtin:0614141.107346.2026"+SECOND_EPC = "urn:epc:id:sgtin:0614141.107346.2027"+PASSPORT_NS = "https://semantica.dev/examples/epcis/passport#"+HAS_EVENT = URIRef(PASSPORT_NS + "hasEvent")+FOLLOWED_BY = URIRef(PASSPORT_NS + "followedBy")++CHAIN = [+ "urn:uuid:5f0f4a3e-0001-4a3e-9b1a-0000000000a1",+ "urn:uuid:5f0f4a3e-0002-4a3e-9b1a-0000000000a2",+ "urn:uuid:5f0f4a3e-0003-4a3e-9b1a-0000000000a3",+ "urn:uuid:5f0f4a3e-0004-4a3e-9b1a-0000000000a4",+ "urn:uuid:5f0f4a3e-0005-4a3e-9b1a-0000000000a5",+]++[email protected](scope="module")+def sample():+ """The example module, loaded from its path: ``examples/`` is not a package."""+ spec = importlib.util.spec_from_file_location("epcis_walk_chain", EXAMPLE)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_one_command_writes_the_passport_and_exits_zero(tmp_path):+ result = subprocess.run(+ [sys.executable, str(EXAMPLE), "--out", str(tmp_path)],+ cwd=str(REPO_ROOT),+ capture_output=True,+ text=True,+ timeout=300,+ )++ assert result.returncode == 0, result.stderr+ assert f"Product passport for {EPC}" in result.stdout++ written = list(tmp_path.glob("*.ttl"))+ assert len(written) == 1++ graph = Graph()+ graph.parse(written[0], format="turtle")++ product = URIRef(EPC)+ assert [str(event) for event in graph.objects(product, HAS_EVENT)] == CHAIN+ for previous, following in zip(CHAIN, CHAIN[1:]):+ assert (URIRef(previous), FOLLOWED_BY, URIRef(following)) in graph++ # The event classes and the business step are the GS1 ones, not the sample's.+ assert (+ URIRef(CHAIN[0]),+ RDF.type,+ URIRef("https://ref.gs1.org/epcis/ObjectEvent"),+ ) in graph+ assert (+ URIRef(CHAIN[1]),+ RDF.type,+ URIRef("https://ref.gs1.org/epcis/AggregationEvent"),+ ) in graph+ steps = {+ str(value)+ for value in graph.objects(URIRef(CHAIN[0]), URIRef(PASSPORT_NS + "bizStep"))+ }+ assert steps == {"https://ref.gs1.org/cbv/BizStep-commissioning"}+++def test_the_product_can_be_chosen(sample, tmp_path, capsys):+ code = sample.main(["--epc", SECOND_EPC, "--out", str(tmp_path)])++ assert code == 0+ assert f"Product passport for {SECOND_EPC}" in capsys.readouterr().out+++def test_a_missing_parent_is_reported_not_raised(sample, capsys):+ code = sample.main(["--events", str(BROKEN_EVENTS)])+ stderr = capsys.readouterr().err++ assert code == 2+ assert "not in the document" in stderr+ assert "Traceback" not in stderr+++def test_events_that_do_not_form_one_chain_are_refused(sample, tmp_path, capsys):+ events = sample.load_events(EVENTS)+ for event in events:+ if event["eventID"].endswith("00a3"):+ del event["parentEventID"]+ branching = tmp_path / "branching.json"+ branching.write_text(+ json.dumps(+ {+ "type": "EPCISDocument",+ "schemaVersion": "2.0",+ "epcisBody": {"eventList": events},+ }+ ),+ encoding="utf-8",+ )++ code = sample.main(["--events", str(branching), "--out", str(tmp_path / "out")])++ assert code == 2+ assert "separate chains" in capsys.readouterr().err+++ "args, expected",+ [+ (["--epc", "urn:epc:id:sgtin:0614141.107346.9999"], "is not in"),+ (["--events", "does-not-exist.json"], "no event set at"),+ ],+)+def test_input_that_cannot_be_walked_is_explained(sample, args, expected, capsys):+ code = sample.main(args)++ assert code == 2+ assert expected in capsys.readouterr().err+++def test_a_document_that_is_not_an_object_is_reported(sample, tmp_path, capsys):+ document = tmp_path / "array.json"+ document.write_text("[]", encoding="utf-8")++ code = sample.main(["--events", str(document)])+ stderr = capsys.readouterr().err++ assert code == 2+ assert "expected an object at the top" in stderr+ assert "Traceback" not in stderr+++def test_a_set_without_a_product_epc_is_reported(sample, tmp_path, capsys):+ document = tmp_path / "productless.json"+ document.write_text(+ json.dumps(+ {+ "type": "EPCISDocument",+ "schemaVersion": "2.0",+ "epcisBody": {+ "eventList": [+ {+ "eventID": "urn:uuid:5f0f4a3e-0009-4a3e-9b1a-0000000000a9",+ "type": "ObjectEvent",+ "eventTime": "2026-09-02T08:12:00.000+02:00",+ }+ ]+ },+ }+ ),+ encoding="utf-8",+ )++ code = sample.main(["--events", str(document)])+ stderr = capsys.readouterr().err++ assert code == 2+ assert "mentions no product EPC" in stderr+ assert "Traceback" not in stderr+++def test_a_different_2x_version_is_rejected(sample, tmp_path, capsys):+ events = sample.load_events(EVENTS)+ document = tmp_path / "version-2-1.json"+ document.write_text(+ json.dumps(+ {+ "type": "EPCISDocument",+ "schemaVersion": "2.1",+ "epcisBody": {"eventList": events},+ }+ ),+ encoding="utf-8",+ )++ code = sample.main(["--events", str(document)])+ stderr = capsys.readouterr().err++ assert code == 2+ assert "this sample reads EPCIS 2.0" in stderr+++def test_jsonld_is_not_an_offered_format(sample):+ # The exporter reifies the relationships, so the sample does not offer a+ # format whose round trip it cannot check. argparse refuses it up front.+ with pytest.raises(SystemExit):+ sample.main(["--format", "jsonld"])+++def test_ntriples_round_trips(sample, tmp_path, capsys):+ code = sample.main(["--format", "ntriples", "--out", str(tmp_path)])++ assert code == 0+ assert list(tmp_path.glob("*.nt"))+ assert "read back and checked" in capsys.readouterr().out