When to clean data, when to fix it at the source, and when to leave it alone

TL;DR

Difficulty: Intermediate

Every data problem has three answers: fix it at the source, clean it in the pipeline, or leave it and flag it.

  • Start with the purpose: the most demanding use of the data sets the standard.
  • Fix at the source first, because it cleans every future row for everyone and retires work.
  • Clean in the pipeline only what is knowable from data you hold, and keep the original beside it.
  • Leave and flag what you cannot know. An invented value is worse than an honest gap.
  • Rank findings by impact times frequency, write every rule into a register with owner, reason, version and test, and agree data contracts with partners who produce your data.

Profiling hands you a list of problems. The hard part is not fixing them, it is deciding which to fix where, and which not to touch at all. This chapter gives you a framework for that decision and runs a whole shop's ten findings through it, with the code, the numbers and the paperwork that keep the result trustworthy.

The question behind every cleaning job

You have profiled your data and you have a list of problems. Duplicate customers, test orders, odd country names, a supplier who measures in millimetres. The tempting next step is to open an editor and start fixing. Every problem, everywhere, as fast as possible.

That instinct costs more than it saves. Some problems should never be cleaned in the warehouse at all, because the honest fix belongs in the system that creates the data. Some can only be cleaned in the pipeline, because the source will never change. And some should not be cleaned by anyone, because "cleaning" them would mean making up information you do not have.

This chapter gives you a way to decide, problem by problem, which of those three it is. It is the hinge of this series: the chapters before it taught you to measure quality and to profile your data. The chapters after it teach the techniques. This one decides which technique, where, and whether at all.

Throughout, I use the same invented shop as the rest of the series: Wrenfield Home, an online homeware shop in Leeds (wrenfieldhome.example). Priya owns it. Callum is her developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL, sells about 1,400 products, takes 1,980 orders a month at an average order value of £72, and has five years of order history. Its data flows into BigQuery, where dbt turns it into reports.

Three answers to every data problem

Every problem that profiling finds has three possible answers. It helps to name them precisely, because most arguments about data quality are really two people silently picking different answers.

Fix at the source. You change the system, the process or the agreement that produces the data, so that new rows arrive correct. The source is wherever the data is born: a checkout form, an admin screen, a database table, a supplier's export, a warehouse partner's daily file.

Clean in the pipeline. You leave the source as it is and apply a written rule on the way into your reports. The pipeline is the chain of steps that copies data out of the sources, reshapes it and loads it where people analyse it. A rule there changes what the reports see, never what the source holds.

Leave it and flag it. You change nothing, and you mark the affected rows so that every report can show, count or exclude them honestly. A flag is simply an extra column that says something about the row, such as phone_status = 'missing'.

There is a fourth answer that hides inside the third: leave it alone entirely, because it does not matter for anything you use the data for. That is a legitimate decision too, as long as it is written down.

These answers are not exclusive. The most common real decision is a pair: fix the source so that new rows are right, and clean or flag the history that is already wrong.

Example: one dirty value, three answers

Wrenfield Home's old addresses, imported from the platform Priya used before Solidus, store the country as free text. Profiling found "UK", "United Kingdom", "England", "GB" and ten other spellings.

  • Fix at the source: in Solidus, a new address stores a reference to a row in the spree_countries table, not free text. So for new addresses the source is already fixed. Nothing more is needed going forward.
  • Clean in the pipeline: the old addresses will never be retyped. But every spelling can be mapped with certainty: "England" is in the United Kingdom, whose ISO country code is GB. A mapping table in the pipeline turns each spelling into GB. The original text stays in the raw data.
  • Leave and flag: a handful of old addresses say "Europe" or are blank. No rule can tell which country they meant without guessing. Those rows keep a null country and get the flag country_unmapped = true.

One finding, and all three answers apply to different parts of it. That is normal.

Purpose comes before any rule

Before you choose an answer, ask what the data is for. Quality is not a property of the data alone. It depends on the job the data has to do. Wang and Strong made this point in a paper whose title says it plainly: what data quality means to data consumers1. I covered the idea of fitness for purpose in the chapter on measuring data quality. Here it decides how much cleaning a problem deserves.

The same flaw can be critical for one purpose and irrelevant for another:

PurposeWhat it needs from the dataWhat it can ignore
Finance and VAT figuresEvery penny, every order, reconciled to the payment provider's settlementsCustomer duplicates, device, channel
Marketing reports (customer acquisition cost, new versus returning)One record per real customer, test and staff orders outA penny of rounding, phone numbers
Ad platform biddingCorrect conversion values, quicklyOld history, addresses
Product recommendationsWhich products were bought togetherExact prices, phone numbers, countries
Delivery and customer serviceA reachable phone number and a correct addressRevenue figures

So the first column of any decision is the purpose, and a problem without a purpose that cares about it goes to the bottom of the list.

Example: the same flaw, two purposes

Wrenfield Home's first two years of order lines came from the old platform, which stored prices as floating point numbers. A floating point number is a binary approximation, so a price of £23.99 can come back as 23.989999999999998 (the chapter on data types explains why).

For Priya's accountant, that matters. Monthly revenue has to match the money the payment providers actually paid out, to the penny, and a sum of tens of thousands of slightly wrong values can drift by pennies or more. For the product recommendation model Callum is building, it does not matter at all: the model only uses which products appear in the same basket. If the recommendation model were the only consumer, the float prices could be left alone. Because finance also uses these lines, they must be cleaned, and the rule has to be exact enough for finance.

The rule follows the most demanding purpose that uses the data. That is why purpose comes first.

Fix at the source whenever you can

A fix at the source is the best value fix there is, for four reasons.

  1. It cleans every future row for everyone. The shop's admin screens, the exports to the accountant, the ad platforms and the warehouse all receive correct data. A pipeline rule only helps the reports downstream of it.
  2. It removes a rule you would otherwise maintain forever. Every pipeline rule is code that has to be tested, documented and kept in step with changes upstream. A source fix retires that work.
  3. It catches the error where the context still exists. At the checkout, the customer is there to correct a typo. Three weeks later, in the warehouse, nobody knows what they meant.
  4. It is often required by law for personal data. The UK GDPR says personal data must be accurate and that every reasonable step must be taken to rectify inaccurate data without delay, having regard to the purposes2, and people have a right to have their inaccurate data rectified3. Correcting a customer's record means correcting it where it lives, in the shop, not in a copy that only the analysts see.

The earlier a problem is caught, the less it costs. The chapter on what dirty data costs works through why a problem caught at entry is far less expensive than one caught after a decision was made on it.

The tools for fixing at the source

You have more tools than most people use:

  • Validation in the application. In Rails, a model validation rejects a record before it is saved and gives the user a message they can act on4.
  • Normalisation on write. Rails can normalise an attribute every time it is assigned, for example stripping spaces and lowering the case of an email address5.
  • Database constraints. A CHECK constraint in PostgreSQL is a rule the database itself enforces on every insert and update, whichever code path writes the row6. Application validations can be skipped by a script or a bulk import. A constraint cannot.
  • Better defaults and controls. A dropdown instead of a free text field, a sensible default instead of an empty one.
  • Process changes. Testing on a staging copy of the shop instead of the live one.
  • Agreements with whoever produces the data. When the source belongs to another team or another company, the fix is a data contract, which I cover further down.

Example: stopping test orders at the source

Profiling found about 40 internal orders a year in Wrenfield Home's order table. Priya and Callum looked at them together and found two different kinds: 28 were test orders (Callum checking a new payment method on the live shop, later cancelled), and 12 were staff purchases (real goods, paid for, at a staff discount).

That split matters. Test orders are not sales, so they should never appear in revenue. Staff purchases are real sales, so finance keeps them, but marketing excludes them from conversion rate and customer acquisition cost, because nobody was acquired. The purpose decides again.

The fix at the source has three parts. First, tests move to a staging copy of the shop, so new test orders stop appearing at all. Second, staff purchases get an explicit flag when they are placed. Third, a check constraint makes sure an order cannot be both a normal customer order and an internal one by accident. Callum writes a migration:

# db/migrate/20260302090000_add_internal_order_flags.rb
class AddInternalOrderFlags < ActiveRecord::Migration[8.0]
  def change
    # 'customer' for normal orders, 'staff' for staff purchases, 'test' for tests
    add_column :spree_orders, :order_origin, :string, null: false, default: "customer"

    add_check_constraint :spree_orders,
      "order_origin IN ('customer', 'staff', 'test')",
      name: "spree_orders_order_origin_valid"
  end
end

add_check_constraint is part of Rails' schema statements and creates a PostgreSQL CHECK constraint7. The default of 'customer' means every existing and future order has a value, so no order ever has an unknown origin.

The worked effect: 40 internal orders a year at £72 is £2,880 of revenue, against annual revenue of 23,760 orders times £72, which is £1,710,720. That is 0.17%. Small for revenue. But 12 staff purchases a year, each counted as a "new customer" if the staff member had not ordered before, also nudge the new customer count and the acquisition cost, and the test orders were sent to the ad platforms as conversions. The fix took Callum under an hour. A low score with a tiny effort is still worth doing, and I come back to that in the triage section.

Example: normalising guest emails on write

Wrenfield Home's customer accounts are handled by Devise through the solidus_auth_devise extension, which lowers the case of account emails8, and Devise strips surrounding whitespace from them by default9. Guest checkouts are different. A guest order stores its email directly in spree_orders.email, and nothing normalises it. So "Priya.Shah@example.com " on a guest order and "priya.shah@example.com" on an account look like two customers.

Rails offers normalizes, which applies a function whenever the attribute is set5. Solidus recommends customising its models by prepending a module from the app/overrides folder, as its guide on customising the core describes10. Here is the override:

# app/overrides/wrenfield/spree/order/normalise_email.rb
module Wrenfield
  module Spree
    module Order
      module NormaliseEmail
        def self.prepended(base)
          # Lower case and trim every email on every new or changed order
          base.normalizes :email, with: ->(email) { email.strip.downcase }
        end

        ::Spree::Order.prepend self
      end
    end
  end
end

From the day this ships, every new guest order stores its email in one form. The source is fixed. The five years of history are not, and normalising does not tell you that a guest and an account are the same person. That part stays in the pipeline, which is where the next section begins.

What a fix at the source cannot do

Be honest about the limits:

  • It does not repair history. Rows written before the fix stay as they were. You still need a pipeline rule or a flag for them.
  • Some sources are not yours. The warehouse partner's file format, a supplier's feed and Google's analytics export belong to other organisations. You can ask, negotiate and write a contract. You cannot deploy.
  • Some gaps are not errors. When a visitor declines analytics cookies, the missing data is their choice, protected by law. There is nothing to fix, and trying to fill it in would be wrong.
  • A strict source can hurt the business. A checkout that rejects every slightly odd phone number loses sales. Validation at the source must be strict where errors are costly and forgiving where the customer's convenience matters more.

Clean in the pipeline when the source cannot change

Cleaning in the pipeline is right when three conditions hold together:

  1. The source cannot or will not change, at least not for the rows you already have.
  2. The true value is knowable from data you hold. A mapping table, a unit conversion or a known time zone gives the right answer without guessing.
  3. The rule is written down and the original is kept. Every cleaned value sits next to its raw value, or the raw data stays untouched in its own layer, so the cleaning can be checked and undone.

The second condition is the one people skip. "England" to GB is knowable. A blank country is not. A price of 23.989999999999998 that was entered as whole pence is knowable: it is £23.99. A missing phone number is not.

Example: the warehouse partner's file

Wrenfield Home's third party logistics partner (3PL), the company that stores and ships the stock, sends a daily CSV file of shipments and returns. Profiling found two problems in it.

First, the SKU, the stock keeping unit that identifies a product variant, comes in the 3PL's own format: their client prefix and the shop's number padded with zeros, so the shop's 10234 arrives as WRN0010234. Without cleaning, not one return joins to a product, and the return rate per product cannot be calculated. On top of that, 85 old products were renumbered when Priya moved to Solidus, and the 3PL still uses their old numbers.

Second, the time stamps are in local UK time with no time zone, while the shop stores everything in UTC (Coordinated Universal Time). In summer, UK time is one hour ahead of UTC. A return scanned at 12.30am on 1 July local time happened at 11.30pm on 30 June in UTC, so it lands in the wrong month unless it is converted.

Both are knowable. The SKU follows a fixed pattern, with a short mapping table for the 85 exceptions. The time zone is always Europe/London. So Callum cleans both in the pipeline, keeping the raw values beside the cleaned ones:

-- models/staging/threepl/stg_threepl__returns.sql
-- PostgreSQL dialect (the same logic runs in BigQuery with small syntax changes)
with source as (
    select * from {{ source('threepl', 'returns_raw') }}
),

legacy_skus as (
    -- 85 products renumbered at the platform move (rule R03, version 2)
    select threepl_sku, shop_sku from {{ ref('threepl_legacy_sku_map') }}
)

select
    s.return_ref,
    s.sku                                         as sku_raw,
    coalesce(
        l.shop_sku,
        ltrim(substring(s.sku from 4), '0')       -- drop 'WRN', then leading zeros
    )                                             as shop_sku,
    l.shop_sku is not null                        as sku_from_legacy_map,

    s.scanned_at_local                            as scanned_at_raw,
    s.scanned_at_local at time zone 'Europe/London' as scanned_at_utc,

    -- In late October one local hour happens twice. Flag it, do not guess.
    (
        s.scanned_at_local::date =
            make_date(extract(year from s.scanned_at_local)::int, 10, 31)
            - extract(dow from make_date(extract(year from s.scanned_at_local)::int, 10, 31))::int
        and s.scanned_at_local::time >= time '01:00'
        and s.scanned_at_local::time <  time '02:00'
    )                                             as scanned_in_repeated_hour,

    'R03.v2'                                      as sku_rule_version,
    'R07.v1'                                      as time_rule_version
from source s
left join legacy_skus l on l.threepl_sku = s.sku

Line by line: ltrim(substring(s.sku from 4), '0') takes the text from the fourth character on (dropping the three letter prefix) and removes leading zeros, so WRN0010234 becomes 10234. The legacy map wins where it has an entry. AT TIME ZONE 'Europe/London' reads a time stamp without a zone as local London time and returns a time stamp with a zone, which PostgreSQL stores as an absolute moment11. The repeated hour check finds the last Sunday in October (31 October minus its day of the week, where Sunday is 0), when UK clocks go back at 2am and the hour from 1am to 2am happens twice. A scan in that hour could be either of two moments, so the row is flagged rather than guessed. The rule versions travel with every row, so any number in a report can be traced to the exact rule that shaped it.

Here is what three raw rows become:

sku_raw     shop_sku  from_legacy_map  scanned_at_raw    scanned_at_utc        repeated_hour
WRN0010234  10234     false            2026-07-01 00:30  2026-06-30 23:30 UTC  false
WRN0000871  20871     true             2026-03-12 14:05  2026-03-12 14:05 UTC  false
WRN0011502  11502     false            2026-10-25 01:20  2026-10-25 01:20 UTC  true

The second row shows the legacy map at work: the 3PL still uses the old number 871, which became 20871 in Solidus. The third row is the repeated hour on 25 October 2026. 1.20am happened twice that night, once in summer time and once in winter time. PostgreSQL reads an ambiguous local time as standard time, so it picks the winter reading, 1.20am UTC12. That may be right or an hour off, and the flag says so.

Notice what Callum does not do. He does not rewrite the 3PL's file, and he does not change the raw table. He also asks the 3PL to send the shop's own SKU and a UTC offset in future, which is the fix at the source. Until they do, the pipeline carries the rule.

Leave it and flag it when cleaning would invent information

This is the answer people find hardest, because a gap or an inconsistency feels like a job left undone. But a value you make up is worse than a value you admit you do not have. A blank is honest. A plausible fake is a lie that looks like data, and nobody downstream can tell the difference.

Leave and flag is right when:

  • The true value cannot be known from anything you hold. A missing phone number, a blank country, a return that has not arrived yet.
  • The difference is real, not an error. Two systems that measure different things will disagree, and "cleaning" one to match the other destroys information.
  • Cleaning would hide a signal. An odd value can be the most important row in the table. A later chapter in this series covers outliers, where this is the central question.

Leaving does not mean ignoring. A flag makes the gap visible, countable and filterable. Every report can then say "2% of orders have no usable phone number" instead of pretending the problem does not exist. The chapter after this one goes deep into missing values and why "unknown" beats a fake default.

There is also a difference between deriving and inventing. Deriving uses a fact you hold to state another fact with certainty: a postcode in the Leeds area tells you the address is in England, so the country is GB. Inventing fills a gap with what is likely: most customers live in the UK, so a blank country is probably GB. Derivation is cleaning. Invention is not, and if you ever do it for a model, it must be flagged as an estimate.

Example: missing phone numbers

About 2% of Wrenfield Home's orders have a missing or invalid phone number. With 23,760 orders a year, that is 475 orders.

Nothing in the data tells Callum the right number for those customers. Any value he wrote in would be invented. So he leaves the raw value and adds a status column:

-- models/staging/shop/stg_shop__order_contacts.sql (PostgreSQL)
select
    o.id                                   as order_id,
    a.phone                                as phone_raw,
    case
        when a.phone is null or btrim(a.phone) = ''
            then 'missing'
        when regexp_replace(a.phone, '[^0-9+]', '', 'g') !~ '^\+?[0-9]{9,15}$'
            then 'invalid_format'
        else 'present'
    end                                    as phone_status
from {{ source('shop', 'spree_orders') }} o
left join {{ source('shop', 'spree_addresses') }} a
       on a.id = o.ship_address_id
where o.completed_at is not null

The regular expression check is deliberately rough: it strips everything except digits and a plus sign, then asks for 9 to 15 digits. It is a flag for counting, not a validation of the number. The proper validation belongs at the source.

At the source, Callum adds a format check at checkout with the phonelib gem, which builds on Google's libphonenumber and offers a Rails validator13. The override:

# app/overrides/wrenfield/spree/address/validate_phone.rb
module Wrenfield
  module Spree
    module Address
      module ValidatePhone
        def self.prepended(base)
          # Check the format only when a number is given. Blank stays allowed.
          base.validates :phone, phone: { possible: true, allow_blank: true }
        end

        ::Spree::Address.prepend self
      end
    end
  end
end

Note allow_blank: true. Whether to make the phone number mandatory is a separate decision. If the carrier needs it to deliver, asking for it is justified. If not, the UK GDPR's data minimisation principle says personal data must be limited to what is necessary for the purpose2, so you do not make a field mandatory just to have tidier data.

Example: Google Analytics shows fewer purchases than the shop

Google Analytics 4 (GA4) records about 15% fewer purchases than Wrenfield Home's order table, because some visitors decline analytics cookies and some browsers block the tracking. In a month with 1,980 orders, GA4 shows about 1,980 times 0.85, which is 1,683.

The tempting "fix" is to scale GA4 up by dividing by 0.85. Do not. The missing share is unlikely to be the same across channels, devices and campaigns, so a single factor would move every channel's figures by the wrong amount, and nobody reading the report would know the numbers had been adjusted. The two systems measure different things: the shop counts orders, GA4 counts the purchases it was allowed to see.

So this finding is left alone and flagged in the documentation of every report that uses GA4: revenue and order counts come from the shop database, behaviour and journeys come from GA4, and the gap is shown, not hidden. The full method for explaining the gap lives in reconciling analytics, ads and orders, and sending purchases from the server is covered in the shop database as the source of truth.

Triage: impact times frequency

Ten problems are rarely ten equal problems. Triage means ranking them so that the effort goes where it matters. A simple, transparent method is enough, and it beats any gut feeling because it can be argued with.

Score each finding on two scales from 1 to 5, then multiply. Impact asks what goes wrong for the purposes that use the data. Frequency asks how much of the data is affected.

ScoreImpact: what goes wrongFrequency: share of rows affected
1Nothing that any report or decision usesUnder 0.1%, or a once a year event
2A secondary report is off, or a figure by pennies or an hour0.1% to 1%
3A monthly management metric is distorted1% to 5%
4Money, customer counts or ad bidding are distorted5% to 20%
5Customers see wrong information, or a legal duty is at stakeOver 20%, or every row

The priority score is the product. If you want to refresh the idea behind it, a quick look at Foundations: expected value helps, because the score is a rough stand in for an expected cost.

S=I×FS = I \times F

where SS is the priority score from 1 to 25, II is the impact score and FF is the frequency score.

Frequency itself is a share, the affected rows divided by all rows in the table (see Foundations: ratios and rates):

f=aNf = \frac{a}{N}

where ff is the share of rows affected, aa is the number of affected rows and NN is the number of rows in the table. You then look up ff in the frequency column above.

Add a third column for the effort of fixing at the source, because a low score with a trivial fix is still worth doing, and a high score with no source fix tells you the pipeline will carry the load for a long time.

Example: Wrenfield Home's ten findings, scored

Priya and Callum scored the ten findings from the profiling chapter together. Every number below is from the invented example.

FindingAffectedffFFIISSEffort at source
3PL SKU formatevery 3PL row100%5420Medium (3PL must change)
Supplier sends mm, others cm180 of 1,400 products12.9%4520Medium (supplier must change)
Duplicate customer accounts2,418 of 78,000 accounts3.1%3412Low going forward, none for history
3PL returns up to 5 days lateup to 30 of 178 monthly returns17%4312Medium (3PL schedule)
GA4 shows 15% fewer purchases297 of 1,980 monthly orders15%4312Not possible (consent)
Legacy prices stored as floats61,000 of 178,000 order lines34%5210Not possible (old platform gone)
3PL local time without zoneevery 3PL row100%5210Low (3PL adds an offset)
Country as free text9,870 of 96,000 addresses10.3%428Done for new addresses
Test and staff orders40 of 23,760 yearly orders0.17%236Low
Missing or invalid phone475 of 23,760 yearly orders2%326Low

Two worked checks. Duplicate accounts: 3.1% of 78,000 accounts is 2,418 accounts, and 3.1% sits in the 1% to 5% band, so F=3F = 3. They distort customer counts, repeat purchase rate and lifetime value, so I=4I = 4, and S=4×3=12S = 4 \times 3 = 12. Supplier units: 180 of 1,400 products is 12.9%, so F=4F = 4. Wrong dimensions reach the product pages, where customers rely on them to decide whether a sofa fits, so I=5I = 5 and S=20S = 20.

Bar chart of the priority score, impact times frequency, for the ten profiling findings of the invented example shop. 3PL SKU format and supplier units score 20, duplicate accounts, late 3PL returns and the GA4 gap score 12, float prices and 3PL time zone score 10, free text country scores 8, test and staff orders and missing phone numbers score 6. Tap or click to open full screen and move around

The ranking already says something useful. The two most urgent problems both belong to partners outside the shop, which means both need a contract as well as a pipeline rule. And the two lowest scores, test orders and phone numbers, are also the two lowest effort source fixes, so they get done in the same week anyway.

Putting a price on it

When a finding is close to the line, a money estimate settles it. The expected annual cost of leaving a problem alone is:

E=n×p×cE = n \times p \times c

where EE is the expected cost per year, nn is the number of affected rows per year, pp is the probability that an affected row leads to a wrong action, and cc is the cost of one wrong action. This is the expected value idea from Foundations: expected value, applied to a data problem.

Example: what missing phone numbers cost

Callum checks the carrier's records for a quarter and estimates (invented figures) that 8% of orders without a usable phone number end in a failed first delivery, because the driver could not call ahead, and that each failed attempt costs about £7.50 in redelivery charges and customer service time. With 475 affected orders a year:

E=475×0.08×7.50=285E = 475 \times 0.08 \times 7.50 = 285

So EE comes to about £285 a year. The source fix, a format check at checkout, takes Callum about half a day. It pays for itself within a year or two, and it never needs maintaining. Cleaning the history is impossible, because the right numbers are unknown, so the history stays flagged. The decision is clear, and it took five minutes to make.

The decision as a flow

Put together, the framework is a short sequence of questions. Ask them in this order for every finding.

Tap or click to open full screen and move around

The recommended path goes through the source fix first. Even when the history needs cleaning, the question "can the source change?" comes before "how do I clean this?", because otherwise the pipeline quietly becomes the permanent home for problems that someone upstream could have stopped.

The ten findings, one by one

This is the full worked example: every finding from Wrenfield Home's profiling, run through the framework. For each one: what was found, which purposes care, and the decision for new rows and for history.

Example: duplicate customer accounts (score 12)

Found: 3.1% of 78,000 accounts, 2,418 records, belong to someone who already has another record. Causes: emails that differ only in case or spaces on guest orders and in accounts imported from the old platform, and guest checkouts by people who also have an account.

Purposes that care: marketing (new versus returning, acquisition cost), lifetime value, customer service.

Decision: fix at the source for new rows (the normalizes override above), and clean in the pipeline for history, with entity resolution matching records that belong to the same person. Accounts are not merged inside the shop automatically: a merge changes what a customer sees when they log in, and choosing the wrong record to keep is hard to undo. Matches the pipeline is unsure about are flagged for a person to review. A later chapter in this series covers duplicate detection and entity resolution in depth, and the customer migration guide shows how to avoid creating such duplicates during a platform move.

Example: test and staff orders (score 6)

Found: about 40 a year, 28 tests and 12 staff purchases.

Purposes that care: finance (tests out, staff purchases in), marketing (both out), ad bidding (both out).

Decision: fix at the source with the order_origin column and staging tests. For the history, a pipeline rule classifies old orders by staff email domain and by a list Priya confirmed by hand, and sets the same order_origin values in the warehouse. Each report then filters by purpose, from one shared definition.

Example: the 3PL SKU format (score 20)

Found: every row of the 3PL file uses the prefixed, padded SKU, and 85 legacy products use old numbers.

Purposes that care: product return rates, stock reconciliation, supplier reviews.

Decision: clean in the pipeline with the pattern rule and a mapping table for the 85 exceptions (shown above). Fix at the source by asking the 3PL to add the shop's SKU as its own column, written into the contract.

Example: 3PL returns up to five days late (score 12)

Found: returns can arrive in the file up to five days after they happen.

Purposes that care: the return rate, refunds forecasting, finance at month end.

This is not dirty data. Each row is correct, it is just late. Cleaning it by estimating the missing returns would invent rows. The worked effect shows why it still matters. The return rate is returns divided by orders (see Foundations: ratios and rates):

r=ROr = \frac{R}{O}

where rr is the return rate, RR is the number of returns for orders in the period and OO is the number of orders in the period.

With 1,980 orders and the true 9% return rate, a month has about 178 returns, roughly 6 a day. On the first day of the next month, in the worst case, the last five days are missing, about 30 returns. The report would then show:

r=1481,980=0.075r = \frac{148}{1{,}980} = 0.075

So rr shows 7.5% instead of the true 9%. Decision: leave and flag. Every month is marked provisional until five days after it closes, and the report says so. The contract asks the 3PL for a returns file within one day. Later chapters cover late arriving data and restating closed periods in depth.

Example: GA4 shows 15% fewer purchases (score 12)

Decision: leave and flag, as worked above. Revenue from the shop, behaviour from GA4, the gap shown and explained.

Example: legacy prices stored as floats (score 10)

Found: 61,000 order lines from the old platform hold prices as floating point numbers.

Purposes that care: finance (to the penny), less so everyone else.

Decision: clean in the pipeline. The source is switched off, so no source fix is possible, and the true values are knowable: every price was entered in whole pence. The rule rounds to two decimals into a numeric(10,2) column, the same type Solidus uses for its order totals14, keeps the raw float beside it, and flags any line where rounding moved the value by more than half a penny, which would mean the value was never a clean price in the first place. A reconciliation test checks that the cleaned lines of each order add up to that order's stored total.

Example: 3PL local time without a zone (score 10)

Decision: clean in the pipeline with AT TIME ZONE 'Europe/London', flag the repeated October hour (shown above), and ask the 3PL to include a UTC offset in future.

Example: country as free text (score 8)

Found: 9,870 of 96,000 addresses, all from the old platform, with 14 spellings.

Decision: clean in the pipeline with a mapping table from each spelling to an ISO country code, and flag what cannot be mapped (shown at the start of this chapter). New addresses are already fixed by Solidus. A later chapter in this series covers mapping tables and standardisation in depth.

Example: missing or invalid phone numbers (score 6)

Decision: leave and flag the history, fix at the source with a format check, as worked above.

Example: one supplier sends millimetres (score 20)

Found: three supplier feeds give dimensions in centimetres. One, covering 180 products, gives millimetres in the same column with no unit.

Purposes that care: the product pages (customers deciding whether something fits), shipping cost estimates, returns analysis.

Decision: fix at the source first. Callum's import into the shop is itself the first source he controls, so it now converts that supplier's values and rejects any dimension outside a plausible range for the product type. The supplier is asked, in a data contract, to add a unit column. The history is cleaned in the pipeline with the same supplier specific conversion, flagged with the rule version.

The ten decisions at a glance

FindingMain decisionAlso done
Duplicate accountsClean in the pipelineFix at the source for new rows, flag unsure matches
Test and staff ordersFix at the sourceClean history in the pipeline
3PL SKU formatClean in the pipelineContract asks for the shop SKU
Late 3PL returnsLeave and flagContract asks for faster delivery
GA4 gapLeave and flagNone
Float pricesClean in the pipelineFlag lines that were never clean prices
3PL time zoneClean in the pipelineContract asks for an offset
Free text countryClean in the pipelineFlag unmapped values
Missing phoneLeave and flagFix at the source for new orders
Supplier unitsFix at the sourceClean history in the pipeline
Grouped bar chart of the ten findings of the invented example shop by decision. As the main decision, 2 findings are fixed at the source, 5 are cleaned in the pipeline and 3 are left and flagged. As an additional action, 5 findings also get a fix at the source, 2 also get pipeline cleaning and 3 also get flags. Tap or click to open full screen and move around

Seven of the ten findings involve a fix at the source, as the main decision or alongside it. That is the pattern to expect. The pipeline cleans what is already there, and the source stops it coming back.

Write every rule down: the rule register

A cleaning rule that lives only in someone's head, or only in a block of SQL, is a time bomb. Six months later nobody remembers why returns from one supplier are divided by ten, and when the supplier fixes its feed, the rule keeps dividing correct values by ten.

The answer is a rule register: one list, kept in the same repository as the pipeline code, with one entry per rule. Each entry answers who, what, why and since when:

FieldWhat it holds
Rule id and versionA stable id (R03) and a version that changes whenever the logic changes
FindingThe problem in plain words
DecisionFix at the source, clean in the pipeline, or leave and flag
RuleExactly what it does, in words a non engineer can check
OwnerThe person who answers for it, usually the business owner of the data
ReasonWhy this rule, and which purposes need it
Introduced and retiredDates, so any historic number can be explained
WhereThe model or code that implements it
TestThe test that proves it works

Example: three entries in Wrenfield Home's register

Callum keeps the register as a dbt seed, a small CSV file that dbt loads into the warehouse as a table so that reports can join to it15. Three of its rows:

rule_id,version,finding,decision,rule,owner,reason,introduced_on,retired_on,model
R03,2,3PL SKU in own format,clean_in_pipeline,"Drop 3 letter prefix and leading zeros; legacy map for 85 renumbered SKUs",Priya,"Return rate per product needs the shop SKU",2026-02-16,,stg_threepl__returns
R07,1,3PL time stamps without zone,clean_in_pipeline,"Read as Europe/London; flag the repeated October hour",Callum,"Month and day boundaries must match the shop (UTC)",2026-02-16,,stg_threepl__returns
R09,1,Missing or invalid phone,leave_and_flag,"phone_status = missing / invalid_format / present; never filled in",Priya,"No source for the true number; carrier needs it for delivery",2026-03-02,,stg_shop__order_contacts

Each model then points at its rules in its properties file, using dbt's meta config, which accepts any dictionary of information you want to attach16. The properties file for the returns model:

# models/staging/threepl/_threepl__models.yml
models:
  - name: stg_threepl__returns
    description: >
      Returns from the 3PL's daily file. Raw values kept beside cleaned ones.
    config:
      meta:
        owner: Priya
        cleaning_rules: ["R03", "R07"]
    columns:
      - name: shop_sku
        data_tests:
          - not_null
          - relationships:
              arguments:
                to: ref('stg_shop__variants')
                field: sku
              config:
                severity: error
                warn_if: ">0"
                error_if: ">10"

The relationships test checks that every cleaned SKU exists in the shop's variants17. With warn_if and error_if, a few unmatched SKUs raise a warning that someone looks at, and more than ten stop the build, because then the rule itself is probably broken18. That is the rule register doing real work: every rule has an owner, a reason and a test that fails loudly when the rule stops matching reality. The chapter on testing data pipelines, later in this series, builds this out properly, in the same test first spirit as test driven development.

Only reversible, auditable cleaning

Two properties separate safe cleaning from dangerous cleaning.

Reversible means you can always get back to the original. The raw data is kept exactly as it arrived, and cleaning creates new columns or new tables instead of overwriting old ones. If a rule turns out to be wrong, you fix the rule and rebuild. Nothing was lost.

Auditable means anyone can see what was changed, by which rule, in which version, and why. The rule version on each row and the register together give that trail.

Both matter for more than tidiness. In the UK, every company must keep accounting records sufficient to show and explain its transactions19. Your shop's orders, refunds and payments are part of that trail. "Cleaning" them in place, overwriting a price or deleting a test order inside the shop database, would make the records explain less, not more. Corrections in the shop belong in the shop's own mechanisms, such as a cancellation or a refund, which leave their own record.

For personal data, the Information Commission's (formerly the ICO's) guidance makes a similar point from the other side: you may keep a record of a mistake, as long as it is clearly identified as a mistake and the records are not misleading about the facts20. A raw layer that keeps an old wrong value, clearly separated from the corrected one, fits that description. A copy that silently mixes both does not.

This is general information about how these rules bear on data work, not legal advice. For your own records, ask your accountant or a solicitor.

Example: cleaning the float prices without losing them

Callum's model for the legacy order lines keeps three columns where a hasty fix would keep one:

-- models/staging/legacy/stg_legacy__order_lines.sql (PostgreSQL)
select
    line_id,
    legacy_order_id,
    price                                         as price_raw,     -- double precision, as imported
    round(price::numeric, 2)::numeric(10,2)       as unit_price,    -- rule R05, version 1
    abs(price::numeric - round(price::numeric, 2)) > 0.005
                                                  as price_not_whole_pence,
    'R05.v1'                                      as price_rule_version
from {{ source('legacy', 'order_lines') }}

On the profiled data, 61,000 lines go through the rule and none has price_not_whole_pence = true, which confirms the assumption behind the rule: these were whole pence prices stored imprecisely, not genuinely odd values. Had any line been flagged, that line would go to a person, not through the rounding.

The test that guards it compares each legacy order's cleaned lines with the order total stored on the old platform. If they ever disagree by more than a penny, the build warns. The original float is still there, so any disagreement can be investigated at the level of the single line.

Never clean silently for one report

The most common cleaning in small businesses is not in any pipeline. It happens in a spreadsheet, the night before a meeting. Someone exports the orders, deletes the rows that look wrong, and builds a chart. The chart is right. And now the business has two versions of the truth, and only one person knows how they differ.

Every one off cleaning step has to move into the shared pipeline, with a register entry, or it has to be undone. That sounds strict. It is the only way the second report agrees with the first.

Example: two revenue figures for December

In the example, before the register existed, Priya's December board pack was built in a spreadsheet. Callum's export included four test orders from Christmas gift wrap testing, and Priya deleted them by hand. Her board pack showed December revenue £288 lower than the dashboard (four orders times £72). The difference was correct, and nobody could explain it in the meeting, because the deletion was not written down anywhere. Twenty minutes went on arguing about which number was right.

After the register, the test order rule lives in the pipeline, the dashboard and the board pack read the same table, and both show the same figure. When Priya wants revenue including test orders for some reason, she filters by order_origin from one shared definition, and the difference is explainable from the register.

Data contracts: fixing the source when the source is someone else

A data contract is a written agreement between the people who produce a dataset and the people who use it. It says what the data will look like, what it means, how good it will be, how often it arrives, who to contact when it breaks, and how changes are announced. It turns "please could you send the SKU differently" into a commitment with a version number.

The Open Data Contract Standard (ODCS), maintained by the Bitol project under the Linux Foundation AI and Data, defines a YAML format for such contracts21. Its sections give a good checklist of what any contract should cover, whether you use the format or a plain document:

SectionWhat it settlesExample for the 3PL file
FundamentalsName, version, status, owner, purpose"3PL daily returns, version 2.0.0, active"
SchemaColumns, types, meaning, required fieldsshop_sku required, text, the shop's own SKU
Data qualityRules with thresholdsNo null SKU, no unknown SKU
Service levelsFrequency, latency, availabilityDaily file by 6am, returns within one day
SupportWhere to raise problemsA named contact and an email address
Team and rolesWho owns and who may accessThe 3PL's account manager, Callum, Priya

Who signs? The producer and the consumer, each with a named person. For the 3PL, the 3PL's account manager and Priya, with Callum as the technical contact. For an internal dataset, the developer who owns the producing code and the person who owns the reports. A contract without names is a wish.

Inside a dbt project there is a narrower, enforceable kind of contract. A dbt model contract declares each column's name and data type, and with enforced: true the model does not build if the SQL produces something different22. That protects the people who use your models from surprise changes. It does not reach an outside supplier, which is why both kinds exist.

Example: the supplier units contract

The supplier who sends millimetres agrees to a contract version 1.0.0. Callum writes it in ODCS form, because the same file can drive automated checks:

# contracts/supplier_c_product_feed.odcs.yaml
apiVersion: v3.2.0
kind: DataContract
id: 2f1c7a52-supplier-c-feed
name: supplier_c_product_feed
version: 1.0.0
status: active
description:
  purpose: Product data for Wrenfield Home's catalogue and product pages.
  usage: Imported nightly into the shop. Dimensions are shown to customers.
schema:
  - name: products
    physicalType: table
    properties:
      - name: supplier_sku
        logicalType: string
        required: true
        unique: true
      - name: width
        logicalType: number
        required: true
        description: Outer width of the product, in the unit given in dimension_unit.
      - name: dimension_unit
        logicalType: string
        required: true
        quality:
          - metric: invalidValues
            arguments:
              validValues: ['cm']
            mustBe: 0
            description: All dimensions are sent in centimetres.
slaProperties:
  - property: frequency
    value: 1
    unit: d

The keys follow the ODCS documentation: apiVersion, kind and the fundamentals at the top, schema with properties for the columns, a quality rule using the invalidValues metric with a list of valid values, and slaProperties for the delivery frequency21. The quality rule says, in a form a machine can check, exactly what the conversation with the supplier agreed: one unit, centimetres, no exceptions.

Until the supplier ships version 1.0.0, Callum's import keeps converting their millimetres. The day the first file arrives with dimension_unit = 'cm', the conversion rule is retired in the register, and the pipeline gets simpler.

Whose job is cleaning?

Cleaning decisions fail most often not because of SQL but because nobody owns them. The data engineer can see the problem but should not decide alone whether staff purchases count as revenue. The business owner can decide but cannot see the problem. The developer of the source system can fix it but does not feel the pain.

Research backs up how common this is. A study of 53 practitioners building high stakes machine learning systems found data cascades, problems caused by data that compound quietly downstream, with a prevalence of 92%, and linked them to practices that undervalue data quality23. The fix is not heroics. It is clear roles.

RoleAt Wrenfield HomeDecidesDoes
Data ownerPriyaWhat a figure means, which purpose wins, what is acceptableSigns off rules that change business figures
ProducerCallum (shop code), the 3PL, suppliersHow data is createdFixes at the source, honours contracts
Data engineerCallumHow a rule is implemented and testedBuilds the pipeline, keeps the register
ConsumersPriya, the accountant, the ads managerNothing aloneReport problems, use the flags

In a small business, one person often holds several roles. Callum is both producer and data engineer. That is fine, as long as each decision is made in the right role: when Callum decides how to round prices, he is the engineer. When he is tempted to decide whether staff purchases are revenue, he asks Priya. For a fuller picture of who does what, see data engineer, data scientist and data analyst.

Example: who decides about staff purchases

When Callum found the 12 staff purchases, his first instinct was to drop them with the tests. He wrote the finding into the register as "proposed" instead and asked Priya. Priya checked with her accountant: staff purchases are real sales and stay in revenue. Marketing excludes them. The register entry records Priya as owner, the accountant's answer as the reason, and the date. A year later, when a new ads manager asks why conversions do not match revenue, the answer is one line in the register, not an archaeology project.

Every cleaning rule should work towards its own retirement

A healthy pipeline cleans less over time, not more. Every time a source fix lands, a pipeline rule should touch fewer rows, and eventually none. If a rule touches the same number of rows every month for years, either the source cannot change (fine, but write that down) or nobody has asked it to (not fine).

So monitor one number per rule: how many rows it changed or flagged this month. Plot it. A falling line is progress. A sudden jump is an early warning that something changed upstream.

Example: two rules that retired themselves

Callum logs the number of rows each rule touches per month. Two lines from the example, from December 2025 to November 2026:

Line chart of how many rows two pipeline rules changed each month at the invented example shop, December 2025 to November 2026. The guest email normalisation rule touched between 54 and 63 rows a month until the source fix in August 2026, 21 in August, then zero from September. The test order rule touched between 2 and 5 rows a month until tests moved to staging in March 2026, then zero from April. Tap or click to open full screen and move around

The test order rule fell to zero after March, when tests moved to staging. The email rule fell after the normalizes override went live in mid August. Both rules stay in the pipeline, because the history still needs them, but they now only ever touch old rows. In the register, each is marked "source fixed", and if either line ever rises again, the monitoring alerts Callum that something upstream has broken.

A checklist for the next finding

When the next problem turns up, these questions, in this order, take five minutes and save weeks:

  1. Purpose: which reports, models or processes use this data, and does this finding change any of them?
  2. Source: who produces it, and can they change it? If it is your own shop, fix it now. If it is a partner, start the contract conversation now.
  3. History: for rows already stored, is the true value knowable from data you hold? If yes, clean in the pipeline. If no, flag it.
  4. Triage: impact times frequency, plus the effort at the source. Do the high scores and the trivial fixes first.
  5. Register: rule id, version, owner, reason, dates, test. No register entry, no rule.
  6. Reversibility: raw kept, cleaned values beside it, rule version on every row.
  7. One truth: no cleaning in spreadsheets for one report. Ever.
  8. Retirement: monitor rows touched per rule. Aim for zero.

Conclusion

Cleaning data is not a race to make every value look tidy. It is a sequence of decisions, and the order matters. Start with the purpose, because it tells you whether a problem matters at all. Then look upstream, because a fix at the source cleans every future row for everyone and retires work instead of creating it. Clean in the pipeline only what you can know for certain, keep the original beside it, and write the rule down with an owner and a test. Leave and flag what you cannot know, because a visible gap is honest and an invented value is not.

Wrenfield Home's ten findings came down to two fixed at the source, five cleaned in the pipeline and three left and flagged, with seven involving a source fix in some form. Your shop's list will differ. The method will not. The chapters that follow take each technique in turn, starting with missing values, the place where the temptation to invent is strongest.

If you would like a second pair of eyes on your own list of findings, I run a free workshop where we sort them into fix, clean and flag together, and the first two weeks of work are on me.

Bring your list of data problems to a free workshop and we will sort it into fix at the source, clean in the pipeline and leave and flag together. The first two weeks of work are on me.

Sources

  1. 1.

    Richard Y. Wang and Diane M. Strong, Beyond Accuracy: What Data Quality Means to Data Consumers, Journal of Management Information Systems 12(4), 5 to 33, 1996, DOI 10.1080/07421222.1996.11518099, record on Semantic Scholar, https://www.semanticscholar.org/paper/b057cc625984119d48846dbf08f30b565f8c263d

  2. 2.

    UK General Data Protection Regulation, Article 5 (principles relating to processing of personal data), legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/5

  3. 3.

    UK General Data Protection Regulation, Article 16 (right to rectification), legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/16

  4. 4.

    Ruby on Rails Guides, Active Record Validations, https://guides.rubyonrails.org/active_record_validations.html

  5. 5.

    Ruby on Rails API (version 8.0), ActiveRecord::Normalization::ClassMethods, normalizes, https://api.rubyonrails.org/v8.0/classes/ActiveRecord/Normalization/ClassMethods.html

  6. 6.

    PostgreSQL Global Development Group, PostgreSQL documentation, 5.5 Constraints, https://www.postgresql.org/docs/current/ddl-constraints.html

  7. 7.

    Ruby on Rails API, ActiveRecord::ConnectionAdapters::SchemaStatements, add_check_constraint, https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html

  8. 8.

    Solidus, solidus_auth_devise, config/initializers/devise.rb (case_insensitive_keys), GitHub, https://github.com/solidusio/solidus_auth_devise/blob/main/config/initializers/devise.rb

  9. 9.

    heartcombo, Devise, generator template devise.rb (strip_whitespace_keys, default :email), GitHub, https://github.com/heartcombo/devise/blob/main/lib/generators/templates/devise.rb

  10. 10.
  11. 11.

    PostgreSQL Global Development Group, PostgreSQL documentation, 9.9 Date/Time Functions and Operators, AT TIME ZONE, https://www.postgresql.org/docs/current/functions-datetime.html

  12. 12.

    PostgreSQL Global Development Group, PostgreSQL documentation, B.2 Handling of Invalid or Ambiguous Timestamps, https://www.postgresql.org/docs/current/datetime-invalid-input.html

  13. 13.

    phonelib contributors (maintained by daddyz on GitHub), phonelib, README, GitHub, https://github.com/daddyz/phonelib

  14. 14.

    Solidus, core/db/migrate/20160101010000_solidus_one_four.rb (spree_orders columns), GitHub, https://github.com/solidusio/solidus/blob/main/core/db/migrate/20160101010000_solidus_one_four.rb

  15. 15.

    dbt Labs, dbt documentation, Add seeds to your DAG, https://docs.getdbt.com/docs/build/seeds

  16. 16.
  17. 17.

    dbt Labs, dbt documentation, Add data tests to your DAG, https://docs.getdbt.com/docs/build/data-tests

  18. 18.

    dbt Labs, dbt documentation, severity, error_if, and warn_if, https://docs.getdbt.com/reference/resource-configs/severity

  19. 19.

    Companies Act 2006, section 386 (duty to keep accounting records), legislation.gov.uk, https://www.legislation.gov.uk/ukpga/2006/46/section/386

  20. 20.
  21. 21.

    Bitol (Linux Foundation AI and Data), Open Data Contract Standard, version 3.2.0, https://bitol-io.github.io/open-data-contract-standard/latest/

  22. 22.

    dbt Labs, dbt documentation, Model contracts, https://docs.getdbt.com/docs/mesh/govern/model-contracts

  23. 23.

    Nithya Sambasivan, Shivani Kapania, Hannah Highfill, Diana Akrong, Praveen Paritosh and Lora Aroyo, "Everyone wants to do the model work, not the data work": Data Cascades in High Stakes AI, Proceedings of the 2021 CHI Conference on Human Factors in Computing Systems, Google Research, https://research.google/pubs/everyone-wants-to-do-the-model-work-not-the-data-work-data-cascades-in-high-stakes-ai/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.