Search and contents

Order-Trail Assembly: one order's story, pulled from every node that touched it

How engine/order_trail.py's assemble_order_trail implements this capability. A Node Type's Activity Log facet is the raw material for order-trail assembly; this module gathers the entries that name one order, from this Node and from every declared peer, into one coherent trail anchored to the order's own canonical IdentityRecord (docs/operations/identity-resolution-and-reconciliation.md). Sections 1 to 3 build the trail from this Node's own Activity Log and Identity Store; section 4 adds the peers, which a site whose Nodes each have a database of their own (every real appliance) needs.

1. Assemble a trail

from engine.activity_log import ActivityLog
from engine.identity_resolution import IdentityStore
from engine.order_trail import assemble_order_trail

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

trail = assemble_order_trail(
    store, activity_log, "MO-1001", single_node=True
)  # this Node's entries

trail.order_id  # "MO-1001"
trail.record  # the order's canonical IdentityRecord
trail.entries  # every ActivityLogEntry of this Node naming this order, oldest first
trail.contributing_node_types  # unique node_type values, in order of first appearance

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 entries and returns a trail that is not complete: trail.complete is false and trail.peers_not_asked_reason says that no peers were asked, because on a site whose Nodes each have a database of their own that trail is a part of the order and a caller that did not say otherwise should not read it as the whole. Passing both is refused with a ValueError.

There is no persistence or dispatch machinery of its own. assemble_order_trail is thin glue over two mechanisms:

  • IdentityStore.get_by_reference_id(EntityType.ORDER, order_id) — the order's own canonical record, the same lookup IdentityResolver/ReconciliationTask already use as their match-check.
  • ActivityLog.query(reference_id=order_id) — every entry in this Node's own Activity Log carrying this order_id somewhere in its own reference_ids, ordered by occurred_at. Called as above, with no peers, the trail holds this Node's entries alone and asks no other Node. A site's other Nodes keep their entries in databases of their own; the peers argument in section 4 is what brings them in.

Raises ValueError if no record is on file for order_id — nothing has explicitly resolved this order yet, so there's no trail to assemble.

2. A trail only ever exists for a resolved order

IdentityStore.get_by_reference_id only returns rows that carry a reference_id, and the only path that creates a PENDING record (IdentityResolver's inferred branch) never sets one — an inferred observation has no explicit reference by definition. So a record assemble_order_trail finds is always RESOLVED already; there's no separate "is this order confirmed yet" check to write or test here, unlike the Mandatory-Human Sign-off Mechanism for genuinely PENDING records.

3. A late-arriving event extends the trail — it never forks a second one

from engine.identity_resolution import EntityType, ReconciliationTask

reconciliation = ReconciliationTask(store, activity_log, "MES", "mes-2")
reconciliation.run(EntityType.ORDER, "MO-1001", {"status": "completed"})

trail = assemble_order_trail(store, activity_log, "MO-1001", single_node=True)
# trail.record.id is unchanged - the same canonical record, now with merged attributes
# trail.entries has one more entry: task_type "Reconciliation", outcome "reconciled"

Reconciliation is the shared mechanism for late-arriving events re-assembling a trail, used by order-trail assembly and Traceability alike (see engine/identity_resolution.py). A duplicate/late-arriving event routed through ReconciliationTask.run merges onto the order's one existing IdentityRecord (IdentityStore.merge_attributes's atomic jsonb || concat) rather than creating a second record — so one order_id always resolves to one IdentityRecord, and assemble_order_trail always assembles into one trail, never two. There's no separate dedup mechanism to build or test here either; it's the same guarantee docs/operations/identity-resolution-and-reconciliation.md §3 already establishes, just consumed by a second caller.

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

trail = assemble_order_trail(
    runtime.store, runtime.activity_log, "MO-1001", peers=runtime.peer_client
)

trail.complete  # False if any declared peer's part is missing
trail.not_contributed  # one PeerFetchResult per such peer: its Node Type, address, outcome
trail.local_complete  # False if the read limit cut short this Node's own entries
trail.disagreements  # Nodes whose identity records for this order differ

With peers (a PeerClient, which must log to the same activity_log you pass), the trail is built from this Node's own entries plus every declared peer's, asked over the Communication Interface, and from this Node's own identity record. Nothing is stored: a peer's entries and record exist only in the returned OrderTrail. Without peers the trail is built as in section 1 and is not complete unless the call says single_node=True, so a site whose Nodes do not share a database passes peers, and a trail that holds this Node's entries alone says so.

  • No peers asked is not the same as no peers declared. A PeerClient over a site that declares no peers (a single-Node site) is a read that asked everyone there was: the trail is complete and peers_not_asked_reason is None. A call that passed no client at all is the one that is not complete. The Management API's trail route always passes a client, and refuses a Node that declares no peers (a single-Node configuration) with a 409, so neither is changed by this.

  • 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 by a limit is in not_contributed with its outcome (PeerFetchOutcome), and complete is false. It never raises. A peer is listed if either its entries or its identity record did not arrive; its entries that did arrive stay in the trail.

  • The order of the reads. Every Node's entries are read first, then the identity record, the same order as section 1, so a reconciliation landing between them can only leave entries behind the record.

  • One deadline. deadline_seconds (default 30) bounds the asking of peers in all three fetches. The record fetch and the coverage gap check each get the time left since the entries fetch began (this Node's own read, which comes first in that fetch, counts against it), but never less than two seconds apiece, so the worst case is the deadline plus four seconds.

  • The refusals are the same, and apply to each Node's record. This Node needs a record of its own on file: a peer that holds one does not stand in for it, and the call raises ValueError "no identity record on file". A record here or on a peer that is not resolved is refused, and the message names the peer. A refusal for this Node's own record comes before any peer is asked, so nothing is requested or logged for a trail that cannot be built.

  • Records that differ are reported, not merged. record is this Node's own. disagreements lists each pair of Nodes whose status, or an attribute both hold, differs. A difference is not a missing contribution, so it does not make the trail incomplete.

  • A peer's entries are filtered as this Node's are. _entry_names_order applies to every entry, so a peer entry that carries the order id only under an unrelated key is excluded.

  • Entries from peers carry no chain hash, so a peer's entries have chain_hash and chain_prev_hash unset: a chain belongs to the Node that wrote it, and only that Node can verify it.

  • Order within one instant. Entries are ordered by occurred_at, then node_instance_id. Two entries of one Node at exactly the same occurred_at stay in the order that Node logged them, as in a single Activity Log (occurred_at, then seq). Different Nodes' databases have no common insertion order, so two entries of different Nodes at one instant are ordered by Node instance, which says nothing about which was written first. The order is the same on every run.

The narrative

The order narrative (see ai-narrative-drafting-task-wiring.md) is told when a trail is incomplete or its Nodes' records differ.

  • Sections headed "Incomplete Trail" and "Records Differ" are written by code, not by the model. They name each missing Node Type and why (a trail that asked no peers states that), and the Node Types that differ. They appear in the drafted narrative and in the fact listing used when inference is disabled.
  • The model also sees which Node Types are missing, never their addresses or the detail of a failure.
  • The entries themselves are the peers' own words and reach the model and the timeline as they are. They are not sanitized.

Coverage gaps

A coverage gap over the order makes the trail incomplete. trail.coverage_gaps lists the coverage gaps (see "Coverage gaps" in database-reference.md) that overlap the span from the order's first entry to its last. An edge that touches counts.

  • A gap is time a Node that took part could not have seen its source, so an event may have happened that no entry records. complete is false while one overlaps.
  • Gaps are kept apart from entries, so the entries are exactly the entries. A trail whose span no gap touches reports none.
  • Without peers, only the Node instances that wrote entries for the order count.
  • With peers, a peer's gaps arrive with its contribution, by the same entries request asked for by task type. A peer that cannot answer it is named in not_contributed like any other.
  • A gap that ended before the first entry, or began after the last, is not shown. A gap says nothing of how many events it hid.

5. A trail as JSON, and the cap on its entries

from engine.trace_answers import order_trail_answer

answer = order_trail_answer(trail, max_entries=2000)  # 2,000 is the default

order_trail_answer turns an OrderTrail into a dict that json.dumps accepts: the order's record (type, reference, status, attributes), the entries with the ten fields that cross the wire (never the chain hashes), the contributing Node Types, complete and local_complete, each Node that did not contribute (Node Type, address, outcome, and a reason this Node wrote, never text a peer sent), and each pair of Nodes whose records differ, by the field names and never a value.

  • The entries are oldest first. Every read of an Activity Log is in the order the entries occurred, and the entries of several Nodes are merged in that order, so the trail is a first-in, first-out record of the order.
  • Above max_entries the answer keeps the earliest. entries_total is how many the trail had, entries_omitted how many the answer left out, and truncated is true. The cap changes nothing else: complete stays the trail's own. A truncated trail can be complete, and an incomplete one can fit under the cap, so the two are separate.
  • The cap bounds the answer, not the work. The trail is assembled in full (every page of every peer, up to the fetch limits) before the cap is applied.
  • The refusals are typed. No record on file is NoIdentityRecordError, a record that is not resolved is IdentityNotResolvedError (it says whose), and an order id that is empty or holds a NUL character is InvalidOrderIdError (raised when peers are given). All are ValueErrors, subclasses of OrderRefusal, with the messages they always had, and each survives copy and pickle.

How a site asks for a trail

A person at a site asks the Node's Management API, not the library:

deployment/kindred_management.sh trail MO-1001

The route is GET /v1/orders/{order_id}/trail, behind the correlation scope. It asks the Node's declared peers as the Node does and returns the answer of this section, with the same cap on the entries. A trail with a peer's part missing is a 200 that names the peer. A site that declares no peers is refused. See Order trail and genealogy for what a peer sees, what is capped, the statuses and the audit entry each request leaves.

Pitfalls

  • assemble_order_trail reads two independently-updated stores, not one atomic snapshot. ActivityLog is queried before IdentityStore deliberately, matching Reconciliation's own write order (merge_attributes on the record, then its ActivityLogEntry) — so a reconciliation landing between the two reads can only leave entries lagging slightly behind an already-updated record, never the reverse (an entry naming a merge record.attributes doesn't reflect yet). There's still no cross-store transaction here (the same "let the database do the atomic part within one store" scope merge_attributes's own docstring already limits itself to, not a claim of cross-store atomicity), so a caller reading trail.record and trail.entries back-to-back during a live reconciliation can still observe that narrower staleness. The tests check sequential calls, not concurrent ones.
  • contributing_node_types is node_type, not node_instance_id. Two different Node instances of the same Node Type (two MES lines, say) collapse into one entry in contributing_node_types — trail.entries itself still carries each entry's own node_instance_id if that finer distinction is needed.
  • A reference value shared by coincidence, not genuine identity, must not join the trail. ActivityLog.query(reference_id=...) matches any value in an entry's reference_ids dict, under any key. Same-shaped string keys other Task modules write into reference_ids — most concretely engine/inventory_shortage.py's own material_id, a human-readable string that can coincidentally equal some other entry's order_id — would join the trail by accident. assemble_order_trail therefore narrows entries to ones that genuinely carry order_id under "order_id", an "order_id_N" key (inventory_shortage.py's own multi-order correlation keys), or "reference_id" (IdentityResolver/ReconciliationTask's own key, accepted deliberately since it's shared across every EntityType and ActivityLogEntry carries no entity_type of its own to narrow it further — excluding it would drop the Reconciliation-extends-the-trail entries this doc's own §3 worked example requires). See _entry_names_order (engine/order_trail.py) for the exact check, and tests/test_order_trail.py::test_a_coincidental_material_id_collision_does_not_join_the_trail for the test. The remaining "reference_id" ambiguity is accepted, not closed — a genuine collision between two different entities' own reference_id values is still possible, just lower probability than the open-ended "any key at all" surface this closes off.

Release: v0.11.0