Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

Write-Audit-Publish and Quarantine Patterns

Give every check a failure policy (block, warn or quarantine), then build a write-audit-publish job in DuckDB: stage each batch, move bad rows to a quarantine table with a reason, audit the batch, and publish in one transaction, so a corrupted batch is held back while consumers keep reading the last good data.

Contentsand lesson path

What you will learn

  • Choose a failure policy per check (block, warn or quarantine) and implement write-audit-publish so a bad batch never replaces good published data.

01. The problem

A partner sends a daily file of orders, and a finance dashboard reads the published table prod.orders. Until now the pipeline loaded each file straight into that table and ran its checks afterwards. When a check failed, the bad rows were already on the dashboard, and someone had to find and delete them by hand.

You will fix that with write-audit-publish (WAP). The job writes each batch to a staging area that consumers never read, audits it there, and publishes it to the consumer-facing table only if the audit passes. A bad batch can then fail as loudly as it likes: the published data stays what it was yesterday.

Not every problem should stop a batch, though. Before writing code, decide what each check does when it fails.

02. Step 1: Choose a failure policy for each check

There are three policies, and the choice depends on how much harm the problem does and on whether it affects single rows or the batch as a whole.

  • Block: hold the whole batch back and alert. Use it when publishing would do damage that is hard to undo, or when the problem means the batch as a whole cannot be trusted: a file that is shorter than its manifest says, duplicate keys that downstream merges would multiply, or amounts on the wrong scale.
  • Quarantine: move the rows that break a rule into a quarantine table, with the reason and the batch they came from, and publish the rest. Use it for row-level problems in otherwise good data, such as an unknown currency on one order. Nothing is lost: the owner can fix the rows and replay them.
  • Warn: publish everything and tell the owner. Use it for changes that may be legitimate, such as a country you have not seen before.

Quarantine needs a limit. If a third of the rows fail a row rule, the batch is broken, not a few rows, so the share of quarantined rows is itself a blocking check. Here is the plan for this job:

  • Row rules, policy quarantine: the currency is EUR or GBP; the amount is between 0 and 10,000.
  • Batch audits, policy block: the row count matches the partner's manifest; order_id is unique and not already published by another batch; at most 5% of rows are quarantined; the mean amount is within 50% of the mean already published.
  • Batch audit, policy warn: every country has been seen before.

The lab uses DuckDB 1.5.6 with Python 3.12 (pip install "duckdb==1.5.6"), in an empty folder.

03. Step 2: Create the partner's files

make_batches.py writes three days of 40 orders, each with a manifest: a small JSON file in which the partner states the row count and the total amount. The second day has two bad rows and a new country; on the third day a bug upstream sends every amount in cents.

Python · make_batches.py
"""Write three daily order files and their manifests, as a partner would send them.

python make_batches.py           all three days, as first sent
python make_batches.py --resend  only 4 November, corrected by the partner
"""
import csv
import json
import random
import sys
from pathlib import Path

rng = random.Random(7)
resend = "--resend" in sys.argv
Path("landing").mkdir(exist_ok=True)


def day_rows(day, first_id, n=40):
    return [[first_id + i, day, rng.choice(["GB", "FR", "DE"]), "EUR",
             round(rng.uniform(10, 90), 2)] for i in range(n)]


def write(day, rows):
    with open(f"landing/orders_{day}.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["order_id", "order_date", "country", "currency", "amount"])
        writer.writerows(rows)
    manifest = {"rows": len(rows), "amount_total": round(sum(r[4] for r in rows), 2)}
    Path(f"landing/orders_{day}.manifest.json").write_text(json.dumps(manifest))
    print(f"orders_{day}.csv: {len(rows)} rows, total {manifest['amount_total']}")


days = {"2026-11-02": day_rows("2026-11-02", 1),
        "2026-11-03": day_rows("2026-11-03", 101),
        "2026-11-04": day_rows("2026-11-04", 201)}
days["2026-11-03"][5][3] = "XYZ"          # an unknown currency
days["2026-11-03"][9][4] = -12.50         # a negative amount
days["2026-11-03"][12][2] = "ES"          # a country not seen before
if resend:
    write("2026-11-04", days["2026-11-04"])
else:
    for row in days["2026-11-04"]:
        row[4] = round(row[4] * 100, 2)   # a bug upstream: amounts sent in cents
    for day, rows in days.items():
        write(day, rows)
Terminal
python make_batches.py
Expected output
orders_2026-11-02.csv: 40 rows, total 1899.0
orders_2026-11-03.csv: 40 rows, total 1843.04
orders_2026-11-04.csv: 40 rows, total 204317.0

The total for 4 November is about a hundred times the others, but the manifest agrees with the file: the partner's own export made the mistake. A control total catches truncated or doubled files, not a wrong unit.

04. Step 3: Write and quarantine

wap.py takes one day as its argument. Save the three parts below together as one file. The first part creates the tables if they do not exist. staging.orders holds the batch being processed; prod.orders is what consumers read; prod.quarantine has the same columns plus reason; prod.batch_log records every decision.

The write step loads the whole file into staging, with explicit column types, so that a wrong type fails here and not in a consumer's query. Then each row rule copies the rows that break it into quarantine and deletes them from staging. Deleting the batch's old quarantine rows first makes a rerun of the same day replace them instead of adding a second copy.

Python · wap.py (part 1 of 3)
"""Write-audit-publish for one daily orders file: stage, quarantine, audit, publish."""
import json
import sys
from pathlib import Path

import duckdb

day = sys.argv[1]
manifest = json.loads(Path(f"landing/orders_{day}.manifest.json").read_text())
con = duckdb.connect("shop.duckdb")
con.execute("CREATE SCHEMA IF NOT EXISTS staging")
con.execute("CREATE SCHEMA IF NOT EXISTS prod")
con.execute("""CREATE TABLE IF NOT EXISTS prod.orders (order_id INTEGER,
    order_date DATE, country VARCHAR, currency VARCHAR, amount DECIMAL(10, 2),
    batch VARCHAR)""")
con.execute("""CREATE TABLE IF NOT EXISTS prod.quarantine AS
    SELECT *, '' AS reason FROM prod.orders WHERE false""")
con.execute("""CREATE TABLE IF NOT EXISTS prod.batch_log (batch VARCHAR,
    decision VARCHAR, failed_checks VARCHAR)""")

# 1. WRITE the whole file to staging, where no consumer reads.
con.execute("""CREATE OR REPLACE TABLE staging.orders AS
    SELECT *, ? AS batch FROM read_csv(?, columns = {'order_id': 'INTEGER',
        'order_date': 'DATE', 'country': 'VARCHAR', 'currency': 'VARCHAR',
        'amount': 'DECIMAL(10, 2)'})""", [day, f"landing/orders_{day}.csv"])

# 2. QUARANTINE rows that break a row rule, with the reason; a rerun replaces them.
ROW_RULES = {
    "unknown currency": "currency NOT IN ('EUR', 'GBP')",
    "amount outside 0..10000": "amount < 0 OR amount > 10000",
}
con.execute("DELETE FROM prod.quarantine WHERE batch = ?", [day])
for reason, rule in ROW_RULES.items():
    con.execute(f"INSERT INTO prod.quarantine SELECT *, ? FROM staging.orders"
                f" WHERE {rule}", [reason])
    con.execute(f"DELETE FROM staging.orders WHERE {rule}")

05. Step 4: Audit the batch

Each audit is one SQL query that returns true when the check passes, with its policy next to it. $day and $rows are named parameters, filled from the command line and the manifest. Note that the uniqueness audit looks at prod.orders as well as at the batch: a key that is unique inside today's file can still collide with yesterday's. When prod.orders is empty, on the first day, the comparisons with published data have nothing to compare with, so they pass.

Python · wap.py (part 2 of 3)
# 3. AUDIT the batch. Each check returns true when it passes and has a policy.
AUDITS = [
    ("rows match the manifest", "block",
     "SELECT (SELECT count(*) FROM staging.orders)"
     " + (SELECT count(*) FROM prod.quarantine WHERE batch = $day) = $rows"),
    ("order_id unique and not yet published", "block",
     "SELECT count(*) = count(DISTINCT order_id) AND NOT EXISTS (SELECT 1"
     " FROM prod.orders p JOIN staging.orders s USING (order_id)"
     " WHERE p.batch <> $day) FROM staging.orders"),
    ("at most 5% of rows quarantined", "block",
     "SELECT (SELECT count(*) FROM prod.quarantine WHERE batch = $day)"
     " <= 0.05 * $rows"),
    ("mean amount within 50% of published mean", "block",
     "SELECT coalesce((SELECT avg(amount) FROM staging.orders)"
     " / (SELECT avg(amount) FROM prod.orders) BETWEEN 0.5 AND 1.5, true)"),
    ("every country already known", "warn",
     "SELECT NOT EXISTS (SELECT country FROM staging.orders EXCEPT"
     " SELECT country FROM prod.orders) OR NOT EXISTS (SELECT 1 FROM prod.orders)"),
]
values = {"day": day, "rows": manifest["rows"]}
failed = {"block": [], "warn": []}
for name, policy, sql in AUDITS:
    params = {k: v for k, v in values.items() if f"${k}" in sql}
    passed = con.execute(sql, params).fetchone()[0]
    print(f"{'pass' if passed else 'FAIL':<4}  {policy:<5}  {name}")
    if not passed:
        failed[policy].append(name)
quarantined = con.execute("SELECT count(*) FROM prod.quarantine WHERE batch = ?",
                          [day]).fetchone()[0]
print(f"quarantined: {quarantined} rows")

06. Step 5: Publish atomically

If any blocking audit failed, the job records the decision and stops: prod.orders is not touched. Otherwise it replaces the day's rows inside one transaction: the delete and the insert become visible together at COMMIT, or not at all if the job crashes in between. Deleting the batch's rows first makes the publish idempotent, so a rerun of the same day gives the same result instead of duplicates.

To show what another reader sees during the publish, the script opens a second connection to the same database with con.cursor() and counts the day's rows just before COMMIT. DuckDB gives each transaction a consistent snapshot, so that reader still sees the old state.

Python · wap.py (part 3 of 3)
# 4. PUBLISH in one transaction, or leave prod exactly as it was.
if failed["block"]:
    decision = "blocked"
else:
    decision = "published"
    con.execute("BEGIN TRANSACTION")
    con.execute("DELETE FROM prod.orders WHERE batch = ?", [day])
    con.execute("INSERT INTO prod.orders SELECT * FROM staging.orders")
    reader = con.cursor()    # a second connection, like a dashboard reading meanwhile
    seen = reader.execute("SELECT count(*) FROM prod.orders WHERE batch = ?",
                          [day]).fetchone()[0]
    print(f"a reader sees {seen} rows of {day} before COMMIT")
    con.execute("COMMIT")
con.execute("INSERT INTO prod.batch_log VALUES (?, ?, ?)",
            [day, decision, ", ".join(failed["block"] + failed["warn"])])
print(f"{decision.upper()}: {day}")

report.py plays the consumer: it shows the published revenue per day and the batch log.

Python · report.py
"""What consumers see: published revenue per day, and the decision for each batch."""
import duckdb

con = duckdb.connect("shop.duckdb", read_only=True)
con.sql("""SELECT order_date, count(*) AS orders, sum(amount) AS revenue
           FROM prod.orders GROUP BY ALL ORDER BY order_date""").show()
con.sql("SELECT * FROM prod.batch_log").show(max_width=88)

07. Step 6: Publish two good days

Terminal
python wap.py 2026-11-02
python wap.py 2026-11-03
Expected output
pass  block  rows match the manifest
pass  block  order_id unique and not yet published
pass  block  at most 5% of rows quarantined
pass  block  mean amount within 50% of published mean
pass  warn   every country already known
quarantined: 0 rows
a reader sees 0 rows of 2026-11-02 before COMMIT
PUBLISHED: 2026-11-02
pass  block  rows match the manifest
pass  block  order_id unique and not yet published
pass  block  at most 5% of rows quarantined
pass  block  mean amount within 50% of published mean
FAIL  warn   every country already known
quarantined: 2 rows
a reader sees 0 rows of 2026-11-03 before COMMIT
PUBLISHED: 2026-11-03

On 3 November two rows went to quarantine and 38 were published. The new country ES failed a warn audit, so the batch was still published and the warning was logged. The reader saw 0 rows of each day before COMMIT, because the insert was not yet visible to anyone else.

08. Step 7: Hold back the corrupted batch

Terminal
python wap.py 2026-11-04
python report.py
Expected output
pass  block  rows match the manifest
pass  block  order_id unique and not yet published
pass  block  at most 5% of rows quarantined
FAIL  block  mean amount within 50% of published mean
pass  warn   every country already known
quarantined: 0 rows
BLOCKED: 2026-11-04
┌────────────┬────────┬───────────────┐
│ order_date │ orders │    revenue    │
│    date    │ int64  │ decimal(38,2) │
├────────────┼────────┼───────────────┤
│ 2026-11-02 │     40 │       1899.00 │
│ 2026-11-03 │     38 │       1789.42 │
└────────────┴────────┴───────────────┘

┌────────────┬───────────┬──────────────────────────────────────────┐
│   batch    │ decision  │              failed_checks               │
│  varchar   │  varchar  │                 varchar                  │
├────────────┼───────────┼──────────────────────────────────────────┤
│ 2026-11-02 │ published │                                          │
│ 2026-11-03 │ published │ every country already known              │
│ 2026-11-04 │ blocked   │ mean amount within 50% of published mean │
└────────────┴───────────┴──────────────────────────────────────────┘

Every amount on 4 November was a valid number below 10,000, so no row rule fired, and the manifest matched. Only the batch-level mean comparison saw that the batch as a whole was about a hundred times too large. The batch was blocked, and the consumer's report is exactly what it was before the job ran: two good days, with no half-loaded third day. The staging table still holds the bad batch for anyone who wants to inspect it. In production this is the moment to alert the partner and the data owner.

09. Step 8: Replay the fixed batch and rerun a day

Terminal
python make_batches.py --resend
python wap.py 2026-11-04
python wap.py 2026-11-03
python report.py
Expected output
orders_2026-11-04.csv: 40 rows, total 2043.17
pass  block  rows match the manifest
pass  block  order_id unique and not yet published
pass  block  at most 5% of rows quarantined
pass  block  mean amount within 50% of published mean
pass  warn   every country already known
quarantined: 0 rows
a reader sees 0 rows of 2026-11-04 before COMMIT
PUBLISHED: 2026-11-04
pass  block  rows match the manifest
pass  block  order_id unique and not yet published
pass  block  at most 5% of rows quarantined
pass  block  mean amount within 50% of published mean
pass  warn   every country already known
quarantined: 2 rows
a reader sees 38 rows of 2026-11-03 before COMMIT
PUBLISHED: 2026-11-03
┌────────────┬────────┬───────────────┐
│ order_date │ orders │    revenue    │
│    date    │ int64  │ decimal(38,2) │
├────────────┼────────┼───────────────┤
│ 2026-11-02 │     40 │       1899.00 │
│ 2026-11-03 │     38 │       1789.42 │
│ 2026-11-04 │     40 │       2043.17 │
└────────────┴────────┴───────────────┘

┌────────────┬───────────┬──────────────────────────────────────────┐
│   batch    │ decision  │              failed_checks               │
│  varchar   │  varchar  │                 varchar                  │
├────────────┼───────────┼──────────────────────────────────────────┤
│ 2026-11-02 │ published │                                          │
│ 2026-11-03 │ published │ every country already known              │
│ 2026-11-04 │ blocked   │ mean amount within 50% of published mean │
│ 2026-11-04 │ published │                                          │
│ 2026-11-03 │ published │                                          │
└────────────┴───────────┴──────────────────────────────────────────┘

The resent file passes and is published. Rerunning 3 November shows two properties at once. The reader saw the 38 old rows until COMMIT, never zero and never 76, and afterwards the day still has 38 rows: the publish replaced the batch instead of appending it. The quarantine still holds two rows for that day, not four. ES no longer warns, because it is now in the published data; whether a country should count as known after one warning is a decision for the data owner.

10. The same pattern in warehouses and lakehouses

Staging tables and a transaction are one way to implement WAP. Others are common:

  • Swap or view switch. Build the new version as a separate table, audit it, then point consumers at it in one step, for example with CREATE OR REPLACE VIEW prod.orders AS SELECT * FROM orders_v42 or a table swap where the warehouse supports one.
  • Table-format branches. Apache Iceberg tables can have branches. With the table property write.wap.enabled set, a Spark job sets spark.wap.branch to write to an audit branch; the audit queries that branch, and the fast_forward procedure moves main to it if the audit passes. Readers of main never see the unaudited snapshot.
  • Catalog branches. Project Nessie, and similar tools such as lakeFS, branch a whole catalog or repository, so a batch that touches several tables can be audited and published together.

The idea is the same in every variant: consumers read a name that only moves after a passing audit.

11. Check your understanding

Practice check · 3 questions

Policies and publishing

Each question changes one detail of the worked example.

Q1. Someone removes `BEGIN TRANSACTION` and `COMMIT` from the publish step, and the process is killed right after the `DELETE`. What does the dashboard show for that day?
Q2. A batch of 40 rows has 9 rows with an unknown currency. What does `wap.py` do with it?
Q3. The partner sends `orders_2026-11-05.csv` with 40 new orders plus 3 orders already published on 4 November, and the manifest says 43 rows. Which audit fails?
Practice only: not graded, not saved, not evidence.

12. Apply it

The skill practice asks for a write-audit-publish step that holds back a deliberately corrupted batch while the previous good data stays published. On your own pipeline:

  • Write down each check with its policy, block, warn or quarantine, and one sentence on why.
  • Add a quarantine table with the batch id and reason, and a limit on the quarantined share.
  • Corrupt one batch on purpose, run the job, and show with a consumer query that the published data did not change. Then fix the batch and replay it.

13. Review prompt

Without looking back, explain what happens in each of the three WAP steps and why the audit runs before consumers can see the batch. Then explain when you block, warn or quarantine, why quarantine needs a limit, and why the publish runs in one transaction and deletes the batch's old rows first.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check