The situation
The orders table is refreshed from batches sent by the order system. A batch contains every order that was created or changed since the previous one.
An AI assistant wrote the load in the answer cell. It has run for a week. The row
count after each load is exactly what the order system reports, so the check passes.
Customer support now says that orders delivered days ago still show as PLACED.
Find the bug and fix it.
Input tables
target_orders
The table as it is before the load. One row per order.
batch_orders
The incoming batch. It can contain new orders, newer versions of orders the target already has, the same order more than once, a row the target already has (the order system re-sends on a timeout), and a version that is older than what the target has (a delayed message).
Both tables have the same columns:
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT | The order. Never NULL. |
status |
STRING | PLACED, PACKED, SHIPPED, DELIVERED or CANCELLED. |
amount |
DECIMAL(10,2) | The order value. It can change between versions. |
updated_at |
TIMESTAMP_NTZ | When this version of the order was saved. |
Two versions of an order with the same updated_at are identical in every column.
Requirement
Return the orders table as it should be after the load.
- One row per
order_idfound in either table. - For each order, keep the version with the latest
updated_at, whichever table it is in. A batch row that is older than the target's row changes nothing. - All four columns come from that one version.
Expected output
One row per order.
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT | |
status |
STRING | |
amount |
DECIMAL(10,2) | |
updated_at |
TIMESTAMP_NTZ |
The AI-written code
def solve(spark): """Apply the incoming batch to the orders table.""" target = spark.table("target_orders") batch = spark.table("batch_orders") # Orders in the batch that the target does not have yet new_orders = batch.join(target, on="order_id", how="left_anti") # Add them to the existing orders result = target.unionByName(new_orders) return result
Explanation
Show explanationGives the answer away. Try the problem first.
The bug
new_orders = batch.join(target, on="order_id", how="left_anti")
result = target.unionByName(new_orders)
A left anti join keeps the rows of the left table that have no match in the
right table. So new_orders is the batch rows whose order_id is not in the target
yet. Those are appended.
Every batch row whose order_id is already in the target is thrown away by that
same join. That includes every update. The load inserts and never updates.
The batch has 69 rows for 64 orders. 20 orders are new. The other 44 already exist, and 23 of them have a newer version in the batch. All 23 keep their old row: 22 have the wrong status and 5 the wrong amount.
Why it got through:
- The row count is right. 100 existing orders plus 20 new ones is 120, which is what the order system reports. An insert-only load and a correct upsert produce the same number of rows.
- On the first run against an empty table, everything is "new", so the output is perfect.
- New orders do arrive, so the table visibly changes after every load.
A row count tells you about inserts. It cannot tell you anything about updates.
The fix
Stop thinking of "the target" and "the batch" as different kinds of thing. Both are piles of order versions. Put them together and keep the latest version of each order:
all_versions = target.unionByName(batch)
latest_first = Window.partitionBy("order_id").orderBy(F.col("updated_at").desc())
result = (
all_versions.withColumn("version_rank", F.row_number().over(latest_first))
.where(F.col("version_rank") == 1)
.drop("version_rank")
)
One rule covers every case in the batch:
| In the batch | Rows | What the rule does |
|---|---|---|
| A new order | 20 | Its only version wins. |
| A copy of a row the target already has | 15 | A tie between identical rows; either one is fine. |
| A newer version | 18 orders | The batch version wins. |
| Two newer versions | 5 orders, 10 rows | The later of the two wins. |
| An older version that arrived late | 6 | The target's version wins. Nothing changes. |
Common wrong answers
The batch always wins. Remove the matching orders from the target and append the whole batch:
target.join(batch, "order_id", "left_anti").unionByName(batch)
Two problems. The five orders with two versions in the batch are now in the result
twice: 125 rows. And the six late, older versions overwrite the newer rows the
target already had. An order can go from DELIVERED back to SHIPPED.
The latest batch row always wins. De-duplicating the batch first fixes the row
count, 120, and leaves the second problem: 6 orders are overwritten with stale
data. "It is in the newest file" does not mean "it is the newest version". Compare
updated_at.
union and distinct(). distinct removes rows that are identical in every
column. Only the 15 re-delivered copies are. Every order with a real update keeps
both its versions: 154 rows.
union and dropDuplicates(["order_id"]). One row per order, 120 rows, and no
say in which one. dropDuplicates keeps whichever row it meets first. On this data
all 23 changed orders came out with a version that is not the latest.
groupBy("order_id") with max of every column. Each column is maximised on
its own, so the result mixes versions: the latest updated_at, the alphabetically
last status, the largest amount. 21 orders get a row that never existed.
Another correct way
F.max_by(F.struct("status", "amount", "updated_at"), "updated_at")
in a groupBy("order_id"), then unpack the struct. max_by returns the whole
struct from the row with the highest updated_at, so the columns stay together. It
gives the same result as the reference solution.
In a real table: MERGE
On Delta Lake this load is a MERGE INTO target USING batch. The same three rules
apply, and the last two are the ones people leave out:
WHEN NOT MATCHED THEN INSERT: the new orders.WHEN MATCHED AND batch.updated_at > target.updated_at THEN UPDATE: the condition is what stops a late, older version from overwriting a newer one.- De-duplicate the batch to one row per
order_idfirst. A merge in which two source rows match the same target row fails.
Edge cases in the data
| Case | Orders | What it catches |
|---|---|---|
| New orders, one row each | 101 to 120 | Keeps the row count of the buggy load correct. |
| One newer version | 18 | The original bug. |
| Two newer versions in one batch | 5 | "Batch wins" without de-duplicating; distinct(). |
| An older version than the target has | 6 | "Batch wins", with or without de-duplicating. |
| Exact copies of target rows | 15 | Must not create duplicates; harmless ties. |
| A changed amount as well as a changed status | 5 | Taking columns from different versions. |