← Agentic engineering

Module 6 · Data and migrations

Review a schema and a migration an agent wrote when you are not the database specialist, change a live table in add, fill, switch, remove order, prove the backup by restoring it, and run a large migration through an agent pipeline that checks every step.

Facts checked

An agent writes a migration in seconds, and it runs cleanly against the small database on your laptop. Whether it is safe depends on things that database does not have: tens of millions of rows, other sessions holding locks, and the previous version of the application still serving requests while the change goes out.

By the end of this module you can review a schema and a migration an agent wrote when you are not the database specialist, change a live table in add, fill, switch, remove order, prove a backup by restoring it, and run a migration over thousands of files through an agent pipeline that checks every step.

Before you read
1.

An agent's pull request renames the column amount to amount_cents in one migration and updates every query in the same change. All tests pass. What goes wrong when it is deployed?

2.

Last night's backup job reported success. What does that prove?

3.

A migration runs in 40 milliseconds on your development database. Which fact about production matters most to whether it is safe?

Read the schema as the person who is not the database specialist

The agent builds its schema from the ticket and from the code it has seen most often. It gets the tables and the joins right far more often than it gets the following right, and these are the risks a database specialist would look for first.

Types that lose information. Money in a floating-point column cannot hold ten cents exactly, and sums drift. Use an integer count of the smallest unit, or the database's exact numeric type. A timestamp stored without a time zone means something different on each server that reads it.

Rules the code assumes and the database does not enforce. The code checks that an email address is free and then inserts it. Two requests at once both pass the check. Only a unique constraint stops the second insert. The same goes for a column the code never leaves empty: if it must never be empty, say NOT NULL.

Indexes that matter only on large tables. In PostgreSQL, declaring a foreign key does not create an index on the referencing column. Deleting a parent row then scans the whole child table. A filter on an unindexed column is instant on two hundred rows and slow on forty million.

Deletes that cascade. ON DELETE CASCADE on a foreign key means that deleting one customer silently deletes every order that points at it. Decide each one on purpose.

The same fact stored twice. The agent adds a status column to a table when an existing table already records the same state, because it did not read that far. Search the schema for the concept before accepting a new column for it.

Ask for three things with any schema change: the change as SQL, the queries that will run against it, and the query plan for each on a copy with production's row counts. Ask for the SQL because the model file does not show what the migration tool will generate. A rename in the model can come out as a drop and an add, which loses the column's data. Prisma Migrate's documentation, read in December 2026, says that is what it generates for a renamed field unless you edit the migration.

Read the migration for what it does to a live table

Ask three questions of every migration. The examples are PostgreSQL's, as its documentation for version 19 stood in December 2026. MySQL and SQL Server answer differently, and their manuals say how.

What does it destroy? DROP, TRUNCATE and a DELETE with no WHERE are the obvious ones. A change of column type that converts the values is easier to miss: once the old values are gone, the conversion cannot be checked or reversed.

What does it lock, and for how long? Most forms of ALTER TABLE take an ACCESS EXCLUSIVE lock, under which no other transaction can use the table at all. Some finish at once. Adding a column with a constant default does not rewrite the table. Others hold the lock while they work through every row:

  • changing a column's type normally rewrites the whole table and its indexes;
  • SET NOT NULL scans the whole table, unless a valid CHECK constraint already proves there are no nulls;
  • adding a constraint scans the table, unless it is added as NOT VALID and validated afterwards with VALIDATE CONSTRAINT, which takes a lighter lock;
  • a plain CREATE INDEX blocks writes until it finishes. CREATE INDEX CONCURRENTLY does not, but it cannot run inside a transaction, and a failed build leaves an invalid index behind that has to be dropped.

Set lock_timeout at the top of the migration. A statement that cannot get its lock then gives up after a few seconds and can be retried, where otherwise it would wait behind a long query for as long as that query runs.

Which version of the application does it assume? During a deploy the previous version and the new one run side by side for a while, and after a rollback the previous version runs alone against the new schema. A migration that only works with the new code is unsafe in both situations.

The agent is unlikely to ask these questions unprompted, because its tests can pass without the answers. Put them in the brief, and ask for the answers in the pull request description.

Add, fill, switch, remove

A change to something live code reads goes out in four steps. Each step is its own pull request and its own deploy. Danilo Sato described the pattern in 2014 under the name parallel change, also called expand and contract.

Add. Create the new column or table beside the old one, allowing it to be empty. Change the code to write to both. Nothing reads the new place yet, so a rollback loses nothing.

Fill. Copy the existing rows across with a script that works in batches, commits each batch, and can be stopped and started again. It does not run inside the schema migration. Finish with a query that counts rows where the old and new values disagree, and expect zero.

Switch. Change the code to read from the new place while it still writes to both. This is still reversible, because the old place is up to date. Leave it running long enough to trust it. Only then stop writing to the old place.

Remove. Drop the old column or table in a later migration, after checking that nothing reads it. This is the only step that cannot be undone, so it waits for a restored backup.

An agent's default is one migration that does all four at once, because that is the shortest change that passes the tests. State the order in the brief, and name which of the four steps this pull request is.

flowchart LR
  A[Add<br/>new column, write both] --> F[Fill<br/>batches, count mismatches]
  F --> S[Switch<br/>read new, still write both]
  S --> R[Remove<br/>drop old, after a restored backup]
  A -. rollback loses nothing .-> A
  S -. rollback still safe .-> S

Restore drills, and backups an agent cannot delete

Until you have restored a backup, you do not know that it works. Find out with a restore drill: restore the latest backup into a scratch database, compare a few counts with production as it stood when the backup was taken, and note how long the restore took. That time is how long a real recovery would take.

Script the drill and run it on a schedule. An agent can write the script and run it against the scratch database. It does not need the production credential to do either.

Run a drill before any remove step. If a migration that drops data goes wrong, you can count only on a backup you have seen restored.

Keep the backups where the credential that can delete the database cannot delete them. In April 2026 the founder of a company called PocketOS described how a coding agent, working on a task in the test environment, found an API token in an unrelated file and used it to delete a storage volume at the company's hosting provider. The Register reported his account on 27 April 2026. The volume held the production database. It also held the backups, which that provider stored in the same volume, and all of it went in a single call that took nine seconds. The provider restored the data from its own copies. The token had been created to manage web domains, and it was valid for every operation.

A clean-up you schedule

The remove step is the one that gets skipped. After the switch the feature works, someone closes the ticket, and nobody drops the old column. GitClear's 2026 report on code maintainability, built from 623 million changes it analysed between 2023 and 2026, shows the same habit in code. Lines that were moved, its measure of refactoring, fell from 21% of changed lines in 2022 to 13% in 2023 and 3.8% in 2026 to date. Duplicated blocks rose from 40.3 per million changed lines in 2023 to 73.0 in 2026 to date, an 81% rise over 2023. GitClear sells code analytics and its page carries no publication date, so treat the figures as one vendor's telemetry.

In a database the leftovers are columns nothing reads, tables nothing writes to, indexes the database's own usage statistics show are never used, and backfills that stopped halfway. Each one costs storage and write time, and the next agent that reads the schema can take it for something in use.

Put a clean-up on the calendar, monthly for a busy schema. The agent produces the list: every column with no reference in the code, every table with no recent writes, every unused index. A person decides what goes, because a program outside the repository may read the database. Each removal is then an ordinary remove step, with its own pull request and a restored backup behind it.

Bulk migrations run by an agent pipeline

Some migrations are thousands of small changes of the same kind. Airbnb published the clearest account of running one with a language model, on 1 April 2025. It converted nearly 3,500 React test files from one testing library to another in six weeks. Its own estimate for doing the work by hand had been a year and a half of engineering time.

The engineers did not hand the job to an agent in a chat. They built a pipeline, and you can use the same design for other bulk work.

One unit at a time, through fixed steps. Each file moved through a series of steps, and moved on only when the check for the step it was on had passed: the converted test ran, then the linter and the type checker passed.

Retries with the failure attached. When a check failed, the pipeline sent the file back to the model with the error and the latest version of the file. Most of the simple and medium files that succeeded did so within ten attempts.

Context chosen per file. By the end, a prompt held between 40,000 and 100,000 tokens and pulled in as many as 50 related files, with examples of good tests from the same project.

Sample, tune, sweep. The first bulk run converted 75% of the files in four hours. The team then took the failures, tuned the prompts and scripts on a sample of each kind, and ran the remainder again. Four days of that reached 97%.

A person finishes the last files. Just under 100 files were left, some retried 50 to 100 times. Engineers fixed those by hand in about another week, starting from the pipeline's best attempt.

This was a code migration with 2025 models. The parts that carry over to a data backfill across tenants, or a library upgrade across services, are the small independent unit, a pass-or-fail check that ignores what the model says about its own work, a cap on retries, a record of each unit's state so the run can resume, and a budget for the last few percent by hand. For data, the agent writes the script and the pipeline runs it. The agent does not hold a production credential and run statements of its own. Many agents and what they cost covers supervising a run of this length.

Move a money column to integer cents on a live table

A scenario. An invoicing service stores invoices.amount as floating-point dollars, and totals have started to disagree by a cent. The table has 38,412,906 rows. The engineer who picks up the ticket builds the screens and has never run a migration on this database. Say what you would check at each step before you read it.

  1. 1 · Read what the agent proposed first

    One migration and one code change. The migration renames amount to amount_cents, then changes its type to bigint using round(amount * 100). The tests pass against a development database of 200 invoices. Ask the three questions. It destroys the original values. It rewrites all 38,412,906 rows under a lock that shuts every other session out of the table. And the version of the code running during the deploy still asks for amount.

  2. 2 · Brief it again with the order stated

    "Four pull requests: add, fill, switch, remove. This one is add only. Add amount_cents bigint, allowed to be empty. Write both columns on every insert and update. Set lock_timeout to five seconds in the migration. Do not touch amount." The migration is now one statement that adds an empty column, and it finishes at once.

  3. 3 · Fill in batches, and stop when the data raises a question

    The agent writes a backfill script: 10,000 rows per transaction by id range, with the last finished id saved so that it can resume. Its closing query counts rows where amount_cents is empty or differs from round(amount * 100). On a copy of production it reports 212 rows whose amount has a fraction of a cent, such as 19.999. Which way those round is a question for whoever owns the finance rules, and the engineer asks them. The answer goes into the script and into the pull request description.

  4. 4 · Run a restore drill before anything that cannot be undone

    Restore last night's backup into a scratch database. It holds 38,371,540 invoices, which matches the production count at the time the backup was taken. The restore takes 47 minutes, so a recovery would take at least that long. The backups sit in a separate account from the one the deploy credential belongs to.

  5. 5 · Switch the reads, then stop the old writes

    The third pull request changes every query to read amount_cents and keeps writing both columns. If totals look wrong, rolling back is safe, because amount is still current. After a week with matching totals, a small change stops writing amount. From that deploy on, a rollback to code that reads amount would show stale figures, so the pull request says so.

  6. 6 · Make the new column required without a long lock

    SET NOT NULL on its own would scan the table while holding its lock. The agent is told to add a CHECK (amount_cents IS NOT NULL) constraint as NOT VALID, validate it in a second statement, and then set NOT NULL, which can skip the scan because the validated constraint already proves there are no nulls.

  7. 7 · Look for readers outside the repository before removing

    A search of the application finds no remaining reference to amount. The engineer asks who else reads the database. The finance team's nightly export does, from a repository the agent was never shown. That export is changed and run once before the last pull request, which drops amount after a fresh restore drill.

  8. 8 · Turn the order into a check

    A continuous-integration check now fails any migration that contains DROP COLUMN, RENAME COLUMN or a type change unless the pull request names the earlier step it follows. The engineer runs it against the agent's first proposal and sees it fail. Guardrails covers building checks like this one.

Try it

Fill the gaps in this section of the rule file the agent reads before it writes a migration.

# Changing data (read before writing a migration)

- A change to a column that live code reads ships as four pull requests:
  add, ______, switch, remove. Say which one this is.
- Every migration sets ______ so that a statement which cannot get its
  lock gives up and can be retried.
- An index on a table with live traffic is built with ______, outside a transaction.
- A backfill runs in ______ that can be stopped and resumed, never inside
  the schema migration.
- `DROP`, `TRUNCATE` and a type change wait until a backup has been ______
  into a scratch database and its counts compared.
The misconception

The migration ran cleanly on the test environment, so it is safe to run on production.

Why it’s wrong

A clean run on test shows that the SQL is valid and that the new code works with the new schema. It says nothing about four things that test does not have. The table is a fraction of the size, so a statement that scans or rewrites it returns before anyone could notice a lock. Nothing else is using the table, so the lock is granted at once. One version of the code is running, where a deploy has two. And the only readers are the ones in the repository.

The agent's report has the same limit. "Migration applied, all tests pass" is true, but only of the test environment.

The correct model

Judge a migration by what it destroys, what it locks at production's size, and which versions of the code it works with. Change live data in add, fill, switch, remove order so that every step but the last can be rolled back. Before the last step, restore a backup and look for readers outside the repository.

Check yourself
  • Which three questions do you ask of a migration an agent wrote?

  • Name the four steps for changing a column that live code reads, and say which one cannot be undone.

  • In PostgreSQL, how do you make a column required on a large table without scanning it under the table's lock?

  • What does a restore drill consist of, and what two things does it tell you?

  • What did Airbnb's pipeline do when a converted file failed a check, and what happened to the files it could not finish?

Before the check

You review an agent's schema for the things a small test database will not show: types that lose information, rules the database does not enforce, missing indexes, and deletes that cascade. You read its migration for what it destroys, what it locks and which version of the code it assumes. A change to live data goes out as add, fill, switch, remove, with a restore drill before the last step and backups kept out of reach of the credential that can delete the database. Bulk work runs through a pipeline that checks each unit, caps retries and leaves the last few percent to a person.

Check yourself before you go on:

  • When was a backup of your main database last restored, and how long did it take?
  • For the last migration an agent wrote for you, could the previous version of the code have run against the new schema?
  • Which programs outside your repository read your database?
  • Which columns in your schema does nothing read any more, and who would decide to drop them?
Sources
1 lab

Labs

Lab 1

Practise this: Change a live column in four steps

Clone the starter: https://github.com/codeprepdev/agentic-engineering-lab-6-change-a-live-column-in-four-steps. It is the appointment book for four vet clinics, in Python with the standard library only, on SQLite. The front desk books from a web screen and the vets read their day from tablets. A deploy replaces one server at a time, so for a few minutes the previous release and the new one run against the same database. Run python3 -m unittest discover, then read the README and AGENTS.md.

The ticket:

Ama (practice manager): The new online booking page has to find free slots, and it can't do sums with "1h 15m". Store each appointment's length as a number of minutes.

Today the length is appointments.duration, the text the front desk typed. It moves to a new column, duration_minutes, a whole number. That is a change to a column that live code reads, so it goes out in four steps, each its own pull request: add, fill, switch, remove. Which step is running will be two settings you add to clinic/settings.py (the starter has neither yet), which book, change_length and day_list read at the moment they run:

  • DURATION_WRITES, where a length is saved: ("text",) for what the code does today,("text", "minutes") from the add step, ("minutes",) at the end;
  • DURATION_READS, where day_list reads it: "text" until the switch, then "minutes".

0. See the agent's default. Give an agent the ticket as Ama wrote it and ask for a plan, without naming the steps. Note what it proposes; do not build it. Then brief it one step at a time, naming which step this is and what it must not touch.

1. Add. A new migration adds duration_minutes, allowed to be empty, with no default and no copying. Set DURATION_WRITES = ("text", "minutes"), leave DURATION_READS = "text", and make booking and changing a length write both.

2. Fill. Write clinic/backfills/duration_minutes.py with run(conn, batch_size=200), which copies each length into minutes in batches, commits each batch, and resumes where a stopped run left off. It returns {"filled": rows it changed, "unparsed": [ids]}. Add mismatches(conn), which counts rows still to fix: minutes empty, or minutes that disagree with the text. Tell the agent to stop and report any length it cannot read rather than guess. When it does, the answer from Ama is: "Book those as 30 minutes, the standard consult, and list them in the pull request." Run it on the sample database (python3 -m clinic.seed clinic.db, then python3 -m clinic.migrate clinic.db) and expect 0 mismatches.

3. Switch. Set DURATION_READS = "minutes", still writing both. Then, as its own change, DURATION_WRITES = ("minutes",). That release still runs against a database where duration exists.

4. Remove. Run the restore drill first, python3 scripts/restore_drill.py clinic.db, on the filled sample database. Then a separate, later migration drops duration, and nothing in the code reads it. The starter's tests all stay, by name; one of them writes the old column, so it changes with the column.

Write STEPS.md with a heading for each step, Add, Fill, Switch and Remove. Under each, put what you briefed the agent and what a rollback straight after that step would leave. Under Remove, paste the restore drill's output line as printed. Leave clinic/settings.py on the final release.

Get python3 -m unittest discover passing, and read the output yourself, then upload the repository folder. The upload leaves out the .git folder, so the hidden tests see your files and no commit history. On fresh databases built from your migrations they run each step: rows booked before the add migration, the release before still booking beside the new column, the add release writing both and reading the text, the fill (every length, the unreadable ones, a server that stops it partway, a second run), the mismatch count, the switch, writing minutes only before the drop, and booking after it. They also check the two migrations, the settings you leave in place, the starter's tests (all there, none skipped) and STEPS.md.

Open the lab · needs a free Tarmac account to have your work marked