In a Django sync I worked on, corrections made the reported totals drift upward. In the example below, changing an order from 10 to 4 makes the projection report 14: it counts both versions.
Here is the same failure reduced to a Python dict and a list.
1. The shape of the sync
The job polls by updated_at and appends changed records to the reporting table.
# "source" stands in for the upstream system: one work order, done, qty 10.
source = {"WO-42": {"status": "DONE", "qty": 10}}
history = [] # append-only: we only ever add rows, never edit or remove one
def sync_once():
for order_id, rec in source.items():
if rec["status"] == "DONE":
history.append({"order_id": order_id, "qty": rec["qty"]})
sync_once()
print(history)
print("total:", sum(h["qty"] for h in history))[{'order_id': 'WO-42', 'qty': 10}]
total: 102. The correction that broke it
The operator corrects the order from 10 to 4. The next poll appends the correction:
source["WO-42"]["qty"] = 4 # the correction, applied upstream
sync_once()
print(history)
print("total:", sum(h["qty"] for h in history))[{'order_id': 'WO-42', 'qty': 10}, {'order_id': 'WO-42', 'qty': 4}]
total: 14The source says 4; the projection reports 14.
3. Why a “duplicate check” didn't save it
The existing check skips a snapshot when its content matches the previous one:
last_seen = {} # order_id -> the last snapshot we projected
def sync_once_with_dedup():
for order_id, rec in source.items():
if rec["status"] != "DONE":
continue
snapshot = {"qty": rec["qty"]}
if last_seen.get(order_id) == snapshot:
continue # identical to last time -> skip
history.append({"order_id": order_id, "qty": rec["qty"]})
last_seen[order_id] = snapshotRun the same correction, and then a second one, through it:
sync_once_with_dedup() # first call: appends normally, records the snapshot
source["WO-42"]["qty"] = 7 # a second correction
sync_once_with_dedup()
print("total:", sum(h["qty"] for h in history))total: 21 # 10 + 4 + 7, every version ever seen, still summed together
A correction changes the content, so it passes. The source order ID tells us which fact we have already counted.
4. Key the projection by source identity
Store one row per source order. In the example, the order ID is the dict key:
history_by_order = {} # order_id -> the ONE row that represents it, always current
def sync_once_fixed():
for order_id, rec in source.items():
if rec["status"] == "DONE":
history_by_order[order_id] = {"order_id": order_id, "qty": rec["qty"]}
sync_once_fixed()
source["WO-42"]["qty"] = 7 # as many corrections as you like, in any order
sync_once_fixed()
source["WO-42"]["qty"] = 4
sync_once_fixed()
print("total:", sum(r["qty"] for r in history_by_order.values()))total: 4 # correct, no matter how many times the order was corrected
In the real sync this meant a foreign key from each history row to the source row it came from, and an update instead of an insert. The idea is exactly this dict.
5. Reconcile against the source
Compare the projection with the source. Checking only the projection cannot tell you which total is right:
def reconcile():
source_total = sum(r["qty"] for r in source.values() if r["status"] == "DONE")
projected_total = sum(r["qty"] for r in history_by_order.values())
diff = projected_total - source_total
print("OK" if diff == 0 else f"MISMATCH: projected={projected_total}, source={source_total}, diff={diff}")
reconcile()Use this to find the old discrepancies and keep it running to catch future drift.
6. A guard for incomplete reads
My first patch for this had a bug of its own. I made the completion timestamp idempotent the same way, by always taking the latest value:
schedule = {"WO-42": {"finished_at": None}}
# First pass — looks idempotent, is not safe:
def sync_schedule(order_id):
rec = source[order_id]
if rec["status"] == "DONE":
schedule[order_id]["finished_at"] = rec.get("finished_at") # always overwriteA poll can see a completed status before finished_at has been populated:
source["WO-42"]["finished_at"] = 100
sync_schedule("WO-42")
print(schedule) # {'finished_at': 100} - correct
source["WO-42"]["finished_at"] = None # a later read arrives before the field lands
sync_schedule("WO-42")
print(schedule) # {'finished_at': None} - a correct value, wipedIn this sync, an empty timestamp means the source is incomplete. Keep the known value until a populated one arrives:
def sync_schedule_fixed(order_id):
rec = source[order_id]
new_value = rec.get("finished_at")
if rec["status"] == "DONE" and new_value is not None: # <- the guard
schedule[order_id]["finished_at"] = new_valueIdempotent and “always take the latest value” are different properties. The first means replaying the same input gives the same result. The second assumes every read is complete, and the moment it is not, it deletes a correct value. Review caught this one before it shipped.
7. What carries over to other syncs
- Detecting changes by
updated_atand appending them double-counts the first correction. - Key the projection by the identity of the source record. Content only tells you the data changed.
- Never let an incomplete read overwrite a known value.
- Keep the reconciliation against the source as a standing job. It would have caught the drift on day one.