DEV Community

Rupak Kulkarni
Rupak Kulkarni

Posted on

Your Gold Table Can Be Wrong Even When the Totals Match: Campaign-Level Reconciliation in Python

A successful aggregation job is not proof that the resulting dashboard is correct. Imagine two advertising campaigns with Silver-layer spend of $100 and $200. Gold reports $110 and $190. The overall spend is still $300, so a global checksum of the metric passes. Both campaign reports, however, are wrong.

This is why reconciliation needs to preserve the reporting grain rather than merely compare grand totals.

On November 24, 2026, the public retail media analytics pipeline added a standalone Silver-to-Gold reconciliation helper. This article explains that implementation and how to extend the pattern into a production publication gate. All examples use synthetic data; the helper is a portfolio implementation, not a claim about a deployed advertising system.

1. Define what must survive aggregation

In a medallion architecture, Bronze retains source records, Silver normalizes and validates them, and Gold aggregates them for consumption. Reconciliation sits at the boundary between the last two layers:

Silver snapshot
    |                     |
    | aggregate expected  | build reporting table
    v                     v
Expected campaign sums   Candidate Gold
    |                     |
    +---- reconcile ------+
               |
         publish or hold
Enter fullscreen mode Exit fullscreen mode

The repository uses three fields as its campaign grain: platform, campaign ID and campaign name. Its additive measures are impressions, clicks, spend, conversions and revenue.

A reconciliation contract needs to state not only these columns but also the reporting period, source snapshot and currency. Comparing Monday's Silver data against Tuesday's Gold data is meaningless, even if both have the same schema. Likewise, summing dollars and euros without conversion is not a valid financial check.

The helper assumes these prerequisites have already been established by the caller.

2. Compare the union of keys, not the intersection

An inner join between expected and actual campaign totals can silently remove the very campaigns that are missing. A full outer comparison is the appropriate starting point.

The implementation builds two dictionaries: aggregated Silver totals and unique Gold totals. It then iterates over the union of their keys. A key found only in Silver becomes a missing Gold issue; a key found only in Gold becomes an unexpected Gold issue.

Here is an executable usage example for Python 3.9 or newer, from the repository root at the linked revision:

from src.reconciliation import reconcile

def campaign(cid, spend):
    return {
        "platform": "search",
        "campaign_id": cid,
        "campaign_name": f"Campaign {cid}",
        "impressions": 100,
        "clicks": 10,
        "conversions": 2,
        "spend": spend,
        "revenue": "50.00",
    }

silver = [
    campaign("A", "100.00"),
    campaign("B", "200.00"),
]
gold = [
    campaign("A", "110.00"),
    campaign("B", "190.00"),
]

report = reconcile(silver, gold)
assert not report["passed"]
assert len(report["issues"]) == 2

for issue in report["issues"]:
    print(issue["key"], issue["metric"], issue["delta"])
Enter fullscreen mode Exit fullscreen mode

The expected result is two spend discrepancies, one positive ten dollars and one negative ten dollars. The total error cancels out globally, but the campaign-level check catches both.

Notice that a missing campaign with zero spend still matters. Its absence may change the number of campaigns displayed, or remove a legitimate row needed for downstream joins. Key coverage and numeric equality are separate invariants.

3. Choose numeric semantics deliberately

The reconciliation module converts values with Decimal(str(value)). It rejects negative and non-finite values and uses exact comparisons for impressions, clicks and conversions. Spend and revenue use an absolute tolerance of one cent by default.

That means a difference of exactly one cent passes, while two cents fails. This is an explicit policy, not a universal accounting standard.

Decimal is useful because decimal-string inputs such as "0.10" and "0.20" can be represented exactly. Binary floating-point arithmetic cannot represent many decimal fractions exactly. However, converting a float to Decimal after an upstream calculation cannot restore precision that has already been lost.

A production implementation should specify decimal precision, scale, rounding mode and the stage at which rounding occurs. It should also distinguish legitimate signed adjustments, such as refunds, from invalid negative values. The current helper deliberately rejects negatives and would need adaptation for such a domain.

A further subtlety: exact comparison of counts does not enforce integer-valued counts. If fractional impressions are invalid, validate that separately.

4. Do not sum ratios

Click-through rate and return on ad spend are derived measures. They should generally be recomputed from the reconciled additive components.

Consider two campaigns:

Campaign Impressions Clicks CTR
A 100 10 10%
B 900 45 5%

The unweighted average CTR is 7.5%, but the combined CTR is 55 / 1000 = 5.5%.

The same principle applies to ROAS: divide total revenue by total spend rather than summing campaign-level ROAS. Define a separate policy for zero denominators. The repository's helper intentionally excludes ratios, so a successful reconciliation does not certify that the Gold ratio expressions are correct.

5. Make failures actionable

A boolean alone is insufficient for debugging. The helper returns a JSON-ready report containing pass status, key counts and discrepancies. Metric discrepancies include the expected value, actual value and signed delta as strings.

The nine synthetic unit tests cover aggregation, count mismatch, money tolerance, missing keys, unexpected keys, duplicate Gold keys, invalid values, empty inputs and invalid campaign keys.

Run them locally:

python -m unittest discover -s tests -p test_reconciliation.py
Enter fullscreen mode Exit fullscreen mode

These are source-inspected tests; this article does not claim a fresh test execution or a performance benchmark.

An important distinction is that duplicate Gold keys and invalid inputs raise exceptions rather than returning ordinary discrepancy records. A publication gate must treat both outcomes as failures. It should persist diagnostic information, retain the previous trusted Gold version and alert the owner instead of silently publishing partial data.

6. Move the pattern to Spark without collecting everything

The current helper is in-memory Python, suitable for bounded extracts. It is not automatically invoked by the repository's orchestrator.

For distributed datasets, the equivalent design is to group Silver by the declared grain, sum typed decimal measures, independently check Gold uniqueness, and perform a full outer join. Add explicit presence markers before joining so missing rows cannot be confused with legitimate zero-valued measures.

Evaluate discrepancy predicates in Spark and write the failed keys to an audit table. Collect only bounded summaries, not the entire dataset. Bind the audit record to the exact Silver and candidate Gold versions; otherwise a later write can invalidate the check before publication.

This is a proposed production extension, not functionality implemented by the standalone helper.

7. Know what a passing result does not prove

Both inputs being empty currently passes. Add expected-volume and freshness checks to detect missing deliveries. Matching totals also cannot prove that Silver itself is correct, that campaign attribution is valid, or that all source events arrived.

Per-key monetary tolerance can accumulate across many campaigns. A financial pipeline may therefore need a second global tolerance or a stricter rounding contract. Campaign names can change over time, so consider stable identifiers and effective-dated dimensions when choosing a production grain.

The central lesson is to treat reconciliation as a conservation contract: preserve key coverage and additive measures across transformations, make discrepancies inspectable, and publish only after the appropriate checks pass.

References

Top comments (0)