Require a Reviewed Migration Plan Before AI Touches Your Schema

Your database migrations are running fine in staging, but a junior developer just asked an LLM to rewrite your core multi-tenant billing schema. The AI generated a slick SQL script that drops a foreign key constraint, renames three production-critical columns, and adds a vector extension your database cluster doesn’t support.

Worse yet, it wrapped the entire thing in a cheerful markdown block assuring you that "this change is fully backward compatible."

You don't just need a chat interface to manage configuration files, Terraform states, database migrations, and Kubernetes manifests. You need an AI Change Management Assistant that operates with the rigor of a senior site reliability engineer—someone who refuses to run raw LLM string outputs directly against your infrastructure, demands human review, computes precise AST-level diffs, and maintains an automated escape hatch when things inevitably go sideways.

If you are building autonomous developer agents or LLM-driven internal tooling, letting an LLM execute arbitrary shell commands or write directly to disk is a one-way ticket to a midnight incident response call.

Let's look at how to build an AI change management assistant from the ground up that uses structured planning, deterministic diff generation, cryptographic approvals, and bulletproof rollbacks.


📋 Table of Contents


The Architectural Flaw of "Chat-to-Execute" AI Tools

Most early attempts at AI infrastructure management rely on a naive loop: prompt the model, parse a code block from the response, and pipe it straight into subprocess.run() or an API client.

[User Prompt] ──> [LLM] ──> [Raw String Output] ──> [os.system / subprocess] ──> 💥

This pattern breaks down for three distinct reasons:

  1. Hallucinated Parameters: LLMs are probabilistic text predictors. They will happily invent CLI flags, database drivers, or Kubernetes API versions that do not exist.
  2. Missing Context Windows: An LLM rarely has the global state of your infrastructure in its active context, leading to blind modifications that violate architectural invariants.
  3. Lack of Reversibility: Even when a command succeeds, knowing how to undo it requires a state machine that tracks the exact delta between "before" and "after."

To fix this, we must shift our mental model from "The AI executes changes" to "The AI proposes state transitions, and a deterministic orchestration engine executes and guards them."


1. Structured Plan Generation with Pydantic and LLM Function Calling

Scenario: An operator asks the assistant to scale a Kubernetes deployment and update an environment variable in AWS Parameter Store. A free-form text response is useless here; you need a structured, machine-parsable execution plan that lists every discrete step, resource target, and risk level.

Why it matters: If you rely on regex parsing of markdown code blocks, your system will eventually choke on a stray backtick or a creative LLM explanation. You need strict schema enforcement at the model output boundary.

Solution: Use Pydantic models combined with modern LLM structured outputs (via OpenAI's JSON mode, Anthropic's tool use, or instructor libraries) to force the LLM to populate a rigid execution plan.

Code:

from enum import Enum
from typing import List, Optional, Dict
from pydantic import BaseModel, Field

class RiskLevel(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"

class ActionType(str, Enum):
    K8S_APPLY = "k8s_apply"
    AWS_SSM_PUT = "aws_ssm_put"
    SQL_MIGRATE = "sql_migrate"
    FILE_WRITE = "file_write"

class ChangeStep(BaseModel):
    step_id: str = Field(..., description="Unique identifier for the step, e.g., 'step-01'")
    action_type: ActionType
    target_resource: str = Field(..., description="ARN, file path, or cluster resource name")
    payload: Dict[str, str] = Field(..., description="Parameters required to execute the action")
    risk_level: RiskLevel
    description: str

class ChangePlan(BaseModel):
    plan_id: str
    summary: str
    steps: List[ChangeStep]
    estimated_duration_seconds: int
    requires_manual_approval: bool = True

Why this works: By validating the model's output against ChangePlan, you ensure that no step can be generated without an explicit action_type, a concrete target_resource, and a quantified risk_level. If the LLM tries to invent an action type not present in the ActionType enum, the validation layer catches it instantly before any infrastructure touches are even contemplated.

💡 Practical note: Always set temperature=0.0 or 0.1 when generating structural plans. You want deterministic output formatting, not creative writing.


2. Building a Deterministic Diff Engine for Non-Text Artifacts

Scenario: The AI plan dictates updating a JSON configuration blob stored in a database or modifying a complex Terraform variables file. Showing the user a raw JSON dump of the "before" and "after" makes human review tedious and error-prone.

Why it matters: Standard line-by-line Unix diffs (diff -u) fail when keys are reordered in JSON, YAML, or structured state dictionaries. A reordering of keys will trigger false-positive diffs, obscuring the actual semantic changes.

Solution: Write a deterministic diff engine that normalizes structured data (sorting keys, parsing YAML/JSON) before computing semantic diffs and rendering them into clean HTML or terminal-friendly ANSI output.

Code:

import json
import deepdiff
from typing import Any, Dict

def compute_semantic_diff(original: Dict[str, Any], proposed: Dict[str, Any]) -> Dict[str, Any]:
    """
    Computes a deep semantic diff between two dictionaries, ignoring key order
    and formatting quirks.
    """
    # deepdiff handles nested object structures, type changes, and item additions/removals
    ddiff = deepdiff.DeepDiff(
        original, 
        proposed, 
        ignore_order=True, 
        report_repetition=True,
        significant_digits=4
    )
    
    # Convert DeepDiff object to a JSON-serializable summary
    return json.loads(ddiff.to_json())

# Example usage
old_config = {"cluster": {"nodes": 3, "region": "us-east-1"}, "debug": False}
new_config = {"debug": True, "cluster": {"nodes": 5, "region": "us-east-1"}}

diff_result = compute_semantic_diff(old_config, new_config)
print(json.dumps(diff_result, indent=2))

Why this works: deepdiff isolates exact path changes (e.g., root['cluster']['nodes'] changed from 3 to 5) rather than raw string offsets. This allows your frontend to render a rich, interactive UI where operators can click into specific nodes, review tree mutations, and sign off on exact modifications.


3. Cryptographic Approvals and Identity-Bound State Machines

Scenario: An AI assistant generates a high-risk plan to drop a PostgreSQL table. A Slack notification fires off with an "Approve" button. Anyone with the webhook URL clicks it, or worse, a compromised Slack bot triggers the approval webhook automatically.

Why it matters: A chat notification with a simple boolean flag (approved: true) provides zero non-repudiation and zero authorization guarantees. In production environments, high-risk changes require cryptographic proof of human consent bound to an authenticated user identity and a specific plan hash.

Solution: Implement a finite state machine (FSM) where plans transition through explicit states (Draft -> PendingReview -> Approved -> Executing -> Completed / RolledBack). Approvals must be signed with a cryptographic token or verified session claim that includes the SHA-256 hash of the exact execution plan.

Code:

import hashlib
import hmac
import time
from typing import Literal

State = Literal["DRAFT", "PENDING_REVIEW", "APPROVED", "REJECTED", "EXECUTING", "COMPLETED", "ROLLED_BACK"]

class ChangeRequestManager:
    def __init__(self, secret_key: bytes):
        self.secret_key = secret_key

    def compute_plan_hash(self, plan_json: str) -> str:
        """Generates a deterministic SHA-256 hash of the plan content."""
        return hashlib.sha256(plan_json.encode('utf-8')).hexdigest()

    def generate_approval_token(self, plan_id: str, plan_hash: str, approver_id: str) -> str:
        """Creates an HMAC token binding the approver to a specific plan hash."""
        message = f"{plan_id}:{plan_hash}:{approver_id}".encode('utf-8')
        return hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

    def verify_approval(self, plan_id: str, plan_json: str, approver_id: str, token: str) -> bool:
        current_hash = self.compute_plan_hash(plan_json)
        expected_token = self.generate_approval_token(plan_id, current_hash, approver_id)
        return hmac.compare_digest(expected_token, token)

Why this works: If an operator approves a plan, but the underlying LLM-generated JSON changes by even a single whitespace character or parameter value between review and execution, the plan hash changes. The verification fails, halting execution immediately. This prevents race conditions and man-in-the-middle tampering of approved payloads.


4. Sandboxed Execution and Dry-Run Verification Loops

Scenario: The change plan is approved, and it’s time to apply a Terraform configuration or run an infrastructure migration script. Running it directly against production invites catastrophic failure if an edge case was missed.

Why it matters: Execution without pre-flight validation turns minor syntax or state errors into production outages. You need an automated verification loop that runs terraform plan, kubectl --dry-run=server, or database dry-runs before touching production resources.

Solution: Build an execution adapter pattern that routes each step through a dry-run phase first. If the dry-run command exits with a non-zero status code or flags destructive drift, the state machine aborts execution and flags the step as failed.

Code:

import subprocess
import logging
from typing import Tuple

logger = logging.getLogger("ChangeAssistant")

class ExecutionAdapter:
    def dry_run_step(self, action_type: str, target: str, payload: dict) -> Tuple[bool, str]:
        if action_type == "k8s_apply":
            # Use server-side dry run to validate against live cluster schema
            manifest = payload.get("manifest_path", "")
            cmd = ["kubectl", "apply", "--dry-run=server", "-f", manifest]
            
        elif action_type == "sql_migrate":
            # Run migration in a transaction rollback block if supported
            dsn = payload.get("dsn")
            migration_file = payload.get("file")
            cmd = ["psql", dsn, "--single-transaction", "-v", "ON_ERROR_STOP=1", "-f", migration_file]
            # For true dry-run in SQL, prepend BEGIN and append ROLLBACK
        else:
            return True, "No dry-run available for this action type."

        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            logger.error(f"Dry-run failed: {result.stderr}")
            return False, result.stderr
        
        return True, result.stdout

Why this works: Server-side dry runs (--dry-run=server for Kubernetes or transaction rollbacks for SQL) query the actual target environment's API server or database engine without committing state mutations. If your schema is out of date or a required Custom Resource Definition (CRD) is missing, you find out before the change touches production data.


5. Automated Rollback Manifests and Compensating Transactions

Scenario: Your migration script ran successfully, but downstream microservices immediately start throwing 500 errors because a required column was dropped prematurely. You need to undo the change instantly.

Why it matters: Expecting an LLM or an exhausted on-call engineer to write a custom rollback script under pressure leads to mistakes. Rollbacks must be planned before the change ever executes.

Solution: For every state-changing step generated by the assistant, require the generation of a compensating action or inverse manifest. If step $N$ fails or a post-execution health check fails, the orchestrator automatically executes the inverse stack in reverse order.

[Step 1: Execute] ──> [Step 2: Execute] ──> [Post-Check Fails ❌]
                                                    │
[Rollback 2: Undo]  <── [Rollback 1: Undo]  <───────┘

Code:

from pydantic import BaseModel
from typing import List, Callable, Dict, Any

class ExecutableStep(BaseModel):
    step_id: str
    forward_action: str
    forward_payload: Dict[str, Any]
    rollback_action: str
    rollback_payload: Dict[str, Any]

class RollbackEngine:
    def __init__(self):
        self.executed_steps: List[ExecutableStep] = []

    def record_execution(self, step: ExecutableStep):
        # Keep track of successfully executed steps for potential rollback
        self.executed_steps.append(step)

    def execute_rollback(self, registry: Dict[str, Callable]) -> bool:
        """
        Executes compensating actions in reverse order of execution (LIFO).
        """
        success = True
        # Iterate in reverse order (LIFO)
        for step in reversed(self.executed_steps):
            handler = registry.get(step.rollback_action)
            if not handler:
                print(f"CRITICAL: No handler found for rollback action {step.rollback_action}")
                success = False
                continue
            
            try:
                print(f"Rolling back step {step.step_id} using {step.rollback_action}...")
                handler(step.rollback_payload)
            except Exception as e:
                print(f"FATAL: Rollback failed for step {step.step_id}: {str(e)}")
                success = False
                # In production, alert PagerDuty here immediately
        
        self.executed_steps.clear()
        return success

Why this works: By treating changes through the lens of compensating transactions (borrowed from distributed systems Saga patterns), you decouple failure recovery from human intervention. If step 3 throws an exception, the engine unwinds steps 2 and 1 automatically using their pre-registered inverse payloads.


6. Audit Logging, Compliance Trails, and Non-Repudiation

Scenario: SOC2 auditors arrive and ask: "Who authorized the production database schema change on Tuesday at 3:14 AM, what exact prompt generated it, and what was the output?"

Why it matters: A standard application log file containing INFO: Change executed successfully will fail audit requirements instantly. Regulators and enterprise security teams demand end-to-end traceability linking the user prompt, the LLM response, the plan hash, the approver's identity, and the execution logs.

Solution: Store every phase of the change lifecycle as an append-only event log in a secure, write-once-read-many (WORM) storage backend or an immutable database table.

Lifecycle Phase Captured Artifact Storage Target
Ingestion Raw user prompt + user JWT/context Encrypted Audit DB
Planning Pydantic JSON schema output + prompt tokens Encrypted Audit DB
Diffing Semantic before/after JSON diff object Encrypted Audit DB
Approval Approver user ID, timestamp, HMAC token Immutable Ledger Table
Execution STDOUT, STDERR, exit codes, execution duration Object Storage / CloudWatch

Production Architecture Decisions: Choosing Your Storage and State Backends

When moving from a local prototype to a production-grade AI change management assistant, your choice of state storage dictates your system's resilience.

  • Relational Databases (PostgreSQL with JSONB): Best for storing change plans, steps, and approval metadata. PostgreSQL's strong consistency guarantees (SERIALIZABLE isolation levels) prevent race conditions where two operators attempt to approve the same plan simultaneously.
  • Event Sourcing vs. CRUD: Avoid standard CRUD updates for change requests. Treat changes as immutable event streams (PlanCreated, PlanModified, PlanApproved, ExecutionStarted, StepSucceeded, StepFailed). This guarantees that your audit trail is structurally impossible to tamper with.
  • Human-in-the-Loop Gateways: Integrate your approval flow with enterprise identity providers (OIDC/SAML) rather than chat platform accounts alone. An approval must resolve to a verified corporate email address (alice@company.com), not just a loose Slack handle.

Final Perspective

Building an AI assistant for infrastructure and code changes is fundamentally an exercise in trust reduction.

The goal of a senior engineer isn't to make the AI smarter so it never makes mistakes; the goal is to build an orchestration framework so robust that even when the LLM hallucinates a disastrous plan, the system catches it at the schema validator, rejects it at the semantic diff viewer, invalidates it at the plan-hash checker, or rolls it back automatically via a compensating transaction before anyone on the engineering team has to reach for their pager.

Post a Comment

Previous Post Next Post