Distinguish workflow correlation, immediate causation, delivery attempts and effect identity across agent and tool boundaries.
Preserve the reason a message exists
An agent can turn one request into several tool calls, retries, review steps and follow-up tasks. A shared correlation identifier lets an operator collect those records. It does not explain which record caused which other record. For that, retain a causation identifier pointing to the immediate triggering message. The two identifiers answer different questions: which workflow does this belong to, and what made it happen?
This guide uses a synthetic artifact analysis service. A request starts an analysis, a classifier proposes a tag, a tool records that tag and a watcher requests another analysis. No real users, files or external services are involved. The interesting failure is a feedback loop in the message graph. If a tool drops the lineage fields, the loop becomes difficult to distinguish from independent requests.
Enterprise Integration Patterns describes correlation identifiers for matching replies to requests. We extend that idea into an explicit application envelope that survives agent and tool boundaries. W3C Trace Context serves a related observability purpose, but application message identity should not depend on whether tracing was sampled, retained or exported successfully.
Give each identifier one job
A message identifier names one logical message. A correlation identifier names the overall operation. A causation identifier names the immediate input that produced the message. An attempt identifier names one delivery or processing attempt. An idempotency key names an effect that must not be applied repeatedly. Combining all five into a session identifier hides important differences.
A queue redelivery normally retains the original message identifier while receiving a new attempt identifier. A handler creating a new message gives it a new message identifier, carries the correlation identifier forward and sets causation to the input message identifier. Retrying transport must not create a new application operation merely because a network request received a new request ID.
Choose identifiers that contain no personal data or credentials. A random opaque value is adequate for this example. Identifiers are references, not evidence of authorization. An external client can invent a correlation string; the ingress adapter should validate its shape and decide whether to preserve it as an external reference while assigning an internal root. Do not let an arbitrary supplied identifier select another caller's state.
Follow a concrete message chain
Let M1 be an AnalyzeArtifact request with correlation C1 and no parent. The classifier emits M2, TagProposed, with correlation C1 and causation M1. The tag writer emits M3, TagRecorded, with correlation C1 and causation M2. A watcher emits M4, AnalyzeArtifact, with correlation C1 and causation M3. Looking only at correlation finds all four records; following causation reconstructs their direction.
Suppose the tag writer invents correlation C2 and drops causation on M3. The watcher still works, and the system may appear healthy. But the visible graph has two roots. An operator investigating C1 cannot find the downstream reanalysis without searching by artifact digest. That search can accidentally join unrelated analyses of the same artifact. Lineage should be preserved by the adapter, rather than reconstructed later from payload coincidence.
Now suppose M2 is delivered twice. Two processing attempts do not imply two classifier decisions. Keep both attempt records, but one logical M2. If both attempts execute the tag write, the effect adapter must recognize the same idempotency key. Correlation alone cannot suppress duplicates because a legitimate workflow may contain many writes with the same correlation identifier.
Build envelopes outside the prompt
The application creates identity fields after accepting a model proposal. The model should not choose its parent, reset its depth or claim membership in a more privileged workflow. A tool result may contain text that looks like an envelope; treat that as result data until a trusted adapter constructs the actual next message.
# Author: Sandeep Belgavi. Original envelope example.
from dataclasses import dataclass
from uuid import uuid4
@dataclass(frozen=True)
class Envelope:
message_id: str
correlation_id: str
causation_id: str | None
kind: str
depth: int
def child(parent, kind):
if parent.depth >= 12:
raise ValueError("lineage depth budget exhausted")
return Envelope(uuid4().hex, parent.correlation_id,
parent.message_id, kind, parent.depth + 1)The depth limit is an application policy, not a property of UUIDs or distributed tracing. Its value should reflect the workflow. A legitimate multi-step analysis may exceed a small fixed budget. Treat exhaustion as a diagnosable outcome with a recovery path, rather than silently discarding work. Persist the parent link with the outgoing message so a process crash cannot erase the explanation for a later action.
Handle fan-out and joins without inventing a parent
Fan-out is straightforward: every child points to the input that caused it. A join is different because several inputs contribute to one result. A single causation field can identify the event that completed the join, but it cannot describe all contributing evidence. Store a bounded causes list or a separate relation table for multi-parent joins, and document what the singular field means.
For example, M8 completes an analysis that required M6 and M7. If causation is M7 because it arrived last, also retain the relationship from M6 to M8. Otherwise the graph makes the first contribution invisible. Avoid storing an entire ancestry chain in every envelope: it grows with workflow depth and leaks more context across boundaries than necessary. Persist immediate edges and query the graph when needed.
Trace spans can link separate asynchronous operations while the application graph retains durable message relationships. Do not force every delayed task into one indefinitely open span. Keep trace identifiers as additional telemetry context, with clear retention and sampling assumptions. A missing trace should reduce observability detail, not remove the ability to determine the parent of a persisted command.
Detect loops using policy as well as lineage
A cycle in workflow behavior does not necessarily form a literal cycle of message IDs. Each pass may create new IDs, producing a long chain instead. In the artifact example, TagRecorded repeatedly causes AnalyzeArtifact, which produces another identical tag. Counting unique message identifiers would miss the loop because all identifiers are new.
One policy can reject a repeated combination of handler, artifact revision and requested operation within a lineage. Another can cap depth or total admitted work. These policies have different false positives. A retry after a transient scan failure may be valid; a new artifact revision may legitimately restart the analysis. Encode these distinctions explicitly, and record which policy rejected a message.
Lineage is evidence for the policy, not the policy itself. It also cannot prevent a malicious or buggy downstream service from emitting disconnected roots. Boundary validation, per-principal budgets and allowed event types remain necessary. Never infer that an action is safe merely because it has a plausible parent identifier.
Migrate existing handlers without losing history
Start at ingress and add envelope fields to stored messages. Preserve legacy request IDs in a separate field when their meaning is ambiguous. Update tool adapters and queue publishers next, because those are common points where a clean root becomes an unconnected child. Introduce validation in observation mode before rejecting old producers that have not migrated.
For messages with no known parent, label the ancestry unknown. Do not invent a parent by picking the most recent request with the same artifact. Such guesses create convincing but false explanations. A migration dashboard should count missing correlation, missing expected causation and invalid parent references separately.
Add a version to the envelope contract and retain the original producer name. Keep payload logging limited: reconstructing lineage rarely requires full prompts, file contents or tokens. A graph of opaque identifiers, event kinds and timestamps can answer many operational questions without turning diagnostics into a second sensitive datastore.
Test the graph rather than its appearance
Create fixtures for a straight chain, fan-out, a multi-parent join, queue redelivery and a tool that omits identity fields. Assert that every non-root message has a valid parent or an explicit unknown-ancestry label. Verify that child messages preserve correlation, that attempts do not masquerade as new logical messages, and that the graph traversal terminates on malformed cycles.
Test the loop policy against both repeated work on one revision and legitimate work on a newer revision. Also test missing parents after retention expiry; a graph reader should return an incomplete result instead of hanging or pretending the chain is complete. The operational gain is a reliable explanation of why work occurred. That gain comes from disciplined adapters and persisted contracts, with agents participating inside the same rules as other software.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.