Inferensys

Prompt

Agent Plan Patching Prompt for Rollback Requirement

A practical prompt playbook for generating compensation plans when an agent fails mid-execution on mutable resources and prior side effects must be undone safely.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise operational context for using the rollback compensation prompt and distinguishes it from simpler recovery strategies.

This prompt is designed for agent runtimes that operate on mutable resources—databases, file systems, cloud infrastructure, APIs with side effects—where a mid-plan failure leaves the system in an inconsistent state. Instead of aborting and leaving partial changes behind, the agent must generate a compensation plan that identifies which completed steps are reversible, determines the correct undo order, and preserves an audit trail of what was rolled back and why. Use this prompt when your agent has already detected a failure, the replanning decision has selected 'rollback' as the recovery strategy, and you need a structured, executable sequence of undo operations.

The prompt expects a detailed execution trace as input: which steps completed, what side effects they produced, the dependency graph between steps, and the nature of the failure that triggered the rollback. It produces a compensation plan with explicit undo operations ordered by reverse dependency—steps that depend on other steps must be rolled back first. Each undo operation includes the target resource, the reversal action, preconditions that must be satisfied before execution, and a verification check to confirm the rollback succeeded. The output also includes a rollback boundary marker indicating which steps are intentionally left in place because they are independent of the failed branch.

Do not use this prompt for read-only workflows, idempotent-only operations, or situations where a simple retry is sufficient. If your agent operates exclusively on immutable or stateless resources, a rollback prompt adds unnecessary complexity and latency. Similarly, if the failure is transient—a network timeout, a rate limit, a temporary unavailability—retry with backoff is the correct strategy, not compensation planning. Reserve this prompt for cases where side effects have already been committed and cannot be ignored, where the cost of inconsistent state exceeds the cost of rollback execution, and where an audit trail is required for compliance, debugging, or operator review.

PRACTICAL GUARDRAILS

Use Case Fit

Where the rollback patching prompt works and where it introduces unacceptable risk. This prompt is designed for agents operating on mutable resources where side effects must be undone cleanly—not for read-only workflows or irreversible actions.

01

Good Fit: Mutable Infrastructure with Audit Trail

Use when: The agent modifies databases, cloud resources, or file systems where every change is logged and reversible. Why it works: The prompt can trace each side effect to a specific step, generate inverse operations, and verify state consistency after rollback.

02

Bad Fit: Irreversible External Actions

Avoid when: The agent sends emails, posts to external APIs without undo endpoints, or triggers physical processes. Risk: The prompt will generate a compensation plan that looks correct but cannot actually reverse the side effect, creating a false sense of safety.

03

Required Input: Step-Level Side Effect Log

Requirement: Each executed step must record what changed, the previous state, and whether the change is reversible. Guardrail: If the agent runtime cannot provide this log, the prompt cannot produce a reliable rollback plan—escalate to human review instead.

04

Operational Risk: Partial Rollback Cascades

What to watch: A rollback step fails mid-execution, leaving the system in an inconsistent state worse than the original failure. Guardrail: The prompt must order rollback steps with dependency awareness and include a pre-rollback state snapshot for manual recovery if compensation fails.

05

Operational Risk: Audit Evidence Gaps

What to watch: The rollback plan executes but the audit trail is incomplete, making it impossible to prove what was undone to compliance reviewers. Guardrail: The prompt must include explicit audit-logging steps in the compensation plan and verify log completeness as a postcondition.

06

Boundary: When to Escalate Instead of Patch

Avoid using this prompt when: The failure involves data corruption where the original state is unknown, or when rollback would violate retention policies or regulatory requirements. Guardrail: Add a pre-patching classification step that routes these cases to human operators with full context.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your agent runtime to generate a compensation plan when a mid-plan failure requires undoing prior side effects.

This prompt template is designed to be injected into your agent's replanning module when a step failure has left the system in a partially modified state. It instructs the model to analyze the execution trace, identify which completed steps produced reversible side effects, and produce an ordered rollback sequence. The template uses square-bracket placeholders that your execution harness must populate with live data before sending the request to the model.

text
You are an agent plan patching module responsible for generating rollback and compensation plans when a mid-plan failure requires undoing prior side effects on mutable resources.

## CONTEXT
- Original Goal: [ORIGINAL_GOAL]
- Original Plan: [ORIGINAL_PLAN_STEPS]
- Execution Trace (completed steps with side effects): [EXECUTION_TRACE]
- Failed Step: [FAILED_STEP_DETAILS]
- Failure Reason: [FAILURE_REASON]
- Current System State: [CURRENT_STATE_SNAPSHOT]
- Available Rollback Tools: [ROLLBACK_TOOLS]
- Audit Requirements: [AUDIT_REQUIREMENTS]

## TASK
Generate a compensation plan that:
1. Identifies every completed step that produced a reversible side effect.
2. Determines the correct undo operation for each reversible side effect.
3. Orders rollback operations to respect dependency constraints (e.g., delete child resources before parent resources).
4. Preserves audit evidence for every rollback action taken.
5. Verifies state consistency after all rollback operations complete.

## OUTPUT SCHEMA
Return a JSON object with this exact structure:
{
  "rollback_required": true,
  "compensation_plan": [
    {
      "step_id": "string",
      "original_action": "string",
      "side_effect_description": "string",
      "reversible": true,
      "rollback_operation": "string",
      "rollback_tool": "string",
      "rollback_arguments": {},
      "depends_on": ["step_id"],
      "verification_check": "string"
    }
  ],
  "irreversible_side_effects": [
    {
      "step_id": "string",
      "side_effect_description": "string",
      "reason_not_reversible": "string",
      "recommended_mitigation": "string"
    }
  ],
  "execution_order": ["step_id"],
  "state_consistency_checks": ["string"],
  "audit_evidence_required": ["string"]
}

## CONSTRAINTS
- Do not propose rollback operations for steps that had no side effects.
- Flag any side effect that cannot be reversed and explain why.
- Order rollback steps so that no step undoes a resource that a later rollback step still depends on.
- Include a verification check for every rollback operation.
- If the failure reason indicates data corruption, prioritize restoring from the last known-good state before attempting rollback.
- If [AUDIT_REQUIREMENTS] specifies regulatory or compliance obligations, include evidence collection steps that satisfy those requirements.

To adapt this template, replace each square-bracket placeholder with data from your agent's execution harness. The [EXECUTION_TRACE] should include structured records of every completed step, its inputs, outputs, and confirmed side effects. The [ROLLBACK_TOOLS] placeholder must list the actual tool signatures available for undo operations—such as delete, restore, or revert functions—so the model can propose concrete tool calls rather than abstract descriptions. For high-risk domains like finance or infrastructure, always route the generated compensation plan through a human approval step before execution. Validate the model's output against the JSON schema before feeding it into your rollback executor, and log both the plan and the validation result for audit purposes.

IMPLEMENTATION TABLE

Prompt Variables

Every placeholder the rollback patching prompt expects. Validate each variable before injection to prevent incomplete compensation plans or unsafe undo operations.

PlaceholderPurposeExampleValidation Notes

[ORIGINAL_PLAN]

The full multi-step plan that was executing before the failure occurred, including step IDs, descriptions, and dependency edges

{"plan_id": "exec-42", "steps": [{"id": "S1", "action": "CREATE_DB", "status": "COMPLETED"}, {"id": "S2", "action": "MIGRATE_DATA", "status": "FAILED"}]}

Must be valid JSON with at least one step marked COMPLETED or PARTIAL. Reject if plan is empty or all steps are PENDING.

[FAILED_STEP_ID]

The identifier of the step whose failure triggered the rollback requirement

S2

Must match an existing step ID in [ORIGINAL_PLAN]. Reject if the step status is not FAILED, TIMEOUT, or HALLUCINATION_DETECTED.

[FAILURE_DETAILS]

Structured error object describing what went wrong, including error type, message, and any partial side effects observed

{"error_type": "DATA_CORRUPTION", "message": "Migration wrote 340 of 1200 records before crash", "partial_effects": ["TABLE_X modified", "TABLE_Y untouched"]}

Must include error_type and partial_effects array. Reject if error_type is null or partial_effects is missing when step had side effects.

[RESOURCE_STATE_SNAPSHOT]

The current state of mutable resources after the failure, captured before any rollback begins

{"resources": [{"id": "DB_MAIN", "type": "database", "state": "PARTIALLY_MIGRATED", "last_consistent_checkpoint": "2025-01-15T10:23:00Z"}]}

Must be valid JSON with at least one resource entry. Validate that resource IDs match those referenced in [ORIGINAL_PLAN] steps. Reject if snapshot timestamp is older than the last completed step timestamp.

[REVERSIBLE_ACTIONS_CATALOG]

A mapping of action types to their known undo operations, constraints, and confirmation requirements

{"CREATE_DB": {"undo": "DROP_DB", "requires_confirmation": true, "irreversible_if": "data written by subsequent steps"}}

Must be valid JSON. Validate that every action type appearing in completed steps of [ORIGINAL_PLAN] has a corresponding entry. Flag missing entries as 'unknown rollback surface' before prompt injection.

[AUDIT_TRAIL_REQUIREMENTS]

Specification for what evidence must be preserved during rollback, including log format, required fields, and retention policy

{"required_fields": ["step_id", "action", "timestamp", "rollback_operator", "evidence_hash"], "log_destination": "audit_db.rollback_log"}

Must include required_fields array. Validate that destination is a known and writable log target. Reject if required_fields is empty.

[CONSTRAINT_BOUNDARY]

Operational limits that the rollback plan must respect, including max rollback steps, time budget, and prohibited actions

{"max_rollback_steps": 10, "time_budget_seconds": 300, "prohibited_actions": ["DROP_PRODUCTION_DB"], "require_human_approval_above_risk": "HIGH"}

Must include max_rollback_steps and time_budget_seconds. Validate that prohibited_actions list does not block all known undo operations for the completed steps. Reject if time_budget_seconds is less than estimated minimum undo time.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the rollback plan generation prompt into an agent runtime with validation, retry, and human-in-the-loop controls.

The rollback patching prompt is not a standalone safety net—it must be embedded in an execution harness that gates irreversible actions, tracks side effects, and enforces compensation before proceeding. Wire this prompt into your agent runtime as a recovery path that activates when a step failure is classified as requiring rollback (as opposed to retry, skip, or abort). The harness should maintain a side-effect ledger—a structured log of every mutating operation the agent has performed, including resource identifiers, timestamps, and pre-operation state snapshots where feasible. Without this ledger, the rollback prompt cannot identify what needs compensation, and the generated plan will be incomplete or dangerous.

Validation layer: Before executing any generated rollback plan, run a structural validator that checks: (1) every reversible step in the original plan has a corresponding compensation step in the rollback plan, (2) compensation steps are ordered correctly (reverse execution order for dependent mutations, parallel where safe), (3) no compensation step introduces new irreversible side effects, and (4) the rollback plan includes an audit evidence step that records what was rolled back and why. If validation fails, do not execute—re-prompt with the specific validation errors injected into [CONSTRAINTS] and request a corrected plan. After two failed validation attempts, escalate to a human operator with the original plan, the side-effect ledger, and both rejected rollback plans for manual review.

Retry and model selection: Use a model with strong reasoning capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) for rollback plan generation—this is a high-stakes reasoning task where errors compound. Set temperature=0 or very low (0.1) to maximize deterministic, auditable output. If the model returns a malformed JSON plan that fails schema validation, retry once with the schema error injected into the prompt as a [CONSTRAINTS] amendment. Do not retry more than twice; after two schema failures, log the raw output, flag the session for human review, and halt the agent. Human-in-the-loop gate: For rollback operations that affect production data, financial records, or user-facing state, insert an approval step before execution. Present the human reviewer with: the original failed step, the side-effect ledger entries requiring compensation, the generated rollback plan, and an estimated blast radius. Require explicit approval before the harness executes any compensation step. For lower-risk environments (internal dev/staging), you may configure auto-approval with a mandatory post-rollback audit log.

Observability and logging: Instrument the harness to emit structured logs at each stage: failure classification (why rollback was chosen over retry), prompt invocation (with prompt version and input hash), validation result (pass/fail with specific violations), human approval decision (with reviewer identity and timestamp), and execution outcome (each compensation step success/failure with state verification). These logs form the audit trail required by the prompt's own output contract and are essential for post-incident review. Store the side-effect ledger and rollback plan alongside the session trace so operators can reconstruct what happened without replaying the entire agent run. What to avoid: Do not use this prompt as a substitute for idempotency design or transactional safety at the tool layer. If your tools support native rollback (database transactions, infrastructure-as-code state reconciliation), prefer those over agent-generated compensation plans. The prompt is a recovery mechanism for when native rollback is unavailable or when the agent has performed multiple cross-system mutations that must be unwound in a specific order.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules your harness must enforce before accepting the model's rollback compensation plan. Reject or retry any response that fails these checks.

Field or ElementType or FormatRequiredValidation Rule

rollback_required

boolean

Must be true or false. If true, compensation_plan must be present and non-empty.

compensation_plan

array of objects

true if rollback_required is true

Each object must have step_id, action, target_resource, and dependency_order fields. Array length must be >= 1.

compensation_plan[].step_id

string

Must match a step_id from the original plan that has reversible side effects. Regex: ^step-[a-z0-9-]+$.

compensation_plan[].action

string enum

Must be one of: delete, revert, restore, deprovision, cancel, notify, or manual_review. No other values accepted.

compensation_plan[].target_resource

string

Must be a non-empty resource identifier. Validate against known resource types in the execution environment.

compensation_plan[].dependency_order

integer >= 1

Must be a positive integer. No duplicate order values. Lower numbers execute first. Gaps allowed but must be sequential in execution.

compensation_plan[].precondition_check

string or null

If present, must describe a verifiable condition before rollback step executes. Null allowed when no precondition exists.

audit_evidence

object

Must contain original_plan_id, failure_step_id, failure_description, and timestamp fields. All string fields must be non-empty.

state_consistency_verification

array of strings

Must list at least one verifiable assertion about system state after rollback. Each string must be a testable condition, not a vague statement.

irreversible_steps

array of strings

If present, each entry must reference a step_id from the original plan. Must include reason field explaining why reversal is impossible.

human_approval_required

boolean

Must be true if any compensation step has action manual_review or if irreversible_steps is non-empty. Otherwise may be false.

estimated_rollback_duration_seconds

integer or null

If present, must be a positive integer. Null allowed when duration cannot be estimated. Harness should set a timeout guard regardless.

PRACTICAL GUARDRAILS

Common Failure Modes

Rollback plan generation fails silently when the prompt assumes perfect state tracking, complete reversibility, or unlimited context. These are the failures that surface first in production and the guardrails that catch them before side effects compound.

01

Incomplete Side-Effect Inventory

What to watch: The model generates a rollback plan that misses irreversible or hidden side effects—database writes, cache invalidations, external API calls, or file system mutations that occurred in prior steps. The compensation plan looks correct but leaves the system in an inconsistent state. Guardrail: Require the agent runtime to pass a structured side-effect log as input, not rely on the model to infer what happened. Validate that every logged side effect appears in the compensation plan output. Reject plans with unaddressed mutations.

02

Rollback Ordering Violations

What to watch: The model proposes rollback steps in an order that violates dependency constraints—undoing a resource creation before deleting dependent records, or reversing a permission grant before revoking access that relied on it. The plan reads plausibly but fails at execution time with cascading errors. Guardrail: Include explicit dependency edges in the side-effect log. Validate the rollback plan's topological ordering against those edges before execution. Flag any plan where a rollback step references a resource that hasn't been restored yet.

03

Audit Trail Gaps Under Failure

What to watch: The rollback plan executes correctly but produces insufficient evidence for compliance, debugging, or incident review. Timestamps, actor identity, before/after state, and rollback rationale are missing or scattered across unstructured text. Guardrail: Define a required audit record schema in the output contract. Validate that every rollback step produces a structured record with at minimum: step ID, action taken, timestamp, state before, state after, and rollback justification. Reject plans that don't include audit record generation as part of each compensation step.

04

Partial Rollback with Silent Residuals

What to watch: The model generates a rollback plan that successfully reverses the primary side effects but leaves residual state—orphaned resources, stale caches, unconsumed events, or dangling references that downstream systems will trip over later. The plan is marked complete but the system is not truly clean. Guardrail: Include a post-rollback state verification step in the prompt template. Require the model to enumerate what state should exist after rollback and what should not. Run a verification pass that checks for residual artifacts before declaring rollback complete.

05

Irreversible Action Blindness

What to watch: The model proposes rollback steps for actions that are fundamentally irreversible—sent emails, published messages, external API calls with no undo endpoint, or data that has already been consumed by downstream systems. The plan pretends compensation is possible when it isn't. Guardrail: Require the side-effect log to classify each action as reversible, compensatable, or irreversible. The prompt must include explicit handling rules: irreversible actions trigger escalation and human notification, not fake rollback steps. Validate that no irreversible action appears with a standard rollback operation in the output.

06

Context Window Truncation During Long Rollbacks

What to watch: For agents with many steps, the full side-effect log plus rollback plan exceeds the context window. The model silently drops earlier side effects from consideration, generating a rollback plan that only covers recent steps while ignoring older mutations. Guardrail: Implement a checkpointed rollback strategy—process the side-effect log in reverse chronological batches, generating rollback steps per batch. Validate that the total count of rollback steps matches the count of reversible and compensatable actions in the full log. Flag mismatches for human review.

IMPLEMENTATION TABLE

Evaluation Rubric

Pass/fail criteria to validate the rollback plan before integrating this prompt into a production agent harness. Each row targets a specific failure mode: incomplete side-effect tracking, unsafe ordering, missing audit evidence, or state inconsistency.

CriterionPass StandardFailure SignalTest Method

Side-Effect Inventory Completeness

Every irreversible side effect from the original plan is listed with its current state (applied, partially applied, unknown)

Missing side effects that would leave the system in an inconsistent state after rollback

Diff the rollback plan's side-effect list against the original plan's documented mutations; flag any mutation not addressed

Compensation Step Ordering

Compensation steps are ordered to reverse side effects in correct dependency sequence (last applied, first reversed) with explicit prerequisites

A compensation step appears before its prerequisite undo operation or violates resource dependency order

Topological sort of the compensation DAG; verify each step's prerequisites are satisfied by prior steps in the sequence

Idempotency Declaration

Each compensation step is marked as idempotent or non-idempotent with a retry strategy for non-idempotent operations

Non-idempotent compensation steps lack a retry guard, risking double-compensation on replay

Parse the plan for idempotency flags; confirm every non-idempotent step includes a pre-check or lock instruction

Audit Trail Preservation

The rollback plan includes instructions to preserve logs, state snapshots, and evidence from the failed execution before any undo operation

Rollback steps that destroy evidence (delete, overwrite) appear before a preservation step

Scan the plan for evidence-destructive operations; assert a preservation step precedes each one

State Consistency Verification

The plan includes a post-rollback verification step that checks the system state matches the pre-execution baseline or an acceptable safe state

No verification step exists, or the verification only checks a subset of affected resources

Extract the verification step; confirm it references all resources mutated in the original plan and defines a pass/fail condition

Partial Completion Handling

The plan explicitly addresses partially applied side effects with a decision branch: complete-then-reverse or safe-undo from partial state

Partially applied side effects are treated as fully applied, leading to incorrect compensation

Inject a test case with a partial mutation; assert the plan contains a conditional branch for partial state

Escalation Trigger Definition

The plan defines conditions under which rollback should halt and escalate to a human operator (e.g., compensation step failure, unknown state)

No escalation condition is defined, or the plan assumes all compensation steps will succeed

Parse for escalation criteria; assert at least one condition triggers human review and the plan specifies what evidence to include in the escalation

Rollback Completeness Assertion

The plan concludes with a completeness check: all identified side effects have a corresponding compensation step or an explicit justification for why reversal is not required

Side effects are listed but lack a matching compensation step without explanation

Map each side effect to a compensation step or a 'no-op with justification' entry; flag unmatched side effects as incomplete

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and minimal post-processing. Replace [TOOL_LOG] with a simple text summary of executed steps. Skip formal state verification—just ask the model to list reversible steps and order them. Accept plain-text output instead of strict JSON.

Prompt snippet

code
Given this execution log [TOOL_LOG] and failure at step [FAILED_STEP], list which prior steps had side effects and propose a rollback order.

Watch for

  • The model may skip steps that had implicit side effects (e.g., state changes not logged)
  • Rollback ordering may be logically impossible if dependencies aren't explicit
  • No verification that the proposed rollback actually restores original state
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.