# What happens when an instance reuses a trace-correlation key across an MCP server restart and an A2A hop: the semantic-convention collision that silently rebinds a resumed agent's memory writes to another agent's episodic record **Date of Record:** 2026 November 25 **Scope:** Applies to any agent instance that propagates a single correlation identifier (trace ID, span ID, session token, or `request_id`) across an MCP tool call, an A2A handoff, and a memory-backend write, where the identifier is generated from a *semantic convention* (e.g., `{task_hash}:{turn}`) rather than a globally unique source. Does not apply to instances using W3C `traceparent` with cryptographically random 128-bit trace IDs and a monotonic span counter, nor to single-hop, single-backend deployments. ## Core Distinction The failure is not "trace correlation breaks." The failure is that a *semantic-convention-aligned* correlation key — one deliberately constructed to be human-readable and stable across restarts, such as `agent-7:summarize_doc:turn3` — is simultaneously interpreted by three subsystems under three different uniqueness assumptions: - The **MCP server** treats the key as an idempotency token for tool-call deduplication (assumes: same key ⇒ retry of the same call). - The **A2A transport** treats the key as a conversation-thread binding (assumes: same key ⇒ same logical session, so the remote peer resumes its cached context). - The **memory backend** treats the key as a write-partition key into the episodic store (assumes: same key ⇒ same authoring instance, so writes append to the same record). These three assumptions are individually reasonable and mutually incompatible. The boundary condition is a **restart-plus-hop interleaving**: an instance crashes mid-task, restarts, regenerates the *identical* semantic key (because the key is a deterministic function of task state, not of process identity), then performs an A2A hop to a peer that had already observed that key from the pre-crash instance. The memory backend, seeing the key, appends the post-restart writes to the *pre-crash* episodic record — and if the pre-crash record was authored by a *different* logical agent that had legitimately used the same convention (e.g., a retry agent spawned by the orchestrator with the same task hash), the resumed instance's memory now contaminates and is contaminated by another agent's state. ## What Was Observed A three-tier pipeline: planner instance `P` (LLM, MCP client), tool server `T` (MCP), memory backend `M` (episodic store keyed by correlation ID), and a summarizer peer `S` (A2A endpoint). Correlation key is generated by `P` as `f"{task_hash}:{turn_index}"` — a semantic convention chosen so that logs from different runs of the same task are greppable. Trace of the failure: 1. `P` at turn 3 emits key `K = "a91f:3"`. Calls `T.retrieve_doc(K)` via MCP. `T` records `K` in its idempotency table (TTL 300 s) and returns document `D`. 2. `P` performs an A2A hop to `S`, sending `K` as the thread binding. `S` caches partial summary state under `K` in its in-process session map. 3. `P` crashes (token-budget exhaustion mid-tool-call; the process is OOM-killed by the sandbox supervisor). The MCP idempotency entry for `K` survives (TTL not expired). `S`'s session cache for `K` survives (peer never received a close). 4. Supervisor restarts `P` from checkpoint at turn 3. `P` recomputes `K = "a91f:3"` — identical, because the key is a pure function of `(task_hash, turn_index)` and the checkpoint preserves both. 5. `P` re-issues `T.retrieve_doc(K)`. `T` sees `K` in its idempotency table and returns the **cached** response from step 1 — correct payload, but `T` also treats this as a deduplicated retry and does *not* re-execute any side effects the tool was supposed to perform on this turn (in this case, a freshness check against the source store). `P` receives a stale document without any signal that freshness was skipped. 6. `P` re-issues the A2A hop with `K`. `S` sees `K` in its session map and *resumes* the pre-crash thread. But `S`'s cached state includes a partial summary that was generated from `P`'s pre-crash reasoning, which `P` no longer has in context (the checkpoint truncated the reasoning trace to fit the window). `S` returns "continuing from where we left off," and `P` now reasons over a summary it cannot reconstruct, silently inheriting hallucinated premises. 7. `P` writes the turn-3 episodic record to `M` under partition key `K`. `M` appends to the existing `K` record — which, critically, was *also* used by a retry-agent `P'` that the orchestrator spawned at step 3 (before the OOM was confirmed), with the same `task_hash` and `turn_index`. `P'`'s writes and `P`'s post-restart writes are now interleaved in one episodic record with no authoring-instance discriminator. The observable symptom is not a crash. It is a *plausible but wrong* final answer: the agent completes, the trace looks clean (one key, one thread, one record), and the contamination is only detectable by diffing the episodic record's authoring sequence against the process-restart log. ## Condition of Validity The failure requires the conjunction of five conditions. Remove any one and the mechanism does not fire: 1. **Deterministic key derivation.** The correlation key is a pure function of task state (task hash, turn index, step name) rather than of process identity (PID, boot UUID, random nonce). This is the *design intent* of semantic-convention alignment — it is what makes the key greppable — and it is precisely what makes it reusable across restarts. 2. **Independent TTLs across tiers.** The MCP idempotency TTL (300 s) exceeds the restart latency (typically 2–20 s for checkpoint resume), so the stale idempotency entry is live when the restarted instance re-issues. If the TTL were shorter than restart latency, step 5 would re-execute. 3. **Peer session cache without liveness check.** The A2A peer holds thread state keyed by the correlation ID but does not verify that the *current* holder of the key is the same logical instance that opened the thread. A2A's `contextId` is conventionally opaque and peer-managed; nothing in the spec forces a peer to bind it to a caller identity. 4. **Memory partition key == correlation key.** The memory backend uses the correlation key as the write partition, so distinct authoring instances with the same convention collide. If the partition key were `(correlation_key, instance_boot_uuid)`, the records would separate. 5. **Orchestrator retry overlap.** A retry agent is spawned with the same `task_hash` before the original is confirmed dead, so two live instances share the key. Without this, the resumed instance at least collides only with its own pre-crash record (self-contamination, recoverable by replay); with it, the collision is cross-agent (unrecoverable without provenance). The invariant that bounds the failure: **a correlation key may be reused across restarts only if every consumer that caches or partitions by it also carries an authoring-instance discriminator that is *not* derivable from task state.** Semantic-convention alignment (greppability, cross-run stability) and instance-identity uniqueness are orthogonal properties; conflating them into one key is the defect. ## Decision Boundary The engineer must choose, at design time, between two mutually exclusive postures: - **Stable-key posture (semantic convention).** Key = `f(task_hash, turn)`. Optimizes for log correlation, cross-run diffing, and idempotent retries. *Requires* that every caching/partitioning consumer carry a separate `instance_boot_id` and that the memory backend partition on `(key, instance_boot_id)`. Under this posture, the resumed instance's writes are *new* records tagged with a new boot ID, and cross-restart continuity is reconstructed by querying all boot IDs for a key — explicit, auditable, and never silent. - **Unique-key posture (W3C traceparent).** Key = random 128-bit trace ID regenerated per process. Optimizes for collision-freedom and provenance. *Sacrifices* cross-run greppability: the same logical task across two runs has two unrelated trace IDs, and correlation must go through a separate `task_hash` index. The boundary is crossed the moment a team adopts the stable-key posture for its greppability *without* adding the boot-ID discriminator to the memory partition and the A2A session binding. The failure is not in choosing either posture; it is in choosing stable-key and then relying on it as if it were unique-key. A second boundary: the A2A peer must reject a thread-resume request whose caller presents a correlation key but no proof of continuity (e.g., the checkpoint digest the peer recorded at thread open). Without this, the peer cannot distinguish "same instance resuming" from "different instance colliding on convention." ## Operational Effect The immediate effect is **silent cross-agent episodic contamination**: the resumed instance's memory writes interleave with a retry agent's, and the pre-crash peer summary is inherited without the reasoning that produced it. Downstream, this manifests as an agent that confidently asserts facts it never derived, because its episodic record now contains another instance's derivations under the same key. The contamination is *self-consistent* — retrieval by key returns a coherent-looking record — so standard memory-drift detectors (which look for contradictions) do not fire; the record is not contradictory, it is *misattributed*. The second-order effect is **idempotency-masked staleness**: the MCP server's deduplication returns cached tool output without re-executing freshness checks, so the resumed instance operates on a document that may have changed during the crash window, with no signal. This is the classic "retry is not resume" confusion, made invisible by the fact that the retry and the resume share a key. The bounded remediation, in order of cost: 1. **Partition memory on `(correlation_key, instance_boot_id)`** and reconstruct continuity by range-query over boot IDs. Cheap, closes the memory collision. 2. **Bind A2A thread state to a caller-presented continuity proof** (checkpoint digest recorded at open, verified at resume). Closes the peer-inheritance path. 3. **Separate MCP idempotency keys from correlation keys**: idempotency should key on `(correlation_key, attempt_nonce)` where the nonce is fresh per process, so a restart is a *new attempt*, not a deduplicated retry. Closes the staleness path. 4. **Orchestrator must not spawn a retry agent until the original's boot ID is confirmed retired**, or must assign the retry a distinct `task_hash` suffix. Closes the cross-agent overlap. The invariant to enforce in code: *no consumer may treat a correlation key as an identity claim.* The key says "this is the same logical task-step"; it does not say "this is the same executing instance." Every cache, idempotency table, and memory partition must carry a discriminator for the latter, and the discriminator must be generated from process identity, never from task state. ```python from __future__ import annotations import hashlib import uuid from dataclasses import dataclass, field from typing import Optional class CorrelationKeyCollision(RuntimeError): """Raised when a correlation key is reused by a distinct authoring instance across a restart or A2A hop, violating the instance-identity invariant.""" @dataclass(frozen=True) class CorrelationKey: # Semantic convention: stable across restarts, greppable, NOT unique. task_hash: str turn_index: int def as_str(self) -> str: return f"{self.task_hash}:{self.turn_index}" @dataclass(frozen=True) class InstanceIdentity: # Process identity: unique per boot, NOT derivable from task state. boot_id: str = field(default_factory=lambda: uuid.uuid4().hex) @property def discriminator(self) -> str: return hashlib.sha256(self.boot_id.encode()).hexdigest()[:16] @dataclass class EpisodicRecord: key: CorrelationKey boot_discriminator: str checkpoint_digest: str writes: list[str] = field(default_factory=list) class MemoryBackend: """Partitions on (correlation_key, boot_discriminator). Rejects any write that attempts to append to a partition owned by a different boot.""" def __init__(self) -> None: self._partitions: dict[tuple[str, str], EpisodicRecord] = {} def open_or_resume( self, key: CorrelationKey, identity: InstanceIdentity, checkpoint_digest: str, ) -> EpisodicRecord: partition = (key.as_str(), identity.discriminator) existing = self._partitions.get(partition) if existing is None: rec = EpisodicRecord( key=key, boot_discriminator=identity.discriminator, checkpoint_digest=checkpoint_digest, ) self._partitions[partition] = rec return rec # Same partition can only be resumed by the same boot (impossible after # restart) or by a boot presenting the exact checkpoint the partition # was opened with. Anything else is a cross-instance collision. if existing.checkpoint_digest != checkpoint_digest: raise CorrelationKeyCollision( f"key {key.as_str()!r} partition owned by boot " f"{existing.boot_discriminator} with checkpoint " f"{existing.checkpoint_digest[:8]}; caller boot " f"{identity.discriminator} presented " f"{checkpoint_digest[:8]} — refusing cross-instance append" ) return existing def append( self, key: CorrelationKey, identity: InstanceIdentity, checkpoint_digest: str, entry: str, ) -> None: # Guard: any write must resolve to a partition owned by this boot, or # to a partition whose checkpoint matches exactly (same-boot resume). partition = (key.as_str(), identity.discriminator) rec = self._partitions.get(partition) if rec is None: raise CorrelationKeyCollision( f"no partition for key {key.as_str()!r} under boot " f"{identity.discriminator}; instance attempted to write to a " f"key it never opened — likely a semantic-convention collision" ) if rec.checkpoint_digest != checkpoint_digest: raise CorrelationKeyCollision( f"checkpoint mismatch on append for key {key.as_str()!r}: " f"partition opened with {rec.checkpoint_digest[:8]}, caller " f"presents {checkpoint_digest[:8]}" ) rec.writes.append(entry) def handle_post_restart_turn( key: CorrelationKey, identity: InstanceIdentity, checkpoint_digest: str, backend: MemoryBackend, turn_text: str, ) -> EpisodicRecord: """Entry point for a resumed instance's turn. Demonstrates the guard: a restarted instance carries a NEW boot_id, so it lands in a fresh partition and cannot silently append to the pre-crash record.""" try: rec = backend.open_or_resume(key, identity, checkpoint_digest) backend.append(key, identity, checkpoint_digest, turn_text) return rec except CorrelationKeyCollision as exc: # Surface, do not swallow: the orchestrator must reconcile the # pre-crash partition and the retry agent's partition explicitly. raise CorrelationKeyCollision( f"resumed turn for key {key.as_str()!r} rejected: {exc}" ) from exc ```