CI/CD, Infrastructure as Code and Safe Releases

A one-line prompt edit can change behavior as much as a rewrite, so it deserves the same release path.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Treat code, prompts, tool definitions, model choices and configuration as one versioned release. Build it once, test it with ordinary tests and agent evaluations, deploy the same artifact through environments, expose it to a little traffic first, compare it with the current version and keep a rehearsed way back.

What you will learn: how to arrange secrets and environments, design a pipeline, describe infrastructure as code, choose between rolling, blue-green, canary and shadow releases, and make rollback real when data and long tasks are involved.
Prerequisites: Deploying Agents to Production, Agent Evaluation Framework and basic use of version control.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library. Its measurements and thresholds are invented. The pipeline fragment is a tool-neutral sketch and does not run on any particular service.

Beginner Changes, environments and secrets

What counts as a change

In ordinary software, behavior changes when code changes. In an agent system it also changes when any of these do:

1. Codeloop, parsing, retries and limits
2. Promptsinstructions and examples
3. Modelsname, version and settings
4. Toolsdescriptions, schemas and the services behind them
5. Knowledgeindexes, documents and memory rules
6. Policypermissions, approvals and filters

If any of these can be edited in a web console and go live at once, you have an untested release path. Either route the change through the pipeline or give the console its own checks, history and rollback. Versioning, Registries and Evaluation-Driven Development covers how to record what belongs to a release.

Environments, configuration and secrets

EnvironmentPurposeData and tools
LocalFast iterationFake tools, made-up data
TestAutomated checks on each changeSimulators and fixed fixtures
StagingRehearsal close to productionTest accounts of real services
ProductionReal usersReal data and actions, least privilege

Configuration is what differs between environments: addresses, limits, model names and feature switches. Keep it in version control, validate it at start-up and fail loudly if something required is missing.

Secrets are keys, passwords and tokens. Keep them in a secret manager, give each environment and service its own, prefer short-lived credentials, rotate them and never put them in images, code, prompts or logs. A model should not see a credential at all: the tool layer holds it and performs the action. See Agent Identity, Authorization and Secrets.

Production data in test

Copying real conversations into a test system spreads personal data to a place with weaker controls. Use synthetic cases, or minimize and mask real ones under an approved process (Fairness, Privacy, Data and Copyright).

Intermediate Pipelines and infrastructure

A pipeline for agents

Continuous integration checks every change automatically. Continuous delivery keeps a tested artifact ready to release. Order the stages from cheap and fast to slow and costly:

Checklint, unit, secrets
Buildone signed artifact
Scorecases and safety
Stagerehearse
Releasegradual
on: change to code, prompts, tools, config or index definition
steps:
  - check:     format, types, unit tests, dependency and secret scan
  - contract:  call each tool simulator with the declared schemas
  - build:     create the image and release manifest once
  - evaluate:  fixed cases, repeated runs, safety cases, cost and time
  - gate:      stop if a threshold fails; show the failing cases
  - stage:     deploy the same artifact, run end-to-end checks
  - approve:   required for high-risk changes
  - release:   canary steps with automatic rollback rules

Making evaluation a usable gate

  • Model output varies, so run important cases several times and judge rates, not single runs.
  • Compare with the current release on the same cases, not only with a fixed number.
  • Treat critical safety cases as must-pass; do not average them away.
  • Keep a quick subset for each change and a full set before release.
  • Cap the pipeline's model spend and cache nothing that would hide a change.
  • Review new failures, because a flaky gate that people override is worse than none.

Statistics for comparing versions are covered in Continuous Evaluation, Statistics and Scorecards, and release testing in Chaos, Recovery Testing and Release Gates.

Protecting the pipeline itself

A pipeline holds powerful credentials. Require review for pipeline changes, give each stage only what it needs, keep secrets away from jobs triggered by untrusted contributions, pin third-party build steps and record who approved each release. If a coding agent can open changes, its work passes the same review and cannot approve itself (Issue-to-Pull-Request, Debugging and TDD Workflows).

Infrastructure as code

Infrastructure as code describes queues, databases, networks, permissions and alerts in files that are reviewed and applied by a tool such as Terraform, OpenTofu, Pulumi or a cloud's own templates.

PracticeReason
Review the planned changes before applyingCatches deletion or replacement of data stores
Protect stateful resources from deletionA rename should not destroy a database
Reuse modules across environmentsStaging resembles production
Guard the tool's state fileIt may contain sensitive values
Detect manual changesDrift makes the next deployment unpredictable
Define budgets and alerts tooNew environments arrive with safeguards

Include agent-specific resources: model deployments and quotas, indexes, evaluation datasets, gateway rules and dashboards.

Three changes that need extra care

Changing the model

A newer model is not automatically better on your tasks. It may format tool calls differently, take more or fewer steps, refuse different requests or use a different number of tokens. Treat a model change as a major release:

  1. Run the full evaluation with the existing prompts and record every difference.
  2. Adjust prompts and settings on a development set, then judge once on cases you held back.
  3. Compare cost per successful task and slow-case latency, not only success.
  4. Check feature support, quota and data terms for the new model.
  5. Canary it, keeping the old model callable until the delayed outcomes look right.

Pin a specific version where the provider offers one. An alias that moves to a new version on its own is a release you did not schedule.

Refreshing knowledge

A new document batch or a rebuilt index can change answers with no code change at all. Build the new index beside the old one, check counts and permissions, run retrieval tests with known questions and then switch a pointer. Keep the previous index until you are satisfied. Routine small updates need lighter automatic checks: sudden drops in document count, empty or duplicated text and access labels that went missing.

Changing a tool

A renamed parameter or a reworded description affects how the model chooses and fills calls. Add new fields as optional, support both shapes during the transition and run selection tests that include cases where the tool should not be called (Tool Testing and Observability). When another team owns the tool, agree how they announce changes and run contract checks on a schedule so that surprises are found by tests.

Expert Release strategies and the way back

Rolling, blue-green, canary and shadow

StrategyHow it worksStrengthLimit
RollingReplace instances a few at a timeSimple, little extra capacityMixed versions with weak control of exposure
Blue-greenRun two full versions and switch trafficFast switch backDouble capacity; everyone moves at once
CanarySend a small share to the new version and grow itLimits harm and compares live behaviorNeeds routing and good measurements
ShadowCopy requests to the new version, discard its outputTests real inputs without user effectExtra cost; actions must be blocked

On Kubernetes, tools such as Argo Rollouts provide blue-green and canary rollouts with automated analysis. Managed platforms and gateways often offer weighted traffic as well.

Shadow runs must not act

A shadow copy that sends email, places orders or writes memory is a second production system. Replace every effectful tool with a recorder, use separate stores and remember that shadow traffic still processes real personal data.

Shadow results are limited for multi-step agents: once the new version chooses a different tool call, recorded replies no longer match. Use shadow runs for early decisions and simulators for whole tasks.

Keep each user on one version

Assign by task, user or tenant with a stable rule, not request by request. A conversation that jumps between prompts or tool schemas can fail in ways neither version would alone, and mixes your measurements.

Deciding to advance or roll back

Write the rules before the release. The example waits for enough requests, treats any policy violation as an immediate stop and compares success, slow-case latency and cost with the stable version.

"""Decide whether to advance a canary release (invented measurements)."""
STEPS = [5, 25, 50, 100]            # percent of traffic
RULES = {
    "min_requests": 200,
    "max_success_drop": 0.02,       # absolute
    "max_latency_ratio": 1.20,
    "max_cost_ratio": 1.15,
}


def judge(base, canary):
    if canary["violations"] > 0:
        return "rollback", ["policy violation"]
    if canary["requests"] < RULES["min_requests"]:
        return "wait", [f"only {canary['requests']} requests"]
    reasons = []
    if base["success"] - canary["success"] > RULES["max_success_drop"]:
        reasons.append(f"success {canary['success']:.1%} vs {base['success']:.1%}")
    if canary["p95"] / base["p95"] > RULES["max_latency_ratio"]:
        reasons.append(f"p95 latency x{canary['p95'] / base['p95']:.2f}")
    if canary["cost"] / base["cost"] > RULES["max_cost_ratio"]:
        reasons.append(f"cost per success x{canary['cost'] / base['cost']:.2f}")
    return ("rollback", reasons) if reasons else ("advance", [])


BASE = {"success": 0.93, "p95": 20.0, "cost": 0.040}
OBSERVED = [
    {"requests": 90, "success": 0.94, "p95": 19.0, "cost": 0.041, "violations": 0},
    {"requests": 400, "success": 0.93, "p95": 21.0, "cost": 0.042, "violations": 0},
    {"requests": 2100, "success": 0.925, "p95": 22.0, "cost": 0.049, "violations": 0},
]

if __name__ == "__main__":
    step = 0
    for window in OBSERVED:
        decision, reasons = judge(BASE, window)
        print(f"at {STEPS[step]:>3}% traffic: {decision:<8} {'; '.join(reasons)}")
        if decision == "rollback":
            print("  traffic returned to the stable version")
            break
        if decision == "advance":
            step += 1

Output:

at   5% traffic: wait     only 90 requests
at   5% traffic: advance  
at  25% traffic: rollback cost per success x1.23
  traffic returned to the stable version

The first window is too small to judge. The second passes, so traffic grows. In the third, success and latency are within limits but cost per success has risen by more than the allowed 15 percent, so the release is rolled back. A check on errors alone would have shipped it.

Be honest about what small samples can show. A few hundred requests can reveal a collapse but not a one-point change in success, and a two-point rule on such a sample will sometimes fire by chance. Choose window sizes for the smallest difference you care about, and keep rare severe failures covered by tests and guardrails rather than hoping a canary meets them.

Some outcomes arrive late: a customer reopens a ticket days later. Advance on early signals, and keep watching the delayed ones with the old version still available.

Rollback that works

Rollback returns to the last good release. It is easy to promise and often harder than expected:

ComplicationPreparation
Tasks started on the new version are still runningFinish them on their version, or define a tested migration
New checkpoint or database formatMake changes readable by both versions before using them
Memory or records written by the faulty versionTag writes with the release so they can be found and corrected
Actions already performedHave compensating steps and a way to list affected cases
Old model no longer offeredTrack retirement dates and test the successor early
Rebuilt indexKeep the previous index until the release is accepted

For databases, use the expand and contract pattern: first add the new field while old code still works, then deploy code that uses it, and only later remove the old field.

Provide a fast control for stopping harm that does not require a deployment: disable a tool, require approval for an action class or pause an agent. Rehearse both this switch and the rollback on a schedule, and time them. Promotion, Feature Flags, Rollback and Drift adds feature flags and promotion rules.

What to record for every release

  • The release identifier and everything pinned by it.
  • Evaluation results with dataset and grader versions.
  • Who approved it, when and for which environments.
  • Canary observations and the final decision.
  • The rollback target and how to invoke it.

Attach the release identifier to every trace and log entry, so that a complaint can be tied to the exact version that handled it (Agent Tracing and OpenTelemetry).

Starting small

A team without any of this can build it in order of value. First put prompts, tool definitions and configuration into version control. Next add a short set of cases that runs on every change and blocks the merge on failure. Then record the release identifier in logs and write down the rollback command. Canary routing and automated analysis come later, once traffic is large enough for them to say something. At each stage, ask what the last surprising incident would have needed in order to be caught earlier, and add that check.

Common mistakes

MistakeBetter approach
Editing prompts directly in productionRelease them with evaluation and history
Rebuilding for each environmentPromote one artifact with different configuration
Gating on one run per caseRepeat and compare rates
Watching only errors in a canaryInclude outcomes, safety, latency and cost
Letting shadow copies call real toolsRecord intended actions instead
Assuming rollback undoes actionsPlan compensation and keep an affected-case list

Checklist

  • Every behavior-changing item is versioned and passes a gate.
  • Secrets live in a manager and differ by environment.
  • One artifact moves from test to production.
  • Safety cases must pass and results are kept.
  • Infrastructure changes are planned, reviewed and protected against data loss.
  • Canary rules and sample sizes are written in advance.
  • Rollback and the stop switch have been rehearsed.
  • Traces carry the release identifier.

Frequently asked questions

Do small prompt edits need the whole pipeline?

They need a gate proportionate to risk, usually a quick regression and safety subset, plus history and rollback.

Canary or blue-green for agents?

Canary usually reveals behavior problems with less harm, while blue-green suits changes that cannot run side by side per user for long.

How can tests be stable with variable output?

Check outcomes and rules instead of exact wording, repeat important cases and use simulators with fixed data.

Can rollback be automatic?

Yes for clear signals such as violations or large metric drops, with a person reviewing ambiguous cases and delayed outcomes.

References and further reading

Next steps