Workflow Versioning, Testing and Resilience

Change running processes without breaking them, and prove the failure paths work before you need them.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Workflows outlive the code that started them, so version definitions and state, keep old runs on a compatible path and replay recorded histories before release. Test with scripted models and tools, including crashes and timeouts. Retry only errors that can clear, in one layer, with growing randomized waits inside an overall deadline. Look up unknown outcomes, and escalate when automation has no safe move.

What you will learn: workflow versioning and state migration, deterministic replay and testing, retries and timeouts, recovery from stuck runs and resilient design.
Prerequisites: Durable Execution, Checkpoints and Approvals and Formal Verification and Testing Foundations.

Beginner Change and failure

Why workflows need special care

An ordinary request finishes before the next deployment. A workflow may be halfway through when you change it. It may also meet failures that a quick call never sees: a service down for an hour, an approval nobody answers, a worker replaced mid-step.

ChangeRisk to running work
Add, remove or reorder a stepReplay or position no longer matches
Rename a state or fieldSaved data cannot be read
Change a ruleOne run judged by two policies
Change a prompt or modelLater steps receive different output
Change a tool contractPending calls become invalid

Workflow versioning

StrategyHowCost
DrainStop new runs, wait for old onesSlow when runs are long
Side by sideOld runs on old workers, new on newOperate two versions
Patch in codeBranch on a recorded marker or versionBranches accumulate
MigrateConvert saved state to the new shapeNeeds careful mapping and tests
RestartCancel and start againOnly if effects can be reconciled

Temporal, for instance, documents both patching within workflow code and versioning of workers, because its replay requires code to stay compatible with recorded history. Record the definition version on every run so you can see how many remain on each before removing old code.

Change
Replay historiesold runs still fit
Test new pathsincluding failures
Release graduallywatch versions
Remove old codewhen no runs remain
The old path is deleted last, after evidence that nothing uses it.

Which changes are safe?

Judge each change against runs at every stage, not only new ones.

ChangeUsually safe?Check
Add an optional state field with a defaultOftenOld saved state loads
Change text in a notificationOftenNo code reads the text
Fix logic inside a recorded activityOftenOutput shape unchanged
Insert or reorder recorded stepsNoVersion or separate workers
Remove a stateNoNo run is in it or can reach it
Tighten a business ruleDependsWhether it applies to open runs
Change retry limits or timeoutsDependsEngine behavior and running timers

"Often" still means test it. Define compatibility in terms of your engine, since they differ in what they record.

Intermediate Testing and replay

Deterministic replay as a release test

Save histories from real or representative runs, with sensitive data removed, and run the new code against them before deploying.

"""Replay recorded histories against new workflow code before release."""

def v1(history):
    return ["fetch", "summarize", "send"]

def v2_unsafe(history):
    return ["fetch", "redact", "summarize", "send"]

def v2_patched(history):
    # new runs record the marker; old runs keep the old path
    if not history or "patch:redact" in history:
        return ["patch:redact", "fetch", "redact", "summarize", "send"]
    return ["fetch", "summarize", "send"]

RECORDED = {
    "run-1 finished": ["fetch", "summarize", "send"],
    "run-2 waiting": ["fetch"],
}

def replay(code, history):
    planned = code(history)
    for position, past in enumerate(history):
        wanted = planned[position] if position < len(planned) else "nothing"
        if wanted != past:
            return f"BREAKS at step {position + 1}: {past} != {wanted}"
    rest = planned[len(history):]
    return f"ok, next: {rest[0] if rest else 'finished'}"

for code in (v2_unsafe, v2_patched):
    print(code.__name__)
    for name, history in RECORDED.items():
        print(f"  {name:<16}{replay(code, history)}")
print("new run under patched code:", v2_patched([])[:3])

Output:

v2_unsafe
  run-1 finished  BREAKS at step 2: summarize != redact
  run-2 waiting   ok, next: redact
v2_patched
  run-1 finished  ok, next: finished
  run-2 waiting   ok, next: summarize
new run under patched code: ['patch:redact', 'fetch', 'redact']

Inserting a redaction step breaks the finished history at step two. The waiting run looks fine under the unsafe change only because it has not yet reached the changed part, which shows why you need histories that stopped at different points. The patched version keeps the old path for any run that already has history without the marker, and gives new runs the new path. This is a simplification. Real tools, including Temporal patching, decide point by point in a history, so an old run that has not yet reached the change may take the new path. Follow your engine's rules exactly.

Note a consequence for safety changes: a run kept on the old path will not redact. If a change must apply to everything, you need a migration or an explicit intervention, not just a version branch.

Runtime checks may not catch every kind of nondeterminism, so replay testing remains valuable even when the engine complains about mismatches.

What to test

LayerMethodFinds
StepsUnit tests with fake dependenciesLogic and parsing errors
PathsScripted model and tool resultsWrong routing, missing exits
FailureInjected timeouts, refusals, crashesDuplicates, stuck runs
TimeControlled clockExpiry and schedule faults
CompatibilityReplay or load old stateBreaking changes
Model behaviorRepeated evaluation on real modelsQuality regressions

Scripted tests prove the workflow handles each answer. They do not show how often a model gives each one, which is the job of Agent Testing: Unit to End-to-End.

State migration

  1. Define the new shape and a mapping from each old state, including waiting ones.
  2. Decide what to do with values that cannot be mapped.
  3. Run on a copy and compare counts and key fields.
  4. Pause affected runs, convert, verify and resume in small groups.
  5. Keep the original until verification and the rollback window pass.
  6. Do not trigger actions merely because state was rewritten.

Approvals deserve attention. If migration changes what was proposed, the old approval no longer covers it and should be requested again.

Writing a path test

A good path test names the situation, scripts every reply and states the expected end. For an onboarding flow: the document check returns "unreadable" twice; the expected result is state "needs person", two requests to the supplier, no account created and one notification to the owner. Add a controlled clock so that a three-day wait runs instantly.

Assert effects, not only the final label. A run can finish in the right state after calling the payment service twice. Fake services should record every call and its operation key, and should be able to succeed while losing the reply, because that case finds most duplicate bugs. Keep a coverage list of states, transitions and failure outcomes, and note which have no test yet.

Expert Resilience

Retry, timeout and recovery

OutcomeResponse
Temporary fault or rate limitWait and retry, honoring any delay the service gives
Rejected requestDo not retry unchanged; fix or escalate
No reply after an actionLook up the outcome by operation key
Repeated failureStop, park and alert
Deadline nearDo not start work that cannot finish
"""Retry with growing, randomized waits that respect an overall deadline."""
import random

def call_with_retry(outcomes, deadline=20.0, attempts=5, base=1.0,
                    call_time=2.0, seed=7):
    rng, clock = random.Random(seed), 0.0
    for attempt in range(1, attempts + 1):
        if clock + call_time > deadline:
            return f"deadline: stopped before attempt {attempt}"
        result = outcomes[min(attempt, len(outcomes)) - 1]
        clock += call_time
        if result == "ok":
            return f"ok on attempt {attempt} at {clock:.1f} s"
        if result == "rejected":
            return f"not retryable on attempt {attempt}"
        if result == "unknown":
            return f"outcome unknown on attempt {attempt}: look it up"
        if attempt == attempts:
            break                      # no point waiting after the last
        wait = rng.uniform(0, base * 2 ** (attempt - 1))
        clock += wait
    return f"gave up after {attempts} attempts at {clock:.1f} s"

for name, outcomes, options in [
        ("brief fault", ["busy", "busy", "ok"], {}),
        ("bad request", ["rejected"], {}),
        ("lost reply", ["busy", "unknown"], {}),
        ("long outage", ["busy"], {}),
        ("tight deadline", ["busy"], {"deadline": 7.0})]:
    print(f"{name:<15}{call_with_retry(outcomes, **options)}")

def layered(layers, tries=3):
    return tries ** layers

print("calls reaching a failing service with 1, 2, 3 retrying layers:",
      [layered(n) for n in (1, 2, 3)])

Output:

brief fault    ok on attempt 3 at 6.6 s
bad request    not retryable on attempt 1
lost reply     outcome unknown on attempt 2: look it up
long outage    gave up after 5 attempts at 13.8 s
tight deadline deadline: stopped before attempt 4
calls reaching a failing service with 1, 2, 3 retrying layers: [3, 9, 27]

The brief fault succeeds on the third attempt. The rejected request stops at once and the lost reply is looked up, not repeated. A long outage ends after five attempts, and a tight deadline stops before an attempt that could not complete. Random waits spread clients apart so they do not all return together, an approach explained in the Amazon Builders' Library. The last line shows why only one layer should retry: three attempts at each of three layers can turn one request into twenty-seven calls. The simulation assumes every call takes the same fixed time; real timeouts need to be enforced on the call itself.

Finding and recovering stuck runs

A run can be stuck without any error: waiting for an event that was lost, claimed by a dead worker or looping inside limits that are too generous. For each state, record the longest normal time and alert beyond it. Give operators a view showing state, age, last event, pending actions and version.

CauseRecovery
Lost eventRead the source record and send the event again, safely
Dead workerExpire the claim and resume from saved progress
Bad dataCorrect at the source, then retry the step
Code defectRelease a fix compatible with the history
No safe pathCompensate or complete by hand and record it

Recover a few runs first and check results before releasing the rest, and pace the release so a recovered backlog does not overwhelm a service that has only just returned.

When a workflow times out

  1. Identify which limit fired: call, step, whole run or approval.
  2. Find actions that may have happened and confirm them.
  3. Check whether the failing dependency has recovered.
  4. Resume from the last confirmed step, or compensate, or hand to a person.
  5. Tell the user the true state.
  6. Fix the cause: limit too short, step too large, missing progress signal or a hung call.

Long steps should report progress so a healthy slow task can be told from a dead one. Simply raising every timeout hides problems and ties up capacity.

Resilient workflow design

ToolPurpose
Retry with backoff and jitterRide out brief faults
TimeoutBound waiting
Operation keyMake repeats harmless
Circuit breakerStop calling a failing service
Saga compensationReverse completed steps where possible
Dead-letter queueKeep hopeless work visible
FallbackA reduced but honest result
Human escalationDecide when no automatic move is safe

A fallback must meet the same permission and data rules as the main path. A cheaper model or cached answer used silently may be worse than an honest failure.

Deadlines across steps

Give the whole run a deadline and pass the remaining time to each step. Otherwise five steps with generous individual limits can add up to far longer than anyone will wait. Reserve time for cleanup and for telling the user. When the remaining time cannot cover the next step, choose a defined outcome early: return a partial result, move the work to the background or hand it over. Retries consume the same budget, so a step with many attempts leaves less for those that follow. For long business processes, separate technical timeouts, which are about a call, from business deadlines, which are about a promise to a person.

Run failure drills

On a test environment, stop a dependency, kill workers, delay approvals and deploy mid-run. Write the expected result first. Check that alerts reach someone, the runbook works and no effect is duplicated. Repeat after major changes. See Incident Runbook and Failure Mode Catalog.

Illustrative example: the Friday deployment

A new validation step is added while hundreds of onboarding runs await documents. Replay of stored histories fails in the pipeline, so release is blocked. The team adds a version branch, runs both paths, applies the new check to old runs through a separate reviewed task and removes the old branch weeks later when none remain.

Rolling back

Going back to old code is also a change that running work must survive. Runs started on the new version may have recorded steps or fields that the old code does not understand. Before release, decide whether rollback means returning all workers, keeping new workers for new-version runs while sending fresh runs to the old version, or fixing forward. Test that choice with a history produced by the new code. Code rollback never reverses actions already taken, so list the effects of the faulty version and handle them as their own task, as described in CI/CD, Infrastructure as Code and Safe Releases.

Release evidence

Keep with each release the replayed histories and results, path and failure tests, evaluation scores for changed prompts or models, the migration check, counts of runs per version and the rollback decision. A reviewer should see what was tested and what was not. Refresh the stored histories regularly so that they include new branches, long waits and the unusual cases found in production.

Common mistakes

  • Editing workflow code without considering waiting runs.
  • Replaying only completed histories.
  • Assuming old runs receive new safety rules.
  • Retrying rejected or unknown outcomes blindly.
  • Retries in every layer.
  • Raising timeouts instead of finding the cause.
  • Failure paths that have never run.

Checklist

  • Runs record their definition version.
  • Histories from several stages are replayed before release.
  • Each change has a plan for in-flight work.
  • Migrations are rehearsed and reversible for a period.
  • Retries are classified, bounded and in one layer.
  • Unknown outcomes are reconciled.
  • Stuck runs alert and have an owner.
  • Failure drills have passed recently.

Frequently asked questions

Can I just wait for old runs to finish?

Yes, when runs are short and urgent fixes are unlikely. Long waits usually require running versions side by side.

Do prompt changes need versioning?

Yes. They can change routing and outputs. Record the version and decide whether running tasks keep the old one.

How many retries are right?

Few, chosen from the deadline, the cost of an attempt and how the service recovers. Measure how often later attempts succeed.

What belongs in a stored test history?

Each step name and result needed for replay, from runs that stopped at different points, with personal and secret data removed.

References and further reading

Next steps