Practical technical guides / AI engineering: memory and context (server-side response chaining)

Chaining on a Stored Response Ignores Your Edited History: previous_response_id and a History Digest

Chaining on a stored response sends the provider copy of the history, so local redaction and compaction never reach the model. Chain only when a digest matches.

By Sandeep Belgavi · Published 2026-11-15

Chaining on a stored response sends the provider copy of the history, so local redaction and compaction never reach the model. Chain only when a digest matches.

Two copies of one conversation

An agent that talks to a model through a stateless chat API owns its conversation history. It sends the whole history on every request, so whatever the history says is what the model sees. If the agent removes a card number from an earlier message, or replaces twenty old turns with a summary, the next request carries the edited version and nothing else.

Response chaining changes that ownership without making it obvious. APIs such as the OpenAI Responses API can store each response on the provider side and let the next request continue it by id, with previous_response_id, sending only the new messages. The provider rebuilds the context from its own stored copy of everything that led to that response. There are now two copies of the conversation: the one in the agent's memory, which the agent edits, and the one behind the response id, which the agent cannot edit. Chaining sends the second.

At Belgavi's Book Store, the help desk agent works on cases such as CASE-5101, where Geetha writes about a refund and mentions the last four digits of a payment card. The agent's memory layer redacts card digits once a case moves past identity checks, and compacts long histories into summaries. Both features are tested, and both are silently bypassed on every request that chains on a stored response created before the edit.

The rule pydantic-ai adopted

pydantic-ai, an agent framework, exposes chaining for OpenAI models through a model setting called openai_previous_response_id. Since v2.58.0 it records a history_digest on responses it creates with that setting, and on later requests it chains only when the current local history still matches the digest; when the history has changed, it resends the full history instead. PR 12575, merged on 6 November 2026 and released in v2.67.0 on 10 November 2026, closed the remaining gap: a response that had no digest at all, for example one created without the setting or by a version older than v2.58.0, was still continued from, "so an edit to it or to the history before it never reached the model". After the fix, such a response is treated like one whose history changed, the request sends the full history, which records a digest, and the next request chains again.

The pull request description is unusually candid about the compatibility impact. Code that passes only part of a conversation, relying on the stored copy for the rest, now sends just that part when the latest response has no digest, and nothing raises an error. Its suggested migrations are to pass the full history, or to pass a concrete response id with no local message history.

The rule is general and does not need pydantic-ai. Chaining is safe only when the provider's copy and the local copy are the same conversation. A digest of the local history at the moment each response was created is a cheap way to know that.

A provider stand-in and three policies

The companion example uses an in-memory provider that stores the full context behind each response id, as a provider-side store does, and returns the context the model actually saw. The client keeps a local history and can redact or compact it. It runs four requests: the first two turns of CASE-5101, a redaction of the card digits, a third request, a compaction to the last two messages, and a fourth request.

def digest(messages):
    data = json.dumps(messages, sort_keys=True, separators=(',', ':')).encode()
    return hashlib.sha256(data).hexdigest()[:16]


class Client:
    def send(self, user_text):
        msg = {'role': 'user', 'content': user_text}
        chain = False
        if self.last and self.policy == 'always_chain':
            chain = True
        elif self.last and self.policy == 'digest':
            chain = self.last[1] is not None and self.last[1] == digest(self.history)
        if chain:
            rid, reply, seen = self.p.respond([msg], previous_response_id=self.last[0])
        else:
            rid, reply, seen = self.p.respond(self.history + [msg])
        self.history += [msg, reply]
        self.last = (rid, digest(self.history))

The digest is recorded after the reply is appended, because the next request continues from a context that includes it. A missing digest counts as a mismatch, which is the case PR 12575 fixed.

PolicyRequests after the redaction that still saw the cardMessages uploaded per request
always chain2 of 21, 1, 1, 1
chain only when the digest matches0 of 21, 1, 5, 4
never chain0 of 21, 3, 5, 4

With chaining on every request, the third and fourth requests both carried the original message with the card digits, and the fourth also ignored the compaction: the model saw the full seven-message context instead of a summary plus two messages. With the digest rule, the second request chained because nothing had changed, the third and fourth resent the edited history, and the model never saw the digits again. Never chaining is also correct, and only costs the extra upload on the second request.

What chaining actually saves

Chaining is often adopted to save tokens, so it is worth being precise. The PR author reports that on two OpenAI models a first request on an unedited history had the same input token count whether it chained or resent, with nothing cached in either case, and that the cost of resending was one larger upload: about 23 KB against 63 bytes in their measurement. That matches the general description of chaining: the model still processes the whole context; what changes is who sends it. I did not repeat that measurement and the example calls no provider. What chaining does save is request size and client bandwidth, and it lets provider-side features that need the stored response, such as reasoning items the client never receives, carry over between turns, as the provider documents for its stored responses.

So the trade is not tokens against correctness. It is upload size and provider-side continuity against control of the context. When the local history has been edited, control should win.

Memory edits that diverge the copies

Any operation that changes earlier messages makes the stored copy stale:

  • Redaction of personal data, secrets or tokens after the fact.
  • Compaction, summarisation and observation masking, where old tool output is replaced by a short note.
  • Removal of failed tool calls or of a turn the user retracted.
  • Reordering or rewriting system and developer messages between turns.
  • Restoring a conversation from a checkpoint and continuing on a different branch.

The last one is easy to miss. If an agent checkpoints at turn five, explores to turn eight, then resumes from the turn five checkpoint, its local history is the turn five history, but the most recent response id belongs to turn eight. Chaining on it continues the abandoned branch.

Implementation steps

  1. Store, with each response id, a digest of the canonical local history that the response's context corresponds to, including the reply. Use a canonical serialisation (sorted keys, fixed separators) so equal histories hash equally.
  2. Before chaining, compute the digest of the current local history and compare. Chain on equality; otherwise send the full history.
  3. Treat a missing digest as a mismatch. This covers responses created by older code, by another process, or restored from storage written before the field existed.
  4. Run every memory edit through one function that the digest check cannot miss, and log when a request falls back to a full resend, with the reason. A spike in fallbacks after a release usually means a new edit path.
  5. Decide on storage separately. If redaction exists for privacy reasons, the stored provider-side copy is itself a retention question. Check the provider's retention and deletion options for stored responses rather than assuming that not chaining makes the stored copy go away.

Failure modes

Digest over the wrong thing. Hashing only message text misses changes to tool call arguments, attachments or roles. Hash the same structure you would send.

Non-canonical serialisation. A dictionary serialised with different key order on two code paths produces different digests and disables chaining forever, which is safe but wasteful. The fallback log shows it.

Edits that happen on another replica. If two workers share a conversation, the digest must be stored with the conversation state, not in process memory.

Partial history by design. Some code deliberately sends only new messages and relies on the stored context. That is a valid design, but then local edits must not exist, and the code should say so explicitly instead of mixing both models.

When you do not need this. If you never edit history, never resume from checkpoints and never redact, chaining on every request is consistent. The digest check costs one hash per request and protects the day someone adds compaction.

Verification

The companion example pins all three policies in expected.json and its tests assert that the always-chain policy leaks the redacted digits into two later requests, that the digest policy and the no-chain policy leak into none, and that the digest policy chains only while the history is unchanged. In a real agent, the equivalent test edits a history mid-conversation against a recorded or fake provider and asserts that the next request's input contains the edited text and not the original.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/response_chain_digest. Views are my own and do not represent any employer, past or present.