Search and contents

Traceability: what went into an order, and everywhere a material was consumed

This guide covers how assemble_genealogy in engine/traceability.py implements Traceability: answering what material went into an order, and everywhere a serial or lot was consumed, in both directions.

This is cross-system correlation, not Kindred implementing traceability itself. Most connected MES and quality systems already track their own lot and serial genealogy. Kindred's job is unifying those records across systems that don't otherwise talk to each other. assemble_order_trail (see order-trail-assembly.md) does the same for an order's own cross-node Activity Log entries, this Node's and, with peers, every declared peer's.

1. Record a material-consumed-in-order observation

from engine.activity_log import ActivityLog
from engine.traceability import GenealogyLink, GenealogyLinkTask

activity_log = ActivityLog()
link_task = GenealogyLinkTask(activity_log, "MES", "mes-1")

link_task.run(GenealogyLink(order_id="MO-1001", material_id="LOT-4471"))

GenealogyLinkTask is Reconciliation-Task-shaped (engine/identity_resolution.py). It is a small Task logged through engine/task_activity_log.py, writing exactly one ActivityLogEntry per link. reference_ids carries both identities under domain-specific keys:

entry.reference_ids  # {"order_id": "MO-1001", "material_id": "LOT-4471"}

This is deliberately not the generic "reference_id" key that IdentityResolver and ReconciliationTask's _reference_ids helper produce. That key's value is per-entity-type ambiguous by design (see the Pitfalls in order-trail-assembly.md), and a genealogy link entry genuinely needs to name two distinct entities in one entry, not one.

GenealogyLinkTask.run raises ValueError if either order_id or material_id is empty or whitespace-only. This is the same "no reference to reconcile against" guard ReconciliationTask.run applies to a bare reference_id. An empty identity is never a genuine observation to log.

2. Assemble a genealogy

from engine.identity_resolution import IdentityStore
from engine.traceability import assemble_genealogy

store = IdentityStore()  # production default table name: identity_records

genealogy = assemble_genealogy(store, activity_log, "MO-1001", single_node=True)

genealogy.materials_in  # ["LOT-4471", ...] - what went into this order
genealogy.consumed_in  # {"LOT-4471": ["MO-1002"], ...} - everywhere else each was consumed
genealogy.completeness  # GenealogyCompleteness.COMPLETE or .INCOMPLETE

single_node and peers

single_node=True says this is a read of one Node: one database, or a site that declares no peers.

  • A call that passes neither peers (section 4) nor single_node reads the same links and returns a genealogy that is INCOMPLETE. The cause is peers_not_asked, and genealogy.peers_not_asked_reason says that no peers were asked. This is because, on a site whose Nodes each have a database of their own, that genealogy holds this Node's links alone.
  • Passing both is refused with a ValueError.

Both directions from one call

  • materials_in walks forward from the order to every material named alongside it (ActivityLog.query(reference_id="MO-1001"), filtered to genealogy-link entries).
  • consumed_in walks outward again from each of those materials (ActivityLog.query(reference_id=<material_id>)) to every other order it was also linked to.

It raises ValueError if no IdentityRecord is on file for order_id. This is the same precondition assemble_order_trail enforces.

3. Completeness is never assumed

Kindred explicitly flags any trace that remains incomplete, rather than silently returning a partial result as if it were whole. This is the same fail-safe-on-the-unknown principle the Sign-off Gate and the retrieval quality gate apply.

assemble_genealogy flags INCOMPLETE whenever any of these holds:

  • No genealogy-link data was ever reported for this order. A source that never told Kindred about any material consumption isn't the same as an order that genuinely used none. This is the distinction the Retrieval Quality Gate draws between "confirmed nothing relevant" and "never got a fair look."
  • A link was itself reported incomplete by the source: GenealogyLink(..., complete=False). This is the integrator's own "gap at the source" case. Addressing the gap at the source is site-specific work, and the flag surfaces it rather than papering over it.
  • A linked material has no corresponding resolved IdentityRecord on file. A source naming a material Kindred has never independently resolved is exactly the case of a connected system with no native genealogy data.
  • A genealogy-link entry is malformed, for example missing its material_id or order_id. Nothing in ActivityLogEntry's schema enforces that pairing for every possible writer, only GenealogyLinkTask.run's convention does. Such an entry is flagged INCOMPLETE rather than silently dropped from the count as if it didn't exist.

A later report clears the flag

A source correcting an earlier gap clears the flag, rather than leaving it stuck forever. Only the most recently reported link per material drives completeness. The Activity Log is append-only, so "the latest report wins" is the only way a later GenealogyLink(..., complete=True) can supersede an earlier complete=False (or unresolved-material) report for the same material.

"Latest" follows activity_log.query's occurred_at, seq, id ordering. That holds for a single Node. Across Nodes the order is occurred_at, node_instance_id (see section 4). See the last Pitfalls entry for what that ordering does and doesn't guarantee.

4. A genealogy across Nodes that each have their own database

genealogy = assemble_genealogy(
    runtime.store, runtime.activity_log, "MO-1001", peers=runtime.peer_client
)

genealogy.completeness  # INCOMPLETE if anything below is not whole
genealogy.causes  # every reason, once each: IncompleteCause values
genealogy.not_contributed  # one PeerFetchResult per declared peer that did not contribute
genealogy.unreached_materials  # materials whose lookup on peers was not made
genealogy.local_complete  # False if the read limit cut short this Node's own entries

With peers (a PeerClient, which must log to the same activity_log you pass):

  • The links are read from this Node's own Activity Log and from every declared peer's, asked over the Communication Interface.
  • A material this Node has no record for is asked of every declared peer.
  • Nothing is stored. A peer's links and records exist only in the returned Genealogy.

Without peers, the genealogy is built as in section 2 and is INCOMPLETE unless the call says single_node=True. A site whose Nodes do not share a database therefore passes peers, and a genealogy that holds this Node's links alone says so. A PeerClient over a site that declares no peers is a read that asked everyone there was, and is not flagged. The Management API's genealogy route always passes a client, so it is unchanged.

How the cross-Node read behaves

  • Both directions combine. The order's own links, and every other order a material was consumed in, come from every Node. A peer's entries are filtered again on this side: only a Material Genealogy Link entry carrying the asked order (or material) under its own key is used.
  • "Latest report wins" holds across Nodes, decided by the merged order occurred_at, then node_instance_id, and the same on every run.
    • Two reports of one Node at exactly one instant stay in the order that Node logged them, so the later one wins, as in a single Activity Log.
    • Each Node stamps its own reports, so Node clocks that disagree decide which report is latest.
    • Two reports at exactly one instant on different Nodes are decided by node_instance_id, not by which was written first.
    • A peer's report can therefore clear or set the incomplete flag.
  • A material resolved only on a peer is resolved, if that peer's record is RESOLVED. A peer's Pending, rejected or merged record leaves the material unresolved. A material this Node has a record for asks no peer (this Node's check is that a record is on file, as in section 3).
  • A peer that did not contribute is named, never silent. A peer that is down, slow, refuses, answers with something unusable or was cut short is in not_contributed with its outcome, once, however many of the fetches it failed. It never raises. Its links that did arrive stay in the genealogy.
  • The refusal comes first. This Node needs a record of its own for the order. A peer that holds one does not stand in for it, and the call raises ValueError before any peer is asked.
  • A peer's link with a material it cannot name (an empty id, or one with a NUL character) is a malformed link, not an error.
  • What a peer sent reaches the narrative. The material and order ids in a peer's links are the peer's own words and reach the model and the fact listing as they are. What stays out is fetch metadata: a peer's detail and its address.
  • _in_progress_orders_for_material (engine/node_main.py) answers a peer's question from this Node's own links. It is unchanged and still local.

Requests are bounded

  • A genealogy of N materials makes 1 + N entries fetches (the order's links, then each material's other orders), and at most one identity fetch per material this Node has no record for. Each asks every declared peer.
  • Only the first max_materials (default 50) materials are looked up on peers, because a peer names the materials it reports.
  • All the fetches share deadline_seconds (default 30). The first gets all of it, every later one only what is left, and none starts with less than two seconds left.
  • Materials with a lookup skipped are in unreached_materials, and they make the genealogy incomplete. Their consumed_in may be empty or partial, which does not mean "consumed nowhere else". A material whose identity lookup alone was skipped is not claimed unresolved.
  • A peer that reports many materials can crowd the rest out of the first max_materials, which are taken in the order first reported. The rest are named, not dropped silently.
  • Every fetch logs one entry on this Node per peer asked.

The narrative and coverage gaps

The narrative (see ai-narrative-drafting-task-wiring.md) carries a section headed "Incomplete Genealogy", written by code and not by the model, whenever the genealogy is INCOMPLETE, from any cause. It says each cause, and each missing Node Type with its outcome, in the drafted narrative and in the fact listing used when inference is disabled.

A coverage gap over the order's links makes the genealogy incomplete.

  • genealogy.coverage_gaps lists the coverage gaps (see "Coverage gaps" in database-reference.md) that overlap the span of the order's link entries. IncompleteCause.COVERAGE_GAP is among the causes while one does.
  • It is the last fetch made, with peers, and like the others it starts only with the time it needs. When the deadline left none, the cause is COVERAGE_NOT_CHECKED and no gap is claimed absent.
  • A gap bears on the order, not on a material, so every page of a paged genealogy carries the same ones. The materials and the orders they were consumed in are exactly what they were.

5. A long genealogy, one page at a time, and its answer as JSON

An order can name a great many materials, and one material can be consumed in a great many orders (a bulk lot, say). The materials are read a page at a time, and the orders listed for each material are capped. You set both.

from engine.trace_answers import genealogy_answer

after = None
while True:
    genealogy = assemble_genealogy(
        runtime.store,
        runtime.activity_log,
        "MO-1001",
        peers=runtime.peer_client,
        page_size=50,  # materials per page; DEFAULT_MATERIALS_PAGE_SIZE is 50
        after_material=after,  # None for the first page
    )
    answer = genealogy_answer(genealogy, max_orders_per_material=200)
    after = answer["next_after_material"]  # None on the last page
    if after is None:
        break
  • page_size and after_material choose the materials one genealogy covers.
    • Without page_size, the genealogy covers every material, in the order first reported, as in sections 2 to 4. after_material must then be None.
    • With it, the genealogy is for the page_size materials that follow after_material, in sorted order of material id.
    • materials_in, consumed_in, the lookups on peers and every material-level cause are for that page alone.
    • materials_total (on the Genealogy and in the answer) says how many materials the order has in all.
  • A page is asked after a material, not at a position.
    • A link that arrives between two requests, however early its time, cannot make a page skip or repeat a material that was already there.
    • A material whose link arrives after its place in the sorted order has been passed is not in that walk, and materials_total counts it. A total that grew while you read therefore means reading again.
    • With peers, a material id over MAX_MATERIAL_ID_LENGTH (256 characters) is a malformed link, not a material, because an id that long could not be passed back as after_material.
  • A page is looked up whole. max_materials still bounds the lookups on peers, but it counts within the page, so page 2 is looked up as page 1 was. With peers, page_size may not exceed max_materials (the call raises ValueError), so no material of a page is left out of the lookups. The two defaults match (DEFAULT_MATERIALS_PAGE_SIZE and DEFAULT_MAX_MATERIALS, 50).
  • Completeness is per page. A page is complete when its own parts are. To say the whole order is complete, read every page and require each to be. The causes about the order itself (no link data, a link naming no material) and the peers that did not contribute are reported on every page.
  • Each page is assembled again. Nothing is kept between pages, so each page asks the peers again for the order's links and for its own materials. That is the cost of keeping nothing: a long order costs one such round per page.
  • max_orders_per_material (default 200) bounds each consumed_in list in the answer.
    • Above it, the first reported orders are kept, consumed_in_omitted names each material that had orders left out and how many, and truncated is true.
    • The cap bounds the answer, not the read. The orders are read in full, within the fetch limits, before it is applied.
    • truncated is about these cut lists only, and it is separate from completeness, which is about what could not be read.
    • A caller that needs every order must treat a truncated answer as unfinished even when it is complete, and must read on until next_after_material is None, whatever truncated says.
  • The answer carries only what it names. genealogy_answer carries the materials, their other orders, the completeness and every cause by name, the peers that did not contribute (Node Type, address, outcome and a reason this Node wrote, never text a peer sent), local_complete and the materials not looked up. A field added to Genealogy is not in the answer until the answer is changed to carry it.

How a site asks for a genealogy

A person at a site asks the Node's Management API, one page at a time:

deployment/kindred_management.sh genealogy MO-1001 page_size=50
deployment/kindred_management.sh genealogy MO-1001 page_size=50 after_material=LOT-B

The route is GET /v1/orders/{order_id}/genealogy, behind the correlation scope. It asks the Node's declared peers as the Node does, and its answer is the one of this section: next_after_material of a page is the after_material of the next, until it is null.

A page with a peer missing is a 200 that names the peer, and a site that declares no peers is refused. See Order trail and genealogy for the loop, what is capped, the statuses and the audit entry each request leaves.

Pitfalls

  • assemble_genealogy does not look at the order record's status, on purpose. A genealogy is built up while the item is manufactured and then stands until the finished good is serviced or the work in process is consumed, as in any manufacturing execution system. What went into an order therefore does not depend on whether its identity record is still being decided. Only the record's presence is checked. assemble_order_trail, which makes a statement about the order itself, also requires it to be resolved.
  • assemble_genealogy requires the order to already be resolved, not the materials. Only order_id is checked against IdentityStore up front (ValueError if missing). A linked material_id with no resolved record doesn't raise. It flags the result INCOMPLETE instead, since a source can genuinely name a material Kindred hasn't independently observed yet.
  • consumed_in only reports INCOMPLETE-driving checks for the anchor order's own links, not for each material's other orders. A material consumed elsewhere under a since-flagged-incomplete link doesn't affect this order's own completeness. That is a fact about the other order, not this one.
  • assemble_genealogy narrows on the specific key, not just ActivityLog.query's broader value match. ActivityLog.query(reference_id=value) alone only guarantees value appears somewhere in an entry's reference_ids dict, under any key. Without also passing reference_ids_key, a coincidental cross-entity collision (an order_id equal to some unrelated entry's material_id, or vice versa) would read back out as a fabricated link. This module passes both reference_ids_key and task_type straight through to ActivityLog.query (see activity-log-query-ordering-and-filtering.md) rather than pulling back every value-matching row and narrowing client-side itself. The Pitfalls in order-trail-assembly.md apply as stated there, since assemble_order_trail has no single key to narrow on. It needs an OR across several key patterns, which reference_ids_key doesn't express.
  • "Latest report wins" relies on activity_log.query's occurred_at, seq ordering (engine/activity_log.py). seq is a real Postgres sequence value assigned at insert time, so it reflects actual insertion order even when two reports for the same material land in the exact same occurred_at instant. A random UUID id as the tiebreak would be deterministic but not insertion-order-correct (see activity-log-query-ordering-and-filtering.md). The tiebreak lives in ActivityLog itself rather than this module, since it is shared infrastructure used by every Activity-Log-reading module in this codebase.

Release: v0.11.0