Agent decision events change shape with each prompt release. Upcast stored events on read with pure functions, mark missing facts unknown, never re-ask the model.
Decision events change shape faster than other events
In an event-sourced system the events are the record. An OrderPlaced event written in 2024 is read again every time a projection is rebuilt, and its schema rarely changes because the business fact it records rarely changes.
Events that record agent decisions behave differently. Each prompt release tends to add something: the model id, a prompt version, a structured reason code instead of free text, evidence references, a confidence field that is later removed. After a year the store of the Belgavi's Book Store help desk holds RefundDecided events in three shapes:
| Version | Fields | Written by |
|---|---|---|
| v1 | amount as a decimal string, free-text reason | the first agent release |
| v2 | amount_cents as an integer, reason, model id | after the currency bug fix |
| v3 | amount_cents, reason_code, reason_text, model with id and prompt_version, evidence | current release |
Projections, audits and replays all have to read all three. The tempting fixes are to rewrite the stored events in place, or to scatter if version == 1 branches across every reader. Both fail in predictable ways. The established answer from event sourcing practice is upcasting: readers ask for the latest version, and a chain of small, pure functions lifts each stored event one version at a time as it is read. This guide applies it to agent decision events. The companion example decision_event_upcasters implements the chain and tests it.
What stays deterministic
Upcasting is a read-side transformation and must be a pure function of the stored event. That rule matters more for agent events than for others, because there is a tempting impurity: calling the model again to fill a field the old event never had. Do not. If a v1 event has no prompt version, the honest value is "unknown before v3", and every consumer of the read model should be able to see that.
What stays fixed:
- Stored events are immutable. No migration rewrites them. If an event is wrong, a new compensating event says so.
- Each upcaster maps exactly one version to the next.
v1_to_v2, thenv2_to_v3. Adding v4 means adding one function, not editing the others. - Unknown facts are marked, not invented. The upcaster for v2 to v3 sets
prompt_versiontounknown-before-v3andevidenceto an empty list. - Model calls happen only when a decision is made, never on replay. A replay that calls the model is a new decision with a new outcome, which is a different event.
The chain in code
The example keeps the chain in a dictionary keyed by source version:
def v1_to_v2(event):
data = event['data']
cents = int((Decimal(data['amount']) * 100).to_integral_value())
return {**event, 'version': 2,
'data': {'amount_cents': cents, 'reason': data['reason'], 'model': None}}
def upcast(event, target=LATEST):
if event['version'] > target:
raise ValueError('event is newer than this reader; upgrade the reader first')
out = copy.deepcopy(event)
while out['version'] < target:
out = UPCASTERS[out['version']](out)
return outThree details earn their place. The conversion from a decimal string uses Decimal, because int(float('4.35') * 100) is 434, not 435. The test suite includes exactly that value. The input is deep-copied so a reader cannot mutate the cached stored event. A reader that meets a version newer than it knows refuses instead of guessing, which is the reader-first rule of any schema rollout.
The reason code is derived from the old free text by a fixed table: "Damaged on arrival" becomes DAMAGED, unknown text becomes OTHER. This is a lossy mapping and it is acceptable only because the original text is kept in reason_text.
A worked example
The example stores four events: two v1 refunds, one v2 and one v3. After upcasting, every event has amount_cents, a reason code and a model object. The projection sums refunds per case: CASE-4201 has 1,550 cents from a v1 event of 12.50 and a v2 event of 300 cents. It also counts 3 decisions with no recorded prompt version.
That count is the useful by-product. An audit that asks "which prompt version decided this refund?" gets an explicit unknown for three of four events, rather than a confident wrong answer. If the business needs the answer, the evidence is in deployment records, and a reviewed backfill event can attach it. That is a new event with its own author, not an edit.
Migration steps for an existing store
- Version every event type now. If old events have no version field, the first upcaster treats a missing version as v1 based on the event's write date or schema fingerprint. Decide that rule once and test it.
- Write the upcasters before the next producer change. Deploy readers that understand v(n+1) before any producer writes it. The refusal on newer versions protects you if the order slips.
- Record fixtures from production. Take a sample of real stored events of each version, strip personal data, and keep them as test fixtures. The test asserts that every fixture upcasts to the latest version and that projections over them match a recorded result.
- Remove version branches from readers. Each projection, report and export now reads only the latest shape.
- Decide what replay may recompute. Deterministic derived values, such as totals, can be recomputed. Model outputs cannot. Put that rule in the projection code review checklist.
Testing the chain
Upcasters are small, but they run on every read of every old event, so a bug in one corrupts every projection built after it. The tests that matter are about properties, not examples:
- Every stored version reaches the latest. One fixture per version, asserted after
upcast. When v4 arrives, the v1 fixture must still pass through all three steps. - Upcasting is idempotent at the top. An event already at the latest version comes back unchanged, so a reader that upcasts twice by accident does no harm.
- Nothing is mutated. Compare the stored list before and after a full pass. Readers often cache events, and an in-place edit would leak into the cache.
- Lossy steps keep the original. Where an upcaster derives a structured field from free text, the test asserts that the text is still present in the new shape.
- Projections match a recorded result. Rebuild the read model from the fixtures and compare it with a committed JSON file. A change to an upcaster that alters a total shows up as a reviewed diff, not as a silent change in a report.
Long chains are a performance question as well. Upcasting costs a few dictionary copies per event; for a projection rebuild over millions of events that is measurable. Cache the upcast form only in memory for the duration of a rebuild, never write it back.
Upcasting compared with the alternatives
| Approach | Strength | Cost |
|---|---|---|
| Upcast on read | stored history untouched, one function per change | every read pays the chain; long chains need tests |
| Copy-and-transform into a new stream | readers see one version; old stream archived | a migration window, two streams to reconcile |
| Rewrite events in place | simple readers | destroys the audit record; any bug is permanent |
| Version branches in every reader | no infrastructure | every new reader repeats the logic and drifts |
For agent decision events, upcast on read is the default. Use copy-and-transform when the chain grows long or slow, and do it as a reviewed migration that keeps the original stream readable.
When an agent is unnecessary
The schema churn comes from changing prompts. If a decision is made by a rule, the event records the rule version and changes only when the rule's inputs change. Where a deterministic decision table covers a class of cases, write a different event type for it, RefundDecidedByRule, and keep the agent's event for the cases that need judgement. Two stable schemas are easier to evolve than one that changes with every prompt.
Failure modes and verification
Watch for an upcaster that reads the clock or configuration, which makes replays differ by date. Watch for one that calls a service, which makes replays slow and nondeterministic. Watch for a projection that treats "unknown" as a real model id. The tests in the example check that upcasting is deterministic, that the latest version passes through unchanged, that stored events are not mutated and that a newer version is refused. Add one more in your own store: rebuild every projection from the full history in CI and compare it with the production read model on a sample of keys.