Identity Column Gaps Under Bulk Insert, With Agents

A test asserts that ORDER BY id returns a contiguous run of integers. It passes with single-row inserts and fails now and then after a bulk load. Nothing is wrong with the application logic. Identity columns in PostgreSQL (SERIAL and GENERATED ... AS IDENTITY) and SQL Server (IDENTITY) promise unique, increasing values. They do not promise values without gaps, and treating those two properties as one is a common and costly mistake in data-layer tests.

The mistake spreads faster once coding agents write tests for you. An agent that sees a fixture insert three rows will often assert that the third row has id == 3, because that is the pattern it was shown. The test passes on a fresh database, then fails when another test runs first or a rollback consumes a value.

This article explains where gaps come from, how to generate test data that contains them on purpose, which assertions express what you actually mean, and what to put in your repository instructions so agent-written tests stop depending on contiguity.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Why identity columns skip values

In PostgreSQL, both SERIAL and identity columns draw from a sequence object, and nextval() is deliberately non-transactional. When an insert rolls back, the value it consumed is not returned. A failed batch, a unique-constraint violation in the middle of a multi-row insert, or an ON CONFLICT DO NOTHING that skips a row all leave holes. Sequences with a CACHE setting above 1 hand each session a block of values, and any values a session does not use are lost when it disconnects. After a crash, PostgreSQL can also skip a small range of values that were pre-logged but never used.

SQL Server caches identity values for performance, and an unexpected restart or failover can discard the unused part of the cache, which shows up as a large jump in the column. Recent versions let you turn the cache off per database with the IDENTITY_CACHE database-scoped configuration, at a cost to insert throughput.

None of this is a bug. Uniqueness and ordering are the guarantees; contiguity never was. Test data and assertions should be designed around that.

Generate gap-aware IDs on purpose

Fixtures that build IDs with range(1, n + 1) teach every test, and every agent reading those tests, that IDs are contiguous. Generating sparse IDs from a seeded random source makes gaps the normal case instead of a surprise:

import random


def sparse_ids(count: int, seed: int = 1234, max_gap: int = 1000) -> list[int]:
    """Increasing, unique IDs with gaps, reproducible from the seed."""
    rng = random.Random(seed)
    current = rng.randint(1, 100)
    ids = []
    for _ in range(count):
        ids.append(current)
        current += rng.randint(1, max_gap)
    return ids

Using a local random.Random(seed) instead of the module-level functions keeps the output stable no matter what else in the test session touches the global random state. Insert the generated values explicitly. For a PostgreSQL identity column defined as GENERATED ALWAYS, that needs OVERRIDING SYSTEM VALUE:

INSERT INTO orders (id, customer_id, total)
OVERRIDING SYSTEM VALUE
VALUES (17, 42, 99.99),
       (1048, 42, 149.00),
       (2001, 43, 75.50);

-- move the sequence past the highest injected value so later inserts do not collide
SELECT setval(pg_get_serial_sequence('orders', 'id'), (SELECT max(id) FROM orders));

pg_get_serial_sequence finds the sequence behind both serial and identity columns, so you do not have to hard-code a sequence name that differs between the two. Forgetting the setval is the classic follow-up bug: the next application insert asks the sequence for a value that a seeded row already holds. The same failure after a database restore is covered in sequence gaps that orphan FK seeds after restore.

Assert what you mean, not contiguity

COUNT(*) = MAX(id) - MIN(id) + 1 looks like an integrity check, but it only checks contiguity. Decide which invariant the test is really about:

  • Every expected row exists. Assert on business keys or on the IDs returned by the insert (RETURNING id), not on a computed range.
  • Ordering. Assert that the IDs for a batch are strictly increasing, which is what the database does guarantee for a single sequence with a positive increment.
  • Gap-free numbering is a real requirement. Invoice or cheque numbers sometimes must be gap-free. An identity column cannot provide that; it needs an application-level counter updated in the same transaction. Test that counter directly with a gap query like the one below.
-- find missing numbers in an invoice range (only meaningful for a gap-free counter)
SELECT s.n AS missing
FROM generate_series(
    (SELECT min(invoice_no) FROM invoices),
    (SELECT max(invoice_no) FROM invoices)
) AS s(n)
LEFT JOIN invoices i ON i.invoice_no = s.n
WHERE i.invoice_no IS NULL;

Scope the query to the batch the test inserted rather than the whole table, so it stays fast and does not report gaps other tests created.

Where agents get this wrong, and the rules that fix it

Agents copy what they see. If the nearest existing test asserts order.id == 1, the next agent-written test will too, and it will pass in the agent's own run on a fresh database. The failure only appears once tests run in a different order or in parallel with pytest-xdist. Put the rule where the agent reads it, for example in .github/copilot-instructions.md or your agent's repository instruction file:

## Database IDs in tests
- Never assert on the literal value of an identity/serial column (no `id == 1`).
- Use the IDs returned by the insert (RETURNING / ORM object) or assert on business keys.
- Do not assert that IDs are contiguous. Assert uniqueness and ordering only.
- Fixtures that insert explicit IDs must call setval(pg_get_serial_sequence(...)) afterwards.

Reviewing agent-written tests for this pattern is quick: search the diff for comparisons against integer literals on id columns. A short custom lint check or a grep in CI catches most of them before review.

The same idea applies when the system under test is an agent. If an agent calls a tool such as get_order(order_id), the eval dataset that drives it should use IDs taken from the seeded rows, not IDs that happened to be 1, 2 and 3 on the machine where the dataset was written. An eval that hard-codes contiguous IDs fails the moment the seed changes, and the failure looks like a model regression when it is a data problem.

Pitfalls in setup and teardown

Restarting sequences under a connection pool. ALTER SEQUENCE ... RESTART takes effect for new nextval calls, but sessions that already hold cached values (with CACHE greater than 1) keep using them. In test databases, keep sequence caches at the default of 1, or recreate the schema per test run.

Partial resets. TRUNCATE ... RESTART IDENTITY resets only sequences owned by columns of the truncated tables. Tables populated by triggers or side effects keep their old sequence positions, which produces hard-to-reproduce collisions. Truncate the full set of related tables together, or give each test run its own schema. The broader cleanup questions are in the test data lifecycle.

Parallel workers. Workers that each insert parents and children can interleave sequence values, so a child's parent ID is not "the previous ID". Always capture the parent ID from the insert. The parallel version of this problem is covered in FK integrity collapse under bulk insert parallelism.

Gaps in identity columns are normal and permanent. Generate them in your fixtures from a seed, assert uniqueness and ordering instead of contiguity, and write those rules down for the agents that now produce a share of your tests. A property-based test that feeds arbitrary sparse ID lists into your code is a good next step for confirming that nothing downstream assumes the numbers line up.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles