Sub topic 14
Verifying the pipeline with reruns and counts
An upsert pipeline that is wrong rarely fails loudly. It usually runs without errors and leaves duplicate rows, lost updates, or old data over new data. This chapter shows how to check a pipeline with two cheap tools: running it again and counting rows.
Prerequisites
This chapter assumes you have read the earlier chapters in this tutorial. You should know:
- How a unique constraint on
(source_system, external_id)supportsINSERT ... ON CONFLICT DO UPDATE. - Why external IDs are normalized before matching.
- How batches and duplicate keys within a batch behave.
- How a stale guard works.
You should also be able to read basic Python and SQL.
What you are trying to prove
A pipeline check should answer four questions.
- Idempotency. Does running the same input twice leave the table exactly as it was after the first run?
- Completeness. Does every incoming key end up in the target, once?
- Update behavior. When a record changes at the source, does the existing row change in place, with its internal
idkept? - Protection. Do stale records and malformed keys get rejected or ignored as designed?
Each question maps to a check you can automate. The diagram shows the order used in this chapter.
Check the input before the load
If you load through a staging table, check it for duplicate keys first. A multi-row INSERT ... ON CONFLICT DO UPDATE in PostgreSQL fails with "ON CONFLICT DO UPDATE command cannot affect row a second time" when two rows in the same statement target the same key. Finding the duplicates before the load gives you a better error than that one.
CREATE TEMP TABLE staging_customers (
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
email text
);
SELECT source_system, btrim(external_id) AS external_id, count(*) AS copies
FROM staging_customers
GROUP BY source_system, btrim(external_id)
HAVING count(*) > 1;An empty result means the batch is safe to load. Group by the normalized value (here btrim), not the raw one. 'C-1001' and 'C-1001 ' look different to GROUP BY but become the same key after normalization.
Count after the load
Counting the table is not enough on its own. A table with 2 rows could hold the right 2 rows or the wrong ones. Check that every staged key is present, and check the total separately.
-- Staged keys missing from the target. Expect zero rows.
SELECT s.source_system, btrim(s.external_id) AS external_id
FROM staging_customers s
LEFT JOIN customers c
ON c.source_system = s.source_system
AND c.external_id = btrim(s.external_id)
WHERE c.id IS NULL;
-- Keys with more than one row. Expect zero rows if the constraint exists.
SELECT source_system, external_id, count(*)
FROM customers
GROUP BY source_system, external_id
HAVING count(*) > 1;The second query should never return rows when the unique constraint is in place. Run it anyway on tables you inherit, because the constraint may be missing, or it may include extra columns that let near-duplicates through.
To compare totals, use the change in row count and not the absolute count. The target may already hold rows from earlier loads or from other source systems.
SELECT count(*) AS before_count FROM customers WHERE source_system = 'crm';
-- run the load
SELECT count(*) AS after_count FROM customers WHERE source_system = 'crm';The expected growth is the number of staged keys that were not already in the target. After a rerun of identical input, the growth must be zero.
Telling inserts from updates
Sometimes you want a per-run report of how many rows were created and how many were updated. A commonly used PostgreSQL trick returns a flag from the upsert itself.
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id, (xmax = 0) AS inserted;xmax is a system column. It is 0 for a freshly inserted row version and non-zero when the row was updated by the conflict path. The behavior is not part of the documented SQL interface, so treat it as a diagnostic and not as business logic. The portable alternative is to compare counts before and after, as shown above.
A related edge case concerns the stale guard. When the WHERE clause on DO UPDATE is false, PostgreSQL skips the update and RETURNING produces no row for that record. A load that reports fewer returned rows than input rows may be working correctly. The missing rows are the ones the guard rejected.
Automating the rerun test in Python
The following script uses SQLite (version 3.24 or later supports ON CONFLICT DO UPDATE). It normalizes keys, removes duplicates within the batch, loads twice, and then compares snapshots.
import sqlite3
UPSERT = (
"INSERT INTO customers (source_system, external_id, name, email) "
"VALUES (?, ?, ?, ?) "
"ON CONFLICT (source_system, external_id) "
"DO UPDATE SET name = excluded.name, email = excluded.email"
)
def make_db():
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"source_system TEXT NOT NULL, "
"external_id TEXT NOT NULL, "
"name TEXT NOT NULL, "
"email TEXT, "
"UNIQUE (source_system, external_id))"
)
return conn
def prepare(rows):
"""Normalize keys and keep the last row for each key."""
latest = {}
for source, ext_id, name, email in rows:
key = (source, ext_id.strip())
latest[key] = (source, ext_id.strip(), name, email)
return list(latest.values())
def load(conn, rows):
batch = prepare(rows)
with conn:
conn.executemany(UPSERT, batch)
return len(batch)
def snapshot(conn):
return conn.execute(
"SELECT id, source_system, external_id, name, email "
"FROM customers ORDER BY source_system, external_id"
).fetchall()
conn = make_db()
rows = [
("crm", " C-1001", "Ada Lovelace", "[email protected]"),
("crm", "C-1002", "Grace Hopper", None),
("crm", "C-1001", "Ada Lovelace", "[email protected]"), # duplicate in batch
]
expected = load(conn, rows)
first = snapshot(conn)
assert len(first) == expected == 2, "row count must equal distinct keys"
load(conn, rows)
assert snapshot(conn) == first, "rerun changed the table"
changed = [
("crm", "C-1001", "Ada Lovelace", "[email protected]"),
("crm", "C-1002", "Grace M. Hopper", None),
]
load(conn, changed)
after = snapshot(conn)
assert len(after) == 2, "update created a new row"
assert [r[0] for r in after] == [r[0] for r in first], "internal ids changed"
assert after[1][3] == "Grace M. Hopper", "update was not applied"
print("all checks passed")Three assertions carry the weight. Comparing full snapshots, including id, proves the rerun changed nothing. Comparing the ids after a real change proves the row was updated in place and not deleted and recreated. Checking len(first) == expected ties the row count to the number of distinct keys instead of the number of input rows (3).
Choosing what goes into the snapshot
A snapshot comparison fails if the table holds columns that change on every write, such as updated_at = now() or a version counter that increments blindly. Leave those columns out of the snapshot, or make the upsert skip writes when nothing changed, for example with WHERE customers.name IS DISTINCT FROM EXCLUDED.name OR customers.email IS DISTINCT FROM EXCLUDED.email. The second approach also avoids needless row rewrites.
Testing the guards
Run two more tests for the features added in earlier chapters.
| Test | Action | Expected result |
|---|---|---|
| Stale replay | Load a record with an older `source_updated_at` than the stored one | Row unchanged, no row returned by `RETURNING` |
| Same timestamp | Load a record with an identical `source_updated_at` and different content | Row unchanged, because the guard uses a strict `<` comparison |
| Whitespace key | Load `' C-1001'` after `'C-1001'` exists | Still one row for that customer |
| Empty key | Load a record with `external_id = ''` | Rejected by validation or a `CHECK` constraint |
| Partial failure | Make one record in a batch violate `NOT NULL` | Whole batch rolled back, table identical to before |
The same-timestamp case is a decision, not a bug. If the source can send two different versions with equal timestamps, the guard cannot tell which is newer, and you need a tie-breaker such as a version number.
The partial failure test matters because it shows whether the load runs in one transaction. In the Python script above, the with conn: block commits only if every statement succeeds. If your loader commits per row, a failure leaves the table half loaded, and a rerun then has to repair it.
Limits of these checks
- Reruns prove consistency, not correctness. A pipeline that maps
nameto the wrong column is perfectly idempotent. Spot-check a few records against the source system by hand. - Sequence gaps are normal. In PostgreSQL,
bigserialvalues are consumed even when the insert turns into an update. Do not assert that ids are contiguous or thatmax(id)equals the row count. - Concurrent runs need their own test. Start two loaders against the same batch and confirm the row count still equals the distinct key count. The unique constraint is what makes this pass.
- Deleted source records are invisible. An upsert never removes rows. If the source deletes a record, counts will show the target holding more rows than the source. Decide whether that is acceptable, and if not, add an explicit delete or soft-delete step and verify it separately.
Exercise
A loader receives 500 records, of which 480 have distinct keys. The target table was empty and has a unique constraint on (sourcesystem, externalid). After the first load, the table has 480 rows. After a rerun with the same 500 records, the table has 480 rows, but the snapshot comparison fails on one column. List two likely causes and the fix for each.
Show answer
Likely cause 1: a column that changes on every write, such as updatedat = now() or a counter, is included in the snapshot. Fix: exclude volatile columns from the snapshot, or make the DO UPDATE skip rows whose business columns have not changed, using IS DISTINCT FROM in a WHERE clause. Likely cause 2: the batch holds duplicate keys with different content, and the final stored values depend on row order, so a rerun in a different order produces different values. Fix: deduplicate the batch before loading with an explicit rule, such as keeping the record with the latest sourceupdated_at, so the result is deterministic.
Exercise
You replay an old record whose sourceupdatedat is earlier than the stored value. The upsert uses a DO UPDATE ... WHERE guard and RETURNING id. What do you expect the statement to return, and what two things do you check afterward?
Show answer
It returns no rows, because the WHERE clause is false and the update is skipped. Afterward, check that the stored row is unchanged by comparing it with a snapshot taken before the replay, and check that the table's row count is the same.